VirtualBox

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

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

iprt: Use RTMSINTERVAL for timeouts. Fixed missing timeout underflow checks in two RTFileAioCtxWait implementations.

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