critsection.c 20.9 KB
Newer Older
1 2 3 4
/*
 * Win32 critical sections
 *
 * Copyright 1998 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21 22 23
#include "config.h"
#include "wine/port.h"

24
#include <assert.h>
25
#include <errno.h>
26
#include <stdarg.h>
27 28
#include <stdio.h>
#include <sys/types.h>
29 30 31
#ifdef HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif
32
#include <time.h>
33 34
#include "ntstatus.h"
#define WIN32_NO_STATUS
35
#include "windef.h"
36
#include "winternl.h"
37
#include "wine/debug.h"
38
#include "ntdll_misc.h"
39

40 41
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
WINE_DECLARE_DEBUG_CHANNEL(relay);
42

43
static inline LONG interlocked_inc( PLONG dest )
44
{
45
    return interlocked_xchg_add( dest, 1 ) + 1;
46 47
}

48
static inline LONG interlocked_dec( PLONG dest )
49
{
50
    return interlocked_xchg_add( dest, -1 ) - 1;
51 52
}

53
static inline void small_pause(void)
54 55 56 57 58 59 60 61
{
#ifdef __i386__
    __asm__ __volatile__( "rep;nop" : : : "memory" );
#else
    __asm__ __volatile__( "" : : : "memory" );
#endif
}

62 63 64 65 66 67 68
static void *no_debug_info_marker = (void *)(ULONG_PTR)-1;

static BOOL crit_section_has_debuginfo(const RTL_CRITICAL_SECTION *crit)
{
    return crit->DebugInfo != NULL && crit->DebugInfo != no_debug_info_marker;
}

69
#ifdef __linux__
70

71 72 73
static int wait_op = 128; /*FUTEX_WAIT|FUTEX_PRIVATE_FLAG*/
static int wake_op = 129; /*FUTEX_WAKE|FUTEX_PRIVATE_FLAG*/

74 75
static inline int futex_wait( int *addr, int val, struct timespec *timeout )
{
76
    return syscall( __NR_futex, addr, wait_op, val, timeout, 0, 0 );
77 78 79 80
}

static inline int futex_wake( int *addr, int val )
{
81
    return syscall( __NR_futex, addr, wake_op, val, NULL, 0, 0 );
82 83 84 85 86 87
}

static inline int use_futexes(void)
{
    static int supported = -1;

88 89 90
    if (supported == -1)
    {
        futex_wait( &supported, 10, NULL );
91 92 93 94 95 96
        if (errno == ENOSYS)
        {
            wait_op = 0; /*FUTEX_WAIT*/
            wake_op = 1; /*FUTEX_WAKE*/
            futex_wait( &supported, 10, NULL );
        }
97 98
        supported = (errno != ENOSYS);
    }
99 100 101
    return supported;
}

102 103 104 105 106 107 108 109 110 111 112 113 114
static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
{
    int val;
    struct timespec timespec;

    if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;

    timespec.tv_sec  = timeout;
    timespec.tv_nsec = 0;
    while ((val = interlocked_cmpxchg( (int *)&crit->LockSemaphore, 0, 1 )) != 1)
    {
        /* note: this may wait longer than specified in case of signals or */
        /*       multiple wake-ups, but that shouldn't be a problem */
115
        if (futex_wait( (int *)&crit->LockSemaphore, val, &timespec ) == -1 && errno == ETIMEDOUT)
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            return STATUS_TIMEOUT;
    }
    return STATUS_WAIT_0;
}

static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
{
    if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;

    *(int *)&crit->LockSemaphore = 1;
    futex_wake( (int *)&crit->LockSemaphore, 1 );
    return STATUS_SUCCESS;
}

static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
{
    if (!use_futexes()) NtClose( crit->LockSemaphore );
}

#elif defined(__APPLE__)

#include <mach/mach.h>
#include <mach/task.h>
#include <mach/semaphore.h>

