VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/thread-posix.cpp@ 34256

Last change on this file since 34256 was 34256, checked in by vboxsync, 15 years ago

IPRT: Must clear the TLS entry holding RTTHREAD before freeing the structure or the electric fence heap may cause a crash when blocking.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 11.4 KB
Line 
1/* $Id: thread-posix.cpp 34256 2010-11-22 15:55:00Z vboxsync $ */
2/** @file
3 * IPRT - Threads, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP RTLOGGROUP_THREAD
32#include <errno.h>
33#include <pthread.h>
34#include <signal.h>
35#if defined(RT_OS_LINUX)
36# include <unistd.h>
37# include <sys/syscall.h>
38#endif
39#if defined(RT_OS_SOLARIS)
40# include <sched.h>
41#endif
42
43#include <iprt/thread.h>
44#include <iprt/log.h>
45#include <iprt/assert.h>
46#include <iprt/asm.h>
47#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
48# include <iprt/asm-amd64-x86.h>
49#endif
50#include <iprt/err.h>
51#include <iprt/string.h>
52#include "internal/thread.h"
53
54
55/*******************************************************************************
56* Defined Constants And Macros *
57*******************************************************************************/
58#ifndef IN_GUEST
59/** Includes RTThreadPoke. */
60# define RTTHREAD_POSIX_WITH_POKE
61#endif
62
63
64/*******************************************************************************
65* Global Variables *
66*******************************************************************************/
67/** The pthread key in which we store the pointer to our own PRTTHREAD structure. */
68static pthread_key_t g_SelfKey;
69#ifdef RTTHREAD_POSIX_WITH_POKE
70/** The signal we use for poking threads.
71 * This is set to -1 if no available signal was found. */
72static int g_iSigPokeThread = -1;
73#endif
74
75
76/*******************************************************************************
77* Internal Functions *
78*******************************************************************************/
79static void *rtThreadNativeMain(void *pvArgs);
80static void rtThreadKeyDestruct(void *pvValue);
81static void rtThreadPosixPokeSignal(int iSignal);
82
83
84int rtThreadNativeInit(void)
85{
86 /*
87 * Allocate the TLS (key in posix terms) where we store the pointer to
88 * a threads RTTHREADINT structure.
89 */
90 int rc = pthread_key_create(&g_SelfKey, rtThreadKeyDestruct);
91 if (rc)
92 return VERR_NO_TLS_FOR_SELF;
93
94#ifdef RTTHREAD_POSIX_WITH_POKE
95 /*
96 * Try register the dummy signal handler for RTThreadPoke.
97 * Avoid SIGRTMIN thru SIGRTMIN+2 because of LinuxThreads.
98 */
99 static const int s_aiSigCandidates[] =
100 {
101# ifdef SIGRTMAX
102 SIGRTMAX-3,
103 SIGRTMAX-2,
104 SIGRTMAX-1,
105# endif
106# ifndef RT_OS_SOLARIS
107 SIGUSR2,
108# endif
109 SIGWINCH
110 };
111
112 g_iSigPokeThread = -1;
113 for (unsigned iSig = 0; iSig < RT_ELEMENTS(s_aiSigCandidates); iSig++)
114 {
115 struct sigaction SigActOld;
116 if (!sigaction(s_aiSigCandidates[iSig], NULL, &SigActOld))
117 {
118 if ( SigActOld.sa_handler == SIG_DFL
119 || SigActOld.sa_handler == rtThreadPosixPokeSignal)
120 {
121 struct sigaction SigAct;
122 RT_ZERO(SigAct);
123 SigAct.sa_handler = rtThreadPosixPokeSignal;
124 SigAct.sa_flags = 0;
125 sigfillset(&SigAct.sa_mask);
126
127 /* ASSUMES no sigaction race... (lazy bird) */
128 if (!sigaction(s_aiSigCandidates[iSig], &SigAct, NULL))
129 {
130 g_iSigPokeThread = s_aiSigCandidates[iSig];
131 break;
132 }
133 AssertMsgFailed(("rc=%Rrc errno=%d\n", RTErrConvertFromErrno(errno), errno));
134 }
135 }
136 else
137 AssertMsgFailed(("rc=%Rrc errno=%d\n", RTErrConvertFromErrno(errno), errno));
138 }
139#endif /* RTTHREAD_POSIX_WITH_POKE */
140 return rc;
141}
142
143
144/**
145 * Destructor called when a thread terminates.
146 * @param pvValue The key value. PRTTHREAD in our case.
147 */
148static void rtThreadKeyDestruct(void *pvValue)
149{
150 /*
151 * Deal with alien threads.
152 */
153 PRTTHREADINT pThread = (PRTTHREADINT)pvValue;
154 if (pThread->fIntFlags & RTTHREADINT_FLAGS_ALIEN)
155 {
156 pthread_setspecific(g_SelfKey, pThread);
157 rtThreadTerminate(pThread, 0);
158 pthread_setspecific(g_SelfKey, NULL);
159 }
160}
161
162
163#ifdef RTTHREAD_POSIX_WITH_POKE
164/**
165 * Dummy signal handler for the poke signal.
166 *
167 * @param iSignal The signal number.
168 */
169static void rtThreadPosixPokeSignal(int iSignal)
170{
171 Assert(iSignal == g_iSigPokeThread);
172 NOREF(iSignal);
173}
174#endif
175
176
177/**
178 * Adopts a thread, this is called immediately after allocating the
179 * thread structure.
180 *
181 * @param pThread Pointer to the thread structure.
182 */
183int rtThreadNativeAdopt(PRTTHREADINT pThread)
184{
185 /*
186 * Block SIGALRM - required for timer-posix.cpp.
187 * This is done to limit harm done by OSes which doesn't do special SIGALRM scheduling.
188 * It will not help much if someone creates threads directly using pthread_create. :/
189 */
190 sigset_t SigSet;
191 sigemptyset(&SigSet);
192 sigaddset(&SigSet, SIGALRM);
193 sigprocmask(SIG_BLOCK, &SigSet, NULL);
194#ifdef RTTHREAD_POSIX_WITH_POKE
195 if (g_iSigPokeThread != -1)
196 siginterrupt(g_iSigPokeThread, 1);
197#endif
198
199 int rc = pthread_setspecific(g_SelfKey, pThread);
200 if (!rc)
201 return VINF_SUCCESS;
202 return VERR_FAILED_TO_SET_SELF_TLS;
203}
204
205
206void rtThreadNativeDestroy(PRTTHREADINT pThread)
207{
208 if (pThread == (PRTTHREADINT)pthread_getspecific(g_SelfKey))
209 pthread_setspecific(g_SelfKey, NULL);
210}
211
212
213/**
214 * Wrapper which unpacks the params and calls thread function.
215 */
216static void *rtThreadNativeMain(void *pvArgs)
217{
218 PRTTHREADINT pThread = (PRTTHREADINT)pvArgs;
219
220#if defined(RT_OS_LINUX)
221 /*
222 * Set the TID.
223 */
224 pThread->tid = syscall(__NR_gettid);
225 ASMMemoryFence();
226#endif
227
228 /*
229 * Block SIGALRM - required for timer-posix.cpp.
230 * This is done to limit harm done by OSes which doesn't do special SIGALRM scheduling.
231 * It will not help much if someone creates threads directly using pthread_create. :/
232 */
233 sigset_t SigSet;
234 sigemptyset(&SigSet);
235 sigaddset(&SigSet, SIGALRM);
236 sigprocmask(SIG_BLOCK, &SigSet, NULL);
237#ifdef RTTHREAD_POSIX_WITH_POKE
238 if (g_iSigPokeThread != -1)
239 siginterrupt(g_iSigPokeThread, 1);
240#endif
241
242 int rc = pthread_setspecific(g_SelfKey, pThread);
243 AssertReleaseMsg(!rc, ("failed to set self TLS. rc=%d thread '%s'\n", rc, pThread->szName));
244
245 /*
246 * Call common main.
247 */
248 pthread_t Self = pthread_self();
249 Assert((uintptr_t)Self == (RTNATIVETHREAD)Self && (uintptr_t)Self != NIL_RTNATIVETHREAD);
250 rc = rtThreadMain(pThread, (uintptr_t)Self, &pThread->szName[0]);
251
252 pthread_exit((void *)rc);
253 return (void *)rc;
254}
255
256
257int rtThreadNativeCreate(PRTTHREADINT pThread, PRTNATIVETHREAD pNativeThread)
258{
259 /*
260 * Set the default stack size.
261 */
262 if (!pThread->cbStack)
263 pThread->cbStack = 512*1024;
264
265#ifdef RT_OS_LINUX
266 pThread->tid = -1;
267#endif
268
269 /*
270 * Setup thread attributes.
271 */
272 pthread_attr_t ThreadAttr;
273 int rc = pthread_attr_init(&ThreadAttr);
274 if (!rc)
275 {
276 rc = pthread_attr_setdetachstate(&ThreadAttr, PTHREAD_CREATE_DETACHED);
277 if (!rc)
278 {
279 rc = pthread_attr_setstacksize(&ThreadAttr, pThread->cbStack);
280 if (!rc)
281 {
282 /*
283 * Create the thread.
284 */
285 pthread_t ThreadId;
286 rc = pthread_create(&ThreadId, &ThreadAttr, rtThreadNativeMain, pThread);
287 if (!rc)
288 {
289 *pNativeThread = (uintptr_t)ThreadId;
290 return VINF_SUCCESS;
291 }
292 }
293 }
294 pthread_attr_destroy(&ThreadAttr);
295 }
296 return RTErrConvertFromErrno(rc);
297}
298
299
300RTDECL(RTTHREAD) RTThreadSelf(void)
301{
302 PRTTHREADINT pThread = (PRTTHREADINT)pthread_getspecific(g_SelfKey);
303 /** @todo import alien threads? */
304 return pThread;
305}
306
307
308RTDECL(RTNATIVETHREAD) RTThreadNativeSelf(void)
309{
310 return (RTNATIVETHREAD)pthread_self();
311}
312
313
314RTDECL(int) RTThreadSleep(RTMSINTERVAL cMillies)
315{
316 LogFlow(("RTThreadSleep: cMillies=%d\n", cMillies));
317 if (!cMillies)
318 {
319 /* pthread_yield() isn't part of SuS, thus this fun. */
320#ifdef RT_OS_DARWIN
321 pthread_yield_np();
322#elif defined(RT_OS_FREEBSD) /* void pthread_yield */
323 pthread_yield();
324#elif defined(RT_OS_SOLARIS)
325 sched_yield();
326#else
327 if (!pthread_yield())
328#endif
329 {
330 LogFlow(("RTThreadSleep: returning %Rrc (cMillies=%d)\n", VINF_SUCCESS, cMillies));
331 return VINF_SUCCESS;
332 }
333 }
334 else
335 {
336 struct timespec ts;
337 struct timespec tsrem = {0,0};
338
339 ts.tv_nsec = (cMillies % 1000) * 1000000;
340 ts.tv_sec = cMillies / 1000;
341 if (!nanosleep(&ts, &tsrem))
342 {
343 LogFlow(("RTThreadSleep: returning %Rrc (cMillies=%d)\n", VINF_SUCCESS, cMillies));
344 return VINF_SUCCESS;
345 }
346 }
347
348 int rc = RTErrConvertFromErrno(errno);
349 LogFlow(("RTThreadSleep: returning %Rrc (cMillies=%d)\n", rc, cMillies));
350 return rc;
351}
352
353
354RTDECL(bool) RTThreadYield(void)
355{
356#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
357 uint64_t u64TS = ASMReadTSC();
358#endif
359#ifdef RT_OS_DARWIN
360 pthread_yield_np();
361#elif defined(RT_OS_SOLARIS)
362 sched_yield();
363#else
364 pthread_yield();
365#endif
366#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
367 u64TS = ASMReadTSC() - u64TS;
368 bool fRc = u64TS > 1500;
369 LogFlow(("RTThreadYield: returning %d (%llu ticks)\n", fRc, u64TS));
370#else
371 bool fRc = true; /* PORTME: Add heuristics for determining whether the cpus was yielded. */
372#endif
373 return fRc;
374}
375
376
377RTR3DECL(uint64_t) RTThreadGetAffinity(void)
378{
379 return 1;
380}
381
382
383RTR3DECL(int) RTThreadSetAffinity(uint64_t u64Mask)
384{
385 if (u64Mask != 1)
386 return VERR_INVALID_PARAMETER;
387 return VINF_SUCCESS;
388}
389
390
391#ifdef RTTHREAD_POSIX_WITH_POKE
392RTDECL(int) RTThreadPoke(RTTHREAD hThread)
393{
394 AssertReturn(hThread != RTThreadSelf(), VERR_INVALID_PARAMETER);
395 PRTTHREADINT pThread = rtThreadGet(hThread);
396 AssertReturn(pThread, VERR_INVALID_HANDLE);
397
398 int rc;
399 if (g_iSigPokeThread != -1)
400 {
401 rc = pthread_kill((pthread_t)(uintptr_t)pThread->Core.Key, g_iSigPokeThread);
402 rc = RTErrConvertFromErrno(rc);
403 }
404 else
405 rc = VERR_NOT_SUPPORTED;
406
407 rtThreadRelease(pThread);
408 return rc;
409}
410#endif
411
412RTR3DECL(int) RTThreadGetExecutionTimeMilli(uint64_t *pKernelTime, uint64_t *pUserTime)
413{
414 return VERR_NOT_IMPLEMENTED;
415}
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