VirtualBox

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

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

iprt/lockvalidation: give better names to anonymous locks

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

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