static inline semaphore_t get_mach_semaphore( RTL_CRITICAL_SECTION *crit )
{
    semaphore_t ret = *(int *)&crit->LockSemaphore;
    if (!ret)
    {
        semaphore_t sem;
        if (semaphore_create( mach_task_self(), &sem, SYNC_POLICY_FIFO, 0 )) return 0;
        if (!(ret = interlocked_cmpxchg( (int *)&crit->LockSemaphore, sem, 0 )))
            ret = sem;
        else
            semaphore_destroy( mach_task_self(), sem );  /* somebody beat us to it */
    }
    return ret;
}

static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
{
    mach_timespec_t timespec;
    semaphore_t sem = get_mach_semaphore( crit );

    timespec.tv_sec = timeout;
    timespec.tv_nsec = 0;
    for (;;)
    {
        switch( semaphore_timedwait( sem, timespec ))
        {
        case KERN_SUCCESS:
            return STATUS_WAIT_0;
        case KERN_ABORTED:
            continue;  /* got a signal, restart */
        case KERN_OPERATION_TIMED_OUT:
            return STATUS_TIMEOUT;
        default:
            return STATUS_INVALID_HANDLE;
        }
    }
}

static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
{
    semaphore_t sem = get_mach_semaphore( crit );
    semaphore_signal( sem );
    return STATUS_SUCCESS;
}

static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
{
    semaphore_destroy( mach_task_self(), *(int *)&crit->LockSemaphore );
}

#else  /* __APPLE__ */

static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
{
    return STATUS_NOT_IMPLEMENTED;
}
197

198 199 200 201 202 203 204 205 206
static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
{
    return STATUS_NOT_IMPLEMENTED;
}

static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
{
    NtClose( crit->LockSemaphore );
}
207 208 209

#endif

210 211 212 213 214 215 216 217 218 219
/***********************************************************************
 *           get_semaphore
 */
static inline HANDLE get_semaphore( RTL_CRITICAL_SECTION *crit )
{
    HANDLE ret = crit->LockSemaphore;
    if (!ret)
    {
        HANDLE sem;
        if (NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 )) return 0;
220
        if (!(ret = interlocked_cmpxchg_ptr( &crit->LockSemaphore, sem, 0 )))
221 222 223 224 225 226 227
            ret = sem;
        else
            NtClose(sem);  /* somebody beat us to it */
    }
    return ret;
}

228 229 230 231 232
/***********************************************************************
 *           wait_semaphore
 */
static inline NTSTATUS wait_semaphore( RTL_CRITICAL_SECTION *crit, int timeout )
{
233
    NTSTATUS ret;
234

235
    /* debug info is cleared by MakeCriticalSectionGlobal */
236
    if (!crit_section_has_debuginfo( crit ) || ((ret = fast_wait( crit, timeout )) == STATUS_NOT_IMPLEMENTED))
237 238 239
    {
        HANDLE sem = get_semaphore( crit );
        LARGE_INTEGER time;
240
        select_op_t select_op;
241 242

        time.QuadPart = timeout * (LONGLONG)-10000000;
243 244
        select_op.wait.op = SELECT_WAIT;
        select_op.wait.handles[0] = wine_server_obj_handle( sem );
245
        ret = server_select( &select_op, offsetof( select_op_t, wait.handles[1] ), 0, &time );
246
    }
247
    return ret;
248 249
}

250 251
/***********************************************************************
 *           RtlInitializeCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
252
 *
253
 * Initialises a new critical section.
Jon Griffiths's avatar
Jon Griffiths committed
254 255 256 257
 *
 * PARAMS
 *  crit [O] Critical section to initialise
 *
258
 * RETURNS
Jon Griffiths's avatar
Jon Griffiths committed
259
 *  STATUS_SUCCESS.
260 261
 *
 * SEE
262
 *  RtlInitializeCriticalSectionEx(),
263 264 265
 *  RtlInitializeCriticalSectionAndSpinCount(), RtlDeleteCriticalSection(),
 *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
 *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
266 267
 */
