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