VirtualBox

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

Last change on this file since 32670 was 32670, checked in by vboxsync, 14 years ago

timer-r0drv-linux.c: bug fixes. The ugly guest debugging tracking will be removed when fully debugged.

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