NTSTATUS WINAPI RtlInitializeCriticalSection( RTL_CRITICAL_SECTION *crit )
268
{
269
    return RtlInitializeCriticalSectionEx( crit, 0, 0 );
270 271 272 273 274
}

/***********************************************************************
 *           RtlInitializeCriticalSectionAndSpinCount   (NTDLL.@)
 *
275
 * Initialises a new critical section with a given spin count.
276 277 278 279 280 281 282 283 284
 *
 * PARAMS
 *   crit      [O] Critical section to initialise
 *   spincount [I] Spin count for crit
 * 
 * RETURNS
 *  STATUS_SUCCESS.
 *
 * NOTES
285 286 287
 *  Available on NT4 SP3 or later.
 *
 * SEE
288
 *  RtlInitializeCriticalSectionEx(),
289 290 291
 *  RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
 *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
 *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
292 293
 */
NTSTATUS WINAPI RtlInitializeCriticalSectionAndSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
294
{
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    return RtlInitializeCriticalSectionEx( crit, spincount, 0 );
}

/***********************************************************************
 *           RtlInitializeCriticalSectionEx   (NTDLL.@)
 *
 * Initialises a new critical section with a given spin count and flags.
 *
 * PARAMS
 *   crit      [O] Critical section to initialise.
 *   spincount [I] Number of times to spin upon contention.
 *   flags     [I] RTL_CRITICAL_SECTION_FLAG_ flags from winnt.h.
 *
 * RETURNS
 *  STATUS_SUCCESS.
 *
 * NOTES
 *  Available on Vista or later.
 *
 * SEE
 *  RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
 *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
 *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
 */
NTSTATUS WINAPI RtlInitializeCriticalSectionEx( RTL_CRITICAL_SECTION *crit, ULONG spincount, ULONG flags )
{
    if (flags & (RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN|RTL_CRITICAL_SECTION_FLAG_STATIC_INIT))
        FIXME("(%p,%u,0x%08x) semi-stub\n", crit, spincount, flags);

    /* FIXME: if RTL_CRITICAL_SECTION_FLAG_STATIC_INIT is given, we should use
     * memory from a static pool to hold the debug info. Then heap.c could pass
     * this flag rather than initialising the process heap CS by hand. If this
     * is done, then debug info should be managed through Rtlp[Allocate|Free]DebugInfo
     * so (e.g.) MakeCriticalSectionGlobal() doesn't free it using HeapFree().
     */
    if (flags & RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO)
331
        crit->DebugInfo = no_debug_info_marker;
332
    else
333
    {
334 335 336 337 338 339 340 341 342 343 344 345
        crit->DebugInfo = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(RTL_CRITICAL_SECTION_DEBUG));
        if (crit->DebugInfo)
        {
            crit->DebugInfo->Type = 0;
            crit->DebugInfo->CreatorBackTraceIndex = 0;
            crit->DebugInfo->CriticalSection = crit;
            crit->DebugInfo->ProcessLocksList.Blink = &(crit->DebugInfo->ProcessLocksList);
            crit->DebugInfo->ProcessLocksList.Flink = &(crit->DebugInfo->ProcessLocksList);
            crit->DebugInfo->EntryCount = 0;
            crit->DebugInfo->ContentionCount = 0;
            memset( crit->DebugInfo->Spare, 0, sizeof(crit->DebugInfo->Spare) );
        }
346
    }
347 348 349 350
    crit->LockCount      = -1;
    crit->RecursionCount = 0;
    crit->OwningThread   = 0;
    crit->LockSemaphore  = 0;
351 352
    if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
    crit->SpinCount = spincount & ~0x80000000;
353 354 355
    return STATUS_SUCCESS;
}

