2 * Win32 critical sections
4 * Copyright 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * 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
22 #include "wine/port.h"
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_SYSCALL_H
30 #include <sys/syscall.h>
34 #define WIN32_NO_STATUS
37 #include "wine/debug.h"
38 #include "ntdll_misc.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
41 WINE_DECLARE_DEBUG_CHANNEL(relay);
43 static inline LONG interlocked_inc( PLONG dest )
45 return interlocked_xchg_add( dest, 1 ) + 1;
48 static inline LONG interlocked_dec( PLONG dest )
50 return interlocked_xchg_add( dest, -1 ) - 1;
53 static inline void small_pause(void)
56 __asm__ __volatile__( "rep;nop" : : : "memory" );
58 __asm__ __volatile__( "" : : : "memory" );
64 static int wait_op = 128; /*FUTEX_WAIT|FUTEX_PRIVATE_FLAG*/
65 static int wake_op = 129; /*FUTEX_WAKE|FUTEX_PRIVATE_FLAG*/
67 static inline int futex_wait( int *addr, int val, struct timespec *timeout )
69 return syscall( SYS_futex, addr, wait_op, val, timeout, 0, 0 );
72 static inline int futex_wake( int *addr, int val )
74 return syscall( SYS_futex, addr, wake_op, val, NULL, 0, 0 );
77 static inline int use_futexes(void)
79 static int supported = -1;
83 futex_wait( &supported, 10, NULL );
86 wait_op = 0; /*FUTEX_WAIT*/
87 wake_op = 1; /*FUTEX_WAKE*/
88 futex_wait( &supported, 10, NULL );
90 supported = (errno != ENOSYS);
95 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
98 struct timespec timespec;
100 if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;
102 timespec.tv_sec = timeout;
103 timespec.tv_nsec = 0;
104 while ((val = interlocked_cmpxchg( (int *)&crit->LockSemaphore, 0, 1 )) != 1)
106 /* note: this may wait longer than specified in case of signals or */
107 /* multiple wake-ups, but that shouldn't be a problem */
108 if (futex_wait( (int *)&crit->LockSemaphore, val, ×pec ) == -1 && errno == ETIMEDOUT)
109 return STATUS_TIMEOUT;
111 return STATUS_WAIT_0;
114 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
116 if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;
118 *(int *)&crit->LockSemaphore = 1;
119 futex_wake( (int *)&crit->LockSemaphore, 1 );
120 return STATUS_SUCCESS;
123 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
125 if (!use_futexes()) NtClose( crit->LockSemaphore );
128 #elif defined(__APPLE__)
130 #include <mach/mach.h>
131 #include <mach/task.h>
132 #include <mach/semaphore.h>
134 static inline semaphore_t get_mach_semaphore( RTL_CRITICAL_SECTION *crit )
136 semaphore_t ret = *(int *)&crit->LockSemaphore;
140 if (semaphore_create( mach_task_self(), &sem, SYNC_POLICY_FIFO, 0 )) return 0;
141 if (!(ret = interlocked_cmpxchg( (int *)&crit->LockSemaphore, sem, 0 )))
144 semaphore_destroy( mach_task_self(), sem ); /* somebody beat us to it */
149 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
151 mach_timespec_t timespec;
152 semaphore_t sem = get_mach_semaphore( crit );
154 timespec.tv_sec = timeout;
155 timespec.tv_nsec = 0;
158 switch( semaphore_timedwait( sem, timespec ))
161 return STATUS_WAIT_0;
163 continue; /* got a signal, restart */
164 case KERN_OPERATION_TIMED_OUT:
165 return STATUS_TIMEOUT;
167 return STATUS_INVALID_HANDLE;
172 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
174 semaphore_t sem = get_mach_semaphore( crit );
175 semaphore_signal( sem );
176 return STATUS_SUCCESS;
179 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
181 semaphore_destroy( mach_task_self(), *(int *)&crit->LockSemaphore );
184 #else /* __APPLE__ */
186 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
188 return STATUS_NOT_IMPLEMENTED;
191 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
193 return STATUS_NOT_IMPLEMENTED;
196 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
198 NtClose( crit->LockSemaphore );
203 /***********************************************************************
206 static inline HANDLE get_semaphore( RTL_CRITICAL_SECTION *crit )
208 HANDLE ret = crit->LockSemaphore;
212 if (NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 )) return 0;
213 if (!(ret = interlocked_cmpxchg_ptr( &crit->LockSemaphore, sem, 0 )))
216 NtClose(sem); /* somebody beat us to it */
221 /***********************************************************************
224 static inline NTSTATUS wait_semaphore( RTL_CRITICAL_SECTION *crit, int timeout )
228 /* debug info is cleared by MakeCriticalSectionGlobal */
229 if (!crit->DebugInfo || ((ret = fast_wait( crit, timeout )) == STATUS_NOT_IMPLEMENTED))
231 HANDLE sem = get_semaphore( crit );
234 time.QuadPart = timeout * (LONGLONG)-10000000;
235 ret = NTDLL_wait_for_multiple_objects( 1, &sem, 0, &time, 0 );
240 /***********************************************************************
241 * RtlInitializeCriticalSection (NTDLL.@)
243 * Initialises a new critical section.
246 * crit [O] Critical section to initialise
252 * RtlInitializeCriticalSectionEx(),
253 * RtlInitializeCriticalSectionAndSpinCount(), RtlDeleteCriticalSection(),
254 * RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
255 * RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
257 NTSTATUS WINAPI RtlInitializeCriticalSection( RTL_CRITICAL_SECTION *crit )
259 return RtlInitializeCriticalSectionEx( crit, 0, 0 );
262 /***********************************************************************
263 * RtlInitializeCriticalSectionAndSpinCount (NTDLL.@)
265 * Initialises a new critical section with a given spin count.
268 * crit [O] Critical section to initialise
269 * spincount [I] Spin count for crit
275 * Available on NT4 SP3 or later.
278 * RtlInitializeCriticalSectionEx(),
279 * RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
280 * RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
281 * RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
283 NTSTATUS WINAPI RtlInitializeCriticalSectionAndSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
285 return RtlInitializeCriticalSectionEx( crit, spincount, 0 );
288 /***********************************************************************
289 * RtlInitializeCriticalSectionEx (NTDLL.@)
291 * Initialises a new critical section with a given spin count and flags.
294 * crit [O] Critical section to initialise.
295 * spincount [I] Number of times to spin upon contention.
296 * flags [I] RTL_CRITICAL_SECTION_FLAG_ flags from winnt.h.
302 * Available on Vista or later.
305 * RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
306 * RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
307 * RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
309 NTSTATUS WINAPI RtlInitializeCriticalSectionEx( RTL_CRITICAL_SECTION *crit, ULONG spincount, ULONG flags )
311 if (flags & (RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN|RTL_CRITICAL_SECTION_FLAG_STATIC_INIT))
312 FIXME("(%p,%u,0x%08x) semi-stub\n", crit, spincount, flags);
314 /* FIXME: if RTL_CRITICAL_SECTION_FLAG_STATIC_INIT is given, we should use
315 * memory from a static pool to hold the debug info. Then heap.c could pass
316 * this flag rather than initialising the process heap CS by hand. If this
317 * is done, then debug info should be managed through Rtlp[Allocate|Free]DebugInfo
318 * so (e.g.) MakeCriticalSectionGlobal() doesn't free it using HeapFree().
320 if (flags & RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO)
321 crit->DebugInfo = NULL;
323 crit->DebugInfo = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(RTL_CRITICAL_SECTION_DEBUG));
327 crit->DebugInfo->Type = 0;
328 crit->DebugInfo->CreatorBackTraceIndex = 0;
329 crit->DebugInfo->CriticalSection = crit;
330 crit->DebugInfo->ProcessLocksList.Blink = &(crit->DebugInfo->ProcessLocksList);
331 crit->DebugInfo->ProcessLocksList.Flink = &(crit->DebugInfo->ProcessLocksList);
332 crit->DebugInfo->EntryCount = 0;
333 crit->DebugInfo->ContentionCount = 0;
334 memset( crit->DebugInfo->Spare, 0, sizeof(crit->DebugInfo->Spare) );
336 crit->LockCount = -1;
337 crit->RecursionCount = 0;
338 crit->OwningThread = 0;
339 crit->LockSemaphore = 0;
340 if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
341 crit->SpinCount = spincount & ~0x80000000;
342 return STATUS_SUCCESS;
345 /***********************************************************************
346 * RtlSetCriticalSectionSpinCount (NTDLL.@)
348 * Sets the spin count of a critical section.
351 * crit [I/O] Critical section
352 * spincount [I] Spin count for crit
355 * The previous spin count.
358 * If the system is not SMP, spincount is ignored and set to 0.
361 * RtlInitializeCriticalSectionEx(),
362 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
363 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
364 * RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
366 ULONG WINAPI RtlSetCriticalSectionSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
368 ULONG oldspincount = crit->SpinCount;
369 if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
370 crit->SpinCount = spincount;
374 /***********************************************************************
375 * RtlDeleteCriticalSection (NTDLL.@)
377 * Frees the resources used by a critical section.
380 * crit [I/O] Critical section to free
386 * RtlInitializeCriticalSectionEx(),
387 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
388 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
389 * RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
391 NTSTATUS WINAPI RtlDeleteCriticalSection( RTL_CRITICAL_SECTION *crit )
393 crit->LockCount = -1;
394 crit->RecursionCount = 0;
395 crit->OwningThread = 0;
398 /* only free the ones we made in here */
399 if (!crit->DebugInfo->Spare[0])
401 RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
402 crit->DebugInfo = NULL;
404 close_semaphore( crit );
406 else NtClose( crit->LockSemaphore );
407 crit->LockSemaphore = 0;
408 return STATUS_SUCCESS;
412 /***********************************************************************
413 * RtlpWaitForCriticalSection (NTDLL.@)
415 * Waits for a busy critical section to become free.
418 * crit [I/O] Critical section to wait for
424 * Use RtlEnterCriticalSection() instead of this function as it is often much
428 * RtlInitializeCriticalSectionEx(),
429 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
430 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
431 * RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
433 NTSTATUS WINAPI RtlpWaitForCriticalSection( RTL_CRITICAL_SECTION *crit )
437 EXCEPTION_RECORD rec;
438 NTSTATUS status = wait_semaphore( crit, 5 );
440 if ( status == STATUS_TIMEOUT )
442 const char *name = NULL;
443 if (crit->DebugInfo) name = (char *)crit->DebugInfo->Spare[0];
444 if (!name) name = "?";
445 ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (60 sec)\n",
446 crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
447 status = wait_semaphore( crit, 60 );
448 if ( status == STATUS_TIMEOUT && TRACE_ON(relay) )
450 ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (5 min)\n",
451 crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
452 status = wait_semaphore( crit, 300 );
455 if (status == STATUS_WAIT_0) break;
457 /* Throw exception only for Wine internal locks */
458 if ((!crit->DebugInfo) || (!crit->DebugInfo->Spare[0])) continue;
460 rec.ExceptionCode = STATUS_POSSIBLE_DEADLOCK;
461 rec.ExceptionFlags = 0;
462 rec.ExceptionRecord = NULL;
463 rec.ExceptionAddress = RtlRaiseException; /* sic */
464 rec.NumberParameters = 1;
465 rec.ExceptionInformation[0] = (ULONG_PTR)crit;
466 RtlRaiseException( &rec );
468 if (crit->DebugInfo) crit->DebugInfo->ContentionCount++;
469 return STATUS_SUCCESS;
473 /***********************************************************************
474 * RtlpUnWaitCriticalSection (NTDLL.@)
476 * Notifies other threads waiting on the busy critical section that it has
480 * crit [I/O] Critical section
483 * Success: STATUS_SUCCESS.
484 * Failure: Any error returned by NtReleaseSemaphore()
487 * Use RtlLeaveCriticalSection() instead of this function as it is often much
491 * RtlInitializeCriticalSectionEx(),
492 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
493 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
494 * RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
496 NTSTATUS WINAPI RtlpUnWaitCriticalSection( RTL_CRITICAL_SECTION *crit )
500 /* debug info is cleared by MakeCriticalSectionGlobal */
501 if (!crit->DebugInfo || ((ret = fast_wake( crit )) == STATUS_NOT_IMPLEMENTED))
503 HANDLE sem = get_semaphore( crit );
504 ret = NtReleaseSemaphore( sem, 1, NULL );
506 if (ret) RtlRaiseStatus( ret );
511 /***********************************************************************
512 * RtlEnterCriticalSection (NTDLL.@)
514 * Enters a critical section, waiting for it to become available if necessary.
517 * crit [I/O] Critical section to enter
520 * STATUS_SUCCESS. The critical section is held by the caller.
523 * RtlInitializeCriticalSectionEx(),
524 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
525 * RtlDeleteCriticalSection(), RtlSetCriticalSectionSpinCount(),
526 * RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
528 NTSTATUS WINAPI RtlEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
534 if (RtlTryEnterCriticalSection( crit )) return STATUS_SUCCESS;
535 for (count = crit->SpinCount; count > 0; count--)
537 if (crit->LockCount > 0) break; /* more than one waiter, don't bother spinning */
538 if (crit->LockCount == -1) /* try again */
540 if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1) goto done;
546 if (interlocked_inc( &crit->LockCount ))
548 if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
550 crit->RecursionCount++;
551 return STATUS_SUCCESS;
554 /* Now wait for it */
555 RtlpWaitForCriticalSection( crit );
558 crit->OwningThread = ULongToHandle(GetCurrentThreadId());
559 crit->RecursionCount = 1;
560 return STATUS_SUCCESS;
564 /***********************************************************************
565 * RtlTryEnterCriticalSection (NTDLL.@)
567 * Tries to enter a critical section without waiting.
570 * crit [I/O] Critical section to enter
573 * Success: TRUE. The critical section is held by the caller.
574 * Failure: FALSE. The critical section is currently held by another thread.
577 * RtlInitializeCriticalSectionEx(),
578 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
579 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
580 * RtlLeaveCriticalSection(), RtlSetCriticalSectionSpinCount()
582 BOOL WINAPI RtlTryEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
585 if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1)
587 crit->OwningThread = ULongToHandle(GetCurrentThreadId());
588 crit->RecursionCount = 1;
591 else if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
593 interlocked_inc( &crit->LockCount );
594 crit->RecursionCount++;
601 /***********************************************************************
602 * RtlLeaveCriticalSection (NTDLL.@)
604 * Leaves a critical section.
607 * crit [I/O] Critical section to leave.
613 * RtlInitializeCriticalSectionEx(),
614 * RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
615 * RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
616 * RtlSetCriticalSectionSpinCount(), RtlTryEnterCriticalSection()
618 NTSTATUS WINAPI RtlLeaveCriticalSection( RTL_CRITICAL_SECTION *crit )
620 if (--crit->RecursionCount) interlocked_dec( &crit->LockCount );
623 crit->OwningThread = 0;
624 if (interlocked_dec( &crit->LockCount ) >= 0)
626 /* someone is waiting */
627 RtlpUnWaitCriticalSection( crit );
630 return STATUS_SUCCESS;