wined3d: Merge the various resource desc structures.
[wine] / dlls / ntdll / critsection.c
1 /*
2  * Win32 critical sections
3  *
4  * Copyright 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_SYSCALL_H
30 #include <sys/syscall.h>
31 #endif
32 #include <time.h>
33 #include "ntstatus.h"
34 #define WIN32_NO_STATUS
35 #include "windef.h"
36 #include "winternl.h"
37 #include "wine/debug.h"
38 #include "ntdll_misc.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
41 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 #ifdef __i386__
56     __asm__ __volatile__( "rep;nop" : : : "memory" );
57 #else
58     __asm__ __volatile__( "" : : : "memory" );
59 #endif
60 }
61
62 #ifdef __linux__
63
64 static inline int futex_wait( int *addr, int val, struct timespec *timeout )
65 {
66     return syscall( SYS_futex, addr, 0/*FUTEX_WAIT*/, val, timeout, 0, 0 );
67 }
68
69 static inline int futex_wake( int *addr, int val )
70 {
71     return syscall( SYS_futex, addr, 1/*FUTEX_WAKE*/, val, NULL, 0, 0 );
72 }
73
74 static inline int use_futexes(void)
75 {
76     static int supported = -1;
77
78     if (supported == -1)
79     {
80         futex_wait( &supported, 10, NULL );
81         supported = (errno != ENOSYS);
82     }
83     return supported;
84 }
85
86 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
87 {
88     int val;
89     struct timespec timespec;
90
91     if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;
92
93     timespec.tv_sec  = timeout;
94     timespec.tv_nsec = 0;
95     while ((val = interlocked_cmpxchg( (int *)&crit->LockSemaphore, 0, 1 )) != 1)
96     {
97         /* note: this may wait longer than specified in case of signals or */
98         /*       multiple wake-ups, but that shouldn't be a problem */
99         if (futex_wait( (int *)&crit->LockSemaphore, val, &timespec ) == -1 && errno == ETIMEDOUT)
100             return STATUS_TIMEOUT;
101     }
102     return STATUS_WAIT_0;
103 }
104
105 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
106 {
107     if (!use_futexes()) return STATUS_NOT_IMPLEMENTED;
108
109     *(int *)&crit->LockSemaphore = 1;
110     futex_wake( (int *)&crit->LockSemaphore, 1 );
111     return STATUS_SUCCESS;
112 }
113
114 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
115 {
116     if (!use_futexes()) NtClose( crit->LockSemaphore );
117 }
118
119 #elif defined(__APPLE__)
120
121 #include <mach/mach.h>
122 #include <mach/task.h>
123 #include <mach/semaphore.h>
124
125 static inline semaphore_t get_mach_semaphore( RTL_CRITICAL_SECTION *crit )
126 {
127     semaphore_t ret = *(int *)&crit->LockSemaphore;
128     if (!ret)
129     {
130         semaphore_t sem;
131         if (semaphore_create( mach_task_self(), &sem, SYNC_POLICY_FIFO, 0 )) return 0;
132         if (!(ret = interlocked_cmpxchg( (int *)&crit->LockSemaphore, sem, 0 )))
133             ret = sem;
134         else
135             semaphore_destroy( mach_task_self(), sem );  /* somebody beat us to it */
136     }
137     return ret;
138 }
139
140 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
141 {
142     mach_timespec_t timespec;
143     semaphore_t sem = get_mach_semaphore( crit );
144
145     timespec.tv_sec = timeout;
146     timespec.tv_nsec = 0;
147     for (;;)
148     {
149         switch( semaphore_timedwait( sem, timespec ))
150         {
151         case KERN_SUCCESS:
152             return STATUS_WAIT_0;
153         case KERN_ABORTED:
154             continue;  /* got a signal, restart */
155         case KERN_OPERATION_TIMED_OUT:
156             return STATUS_TIMEOUT;
157         default:
158             return STATUS_INVALID_HANDLE;
159         }
160     }
161 }
162
163 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
164 {
165     semaphore_t sem = get_mach_semaphore( crit );
166     semaphore_signal( sem );
167     return STATUS_SUCCESS;
168 }
169
170 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
171 {
172     semaphore_destroy( mach_task_self(), *(int *)&crit->LockSemaphore );
173 }
174
175 #else  /* __APPLE__ */
176
177 static inline NTSTATUS fast_wait( RTL_CRITICAL_SECTION *crit, int timeout )
178 {
179     return STATUS_NOT_IMPLEMENTED;
180 }
181
182 static inline NTSTATUS fast_wake( RTL_CRITICAL_SECTION *crit )
183 {
184     return STATUS_NOT_IMPLEMENTED;
185 }
186
187 static inline void close_semaphore( RTL_CRITICAL_SECTION *crit )
188 {
189     NtClose( crit->LockSemaphore );
190 }
191
192 #endif
193
194 /***********************************************************************
195  *           get_semaphore
196  */
197 static inline HANDLE get_semaphore( RTL_CRITICAL_SECTION *crit )
198 {
199     HANDLE ret = crit->LockSemaphore;
200     if (!ret)
201     {
202         HANDLE sem;
203         if (NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 )) return 0;
204         if (!(ret = interlocked_cmpxchg_ptr( &crit->LockSemaphore, sem, 0 )))
205             ret = sem;
206         else
207             NtClose(sem);  /* somebody beat us to it */
208     }
209     return ret;
210 }
211
212 /***********************************************************************
213  *           wait_semaphore
214  */
215 static inline NTSTATUS wait_semaphore( RTL_CRITICAL_SECTION *crit, int timeout )
216 {
217     NTSTATUS ret;
218
219     /* debug info is cleared by MakeCriticalSectionGlobal */
220     if (!crit->DebugInfo || ((ret = fast_wait( crit, timeout )) == STATUS_NOT_IMPLEMENTED))
221     {
222         HANDLE sem = get_semaphore( crit );
223         LARGE_INTEGER time;
224
225         time.QuadPart = timeout * (LONGLONG)-10000000;
226         ret = NTDLL_wait_for_multiple_objects( 1, &sem, 0, &time, 0 );
227     }
228     return ret;
229 }
230
231 /***********************************************************************
232  *           RtlInitializeCriticalSection   (NTDLL.@)
233  *
234  * Initialises a new critical section.
235  *
236  * PARAMS
237  *  crit [O] Critical section to initialise
238  *
239  * RETURNS
240  *  STATUS_SUCCESS.
241  *
242  * SEE
243  *  RtlInitializeCriticalSectionEx(),
244  *  RtlInitializeCriticalSectionAndSpinCount(), RtlDeleteCriticalSection(),
245  *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
246  *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
247  */
248 NTSTATUS WINAPI RtlInitializeCriticalSection( RTL_CRITICAL_SECTION *crit )
249 {
250     return RtlInitializeCriticalSectionEx( crit, 0, 0 );
251 }
252
253 /***********************************************************************
254  *           RtlInitializeCriticalSectionAndSpinCount   (NTDLL.@)
255  *
256  * Initialises a new critical section with a given spin count.
257  *
258  * PARAMS
259  *   crit      [O] Critical section to initialise
260  *   spincount [I] Spin count for crit
261  * 
262  * RETURNS
263  *  STATUS_SUCCESS.
264  *
265  * NOTES
266  *  Available on NT4 SP3 or later.
267  *
268  * SEE
269  *  RtlInitializeCriticalSectionEx(),
270  *  RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
271  *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
272  *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
273  */
274 NTSTATUS WINAPI RtlInitializeCriticalSectionAndSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
275 {
276     return RtlInitializeCriticalSectionEx( crit, spincount, 0 );
277 }
278
279 /***********************************************************************
280  *           RtlInitializeCriticalSectionEx   (NTDLL.@)
281  *
282  * Initialises a new critical section with a given spin count and flags.
283  *
284  * PARAMS
285  *   crit      [O] Critical section to initialise.
286  *   spincount [I] Number of times to spin upon contention.
287  *   flags     [I] RTL_CRITICAL_SECTION_FLAG_ flags from winnt.h.
288  *
289  * RETURNS
290  *  STATUS_SUCCESS.
291  *
292  * NOTES
293  *  Available on Vista or later.
294  *
295  * SEE
296  *  RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
297  *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
298  *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
299  */
300 NTSTATUS WINAPI RtlInitializeCriticalSectionEx( RTL_CRITICAL_SECTION *crit, ULONG spincount, ULONG flags )
301 {
302     if (flags & (RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN|RTL_CRITICAL_SECTION_FLAG_STATIC_INIT))
303         FIXME("(%p,%u,0x%08x) semi-stub\n", crit, spincount, flags);
304
305     /* FIXME: if RTL_CRITICAL_SECTION_FLAG_STATIC_INIT is given, we should use
306      * memory from a static pool to hold the debug info. Then heap.c could pass
307      * this flag rather than initialising the process heap CS by hand. If this
308      * is done, then debug info should be managed through Rtlp[Allocate|Free]DebugInfo
309      * so (e.g.) MakeCriticalSectionGlobal() doesn't free it using HeapFree().
310      */
311     if (flags & RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO)
312         crit->DebugInfo = NULL;
313     else
314         crit->DebugInfo = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(RTL_CRITICAL_SECTION_DEBUG));
315
316     if (crit->DebugInfo)
317     {
318         crit->DebugInfo->Type = 0;
319         crit->DebugInfo->CreatorBackTraceIndex = 0;
320         crit->DebugInfo->CriticalSection = crit;
321         crit->DebugInfo->ProcessLocksList.Blink = &(crit->DebugInfo->ProcessLocksList);
322         crit->DebugInfo->ProcessLocksList.Flink = &(crit->DebugInfo->ProcessLocksList);
323         crit->DebugInfo->EntryCount = 0;
324         crit->DebugInfo->ContentionCount = 0;
325         memset( crit->DebugInfo->Spare, 0, sizeof(crit->DebugInfo->Spare) );
326     }
327     crit->LockCount      = -1;
328     crit->RecursionCount = 0;
329     crit->OwningThread   = 0;
330     crit->LockSemaphore  = 0;
331     if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
332     crit->SpinCount = spincount & ~0x80000000;
333     return STATUS_SUCCESS;
334 }
335
336 /***********************************************************************
337  *           RtlSetCriticalSectionSpinCount   (NTDLL.@)
338  *
339  * Sets the spin count of a critical section.
340  *
341  * PARAMS
342  *   crit      [I/O] Critical section
343  *   spincount [I] Spin count for crit
344  *
345  * RETURNS
346  *  The previous spin count.
347  *
348  * NOTES
349  *  If the system is not SMP, spincount is ignored and set to 0.
350  *
351  * SEE
352  *  RtlInitializeCriticalSectionEx(),
353  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
354  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
355  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
356  */
357 ULONG WINAPI RtlSetCriticalSectionSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
358 {
359     ULONG oldspincount = crit->SpinCount;
360     if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
361     crit->SpinCount = spincount;
362     return oldspincount;
363 }
364
365 /***********************************************************************
366  *           RtlDeleteCriticalSection   (NTDLL.@)
367  *
368  * Frees the resources used by a critical section.
369  *
370  * PARAMS
371  *  crit [I/O] Critical section to free
372  *
373  * RETURNS
374  *  STATUS_SUCCESS.
375  *
376  * SEE
377  *  RtlInitializeCriticalSectionEx(),
378  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
379  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
380  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
381  */
382 NTSTATUS WINAPI RtlDeleteCriticalSection( RTL_CRITICAL_SECTION *crit )
383 {
384     crit->LockCount      = -1;
385     crit->RecursionCount = 0;
386     crit->OwningThread   = 0;
387     if (crit->DebugInfo)
388     {
389         /* only free the ones we made in here */
390         if (!crit->DebugInfo->Spare[0])
391         {
392             RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
393             crit->DebugInfo = NULL;
394         }
395         close_semaphore( crit );
396     }
397     else NtClose( crit->LockSemaphore );
398     crit->LockSemaphore = 0;
399     return STATUS_SUCCESS;
400 }
401
402
403 /***********************************************************************
404  *           RtlpWaitForCriticalSection   (NTDLL.@)
405  *
406  * Waits for a busy critical section to become free.
407  * 
408  * PARAMS
409  *  crit [I/O] Critical section to wait for
410  *
411  * RETURNS
412  *  STATUS_SUCCESS.
413  *
414  * NOTES
415  *  Use RtlEnterCriticalSection() instead of this function as it is often much
416  *  faster.
417  *
418  * SEE
419  *  RtlInitializeCriticalSectionEx(),
420  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
421  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
422  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
423  */
424 NTSTATUS WINAPI RtlpWaitForCriticalSection( RTL_CRITICAL_SECTION *crit )
425 {
426     for (;;)
427     {
428         EXCEPTION_RECORD rec;
429         NTSTATUS status = wait_semaphore( crit, 5 );
430
431         if ( status == STATUS_TIMEOUT )
432         {
433             const char *name = NULL;
434             if (crit->DebugInfo) name = (char *)crit->DebugInfo->Spare[0];
435             if (!name) name = "?";
436             ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (60 sec)\n",
437                  crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
438             status = wait_semaphore( crit, 60 );
439             if ( status == STATUS_TIMEOUT && TRACE_ON(relay) )
440             {
441                 ERR( "section %p %s wait timed out in thread %04x, blocked by %04x, retrying (5 min)\n",
442                      crit, debugstr_a(name), GetCurrentThreadId(), HandleToULong(crit->OwningThread) );
443                 status = wait_semaphore( crit, 300 );
444             }
445         }
446         if (status == STATUS_WAIT_0) break;
447
448         /* Throw exception only for Wine internal locks */
449         if ((!crit->DebugInfo) || (!crit->DebugInfo->Spare[0])) continue;
450
451         rec.ExceptionCode    = STATUS_POSSIBLE_DEADLOCK;
452         rec.ExceptionFlags   = 0;
453         rec.ExceptionRecord  = NULL;
454         rec.ExceptionAddress = RtlRaiseException;  /* sic */
455         rec.NumberParameters = 1;
456         rec.ExceptionInformation[0] = (ULONG_PTR)crit;
457         RtlRaiseException( &rec );
458     }
459     if (crit->DebugInfo) crit->DebugInfo->ContentionCount++;
460     return STATUS_SUCCESS;
461 }
462
463
464 /***********************************************************************
465  *           RtlpUnWaitCriticalSection   (NTDLL.@)
466  *
467  * Notifies other threads waiting on the busy critical section that it has
468  * become free.
469  * 
470  * PARAMS
471  *  crit [I/O] Critical section
472  *
473  * RETURNS
474  *  Success: STATUS_SUCCESS.
475  *  Failure: Any error returned by NtReleaseSemaphore()
476  *
477  * NOTES
478  *  Use RtlLeaveCriticalSection() instead of this function as it is often much
479  *  faster.
480  *
481  * SEE
482  *  RtlInitializeCriticalSectionEx(),
483  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
484  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
485  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
486  */
487 NTSTATUS WINAPI RtlpUnWaitCriticalSection( RTL_CRITICAL_SECTION *crit )
488 {
489     NTSTATUS ret;
490
491     /* debug info is cleared by MakeCriticalSectionGlobal */
492     if (!crit->DebugInfo || ((ret = fast_wake( crit )) == STATUS_NOT_IMPLEMENTED))
493     {
494         HANDLE sem = get_semaphore( crit );
495         ret = NtReleaseSemaphore( sem, 1, NULL );
496     }
497     if (ret) RtlRaiseStatus( ret );
498     return ret;
499 }
500
501
502 /***********************************************************************
503  *           RtlEnterCriticalSection   (NTDLL.@)
504  *
505  * Enters a critical section, waiting for it to become available if necessary.
506  *
507  * PARAMS
508  *  crit [I/O] Critical section to enter
509  *
510  * RETURNS
511  *  STATUS_SUCCESS. The critical section is held by the caller.
512  *  
513  * SEE
514  *  RtlInitializeCriticalSectionEx(),
515  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
516  *  RtlDeleteCriticalSection(), RtlSetCriticalSectionSpinCount(),
517  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
518  */
519 NTSTATUS WINAPI RtlEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
520 {
521     if (crit->SpinCount)
522     {
523         ULONG count;
524
525         if (RtlTryEnterCriticalSection( crit )) return STATUS_SUCCESS;
526         for (count = crit->SpinCount; count > 0; count--)
527         {
528             if (crit->LockCount > 0) break;  /* more than one waiter, don't bother spinning */
529             if (crit->LockCount == -1)       /* try again */
530             {
531                 if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1) goto done;
532             }
533             small_pause();
534         }
535     }
536
537     if (interlocked_inc( &crit->LockCount ))
538     {
539         if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
540         {
541             crit->RecursionCount++;
542             return STATUS_SUCCESS;
543         }
544
545         /* Now wait for it */
546         RtlpWaitForCriticalSection( crit );
547     }
548 done:
549     crit->OwningThread   = ULongToHandle(GetCurrentThreadId());
550     crit->RecursionCount = 1;
551     return STATUS_SUCCESS;
552 }
553
554
555 /***********************************************************************
556  *           RtlTryEnterCriticalSection   (NTDLL.@)
557  *
558  * Tries to enter a critical section without waiting.
559  *
560  * PARAMS
561  *  crit [I/O] Critical section to enter
562  *
563  * RETURNS
564  *  Success: TRUE. The critical section is held by the caller.
565  *  Failure: FALSE. The critical section is currently held by another thread.
566  *
567  * SEE
568  *  RtlInitializeCriticalSectionEx(),
569  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
570  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
571  *  RtlLeaveCriticalSection(), RtlSetCriticalSectionSpinCount()
572  */
573 BOOL WINAPI RtlTryEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
574 {
575     BOOL ret = FALSE;
576     if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1)
577     {
578         crit->OwningThread   = ULongToHandle(GetCurrentThreadId());
579         crit->RecursionCount = 1;
580         ret = TRUE;
581     }
582     else if (crit->OwningThread == ULongToHandle(GetCurrentThreadId()))
583     {
584         interlocked_inc( &crit->LockCount );
585         crit->RecursionCount++;
586         ret = TRUE;
587     }
588     return ret;
589 }
590
591
592 /***********************************************************************
593  *           RtlLeaveCriticalSection   (NTDLL.@)
594  *
595  * Leaves a critical section.
596  *
597  * PARAMS
598  *  crit [I/O] Critical section to leave.
599  *
600  * RETURNS
601  *  STATUS_SUCCESS.
602  *
603  * SEE
604  *  RtlInitializeCriticalSectionEx(),
605  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
606  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
607  *  RtlSetCriticalSectionSpinCount(), RtlTryEnterCriticalSection()
608  */
609 NTSTATUS WINAPI RtlLeaveCriticalSection( RTL_CRITICAL_SECTION *crit )
610 {
611     if (--crit->RecursionCount) interlocked_dec( &crit->LockCount );
612     else
613     {
614         crit->OwningThread = 0;
615         if (interlocked_dec( &crit->LockCount ) >= 0)
616         {
617             /* someone is waiting */
618             RtlpUnWaitCriticalSection( crit );
619         }
620     }
621     return STATUS_SUCCESS;
622 }