356
/***********************************************************************
357
 *           RtlSetCriticalSectionSpinCount   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
358
 *
359
 * Sets the spin count of a critical section.
Jon Griffiths's avatar
Jon Griffiths committed
360 361
 *
 * PARAMS
362
 *   crit      [I/O] Critical section
Jon Griffiths's avatar
Jon Griffiths committed
363
 *   spincount [I] Spin count for crit
364
 *
Jon Griffiths's avatar
Jon Griffiths committed
365
 * RETURNS
366
 *  The previous spin count.
Jon Griffiths's avatar
Jon Griffiths committed
367 368
 *
 * NOTES
369
 *  If the system is not SMP, spincount is ignored and set to 0.
370 371
 *
 * SEE
372
 *  RtlInitializeCriticalSectionEx(),
373 374 375
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
376
 */
377
ULONG WINAPI RtlSetCriticalSectionSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
378
{
379 380
    ULONG oldspincount = crit->SpinCount;
    if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
381
    crit->SpinCount = spincount;
382
    return oldspincount;
383 384
}

385 386
/***********************************************************************
 *           RtlDeleteCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
387
 *
388
 * Frees the resources used by a critical section.
Jon Griffiths's avatar
Jon Griffiths committed
389 390 391 392 393 394
 *
 * PARAMS
 *  crit [I/O] Critical section to free
 *
 * RETURNS
 *  STATUS_SUCCESS.
395 396
 *
 * SEE
397
 *  RtlInitializeCriticalSectionEx(),
398 399 400
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
401 402 403 404 405 406
 */
NTSTATUS WINAPI RtlDeleteCriticalSection( RTL_CRITICAL_SECTION *crit )
{
    crit->LockCount      = -1;
    crit->RecursionCount = 0;
    crit->OwningThread   = 0;
407
    if (crit_section_has_debuginfo( crit ))
408 409
    {
        /* only free the ones we made in here */
410
        if (!crit->DebugInfo->Spare[0])
411
        {
412
            RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
413 414
            crit->DebugInfo = NULL;
        }
415
        close_semaphore( crit );
416
    }
417 418
    else NtClose( crit->LockSemaphore );
    crit->LockSemaphore = 0;
419 420 421 422 423 424
    return STATUS_SUCCESS;
}


/***********************************************************************
 *           RtlpWaitForCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
425
 *
426
 * Waits for a busy critical section to become free.
Jon Griffiths's avatar
Jon Griffiths committed
427 428 429 430 431 432
 * 
 * PARAMS
 *  crit [I/O] Critical section to wait for
 *
 * RETURNS
 *  STATUS_SUCCESS.
433 434 435 436 437 438
 *
 * NOTES
 *  Use RtlEnterCriticalSection() instead of this function as it is often much
 *  faster.
 *
 * SEE
439
 *  RtlInitializeCriticalSectionEx(),
440 441 442
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
443 444 445
 */
NTSTATUS WINAPI RtlpWaitForCriticalSection( RTL_CRITICAL_SECTION *crit )
{
446
    LONGLONG timeout = NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart / -10000000;
447 448 449 450 451 452 453 454 455

    /* Don't allow blocking on a critical section during process termination */
    if (RtlDllShutdownInProgress())
    {
        WARN( "process %s is shutting down, returning STATUS_SUCCESS\n",
              debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer) );
        return STATUS_SUCCESS;
    }

