Specify 64-bit integers as double instead of long long in spec files
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include "windef.h"
29 #include "winternl.h"
30 #include "wine/debug.h"
31 #include "ntdll_misc.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
34 WINE_DECLARE_DEBUG_CHANNEL(relay);
35
36 inline static LONG interlocked_inc( PLONG dest )
37 {
38     return interlocked_xchg_add( dest, 1 ) + 1;
39 }
40
41 inline static LONG interlocked_dec( PLONG dest )
42 {
43     return interlocked_xchg_add( dest, -1 ) - 1;
44 }
45
46 inline static void small_pause(void)
47 {
48 #ifdef __i386__
49     __asm__ __volatile__( "rep;nop" : : : "memory" );
50 #else
51     __asm__ __volatile__( "" : : : "memory" );
52 #endif
53 }
54
55 /***********************************************************************
56  *           get_semaphore
57  */
58 static inline HANDLE get_semaphore( RTL_CRITICAL_SECTION *crit )
59 {
60     HANDLE ret = crit->LockSemaphore;
61     if (!ret)
62     {
63         HANDLE sem;
64         if (NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 )) return 0;
65         if (!(ret = (HANDLE)interlocked_cmpxchg_ptr( (PVOID *)&crit->LockSemaphore,
66                                                      (PVOID)sem, 0 )))
67             ret = sem;
68         else
69             NtClose(sem);  /* somebody beat us to it */
70     }
71     return ret;
72 }
73
74 /***********************************************************************
75  *           RtlInitializeCriticalSection   (NTDLL.@)
76  *
77  * Initialises a new critical section.
78  *
79  * PARAMS
80  *  crit [O] Critical section to initialise
81  *
82  * RETURNS
83  *  STATUS_SUCCESS.
84  *
85  * SEE
86  *  RtlInitializeCriticalSectionAndSpinCount(), RtlDeleteCriticalSection(),
87  *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
88  *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
89  */
90 NTSTATUS WINAPI RtlInitializeCriticalSection( RTL_CRITICAL_SECTION *crit )
91 {
92     return RtlInitializeCriticalSectionAndSpinCount( crit, 0 );
93 }
94
95 /***********************************************************************
96  *           RtlInitializeCriticalSectionAndSpinCount   (NTDLL.@)
97  *
98  * Initialises a new critical section with a given spin count.
99  *
100  * PARAMS
101  *   crit      [O] Critical section to initialise
102  *   spincount [I] Spin count for crit
103  * 
104  * RETURNS
105  *  STATUS_SUCCESS.
106  *
107  * NOTES
108  *  Available on NT4 SP3 or later.
109  *
110  * SEE
111  *  RtlInitializeCriticalSection(), RtlDeleteCriticalSection(),
112  *  RtlEnterCriticalSection(), RtlLeaveCriticalSection(),
113  *  RtlTryEnterCriticalSection(), RtlSetCriticalSectionSpinCount()
114  */
115 NTSTATUS WINAPI RtlInitializeCriticalSectionAndSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
116 {
117     crit->DebugInfo = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(RTL_CRITICAL_SECTION_DEBUG));
118     if (crit->DebugInfo)
119     {
120         crit->DebugInfo->Type = 0;
121         crit->DebugInfo->CreatorBackTraceIndex = 0;
122         crit->DebugInfo->CriticalSection = crit;
123         crit->DebugInfo->ProcessLocksList.Blink = &(crit->DebugInfo->ProcessLocksList);
124         crit->DebugInfo->ProcessLocksList.Flink = &(crit->DebugInfo->ProcessLocksList);
125         crit->DebugInfo->EntryCount = 0;
126         crit->DebugInfo->ContentionCount = 0;
127         memset( crit->DebugInfo->Spare, 0, sizeof(crit->DebugInfo->Spare) );
128     }
129     crit->LockCount      = -1;
130     crit->RecursionCount = 0;
131     crit->OwningThread   = 0;
132     crit->LockSemaphore  = 0;
133     if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
134     crit->SpinCount = spincount & ~0x80000000;
135     return STATUS_SUCCESS;
136 }
137
138 /***********************************************************************
139  *           RtlSetCriticalSectionSpinCount   (NTDLL.@)
140  *
141  * Sets the spin count of a critical section.
142  *
143  * PARAMS
144  *   crit      [I/O] Critical section
145  *   spincount [I] Spin count for crit
146  *
147  * RETURNS
148  *  The previous spin count.
149  *
150  * NOTES
151  *  If the system is not SMP, spincount is ignored and set to 0.
152  *
153  * SEE
154  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
155  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
156  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
157  */
158 ULONG WINAPI RtlSetCriticalSectionSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
159 {
160     ULONG oldspincount = crit->SpinCount;
161     if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
162     crit->SpinCount = spincount;
163     return oldspincount;
164 }
165
166 /***********************************************************************
167  *           RtlDeleteCriticalSection   (NTDLL.@)
168  *
169  * Frees the resources used by a critical section.
170  *
171  * PARAMS
172  *  crit [I/O] Critical section to free
173  *
174  * RETURNS
175  *  STATUS_SUCCESS.
176  *
177  * SEE
178  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
179  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
180  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
181  */
182 NTSTATUS WINAPI RtlDeleteCriticalSection( RTL_CRITICAL_SECTION *crit )
183 {
184     crit->LockCount      = -1;
185     crit->RecursionCount = 0;
186     crit->OwningThread   = 0;
187     if (crit->LockSemaphore) NtClose( crit->LockSemaphore );
188     crit->LockSemaphore  = 0;
189     if (crit->DebugInfo)
190     {
191         /* only free the ones we made in here */
192         if (!crit->DebugInfo->Spare[0])
193         {
194             RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
195             crit->DebugInfo = NULL;
196         }
197     }
198     return STATUS_SUCCESS;
199 }
200
201
202 /***********************************************************************
203  *           RtlpWaitForCriticalSection   (NTDLL.@)
204  *
205  * Waits for a busy critical section to become free.
206  * 
207  * PARAMS
208  *  crit [I/O] Critical section to wait for
209  *
210  * RETURNS
211  *  STATUS_SUCCESS.
212  *
213  * NOTES
214  *  Use RtlEnterCriticalSection() instead of this function as it is often much
215  *  faster.
216  *
217  * SEE
218  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
219  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
220  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
221  */
222 NTSTATUS WINAPI RtlpWaitForCriticalSection( RTL_CRITICAL_SECTION *crit )
223 {
224     for (;;)
225     {
226         EXCEPTION_RECORD rec;
227         HANDLE sem = get_semaphore( crit );
228         LARGE_INTEGER time;
229         DWORD status;
230
231         time.QuadPart = -5000 * 10000;  /* 5 seconds */
232         status = NtWaitForSingleObject( sem, FALSE, &time );
233         if ( status == STATUS_TIMEOUT )
234         {
235             const char *name = NULL;
236             if (crit->DebugInfo) name = (char *)crit->DebugInfo->Spare[0];
237             if (!name) name = "?";
238             ERR( "section %p %s wait timed out in thread %04lx, blocked by %04lx, retrying (60 sec)\n",
239                  crit, debugstr_a(name), GetCurrentThreadId(), (DWORD)crit->OwningThread );
240             time.QuadPart = -60000 * 10000;
241             status = NtWaitForSingleObject( sem, FALSE, &time );
242             if ( status == STATUS_TIMEOUT && TRACE_ON(relay) )
243             {
244                 ERR( "section %p %s wait timed out in thread %04lx, blocked by %04lx, retrying (5 min)\n",
245                      crit, debugstr_a(name), GetCurrentThreadId(), (DWORD) crit->OwningThread );
246                 time.QuadPart = -300000 * (ULONGLONG)10000;
247                 status = NtWaitForSingleObject( sem, FALSE, &time );
248             }
249         }
250         if (status == STATUS_WAIT_0) return STATUS_SUCCESS;
251
252         /* Throw exception only for Wine internal locks */
253         if ((!crit->DebugInfo) || (!crit->DebugInfo->Spare[0])) continue;
254
255         rec.ExceptionCode    = STATUS_POSSIBLE_DEADLOCK;
256         rec.ExceptionFlags   = 0;
257         rec.ExceptionRecord  = NULL;
258         rec.ExceptionAddress = RtlRaiseException;  /* sic */
259         rec.NumberParameters = 1;
260         rec.ExceptionInformation[0] = (ULONG_PTR)crit;
261         RtlRaiseException( &rec );
262     }
263 }
264
265
266 /***********************************************************************
267  *           RtlpUnWaitCriticalSection   (NTDLL.@)
268  *
269  * Notifies other threads waiting on the busy critical section that it has
270  * become free.
271  * 
272  * PARAMS
273  *  crit [I/O] Critical section
274  *
275  * RETURNS
276  *  Success: STATUS_SUCCESS.
277  *  Failure: Any error returned by NtReleaseSemaphore()
278  *
279  * NOTES
280  *  Use RtlLeaveCriticalSection() instead of this function as it is often much
281  *  faster.
282  *
283  * SEE
284  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
285  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
286  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
287  */
288 NTSTATUS WINAPI RtlpUnWaitCriticalSection( RTL_CRITICAL_SECTION *crit )
289 {
290     HANDLE sem = get_semaphore( crit );
291     NTSTATUS res = NtReleaseSemaphore( sem, 1, NULL );
292     if (res) RtlRaiseStatus( res );
293     return res;
294 }
295
296
297 /***********************************************************************
298  *           RtlEnterCriticalSection   (NTDLL.@)
299  *
300  * Enters a critical section, waiting for it to become available if necessary.
301  *
302  * PARAMS
303  *  crit [I/O] Critical section to enter
304  *
305  * RETURNS
306  *  STATUS_SUCCESS. The critical section is held by the caller.
307  *  
308  * SEE
309  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
310  *  RtlDeleteCriticalSection(), RtlSetCriticalSectionSpinCount(),
311  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
312  */
313 NTSTATUS WINAPI RtlEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
314 {
315     if (crit->SpinCount)
316     {
317         ULONG count;
318
319         if (RtlTryEnterCriticalSection( crit )) return STATUS_SUCCESS;
320         for (count = crit->SpinCount; count > 0; count--)
321         {
322             if (crit->LockCount > 0) break;  /* more than one waiter, don't bother spinning */
323             if (crit->LockCount == -1)       /* try again */
324             {
325                 if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1) goto done;
326             }
327             small_pause();
328         }
329     }
330
331     if (interlocked_inc( &crit->LockCount ))
332     {
333         if (crit->OwningThread == (HANDLE)GetCurrentThreadId())
334         {
335             crit->RecursionCount++;
336             return STATUS_SUCCESS;
337         }
338
339         /* Now wait for it */
340         RtlpWaitForCriticalSection( crit );
341     }
342 done:
343     crit->OwningThread   = (HANDLE)GetCurrentThreadId();
344     crit->RecursionCount = 1;
345     return STATUS_SUCCESS;
346 }
347
348
349 /***********************************************************************
350  *           RtlTryEnterCriticalSection   (NTDLL.@)
351  *
352  * Tries to enter a critical section without waiting.
353  *
354  * PARAMS
355  *  crit [I/O] Critical section to enter
356  *
357  * RETURNS
358  *  Success: TRUE. The critical section is held by the caller.
359  *  Failure: FALSE. The critical section is currently held by another thread.
360  *
361  * SEE
362  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
363  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
364  *  RtlLeaveCriticalSection(), RtlSetCriticalSectionSpinCount()
365  */
366 BOOL WINAPI RtlTryEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
367 {
368     BOOL ret = FALSE;
369     if (interlocked_cmpxchg( &crit->LockCount, 0L, -1 ) == -1)
370     {
371         crit->OwningThread   = (HANDLE)GetCurrentThreadId();
372         crit->RecursionCount = 1;
373         ret = TRUE;
374     }
375     else if (crit->OwningThread == (HANDLE)GetCurrentThreadId())
376     {
377         interlocked_inc( &crit->LockCount );
378         crit->RecursionCount++;
379         ret = TRUE;
380     }
381     return ret;
382 }
383
384
385 /***********************************************************************
386  *           RtlLeaveCriticalSection   (NTDLL.@)
387  *
388  * Leaves a critical section.
389  *
390  * PARAMS
391  *  crit [I/O] Critical section to leave.
392  *
393  * RETURNS
394  *  STATUS_SUCCESS.
395  *
396  * SEE
397  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
398  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
399  *  RtlSetCriticalSectionSpinCount(), RtlTryEnterCriticalSection()
400  */
401 NTSTATUS WINAPI RtlLeaveCriticalSection( RTL_CRITICAL_SECTION *crit )
402 {
403     if (--crit->RecursionCount) interlocked_dec( &crit->LockCount );
404     else
405     {
406         crit->OwningThread = 0;
407         if (interlocked_dec( &crit->LockCount ) >= 0)
408         {
409             /* someone is waiting */
410             RtlpUnWaitCriticalSection( crit );
411         }
412     }
413     return STATUS_SUCCESS;
414 }