VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/linux/semmutex-linux.cpp@ 25711

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

iprt: RTSemMutex order validation.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 13.3 KB
Line 
1/* $Id: semmutex-linux.cpp 25711 2010-01-11 11:15:04Z vboxsync $ */
2/** @file
3 * IPRT - Mutex Semaphore, Linux (2.6.x+).
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* Header Files *
33*******************************************************************************/
34#include <iprt/semaphore.h>
35#include "internal/iprt.h"
36
37#include <iprt/alloc.h>
38#include <iprt/asm.h>
39#include <iprt/assert.h>
40#include <iprt/err.h>
41#include <iprt/lockvalidator.h>
42#include <iprt/thread.h>
43#include <iprt/time.h>
44#include "internal/magics.h"
45#include "internal/strict.h"
46
47#include <errno.h>
48#include <limits.h>
49#include <pthread.h>
50#include <unistd.h>
51#include <sys/time.h>
52#include <sys/syscall.h>
53#if 0 /* With 2.6.17 futex.h has become C++ unfriendly. */
54# include <linux/futex.h>
55#else
56# define FUTEX_WAIT 0
57# define FUTEX_WAKE 1
58#endif
59
60
61/*******************************************************************************
62* Structures and Typedefs *
63*******************************************************************************/
64/**
65 * Linux internal representation of a Mutex semaphore.
66 */
67struct RTSEMMUTEXINTERNAL
68{
69 /** The futex state variable.
70 * 0 means unlocked.
71 * 1 means locked, no waiters.
72 * 2 means locked, one or more waiters.
73 */
74 int32_t volatile iState;
75 /** Nesting count. */
76 uint32_t volatile cNesting;
77 /** The owner of the mutex. */
78 pthread_t volatile Owner;
79 /** Magic value (RTSEMMUTEX_MAGIC). */
80 uint32_t volatile u32Magic;
81#ifdef RTSEMMUTEX_STRICT
82 /** Lock validator record associated with this mutex. */
83 RTLOCKVALRECEXCL ValidatorRec;
84#endif
85};
86
87
88/* Undefine debug mappings. */
89#undef RTSemMutexRequest
90#undef RTSemMutexRequestNoResume
91
92
93/**
94 * Wrapper for the futex syscall.
95 */
96static long sys_futex(int32_t volatile *uaddr, int op, int val, struct timespec *utime, int32_t *uaddr2, int val3)
97{
98 errno = 0;
99 long rc = syscall(__NR_futex, uaddr, op, val, utime, uaddr2, val3);
100 if (rc < 0)
101 {
102 Assert(rc == -1);
103 rc = -errno;
104 }
105 return rc;
106}
107
108
109#undef RTSemMutexCreate
110RTDECL(int) RTSemMutexCreate(PRTSEMMUTEX phMutexSem)
111{
112 return RTSemMutexCreateEx(phMutexSem, 0 /*fFlags*/, NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_NONE, NULL);
113}
114
115
116RTDECL(int) RTSemMutexCreateEx(PRTSEMMUTEX phMutexSem, uint32_t fFlags,
117 RTLOCKVALCLASS hClass, uint32_t uSubClass, const char *pszNameFmt, ...)
118{
119 AssertReturn(!(fFlags & ~RTSEMMUTEX_FLAGS_NO_LOCK_VAL), VERR_INVALID_PARAMETER);
120
121 /*
122 * Allocate semaphore handle.
123 */
124 struct RTSEMMUTEXINTERNAL *pThis = (struct RTSEMMUTEXINTERNAL *)RTMemAlloc(sizeof(struct RTSEMMUTEXINTERNAL));
125 if (pThis)
126 {
127 pThis->u32Magic = RTSEMMUTEX_MAGIC;
128 pThis->iState = 0;
129 pThis->Owner = (pthread_t)~0;
130 pThis->cNesting = 0;
131#ifdef RTSEMMUTEX_STRICT
132 va_list va;
133 va_start(va, pszNameFmt);
134 RTLockValidatorRecExclInitV(&pThis->ValidatorRec, hClass, uSubClass, pThis,
135 !(fFlags & RTSEMMUTEX_FLAGS_NO_LOCK_VAL), pszNameFmt, va);
136 va_end(va);
137#endif
138
139 *phMutexSem = pThis;
140 return VINF_SUCCESS;
141 }
142
143 return VERR_NO_MEMORY;
144}
145
146
147RTDECL(int) RTSemMutexDestroy(RTSEMMUTEX MutexSem)
148{
149 /*
150 * Validate input.
151 */
152 if (MutexSem == NIL_RTSEMMUTEX)
153 return VINF_SUCCESS;
154 struct RTSEMMUTEXINTERNAL *pThis = MutexSem;
155 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
156 AssertMsgReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC,
157 ("MutexSem=%p u32Magic=%#x\n", pThis, pThis->u32Magic),
158 VERR_INVALID_HANDLE);
159
160 /*
161 * Invalidate the semaphore and wake up anyone waiting on it.
162 */
163 ASMAtomicWriteU32(&pThis->u32Magic, RTSEMMUTEX_MAGIC_DEAD);
164 if (ASMAtomicXchgS32(&pThis->iState, 0) > 0)
165 {
166 sys_futex(&pThis->iState, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
167 usleep(1000);
168 }
169 pThis->Owner = (pthread_t)~0;
170 pThis->cNesting = 0;
171#ifdef RTSEMMUTEX_STRICT
172 RTLockValidatorRecExclDelete(&pThis->ValidatorRec);
173#endif
174
175 /*
176 * Free the semaphore memory and be gone.
177 */
178 RTMemFree(pThis);
179 return VINF_SUCCESS;
180}
181
182
183RTDECL(uint32_t) RTSemMutexSetSubClass(RTSEMMUTEX hMutexSem, uint32_t uSubClass)
184{
185#ifdef RTSEMMUTEX_STRICT
186 /*
187 * Validate.
188 */
189 RTSEMMUTEXINTERNAL *pThis = hMutexSem;
190 AssertPtrReturn(pThis, RTLOCKVAL_SUB_CLASS_INVALID);
191 AssertReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC, RTLOCKVAL_SUB_CLASS_INVALID);
192
193 return RTLockValidatorRecExclSetSubClass(&pThis->ValidatorRec, uSubClass);
194#else
195 return RTLOCKVAL_SUB_CLASS_INVALID;
196#endif
197}
198
199
200DECL_FORCE_INLINE(int) rtSemMutexRequest(RTSEMMUTEX MutexSem, unsigned cMillies, bool fAutoResume, PCRTLOCKVALSRCPOS pSrcPos)
201{
202 /*
203 * Validate input.
204 */
205 struct RTSEMMUTEXINTERNAL *pThis = MutexSem;
206 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
207 AssertReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC, VERR_INVALID_HANDLE);
208
209 /*
210 * Check if nested request.
211 */
212 pthread_t Self = pthread_self();
213 if ( pThis->Owner == Self
214 && pThis->cNesting > 0)
215 {
216#ifdef RTSEMMUTEX_STRICT
217 int rc9 = RTLockValidatorRecExclRecursion(&pThis->ValidatorRec, pSrcPos);
218 if (RT_FAILURE(rc9))
219 return rc9;
220#endif
221 ASMAtomicIncU32(&pThis->cNesting);
222 return VINF_SUCCESS;
223 }
224
225#ifdef RTSEMMUTEX_STRICT
226 RTTHREAD hThreadSelf = RTThreadSelfAutoAdopt();
227 if (cMillies)
228 {
229 int rc9 = RTLockValidatorRecExclCheckOrder(&pThis->ValidatorRec, hThreadSelf, pSrcPos, cMillies);
230 if (RT_FAILURE(rc9))
231 return rc9;
232 }
233#else
234 RTTHREAD hThreadSelf = RTThreadSelf();
235#endif
236
237 /*
238 * Convert timeout value.
239 */
240 struct timespec ts;
241 struct timespec *pTimeout = NULL;
242 uint64_t u64End = 0; /* shut up gcc */
243 if (cMillies != RT_INDEFINITE_WAIT)
244 {
245 ts.tv_sec = cMillies / 1000;
246 ts.tv_nsec = (cMillies % 1000) * UINT32_C(1000000);
247 u64End = RTTimeSystemNanoTS() + cMillies * UINT64_C(1000000);
248 pTimeout = &ts;
249 }
250
251 /*
252 * Lock the mutex.
253 * Optimize for the uncontended case (makes 1-2 ns difference).
254 */
255 if (RT_UNLIKELY(!ASMAtomicCmpXchgS32(&pThis->iState, 1, 0)))
256 {
257 for (;;)
258 {
259 int32_t iOld = ASMAtomicXchgS32(&pThis->iState, 2);
260
261 /*
262 * Was the lock released in the meantime? This is unlikely (but possible)
263 */
264 if (RT_UNLIKELY(iOld == 0))
265 break;
266
267 /*
268 * Go to sleep.
269 */
270 if (pTimeout && ( pTimeout->tv_sec || pTimeout->tv_nsec ))
271 {
272#ifdef RTSEMMUTEX_STRICT
273 int rc9 = RTLockValidatorRecExclCheckBlocking(&pThis->ValidatorRec, hThreadSelf, pSrcPos, true,
274 cMillies, RTTHREADSTATE_MUTEX, true);
275 if (RT_FAILURE(rc9))
276 return rc9;
277#else
278 RTThreadBlocking(hThreadSelf, RTTHREADSTATE_MUTEX, true);
279#endif
280 }
281
282 long rc = sys_futex(&pThis->iState, FUTEX_WAIT, 2, pTimeout, NULL, 0);
283
284 RTThreadUnblocked(hThreadSelf, RTTHREADSTATE_MUTEX);
285 if (RT_UNLIKELY(pThis->u32Magic != RTSEMMUTEX_MAGIC))
286 return VERR_SEM_DESTROYED;
287
288 /*
289 * Act on the wakup code.
290 */
291 if (rc == -ETIMEDOUT)
292 {
293 Assert(pTimeout);
294 return VERR_TIMEOUT;
295 }
296 if (rc == 0)
297 /* we'll leave the loop now unless another thread is faster */;
298 else if (rc == -EWOULDBLOCK)
299 /* retry with new value. */;
300 else if (rc == -EINTR)
301 {
302 if (!fAutoResume)
303 return VERR_INTERRUPTED;
304 }
305 else
306 {
307 /* this shouldn't happen! */
308 AssertMsgFailed(("rc=%ld errno=%d\n", rc, errno));
309 return RTErrConvertFromErrno(rc);
310 }
311
312 /* adjust the relative timeout */
313 if (pTimeout)
314 {
315 int64_t i64Diff = u64End - RTTimeSystemNanoTS();
316 if (i64Diff < 1000)
317 {
318 rc = VERR_TIMEOUT;
319 break;
320 }
321 ts.tv_sec = (uint64_t)i64Diff / UINT32_C(1000000000);
322 ts.tv_nsec = (uint64_t)i64Diff % UINT32_C(1000000000);
323 }
324 }
325
326 /*
327 * When leaving this loop, iState is set to 2. This means that we gained the
328 * lock and there are _possibly_ some waiters. We don't know exactly as another
329 * thread might entered this loop at nearly the same time. Therefore we will
330 * call futex_wakeup once too often (if _no_ other thread entered this loop).
331 * The key problem is the simple futex_wait test for x != y (iState != 2) in
332 * our case).
333 */
334 }
335
336 /*
337 * Set the owner and nesting.
338 */
339 pThis->Owner = Self;
340 ASMAtomicWriteU32(&pThis->cNesting, 1);
341#ifdef RTSEMMUTEX_STRICT
342 RTLockValidatorRecExclSetOwner(&pThis->ValidatorRec, hThreadSelf, pSrcPos, true);
343#endif
344 return VINF_SUCCESS;
345}
346
347
348RTDECL(int) RTSemMutexRequest(RTSEMMUTEX MutexSem, unsigned cMillies)
349{
350#ifndef RTSEMMUTEX_STRICT
351 int rc = rtSemMutexRequest(MutexSem, cMillies, true, NULL);
352#else
353 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_NORMAL_API();
354 int rc = rtSemMutexRequest(MutexSem, cMillies, true, &SrcPos);
355#endif
356 Assert(rc != VERR_INTERRUPTED);
357 return rc;
358}
359
360
361RTDECL(int) RTSemMutexRequestDebug(RTSEMMUTEX MutexSem, unsigned cMillies, RTHCUINTPTR uId, RT_SRC_POS_DECL)
362{
363 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_DEBUG_API();
364 int rc = rtSemMutexRequest(MutexSem, cMillies, true, &SrcPos);
365 Assert(rc != VERR_INTERRUPTED);
366 return rc;
367}
368
369
370RTDECL(int) RTSemMutexRequestNoResume(RTSEMMUTEX MutexSem, unsigned cMillies)
371{
372#ifndef RTSEMMUTEX_STRICT
373 return rtSemMutexRequest(MutexSem, cMillies, false, NULL);
374#else
375 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_NORMAL_API();
376 return rtSemMutexRequest(MutexSem, cMillies, false, &SrcPos);
377#endif
378}
379
380
381RTDECL(int) RTSemMutexRequestNoResumeDebug(RTSEMMUTEX MutexSem, unsigned cMillies, RTHCUINTPTR uId, RT_SRC_POS_DECL)
382{
383 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_DEBUG_API();
384 return rtSemMutexRequest(MutexSem, cMillies, false, &SrcPos);
385}
386
387
388RTDECL(int) RTSemMutexRelease(RTSEMMUTEX MutexSem)
389{
390 /*
391 * Validate input.
392 */
393 struct RTSEMMUTEXINTERNAL *pThis = MutexSem;
394 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
395 AssertReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC, VERR_INVALID_HANDLE);
396
397#ifdef RTSEMMUTEX_STRICT
398 int rc9 = RTLockValidatorRecExclReleaseOwner(&pThis->ValidatorRec, pThis->cNestings != 1);
399 if (RT_FAILURE(rc9))
400 return rc9;
401#endif
402
403 /*
404 * Check if nested.
405 */
406 pthread_t Self = pthread_self();
407 if (RT_UNLIKELY( pThis->Owner != Self
408 || pThis->cNesting == 0))
409 {
410 AssertMsgFailed(("Not owner of mutex %p!! Self=%08x Owner=%08x cNesting=%d\n",
411 pThis, Self, pThis->Owner, pThis->cNesting));
412 return VERR_NOT_OWNER;
413 }
414
415 /*
416 * If nested we'll just pop a nesting.
417 */
418 if (pThis->cNesting > 1)
419 {
420 ASMAtomicDecU32(&pThis->cNesting);
421 return VINF_SUCCESS;
422 }
423
424 /*
425 * Clear the state. (cNesting == 1)
426 */
427 pThis->Owner = (pthread_t)~0;
428 ASMAtomicWriteU32(&pThis->cNesting, 0);
429
430 /*
431 * Release the mutex.
432 */
433 int32_t iNew = ASMAtomicDecS32(&pThis->iState);
434 if (RT_UNLIKELY(iNew != 0))
435 {
436 /* somebody is waiting, try wake up one of them. */
437 ASMAtomicXchgS32(&pThis->iState, 0);
438 (void)sys_futex(&pThis->iState, FUTEX_WAKE, 1, NULL, NULL, 0);
439 }
440 return VINF_SUCCESS;
441}
442
443
444RTDECL(bool) RTSemMutexIsOwned(RTSEMMUTEX hMutex)
445{
446 /*
447 * Validate.
448 */
449 RTSEMMUTEXINTERNAL *pThis = hMutex;
450 AssertPtrReturn(pThis, false);
451 AssertReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC, false);
452
453 return pThis->Owner != (pthread_t)~0;
454}
455
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