456 457 458
    for (;;)
    {
        EXCEPTION_RECORD rec;
459
        NTSTATUS status = wait_semaphore( crit, 5 );
460
        timeout -= 5;
461

462
        if ( status == STATUS_TIMEOUT )
463
        {
464
            const char *name = NULL;
465
            if (crit_section_has_debuginfo( crit )) name = (char *)crit->DebugInfo->Spare[0];
466
            if (!name) name = "?";
467
            ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (60 sec)\n",
468
                 crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
469
            status = wait_semaphore( crit, 60 );
470 471
            timeout -= 60;

472
            if ( status == STATUS_TIMEOUT && TRACE_ON(relay) )
473
            {
474
                ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (5 min)\n",
475
                     crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
476
                status = wait_semaphore( crit, 300 );
477
                timeout -= 300;
478 479
            }
        }
480
        if (status == STATUS_WAIT_0) break;
481

482
        /* Throw exception only for Wine internal locks */
483
        if (!crit_section_has_debuginfo( crit ) || !crit->DebugInfo->Spare[0]) continue;
484

485 486 487
        /* only throw deadlock exception if configured timeout is reached */
        if (timeout > 0) continue;

488
        rec.ExceptionCode    = STATUS_POSSIBLE_DEADLOCK;
489 490 491 492
        rec.ExceptionFlags   = 0;
        rec.ExceptionRecord  = NULL;
        rec.ExceptionAddress = RtlRaiseException;  /* sic */
        rec.NumberParameters = 1;
493
        rec.ExceptionInformation[0] = (ULONG_PTR)crit;
494 495
        RtlRaiseException( &rec );
    }
496
    if (crit_section_has_debuginfo( crit )) crit->DebugInfo->ContentionCount++;
497
    return STATUS_SUCCESS;
498 499 500 501 502
}


/***********************************************************************
 *           RtlpUnWaitCriticalSection   (NTDLL.@)
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
 *
 * Notifies other threads waiting on the busy critical section that it has
 * become free.
 * 
 * PARAMS
 *  crit [I/O] Critical section
 *
 * RETURNS
 *  Success: STATUS_SUCCESS.
 *  Failure: Any error returned by NtReleaseSemaphore()
 *
 * NOTES
 *  Use RtlLeaveCriticalSection() instead of this function as it is often much
 *  faster.
 *
 * SEE
519
 *  RtlInitializeCriticalSectionEx(),
520 521 522
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
523 524 525
 */
NTSTATUS WINAPI RtlpUnWaitCriticalSection( RTL_CRITICAL_SECTION *crit )
{
526 527 528
    NTSTATUS ret;

    /* debug info is cleared by MakeCriticalSectionGlobal */
529
    if (!crit_section_has_debuginfo( crit ) || ((ret = fast_wake( crit )) == STATUS_NOT_IMPLEMENTED))
530 531
    {
        HANDLE sem = get_semaphore( crit );
532
        ret = NtReleaseSemaphore( sem, 1, NULL );
533
    }
534 535
    if (ret) RtlRaiseStatus( ret );
    return ret;
536 537 538 539 540
}


/***********************************************************************
 *           RtlEnterCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
541
 *
542
 * Enters a critical section, waiting for it to become available if necessary.
Jon Griffiths's avatar
Jon Griffiths committed
543 544 545 546 547 548 549
 *
 * PARAMS
 *  crit [I/O] Critical section to enter
 *
 * RETURNS
 *  STATUS_SUCCESS. The critical section is held by the caller.
 *  
550
 * SEE
551
 *  RtlInitializeCriticalSectionEx(),
552 553 554
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlSetCriticalSectionSpinCount(),
 *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
555 556 557
 */
NTSTATUS WINAPI RtlEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
{
558 559 560 561 562 563 564 565 566 567
    if (crit->SpinCount)
    {
        ULONG count;

        if (RtlTryEnterCriticalSection( crit )) return STATUS_SUCCESS;
        for (count = crit->SpinCount; count > 0; count--)
        {
            if (crit->LockCount > 0) break;  /* more than one waiter, don't bother spinning */
            if (crit->LockCount == -1)       /* try again */
            {
568
                if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1) goto done;
569 570 571 572 573
            }
            small_pause();
        }
    }

574 575
    if (interlocked_inc( &crit->LockCount ))
    {
576
        if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
577 578 579 580 581 582 583 584
        {
            crit->RecursionCount++;
            return STATUS_SUCCESS;
        }

        /* Now wait for it */
        RtlpWaitForCriticalSection( crit );
    }
