Don't include winbase.h or winerror.h when not necessary.
[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     if (!GetProcessHeap()) crit->DebugInfo = NULL;
118     else
119     {
120         crit->DebugInfo = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(CRITICAL_SECTION_DEBUG));
121         if (crit->DebugInfo)
122         {
123             crit->DebugInfo->Type = 0;
124             crit->DebugInfo->CreatorBackTraceIndex = 0;
125             crit->DebugInfo->CriticalSection = crit;
126             crit->DebugInfo->ProcessLocksList.Blink = &(crit->DebugInfo->ProcessLocksList);
127             crit->DebugInfo->ProcessLocksList.Flink = &(crit->DebugInfo->ProcessLocksList);
128             crit->DebugInfo->EntryCount = 0;
129             crit->DebugInfo->ContentionCount = 0;
130             crit->DebugInfo->Spare[0] = 0;
131             crit->DebugInfo->Spare[1] = 0;
132         }
133     }
134     crit->LockCount      = -1;
135     crit->RecursionCount = 0;
136     crit->OwningThread   = 0;
137     crit->LockSemaphore  = 0;
138     crit->SpinCount      = spincount;
139     return STATUS_SUCCESS;
140 }
141
142 /***********************************************************************
143  *           RtlSetCriticalSectionSpinCount   (NTDLL.@)
144  *
145  * Sets the spin count of a critical section.
146  *
147  * PARAMS
148  *   crit      [I/O] Critical section
149  *   spincount [I] Spin count for crit
150  *
151  * RETURNS
152  *  The previous spin count.
153  *
154  * NOTES
155  *  If the system is not SMP, spincount is ignored and set to 0.
156  *
157  * SEE
158  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
159  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
160  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
161  */
162 ULONG WINAPI RtlSetCriticalSectionSpinCount( RTL_CRITICAL_SECTION *crit, ULONG spincount )
163 {
164     ULONG oldspincount = crit->SpinCount;
165     if (NtCurrentTeb()->Peb->NumberOfProcessors <= 1) spincount = 0;
166     crit->SpinCount = spincount;
167     return oldspincount;
168 }
169
170 /***********************************************************************
171  *           RtlDeleteCriticalSection   (NTDLL.@)
172  *
173  * Frees the resources used by a critical section.
174  *
175  * PARAMS
176  *  crit [I/O] Critical section to free
177  *
178  * RETURNS
179  *  STATUS_SUCCESS.
180  *
181  * SEE
182  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
183  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
184  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
185  */
186 NTSTATUS WINAPI RtlDeleteCriticalSection( RTL_CRITICAL_SECTION *crit )
187 {
188     crit->LockCount      = -1;
189     crit->RecursionCount = 0;
190     crit->OwningThread   = 0;
191     if (crit->LockSemaphore) NtClose( crit->LockSemaphore );
192     crit->LockSemaphore  = 0;
193     if (crit->DebugInfo)
194     {
195         /* only free the ones we made in here */
196         if (!crit->DebugInfo->Spare[1])
197         {
198             RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
199             crit->DebugInfo = NULL;
200         }
201     }
202     return STATUS_SUCCESS;
203 }
204
205
206 /***********************************************************************
207  *           RtlpWaitForCriticalSection   (NTDLL.@)
208  *
209  * Waits for a busy critical section to become free.
210  * 
211  * PARAMS
212  *  crit [I/O] Critical section to wait for
213  *
214  * RETURNS
215  *  STATUS_SUCCESS.
216  *
217  * NOTES
218  *  Use RtlEnterCriticalSection() instead of this function as it is often much
219  *  faster.
220  *
221  * SEE
222  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
223  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
224  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
225  */
226 NTSTATUS WINAPI RtlpWaitForCriticalSection( RTL_CRITICAL_SECTION *crit )
227 {
228     for (;;)
229     {
230         EXCEPTION_RECORD rec;
231         HANDLE sem = get_semaphore( crit );
232         LARGE_INTEGER time;
233         DWORD status;
234
235         time.QuadPart = -5000 * 10000;  /* 5 seconds */
236         status = NtWaitForSingleObject( sem, FALSE, &time );
237         if ( status == WAIT_TIMEOUT )
238         {
239             const char *name = NULL;
240             if (crit->DebugInfo) name = (char *)crit->DebugInfo->Spare[1];
241             if (!name) name = "?";
242             ERR( "section %p %s wait timed out in thread %04lx, blocked by %04lx, retrying (60 sec)\n",
243                  crit, debugstr_a(name), GetCurrentThreadId(), (DWORD)crit->OwningThread );
244             time.QuadPart = -60000 * 10000;
245             status = NtWaitForSingleObject( sem, FALSE, &time );
246             if ( status == WAIT_TIMEOUT && TRACE_ON(relay) )
247             {
248                 ERR( "section %p %s wait timed out in thread %04lx, blocked by %04lx, retrying (5 min)\n",
249                      crit, debugstr_a(name), GetCurrentThreadId(), (DWORD) crit->OwningThread );
250                 time.QuadPart = -300000 * (ULONGLONG)10000;
251                 status = NtWaitForSingleObject( sem, FALSE, &time );
252             }
253         }
254         if (status == STATUS_WAIT_0) return STATUS_SUCCESS;
255
256         /* Throw exception only for Wine internal locks */
257         if ((!crit->DebugInfo) || (!crit->DebugInfo->Spare[1])) continue;
258
259         rec.ExceptionCode    = STATUS_POSSIBLE_DEADLOCK;
260         rec.ExceptionFlags   = 0;
261         rec.ExceptionRecord  = NULL;
262         rec.ExceptionAddress = RtlRaiseException;  /* sic */
263         rec.NumberParameters = 1;
264         rec.ExceptionInformation[0] = (ULONG_PTR)crit;
265         RtlRaiseException( &rec );
266     }
267 }
268
269
270 /***********************************************************************
271  *           RtlpUnWaitCriticalSection   (NTDLL.@)
272  *
273  * Notifies other threads waiting on the busy critical section that it has
274  * become free.
275  * 
276  * PARAMS
277  *  crit [I/O] Critical section
278  *
279  * RETURNS
280  *  Success: STATUS_SUCCESS.
281  *  Failure: Any error returned by NtReleaseSemaphore()
282  *
283  * NOTES
284  *  Use RtlLeaveCriticalSection() instead of this function as it is often much
285  *  faster.
286  *
287  * SEE
288  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
289  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
290  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
291  */
292 NTSTATUS WINAPI RtlpUnWaitCriticalSection( RTL_CRITICAL_SECTION *crit )
293 {
294     HANDLE sem = get_semaphore( crit );
295     NTSTATUS res = NtReleaseSemaphore( sem, 1, NULL );
296     if (res) RtlRaiseStatus( res );
297     return res;
298 }
299
300
301 /***********************************************************************
302  *           RtlEnterCriticalSection   (NTDLL.@)
303  *
304  * Enters a critical section, waiting for it to become available if necessary.
305  *
306  * PARAMS
307  *  crit [I/O] Critical section to enter
308  *
309  * RETURNS
310  *  STATUS_SUCCESS. The critical section is held by the caller.
311  *  
312  * SEE
313  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
314  *  RtlDeleteCriticalSection(), RtlSetCriticalSectionSpinCount(),
315  *  RtlLeaveCriticalSection(), RtlTryEnterCriticalSection()
316  */
317 NTSTATUS WINAPI RtlEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
318 {
319     if (crit->SpinCount)
320     {
321         ULONG count;
322
323         if (RtlTryEnterCriticalSection( crit )) return STATUS_SUCCESS;
324         for (count = crit->SpinCount; count > 0; count--)
325         {
326             if (crit->LockCount > 0) break;  /* more than one waiter, don't bother spinning */
327             if (crit->LockCount == -1)       /* try again */
328             {
329                 if (interlocked_cmpxchg( &crit->LockCount, 0, -1 ) == -1) goto done;
330             }
331             small_pause();
332         }
333     }
334
335     if (interlocked_inc( &crit->LockCount ))
336     {
337         if (crit->OwningThread == (HANDLE)GetCurrentThreadId())
338         {
339             crit->RecursionCount++;
340             return STATUS_SUCCESS;
341         }
342
343         /* Now wait for it */
344         RtlpWaitForCriticalSection( crit );
345     }
346 done:
347     crit->OwningThread   = (HANDLE)GetCurrentThreadId();
348     crit->RecursionCount = 1;
349     return STATUS_SUCCESS;
350 }
351
352
353 /***********************************************************************
354  *           RtlTryEnterCriticalSection   (NTDLL.@)
355  *
356  * Tries to enter a critical section without waiting.
357  *
358  * PARAMS
359  *  crit [I/O] Critical section to enter
360  *
361  * RETURNS
362  *  Success: TRUE. The critical section is held by the caller.
363  *  Failure: FALSE. The critical section is currently held by another thread.
364  *
365  * SEE
366  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
367  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
368  *  RtlLeaveCriticalSection(), RtlSetCriticalSectionSpinCount()
369  */
370 BOOL WINAPI RtlTryEnterCriticalSection( RTL_CRITICAL_SECTION *crit )
371 {
372     BOOL ret = FALSE;
373     if (interlocked_cmpxchg( &crit->LockCount, 0L, -1 ) == -1)
374     {
375         crit->OwningThread   = (HANDLE)GetCurrentThreadId();
376         crit->RecursionCount = 1;
377         ret = TRUE;
378     }
379     else if (crit->OwningThread == (HANDLE)GetCurrentThreadId())
380     {
381         interlocked_inc( &crit->LockCount );
382         crit->RecursionCount++;
383         ret = TRUE;
384     }
385     return ret;
386 }
387
388
389 /***********************************************************************
390  *           RtlLeaveCriticalSection   (NTDLL.@)
391  *
392  * Leaves a critical section.
393  *
394  * PARAMS
395  *  crit [I/O] Critical section to leave.
396  *
397  * RETURNS
398  *  STATUS_SUCCESS.
399  *
400  * SEE
401  *  RtlInitializeCriticalSection(), RtlInitializeCriticalSectionAndSpinCount(),
402  *  RtlDeleteCriticalSection(), RtlEnterCriticalSection(),
403  *  RtlSetCriticalSectionSpinCount(), RtlTryEnterCriticalSection()
404  */
405 NTSTATUS WINAPI RtlLeaveCriticalSection( RTL_CRITICAL_SECTION *crit )
406 {
407     if (--crit->RecursionCount) interlocked_dec( &crit->LockCount );
408     else
409     {
410         crit->OwningThread = 0;
411         if (interlocked_dec( &crit->LockCount ) >= 0)
412         {
413             /* someone is waiting */
414             RtlpUnWaitCriticalSection( crit );
415         }
416     }
417     return STATUS_SUCCESS;
418 }