VirtualBox

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

Last change on this file since 62584 was 62477, checked in by vboxsync, 8 years ago

(C) 2016

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