585
done:
586
    crit->OwningThread   = ULongToHandle(GetCurrentThreadId());
587 588 589 590 591 592 593
    crit->RecursionCount = 1;
    return STATUS_SUCCESS;
}


/***********************************************************************
 *           RtlTryEnterCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
594
 *
595
 * Tries to enter a critical section without waiting.
Jon Griffiths's avatar
Jon Griffiths committed
596 597 598 599 600 601 602
 *
 * PARAMS
 *  crit [I/O] Critical section to enter
 *
 * RETURNS
 *  Success: TRUE. The critical section is held by the caller.
 *  Failure: FALSE. The critical section is currently held by another thread.
603 604
 *
 * SEE
605
 *  RtlInitializeCriticalSectionEx(),
606 607 608
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlLeaveCriticalSection(), RtlSetCriticalSectionSpinCount()
609 610 611 612
 */
BOOL WINAPI RtlTryEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
{
    BOOL ret = FALSE;
613
    if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1)
614
    {
615
        crit->OwningThread   = ULongToHandle(GetCurrentThreadId());
616 617 618
        crit->RecursionCount = 1;
        ret = TRUE;
    }
619
    else if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
620 621 622 623 624 625 626 627 628
    {
        interlocked_inc( &crit->LockCount );
        crit->RecursionCount++;
        ret = TRUE;
    }
    return ret;
}


629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
/***********************************************************************
 *           RtlIsCriticalSectionLocked   (NTDLL.@)
 *
 * Checks if the critical section is locked by any thread.
 *
 * PARAMS
 *  crit [I/O] Critical section to check.
 *
 * RETURNS
 *  Success: TRUE. The critical section is locked.
 *  Failure: FALSE. The critical section is not locked.
 */
BOOL WINAPI RtlIsCriticalSectionLocked( RTL_CRITICAL_SECTION *crit )
{
    return crit->RecursionCount != 0;
}


/***********************************************************************
 *           RtlIsCriticalSectionLockedByThread   (NTDLL.@)
 *
 * Checks if the critical section is locked by the current thread.
 *
 * PARAMS
 *  crit [I/O] Critical section to check.
 *
 * RETURNS
 *  Success: TRUE. The critical section is locked.
 *  Failure: FALSE. The critical section is not locked.
 */
BOOL WINAPI RtlIsCriticalSectionLockedByThread( RTL_CRITICAL_SECTION *crit )
{
    return crit->OwningThread == ULongToHandle(GetCurrentThreadId()) &&
           crit->RecursionCount;
}


666 667
/***********************************************************************
 *           RtlLeaveCriticalSection   (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
668
 *
669
 * Leaves a critical section.
Jon Griffiths's avatar
Jon Griffiths committed
670 671
 *
 * PARAMS
672
 *  crit [I/O] Critical section to leave.
Jon Griffiths's avatar
Jon Griffiths committed
673 674 675
 *
 * RETURNS
 *  STATUS_SUCCESS.
676 677
 *
 * SEE
678
 *  RtlInitializeCriticalSectionEx(),
679 680 681
 *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
 *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
 *  RtlSetCriticalSectionSpinCount(), RtlTryEnterCriticalSection()
682 683 684
 */
NTSTATUS WINAPI RtlLeaveCriticalSection( RTL_CRITICAL_SECTION *crit )
{
685 686 687 688 689
    if (--crit->RecursionCount)
    {
        if (crit->RecursionCount > 0) interlocked_dec( &crit->LockCount );
        else ERR( "section %p is not acquired\n", crit );
    }
690 691 692 693 694 695 696 697 698 699 700
    else
    {
        crit->OwningThread = 0;
        if (interlocked_dec( &crit->LockCount ) >= 0)
        {
            /* someone is waiting */
            RtlpUnWaitCriticalSection( crit );
        }
    }
    return STATUS_SUCCESS;
}