VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/misc/thread.cpp@ 11557

Last change on this file since 11557 was 10795, checked in by vboxsync, 17 years ago

IPRT: Enabled the rtThreadRemoveLocked assertion on OS/2, hoping that the problem has been fix. Let me know if its still broken.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 45.5 KB
Line 
1/* $Id: thread.cpp 10795 2008-07-21 22:36:19Z vboxsync $ */
2/** @file
3 * IPRT - Threads, common routines.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32
33/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#define LOG_GROUP RTLOGGROUP_THREAD
37#include <iprt/thread.h>
38#include <iprt/log.h>
39#include <iprt/avl.h>
40#include <iprt/alloc.h>
41#include <iprt/assert.h>
42#include <iprt/semaphore.h>
43#ifdef IN_RING0
44# include <iprt/spinlock.h>
45#endif
46#include <iprt/asm.h>
47#include <iprt/err.h>
48#include <iprt/string.h>
49#include "internal/thread.h"
50#include "internal/sched.h"
51#include "internal/process.h"
52
53
54/*******************************************************************************
55* Defined Constants And Macros *
56*******************************************************************************/
57#ifdef IN_RING0
58# define RT_THREAD_LOCK_TMP(Tmp) RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER
59# define RT_THREAD_LOCK_RW(Tmp) RTSpinlockAcquireNoInts(g_ThreadSpinlock, &(Tmp))
60# define RT_THREAD_UNLOCK_RW(Tmp) RTSpinlockReleaseNoInts(g_ThreadSpinlock, &(Tmp))
61# define RT_THREAD_LOCK_RD(Tmp) RTSpinlockAcquireNoInts(g_ThreadSpinlock, &(Tmp))
62# define RT_THREAD_UNLOCK_RD(Tmp) RTSpinlockReleaseNoInts(g_ThreadSpinlock, &(Tmp))
63#else
64# define RT_THREAD_LOCK_TMP(Tmp)
65# define RT_THREAD_LOCK_RW(Tmp) rtThreadLockRW()
66# define RT_THREAD_UNLOCK_RW(Tmp) rtThreadUnLockRW()
67# define RT_THREAD_LOCK_RD(Tmp) rtThreadLockRD()
68# define RT_THREAD_UNLOCK_RD(Tmp) rtThreadUnLockRD()
69#endif
70
71
72/*******************************************************************************
73* Global Variables *
74*******************************************************************************/
75/** The AVL thread containing the threads. */
76static PAVLPVNODECORE g_ThreadTree;
77#ifdef IN_RING3
78/** The RW lock protecting the tree. */
79static RTSEMRW g_ThreadRWSem = NIL_RTSEMRW;
80#else
81/** The spinlocks protecting the tree. */
82static RTSPINLOCK g_ThreadSpinlock = NIL_RTSPINLOCK;
83#endif
84
85
86/*******************************************************************************
87* Internal Functions *
88*******************************************************************************/
89static void rtThreadDestroy(PRTTHREADINT pThread);
90static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName);
91static void rtThreadRemoveLocked(PRTTHREADINT pThread);
92static PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, unsigned fIntFlags, const char *pszName);
93
94
95/** @page pg_rt_thread IPRT Thread Internals
96 *
97 * IPRT provides interface to whatever native threading that the host provides,
98 * preferably using a CRT level interface to better integrate with other libraries.
99 *
100 * Internally IPRT keeps track of threads by means of the RTTHREADINT structure.
101 * All the RTTHREADINT structures are kept in a AVL tree which is protected by a
102 * read/write lock for efficient access. A thread is inserted into the tree in
103 * three places in the code. The main thread is 'adopted' by IPRT on RTR3Init()
104 * by rtThreadAdopt(). When creating a new thread there the child and the parent
105 * race inserting the thread, this is rtThreadMain() and RTThreadCreate.
106 *
107 * RTTHREADINT objects are using reference counting as a mean of sticking around
108 * till no-one needs them any longer. Waitable threads is created with one extra
109 * reference so they won't go away until they are waited on. This introduces a
110 * major problem if we use the host thread identifier as key in the AVL tree - the
111 * host may reuse the thread identifier before the thread was waited on. So, on
112 * most platforms we are using the RTTHREADINT pointer as key and not the
113 * thread id. RTThreadSelf() then have to be implemented using a pointer stored
114 * in thread local storage (TLS).
115 *
116 * In Ring-0 we only try keep track of kernel threads created by RTCreateThread
117 * at the moment. There we really only need the 'join' feature, but doing things
118 * the same way allow us to name threads and similar stuff.
119 */
120
121
122/**
123 * Initializes the thread database.
124 *
125 * @returns iprt status code.
126 */
127int rtThreadInit(void)
128{
129#ifdef IN_RING3
130 int rc = VINF_ALREADY_INITIALIZED;
131 if (g_ThreadRWSem == NIL_RTSEMRW)
132 {
133 /*
134 * We assume the caller is the 1st thread, which we'll call 'main'.
135 * But first, we'll create the semaphore.
136 */
137 int rc = RTSemRWCreate(&g_ThreadRWSem);
138 if (RT_SUCCESS(rc))
139 {
140 rc = rtThreadNativeInit();
141#ifdef IN_RING3
142 if (RT_SUCCESS(rc))
143 rc = rtThreadAdopt(RTTHREADTYPE_DEFAULT, 0, "main");
144 if (RT_SUCCESS(rc))
145 rc = rtSchedNativeCalcDefaultPriority(RTTHREADTYPE_DEFAULT);
146#endif
147 if (RT_SUCCESS(rc))
148 return VINF_SUCCESS;
149
150 /* failed, clear out */
151 RTSemRWDestroy(g_ThreadRWSem);
152 g_ThreadRWSem = NIL_RTSEMRW;
153 }
154 }
155
156#elif defined(IN_RING0)
157
158 /*
159 * Create the spinlock and to native init.
160 */
161 Assert(g_ThreadSpinlock == NIL_RTSPINLOCK);
162 int rc = RTSpinlockCreate(&g_ThreadSpinlock);
163 if (RT_SUCCESS(rc))
164 {
165 rc = rtThreadNativeInit();
166 if (RT_SUCCESS(rc))
167 return VINF_SUCCESS;
168
169 /* failed, clear out */
170 RTSpinlockDestroy(g_ThreadSpinlock);
171 g_ThreadSpinlock = NIL_RTSPINLOCK;
172 }
173#else
174# error "!IN_RING0 && !IN_RING3"
175#endif
176 return rc;
177}
178
179
180/**
181 * Terminates the thread database.
182 */
183void rtThreadTerm(void)
184{
185#ifdef IN_RING3
186 /* we don't cleanup here yet */
187
188#elif defined(IN_RING0)
189 /* just destroy the spinlock and assume the thread is fine... */
190 RTSpinlockDestroy(g_ThreadSpinlock);
191 g_ThreadSpinlock = NIL_RTSPINLOCK;
192 if (g_ThreadTree != NULL)
193 AssertMsg2("WARNING: g_ThreadTree=%p\n", g_ThreadTree);
194#endif
195}
196
197
198
199#ifdef IN_RING3
200
201DECLINLINE(void) rtThreadLockRW(void)
202{
203 if (g_ThreadRWSem == NIL_RTSEMRW)
204 rtThreadInit();
205 int rc = RTSemRWRequestWrite(g_ThreadRWSem, RT_INDEFINITE_WAIT);
206 AssertReleaseRC(rc);
207}
208
209
210DECLINLINE(void) rtThreadLockRD(void)
211{
212 if (g_ThreadRWSem == NIL_RTSEMRW)
213 rtThreadInit();
214 int rc = RTSemRWRequestRead(g_ThreadRWSem, RT_INDEFINITE_WAIT);
215 AssertReleaseRC(rc);
216}
217
218
219DECLINLINE(void) rtThreadUnLockRW(void)
220{
221 int rc = RTSemRWReleaseWrite(g_ThreadRWSem);
222 AssertReleaseRC(rc);
223}
224
225
226DECLINLINE(void) rtThreadUnLockRD(void)
227{
228 int rc = RTSemRWReleaseRead(g_ThreadRWSem);
229 AssertReleaseRC(rc);
230}
231
232#endif /* IN_RING3 */
233
234
235/**
236 * Adopts the calling thread.
237 * No locks are taken or released by this function.
238 */
239static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName)
240{
241 Assert(!(fFlags & RTTHREADFLAGS_WAITABLE));
242 fFlags &= ~RTTHREADFLAGS_WAITABLE;
243
244 /*
245 * Allocate and insert the thread.
246 * (It is vital that rtThreadNativeAdopt updates the TLS before
247 * we try inserting the thread because of locking.)
248 */
249 int rc = VERR_NO_MEMORY;
250 PRTTHREADINT pThread = rtThreadAlloc(enmType, fFlags, RTTHREADINT_FLAGS_ALIEN, pszName);
251 if (pThread)
252 {
253 RTNATIVETHREAD NativeThread = RTThreadNativeSelf();
254 rc = rtThreadNativeAdopt(pThread);
255 if (RT_SUCCESS(rc))
256 {
257 rtThreadInsert(pThread, NativeThread);
258 ASMAtomicWriteSize(&pThread->enmState, RTTHREADSTATE_RUNNING);
259 rtThreadRelease(pThread);
260 }
261 }
262 return rc;
263}
264
265
266/**
267 * Adopts a non-IPRT thread.
268 *
269 * @returns IPRT status code.
270 * @param enmType The thread type.
271 * @param fFlags The thread flags. RTTHREADFLAGS_WAITABLE is not currently allowed.
272 * @param pszName The thread name. Optional.
273 * @param pThread Where to store the thread handle. Optional.
274 */
275RTDECL(int) RTThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName, PRTTHREAD pThread)
276{
277 AssertReturn(!(fFlags & RTTHREADFLAGS_WAITABLE), VERR_INVALID_PARAMETER);
278 AssertReturn(!pszName || VALID_PTR(pszName), VERR_INVALID_POINTER);
279 AssertReturn(!pThread || VALID_PTR(pThread), VERR_INVALID_POINTER);
280
281 int rc = VINF_SUCCESS;
282 RTTHREAD Thread = RTThreadSelf();
283 if (Thread == NIL_RTTHREAD)
284 {
285 /* generate a name if none was given. */
286 char szName[RTTHREAD_NAME_LEN];
287 if (!pszName || !*pszName)
288 {
289 static uint32_t s_i32AlienId = 0;
290 uint32_t i32Id = ASMAtomicIncU32(&s_i32AlienId);
291 RTStrPrintf(szName, sizeof(szName), "ALIEN-%RX32", i32Id);
292 pszName = szName;
293 }
294
295 /* try adopt it */
296 rc = rtThreadAdopt(enmType, fFlags, pszName);
297 Thread = RTThreadSelf();
298 Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x rc=%Rrc\n",
299 Thread, RTThreadNativeSelf(), pszName, enmType, fFlags, rc));
300 }
301 else
302 Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x - already adopted!\n",
303 Thread, RTThreadNativeSelf(), pszName, enmType, fFlags));
304
305 if (pThread)
306 *pThread = Thread;
307 return rc;
308}
309
310
311/**
312 * Allocates a per thread data structure and initializes the basic fields.
313 *
314 * @returns Pointer to per thread data structure.
315 * This is reference once.
316 * @returns NULL on failure.
317 * @param enmType The thread type.
318 * @param fFlags The thread flags.
319 * @param fIntFlags The internal thread flags.
320 * @param pszName Pointer to the thread name.
321 */
322PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, unsigned fIntFlags, const char *pszName)
323{
324 PRTTHREADINT pThread = (PRTTHREADINT)RTMemAllocZ(sizeof(RTTHREADINT));
325 if (pThread)
326 {
327 pThread->Core.Key = (void*)NIL_RTTHREAD;
328 pThread->u32Magic = RTTHREADINT_MAGIC;
329 size_t cchName = strlen(pszName);
330 if (cchName >= RTTHREAD_NAME_LEN)
331 cchName = RTTHREAD_NAME_LEN - 1;
332 memcpy(pThread->szName, pszName, cchName);
333 pThread->szName[cchName] = '\0';
334 pThread->cRefs = 2 + !!(fFlags & RTTHREADFLAGS_WAITABLE); /* And extra reference if waitable. */
335 pThread->rc = VERR_PROCESS_RUNNING; /** @todo get a better error code! */
336 pThread->enmType = enmType;
337 pThread->fFlags = fFlags;
338 pThread->fIntFlags = fIntFlags;
339 pThread->enmState = RTTHREADSTATE_INITIALIZING;
340 int rc = RTSemEventMultiCreate(&pThread->EventUser);
341 if (RT_SUCCESS(rc))
342 {
343 rc = RTSemEventMultiCreate(&pThread->EventTerminated);
344 if (RT_SUCCESS(rc))
345 return pThread;
346 RTSemEventMultiDestroy(pThread->EventUser);
347 }
348 RTMemFree(pThread);
349 }
350 return NULL;
351}
352
353
354/**
355 * Insert the per thread data structure into the tree.
356 *
357 * This can be called from both the thread it self and the parent,
358 * thus it must handle insertion failures in a nice manner.
359 *
360 * @param pThread Pointer to thread structure allocated by rtThreadAlloc().
361 * @param NativeThread The native thread id.
362 */
363void rtThreadInsert(PRTTHREADINT pThread, RTNATIVETHREAD NativeThread)
364{
365 Assert(pThread);
366 Assert(pThread->u32Magic == RTTHREADINT_MAGIC);
367
368 RT_THREAD_LOCK_TMP(Tmp);
369 RT_THREAD_LOCK_RW(Tmp);
370
371 /*
372 * Do not insert a terminated thread.
373 *
374 * This may happen if the thread finishes before the RTThreadCreate call
375 * gets this far. Since the OS may quickly reuse the native thread ID
376 * it should not be reinserted at this point.
377 */
378 if (pThread->enmState != RTTHREADSTATE_TERMINATED)
379 {
380 /*
381 * Before inserting we must check if there is a thread with this id
382 * in the tree already. We're racing parent and child on insert here
383 * so that the handle is valid in both ends when they return / start.
384 *
385 * If it's not ourself we find, it's a dead alien thread and we will
386 * unlink it from the tree. Alien threads will be released at this point.
387 */
388 PRTTHREADINT pThreadOther = (PRTTHREADINT)RTAvlPVGet(&g_ThreadTree, (void *)NativeThread);
389 if (pThreadOther != pThread)
390 {
391 /* remove dead alien if any */
392 if (pThreadOther)
393 {
394 AssertMsg(pThreadOther->fIntFlags & RTTHREADINT_FLAGS_ALIEN, ("%p:%s; %p:%s\n", pThread, pThread->szName, pThreadOther, pThreadOther->szName));
395 ASMAtomicBitClear(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT);
396 rtThreadRemoveLocked(pThreadOther);
397 if (pThreadOther->fIntFlags & RTTHREADINT_FLAGS_ALIEN)
398 rtThreadRelease(pThreadOther);
399 }
400
401 /* insert the thread */
402 ASMAtomicWritePtr(&pThread->Core.Key, (void *)NativeThread);
403 bool fRc = RTAvlPVInsert(&g_ThreadTree, &pThread->Core);
404 ASMAtomicOrU32(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE);
405
406 AssertReleaseMsg(fRc, ("Lock problem? %p (%RTnthrd) %s\n", pThread, NativeThread, pThread->szName));
407 NOREF(fRc);
408 }
409 }
410
411 RT_THREAD_UNLOCK_RW(Tmp);
412}
413
414
415/**
416 * Removes the thread from the AVL tree, call owns the tree lock
417 * and has cleared the RTTHREADINT_FLAG_IN_TREE bit.
418 *
419 * @param pThread The thread to remove.
420 */
421static void rtThreadRemoveLocked(PRTTHREADINT pThread)
422{
423 PRTTHREADINT pThread2 = (PRTTHREADINT)RTAvlPVRemove(&g_ThreadTree, pThread->Core.Key);
424 AssertMsg(pThread2 == pThread, ("%p(%s) != %p (%p/%s)\n", pThread2, pThread2 ? pThread2->szName : "<null>",
425 pThread, pThread->Core.Key, pThread->szName));
426 NOREF(pThread2);
427}
428
429
430/**
431 * Removes the thread from the AVL tree.
432 *
433 * @param pThread The thread to remove.
434 */
435static void rtThreadRemove(PRTTHREADINT pThread)
436{
437 RT_THREAD_LOCK_TMP(Tmp);
438 RT_THREAD_LOCK_RW(Tmp);
439 if (ASMAtomicBitTestAndClear(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT))
440 rtThreadRemoveLocked(pThread);
441 RT_THREAD_UNLOCK_RW(Tmp);
442}
443
444
445/**
446 * Checks if a thread is alive or not.
447 *
448 * @returns true if the thread is alive (or we don't really know).
449 * @returns false if the thread has surely terminate.
450 */
451DECLINLINE(bool) rtThreadIsAlive(PRTTHREADINT pThread)
452{
453 return !(pThread->fIntFlags & RTTHREADINT_FLAGS_TERMINATED);
454}
455
456
457/**
458 * Gets a thread by it's native ID.
459 *
460 * @returns pointer to the thread structure.
461 * @returns NULL if not a thread IPRT knows.
462 * @param NativeThread The native thread id.
463 */
464PRTTHREADINT rtThreadGetByNative(RTNATIVETHREAD NativeThread)
465{
466 /*
467 * Simple tree lookup.
468 */
469 RT_THREAD_LOCK_TMP(Tmp);
470 RT_THREAD_LOCK_RD(Tmp);
471 PRTTHREADINT pThread = (PRTTHREADINT)RTAvlPVGet(&g_ThreadTree, (void *)NativeThread);
472 RT_THREAD_UNLOCK_RD(Tmp);
473 return pThread;
474}
475
476
477/**
478 * Gets the per thread data structure for a thread handle.
479 *
480 * @returns Pointer to the per thread data structure for Thread.
481 * The caller must release the thread using rtThreadRelease().
482 * @returns NULL if Thread was not found.
483 * @param Thread Thread id which structure is to be returned.
484 */
485PRTTHREADINT rtThreadGet(RTTHREAD Thread)
486{
487 if ( Thread != NIL_RTTHREAD
488 && VALID_PTR(Thread))
489 {
490 PRTTHREADINT pThread = (PRTTHREADINT)Thread;
491 if ( pThread->u32Magic == RTTHREADINT_MAGIC
492 && pThread->cRefs > 0)
493 {
494 ASMAtomicIncU32(&pThread->cRefs);
495 return pThread;
496 }
497 }
498
499 AssertMsgFailed(("Thread=%RTthrd\n", Thread));
500 return NULL;
501}
502
503
504/**
505 * Release a per thread data structure.
506 *
507 * @returns New reference count.
508 * @param pThread The thread structure to release.
509 */
510uint32_t rtThreadRelease(PRTTHREADINT pThread)
511{
512 Assert(pThread);
513 uint32_t cRefs;
514 if (pThread->cRefs >= 1)
515 {
516 cRefs = ASMAtomicDecU32(&pThread->cRefs);
517 if (!cRefs)
518 rtThreadDestroy(pThread);
519 }
520 else
521 cRefs = 0;
522 return cRefs;
523}
524
525
526/**
527 * Destroys the per thread data.
528 *
529 * @param pThread The thread to destroy.
530 */
531static void rtThreadDestroy(PRTTHREADINT pThread)
532{
533 /*
534 * Remove it from the tree and mark it as dead.
535 *
536 * Threads that has seen rtThreadTerminate and should already have been
537 * removed from the tree. There is probably no thread that should
538 * require removing here. However, be careful making sure that cRefs
539 * isn't 0 if we do or we'll blow up because the strict locking code
540 * will be calling us back.
541 */
542 if (ASMBitTest(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT))
543 {
544 ASMAtomicIncU32(&pThread->cRefs);
545 rtThreadRemove(pThread);
546 ASMAtomicDecU32(&pThread->cRefs);
547 }
548 ASMAtomicXchgU32(&pThread->u32Magic, RTTHREADINT_MAGIC_DEAD);
549
550 /*
551 * Free resources.
552 */
553 ASMAtomicWritePtr(&pThread->Core.Key, (void *)NIL_RTTHREAD);
554 pThread->enmType = RTTHREADTYPE_INVALID;
555 RTSemEventMultiDestroy(pThread->EventUser);
556 pThread->EventUser = NIL_RTSEMEVENTMULTI;
557 if (pThread->EventTerminated != NIL_RTSEMEVENTMULTI)
558 {
559 RTSemEventMultiDestroy(pThread->EventTerminated);
560 pThread->EventTerminated = NIL_RTSEMEVENTMULTI;
561 }
562 RTMemFree(pThread);
563}
564
565
566/**
567 * Terminates the thread.
568 * Called by the thread wrapper function when the thread terminates.
569 *
570 * @param pThread The thread structure.
571 * @param rc The thread result code.
572 */
573void rtThreadTerminate(PRTTHREADINT pThread, int rc)
574{
575 Assert(pThread->cRefs >= 1);
576
577#ifdef IPRT_WITH_GENERIC_TLS
578 /*
579 * Destroy TLS entries.
580 */
581 rtThreadTlsDestruction(pThread);
582#endif /* IPRT_WITH_GENERIC_TLS */
583
584 /*
585 * Set the rc, mark it terminated and signal anyone waiting.
586 */
587 pThread->rc = rc;
588 ASMAtomicWriteSize(&pThread->enmState, RTTHREADSTATE_TERMINATED);
589 ASMAtomicOrU32(&pThread->fIntFlags, RTTHREADINT_FLAGS_TERMINATED);
590 if (pThread->EventTerminated != NIL_RTSEMEVENTMULTI)
591 RTSemEventMultiSignal(pThread->EventTerminated);
592
593 /*
594 * Remove the thread from the tree so that there will be no
595 * key clashes in the AVL tree and release our reference to ourself.
596 */
597 rtThreadRemove(pThread);
598 rtThreadRelease(pThread);
599}
600
601
602/**
603 * The common thread main function.
604 * This is called by rtThreadNativeMain().
605 *
606 * @returns The status code of the thread.
607 * pThread is dereference by the thread before returning!
608 * @param pThread The thread structure.
609 * @param NativeThread The native thread id.
610 * @param pszThreadName The name of the thread (purely a dummy for backtrace).
611 */
612int rtThreadMain(PRTTHREADINT pThread, RTNATIVETHREAD NativeThread, const char *pszThreadName)
613{
614 NOREF(pszThreadName);
615 rtThreadInsert(pThread, NativeThread);
616 Log(("rtThreadMain: Starting: pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
617 pThread, NativeThread, pThread->szName, pThread->pfnThread, pThread->pvUser));
618
619 /*
620 * Change the priority.
621 */
622 int rc = rtThreadNativeSetPriority(pThread, pThread->enmType);
623#ifdef IN_RING3
624 AssertMsgRC(rc, ("Failed to set priority of thread %p (%RTnthrd / %s) to enmType=%d enmPriority=%d rc=%Vrc\n",
625 pThread, NativeThread, pThread->szName, pThread->enmType, g_enmProcessPriority, rc));
626#else
627 AssertMsgRC(rc, ("Failed to set priority of thread %p (%RTnthrd / %s) to enmType=%d rc=%Vrc\n",
628 pThread, NativeThread, pThread->szName, pThread->enmType, rc));
629#endif
630
631 /*
632 * Call thread function and terminate when it returns.
633 */
634 ASMAtomicWriteSize(&pThread->enmState, RTTHREADSTATE_RUNNING);
635 rc = pThread->pfnThread(pThread, pThread->pvUser);
636
637 Log(("rtThreadMain: Terminating: rc=%d pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
638 rc, pThread, NativeThread, pThread->szName, pThread->pfnThread, pThread->pvUser));
639 rtThreadTerminate(pThread, rc);
640 return rc;
641}
642
643
644/**
645 * Create a new thread.
646 *
647 * @returns iprt status code.
648 * @param pThread Where to store the thread handle to the new thread. (optional)
649 * @param pfnThread The thread function.
650 * @param pvUser User argument.
651 * @param cbStack The size of the stack for the new thread.
652 * Use 0 for the default stack size.
653 * @param enmType The thread type. Used for deciding scheduling attributes
654 * of the thread.
655 * @param fFlags Flags of the RTTHREADFLAGS type (ORed together).
656 * @param pszName Thread name.
657 */
658RTDECL(int) RTThreadCreate(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
659 RTTHREADTYPE enmType, unsigned fFlags, const char *pszName)
660{
661 LogFlow(("RTThreadCreate: pThread=%p pfnThread=%p pvUser=%p cbStack=%#x enmType=%d fFlags=%#x pszName=%p:{%s}\n",
662 pThread, pfnThread, pvUser, cbStack, enmType, fFlags, pszName, pszName));
663
664 /*
665 * Validate input.
666 */
667 if (!VALID_PTR(pThread) && pThread)
668 {
669 Assert(VALID_PTR(pThread));
670 return VERR_INVALID_PARAMETER;
671 }
672 if (!VALID_PTR(pfnThread))
673 {
674 Assert(VALID_PTR(pfnThread));
675 return VERR_INVALID_PARAMETER;
676 }
677 if (!pszName || !*pszName || strlen(pszName) >= RTTHREAD_NAME_LEN)
678 {
679 AssertMsgFailed(("pszName=%s (max len is %d because of logging)\n", pszName, RTTHREAD_NAME_LEN - 1));
680 return VERR_INVALID_PARAMETER;
681 }
682 if (fFlags & ~RTTHREADFLAGS_MASK)
683 {
684 AssertMsgFailed(("fFlags=%#x\n", fFlags));
685 return VERR_INVALID_PARAMETER;
686 }
687
688 /*
689 * Allocate thread argument.
690 */
691 int rc;
692 PRTTHREADINT pThreadInt = rtThreadAlloc(enmType, fFlags, 0, pszName);
693 if (pThreadInt)
694 {
695 pThreadInt->pfnThread = pfnThread;
696 pThreadInt->pvUser = pvUser;
697 pThreadInt->cbStack = cbStack;
698
699 RTNATIVETHREAD NativeThread;
700 rc = rtThreadNativeCreate(pThreadInt, &NativeThread);
701 if (RT_SUCCESS(rc))
702 {
703 rtThreadInsert(pThreadInt, NativeThread);
704 rtThreadRelease(pThreadInt);
705 Log(("RTThreadCreate: Created thread %p (%p) %s\n", pThreadInt, NativeThread, pszName));
706 if (pThread)
707 *pThread = pThreadInt;
708 return VINF_SUCCESS;
709 }
710
711 pThreadInt->cRefs = 1;
712 rtThreadRelease(pThreadInt);
713 }
714 else
715 rc = VERR_NO_TMP_MEMORY;
716 LogFlow(("RTThreadCreate: Failed to create thread, rc=%Vrc\n", rc));
717 AssertReleaseRC(rc);
718 return rc;
719}
720
721
722/**
723 * Gets the native thread id of a IPRT thread.
724 *
725 * @returns The native thread id.
726 * @param Thread The IPRT thread.
727 */
728RTDECL(RTNATIVETHREAD) RTThreadGetNative(RTTHREAD Thread)
729{
730 PRTTHREADINT pThread = rtThreadGet(Thread);
731 if (pThread)
732 {
733 RTNATIVETHREAD NativeThread = (RTNATIVETHREAD)pThread->Core.Key;
734 rtThreadRelease(pThread);
735 return NativeThread;
736 }
737 return NIL_RTNATIVETHREAD;
738}
739
740
741/**
742 * Gets the IPRT thread of a native thread.
743 *
744 * @returns The IPRT thread handle
745 * @returns NIL_RTTHREAD if not a thread known to IPRT.
746 * @param NativeThread The native thread handle/id.
747 */
748RTDECL(RTTHREAD) RTThreadFromNative(RTNATIVETHREAD NativeThread)
749{
750 PRTTHREADINT pThread = rtThreadGetByNative(NativeThread);
751 if (pThread)
752 return pThread;
753 return NIL_RTTHREAD;
754}
755
756
757/**
758 * Gets the name of the current thread thread.
759 *
760 * @returns Pointer to readonly name string.
761 * @returns NULL on failure.
762 */
763RTDECL(const char *) RTThreadSelfName(void)
764{
765 RTTHREAD Thread = RTThreadSelf();
766 if (Thread != NIL_RTTHREAD)
767 {
768 PRTTHREADINT pThread = rtThreadGet(Thread);
769 if (pThread)
770 {
771 const char *szName = pThread->szName;
772 rtThreadRelease(pThread);
773 return szName;
774 }
775 }
776 return NULL;
777}
778
779
780/**
781 * Gets the name of a thread.
782 *
783 * @returns Pointer to readonly name string.
784 * @returns NULL on failure.
785 * @param Thread Thread handle of the thread to query the name of.
786 */
787RTDECL(const char *) RTThreadGetName(RTTHREAD Thread)
788{
789 if (Thread == NIL_RTTHREAD)
790 return NULL;
791 PRTTHREADINT pThread = rtThreadGet(Thread);
792 if (pThread)
793 {
794 const char *szName = pThread->szName;
795 rtThreadRelease(pThread);
796 return szName;
797 }
798 return NULL;
799}
800
801
802/**
803 * Sets the name of a thread.
804 *
805 * @returns iprt status code.
806 * @param Thread Thread handle of the thread to query the name of.
807 * @param pszName The thread name.
808 */
809RTDECL(int) RTThreadSetName(RTTHREAD Thread, const char *pszName)
810{
811 /*
812 * Validate input.
813 */
814 size_t cchName = strlen(pszName);
815 if (cchName >= RTTHREAD_NAME_LEN)
816 {
817 AssertMsgFailed(("pszName=%s is too long, max is %d\n", pszName, RTTHREAD_NAME_LEN - 1));
818 return VERR_INVALID_PARAMETER;
819 }
820 PRTTHREADINT pThread = rtThreadGet(Thread);
821 if (!pThread)
822 return VERR_INVALID_HANDLE;
823
824 /*
825 * Update the name.
826 */
827 pThread->szName[cchName] = '\0'; /* paranoia */
828 memcpy(pThread->szName, pszName, cchName);
829 rtThreadRelease(pThread);
830 return VINF_SUCCESS;
831}
832
833
834/**
835 * Signal the user event.
836 *
837 * @returns iprt status code.
838 */
839RTDECL(int) RTThreadUserSignal(RTTHREAD Thread)
840{
841 int rc;
842 PRTTHREADINT pThread = rtThreadGet(Thread);
843 if (pThread)
844 {
845 rc = RTSemEventMultiSignal(pThread->EventUser);
846 rtThreadRelease(pThread);
847 }
848 else
849 rc = VERR_INVALID_HANDLE;
850 return rc;
851}
852
853
854/**
855 * Wait for the user event, resume on interruption.
856 *
857 * @returns iprt status code.
858 * @param Thread The thread to wait for.
859 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
860 * an indefinite wait.
861 */
862RTDECL(int) RTThreadUserWait(RTTHREAD Thread, unsigned cMillies)
863{
864 int rc;
865 PRTTHREADINT pThread = rtThreadGet(Thread);
866 if (pThread)
867 {
868 rc = RTSemEventMultiWait(pThread->EventUser, cMillies);
869 rtThreadRelease(pThread);
870 }
871 else
872 rc = VERR_INVALID_HANDLE;
873 return rc;
874}
875
876
877/**
878 * Wait for the user event, return on interruption.
879 *
880 * @returns iprt status code.
881 * @param Thread The thread to wait for.
882 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
883 * an indefinite wait.
884 */
885RTDECL(int) RTThreadUserWaitNoResume(RTTHREAD Thread, unsigned cMillies)
886{
887 int rc;
888 PRTTHREADINT pThread = rtThreadGet(Thread);
889 if (pThread)
890 {
891 rc = RTSemEventMultiWaitNoResume(pThread->EventUser, cMillies);
892 rtThreadRelease(pThread);
893 }
894 else
895 rc = VERR_INVALID_HANDLE;
896 return rc;
897}
898
899
900/**
901 * Reset the user event.
902 *
903 * @returns iprt status code.
904 * @param Thread The thread to reset.
905 */
906RTDECL(int) RTThreadUserReset(RTTHREAD Thread)
907{
908 int rc;
909 PRTTHREADINT pThread = rtThreadGet(Thread);
910 if (pThread)
911 {
912 rc = RTSemEventMultiReset(pThread->EventUser);
913 rtThreadRelease(pThread);
914 }
915 else
916 rc = VERR_INVALID_HANDLE;
917 return rc;
918}
919
920
921/**
922 * Wait for the thread to terminate.
923 *
924 * @returns iprt status code.
925 * @param Thread The thread to wait for.
926 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
927 * an indefinite wait.
928 * @param prc Where to store the return code of the thread. Optional.
929 * @param fAutoResume Whether or not to resume the wait on VERR_INTERRUPTED.
930 */
931static int rtThreadWait(RTTHREAD Thread, unsigned cMillies, int *prc, bool fAutoResume)
932{
933 int rc = VERR_INVALID_HANDLE;
934 if (Thread != NIL_RTTHREAD)
935 {
936 PRTTHREADINT pThread = rtThreadGet(Thread);
937 if (pThread)
938 {
939 if (pThread->fFlags & RTTHREADFLAGS_WAITABLE)
940 {
941 if (fAutoResume)
942 rc = RTSemEventMultiWait(pThread->EventTerminated, cMillies);
943 else
944 rc = RTSemEventMultiWaitNoResume(pThread->EventTerminated, cMillies);
945 if (RT_SUCCESS(rc))
946 {
947 if (prc)
948 *prc = pThread->rc;
949
950 /*
951 * If the thread is marked as waitable, we'll do one additional
952 * release in order to free up the thread structure (see how we
953 * init cRef in rtThreadAlloc()).
954 */
955 if (ASMAtomicBitTestAndClear(&pThread->fFlags, RTTHREADFLAGS_WAITABLE_BIT))
956 rtThreadRelease(pThread);
957 }
958 }
959 else
960 {
961 rc = VERR_THREAD_NOT_WAITABLE;
962 AssertRC(rc);
963 }
964 rtThreadRelease(pThread);
965 }
966 }
967 return rc;
968}
969
970
971/**
972 * Wait for the thread to terminate, resume on interruption.
973 *
974 * @returns iprt status code.
975 * Will not return VERR_INTERRUPTED.
976 * @param Thread The thread to wait for.
977 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
978 * an indefinite wait.
979 * @param prc Where to store the return code of the thread. Optional.
980 */
981RTDECL(int) RTThreadWait(RTTHREAD Thread, unsigned cMillies, int *prc)
982{
983 int rc = rtThreadWait(Thread, cMillies, prc, true);
984 Assert(rc != VERR_INTERRUPTED);
985 return rc;
986}
987
988
989/**
990 * Wait for the thread to terminate, return on interruption.
991 *
992 * @returns iprt status code.
993 * @param Thread The thread to wait for.
994 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
995 * an indefinite wait.
996 * @param prc Where to store the return code of the thread. Optional.
997 */
998RTDECL(int) RTThreadWaitNoResume(RTTHREAD Thread, unsigned cMillies, int *prc)
999{
1000 return rtThreadWait(Thread, cMillies, prc, false);
1001}
1002
1003
1004/**
1005 * Changes the type of the specified thread.
1006 *
1007 * @returns iprt status code.
1008 * @param Thread The thread which type should be changed.
1009 * @param enmType The new thread type.
1010 */
1011RTDECL(int) RTThreadSetType(RTTHREAD Thread, RTTHREADTYPE enmType)
1012{
1013 /*
1014 * Validate input.
1015 */
1016 int rc;
1017 if ( enmType > RTTHREADTYPE_INVALID
1018 && enmType < RTTHREADTYPE_END)
1019 {
1020 PRTTHREADINT pThread = rtThreadGet(Thread);
1021 if (pThread)
1022 {
1023 if (rtThreadIsAlive(pThread))
1024 {
1025 /*
1026 * Do the job.
1027 */
1028 RT_THREAD_LOCK_TMP(Tmp);
1029 RT_THREAD_LOCK_RW(Tmp);
1030 rc = rtThreadNativeSetPriority(pThread, enmType);
1031 if (RT_SUCCESS(rc))
1032 ASMAtomicXchgSize(&pThread->enmType, enmType);
1033 RT_THREAD_UNLOCK_RW(Tmp);
1034 if (RT_FAILURE(rc))
1035 Log(("RTThreadSetType: failed on thread %p (%s), rc=%Vrc!!!\n", Thread, pThread->szName, rc));
1036 }
1037 else
1038 rc = VERR_THREAD_IS_DEAD;
1039 rtThreadRelease(pThread);
1040 }
1041 else
1042 rc = VERR_INVALID_HANDLE;
1043 }
1044 else
1045 {
1046 AssertMsgFailed(("enmType=%d\n", enmType));
1047 rc = VERR_INVALID_PARAMETER;
1048 }
1049 return rc;
1050}
1051
1052
1053/**
1054 * Gets the type of the specified thread.
1055 *
1056 * @returns The thread type.
1057 * @returns RTTHREADTYPE_INVALID if the thread handle is invalid.
1058 * @param Thread The thread in question.
1059 */
1060RTDECL(RTTHREADTYPE) RTThreadGetType(RTTHREAD Thread)
1061{
1062 RTTHREADTYPE enmType = RTTHREADTYPE_INVALID;
1063 PRTTHREADINT pThread = rtThreadGet(Thread);
1064 if (pThread)
1065 {
1066 enmType = pThread->enmType;
1067 rtThreadRelease(pThread);
1068 }
1069 return enmType;
1070}
1071
1072
1073#ifdef IN_RING3
1074
1075/**
1076 * Gets the number of write locks and critical sections the specified
1077 * thread owns.
1078 *
1079 * This number does not include any nested lock/critect entries.
1080 *
1081 * Note that it probably will return 0 for non-strict builds since
1082 * release builds doesn't do unnecessary diagnostic counting like this.
1083 *
1084 * @returns Number of locks on success (0+) and VERR_INVALID_HANDLER on failure
1085 * @param Thread The thread we're inquiring about.
1086 */
1087RTDECL(int32_t) RTThreadGetWriteLockCount(RTTHREAD Thread)
1088{
1089 if (Thread == NIL_RTTHREAD)
1090 return 0;
1091
1092 PRTTHREADINT pThread = rtThreadGet(Thread);
1093 if (!pThread)
1094 return VERR_INVALID_HANDLE;
1095 int32_t cWriteLocks = ASMAtomicReadS32(&pThread->cWriteLocks);
1096 rtThreadRelease(pThread);
1097 return cWriteLocks;
1098}
1099
1100
1101/**
1102 * Works the THREADINT::cWriteLocks member, mostly internal.
1103 *
1104 * @param Thread The current thread.
1105 */
1106RTDECL(void) RTThreadWriteLockInc(RTTHREAD Thread)
1107{
1108 PRTTHREADINT pThread = rtThreadGet(Thread);
1109 Assert(pThread);
1110 ASMAtomicIncS32(&pThread->cWriteLocks);
1111 rtThreadRelease(pThread);
1112}
1113
1114
1115/**
1116 * Works the THREADINT::cWriteLocks member, mostly internal.
1117 *
1118 * @param Thread The current thread.
1119 */
1120RTDECL(void) RTThreadWriteLockDec(RTTHREAD Thread)
1121{
1122 PRTTHREADINT pThread = rtThreadGet(Thread);
1123 Assert(pThread);
1124 ASMAtomicDecS32(&pThread->cWriteLocks);
1125 rtThreadRelease(pThread);
1126}
1127
1128
1129/**
1130 * Gets the number of read locks the specified thread owns.
1131 *
1132 * Note that nesting read lock entry will be included in the
1133 * total sum. And that it probably will return 0 for non-strict
1134 * builds since release builds doesn't do unnecessary diagnostic
1135 * counting like this.
1136 *
1137 * @returns Number of read locks on success (0+) and VERR_INVALID_HANDLER on failure
1138 * @param Thread The thread we're inquiring about.
1139 */
1140RTDECL(int32_t) RTThreadGetReadLockCount(RTTHREAD Thread)
1141{
1142 if (Thread == NIL_RTTHREAD)
1143 return 0;
1144
1145 PRTTHREADINT pThread = rtThreadGet(Thread);
1146 if (!pThread)
1147 return VERR_INVALID_HANDLE;
1148 int32_t cReadLocks = ASMAtomicReadS32(&pThread->cReadLocks);
1149 rtThreadRelease(pThread);
1150 return cReadLocks;
1151}
1152
1153
1154/**
1155 * Works the THREADINT::cReadLocks member.
1156 *
1157 * @param Thread The current thread.
1158 */
1159RTDECL(void) RTThreadReadLockInc(RTTHREAD Thread)
1160{
1161 PRTTHREADINT pThread = rtThreadGet(Thread);
1162 Assert(pThread);
1163 ASMAtomicIncS32(&pThread->cReadLocks);
1164 rtThreadRelease(pThread);
1165}
1166
1167
1168/**
1169 * Works the THREADINT::cReadLocks member.
1170 *
1171 * @param Thread The current thread.
1172 */
1173RTDECL(void) RTThreadReadLockDec(RTTHREAD Thread)
1174{
1175 PRTTHREADINT pThread = rtThreadGet(Thread);
1176 Assert(pThread);
1177 ASMAtomicDecS32(&pThread->cReadLocks);
1178 rtThreadRelease(pThread);
1179}
1180
1181
1182
1183
1184
1185/**
1186 * Recalculates scheduling attributes for the the default process
1187 * priority using the specified priority type for the calling thread.
1188 *
1189 * The scheduling attributes are targeted at threads and they are protected
1190 * by the thread read-write semaphore, that's why RTProc is forwarding the
1191 * operation to RTThread.
1192 *
1193 * @returns iprt status code.
1194 * @remarks Will only work for strict builds.
1195 */
1196int rtThreadDoCalcDefaultPriority(RTTHREADTYPE enmType)
1197{
1198 RT_THREAD_LOCK_TMP(Tmp);
1199 RT_THREAD_LOCK_RW(Tmp);
1200 int rc = rtSchedNativeCalcDefaultPriority(enmType);
1201 RT_THREAD_UNLOCK_RW(Tmp);
1202 return rc;
1203}
1204
1205
1206/**
1207 * Thread enumerator - sets the priority of one thread.
1208 *
1209 * @returns 0 to continue.
1210 * @returns !0 to stop. In our case a VERR_ code.
1211 * @param pNode The thread node.
1212 * @param pvUser The new priority.
1213 */
1214static DECLCALLBACK(int) rtThreadSetPriorityOne(PAVLPVNODECORE pNode, void *pvUser)
1215{
1216 PRTTHREADINT pThread = (PRTTHREADINT)pNode;
1217 if (!rtThreadIsAlive(pThread))
1218 return VINF_SUCCESS;
1219 int rc = rtThreadNativeSetPriority(pThread, pThread->enmType);
1220 if (RT_SUCCESS(rc)) /* hide any warnings */
1221 return VINF_SUCCESS;
1222 return rc;
1223}
1224
1225
1226/**
1227 * Attempts to alter the priority of the current process.
1228 *
1229 * The scheduling attributes are targeted at threads and they are protected
1230 * by the thread read-write semaphore, that's why RTProc is forwarding the
1231 * operation to RTThread. This operation also involves updating all thread
1232 * which is much faster done from RTThread.
1233 *
1234 * @returns iprt status code.
1235 * @param enmPriority The new priority.
1236 */
1237int rtThreadDoSetProcPriority(RTPROCPRIORITY enmPriority)
1238{
1239 LogFlow(("rtThreadDoSetProcPriority: enmPriority=%d\n", enmPriority));
1240
1241 /*
1242 * First validate that we're allowed by the OS to use all the
1243 * scheduling attributes defined by the specified process priority.
1244 */
1245 RT_THREAD_LOCK_TMP(Tmp);
1246 RT_THREAD_LOCK_RW(Tmp);
1247 int rc = rtProcNativeSetPriority(enmPriority);
1248 if (RT_SUCCESS(rc))
1249 {
1250 /*
1251 * Update the priority of existing thread.
1252 */
1253 rc = RTAvlPVDoWithAll(&g_ThreadTree, true, rtThreadSetPriorityOne, NULL);
1254 if (RT_SUCCESS(rc))
1255 ASMAtomicXchgSize(&g_enmProcessPriority, enmPriority);
1256 else
1257 {
1258 /*
1259 * Failed, restore the priority.
1260 */
1261 rtProcNativeSetPriority(g_enmProcessPriority);
1262 RTAvlPVDoWithAll(&g_ThreadTree, true, rtThreadSetPriorityOne, NULL);
1263 }
1264 }
1265 RT_THREAD_UNLOCK_RW(Tmp);
1266 LogFlow(("rtThreadDoSetProcPriority: returns %Vrc\n", rc));
1267 return rc;
1268}
1269
1270
1271/**
1272 * Bitch about a deadlock.
1273 *
1274 * @param pThread This thread.
1275 * @param pCur The thread we're deadlocking with.
1276 * @param enmState The sleep state.
1277 * @param u64Block The block data. A pointer or handle.
1278 * @param pszFile Where we are gonna block.
1279 * @param uLine Where we are gonna block.
1280 * @param uId Where we are gonna block.
1281 */
1282static void rtThreadDeadlock(PRTTHREADINT pThread, PRTTHREADINT pCur, RTTHREADSTATE enmState, uint64_t u64Block,
1283 const char *pszFile, unsigned uLine, RTUINTPTR uId)
1284{
1285 AssertMsg1(pCur == pThread ? "!!Deadlock detected!!" : "!!Deadlock exists!!", uLine, pszFile, "");
1286
1287 /*
1288 * Print the threads and locks involved.
1289 */
1290 PRTTHREADINT apSeenThreads[8] = {0,0,0,0,0,0,0,0};
1291 unsigned iSeenThread = 0;
1292 pCur = pThread;
1293 for (unsigned iEntry = 0; pCur && iEntry < 256; iEntry++)
1294 {
1295 /*
1296 * Print info on pCur. Determin next while doing so.
1297 */
1298 AssertMsg2(" #%d: %RTthrd/%RTnthrd %s: %s(%u) %RTptr\n",
1299 iEntry, pCur, pCur->Core.Key, pCur->szName,
1300 pCur->pszBlockFile, pCur->uBlockLine, pCur->uBlockId);
1301 PRTTHREADINT pNext = NULL;
1302 switch (pCur->enmState)
1303 {
1304 case RTTHREADSTATE_CRITSECT:
1305 {
1306 PRTCRITSECT pCritSect = pCur->Block.pCritSect;
1307 if (pCur->enmState != RTTHREADSTATE_CRITSECT)
1308 {
1309 AssertMsg2("Impossible!!!\n");
1310 break;
1311 }
1312 if (VALID_PTR(pCritSect) && RTCritSectIsInitialized(pCritSect))
1313 {
1314 AssertMsg2(" Waiting on CRITSECT %p: Entered %s(%u) %RTptr\n",
1315 pCritSect, pCritSect->Strict.pszEnterFile,
1316 pCritSect->Strict.u32EnterLine, pCritSect->Strict.uEnterId);
1317 pNext = pCritSect->Strict.ThreadOwner;
1318 }
1319 else
1320 AssertMsg2(" Waiting on CRITSECT %p: invalid pointer or uninitialized critsect\n", pCritSect);
1321 break;
1322 }
1323
1324 default:
1325 AssertMsg2(" Impossible!!! enmState=%d\n", pCur->enmState);
1326 break;
1327 }
1328
1329 /*
1330 * Check for cycle.
1331 */
1332 if (iEntry && pCur == pThread)
1333 break;
1334 for (unsigned i = 0; i < ELEMENTS(apSeenThreads); i++)
1335 if (apSeenThreads[i] == pCur)
1336 {
1337 AssertMsg2(" Cycle!\n");
1338 pNext = NULL;
1339 break;
1340 }
1341
1342 /*
1343 * Advance to the next thread.
1344 */
1345 iSeenThread = (iSeenThread + 1) % ELEMENTS(apSeenThreads);
1346 apSeenThreads[iSeenThread] = pCur;
1347 pCur = pNext;
1348 }
1349 AssertBreakpoint();
1350}
1351
1352
1353/**
1354 * Change the thread state to blocking and do deadlock detection.
1355 *
1356 * This is a RT_STRICT method for debugging locks and detecting deadlocks.
1357 *
1358 * @param pThread This thread.
1359 * @param enmState The sleep state.
1360 * @param u64Block The block data. A pointer or handle.
1361 * @param pszFile Where we are blocking.
1362 * @param uLine Where we are blocking.
1363 * @param uId Where we are blocking.
1364 */
1365void rtThreadBlocking(PRTTHREADINT pThread, RTTHREADSTATE enmState, uint64_t u64Block,
1366 const char *pszFile, unsigned uLine, RTUINTPTR uId)
1367{
1368 Assert(RTTHREAD_IS_SLEEPING(enmState));
1369 if (pThread && pThread->enmState == RTTHREADSTATE_RUNNING)
1370 {
1371 /** @todo This has to be serialized! The deadlock detection isn't 100% safe!!! */
1372 pThread->Block.u64 = u64Block;
1373 pThread->pszBlockFile = pszFile;
1374 pThread->uBlockLine = uLine;
1375 pThread->uBlockId = uId;
1376 ASMAtomicWriteSize(&pThread->enmState, enmState);
1377
1378 /*
1379 * Do deadlock detection.
1380 *
1381 * Since we're missing proper serialization, we don't declare it a
1382 * deadlock until we've got three runs with the same list length.
1383 * While this isn't perfect, it should avoid out the most obvious
1384 * races on SMP boxes.
1385 */
1386 PRTTHREADINT pCur;
1387 unsigned cPrevLength = ~0U;
1388 unsigned cEqualRuns = 0;
1389 unsigned iParanoia = 256;
1390 do
1391 {
1392 unsigned cLength = 0;
1393 pCur = pThread;
1394 for (;;)
1395 {
1396 /*
1397 * Get the next thread.
1398 */
1399 for (;;)
1400 {
1401 switch (pCur->enmState)
1402 {
1403 case RTTHREADSTATE_CRITSECT:
1404 {
1405 PRTCRITSECT pCritSect = pCur->Block.pCritSect;
1406 if (pCur->enmState != RTTHREADSTATE_CRITSECT)
1407 continue;
1408 pCur = pCritSect->Strict.ThreadOwner;
1409 break;
1410 }
1411
1412 default:
1413 pCur = NULL;
1414 break;
1415 }
1416 break;
1417 }
1418 if (!pCur)
1419 return;
1420
1421 /*
1422 * If we've got back to the blocking thread id we've got a deadlock.
1423 * If we've got a chain of more than 256 items, there is some kind of cycle
1424 * in the list, which means that there is already a deadlock somewhere.
1425 */
1426 if (pCur == pThread || cLength >= 256)
1427 break;
1428 cLength++;
1429 }
1430
1431 /* compare with previous list run. */
1432 if (cLength != cPrevLength)
1433 {
1434 cPrevLength = cLength;
1435 cEqualRuns = 0;
1436 }
1437 else
1438 cEqualRuns++;
1439 } while (cEqualRuns < 3 && --iParanoia > 0);
1440
1441 /*
1442 * Ok, if we ever get here, it's most likely a genuine deadlock.
1443 */
1444 rtThreadDeadlock(pThread, pCur, enmState, u64Block, pszFile, uLine, uId);
1445 }
1446}
1447
1448
1449/**
1450 * Unblocks a thread.
1451 *
1452 * This function is paired with rtThreadBlocking.
1453 *
1454 * @param pThread The current thread.
1455 * @param enmCurState The current state, used to check for nested blocking.
1456 * The new state will be running.
1457 */
1458void rtThreadUnblocked(PRTTHREADINT pThread, RTTHREADSTATE enmCurState)
1459{
1460 if (pThread && pThread->enmState == enmCurState)
1461 ASMAtomicWriteSize(&pThread->enmState, RTTHREADSTATE_RUNNING);
1462}
1463
1464#endif /* IN_RING3 */
1465
1466
1467#ifdef IPRT_WITH_GENERIC_TLS
1468
1469/**
1470 * Thread enumerator - clears a TLS entry.
1471 *
1472 * @returns 0.
1473 * @param pNode The thread node.
1474 * @param pvUser The TLS index.
1475 */
1476static DECLCALLBACK(int) rtThreadClearTlsEntryCallback(PAVLPVNODECORE pNode, void *pvUser)
1477{
1478 PRTTHREADINT pThread = (PRTTHREADINT)pNode;
1479 RTTLS iTls = (RTTLS)(uintptr_t)pvUser;
1480 ASMAtomicWritePtr(&pThread->apvTlsEntries[iTls], NULL);
1481 return 0;
1482}
1483
1484
1485/**
1486 * Helper for the generic TLS implementation that clears a given TLS
1487 * entry on all threads.
1488 *
1489 * @param iTls The TLS entry. (valid)
1490 */
1491void rtThreadClearTlsEntry(RTTLS iTls)
1492{
1493 RT_THREAD_LOCK_TMP(Tmp);
1494 RT_THREAD_LOCK_RD(Tmp);
1495 RTAvlPVDoWithAll(&g_ThreadTree, true /* fFromLeft*/, rtThreadClearTlsEntryCallback, (void *)(uintptr_t)iTls);
1496 RT_THREAD_UNLOCK_RD(Tmp);
1497}
1498
1499#endif /* IPRT_WITH_GENERIC_TLS */
1500
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette