VirtualBox

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

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

r0drv/linux/timer: be consistent, this is SMP only

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.5 KB
Line 
1/* $Id: timer-r0drv-linux.c 27198 2010-03-09 09:52:40Z vboxsync $ */
2/** @file
3 * IPRT - Timers, Ring-0 Driver, Linux.
4 */
5
6/*
7 * Copyright (C) 2006-2008 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#include "the-linux-kernel.h"
36#include "internal/iprt.h"
37
38#include <iprt/timer.h>
39#include <iprt/time.h>
40#include <iprt/mp.h>
41#include <iprt/cpuset.h>
42#include <iprt/spinlock.h>
43#include <iprt/err.h>
44#include <iprt/asm.h>
45#include <iprt/assert.h>
46#include <iprt/alloc.h>
47
48#include "internal/magics.h"
49
50/* We use the API of Linux 2.6.28+ (hrtimer_add_expires_ns()) */
51#if !defined(RT_USE_LINUX_HRTIMER) \
52 && LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28) \
53 && 0 /* currently disabled */
54# define RT_USE_LINUX_HRTIMER
55#endif
56
57/* This check must match the ktime usage in rtTimeGetSystemNanoTS() / time-r0drv-linux.c. */
58#if defined(RT_USE_LINUX_HRTIMER) \
59 && LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 28)
60# error "RT_USE_LINUX_HRTIMER requires 2.6.28 or later, sorry."
61#endif
62
63#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)
64# define mod_timer_pinned mod_timer
65#endif
66
67
68/*******************************************************************************
69* Structures and Typedefs *
70*******************************************************************************/
71/**
72 * Timer state machine.
73 *
74 * This is used to try handle the issues with MP events and
75 * timers that runs on all CPUs. It's relatively nasty :-/
76 */
77typedef enum RTTIMERLNXSTATE
78{
79 /** Stopped. */
80 RTTIMERLNXSTATE_STOPPED = 0,
81 /** Transient state; next ACTIVE. */
82 RTTIMERLNXSTATE_STARTING,
83 /** Transient state; next ACTIVE. (not really necessary) */
84 RTTIMERLNXSTATE_MP_STARTING,
85 /** Active. */
86 RTTIMERLNXSTATE_ACTIVE,
87 /** Transient state; next STOPPED. */
88 RTTIMERLNXSTATE_STOPPING,
89 /** Transient state; next STOPPED. */
90 RTTIMERLNXSTATE_MP_STOPPING,
91 /** The usual 32-bit hack. */
92 RTTIMERLNXSTATE_32BIT_HACK = 0x7fffffff
93} RTTIMERLNXSTATE;
94
95
96/**
97 * A Linux sub-timer.
98 */
99typedef struct RTTIMERLNXSUBTIMER
100{
101 /** The linux timer structure. */
102#ifdef RT_USE_LINUX_HRTIMER
103 struct hrtimer LnxTimer;
104#else
105 struct timer_list LnxTimer;
106 /** The start of the current run (ns).
107 * This is used to calculate when the timer ought to fire the next time. */
108 uint64_t u64StartTS;
109 /** The start of the current run (ns).
110 * This is used to calculate when the timer ought to fire the next time. */
111 uint64_t u64NextTS;
112#endif
113 /** The current tick number (since u64StartTS). */
114 uint64_t iTick;
115 /** Pointer to the parent timer. */
116 PRTTIMER pParent;
117#ifndef RT_USE_LINUX_HRTIMER
118 /** The u64NextTS in jiffies. */
119 unsigned long ulNextJiffies;
120#endif
121 /** The current sub-timer state. */
122 RTTIMERLNXSTATE volatile enmState;
123} RTTIMERLNXSUBTIMER;
124/** Pointer to a linux sub-timer. */
125typedef RTTIMERLNXSUBTIMER *PRTTIMERLNXSUBTIMER;
126AssertCompileMemberOffset(RTTIMERLNXSUBTIMER, LnxTimer, 0);
127
128
129/**
130 * The internal representation of an Linux timer handle.
131 */
132typedef struct RTTIMER
133{
134 /** Magic.
135 * This is RTTIMER_MAGIC, but changes to something else before the timer
136 * is destroyed to indicate clearly that thread should exit. */
137 uint32_t volatile u32Magic;
138 /** Spinlock synchronizing the fSuspended and MP event handling.
139 * This is NIL_RTSPINLOCK if cCpus == 1. */
140 RTSPINLOCK hSpinlock;
141 /** Flag indicating that the timer is suspended. */
142 bool volatile fSuspended;
143 /** Whether the timer must run on one specific CPU or not. */
144 bool fSpecificCpu;
145#ifdef CONFIG_SMP
146 /** Whether the timer must run on all CPUs or not. */
147 bool fAllCpus;
148#endif /* else: All -> specific on non-SMP kernels */
149 /** The CPU it must run on if fSpecificCpu is set. */
150 RTCPUID idCpu;
151 /** The number of CPUs this timer should run on. */
152 RTCPUID cCpus;
153 /** Callback. */
154 PFNRTTIMER pfnTimer;
155 /** User argument. */
156 void *pvUser;
157 /** The timer interval. 0 if one-shot. */
158 uint64_t u64NanoInterval;
159#ifndef RT_USE_LINUX_HRTIMER
160 /** This is set to the number of jiffies between ticks if the interval is
161 * an exact number of jiffies. */
162 unsigned long cJiffies;
163#endif
164 /** Sub-timers.
165 * Normally there is just one, but for RTTIMER_FLAGS_CPU_ALL this will contain
166 * an entry for all possible cpus. In that case the index will be the same as
167 * for the RTCpuSet. */
168 RTTIMERLNXSUBTIMER aSubTimers[1];
169} RTTIMER;
170
171
172/**
173 * A rtTimerLinuxStartOnCpu and rtTimerLinuxStartOnCpu argument package.
174 */
175typedef struct RTTIMERLINUXSTARTONCPUARGS
176{
177 /** The current time (RTTimeNanoTS). */
178 uint64_t u64Now;
179 /** When to start firing (delta). */
180 uint64_t u64First;
181} RTTIMERLINUXSTARTONCPUARGS;
182/** Pointer to a rtTimerLinuxStartOnCpu argument package. */
183typedef RTTIMERLINUXSTARTONCPUARGS *PRTTIMERLINUXSTARTONCPUARGS;
184
185
186/**
187 * Sets the state.
188 */
189DECLINLINE(void) rtTimerLnxSetState(RTTIMERLNXSTATE volatile *penmState, RTTIMERLNXSTATE enmNewState)
190{
191 ASMAtomicWriteU32((uint32_t volatile *)penmState, enmNewState);
192}
193
194
195/**
196 * Sets the state if it has a certain value.
197 *
198 * @return true if xchg was done.
199 * @return false if xchg wasn't done.
200 */
201DECLINLINE(bool) rtTimerLnxCmpXchgState(RTTIMERLNXSTATE volatile *penmState, RTTIMERLNXSTATE enmNewState, RTTIMERLNXSTATE enmCurState)
202{
203 return ASMAtomicCmpXchgU32((uint32_t volatile *)penmState, enmNewState, enmCurState);
204}
205
206
207/**
208 * Gets the state.
209 */
210DECLINLINE(RTTIMERLNXSTATE) rtTimerLnxGetState(RTTIMERLNXSTATE volatile *penmState)
211{
212 return (RTTIMERLNXSTATE)ASMAtomicUoReadU32((uint32_t volatile *)penmState);
213}
214
215
216#ifdef RT_USE_LINUX_HRTIMER
217/**
218 * Converts a nano second time stamp to ktime_t.
219 *
220 * ASSUMES RTTimeNanoTS() is implemented using ktime_get_ts().
221 *
222 * @returns ktime_t.
223 * @param cNanoSecs Nanoseconds.
224 */
225DECLINLINE(ktime_t) rtTimerLnxNanoToKt(uint64_t cNanoSecs)
226{
227 /* With some luck the compiler optimizes the division out of this... (Bet it doesn't.) */
228 return ktime_set(cNanoSecs / 1000000000, cNanoSecs % 1000000000);
229}
230
231/**
232 * Converts ktime_t to a nano second time stamp.
233 *
234 * ASSUMES RTTimeNanoTS() is implemented using ktime_get_ts().
235 *
236 * @returns nano second time stamp.
237 * @param Kt ktime_t.
238 */
239DECLINLINE(uint64_t) rtTimerLnxKtToNano(ktime_t Kt)
240{
241 return ktime_to_ns(Kt);
242}
243
244#else /* ! RT_USE_LINUX_HRTIMER */
245
246/**
247 * Converts a nano second interval to jiffies.
248 *
249 * @returns Jiffies.
250 * @param cNanoSecs Nanoseconds.
251 */
252DECLINLINE(unsigned long) rtTimerLnxNanoToJiffies(uint64_t cNanoSecs)
253{
254 /* this can be made even better... */
255 if (cNanoSecs > (uint64_t)TICK_NSEC * MAX_JIFFY_OFFSET)
256 return MAX_JIFFY_OFFSET;
257# if ARCH_BITS == 32
258 if (RT_LIKELY(cNanoSecs <= UINT32_MAX))
259 return ((uint32_t)cNanoSecs + (TICK_NSEC-1)) / TICK_NSEC;
260# endif
261 return (cNanoSecs + (TICK_NSEC-1)) / TICK_NSEC;
262}
263#endif /* ! RT_USE_LINUX_HRTIMER */
264
265
266/**
267 * Starts a sub-timer (RTTimerStart).
268 *
269 * @param pSubTimer The sub-timer to start.
270 * @param u64Now The current timestamp (RTTimeNanoTS()).
271 * @param u64First The interval from u64Now to the first time the timer should fire.
272 * @param fPinned true = timer pinned to a specific CPU,
273 * false = timer can migrate between CPUs
274 */
275static void rtTimerLnxStartSubTimer(PRTTIMERLNXSUBTIMER pSubTimer, uint64_t u64Now, uint64_t u64First, bool fPinned)
276{
277 /*
278 * Calc when it should start firing.
279 */
280 uint64_t u64NextTS = u64Now + u64First;
281#ifndef RT_USE_LINUX_HRTIMER
282 pSubTimer->u64StartTS = u64NextTS;
283 pSubTimer->u64NextTS = u64NextTS;
284#endif
285
286 pSubTimer->iTick = 0;
287
288#ifdef RT_USE_LINUX_HRTIMER
289 hrtimer_start(&pSubTimer->LnxTimer, rtTimerLnxNanoToKt(u64NextTS), HRTIMER_MODE_ABS);
290#else
291 {
292 unsigned long cJiffies = !u64First ? 0 : rtTimerLnxNanoToJiffies(u64First);
293 pSubTimer->ulNextJiffies = jiffies + cJiffies;
294# ifdef CONFIG_SMP
295 if (fPinned)
296 mod_timer_pinned(&pSubTimer->LnxTimer, pSubTimer->ulNextJiffies);
297 else
298# endif
299 mod_timer(&pSubTimer->LnxTimer, pSubTimer->ulNextJiffies);
300 }
301#endif
302
303 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_ACTIVE);
304}
305
306
307/**
308 * Stops a sub-timer (RTTimerStart and rtTimerLinuxMpEvent()).
309 *
310 * @param pSubTimer The sub-timer.
311 */
312static void rtTimerLnxStopSubTimer(PRTTIMERLNXSUBTIMER pSubTimer)
313{
314#ifdef RT_USE_LINUX_HRTIMER
315 hrtimer_cancel(&pSubTimer->LnxTimer);
316#else
317 if (timer_pending(&pSubTimer->LnxTimer))
318 del_timer_sync(&pSubTimer->LnxTimer);
319#endif
320
321 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED);
322}
323
324
325#ifdef RT_USE_LINUX_HRTIMER
326/**
327 * Timer callback function.
328 * @returns HRTIMER_NORESTART or HRTIMER_RESTART depending on whether it's a one-shot or interval timer.
329 * @param pHrTimer Pointer to the sub-timer structure.
330 */
331static enum hrtimer_restart rtTimerLinuxCallback(struct hrtimer *pHrTimer)
332#else
333/**
334 * Timer callback function.
335 * @param ulUser Address of the sub-timer structure.
336 */
337static void rtTimerLinuxCallback(unsigned long ulUser)
338#endif
339{
340#ifdef RT_USE_LINUX_HRTIMER
341 enum hrtimer_restart rc;
342 PRTTIMERLNXSUBTIMER pSubTimer = (PRTTIMERLNXSUBTIMER)pHrTimer;
343#else
344 PRTTIMERLNXSUBTIMER pSubTimer = (PRTTIMERLNXSUBTIMER)ulUser;
345#endif
346 PRTTIMER pTimer = pSubTimer->pParent;
347
348 /*
349 * Don't call the handler if the timer has been suspended.
350 * Also, when running on all CPUS, make sure we don't call out twice
351 * on a CPU because of timer migration.
352 *
353 * For the specific cpu case, we're just ignoring timer migration for now... (bad)
354 */
355 if ( ASMAtomicUoReadBool(&pTimer->fSuspended)
356#ifdef CONFIG_SMP
357 || ( pTimer->fAllCpus
358 && (RTCPUID)(pSubTimer - &pTimer->aSubTimers[0]) != RTMpCpuId())
359#endif
360 )
361 {
362 rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_ACTIVE);
363# ifdef RT_USE_LINUX_HRTIMER
364 rc = HRTIMER_NORESTART;
365# endif
366 }
367 else if (!pTimer->u64NanoInterval)
368 {
369 /*
370 * One shot timer, stop it before dispatching it.
371 */
372 if (pTimer->cCpus == 1)
373 ASMAtomicWriteBool(&pTimer->fSuspended, true);
374 rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_ACTIVE);
375#ifdef RT_USE_LINUX_HRTIMER
376 rc = HRTIMER_NORESTART;
377#else
378 /* detached before we're called, nothing to do for this case. */
379#endif
380
381 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pSubTimer->iTick);
382 }
383 else
384 {
385 const uint64_t iTick = ++pSubTimer->iTick;
386
387#ifdef RT_USE_LINUX_HRTIMER
388 hrtimer_add_expires_ns(&pSubTimer->LnxTimer, pTimer->u64NanoInterval);
389 rc = HRTIMER_RESTART;
390#else
391 const uint64_t u64NanoTS = RTTimeNanoTS();
392
393 /*
394 * Interval timer, calculate the next timeout and re-arm it.
395 *
396 * The first time around, we'll re-adjust the u64StartTS to
397 * try prevent some jittering if we were started at a bad time.
398 * This may of course backfire with highres timers...
399 */
400 if (RT_UNLIKELY(iTick == 1))
401 {
402 pSubTimer->u64StartTS = pSubTimer->u64NextTS = u64NanoTS;
403 pSubTimer->ulNextJiffies = jiffies;
404 }
405
406 pSubTimer->u64NextTS += pTimer->u64NanoInterval;
407 if (pTimer->cJiffies)
408 {
409 pSubTimer->ulNextJiffies += pTimer->cJiffies;
410 /* Prevent overflows when the jiffies counter wraps around.
411 * Special thanks to Ken Preslan for helping debugging! */
412 while (time_before(pSubTimer->ulNextJiffies, jiffies))
413 {
414 pSubTimer->ulNextJiffies += pTimer->cJiffies;
415 pSubTimer->u64NextTS += pTimer->u64NanoInterval;
416 }
417 }
418 else
419 {
420 while (pSubTimer->u64NextTS < u64NanoTS)
421 pSubTimer->u64NextTS += pTimer->u64NanoInterval;
422 pSubTimer->ulNextJiffies = jiffies + rtTimerLnxNanoToJiffies(pSubTimer->u64NextTS - u64NanoTS);
423 }
424
425# ifdef CONFIG_SMP
426 if (pTimer->fSpecificCpu || pTimer->fAllCpus)
427 mod_timer_pinned(&pSubTimer->LnxTimer, pSubTimer->ulNextJiffies);
428 else
429# endif
430 mod_timer(&pSubTimer->LnxTimer, pSubTimer->ulNextJiffies);
431#endif
432
433 /*
434 * Run the timer.
435 */
436 pTimer->pfnTimer(pTimer, pTimer->pvUser, iTick);
437 }
438
439#ifdef RT_USE_LINUX_HRTIMER
440 return rc;
441#endif
442}
443
444
445#ifdef CONFIG_SMP
446
447/**
448 * Per-cpu callback function (RTMpOnAll/RTMpOnSpecific).
449 *
450 * @param idCpu The current CPU.
451 * @param pvUser1 Pointer to the timer.
452 * @param pvUser2 Pointer to the argument structure.
453 */
454static DECLCALLBACK(void) rtTimerLnxStartAllOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
455{
456 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
457 PRTTIMER pTimer = (PRTTIMER)pvUser1;
458 Assert(idCpu < pTimer->cCpus);
459 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[idCpu], pArgs->u64Now, pArgs->u64First, true /*fPinned*/);
460}
461
462
463/**
464 * Worker for RTTimerStart() that takes care of the ugly bit.s
465 *
466 * @returns RTTimerStart() return value.
467 * @param pTimer The timer.
468 * @param pArgs The argument structure.
469 */
470static int rtTimerLnxStartAll(PRTTIMER pTimer, PRTTIMERLINUXSTARTONCPUARGS pArgs)
471{
472 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
473 RTCPUID iCpu;
474 RTCPUSET OnlineSet;
475 RTCPUSET OnlineSet2;
476 int rc2;
477
478 /*
479 * Prepare all the sub-timers for the startup and then flag the timer
480 * as a whole as non-suspended, make sure we get them all before
481 * clearing fSuspended as the MP handler will be waiting on this
482 * should something happen while we're looping.
483 */
484 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
485
486 do
487 {
488 RTMpGetOnlineSet(&OnlineSet);
489 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
490 {
491 Assert(pTimer->aSubTimers[iCpu].enmState != RTTIMERLNXSTATE_MP_STOPPING);
492 rtTimerLnxSetState(&pTimer->aSubTimers[iCpu].enmState,
493 RTCpuSetIsMember(&OnlineSet, iCpu)
494 ? RTTIMERLNXSTATE_STARTING
495 : RTTIMERLNXSTATE_STOPPED);
496 }
497 } while (!RTCpuSetIsEqual(&OnlineSet, RTMpGetOnlineSet(&OnlineSet2)));
498
499 ASMAtomicWriteBool(&pTimer->fSuspended, false);
500
501 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
502
503 /*
504 * Start them (can't find any exported function that allows me to
505 * do this without the cross calls).
506 */
507 pArgs->u64Now = RTTimeNanoTS();
508 rc2 = RTMpOnAll(rtTimerLnxStartAllOnCpu, pTimer, pArgs);
509 AssertRC(rc2); /* screw this if it fails. */
510
511 /*
512 * Reset the sub-timers who didn't start up (ALL CPUs case).
513 * CPUs that comes online between the
514 */
515 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
516
517 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
518 if (rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState, RTTIMERLNXSTATE_STOPPED, RTTIMERLNXSTATE_STARTING))
519 {
520 /** @todo very odd case for a rainy day. Cpus that temporarily went offline while
521 * we were between calls needs to nudged as the MP handler will ignore events for
522 * them because of the STARTING state. This is an extremely unlikely case - not that
523 * that means anything in my experience... ;-) */
524 }
525
526 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
527
528 return VINF_SUCCESS;
529}
530
531
532/**
533 * Worker for RTTimerStop() that takes care of the ugly SMP bits.
534 *
535 * @returns RTTimerStop() return value.
536 * @param pTimer The timer (valid).
537 */
538static int rtTimerLnxStopAll(PRTTIMER pTimer)
539{
540 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
541 RTCPUID iCpu;
542
543
544 /*
545 * Mark the timer as suspended and flag all timers as stopping, except
546 * for those being stopped by an MP event.
547 */
548 RTSpinlockAcquire(pTimer->hSpinlock, &Tmp);
549
550 ASMAtomicWriteBool(&pTimer->fSuspended, true);
551 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
552 {
553 RTTIMERLNXSTATE enmState;
554 do
555 {
556 enmState = rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState);
557 if ( enmState == RTTIMERLNXSTATE_STOPPED
558 || enmState == RTTIMERLNXSTATE_MP_STOPPING)
559 break;
560 Assert(enmState == RTTIMERLNXSTATE_ACTIVE);
561 } while (!rtTimerLnxCmpXchgState(&pTimer->aSubTimers[iCpu].enmState, RTTIMERLNXSTATE_STOPPING, enmState));
562 }
563
564 RTSpinlockRelease(pTimer->hSpinlock, &Tmp);
565
566 /*
567 * Do the actual stopping. Fortunately, this doesn't require any IPIs.
568 * Unfortunately it cannot be done synchronously from within the spinlock,
569 * because we might end up in an active waiting for a handler to complete.
570 */
571 for (iCpu = 0; iCpu < pTimer->cCpus; iCpu++)
572 if (rtTimerLnxGetState(&pTimer->aSubTimers[iCpu].enmState) == RTTIMERLNXSTATE_STOPPING)
573 rtTimerLnxStopSubTimer(&pTimer->aSubTimers[iCpu]);
574
575 return VINF_SUCCESS;
576}
577
578
579/**
580 * Per-cpu callback function (RTMpOnSpecific) used by rtTimerLinuxMpEvent()
581 * to start a sub-timer on a cpu that just have come online.
582 *
583 * @param idCpu The current CPU.
584 * @param pvUser1 Pointer to the timer.
585 * @param pvUser2 Pointer to the argument structure.
586 */
587static DECLCALLBACK(void) rtTimerLinuxMpStartOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
588{
589 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
590 PRTTIMER pTimer = (PRTTIMER)pvUser1;
591 RTSPINLOCK hSpinlock;
592 Assert(idCpu < pTimer->cCpus);
593
594 /*
595 * We have to be kind of careful here as we might be racing RTTimerStop
596 * (and/or RTTimerDestroy, thus the paranoia.
597 */
598 hSpinlock = pTimer->hSpinlock;
599 if ( hSpinlock != NIL_RTSPINLOCK
600 && pTimer->u32Magic == RTTIMER_MAGIC)
601 {
602 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
603 RTSpinlockAcquire(hSpinlock, &Tmp);
604
605 if ( !ASMAtomicUoReadBool(&pTimer->fSuspended)
606 && pTimer->u32Magic == RTTIMER_MAGIC)
607 {
608 /* We're sane and the timer is not suspended yet. */
609 PRTTIMERLNXSUBTIMER pSubTimer = &pTimer->aSubTimers[idCpu];
610 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STARTING, RTTIMERLNXSTATE_STOPPED))
611 rtTimerLnxStartSubTimer(pSubTimer, pArgs->u64Now, pArgs->u64First, true /*fPinned*/);
612 }
613
614 RTSpinlockRelease(hSpinlock, &Tmp);
615 }
616}
617
618
619/**
620 * MP event notification callback.
621 *
622 * @param enmEvent The event.
623 * @param idCpu The cpu it applies to.
624 * @param pvUser The timer.
625 */
626static DECLCALLBACK(void) rtTimerLinuxMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser)
627{
628 PRTTIMER pTimer = (PRTTIMER)pvUser;
629 PRTTIMERLNXSUBTIMER pSubTimer = &pTimer->aSubTimers[idCpu];
630 RTSPINLOCK hSpinlock;
631 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
632
633 Assert(idCpu < pTimer->cCpus);
634
635 /*
636 * Some initial paranoia.
637 */
638 if (pTimer->u32Magic != RTTIMER_MAGIC)
639 return;
640 hSpinlock = pTimer->hSpinlock;
641 if (hSpinlock == NIL_RTSPINLOCK)
642 return;
643
644 RTSpinlockAcquire(hSpinlock, &Tmp);
645
646 /* Is it active? */
647 if ( !ASMAtomicUoReadBool(&pTimer->fSuspended)
648 && pTimer->u32Magic == RTTIMER_MAGIC)
649 {
650 switch (enmEvent)
651 {
652 /*
653 * Try do it without leaving the spin lock, but if we have to, retake it
654 * when we're on the right cpu.
655 */
656 case RTMPEVENT_ONLINE:
657 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STARTING, RTTIMERLNXSTATE_STOPPED))
658 {
659 RTTIMERLINUXSTARTONCPUARGS Args;
660 Args.u64Now = RTTimeNanoTS();
661 Args.u64First = 0;
662
663 if (RTMpCpuId() == idCpu)
664 rtTimerLnxStartSubTimer(pSubTimer, Args.u64Now, Args.u64First, true /*fPinned*/);
665 else
666 {
667 rtTimerLnxSetState(&pSubTimer->enmState, RTTIMERLNXSTATE_STOPPED); /* we'll recheck it. */
668 RTSpinlockRelease(hSpinlock, &Tmp);
669
670 RTMpOnSpecific(idCpu, rtTimerLinuxMpStartOnCpu, pTimer, &Args);
671 return; /* we've left the spinlock */
672 }
673 }
674 break;
675
676 /*
677 * The CPU is (going) offline, make sure the sub-timer is stopped.
678 *
679 * Linux will migrate it to a different CPU, but we don't want this. The
680 * timer function is checking for this.
681 */
682 case RTMPEVENT_OFFLINE:
683 if (rtTimerLnxCmpXchgState(&pSubTimer->enmState, RTTIMERLNXSTATE_MP_STOPPING, RTTIMERLNXSTATE_ACTIVE))
684 {
685 RTSpinlockRelease(hSpinlock, &Tmp);
686
687 rtTimerLnxStopSubTimer(pSubTimer);
688 return; /* we've left the spinlock */
689 }
690 break;
691 }
692 }
693
694 RTSpinlockRelease(hSpinlock, &Tmp);
695}
696
697#endif /* CONFIG_SMP */
698
699
700/**
701 * Callback function use by RTTimerStart via RTMpOnSpecific to start
702 * a timer running on a specific CPU.
703 *
704 * @param idCpu The current CPU.
705 * @param pvUser1 Pointer to the timer.
706 * @param pvUser2 Pointer to the argument structure.
707 */
708static DECLCALLBACK(void) rtTimerLnxStartOnSpecificCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
709{
710 PRTTIMERLINUXSTARTONCPUARGS pArgs = (PRTTIMERLINUXSTARTONCPUARGS)pvUser2;
711 PRTTIMER pTimer = (PRTTIMER)pvUser1;
712 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[0], pArgs->u64Now, pArgs->u64First, true /*fPinned*/);
713}
714
715
716RTDECL(int) RTTimerStart(PRTTIMER pTimer, uint64_t u64First)
717{
718 RTTIMERLINUXSTARTONCPUARGS Args;
719 int rc2;
720
721 /*
722 * Validate.
723 */
724 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
725 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
726
727 if (!ASMAtomicUoReadBool(&pTimer->fSuspended))
728 return VERR_TIMER_ACTIVE;
729
730 Args.u64First = u64First;
731#ifdef CONFIG_SMP
732 /*
733 * Omnit timer?
734 */
735 if (pTimer->fAllCpus)
736 return rtTimerLnxStartAll(pTimer, &Args);
737#endif
738
739 /*
740 * Simple timer - Pretty straight forward.
741 */
742 Args.u64Now = RTTimeNanoTS();
743 rtTimerLnxSetState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STARTING);
744 ASMAtomicWriteBool(&pTimer->fSuspended, false);
745 if (!pTimer->fSpecificCpu)
746 rtTimerLnxStartSubTimer(&pTimer->aSubTimers[0], Args.u64Now, Args.u64First, false /*fPinned*/);
747 else
748 {
749 rc2 = RTMpOnSpecific(pTimer->idCpu, rtTimerLnxStartOnSpecificCpu, pTimer, &Args);
750 if (RT_FAILURE(rc2))
751 {
752 /* Suspend it, the cpu id is probably invalid or offline. */
753 ASMAtomicWriteBool(&pTimer->fSuspended, true);
754 rtTimerLnxSetState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STOPPED);
755 return rc2;
756 }
757 }
758
759 return VINF_SUCCESS;
760}
761RT_EXPORT_SYMBOL(RTTimerStart);
762
763
764RTDECL(int) RTTimerStop(PRTTIMER pTimer)
765{
766
767 /*
768 * Validate.
769 */
770 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
771 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
772
773 if (ASMAtomicUoReadBool(&pTimer->fSuspended))
774 return VERR_TIMER_SUSPENDED;
775
776#ifdef CONFIG_SMP
777 /*
778 * Omni timer?
779 */
780 if (pTimer->fAllCpus)
781 return rtTimerLnxStopAll(pTimer);
782#endif
783
784 /*
785 * Simple timer.
786 */
787 ASMAtomicWriteBool(&pTimer->fSuspended, true);
788 rtTimerLnxSetState(&pTimer->aSubTimers[0].enmState, RTTIMERLNXSTATE_STOPPING);
789 rtTimerLnxStopSubTimer(&pTimer->aSubTimers[0]);
790
791 return VINF_SUCCESS;
792}
793RT_EXPORT_SYMBOL(RTTimerStop);
794
795
796RTDECL(int) RTTimerDestroy(PRTTIMER pTimer)
797{
798 RTSPINLOCK hSpinlock;
799
800 /* It's ok to pass NULL pointer. */
801 if (pTimer == /*NIL_RTTIMER*/ NULL)
802 return VINF_SUCCESS;
803 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
804 AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, VERR_INVALID_HANDLE);
805
806 /*
807 * Remove the MP notifications first because it'll reduce the risk of
808 * us overtaking any MP event that might theoretically be racing us here.
809 */
810 hSpinlock = pTimer->hSpinlock;
811#ifdef CONFIG_SMP
812 if ( pTimer->cCpus > 1
813 && hSpinlock != NIL_RTSPINLOCK)
814 {
815 int rc = RTMpNotificationDeregister(rtTimerLinuxMpEvent, pTimer);
816 AssertRC(rc);
817 }
818#endif /* CONFIG_SMP */
819
820 /*
821 * Stop the timer if it's running.
822 */
823 if (!ASMAtomicUoReadBool(&pTimer->fSuspended))
824 RTTimerStop(pTimer);
825
826 /*
827 * Uninitialize the structure and free the associated resources.
828 * The spinlock goes last.
829 */
830 ASMAtomicWriteU32(&pTimer->u32Magic, ~RTTIMER_MAGIC);
831 RTMemFree(pTimer);
832 if (hSpinlock != NIL_RTSPINLOCK)
833 RTSpinlockDestroy(hSpinlock);
834
835 return VINF_SUCCESS;
836}
837RT_EXPORT_SYMBOL(RTTimerDestroy);
838
839
840RTDECL(int) RTTimerCreateEx(PRTTIMER *ppTimer, uint64_t u64NanoInterval, unsigned fFlags, PFNRTTIMER pfnTimer, void *pvUser)
841{
842 PRTTIMER pTimer;
843 RTCPUID iCpu;
844 unsigned cCpus;
845
846 *ppTimer = NULL;
847
848 /*
849 * Validate flags.
850 */
851 if (!RTTIMER_FLAGS_ARE_VALID(fFlags))
852 return VERR_INVALID_PARAMETER;
853 if ( (fFlags & RTTIMER_FLAGS_CPU_SPECIFIC)
854 && (fFlags & RTTIMER_FLAGS_CPU_ALL) != RTTIMER_FLAGS_CPU_ALL
855 && !RTMpIsCpuOnline(fFlags & RTTIMER_FLAGS_CPU_MASK))
856 return (fFlags & RTTIMER_FLAGS_CPU_MASK) > RTMpGetMaxCpuId()
857 ? VERR_CPU_NOT_FOUND
858 : VERR_CPU_OFFLINE;
859
860 /*
861 * Allocate the timer handler.
862 */
863 cCpus = 1;
864#ifdef CONFIG_SMP
865 if ((fFlags & RTTIMER_FLAGS_CPU_ALL) == RTTIMER_FLAGS_CPU_ALL)
866 {
867 cCpus = RTMpGetMaxCpuId() + 1;
868 Assert(cCpus <= RTCPUSET_MAX_CPUS); /* On linux we have a 1:1 relationship between cpuid and set index. */
869 AssertReturn(u64NanoInterval, VERR_NOT_IMPLEMENTED); /* We don't implement single shot on all cpus, sorry. */
870 }
871#endif
872
873 pTimer = (PRTTIMER)RTMemAllocZ(RT_OFFSETOF(RTTIMER, aSubTimers[cCpus]));
874 if (!pTimer)
875 return VERR_NO_MEMORY;
876
877 /*
878 * Initialize it.
879 */
880 pTimer->u32Magic = RTTIMER_MAGIC;
881 pTimer->hSpinlock = NIL_RTSPINLOCK;
882 pTimer->fSuspended = true;
883#ifdef CONFIG_SMP
884 pTimer->fSpecificCpu = (fFlags & RTTIMER_FLAGS_CPU_SPECIFIC) && (fFlags & RTTIMER_FLAGS_CPU_ALL) != RTTIMER_FLAGS_CPU_ALL;
885 pTimer->fAllCpus = (fFlags & RTTIMER_FLAGS_CPU_ALL) == RTTIMER_FLAGS_CPU_ALL;
886 pTimer->idCpu = fFlags & RTTIMER_FLAGS_CPU_MASK;
887#else
888 pTimer->fSpecificCpu = !!(fFlags & RTTIMER_FLAGS_CPU_SPECIFIC);
889 pTimer->idCpu = RTMpCpuId();
890#endif
891 pTimer->cCpus = cCpus;
892 pTimer->pfnTimer = pfnTimer;
893 pTimer->pvUser = pvUser;
894 pTimer->u64NanoInterval = u64NanoInterval;
895#ifndef RT_USE_LINUX_HRTIMER
896 pTimer->cJiffies = u64NanoInterval / RTTimerGetSystemGranularity();
897 if (pTimer->cJiffies * RTTimerGetSystemGranularity() != u64NanoInterval)
898 pTimer->cJiffies = 0;
899#endif
900
901 for (iCpu = 0; iCpu < cCpus; iCpu++)
902 {
903#ifdef RT_USE_LINUX_HRTIMER
904 hrtimer_init(&pTimer->aSubTimers[iCpu].LnxTimer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
905 pTimer->aSubTimers[iCpu].LnxTimer.function = rtTimerLinuxCallback;
906#else
907 init_timer(&pTimer->aSubTimers[iCpu].LnxTimer);
908 pTimer->aSubTimers[iCpu].LnxTimer.data = (unsigned long)&pTimer->aSubTimers[iCpu];
909 pTimer->aSubTimers[iCpu].LnxTimer.function = rtTimerLinuxCallback;
910 pTimer->aSubTimers[iCpu].LnxTimer.expires = jiffies;
911 pTimer->aSubTimers[iCpu].u64StartTS = 0;
912 pTimer->aSubTimers[iCpu].u64NextTS = 0;
913#endif
914 pTimer->aSubTimers[iCpu].iTick = 0;
915 pTimer->aSubTimers[iCpu].pParent = pTimer;
916 pTimer->aSubTimers[iCpu].enmState = RTTIMERLNXSTATE_STOPPED;
917 }
918
919#ifdef CONFIG_SMP
920 /*
921 * If this is running on ALL cpus, we'll have to register a callback
922 * for MP events (so timers can be started/stopped on cpus going
923 * online/offline). We also create the spinlock for syncrhonizing
924 * stop/start/mp-event.
925 */
926 if (cCpus > 1)
927 {
928 int rc = RTSpinlockCreate(&pTimer->hSpinlock);
929 if (RT_SUCCESS(rc))
930 rc = RTMpNotificationRegister(rtTimerLinuxMpEvent, pTimer);
931 else
932 pTimer->hSpinlock = NIL_RTSPINLOCK;
933 if (RT_FAILURE(rc))
934 {
935 RTTimerDestroy(pTimer);
936 return rc;
937 }
938 }
939#endif /* CONFIG_SMP */
940
941 *ppTimer = pTimer;
942 return VINF_SUCCESS;
943}
944RT_EXPORT_SYMBOL(RTTimerCreateEx);
945
946
947RTDECL(uint32_t) RTTimerGetSystemGranularity(void)
948{
949#ifdef RT_USE_LINUX_HRTIMER
950 struct timespec Ts;
951 int rc = hrtimer_get_res(CLOCK_MONOTONIC, &Ts);
952 if (!rc)
953 {
954 Assert(!Ts.tv_sec);
955 return Ts.tv_nsec;
956 }
957#endif
958 return 1000000000 / HZ; /* ns */
959}
960RT_EXPORT_SYMBOL(RTTimerGetSystemGranularity);
961
962
963RTDECL(int) RTTimerRequestSystemGranularity(uint32_t u32Request, uint32_t *pu32Granted)
964{
965 return VERR_NOT_SUPPORTED;
966}
967RT_EXPORT_SYMBOL(RTTimerRequestSystemGranularity);
968
969
970RTDECL(int) RTTimerReleaseSystemGranularity(uint32_t u32Granted)
971{
972 return VERR_NOT_SUPPORTED;
973}
974RT_EXPORT_SYMBOL(RTTimerReleaseSystemGranularity);
975
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