VirtualBox

source: vbox/trunk/src/VBox/Runtime/nt/semevent-nt.cpp@ 106877

Last change on this file since 106877 was 106061, checked in by vboxsync, 2 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 15.8 KB
Line 
1/* $Id: semevent-nt.cpp 106061 2024-09-16 14:03:52Z vboxsync $ */
2/** @file
3 * IPRT - Single Release Event Semaphores, Ring-0 Driver & Ring-3 Userland, NT.
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define RTSEMEVENT_WITHOUT_REMAPPING
42#ifdef IN_RING0
43# include "../r0drv/nt/the-nt-kernel.h"
44#else
45# include <iprt/nt/nt.h>
46#endif
47#include <iprt/semaphore.h>
48
49#include <iprt/asm.h>
50#include <iprt/assert.h>
51#include <iprt/err.h>
52#include <iprt/lockvalidator.h>
53#include <iprt/mem.h>
54#include <iprt/time.h>
55
56#include "internal/magics.h"
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62/**
63 * NT event semaphore.
64 */
65typedef struct RTSEMEVENTINTERNAL
66{
67 /** Magic value (RTSEMEVENT_MAGIC). */
68 uint32_t volatile u32Magic;
69 /** Reference counter. */
70 uint32_t volatile cRefs;
71#ifdef IN_RING0
72 /** The NT event object. */
73 KEVENT Event;
74#elif defined(IN_RING3)
75 /** Handle to the NT event object. */
76 HANDLE hEvent;
77#else
78# error "Unknown context"
79#endif
80#if defined(RTSEMEVENT_STRICT) && defined(IN_RING3)
81 /** Signallers. */
82 RTLOCKVALRECSHRD Signallers;
83 /** Indicates that lock validation should be performed. */
84 bool volatile fEverHadSignallers;
85#endif
86
87} RTSEMEVENTINTERNAL, *PRTSEMEVENTINTERNAL;
88
89
90RTDECL(int) RTSemEventCreate(PRTSEMEVENT phEventSem)
91{
92 return RTSemEventCreateEx(phEventSem, 0 /*fFlags*/, NIL_RTLOCKVALCLASS, NULL);
93}
94
95
96RTDECL(int) RTSemEventCreateEx(PRTSEMEVENT phEventSem, uint32_t fFlags, RTLOCKVALCLASS hClass, const char *pszNameFmt, ...)
97{
98 AssertReturn(!(fFlags & ~(RTSEMEVENT_FLAGS_NO_LOCK_VAL | RTSEMEVENT_FLAGS_BOOTSTRAP_HACK)), VERR_INVALID_PARAMETER);
99 Assert(!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK) || (fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL));
100 AssertCompile(sizeof(RTSEMEVENTINTERNAL) > sizeof(void *));
101
102 PRTSEMEVENTINTERNAL pThis = (PRTSEMEVENTINTERNAL)RTMemAlloc(sizeof(*pThis));
103 if (pThis)
104 {
105 pThis->u32Magic = RTSEMEVENT_MAGIC;
106 pThis->cRefs = 1;
107#ifdef IN_RING0
108 KeInitializeEvent(&pThis->Event, SynchronizationEvent, FALSE /* not signalled */);
109#else
110 NTSTATUS rcNt = NtCreateEvent(&pThis->hEvent, EVENT_ALL_ACCESS, NULL /*pObjAttr*/,
111 SynchronizationEvent, FALSE /*not signalled*/);
112 if (NT_SUCCESS(rcNt))
113#endif
114 {
115#if defined(RTSEMEVENT_STRICT) && defined(IN_RING3)
116 if (!pszNameFmt)
117 {
118 static uint32_t volatile s_iSemEventAnon = 0;
119 RTLockValidatorRecSharedInit(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis,
120 true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL),
121 "RTSemEvent-%u", ASMAtomicIncU32(&s_iSemEventAnon) - 1);
122 }
123 else
124 {
125 va_list va;
126 va_start(va, pszNameFmt);
127 RTLockValidatorRecSharedInitV(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis,
128 true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL),
129 pszNameFmt, va);
130 va_end(va);
131 }
132 pThis->fEverHadSignallers = false;
133#else
134 RT_NOREF_PV(hClass); RT_NOREF_PV(pszNameFmt);
135#endif
136 *phEventSem = pThis;
137 return VINF_SUCCESS;
138 }
139#ifdef IN_RING3
140 RTMemFree(pThis);
141 return RTErrConvertFromNtStatus(rcNt);
142#endif
143 }
144 return VERR_NO_MEMORY;
145}
146
147
148/**
149 * Retains a reference to the semaphore.
150 *
151 * @param pThis The semaphore to retain.
152 */
153DECLINLINE(void) rtR0SemEventNtRetain(PRTSEMEVENTINTERNAL pThis)
154{
155 uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
156 Assert(cRefs < 100000); NOREF(cRefs);
157}
158
159
160/**
161 * Releases a reference to the semaphore.
162 *
163 * @param pThis The semaphore to release
164 */
165DECLINLINE(void) rtR0SemEventNtRelease(PRTSEMEVENTINTERNAL pThis)
166{
167 if (ASMAtomicDecU32(&pThis->cRefs) == 0)
168 {
169#ifdef IN_RING3
170 NTSTATUS rcNt = NtClose(pThis->hEvent);
171 AssertMsg(NT_SUCCESS(rcNt), ("%#x\n", rcNt)); RT_NOREF(rcNt);
172 pThis->hEvent = NULL;
173#endif
174#if defined(RTSEMEVENT_STRICT) && defined(IN_RING3)
175 RTLockValidatorRecSharedDelete(&pThis->Signallers);
176#endif
177 RTMemFree(pThis);
178 }
179}
180
181
182RTDECL(int) RTSemEventDestroy(RTSEMEVENT hEventSem)
183{
184 /*
185 * Validate input.
186 */
187 PRTSEMEVENTINTERNAL pThis = hEventSem;
188 if (pThis == NIL_RTSEMEVENT)
189 return VINF_SUCCESS;
190 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
191 AssertMsgReturn(pThis->u32Magic == RTSEMEVENT_MAGIC, ("pThis->u32Magic=%RX32 pThis=%p\n", pThis->u32Magic, pThis), VERR_INVALID_HANDLE);
192
193 /*
194 * Invalidate it and signal the object just in case.
195 */
196 ASMAtomicIncU32(&pThis->u32Magic);
197#ifdef IN_RING0
198 KeSetEvent(&pThis->Event, 0xfff, FALSE);
199#else
200 NtSetEvent(pThis->hEvent, NULL);
201#endif
202
203 rtR0SemEventNtRelease(pThis);
204 return VINF_SUCCESS;
205}
206
207
208RTDECL(int) RTSemEventSignal(RTSEMEVENT hEventSem)
209{
210 /*
211 * Validate input.
212 */
213 PRTSEMEVENTINTERNAL pThis = (PRTSEMEVENTINTERNAL)hEventSem;
214 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
215 AssertMsgReturn(pThis->u32Magic == RTSEMEVENT_MAGIC, ("pThis->u32Magic=%RX32 pThis=%p\n", pThis->u32Magic, pThis), VERR_INVALID_HANDLE);
216 rtR0SemEventNtRetain(pThis);
217
218#if defined(RTSEMEVENT_STRICT) && defined(IN_RING3)
219 if (pThis->fEverHadSignallers)
220 {
221 int rc9 = RTLockValidatorRecSharedCheckSignaller(&pThis->Signallers, NIL_RTTHREAD);
222 if (RT_FAILURE(rc9))
223 return rc9;
224 }
225#endif
226
227 /*
228 * Signal the event object.
229 */
230#ifdef IN_RING0
231 KeSetEvent(&pThis->Event, 1, FALSE);
232#else
233 NTSTATUS rcNt = NtSetEvent(pThis->hEvent, NULL);
234#endif
235
236 rtR0SemEventNtRelease(pThis);
237#ifdef IN_RING3
238 AssertMsgReturn(NT_SUCCESS(rcNt), ("Signaling hEventSem %p failed: %#x\n", pThis, rcNt), RTErrConvertFromNtStatus(rcNt));
239#endif
240 return VINF_SUCCESS;
241}
242
243
244
245/**
246 * Worker for RTSemEventWaitEx and RTSemEventWaitExDebug.
247 *
248 * @returns VBox status code.
249 * @param pThis The event semaphore.
250 * @param fFlags See RTSemEventWaitEx.
251 * @param uTimeout See RTSemEventWaitEx.
252 * @param pSrcPos The source code position of the wait.
253 */
254DECLINLINE(int) rtR0SemEventNtWait(PRTSEMEVENTINTERNAL pThis, uint32_t fFlags, uint64_t uTimeout,
255 PCRTLOCKVALSRCPOS pSrcPos)
256{
257 /*
258 * Validate input.
259 */
260 if (!pThis)
261 return VERR_INVALID_PARAMETER;
262 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
263 AssertMsgReturn(pThis->u32Magic == RTSEMEVENT_MAGIC, ("%p u32Magic=%RX32\n", pThis, pThis->u32Magic), VERR_INVALID_HANDLE);
264 AssertReturn(RTSEMWAIT_FLAGS_ARE_VALID(fFlags), VERR_INVALID_FLAGS);
265 NOREF(pSrcPos);
266
267 rtR0SemEventNtRetain(pThis);
268
269 /*
270 * Lock validation needs to be done only when not polling.
271 */
272#if defined(RTSEMEVENT_STRICT) && defined(IN_RING3)
273 RTTHREAD const hThreadSelf = !(pThis->fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK) ? RTThreadSelfAutoAdopt() : RTThreadSelf();
274 if ( pThis->fEverHadSignallers
275 && ( uTimeout != 0
276 || (fFlags & (RTSEMWAIT_FLAGS_INDEFINITE | RTSEMWAIT_FLAGS_ABSOLUTE))) )
277 {
278 int rc9 = RTLockValidatorRecSharedCheckBlocking(&pThis->Signallers, hThreadSelf, NULL /*pSrcPos*/, false,
279 fFlags & RTSEMWAIT_FLAGS_INDEFINITE
280 ? RT_INDEFINITE_WAIT : RT_MS_30SEC /*whatever*/,
281 RTTHREADSTATE_EVENT, true);
282 if (RT_FAILURE(rc9))
283 return rc9;
284 }
285#elif defined(IN_RING3)
286 RTTHREAD const hThreadSelf = RTThreadSelf();
287#endif
288
289 /*
290 * Convert the timeout to a relative one because KeWaitForSingleObject
291 * takes system time instead of interrupt time as input for absolute
292 * timeout specifications. So, we're best off by giving it relative time.
293 *
294 * Lazy bird converts uTimeout to relative nanoseconds and then to Nt time.
295 */
296#ifdef IN_RING3
297 uint64_t nsStartNow = 0;
298#endif
299 if (!(fFlags & RTSEMWAIT_FLAGS_INDEFINITE))
300 {
301 if (fFlags & RTSEMWAIT_FLAGS_MILLISECS)
302 uTimeout = uTimeout < UINT64_MAX / RT_NS_1MS
303 ? uTimeout * RT_NS_1MS
304 : UINT64_MAX;
305 if (uTimeout == UINT64_MAX)
306 fFlags |= RTSEMWAIT_FLAGS_INDEFINITE;
307 else
308 {
309#ifdef IN_RING3
310 if (fFlags & (RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_ABSOLUTE))
311 nsStartNow = RTTimeSystemNanoTS();
312#endif
313 if (fFlags & RTSEMWAIT_FLAGS_ABSOLUTE)
314 {
315#ifdef IN_RING0
316 uint64_t const nsStartNow = RTTimeSystemNanoTS();
317#endif
318 uTimeout = nsStartNow < uTimeout
319 ? uTimeout - nsStartNow
320 : 0;
321 }
322 }
323 }
324
325 /*
326 * Wait for it.
327 * We're assuming interruptible waits should happen at UserMode level.
328 */
329 int rc;
330#ifdef IN_RING3
331 for (;;)
332#endif
333 {
334#ifdef IN_RING0
335 BOOLEAN fInterruptible = !!(fFlags & RTSEMWAIT_FLAGS_INTERRUPTIBLE);
336 KPROCESSOR_MODE WaitMode = fInterruptible ? UserMode : KernelMode;
337#endif
338 NTSTATUS rcNt;
339#ifdef IN_RING3
340 RTThreadBlocking(hThreadSelf, RTTHREADSTATE_EVENT, true);
341#endif
342 if (fFlags & RTSEMWAIT_FLAGS_INDEFINITE)
343#ifdef IN_RING0
344 rcNt = KeWaitForSingleObject(&pThis->Event, Executive, WaitMode, fInterruptible, NULL);
345#else
346 rcNt = NtWaitForSingleObject(pThis->hEvent, TRUE /*Alertable*/, NULL);
347#endif
348 else
349 {
350 LARGE_INTEGER Timeout;
351 Timeout.QuadPart = -(int64_t)(uTimeout / 100);
352#ifdef IN_RING0
353 rcNt = KeWaitForSingleObject(&pThis->Event, Executive, WaitMode, fInterruptible, &Timeout);
354#else
355 rcNt = NtWaitForSingleObject(pThis->hEvent, TRUE /*Alertable*/, &Timeout);
356#endif
357 }
358#ifdef IN_RING3
359 RTThreadUnblocked(hThreadSelf, RTTHREADSTATE_EVENT);
360#endif
361 if (pThis->u32Magic == RTSEMEVENT_MAGIC)
362 {
363 switch (rcNt)
364 {
365 case STATUS_SUCCESS:
366 rc = VINF_SUCCESS;
367 break;
368
369 case STATUS_TIMEOUT:
370 Assert(!(fFlags & RTSEMWAIT_FLAGS_INDEFINITE));
371 rc = VERR_TIMEOUT;
372 break;
373
374 case STATUS_USER_APC:
375 case STATUS_ALERTED:
376 rc = VERR_INTERRUPTED;
377#ifdef IN_RING3
378 /* Loop if when automatically resuming on interruption, adjusting the timeout. */
379 if (fFlags & RTSEMWAIT_FLAGS_RESUME)
380 {
381 if (!(fFlags & RTSEMWAIT_FLAGS_INDEFINITE) && uTimeout > 0)
382 {
383 uint64_t const nsNewNow = RTTimeSystemNanoTS();
384 uint64_t const cNsElapsed = nsNewNow - nsStartNow;
385 if (cNsElapsed < uTimeout)
386 uTimeout -= cNsElapsed;
387 else
388 uTimeout = 0;
389 nsStartNow = nsNewNow;
390 }
391 continue;
392 }
393#endif
394 break;
395
396#ifdef IN_RING3
397 case STATUS_ABANDONED_WAIT_0:
398 rc = VERR_SEM_OWNER_DIED;
399 break;
400#endif
401 default:
402 AssertMsgFailed(("pThis->u32Magic=%RX32 pThis=%p: wait returned %x!\n", pThis->u32Magic, pThis, rcNt));
403 rc = VERR_INTERNAL_ERROR_4;
404 break;
405 }
406 }
407 else
408 rc = VERR_SEM_DESTROYED;
409#ifdef IN_RING3
410 break;
411#endif
412 }
413
414 rtR0SemEventNtRelease(pThis);
415 return rc;
416}
417
418
419RTDECL(int) RTSemEventWaitEx(RTSEMEVENT hEventSem, uint32_t fFlags, uint64_t uTimeout)
420{
421#ifndef RTSEMEVENT_STRICT
422 return rtR0SemEventNtWait(hEventSem, fFlags, uTimeout, NULL);
423#else
424 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_NORMAL_API();
425 return rtR0SemEventNtWait(hEventSem, fFlags, uTimeout, &SrcPos);
426#endif
427}
428
429
430RTDECL(int) RTSemEventWaitExDebug(RTSEMEVENT hEventSem, uint32_t fFlags, uint64_t uTimeout,
431 RTHCUINTPTR uId, RT_SRC_POS_DECL)
432{
433 RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_DEBUG_API();
434 return rtR0SemEventNtWait(hEventSem, fFlags, uTimeout, &SrcPos);
435}
436
437
438#ifdef IN_RING0
439RTR0DECL(bool) RTSemEventIsSignalSafe(void)
440{
441 return KeGetCurrentIrql() <= DISPATCH_LEVEL;
442}
443#endif
444
445#ifdef IN_RING3
446
447RTDECL(void) RTSemEventSetSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread)
448{
449# ifdef RTSEMEVENT_STRICT
450 struct RTSEMEVENTINTERNAL *pThis = hEventSem;
451 AssertPtrReturnVoid(pThis);
452 AssertReturnVoid(pThis->u32Magic == RTSEMEVENT_MAGIC);
453
454 ASMAtomicWriteBool(&pThis->fEverHadSignallers, true);
455 RTLockValidatorRecSharedResetOwner(&pThis->Signallers, hThread, NULL);
456# else
457 RT_NOREF_PV(hEventSem); RT_NOREF_PV(hThread);
458# endif
459}
460
461
462RTDECL(void) RTSemEventAddSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread)
463{
464# ifdef RTSEMEVENT_STRICT
465 struct RTSEMEVENTINTERNAL *pThis = hEventSem;
466 AssertPtrReturnVoid(pThis);
467 AssertReturnVoid(pThis->u32Magic == RTSEMEVENT_MAGIC);
468
469 ASMAtomicWriteBool(&pThis->fEverHadSignallers, true);
470 RTLockValidatorRecSharedAddOwner(&pThis->Signallers, hThread, NULL);
471# else
472 RT_NOREF_PV(hEventSem); RT_NOREF_PV(hThread);
473# endif
474}
475
476
477RTDECL(void) RTSemEventRemoveSignaller(RTSEMEVENT hEventSem, RTTHREAD hThread)
478{
479# ifdef RTSEMEVENT_STRICT
480 struct RTSEMEVENTINTERNAL *pThis = hEventSem;
481 AssertPtrReturnVoid(pThis);
482 AssertReturnVoid(pThis->u32Magic == RTSEMEVENT_MAGIC);
483
484 RTLockValidatorRecSharedRemoveOwner(&pThis->Signallers, hThread);
485# else
486 RT_NOREF_PV(hEventSem); RT_NOREF_PV(hThread);
487# endif
488}
489
490#endif /* IN_RING3 */
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