VirtualBox

source: vbox/trunk/src/VBox/Runtime/r0drv/linux/timer-r0drv-linux.c@ 39008

Last change on this file since 39008 was 39008, checked in by vboxsync, 13 years ago

in_atomic() was added in 2.5.32 (i386).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.4 KB
Line 
1/* $Id: timer-r0drv-linux.c 39008 2011-10-17 14:54:31Z vboxsync $ */
2/** @file
3 * IPRT - Timers, Ring-0 Driver, Linux.
4 */
5
6/*
7 * Copyright (C) 2006-2011 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 "the-linux-kernel.h"
32#include "internal/iprt.h"
33
34#include <iprt/timer.h>
35#include <iprt/time.h>
36#include <iprt/mp.h>
37#include <iprt/cpuset.h>
38#include <iprt/spinlock.h>
39#include <iprt/err.h>
40#include <iprt/asm.h>
41#include <iprt/assert.h>
42#include <iprt/alloc.h>
43
44#include "internal/magics.h"
45
46/** @def RTTIMER_LINUX_WITH_HRTIMER
47 * Whether to use high resolution timers. */
48#if !defined(RTTIMER_LINUX_WITH_HRTIMER) \
49 && defined(IPRT_LINUX_HAS_HRTIMER)
50# define RTTIMER_LINUX_WITH_HRTIMER
51#endif
52
53#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)
54# define mod_timer_pinned mod_timer
55# define HRTIMER_MODE_ABS_PINNED HRTIMER_MODE_ABS
56#endif
57
58
59/*******************************************************************************
60* Structures and Typedefs *
61*******************************************************************************/
62/**
63 * Timer state machine.
64 *
65 * This is used to try handle the issues with MP events and
66 * timers that runs on all CPUs. It's relatively nasty :-/
67 */
68typedef enum RTTIMERLNXSTATE
69{
70 /** Stopped. */
71 RTTIMERLNXSTATE_STOPPED = 0,
72 /** Transient state; next ACTIVE. */
73 RTTIMERLNXSTATE_STARTING,
74 /** Transient state; next ACTIVE. (not really necessary) */
75 RTTIMERLNXSTATE_MP_STARTING,
76 /** Active. */
77 RTTIMERLNXSTATE_ACTIVE,
78 /** Active and in callback; next ACTIVE, STOPPED or CALLBACK_DESTROYING. */
79 RTTIMERLNXSTATE_CALLBACK,
80 /** Stopped while in the callback; next STOPPED. */
81 RTTIMERLNXSTATE_CB_STOPPING,
82 /** Restarted while in the callback; next ACTIVE, STOPPED, DESTROYING. */
83 RTTIMERLNXSTATE_CB_RESTARTING,
84 /** The callback shall destroy the timer; next STOPPED. */
85 RTTIMERLNXSTATE_CB_DESTROYING,
86 /** Transient state; next STOPPED. */
87 RTTIMERLNXSTATE_STOPPING,
88 /** Transient state; next STOPPED. */
89 RTTIMERLNXSTATE_MP_STOPPING,
90 /** The usual 32-bit hack. */
91 RTTIMERLNXSTATE_32BIT_HACK = 0x7fffffff
92} RTTIMERLNXSTATE;
93
94
95/**
96 * A Linux sub-timer.
97 */
98typedef struct RTTIMERLNXSUBTIMER
99{
100 /** Timer specific data. */
101 union
102 {
103#if defined(RTTIMER_LINUX_WITH_HRTIMER)
104 /** High resolution timer. */
105 struct
106 {
107 /** The linux timer structure. */
108 struct hrtimer LnxTimer;
109 } Hr;
110#endif
111 /** Standard timer. */
112 struct
113 {
114 /** The linux timer structure. */
115 struct timer_list LnxTimer;
116 /** The start of the current run (ns).
117 * This is used to calculate when the timer ought to fire the next time. */
118 uint64_t u64NextTS;
119 /** The u64NextTS in jiffies. */
120 unsigned long ulNextJiffies;
121 /** Set when starting or changing the timer so that u64StartTs
122 * and u64NextTS gets reinitialized (eliminating some jitter). */
123 bool volatile fFirstAfterChg;
124 } Std;
125 } u;
126 /** The current tick number. */
127 uint64_t iTick;
128 /** Restart the single shot timer at this specific time.
129 * Used when a single shot timer is restarted from the callback. */
130 uint64_t volatile uNsRestartAt;
131 /** Pointer to the parent timer. */
132 PRTTIMER pParent;
133 /** The current sub-timer state. */
134 RTTIMERLNXSTATE volatile enmState;
135} RTTIMERLNXSUBTIMER;
136/** Pointer to a linux sub-timer. */
137typedef RTTIMERLNXSUBTIMER *PRTTIMERLNXSUBTIMER;
138
139
140/**
141 * The internal representation of an Linux timer handle.
142 */
143typedef struct RTTIMER
144{
145 /** Magic.
146 * This is RTTIMER_MAGIC, but changes to something else before the timer
147 * is destroyed to indicate clearly that thread should exit. */
148 uint32_t volatile u32Magic;
149 /** Spinlock synchronizing the fSuspended and MP event handling.
150 * This is NIL_RTSPINLOCK if cCpus == 1. */
151 RTSPINLOCK hSpinlock;
152 /** Flag indicating that the timer is suspended. */
153 bool volatile fSuspended;
154 /** Whether the timer must run on one specific CPU or not. */
155 bool fSpecificCpu;
156#ifdef CONFIG_SMP
157 /** Whether the timer must run on all CPUs or not. */
158 bool fAllCpus;
159#endif /* else: All -> specific on non-SMP kernels */
160 /** Whether it is a high resolution timer or a standard one. */
161 bool fHighRes;
162 /** The id of the CPU it must run on if fSpecificCpu is set. */
163 RTCPUID idCpu;
164 /** The number of CPUs this timer should run on. */
165 RTCPUID cCpus;
166 /** Callback. */
167 PFNRTTIMER pfnTimer;
168 /** User argument. */
169 void *pvUser;
170 /** The timer interval. 0 if one-shot. */
171 uint64_t volatile u64NanoInterval;
172 /** This is set to the number of jiffies between ticks if the interval is
173 * an exact number of jiffies. (Standard timers only.) */
174 unsigned long volatile cJiffies;
175 /** The change interval spinlock for standard timers only. */
176 spinlock_t ChgIntLock;
177 /** Workqueue item for delayed destruction. */
178 RTR0LNXWORKQUEUEITEM DtorWorkqueueItem;
179 /** Sub-timers.
180 * Normally there is just one, but for RTTIMER_FLAGS_CPU_ALL this will contain
181 * an entry for all possible cpus. In that case the index will be the same as
182 * for the RTCpuSet. */
183 RTTIMERLNXSUBTIMER aSubTimers[1];
184} RTTIMER;
185
186
187/**
188 * A rtTimerLinuxStartOnCpu and rtTimerLinuxStartOnCpu argument package.
189 */
190typedef struct RTTIMERLINUXSTARTONCPUARGS
191{
192 /** The current time (RTTimeSystemNanoTS). */
193 uint64_t u64Now;
194 /** When to start firing (delta). */
195 uint64_t u64First;
196} RTTIMERLINUXSTARTONCPUARGS;
197/** Pointer to a rtTimerLinuxStartOnCpu argument package. */
198typedef RTTIMERLINUXSTARTONCPUARGS *PRTTIMERLINUXSTARTONCPUARGS;
199
200
201/*******************************************************************************
202* Internal Functions *
203*******************************************************************************/
204#ifdef CONFIG_SMP
205static DECLCALLBACK(void) rtTimerLinuxMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser);
206#endif
207
208#if 0
209#define DEBUG_HACKING
210#include <iprt/string.h>
211#include <iprt/asm-amd64-x86.h>
212static void myLogBackdoorPrintf(const char *pszFormat, ...)
213{
214 char szTmp[256];
215 va_list args;
216 size_t cb;
217
218 cb = RTStrPrintf(szTmp, sizeof(szTmp) - 10, "%d: ", RTMpCpuId());
219 va_start(args, pszFormat);
220 cb += RTStrPrintfV(&szTmp[cb], sizeof(szTmp) - cb, pszFormat, args);
221 va_end(args);
222
223 ASMOutStrU8(0x504, (uint8_t *)&szTmp[0], cb);
224}
225# define RTAssertMsg1Weak(pszExpr, uLine, pszFile, pszFunction) \
226 myLogBackdoorPrintf("\n!!Guest Assertion failed!!\n%s(%d) %s\n%s\n", uLine, pszFile, pszFunction, (pszExpr))
227# define RTAssertMsg2Weak myLogBackdoorPrintf
228# define RTTIMERLNX_LOG(a) myLogBackdoorPrintf a
229#else
230# define RTTIMERLNX_LOG(a) do { } while (0)
231#endif
232
233/**
234 * Sets the state.
235 */
236DECLINLINE(void) rtTimerLnxSetState(RTTIMERLNXSTATE volatile *penmState, RTTIMERLNXSTATE enmNewState)
237{
238#ifdef DEBUG_HACKING
239 RTTIMERLNX_LOG(("set %d -> %d\n", *penmState, enmNewState));
240#endif
241 ASMAtomicWriteU32((uint32_t volatile *)penmState, enmNewState);
242}
243
244
245/**
246 * Sets the state if it has a certain value.
247 *
248 * @return true if xchg was done.
249 * @return false if xchg wasn't done.
250 */
251#ifdef DEBUG_HACKING
252#define rtTimerLnxCmpXchgState(penmState, enmNewState, enmCurState) rtTimerLnxCmpXchgStateDebug(penmState, enmNewState, enmCurState, __LINE__)
253static bool rtTimerLnxCmpXchgStateDebug(RTTIMERLNXSTATE volatile *penmState, RTTIMERLNXSTATE enmNewState,
254 RTTIMERLNXSTATE enmCurState, uint32_t uLine)
255{
256 RTTIMERLNXSTATE enmOldState = enmCurState;
257 bool fRc = ASMAtomicCmpXchgExU32((uint32_t volatile *)penmState, enmNewState, enmCurState, (uint32_t *)&enmOldState);
258 RTTIMERLNX_LOG(("cxg %d -> %d - %d at %u\n", enmOldState, enmNewState, fRc, uLine));
259 return fRc;
260}
261#else
262DECLINLINE(bool) rtTimerLnxCmpXchgState(RTTIMERLNXSTATE volatile *penmState, RTTIMERLNXSTATE enmNewState,
263 RTTIMERLNXSTATE enmCurState)
264{
265 return ASMAtomicCmpXchgU32((uint32_t volatile *)penmState, enmNewState, enmCurState);
266}
267#endif
268
269
270/**
271 * Gets the state.
272 */
273DECLINLINE(RTTIMERLNXSTATE) rtTimerLnxGetState(RTTIMERLNXSTATE volatile *penmState)
274{
275 return (RTTIMERLNXSTATE)ASMAtomicUoReadU32((uint32_t volatile *)penmState);
276}
277
278#ifdef RTTIMER_LINUX_WITH_HRTIMER
279
280/**
281 * Converts a nano second time stamp to ktime_t.
282 *
283 * ASSUMES RTTimeSystemNanoTS() is implemented using ktime_get_ts().
284 *
285 * @returns ktime_t.
286 * @param cNanoSecs Nanoseconds.
287 */
288DECLINLINE(ktime_t) rtTimerLnxNanoToKt(uint64_t cNanoSecs)
289{
290 /* With some luck the compiler optimizes the division out of this... (Bet it doesn't.) */
291 return ktime_set(cNanoSecs / 1000000000, cNanoSecs % 1000000000);
292}
293
294/**
295 * Converts ktime_t to a nano second time stamp.
296 *
297 * ASSUMES RTTimeSystemNanoTS() is implemented using ktime_get_ts().
298 *
299 * @returns nano second time stamp.
300 * @param Kt ktime_t.
301 */
302DECLINLINE(uint64_t) rtTimerLnxKtToNano(ktime_t Kt)
303{
304 return ktime_to_ns(Kt);
305}
306
307#endif /* RTTIMER_LINUX_WITH_HRTIMER */
308
309/**
310 * Converts a nano second interval to jiffies.
311 *
312 * @returns Jiffies.
313 * @param cNanoSecs Nanoseconds.
314 */
315DECLINLINE(unsigned long) rtTimerLnxNanoToJiffies(uint64_t cNanoSecs)
316{
317 /* this can be made even better... */
318 if (cNanoSecs > (uint64_t)TICK_NSEC * MAX_JIFFY_OFFSET)
319 return MAX_JIFFY_OFFSET;
320# if ARCH_BITS == 32
321 if (RT_LIKELY(cNanoSecs <= UINT32_MAX))
322 return ((uint32_t)cNanoSecs + (TICK_NSEC-1)) / TICK_NSEC;
323# endif
324 return (cNanoSecs + (TICK_NSEC-1)) / TICK_NSEC;
325}
326
327
328/**
329 * Starts a sub-timer (RTTimerStart).
330 *
331 * @param pSubTimer The sub-timer to start.
332 * @param u64Now The current timestamp (RTTimeSystemNanoTS()).
333 * @param u64First The interval from u64Now to the first time the timer should fire.
334 * @param fPinned true = timer pinned to a specific CPU,
335 * false = timer can migrate between CPUs
336 * @param fHighRes Whether the user requested a high resolution timer or not.
337 * @param enmOldState The old timer state.
338 */
339static void rtTimerLnxStartSubTimer(PRTTIMERLNXSUBTIMER pSubTimer, uint64_t u64Now, uint64_t u64First,
340 bool fPinned, bool fHighRes)
341{
342 /*
343 * Calc when it should start firing.
344 */
345 uint64_t u64NextTS = u64Now + u64First;
346 if (!fHighRes)
347 pSubTimer->u.Std.u64NextTS = u64NextTS;
348 RTTIMERLNX_LOG(("startsubtimer %p\n", pSubTimer->pParent));
349
350 pSubTimer->iTick = 0;
351
352#ifdef RTTIMER_LINUX_WITH_HRTIMER
353 if (fHighRes)
354 hrtimer_start(&pSubTimer->u.Hr.LnxTimer, rtTimerLnxNanoToKt(u64NextTS),
355 fPinned ? HRTIMER_MODE_ABS_PINNED : HRTIMER_MODE_ABS);
356 else
357#endif
358 {
359 unsigned long cJiffies = !u64First ? 0 : rtTimerLnxNanoToJiffies(u64First);
360 pSubTimer->u.Std.ulNextJiffies = jiffies + cJiffies;
361 pSubTimer->u.Std.fFirstAfterChg = true;
362#ifdef CONFIG_SMP
363 if (fPinned)
364 mod_timer_pinned(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
365 else
366#endif
367 mod_timer(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
368 }
369
370 /* Be a bit careful here since we could be racing the callback. */
371 if (!rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_STARTING))
372 rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_MP_STARTING);
373}
374
375
376/**
377 * Stops a sub-timer (RTTimerStart and rtTimerLinuxMpEvent()).
378 *
379 * The caller has already changed the state, so we will not be in a callback
380 * situation wrt to the calling thread.
381 *
382 * @param pSubTimer The sub-timer.
383 * @param fHighRes Whether the user requested a high resolution timer or not.
384 */
385static void rtTimerLnxStopSubTimer(PRTTIMERLNXSUBTIMER pSubTimer, bool fHighRes)
386{
387 RTTIMERLNX_LOG(("stopsubtimer %p %d\n", pSubTimer->pParent, fHighRes));
388#ifdef RTTIMER_LINUX_WITH_HRTIMER
389 if (fHighRes)
390 {
391 /* There is no equivalent to del_timer in the hrtimer API,
392 hrtimer_cancel() == del_timer_sync(). Just like the WARN_ON in
393 del_timer_sync() asserts, waiting for a timer callback to complete
394 is deadlock prone, so don't do it. */
395 int rc = hrtimer_try_to_cancel(&pSubTimer->u.Hr.LnxTimer);
396 if (rc < 0)
397 {
398 hrtimer_start(&pSubTimer->u.Hr.LnxTimer, ktime_set(KTIME_SEC_MAX, 0), HRTIMER_MODE_ABS);
399 hrtimer_try_to_cancel(&pSubTimer->u.Hr.LnxTimer);
400 }
401 }
402 else
403#endif
404 del_timer(&pSubTimer->u.Std.LnxTimer);
405
406 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED);
407}
408
409
410/**
411 * Used by RTTimerDestroy and rtTimerLnxCallbackDestroy to do the actual work.
412 *
413 * @param pTimer The timer in question.
414 */
415static void rtTimerLnxDestroyIt(PRTTIMER pTimer)
416{
417 RTSPINLOCK hSpinlock = pTimer->hSpinlock;
418 RTCPUID iCpu;
419 Assert(pTimer->fSuspended);
420 RTTIMERLNX_LOG(("destroyit %p\n", pTimer));
421
422 /*
423 * Remove the MP notifications first because it'll reduce the risk of
424 * us overtaking any MP event that might theoretically be racing us here.
425 */
426#ifdef CONFIG_SMP
427 if ( pTimer->cCpus > 1
428 && hSpinlock != NIL_RTSPINLOCK)
429 {
430 int rc = RTMpNotificationDeregister(rtTimerLinuxMpEvent, pTimer);
431 AssertRC(rc);
432 }
433#endif /* CONFIG_SMP */
434
435 /*
436 * Invalidate the handle.
437 */
438 ASMAtomicWriteU32(&pTimer->u32Magic, ~RTTIMER_MAGIC);
439
440 /*
441 * Make sure all timers have stopped executing since we're stopping them in
442 * an asynchronous manner up in rtTimerLnxStopSubTimer.
443 */
444 iCpu = pTimer->cCpus;
445 while (iCpu-- > 0)
446 {
447#ifdef RTTIMER_LINUX_WITH_HRTIMER
448 if (pTimer->fHighRes)
449 hrtimer_cancel(&pTimer->aSubTimers[iCpu].u.Hr.LnxTimer);
450 else
451#endif
452 del_timer_sync(&pTimer->aSubTimers[iCpu].u.Std.LnxTimer);
453 }
454
455 /*
456 * Finally, free the resources.
457 */
458 RTMemFreeEx(pTimer, RT_OFFSETOF(RTTIMER, aSubTimers[pTimer->cCpus]));
459 if (hSpinlock != NIL_RTSPINLOCK)
460 RTSpinlockDestroy(hSpinlock);
461}
462
463
464/**
465 * Workqueue callback (no DECLCALLBACK!) for deferred destruction.
466 *
467 * @param pWork Pointer to the DtorWorkqueueItem member of our timer
468 * structure.
469 */
470static void rtTimerLnxDestroyDeferred(RTR0LNXWORKQUEUEITEM *pWork)
471{
472 PRTTIMER pTimer = RT_FROM_MEMBER(pWork, RTTIMER, DtorWorkqueueItem);
473 rtTimerLnxDestroyIt(pTimer);
474}
475
476
477/**
478 * Called when the timer was destroyed by the callback function.
479 *
480 * @param pTimer The timer.
481 * @param pSubTimer The sub-timer which we're handling, the state of this
482 * will be RTTIMERLNXSTATE_CALLBACK_DESTROYING.
483 */
484static void rtTimerLnxCallbackDestroy(PRTTIMER pTimer, PRTTIMERLNXSUBTIMER pSubTimer)
485{
486 /*
487 * If it's an omni timer, the last dude does the destroying.
488 */
489 if (pTimer->cCpus > 1)
490 {
491 uint32_t iCpu = pTimer->cCpus;
492 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
493 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
494
495 Assert(pSubTimer->enmState == RTTIMERLNXSTATE_CB_DESTROYING);
496 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED);
497
498 while (iCpu-- > 0)
499 if (rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState) != RTTIMERLNXSTATE_STOPPED)
500 {
501 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
502 return;
503 }
504
505 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
506 }
507
508 /*
509 * Destroying a timer from the callback is unsafe since the callout code
510 * might be touching the timer structure upon return (hrtimer does!). So,
511 * we have to defer the actual destruction to the IRPT workqueue.
512 */
513 rtR0LnxWorkqueuePush(&pTimer->DtorWorkqueueItem, rtTimerLnxDestroyDeferred);
514}
515
516
517#ifdef CONFIG_SMP
518/**
519 * Deal with a sub-timer that has migrated.
520 *
521 * @param pTimer The timer.
522 * @param pSubTimer The sub-timer.
523 */
524static void rtTimerLnxCallbackHandleMigration(PRTTIMER pTimer, PRTTIMERLNXSUBTIMER pSubTimer)
525{
526 RTTIMERLNXSTATE enmState;
527 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
528 if (pTimer->cCpus > 1)
529 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
530
531 do
532 {
533 enmState = rtTimerLnxGetState(&pSubTimer->enmState);
534 switch (enmState)
535 {
536 case RTTIMERLNXSTATE_STOPPING:
537 case RTTIMERLNXSTATE_MP_STOPPING:
538 enmState = RTTIMERLNXSTATE_STOPPED;
539 case RTTIMERLNXSTATE_STOPPED:
540 break;
541
542 default:
543 AssertMsgFailed(("%d\n", enmState));
544 case RTTIMERLNXSTATE_STARTING:
545 case RTTIMERLNXSTATE_MP_STARTING:
546 case RTTIMERLNXSTATE_ACTIVE:
547 case RTTIMERLNXSTATE_CALLBACK:
548 case RTTIMERLNXSTATE_CB_STOPPING:
549 case RTTIMERLNXSTATE_CB_RESTARTING:
550 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, enmState))
551 enmState = RTTIMERLNXSTATE_STOPPED;
552 break;
553
554 case RTTIMERLNXSTATE_CB_DESTROYING:
555 {
556 if (pTimer->cCpus > 1)
557 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
558
559 rtTimerLnxCallbackDestroy(pTimer, pSubTimer);
560 return;
561 }
562 }
563 } while (enmState != RTTIMERLNXSTATE_STOPPED);
564
565 if (pTimer->cCpus > 1)
566 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
567}
568#endif /* CONFIG_SMP */
569
570
571/**
572 * The slow path of rtTimerLnxChangeToCallbackState.
573 *
574 * @returns true if changed successfully, false if not.
575 * @param pSubTimer The sub-timer.
576 */
577static bool rtTimerLnxChangeToCallbackStateSlow(PRTTIMERLNXSUBTIMER pSubTimer)
578{
579 for (;;)
580 {
581 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pSubTimer->enmState);
582 switch (enmState)
583 {
584 case RTTIMERLNXSTATE_ACTIVE:
585 case RTTIMERLNXSTATE_STARTING:
586 case RTTIMERLNXSTATE_MP_STARTING:
587 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_CALLBACK, enmState))
588 return true;
589 break;
590
591 case RTTIMERLNXSTATE_CALLBACK:
592 case RTTIMERLNXSTATE_CB_STOPPING:
593 case RTTIMERLNXSTATE_CB_RESTARTING:
594 case RTTIMERLNXSTATE_CB_DESTROYING:
595 AssertMsgFailed(("%d\n", enmState));
596 default:
597 return false;
598 }
599 ASMNopPause();
600 }
601}
602
603
604/**
605 * Tries to change the sub-timer state to 'callback'.
606 *
607 * @returns true if changed successfully, false if not.
608 * @param pSubTimer The sub-timer.
609 */
610DECLINLINE(bool) rtTimerLnxChangeToCallbackState(PRTTIMERLNXSUBTIMER pSubTimer)
611{
612 if (RT_LIKELY(rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_CALLBACK, RTTIMERLNXSTATE_ACTIVE)))
613 return true;
614 return rtTimerLnxChangeToCallbackStateSlow(pSubTimer);
615}
616
617
618#ifdef RTTIMER_LINUX_WITH_HRTIMER
619/**
620 * Timer callback function for high resolution timers.
621 *
622 * @returns HRTIMER_NORESTART or HRTIMER_RESTART depending on whether it's a
623 * one-shot or interval timer.
624 * @param pHrTimer Pointer to the sub-timer structure.
625 */
626static enum hrtimer_restart rtTimerLinuxHrCallback(struct hrtimer *pHrTimer)
627{
628 PRTTIMERLNXSUBTIMER pSubTimer = RT_FROM_MEMBER(pHrTimer, RTTIMERLNXSUBTIMER, u.Hr.LnxTimer);
629 PRTTIMER pTimer = pSubTimer->pParent;
630
631
632 RTTIMERLNX_LOG(("hrcallback %p\n", pTimer));
633 if (RT_UNLIKELY(!rtTimerLnxChangeToCallbackState(pSubTimer)))
634 return HRTIMER_NORESTART;
635
636#ifdef CONFIG_SMP
637 /*
638 * Check for unwanted migration.
639 */
640 if (pTimer->fAllCpus || pTimer->fSpecificCpu)
641 {
642 RTCPUID idCpu = RTMpCpuId();
643 if (RT_UNLIKELY( pTimer->fAllCpus
644 ? (RTCPUID)(pSubTimer - &pTimer->aSubTimers[0]) != idCpu
645 : pTimer->idCpu != idCpu))
646 {
647 rtTimerLnxCallbackHandleMigration(pTimer, pSubTimer);
648 return HRTIMER_NORESTART;
649 }
650 }
651#endif
652
653 if (pTimer->u64NanoInterval)
654 {
655 /*
656 * Periodic timer, run it and update the native timer afterwards so
657 * we can handle RTTimerStop and RTTimerChangeInterval from the
658 * callback as well as a racing control thread.
659 */
660 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pSubTimer->iTick);
661 hrtimer_add_expires_ns(&pSubTimer->u.Hr.LnxTimer, ASMAtomicReadU64(&pTimer->u64NanoInterval));
662 if (RT_LIKELY(rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_CALLBACK)))
663 return HRTIMER_RESTART;
664 }
665 else
666 {
667 /*
668 * One shot timer (no omni), stop it before dispatching it.
669 * Allow RTTimerStart as well as RTTimerDestroy to be called from
670 * the callback.
671 */
672 ASMAtomicWriteBool(&pTimer->fSuspended, true);
673 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pSubTimer->iTick);
674 if (RT_LIKELY(rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_CALLBACK)))
675 return HRTIMER_NORESTART;
676 }
677
678 /*
679 * Some state change occurred while we were in the callback routine.
680 */
681 for (;;)
682 {
683 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pSubTimer->enmState);
684 switch (enmState)
685 {
686 case RTTIMERLNXSTATE_CB_DESTROYING:
687 rtTimerLnxCallbackDestroy(pTimer, pSubTimer);
688 return HRTIMER_NORESTART;
689
690 case RTTIMERLNXSTATE_CB_STOPPING:
691 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_CB_STOPPING))
692 return HRTIMER_NORESTART;
693 break;
694
695 case RTTIMERLNXSTATE_CB_RESTARTING:
696 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_CB_RESTARTING))
697 {
698 pSubTimer->iTick = 0;
699 hrtimer_set_expires(&pSubTimer->u.Hr.LnxTimer, rtTimerLnxNanoToKt(pSubTimer->uNsRestartAt));
700 return HRTIMER_RESTART;
701 }
702 break;
703
704 default:
705 AssertMsgFailed(("%d\n", enmState));
706 return HRTIMER_NORESTART;
707 }
708 ASMNopPause();
709 }
710}
711#endif /* RTTIMER_LINUX_WITH_HRTIMER */
712
713
714/**
715 * Timer callback function for standard timers.
716 *
717 * @param ulUser Address of the sub-timer structure.
718 */
719static void rtTimerLinuxStdCallback(unsigned long ulUser)
720{
721 PRTTIMERLNXSUBTIMER pSubTimer = (PRTTIMERLNXSUBTIMER)ulUser;
722 PRTTIMER pTimer = pSubTimer->pParent;
723
724 RTTIMERLNX_LOG(("stdcallback %p\n", pTimer));
725 if (RT_UNLIKELY(!rtTimerLnxChangeToCallbackState(pSubTimer)))
726 return;
727
728#ifdef CONFIG_SMP
729 /*
730 * Check for unwanted migration.
731 */
732 if (pTimer->fAllCpus || pTimer->fSpecificCpu)
733 {
734 RTCPUID idCpu = RTMpCpuId();
735 if (RT_UNLIKELY( pTimer->fAllCpus
736 ? (RTCPUID)(pSubTimer - &pTimer->aSubTimers[0]) != idCpu
737 : pTimer->idCpu != idCpu))
738 {
739 rtTimerLnxCallbackHandleMigration(pTimer, pSubTimer);
740 return;
741 }
742 }
743#endif
744
745 if (pTimer->u64NanoInterval)
746 {
747 /*
748 * Interval timer, calculate the next timeout.
749 *
750 * The first time around, we'll re-adjust the u.Std.u64NextTS to
751 * try prevent some jittering if we were started at a bad time.
752 */
753 const uint64_t iTick = ++pSubTimer->iTick;
754 uint64_t u64NanoInterval;
755 unsigned long cJiffies;
756 unsigned long flFlags;
757
758 spin_lock_irqsave(&pTimer->ChgIntLock, flFlags);
759 u64NanoInterval = pTimer->u64NanoInterval;
760 cJiffies = pTimer->cJiffies;
761 if (RT_UNLIKELY(pSubTimer->u.Std.fFirstAfterChg))
762 {
763 pSubTimer->u.Std.fFirstAfterChg = false;
764 pSubTimer->u.Std.u64NextTS = RTTimeSystemNanoTS();
765 pSubTimer->u.Std.ulNextJiffies = jiffies;
766 }
767 spin_unlock_irqrestore(&pTimer->ChgIntLock, flFlags);
768
769 pSubTimer->u.Std.u64NextTS += u64NanoInterval;
770 if (cJiffies)
771 {
772 pSubTimer->u.Std.ulNextJiffies += cJiffies;
773 /* Prevent overflows when the jiffies counter wraps around.
774 * Special thanks to Ken Preslan for helping debugging! */
775 while (time_before(pSubTimer->u.Std.ulNextJiffies, jiffies))
776 {
777 pSubTimer->u.Std.ulNextJiffies += cJiffies;
778 pSubTimer->u.Std.u64NextTS += u64NanoInterval;
779 }
780 }
781 else
782 {
783 const uint64_t u64NanoTS = RTTimeSystemNanoTS();
784 while (pSubTimer->u.Std.u64NextTS < u64NanoTS)
785 pSubTimer->u.Std.u64NextTS += u64NanoInterval;
786 pSubTimer->u.Std.ulNextJiffies = jiffies + rtTimerLnxNanoToJiffies(pSubTimer->u.Std.u64NextTS - u64NanoTS);
787 }
788
789 /*
790 * Run the timer and re-arm it unless the state changed .
791 * .
792 * We must re-arm it afterwards as we're not in a position to undo this .
793 * operation if for instance someone stopped or destroyed us while we .
794 * were in the callback. (Linux takes care of any races here.)
795 */
796 pTimer->pfnTimer(pTimer, pTimer->pvUser, iTick);
797 if (RT_LIKELY(rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_CALLBACK)))
798 {
799#ifdef CONFIG_SMP
800 if (pTimer->fSpecificCpu || pTimer->fAllCpus)
801 mod_timer_pinned(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
802 else
803#endif
804 mod_timer(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
805 return;
806 }
807 }
808 else
809 {
810 /*
811 * One shot timer, stop it before dispatching it.
812 * Allow RTTimerStart as well as RTTimerDestroy to be called from
813 * the callback.
814 */
815 ASMAtomicWriteBool(&pTimer->fSuspended, true);
816 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pSubTimer->iTick);
817 if (RT_LIKELY(rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_CALLBACK)))
818 return;
819 }
820
821 /*
822 * Some state change occurred while we were in the callback routine.
823 */
824 for (;;)
825 {
826 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pSubTimer->enmState);
827 switch (enmState)
828 {
829 case RTTIMERLNXSTATE_CB_DESTROYING:
830 rtTimerLnxCallbackDestroy(pTimer, pSubTimer);
831 return;
832
833 case RTTIMERLNXSTATE_CB_STOPPING:
834 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_CB_STOPPING))
835 return;
836 break;
837
838 case RTTIMERLNXSTATE_CB_RESTARTING:
839 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE, RTTIMERLNXSTATE_CB_RESTARTING))
840 {
841 uint64_t u64NanoTS;
842 uint64_t u64NextTS;
843 unsigned long flFlags;
844
845 spin_lock_irqsave(&pTimer->ChgIntLock, flFlags);
846 u64NextTS = pSubTimer->uNsRestartAt;
847 u64NanoTS = RTTimeSystemNanoTS();
848 pSubTimer->iTick = 0;
849 pSubTimer->u.Std.u64NextTS = u64NextTS;
850 pSubTimer->u.Std.fFirstAfterChg = true;
851 pSubTimer->u.Std.ulNextJiffies = u64NextTS > u64NanoTS
852 ? jiffies + rtTimerLnxNanoToJiffies(u64NextTS - u64NanoTS)
853 : jiffies;
854 spin_unlock_irqrestore(&pTimer->ChgIntLock, flFlags);
855
856#ifdef CONFIG_SMP
857 if (pTimer->fSpecificCpu || pTimer->fAllCpus)
858 mod_timer_pinned(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
859 else
860#endif
861 mod_timer(&pSubTimer->u.Std.LnxTimer, pSubTimer->u.Std.ulNextJiffies);
862 return;
863 }
864 break;
865
866 default:
867 AssertMsgFailed(("%d\n", enmState));
868 return;
869 }
870 ASMNopPause();
871 }
872}
873
874
875#ifdef CONFIG_SMP
876
877/**
878 * Per-cpu callback function (RTMpOnAll/RTMpOnSpecific).
879 *
880 * @param idCpu The current CPU.
881 * @param pvUser1 Pointer to the timer.
882 * @param pvUser2 Pointer to the argument structure.
883 */
884static DECLCALLBACK(void) rtTimerLnxStartAllOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
885{
886 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
887 PRTTIMER pTimer = (PRTTIMER)pvUser1;
888 Assert(idCpu < pTimer->cCpus);
889 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[idCpu], pArgs->u64Now, pArgs->u64First, true /*fPinned*/, pTimer->fHighRes);
890}
891
892
893/**
894 * Worker for RTTimerStart() that takes care of the ugly bits.
895 *
896 * @returns RTTimerStart() return value.
897 * @param pTimer The timer.
898 * @param pArgs The argument structure.
899 */
900static int rtTimerLnxOmniStart(PRTTIMER pTimer, PRTTIMERLINUXSTARTONCPUARGS pArgs)
901{
902 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
903 RTCPUID iCpu;
904 RTCPUSET OnlineSet;
905 RTCPUSET OnlineSet2;
906 int rc2;
907
908 /*
909 * Prepare all the sub-timers for the startup and then flag the timer
910 * as a whole as non-suspended, make sure we get them all before
911 * clearing fSuspended as the MP handler will be waiting on this
912 * should something happen while we're looping.
913 */
914 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
915
916 /* Just make it a omni timer restriction that no stop/start races are allowed. */
917 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
918 if (rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState) != RTTIMERLNXSTATE_STOPPED)
919 {
920 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
921 return VERR_TIMER_BUSY;
922 }
923
924 do
925 {
926 RTMpGetOnlineSet(&OnlineSet);
927 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
928 {
929 Assert(pTimer->aSubTimers[iCpu].enmState != RTTIMERLNXSTATE_MP_STOPPING);
930 rtTimerLnxSetState(&pTimer->aSubTimers[iCpu].enmState,
931 RTCpuSetIsMember(&OnlineSet, iCpu)
932 ? RTTIMERLNXSTATE_STARTING
933 : RTTIMERLNXSTATE_STOPPED);
934 }
935 } while (!RTCpuSetIsEqual(&OnlineSet, RTMpGetOnlineSet(&OnlineSet2)));
936
937 ASMAtomicWriteBool(&pTimer->fSuspended, false);
938
939 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
940
941 /*
942 * Start them (can't find any exported function that allows me to
943 * do this without the cross calls).
944 */
945 pArgs->u64Now = RTTimeSystemNanoTS();
946 rc2 = RTMpOnAll(rtTimerLnxStartAllOnCpu, pTimer, pArgs);
947 AssertRC(rc2); /* screw this if it fails. */
948
949 /*
950 * Reset the sub-timers who didn't start up (ALL CPUs case).
951 */
952 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
953
954 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
955 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_STARTING))
956 {
957 /** @todo very odd case for a rainy day. Cpus that temporarily went offline while
958 * we were between calls needs to nudged as the MP handler will ignore events for
959 * them because of the STARTING state. This is an extremely unlikely case - not that
960 * that means anything in my experience... ;-) */
961 RTTIMERLNX_LOG(("what!? iCpu=%u -> didn't start\n", iCpu));
962 }
963
964 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
965
966 return VINF_SUCCESS;
967}
968
969
970/**
971 * Worker for RTTimerStop() that takes care of the ugly SMP bits.
972 *
973 * @returns true if there was any active callbacks, false if not.
974 * @param pTimer The timer (valid).
975 * @param fForDestroy Whether this is for RTTimerDestroy or not.
976 */
977static bool rtTimerLnxOmniStop(PRTTIMER pTimer, bool fForDestroy)
978{
979 bool fActiveCallbacks = false;
980 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
981 RTCPUID iCpu;
982 RTTIMERLNXSTATE enmState;
983
984
985 /*
986 * Mark the timer as suspended and flag all timers as stopping, except
987 * for those being stopped by an MP event.
988 */
989 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
990
991 ASMAtomicWriteBool(&pTimer->fSuspended, true);
992 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
993 {
994 for (;;)
995 {
996 enmState = rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState);
997 if ( enmState == RTTIMERLNXSTATE_STOPPED
998 || enmState == RTTIMERLNXSTATE_MP_STOPPING)
999 break;
1000 if ( enmState == RTTIMERLNXSTATE_CALLBACK
1001 || enmState == RTTIMERLNXSTATE_CB_STOPPING
1002 || enmState == RTTIMERLNXSTATE_CB_RESTARTING)
1003 {
1004 Assert(enmState != RTTIMERLNXSTATE_CB_STOPPING || fForDestroy);
1005 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState,
1006 !fForDestroy ? RTTIMERLNXSTATE_CB_STOPPING : RTTIMERLNXSTATE_CB_DESTROYING,
1007 enmState))
1008 {
1009 fActiveCallbacks = true;
1010 break;
1011 }
1012 }
1013 else
1014 {
1015 Assert(enmState == RTTIMERLNXSTATE_ACTIVE);
1016 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState, RTTIMERLNXSTATE_STOPPING, enmState))
1017 break;
1018 }
1019 ASMNopPause();
1020 }
1021 }
1022
1023 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
1024
1025 /*
1026 * Do the actual stopping. Fortunately, this doesn't require any IPIs.
1027 * Unfortunately it cannot be done synchronously.
1028 */
1029 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
1030 if (rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState) == RTTIMERLNXSTATE_STOPPING)
1031 rtTimerLnxStopSubTimer(&pTimer->aSubTimers[iCpu], pTimer->fHighRes);
1032
1033 return fActiveCallbacks;
1034}
1035
1036
1037/**
1038 * Per-cpu callback function (RTMpOnSpecific) used by rtTimerLinuxMpEvent()
1039 * to start a sub-timer on a cpu that just have come online.
1040 *
1041 * @param idCpu The current CPU.
1042 * @param pvUser1 Pointer to the timer.
1043 * @param pvUser2 Pointer to the argument structure.
1044 */
1045static DECLCALLBACK(void) rtTimerLinuxMpStartOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1046{
1047 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
1048 PRTTIMER pTimer = (PRTTIMER)pvUser1;
1049 RTSPINLOCK hSpinlock;
1050 Assert(idCpu < pTimer->cCpus);
1051
1052 /*
1053 * We have to be kind of careful here as we might be racing RTTimerStop
1054 * (and/or RTTimerDestroy, thus the paranoia.
1055 */
1056 hSpinlock = pTimer->hSpinlock;
1057 if ( hSpinlock != NIL_RTSPINLOCK
1058 && pTimer->u32Magic == RTTIMER_MAGIC)
1059 {
1060 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
1061 RTSpinlockAcquire(hSpinlock, &Tmp);
1062
1063 if ( !ASMAtomicUoReadBool(&pTimer->fSuspended)
1064 && pTimer->u32Magic == RTTIMER_MAGIC)
1065 {
1066 /* We're sane and the timer is not suspended yet. */
1067 PRTTIMERLNXSUBTIMER pSubTimer = &pTimer->aSubTimers[idCpu];
1068 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STARTING, RTTIMERLNXSTATE_STOPPED))
1069 rtTimerLnxStartSubTimer(pSubTimer, pArgs->u64Now, pArgs->u64First, true /*fPinned*/, pTimer->fHighRes);
1070 }
1071
1072 RTSpinlockRelease(hSpinlock, &Tmp);
1073 }
1074}
1075
1076
1077/**
1078 * MP event notification callback.
1079 *
1080 * @param enmEvent The event.
1081 * @param idCpu The cpu it applies to.
1082 * @param pvUser The timer.
1083 */
1084static DECLCALLBACK(void) rtTimerLinuxMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser)
1085{
1086 PRTTIMER pTimer = (PRTTIMER)pvUser;
1087 PRTTIMERLNXSUBTIMER pSubTimer = &pTimer->aSubTimers[idCpu];
1088 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
1089 RTSPINLOCK hSpinlock;
1090
1091 Assert(idCpu < pTimer->cCpus);
1092
1093 /*
1094 * Some initial paranoia.
1095 */
1096 if (pTimer->u32Magic != RTTIMER_MAGIC)
1097 return;
1098 hSpinlock = pTimer->hSpinlock;
1099 if (hSpinlock == NIL_RTSPINLOCK)
1100 return;
1101
1102 RTSpinlockAcquire(hSpinlock, &Tmp);
1103
1104 /* Is it active? */
1105 if ( !ASMAtomicUoReadBool(&pTimer->fSuspended)
1106 && pTimer->u32Magic == RTTIMER_MAGIC)
1107 {
1108 switch (enmEvent)
1109 {
1110 /*
1111 * Try do it without leaving the spin lock, but if we have to, retake it
1112 * when we're on the right cpu.
1113 */
1114 case RTMPEVENT_ONLINE:
1115 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STARTING, RTTIMERLNXSTATE_STOPPED))
1116 {
1117 RTTIMERLINUXSTARTONCPUARGS Args;
1118 Args.u64Now = RTTimeSystemNanoTS();
1119 Args.u64First = 0;
1120
1121 if (RTMpCpuId() == idCpu)
1122 rtTimerLnxStartSubTimer(pSubTimer, Args.u64Now, Args.u64First, true /*fPinned*/, pTimer->fHighRes);
1123 else
1124 {
1125 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED); /* we'll recheck it. */
1126 RTSpinlockRelease(hSpinlock, &Tmp);
1127
1128 RTMpOnSpecific(idCpu, rtTimerLinuxMpStartOnCpu, pTimer, &Args);
1129 return; /* we've left the spinlock */
1130 }
1131 }
1132 break;
1133
1134 /*
1135 * The CPU is (going) offline, make sure the sub-timer is stopped.
1136 *
1137 * Linux will migrate it to a different CPU, but we don't want this. The
1138 * timer function is checking for this.
1139 */
1140 case RTMPEVENT_OFFLINE:
1141 {
1142 RTTIMERLNXSTATE enmState;
1143 while ( (enmState = rtTimerLnxGetState(&pSubTimer->enmState)) == RTTIMERLNXSTATE_ACTIVE
1144 || enmState == RTTIMERLNXSTATE_CALLBACK
1145 || enmState == RTTIMERLNXSTATE_CB_RESTARTING)
1146 {
1147 if (enmState == RTTIMERLNXSTATE_ACTIVE)
1148 {
1149 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STOPPING, RTTIMERLNXSTATE_ACTIVE))
1150 {
1151 RTSpinlockRelease(hSpinlock, &Tmp);
1152
1153 rtTimerLnxStopSubTimer(pSubTimer, pTimer->fHighRes);
1154 return; /* we've left the spinlock */
1155 }
1156 }
1157 else if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_CB_STOPPING, enmState))
1158 break;
1159
1160 /* State not stable, try again. */
1161 ASMNopPause();
1162 }
1163 break;
1164 }
1165 }
1166 }
1167
1168 RTSpinlockRelease(hSpinlock, &Tmp);
1169}
1170
1171#endif /* CONFIG_SMP */
1172
1173
1174/**
1175 * Callback function use by RTTimerStart via RTMpOnSpecific to start a timer
1176 * running on a specific CPU.
1177 *
1178 * @param idCpu The current CPU.
1179 * @param pvUser1 Pointer to the timer.
1180 * @param pvUser2 Pointer to the argument structure.
1181 */
1182static DECLCALLBACK(void) rtTimerLnxStartOnSpecificCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1183{
1184 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
1185 PRTTIMER pTimer = (PRTTIMER)pvUser1;
1186 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[0], pArgs->u64Now, pArgs->u64First, true /*fPinned*/, pTimer->fHighRes);
1187}
1188
1189
1190RTDECL(int) RTTimerStart(PRTTIMER pTimer, uint64_t u64First)
1191{
1192 RTTIMERLINUXSTARTONCPUARGS Args;
1193 int rc2;
1194
1195 /*
1196 * Validate.
1197 */
1198 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
1199 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
1200
1201 if (!ASMAtomicUoReadBool(&pTimer->fSuspended))
1202 return VERR_TIMER_ACTIVE;
1203 RTTIMERLNX_LOG(("start %p cCpus=%d\n", pTimer, pTimer->cCpus));
1204
1205 Args.u64First = u64First;
1206#ifdef CONFIG_SMP
1207 /*
1208 * Omni timer?
1209 */
1210 if (pTimer->fAllCpus)
1211 return rtTimerLnxOmniStart(pTimer, &Args);
1212#endif
1213
1214 /*
1215 * Simple timer - Pretty straight forward if it wasn't for restarting.
1216 */
1217 Args.u64Now = RTTimeSystemNanoTS();
1218 ASMAtomicWriteU64(&pTimer->aSubTimers[0].uNsRestartAt, Args.u64Now + u64First);
1219 for (;;)
1220 {
1221 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pTimer->aSubTimers[0].enmState);
1222 switch (enmState)
1223 {
1224 case RTTIMERLNXSTATE_STOPPED:
1225 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STARTING, RTTIMERLNXSTATE_STOPPED))
1226 {
1227 ASMAtomicWriteBool(&pTimer->fSuspended, false);
1228 if (!pTimer->fSpecificCpu)
1229 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[0], Args.u64Now, Args.u64First,
1230 false /*fPinned*/, pTimer->fHighRes);
1231 else
1232 {
1233 rc2 = RTMpOnSpecific(pTimer->idCpu, rtTimerLnxStartOnSpecificCpu, pTimer, &Args);
1234 if (RT_FAILURE(rc2))
1235 {
1236 /* Suspend it, the cpu id is probably invalid or offline. */
1237 ASMAtomicWriteBool(&pTimer->fSuspended, true);
1238 rtTimerLnxSetState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STOPPED);
1239 return rc2;
1240 }
1241 }
1242 return VINF_SUCCESS;
1243 }
1244 break;
1245
1246 case RTTIMERLNXSTATE_CALLBACK:
1247 case RTTIMERLNXSTATE_CB_STOPPING:
1248 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_CB_RESTARTING, enmState))
1249 {
1250 ASMAtomicWriteBool(&pTimer->fSuspended, false);
1251 return VINF_SUCCESS;
1252 }
1253 break;
1254
1255 default:
1256 AssertMsgFailed(("%d\n", enmState));
1257 return VERR_INTERNAL_ERROR_4;
1258 }
1259 ASMNopPause();
1260 }
1261}
1262RT_EXPORT_SYMBOL(RTTimerStart);
1263
1264
1265/**
1266 * Common worker for RTTimerStop and RTTimerDestroy.
1267 *
1268 * @returns true if there was any active callbacks, false if not.
1269 * @param pTimer The timer to stop.
1270 * @param fForDestroy Whether it's RTTimerDestroy calling or not.
1271 */
1272static bool rtTimerLnxStop(PRTTIMER pTimer, bool fForDestroy)
1273{
1274 RTTIMERLNX_LOG(("lnxstop %p %d\n", pTimer, fForDestroy));
1275#ifdef CONFIG_SMP
1276 /*
1277 * Omni timer?
1278 */
1279 if (pTimer->fAllCpus)
1280 return rtTimerLnxOmniStop(pTimer, fForDestroy);
1281#endif
1282
1283 /*
1284 * Simple timer.
1285 */
1286 ASMAtomicWriteBool(&pTimer->fSuspended, true);
1287 for (;;)
1288 {
1289 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pTimer->aSubTimers[0].enmState);
1290 switch (enmState)
1291 {
1292 case RTTIMERLNXSTATE_ACTIVE:
1293 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STOPPING, RTTIMERLNXSTATE_ACTIVE))
1294 {
1295 rtTimerLnxStopSubTimer(&pTimer->aSubTimers[0], pTimer->fHighRes);
1296 return false;
1297 }
1298 break;
1299
1300 case RTTIMERLNXSTATE_CALLBACK:
1301 case RTTIMERLNXSTATE_CB_RESTARTING:
1302 case RTTIMERLNXSTATE_CB_STOPPING:
1303 Assert(enmState != RTTIMERLNXSTATE_CB_STOPPING || fForDestroy);
1304 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[0].enmState,
1305 !fForDestroy ? RTTIMERLNXSTATE_CB_STOPPING : RTTIMERLNXSTATE_CB_DESTROYING,
1306 enmState))
1307 return true;
1308 break;
1309
1310 case RTTIMERLNXSTATE_STOPPED:
1311 return VINF_SUCCESS;
1312
1313 case RTTIMERLNXSTATE_CB_DESTROYING:
1314 AssertMsgFailed(("enmState=%d pTimer=%p\n", enmState, pTimer));
1315 return true;
1316
1317 default:
1318 case RTTIMERLNXSTATE_STARTING:
1319 case RTTIMERLNXSTATE_MP_STARTING:
1320 case RTTIMERLNXSTATE_STOPPING:
1321 case RTTIMERLNXSTATE_MP_STOPPING:
1322 AssertMsgFailed(("enmState=%d pTimer=%p\n", enmState, pTimer));
1323 return false;
1324 }
1325
1326 /* State not stable, try again. */
1327 ASMNopPause();
1328 }
1329}
1330
1331
1332RTDECL(int) RTTimerStop(PRTTIMER pTimer)
1333{
1334 /*
1335 * Validate.
1336 */
1337 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
1338 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
1339 RTTIMERLNX_LOG(("stop %p\n", pTimer));
1340
1341 if (ASMAtomicUoReadBool(&pTimer->fSuspended))
1342 return VERR_TIMER_SUSPENDED;
1343
1344 rtTimerLnxStop(pTimer, false /*fForDestroy*/);
1345 return VINF_SUCCESS;
1346}
1347RT_EXPORT_SYMBOL(RTTimerStop);
1348
1349
1350RTDECL(int) RTTimerChangeInterval(PRTTIMER pTimer, uint64_t u64NanoInterval)
1351{
1352 unsigned long cJiffies;
1353 unsigned long flFlags;
1354
1355 /*
1356 * Validate.
1357 */
1358 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
1359 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
1360 AssertReturn(u64NanoInterval, VERR_INVALID_PARAMETER);
1361 RTTIMERLNX_LOG(("change %p %llu\n", pTimer, u64NanoInterval));
1362
1363#ifdef RTTIMER_LINUX_WITH_HRTIMER
1364 /*
1365 * For the high resolution timers it is easy since we don't care so much
1366 * about when it is applied to the sub-timers.
1367 */
1368 if (pTimer->fHighRes)
1369 {
1370 ASMAtomicWriteU64(&pTimer->u64NanoInterval, u64NanoInterval);
1371 return VINF_SUCCESS;
1372 }
1373#endif
1374
1375 /*
1376 * Standard timers have a bit more complicated way of calculating
1377 * their interval and such. So, forget omni timers for now.
1378 */
1379 if (pTimer->cCpus > 1)
1380 return VERR_NOT_SUPPORTED;
1381
1382 cJiffies = u64NanoInterval / RTTimerGetSystemGranularity();
1383 if (cJiffies * RTTimerGetSystemGranularity() != u64NanoInterval)
1384 cJiffies = 0;
1385
1386 spin_lock_irqsave(&pTimer->ChgIntLock, flFlags);
1387 pTimer->aSubTimers[0].u.Std.fFirstAfterChg = true;
1388 pTimer->cJiffies = cJiffies;
1389 ASMAtomicWriteU64(&pTimer->u64NanoInterval, u64NanoInterval);
1390 spin_unlock_irqrestore(&pTimer->ChgIntLock, flFlags);
1391 return VINF_SUCCESS;
1392}
1393RT_EXPORT_SYMBOL(RTTimerChangeInterval);
1394
1395
1396RTDECL(int) RTTimerDestroy(PRTTIMER pTimer)
1397{
1398 bool fCanDestroy;
1399
1400 /*
1401 * Validate. It's ok to pass NULL pointer.
1402 */
1403 if (pTimer == /*NIL_RTTIMER*/ NULL)
1404 return VINF_SUCCESS;
1405 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
1406 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
1407 RTTIMERLNX_LOG(("destroy %p\n", pTimer));
1408/** @todo We should invalidate the magic here! */
1409
1410 /*
1411 * Stop the timer if it's still active, then destroy it if we can.
1412 */
1413 if (!ASMAtomicUoReadBool(&pTimer->fSuspended))
1414 fCanDestroy = rtTimerLnxStop(pTimer, true /*fForDestroy*/);
1415 else
1416 {
1417 uint32_t iCpu = pTimer->cCpus;
1418 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
1419 if (pTimer->cCpus > 1)
1420 RTSpinlockAcquireNoInts(pTimer->hSpinlock, &Tmp);
1421
1422 fCanDestroy = true;
1423 while (iCpu-- > 0)
1424 {
1425 for (;;)
1426 {
1427 RTTIMERLNXSTATE enmState = rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState);
1428 switch (enmState)
1429 {
1430 case RTTIMERLNXSTATE_CALLBACK:
1431 case RTTIMERLNXSTATE_CB_RESTARTING:
1432 case RTTIMERLNXSTATE_CB_STOPPING:
1433 if (!rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState, RTTIMERLNXSTATE_CB_DESTROYING, enmState))
1434 continue;
1435 fCanDestroy = false;
1436 break;
1437
1438 case RTTIMERLNXSTATE_CB_DESTROYING:
1439 AssertMsgFailed(("%d\n", enmState));
1440 fCanDestroy = false;
1441 break;
1442 default:
1443 break;
1444 }
1445 break;
1446 }
1447 }
1448
1449 if (pTimer->cCpus > 1)
1450 RTSpinlockReleaseNoInts(pTimer->hSpinlock, &Tmp);
1451 }
1452
1453 if (fCanDestroy)
1454 {
1455 /* For paranoid reasons, defer actually destroying the semaphore when
1456 in atomic or interrupt context. */
1457#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 32)
1458 if (in_atomic() || in_interrupt())
1459#else
1460 if (in_interrupt())
1461#endif
1462 rtR0LnxWorkqueuePush(&pTimer->DtorWorkqueueItem, rtTimerLnxDestroyDeferred);
1463 else
1464 rtTimerLnxDestroyIt(pTimer);
1465 }
1466
1467 return VINF_SUCCESS;
1468}
1469RT_EXPORT_SYMBOL(RTTimerDestroy);
1470
1471
1472RTDECL(int) RTTimerCreateEx(PRTTIMER *ppTimer, uint64_t u64NanoInterval, uint32_t fFlags, PFNRTTIMER pfnTimer, void *pvUser)
1473{
1474 PRTTIMER pTimer;
1475 RTCPUID iCpu;
1476 unsigned cCpus;
1477 int rc;
1478
1479 rtR0LnxWorkqueueFlush(); /* for 2.4 */
1480 *ppTimer = NULL;
1481
1482 /*
1483 * Validate flags.
1484 */
1485 if (!RTTIMER_FLAGS_ARE_VALID(fFlags))
1486 return VERR_INVALID_PARAMETER;
1487 if ( (fFlags & RTTIMER_FLAGS_CPU_SPECIFIC)
1488 && (fFlags & RTTIMER_FLAGS_CPU_ALL) != RTTIMER_FLAGS_CPU_ALL
1489 && !RTMpIsCpuPossible(RTMpCpuIdFromSetIndex(fFlags & RTTIMER_FLAGS_CPU_MASK)))
1490 return VERR_CPU_NOT_FOUND;
1491
1492 /*
1493 * Allocate the timer handler.
1494 */
1495 cCpus = 1;
1496#ifdef CONFIG_SMP
1497 if ((fFlags & RTTIMER_FLAGS_CPU_ALL) == RTTIMER_FLAGS_CPU_ALL)
1498 {
1499 cCpus = RTMpGetMaxCpuId() + 1;
1500 Assert(cCpus <= RTCPUSET_MAX_CPUS); /* On linux we have a 1:1 relationship between cpuid and set index. */
1501 AssertReturn(u64NanoInterval, VERR_NOT_IMPLEMENTED); /* We don't implement single shot on all cpus, sorry. */
1502 }
1503#endif
1504
1505 rc = RTMemAllocEx(RT_OFFSETOF(RTTIMER, aSubTimers[cCpus]), 0,
1506 RTMEMALLOCEX_FLAGS_ZEROED | RTMEMALLOCEX_FLAGS_ANY_CTX_FREE, (void **)&pTimer);
1507 if (RT_FAILURE(rc))
1508 return rc;
1509
1510 /*
1511 * Initialize it.
1512 */
1513 pTimer->u32Magic = RTTIMER_MAGIC;
1514 pTimer->hSpinlock = NIL_RTSPINLOCK;
1515 pTimer->fSuspended = true;
1516 pTimer->fHighRes = !!(fFlags & RTTIMER_FLAGS_HIGH_RES);
1517#ifdef CONFIG_SMP
1518 pTimer->fSpecificCpu = (fFlags & RTTIMER_FLAGS_CPU_SPECIFIC) && (fFlags & RTTIMER_FLAGS_CPU_ALL) != RTTIMER_FLAGS_CPU_ALL;
1519 pTimer->fAllCpus = (fFlags & RTTIMER_FLAGS_CPU_ALL) == RTTIMER_FLAGS_CPU_ALL;
1520 pTimer->idCpu = pTimer->fSpecificCpu
1521 ? RTMpCpuIdFromSetIndex(fFlags & RTTIMER_FLAGS_CPU_MASK)
1522 : NIL_RTCPUID;
1523#else
1524 pTimer->fSpecificCpu = !!(fFlags & RTTIMER_FLAGS_CPU_SPECIFIC);
1525 pTimer->idCpu = RTMpCpuId();
1526#endif
1527 pTimer->cCpus = cCpus;
1528 pTimer->pfnTimer = pfnTimer;
1529 pTimer->pvUser = pvUser;
1530 pTimer->u64NanoInterval = u64NanoInterval;
1531 pTimer->cJiffies = u64NanoInterval / RTTimerGetSystemGranularity();
1532 if (pTimer->cJiffies * RTTimerGetSystemGranularity() != u64NanoInterval)
1533 pTimer->cJiffies = 0;
1534 spin_lock_init(&pTimer->ChgIntLock);
1535
1536 for (iCpu = 0; iCpu < cCpus; iCpu++)
1537 {
1538#ifdef RTTIMER_LINUX_WITH_HRTIMER
1539 if (pTimer->fHighRes)
1540 {
1541 hrtimer_init(&pTimer->aSubTimers[iCpu].u.Hr.LnxTimer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1542 pTimer->aSubTimers[iCpu].u.Hr.LnxTimer.function = rtTimerLinuxHrCallback;
1543 }
1544 else
1545#endif
1546 {
1547 init_timer(&pTimer->aSubTimers[iCpu].u.Std.LnxTimer);
1548 pTimer->aSubTimers[iCpu].u.Std.LnxTimer.data = (unsigned long)&pTimer->aSubTimers[iCpu];
1549 pTimer->aSubTimers[iCpu].u.Std.LnxTimer.function = rtTimerLinuxStdCallback;
1550 pTimer->aSubTimers[iCpu].u.Std.LnxTimer.expires = jiffies;
1551 pTimer->aSubTimers[iCpu].u.Std.u64NextTS = 0;
1552 }
1553 pTimer->aSubTimers[iCpu].iTick = 0;
1554 pTimer->aSubTimers[iCpu].pParent = pTimer;
1555 pTimer->aSubTimers[iCpu].enmState = RTTIMERLNXSTATE_STOPPED;
1556 }
1557
1558#ifdef CONFIG_SMP
1559 /*
1560 * If this is running on ALL cpus, we'll have to register a callback
1561 * for MP events (so timers can be started/stopped on cpus going
1562 * online/offline). We also create the spinlock for synchronizing
1563 * stop/start/mp-event.
1564 */
1565 if (cCpus > 1)
1566 {
1567 int rc = RTSpinlockCreate(&pTimer->hSpinlock);
1568 if (RT_SUCCESS(rc))
1569 rc = RTMpNotificationRegister(rtTimerLinuxMpEvent, pTimer);
1570 else
1571 pTimer->hSpinlock = NIL_RTSPINLOCK;
1572 if (RT_FAILURE(rc))
1573 {
1574 RTTimerDestroy(pTimer);
1575 return rc;
1576 }
1577 }
1578#endif /* CONFIG_SMP */
1579
1580 RTTIMERLNX_LOG(("create %p hires=%d fFlags=%#x cCpus=%u\n", pTimer, pTimer->fHighRes, fFlags, cCpus));
1581 *ppTimer = pTimer;
1582 return VINF_SUCCESS;
1583}
1584RT_EXPORT_SYMBOL(RTTimerCreateEx);
1585
1586
1587RTDECL(uint32_t) RTTimerGetSystemGranularity(void)
1588{
1589#if 0 /** @todo Not sure if this is what we want or not... Add new API for
1590 * querying the resolution of the high res timers? */
1591 struct timespec Ts;
1592 int rc = hrtimer_get_res(CLOCK_MONOTONIC, &Ts);
1593 if (!rc)
1594 {
1595 Assert(!Ts.tv_sec);
1596 return Ts.tv_nsec;
1597 }
1598#endif
1599 return 1000000000 / HZ; /* ns */
1600}
1601RT_EXPORT_SYMBOL(RTTimerGetSystemGranularity);
1602
1603
1604RTDECL(int) RTTimerRequestSystemGranularity(uint32_t u32Request, uint32_t *pu32Granted)
1605{
1606 return VERR_NOT_SUPPORTED;
1607}
1608RT_EXPORT_SYMBOL(RTTimerRequestSystemGranularity);
1609
1610
1611RTDECL(int) RTTimerReleaseSystemGranularity(uint32_t u32Granted)
1612{
1613 return VERR_NOT_SUPPORTED;
1614}
1615RT_EXPORT_SYMBOL(RTTimerReleaseSystemGranularity);
1616
1617
1618RTDECL(bool) RTTimerCanDoHighResolution(void)
1619{
1620#ifdef RTTIMER_LINUX_WITH_HRTIMER
1621 return true;
1622#else
1623 return false;
1624#endif
1625}
1626RT_EXPORT_SYMBOL(RTTimerCanDoHighResolution);
1627
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