xref: /openbmc/qemu/include/qemu/timer.h (revision d16ccfea)
1 #ifndef QEMU_TIMER_H
2 #define QEMU_TIMER_H
3 
4 #include "qemu/bitops.h"
5 #include "qemu/notify.h"
6 #include "qemu/host-utils.h"
7 
8 #define NANOSECONDS_PER_SECOND 1000000000LL
9 
10 /* timers */
11 
12 #define SCALE_MS 1000000
13 #define SCALE_US 1000
14 #define SCALE_NS 1
15 
16 /**
17  * QEMUClockType:
18  *
19  * The following clock types are available:
20  *
21  * @QEMU_CLOCK_REALTIME: Real time clock
22  *
23  * The real time clock should be used only for stuff which does not
24  * change the virtual machine state, as it runs even if the virtual
25  * machine is stopped.
26  *
27  * @QEMU_CLOCK_VIRTUAL: virtual clock
28  *
29  * The virtual clock only runs during the emulation. It stops
30  * when the virtual machine is stopped.
31  *
32  * @QEMU_CLOCK_HOST: host clock
33  *
34  * The host clock should be used for device models that emulate accurate
35  * real time sources. It will continue to run when the virtual machine
36  * is suspended, and it will reflect system time changes the host may
37  * undergo (e.g. due to NTP).
38  *
39  * @QEMU_CLOCK_VIRTUAL_RT: realtime clock used for icount warp
40  *
41  * Outside icount mode, this clock is the same as @QEMU_CLOCK_VIRTUAL.
42  * In icount mode, this clock counts nanoseconds while the virtual
43  * machine is running.  It is used to increase @QEMU_CLOCK_VIRTUAL
44  * while the CPUs are sleeping and thus not executing instructions.
45  */
46 
47 typedef enum {
48     QEMU_CLOCK_REALTIME = 0,
49     QEMU_CLOCK_VIRTUAL = 1,
50     QEMU_CLOCK_HOST = 2,
51     QEMU_CLOCK_VIRTUAL_RT = 3,
52     QEMU_CLOCK_MAX
53 } QEMUClockType;
54 
55 /**
56  * QEMU Timer attributes:
57  *
58  * An individual timer may be given one or multiple attributes when initialized.
59  * Each attribute corresponds to one bit. Attributes modify the processing
60  * of timers when they fire.
61  *
62  * The following attributes are available:
63  *
64  * QEMU_TIMER_ATTR_EXTERNAL: drives external subsystem
65  * QEMU_TIMER_ATTR_ALL: mask for all existing attributes
66  *
67  * Timers with this attribute do not recorded in rr mode, therefore it could be
68  * used for the subsystems that operate outside the guest core. Applicable only
69  * with virtual clock type.
70  */
71 
72 #define QEMU_TIMER_ATTR_EXTERNAL ((int)BIT(0))
73 #define QEMU_TIMER_ATTR_ALL      0xffffffff
74 
75 typedef struct QEMUTimerList QEMUTimerList;
76 
77 struct QEMUTimerListGroup {
78     QEMUTimerList *tl[QEMU_CLOCK_MAX];
79 };
80 
81 typedef void QEMUTimerCB(void *opaque);
82 typedef void QEMUTimerListNotifyCB(void *opaque, QEMUClockType type);
83 
84 struct QEMUTimer {
85     int64_t expire_time;        /* in nanoseconds */
86     QEMUTimerList *timer_list;
87     QEMUTimerCB *cb;
88     void *opaque;
89     QEMUTimer *next;
90     int attributes;
91     int scale;
92 };
93 
94 extern QEMUTimerListGroup main_loop_tlg;
95 
96 /*
97  * qemu_clock_get_ns;
98  * @type: the clock type
99  *
100  * Get the nanosecond value of a clock with
101  * type @type
102  *
103  * Returns: the clock value in nanoseconds
104  */
105 int64_t qemu_clock_get_ns(QEMUClockType type);
106 
107 /**
108  * qemu_clock_get_ms;
109  * @type: the clock type
110  *
111  * Get the millisecond value of a clock with
112  * type @type
113  *
114  * Returns: the clock value in milliseconds
115  */
qemu_clock_get_ms(QEMUClockType type)116 static inline int64_t qemu_clock_get_ms(QEMUClockType type)
117 {
118     return qemu_clock_get_ns(type) / SCALE_MS;
119 }
120 
121 /**
122  * qemu_clock_get_us;
123  * @type: the clock type
124  *
125  * Get the microsecond value of a clock with
126  * type @type
127  *
128  * Returns: the clock value in microseconds
129  */
qemu_clock_get_us(QEMUClockType type)130 static inline int64_t qemu_clock_get_us(QEMUClockType type)
131 {
132     return qemu_clock_get_ns(type) / SCALE_US;
133 }
134 
135 /**
136  * qemu_clock_has_timers:
137  * @type: the clock type
138  *
139  * Determines whether a clock's default timer list
140  * has timers attached
141  *
142  * Note that this function should not be used when other threads also access
143  * the timer list.  The return value may be outdated by the time it is acted
144  * upon.
145  *
146  * Returns: true if the clock's default timer list
147  * has timers attached
148  */
149 bool qemu_clock_has_timers(QEMUClockType type);
150 
151 /**
152  * qemu_clock_expired:
153  * @type: the clock type
154  *
155  * Determines whether a clock's default timer list
156  * has an expired timer.
157  *
158  * Returns: true if the clock's default timer list has
159  * an expired timer
160  */
161 bool qemu_clock_expired(QEMUClockType type);
162 
163 /**
164  * qemu_clock_use_for_deadline:
165  * @type: the clock type
166  *
167  * Determine whether a clock should be used for deadline
168  * calculations. Some clocks, for instance vm_clock with
169  * icount_enabled() set, do not count in nanoseconds.
170  * Such clocks are not used for deadline calculations, and are presumed
171  * to interrupt any poll using qemu_notify/aio_notify
172  * etc.
173  *
174  * Returns: true if the clock runs in nanoseconds and
175  * should be used for a deadline.
176  */
177 bool qemu_clock_use_for_deadline(QEMUClockType type);
178 
179 /**
180  * qemu_clock_deadline_ns_all:
181  * @type: the clock type
182  * @attr_mask: mask for the timer attributes that are included
183  *             in deadline calculation
184  *
185  * Calculate the deadline across all timer lists associated
186  * with a clock (as opposed to just the default one)
187  * in nanoseconds, or -1 if no timer is set to expire.
188  *
189  * Returns: time until expiry in nanoseconds or -1
190  */
191 int64_t qemu_clock_deadline_ns_all(QEMUClockType type, int attr_mask);
192 
193 /**
194  * qemu_clock_get_main_loop_timerlist:
195  * @type: the clock type
196  *
197  * Return the default timer list associated with a clock.
198  *
199  * Returns: the default timer list
200  */
201 QEMUTimerList *qemu_clock_get_main_loop_timerlist(QEMUClockType type);
202 
203 /**
204  * qemu_clock_nofify:
205  * @type: the clock type
206  *
207  * Call the notifier callback connected with the default timer
208  * list linked to the clock, or qemu_notify() if none.
209  */
210 void qemu_clock_notify(QEMUClockType type);
211 
212 /**
213  * qemu_clock_enable:
214  * @type: the clock type
215  * @enabled: true to enable, false to disable
216  *
217  * Enable or disable a clock
218  * Disabling the clock will wait for related timerlists to stop
219  * executing qemu_run_timers.  Thus, this functions should not
220  * be used from the callback of a timer that is based on @clock.
221  * Doing so would cause a deadlock.
222  *
223  * Caller should hold BQL.
224  */
225 void qemu_clock_enable(QEMUClockType type, bool enabled);
226 
227 /**
228  * qemu_clock_run_timers:
229  * @type: clock on which to operate
230  *
231  * Run all the timers associated with the default timer list
232  * of a clock.
233  *
234  * Returns: true if any timer ran.
235  */
236 bool qemu_clock_run_timers(QEMUClockType type);
237 
238 /**
239  * qemu_clock_run_all_timers:
240  *
241  * Run all the timers associated with the default timer list
242  * of every clock.
243  *
244  * Returns: true if any timer ran.
245  */
246 bool qemu_clock_run_all_timers(void);
247 
248 /**
249  * qemu_clock_advance_virtual_time(): advance the virtual time tick
250  * @target_ns: target time in nanoseconds
251  *
252  * This function is used where the control of the flow of time has
253  * been delegated to outside the clock subsystem (be it qtest, icount
254  * or some other external source). You can ask the clock system to
255  * return @early at the first expired timer.
256  *
257  * Time can only move forward, attempts to reverse time would lead to
258  * an error.
259  *
260  * Returns: new virtual time.
261  */
262 int64_t qemu_clock_advance_virtual_time(int64_t target_ns);
263 
264 /*
265  * QEMUTimerList
266  */
267 
268 /**
269  * timerlist_new:
270  * @type: the clock type to associate with the timerlist
271  * @cb: the callback to call on notification
272  * @opaque: the opaque pointer to pass to the callback
273  *
274  * Create a new timerlist associated with the clock of
275  * type @type.
276  *
277  * Returns: a pointer to the QEMUTimerList created
278  */
279 QEMUTimerList *timerlist_new(QEMUClockType type,
280                              QEMUTimerListNotifyCB *cb, void *opaque);
281 
282 /**
283  * timerlist_free:
284  * @timer_list: the timer list to free
285  *
286  * Frees a timer_list. It must have no active timers.
287  */
288 void timerlist_free(QEMUTimerList *timer_list);
289 
290 /**
291  * timerlist_has_timers:
292  * @timer_list: the timer list to operate on
293  *
294  * Determine whether a timer list has active timers
295  *
296  * Note that this function should not be used when other threads also access
297  * the timer list.  The return value may be outdated by the time it is acted
298  * upon.
299  *
300  * Returns: true if the timer list has timers.
301  */
302 bool timerlist_has_timers(QEMUTimerList *timer_list);
303 
304 /**
305  * timerlist_expired:
306  * @timer_list: the timer list to operate on
307  *
308  * Determine whether a timer list has any timers which
309  * are expired.
310  *
311  * Returns: true if the timer list has timers which
312  * have expired.
313  */
314 bool timerlist_expired(QEMUTimerList *timer_list);
315 
316 /**
317  * timerlist_deadline_ns:
318  * @timer_list: the timer list to operate on
319  *
320  * Determine the deadline for a timer_list, i.e.
321  * the number of nanoseconds until the first timer
322  * expires. Return -1 if there are no timers.
323  *
324  * Returns: the number of nanoseconds until the earliest
325  * timer expires -1 if none
326  */
327 int64_t timerlist_deadline_ns(QEMUTimerList *timer_list);
328 
329 /**
330  * timerlist_get_clock:
331  * @timer_list: the timer list to operate on
332  *
333  * Determine the clock type associated with a timer list.
334  *
335  * Returns: the clock type associated with the
336  * timer list.
337  */
338 QEMUClockType timerlist_get_clock(QEMUTimerList *timer_list);
339 
340 /**
341  * timerlist_run_timers:
342  * @timer_list: the timer list to use
343  *
344  * Call all expired timers associated with the timer list.
345  *
346  * Returns: true if any timer expired
347  */
348 bool timerlist_run_timers(QEMUTimerList *timer_list);
349 
350 /**
351  * timerlist_notify:
352  * @timer_list: the timer list to use
353  *
354  * call the notifier callback associated with the timer list.
355  */
356 void timerlist_notify(QEMUTimerList *timer_list);
357 
358 /*
359  * QEMUTimerListGroup
360  */
361 
362 /**
363  * timerlistgroup_init:
364  * @tlg: the timer list group
365  * @cb: the callback to call when a notify is required
366  * @opaque: the opaque pointer to be passed to the callback.
367  *
368  * Initialise a timer list group. This must already be
369  * allocated in memory and zeroed. The notifier callback is
370  * called whenever a clock in the timer list group is
371  * reenabled or whenever a timer associated with any timer
372  * list is modified. If @cb is specified as null, qemu_notify()
373  * is used instead.
374  */
375 void timerlistgroup_init(QEMUTimerListGroup *tlg,
376                          QEMUTimerListNotifyCB *cb, void *opaque);
377 
378 /**
379  * timerlistgroup_deinit:
380  * @tlg: the timer list group
381  *
382  * Deinitialise a timer list group. This must already be
383  * initialised. Note the memory is not freed.
384  */
385 void timerlistgroup_deinit(QEMUTimerListGroup *tlg);
386 
387 /**
388  * timerlistgroup_run_timers:
389  * @tlg: the timer list group
390  *
391  * Run the timers associated with a timer list group.
392  * This will run timers on multiple clocks.
393  *
394  * Returns: true if any timer callback ran
395  */
396 bool timerlistgroup_run_timers(QEMUTimerListGroup *tlg);
397 
398 /**
399  * timerlistgroup_deadline_ns:
400  * @tlg: the timer list group
401  *
402  * Determine the deadline of the soonest timer to
403  * expire associated with any timer list linked to
404  * the timer list group. Only clocks suitable for
405  * deadline calculation are included.
406  *
407  * Returns: the deadline in nanoseconds or -1 if no
408  * timers are to expire.
409  */
410 int64_t timerlistgroup_deadline_ns(QEMUTimerListGroup *tlg);
411 
412 /*
413  * QEMUTimer
414  */
415 
416 /**
417  * timer_init_full:
418  * @ts: the timer to be initialised
419  * @timer_list_group: (optional) the timer list group to attach the timer to
420  * @type: the clock type to use
421  * @scale: the scale value for the timer
422  * @attributes: 0, or one or more OR'ed QEMU_TIMER_ATTR_<id> values
423  * @cb: the callback to be called when the timer expires
424  * @opaque: the opaque pointer to be passed to the callback
425  *
426  * Initialise a timer with the given scale and attributes,
427  * and associate it with timer list for given clock @type in @timer_list_group
428  * (or default timer list group, if NULL).
429  * The caller is responsible for allocating the memory.
430  *
431  * You need not call an explicit deinit call. Simply make
432  * sure it is not on a list with timer_del.
433  */
434 void timer_init_full(QEMUTimer *ts,
435                      QEMUTimerListGroup *timer_list_group, QEMUClockType type,
436                      int scale, int attributes,
437                      QEMUTimerCB *cb, void *opaque);
438 
439 /**
440  * timer_init:
441  * @ts: the timer to be initialised
442  * @type: the clock to associate with the timer
443  * @scale: the scale value for the timer
444  * @cb: the callback to call when the timer expires
445  * @opaque: the opaque pointer to pass to the callback
446  *
447  * Initialize a timer with the given scale on the default timer list
448  * associated with the clock.
449  * See timer_init_full for details.
450  */
timer_init(QEMUTimer * ts,QEMUClockType type,int scale,QEMUTimerCB * cb,void * opaque)451 static inline void timer_init(QEMUTimer *ts, QEMUClockType type, int scale,
452                               QEMUTimerCB *cb, void *opaque)
453 {
454     timer_init_full(ts, NULL, type, scale, 0, cb, opaque);
455 }
456 
457 /**
458  * timer_init_ns:
459  * @ts: the timer to be initialised
460  * @type: the clock to associate with the timer
461  * @cb: the callback to call when the timer expires
462  * @opaque: the opaque pointer to pass to the callback
463  *
464  * Initialize a timer with nanosecond scale on the default timer list
465  * associated with the clock.
466  * See timer_init_full for details.
467  */
timer_init_ns(QEMUTimer * ts,QEMUClockType type,QEMUTimerCB * cb,void * opaque)468 static inline void timer_init_ns(QEMUTimer *ts, QEMUClockType type,
469                                  QEMUTimerCB *cb, void *opaque)
470 {
471     timer_init(ts, type, SCALE_NS, cb, opaque);
472 }
473 
474 /**
475  * timer_init_us:
476  * @ts: the timer to be initialised
477  * @type: the clock to associate with the timer
478  * @cb: the callback to call when the timer expires
479  * @opaque: the opaque pointer to pass to the callback
480  *
481  * Initialize a timer with microsecond scale on the default timer list
482  * associated with the clock.
483  * See timer_init_full for details.
484  */
timer_init_us(QEMUTimer * ts,QEMUClockType type,QEMUTimerCB * cb,void * opaque)485 static inline void timer_init_us(QEMUTimer *ts, QEMUClockType type,
486                                  QEMUTimerCB *cb, void *opaque)
487 {
488     timer_init(ts, type, SCALE_US, cb, opaque);
489 }
490 
491 /**
492  * timer_init_ms:
493  * @ts: the timer to be initialised
494  * @type: the clock to associate with the timer
495  * @cb: the callback to call when the timer expires
496  * @opaque: the opaque pointer to pass to the callback
497  *
498  * Initialize a timer with millisecond scale on the default timer list
499  * associated with the clock.
500  * See timer_init_full for details.
501  */
timer_init_ms(QEMUTimer * ts,QEMUClockType type,QEMUTimerCB * cb,void * opaque)502 static inline void timer_init_ms(QEMUTimer *ts, QEMUClockType type,
503                                  QEMUTimerCB *cb, void *opaque)
504 {
505     timer_init(ts, type, SCALE_MS, cb, opaque);
506 }
507 
508 /**
509  * timer_new_full:
510  * @timer_list_group: (optional) the timer list group to attach the timer to
511  * @type: the clock type to use
512  * @scale: the scale value for the timer
513  * @attributes: 0, or one or more OR'ed QEMU_TIMER_ATTR_<id> values
514  * @cb: the callback to be called when the timer expires
515  * @opaque: the opaque pointer to be passed to the callback
516  *
517  * Create a new timer with the given scale and attributes,
518  * and associate it with timer list for given clock @type in @timer_list_group
519  * (or default timer list group, if NULL).
520  * The memory is allocated by the function.
521  *
522  * This is not the preferred interface unless you know you
523  * are going to call timer_free. Use timer_init or timer_init_full instead.
524  *
525  * The default timer list has one special feature: in icount mode,
526  * %QEMU_CLOCK_VIRTUAL timers are run in the vCPU thread.  This is
527  * not true of other timer lists, which are typically associated
528  * with an AioContext---each of them runs its timer callbacks in its own
529  * AioContext thread.
530  *
531  * Returns: a pointer to the timer
532  */
timer_new_full(QEMUTimerListGroup * timer_list_group,QEMUClockType type,int scale,int attributes,QEMUTimerCB * cb,void * opaque)533 static inline QEMUTimer *timer_new_full(QEMUTimerListGroup *timer_list_group,
534                                         QEMUClockType type,
535                                         int scale, int attributes,
536                                         QEMUTimerCB *cb, void *opaque)
537 {
538     QEMUTimer *ts = g_new0(QEMUTimer, 1);
539     timer_init_full(ts, timer_list_group, type, scale, attributes, cb, opaque);
540     return ts;
541 }
542 
543 /**
544  * timer_new:
545  * @type: the clock type to use
546  * @scale: the scale value for the timer
547  * @cb: the callback to be called when the timer expires
548  * @opaque: the opaque pointer to be passed to the callback
549  *
550  * Create a new timer with the given scale,
551  * and associate it with the default timer list for the clock type @type.
552  * See timer_new_full for details.
553  *
554  * Returns: a pointer to the timer
555  */
timer_new(QEMUClockType type,int scale,QEMUTimerCB * cb,void * opaque)556 static inline QEMUTimer *timer_new(QEMUClockType type, int scale,
557                                    QEMUTimerCB *cb, void *opaque)
558 {
559     return timer_new_full(NULL, type, scale, 0, cb, opaque);
560 }
561 
562 /**
563  * timer_new_ns:
564  * @type: the clock type to associate with the timer
565  * @cb: the callback to call when the timer expires
566  * @opaque: the opaque pointer to pass to the callback
567  *
568  * Create a new timer with nanosecond scale on the default timer list
569  * associated with the clock.
570  * See timer_new_full for details.
571  *
572  * Returns: a pointer to the newly created timer
573  */
timer_new_ns(QEMUClockType type,QEMUTimerCB * cb,void * opaque)574 static inline QEMUTimer *timer_new_ns(QEMUClockType type, QEMUTimerCB *cb,
575                                       void *opaque)
576 {
577     return timer_new(type, SCALE_NS, cb, opaque);
578 }
579 
580 /**
581  * timer_new_us:
582  * @type: the clock type to associate with the timer
583  * @cb: the callback to call when the timer expires
584  * @opaque: the opaque pointer to pass to the callback
585  *
586  * Create a new timer with microsecond scale on the default timer list
587  * associated with the clock.
588  * See timer_new_full for details.
589  *
590  * Returns: a pointer to the newly created timer
591  */
timer_new_us(QEMUClockType type,QEMUTimerCB * cb,void * opaque)592 static inline QEMUTimer *timer_new_us(QEMUClockType type, QEMUTimerCB *cb,
593                                       void *opaque)
594 {
595     return timer_new(type, SCALE_US, cb, opaque);
596 }
597 
598 /**
599  * timer_new_ms:
600  * @type: the clock type to associate with the timer
601  * @cb: the callback to call when the timer expires
602  * @opaque: the opaque pointer to pass to the callback
603  *
604  * Create a new timer with millisecond scale on the default timer list
605  * associated with the clock.
606  * See timer_new_full for details.
607  *
608  * Returns: a pointer to the newly created timer
609  */
timer_new_ms(QEMUClockType type,QEMUTimerCB * cb,void * opaque)610 static inline QEMUTimer *timer_new_ms(QEMUClockType type, QEMUTimerCB *cb,
611                                       void *opaque)
612 {
613     return timer_new(type, SCALE_MS, cb, opaque);
614 }
615 
616 /**
617  * timer_deinit:
618  * @ts: the timer to be de-initialised
619  *
620  * Deassociate the timer from any timerlist.  You should
621  * call timer_del before.  After this call, any further
622  * timer_del call cannot cause dangling pointer accesses
623  * even if the previously used timerlist is freed.
624  */
625 void timer_deinit(QEMUTimer *ts);
626 
627 /**
628  * timer_del:
629  * @ts: the timer
630  *
631  * Delete a timer from the active list.
632  *
633  * This function is thread-safe but the timer and its timer list must not be
634  * freed while this function is running.
635  */
636 void timer_del(QEMUTimer *ts);
637 
638 /**
639  * timer_free:
640  * @ts: the timer
641  *
642  * Free a timer. This will call timer_del() for you to remove
643  * the timer from the active list if it was still active.
644  */
timer_free(QEMUTimer * ts)645 static inline void timer_free(QEMUTimer *ts)
646 {
647     if (ts) {
648         timer_del(ts);
649         g_free(ts);
650     }
651 }
652 
653 /**
654  * timer_mod_ns:
655  * @ts: the timer
656  * @expire_time: the expiry time in nanoseconds
657  *
658  * Modify a timer to expire at @expire_time
659  *
660  * This function is thread-safe but the timer and its timer list must not be
661  * freed while this function is running.
662  */
663 void timer_mod_ns(QEMUTimer *ts, int64_t expire_time);
664 
665 /**
666  * timer_mod_anticipate_ns:
667  * @ts: the timer
668  * @expire_time: the expiry time in nanoseconds
669  *
670  * Modify a timer to expire at @expire_time or the current time,
671  * whichever comes earlier.
672  *
673  * This function is thread-safe but the timer and its timer list must not be
674  * freed while this function is running.
675  */
676 void timer_mod_anticipate_ns(QEMUTimer *ts, int64_t expire_time);
677 
678 /**
679  * timer_mod:
680  * @ts: the timer
681  * @expire_time: the expire time in the units associated with the timer
682  *
683  * Modify a timer to expiry at @expire_time, taking into
684  * account the scale associated with the timer.
685  *
686  * This function is thread-safe but the timer and its timer list must not be
687  * freed while this function is running.
688  */
689 void timer_mod(QEMUTimer *ts, int64_t expire_timer);
690 
691 /**
692  * timer_mod_anticipate:
693  * @ts: the timer
694  * @expire_time: the expire time in the units associated with the timer
695  *
696  * Modify a timer to expire at @expire_time or the current time, whichever
697  * comes earlier, taking into account the scale associated with the timer.
698  *
699  * This function is thread-safe but the timer and its timer list must not be
700  * freed while this function is running.
701  */
702 void timer_mod_anticipate(QEMUTimer *ts, int64_t expire_time);
703 
704 /**
705  * timer_pending:
706  * @ts: the timer
707  *
708  * Determines whether a timer is pending (i.e. is on the
709  * active list of timers, whether or not it has not yet expired).
710  *
711  * Returns: true if the timer is pending
712  */
713 bool timer_pending(QEMUTimer *ts);
714 
715 /**
716  * timer_expired:
717  * @ts: the timer
718  * @current_time: the current time
719  *
720  * Determines whether a timer has expired.
721  *
722  * Returns: true if the timer has expired
723  */
724 bool timer_expired(QEMUTimer *timer_head, int64_t current_time);
725 
726 /**
727  * timer_expire_time_ns:
728  * @ts: the timer
729  *
730  * Determine the expiry time of a timer
731  *
732  * Returns: the expiry time in nanoseconds
733  */
734 uint64_t timer_expire_time_ns(QEMUTimer *ts);
735 
736 /**
737  * timer_get:
738  * @f: the file
739  * @ts: the timer
740  *
741  * Read a timer @ts from a file @f
742  */
743 void timer_get(QEMUFile *f, QEMUTimer *ts);
744 
745 /**
746  * timer_put:
747  * @f: the file
748  * @ts: the timer
749  */
750 void timer_put(QEMUFile *f, QEMUTimer *ts);
751 
752 /*
753  * General utility functions
754  */
755 
756 /**
757  * qemu_timeout_ns_to_ms:
758  * @ns: nanosecond timeout value
759  *
760  * Convert a nanosecond timeout value (or -1) to
761  * a millisecond value (or -1), always rounding up.
762  *
763  * Returns: millisecond timeout value
764  */
765 int qemu_timeout_ns_to_ms(int64_t ns);
766 
767 /**
768  * qemu_poll_ns:
769  * @fds: Array of file descriptors
770  * @nfds: number of file descriptors
771  * @timeout: timeout in nanoseconds
772  *
773  * Perform a poll like g_poll but with a timeout in nanoseconds.
774  * See g_poll documentation for further details.
775  *
776  * Returns: number of fds ready
777  */
778 int qemu_poll_ns(GPollFD *fds, guint nfds, int64_t timeout);
779 
780 /**
781  * qemu_soonest_timeout:
782  * @timeout1: first timeout in nanoseconds (or -1 for infinite)
783  * @timeout2: second timeout in nanoseconds (or -1 for infinite)
784  *
785  * Calculates the soonest of two timeout values. -1 means infinite, which
786  * is later than any other value.
787  *
788  * Returns: soonest timeout value in nanoseconds (or -1 for infinite)
789  */
qemu_soonest_timeout(int64_t timeout1,int64_t timeout2)790 static inline int64_t qemu_soonest_timeout(int64_t timeout1, int64_t timeout2)
791 {
792     /* we can abuse the fact that -1 (which means infinite) is a maximal
793      * value when cast to unsigned. As this is disgusting, it's kept in
794      * one inline function.
795      */
796     return ((uint64_t) timeout1 < (uint64_t) timeout2) ? timeout1 : timeout2;
797 }
798 
799 /**
800  * initclocks:
801  *
802  * Initialise the clock & timer infrastructure
803  */
804 void init_clocks(QEMUTimerListNotifyCB *notify_cb);
805 
get_max_clock_jump(void)806 static inline int64_t get_max_clock_jump(void)
807 {
808     /* This should be small enough to prevent excessive interrupts from being
809      * generated by the RTC on clock jumps, but large enough to avoid frequent
810      * unnecessary resets in idle VMs.
811      */
812     return 60 * NANOSECONDS_PER_SECOND;
813 }
814 
815 /*
816  * Low level clock functions
817  */
818 
819 /* get host real time in nanosecond */
get_clock_realtime(void)820 static inline int64_t get_clock_realtime(void)
821 {
822     struct timeval tv;
823 
824     gettimeofday(&tv, NULL);
825     return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
826 }
827 
828 extern int64_t clock_start;
829 
830 /* Warning: don't insert tracepoints into these functions, they are
831    also used by simpletrace backend and tracepoints would cause
832    an infinite recursion! */
833 #ifdef _WIN32
834 extern int64_t clock_freq;
835 
get_clock(void)836 static inline int64_t get_clock(void)
837 {
838     LARGE_INTEGER ti;
839     QueryPerformanceCounter(&ti);
840     return muldiv64(ti.QuadPart, NANOSECONDS_PER_SECOND, clock_freq);
841 }
842 
843 #else
844 
845 extern int use_rt_clock;
846 
get_clock(void)847 static inline int64_t get_clock(void)
848 {
849     if (use_rt_clock) {
850         struct timespec ts;
851         clock_gettime(CLOCK_MONOTONIC, &ts);
852         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
853     } else {
854         /* XXX: using gettimeofday leads to problems if the date
855            changes, so it should be avoided. */
856         return get_clock_realtime();
857     }
858 }
859 #endif
860 
861 /*******************************************/
862 /* host CPU ticks (if available) */
863 
864 #if defined(_ARCH_PPC)
865 
cpu_get_host_ticks(void)866 static inline int64_t cpu_get_host_ticks(void)
867 {
868     int64_t retval;
869 #ifdef _ARCH_PPC64
870     /* This reads timebase in one 64bit go and includes Cell workaround from:
871        http://ozlabs.org/pipermail/linuxppc-dev/2006-October/027052.html
872     */
873     __asm__ __volatile__ ("mftb    %0\n\t"
874                           "cmpwi   %0,0\n\t"
875                           "beq-    $-8"
876                           : "=r" (retval));
877 #else
878     /* http://ozlabs.org/pipermail/linuxppc-dev/1999-October/003889.html */
879     unsigned long junk;
880     __asm__ __volatile__ ("mfspr   %1,269\n\t"  /* mftbu */
881                           "mfspr   %L0,268\n\t" /* mftb */
882                           "mfspr   %0,269\n\t"  /* mftbu */
883                           "cmpw    %0,%1\n\t"
884                           "bne     $-16"
885                           : "=r" (retval), "=r" (junk));
886 #endif
887     return retval;
888 }
889 
890 #elif defined(__i386__)
891 
cpu_get_host_ticks(void)892 static inline int64_t cpu_get_host_ticks(void)
893 {
894     int64_t val;
895     asm volatile ("rdtsc" : "=A" (val));
896     return val;
897 }
898 
899 #elif defined(__x86_64__)
900 
cpu_get_host_ticks(void)901 static inline int64_t cpu_get_host_ticks(void)
902 {
903     uint32_t low,high;
904     int64_t val;
905     asm volatile("rdtsc" : "=a" (low), "=d" (high));
906     val = high;
907     val <<= 32;
908     val |= low;
909     return val;
910 }
911 
912 #elif defined(__hppa__)
913 
cpu_get_host_ticks(void)914 static inline int64_t cpu_get_host_ticks(void)
915 {
916     int val;
917     asm volatile ("mfctl %%cr16, %0" : "=r"(val));
918     return val;
919 }
920 
921 #elif defined(__s390__)
922 
cpu_get_host_ticks(void)923 static inline int64_t cpu_get_host_ticks(void)
924 {
925     int64_t val;
926     asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
927     return val;
928 }
929 
930 #elif defined(__sparc__)
931 
cpu_get_host_ticks(void)932 static inline int64_t cpu_get_host_ticks (void)
933 {
934 #if defined(_LP64)
935     uint64_t        rval;
936     asm volatile("rd %%tick,%0" : "=r"(rval));
937     return rval;
938 #else
939     /* We need an %o or %g register for this.  For recent enough gcc
940        there is an "h" constraint for that.  Don't bother with that.  */
941     union {
942         uint64_t i64;
943         struct {
944             uint32_t high;
945             uint32_t low;
946         }       i32;
947     } rval;
948     asm volatile("rd %%tick,%%g1; srlx %%g1,32,%0; mov %%g1,%1"
949                  : "=r"(rval.i32.high), "=r"(rval.i32.low) : : "g1");
950     return rval.i64;
951 #endif
952 }
953 
954 #elif defined(__mips__) && \
955     ((defined(__mips_isa_rev) && __mips_isa_rev >= 2) || defined(__linux__))
956 /*
957  * binutils wants to use rdhwr only on mips32r2
958  * but as linux kernel emulate it, it's fine
959  * to use it.
960  *
961  */
962 #define MIPS_RDHWR(rd, value) {                         \
963         __asm__ __volatile__ (".set   push\n\t"         \
964                               ".set mips32r2\n\t"       \
965                               "rdhwr  %0, "rd"\n\t"     \
966                               ".set   pop"              \
967                               : "=r" (value));          \
968     }
969 
cpu_get_host_ticks(void)970 static inline int64_t cpu_get_host_ticks(void)
971 {
972     /* On kernels >= 2.6.25 rdhwr <reg>, $2 and $3 are emulated */
973     uint32_t count;
974     static uint32_t cyc_per_count = 0;
975 
976     if (!cyc_per_count) {
977         MIPS_RDHWR("$3", cyc_per_count);
978     }
979 
980     MIPS_RDHWR("$2", count);
981     return (int64_t)(count * cyc_per_count);
982 }
983 
984 #elif defined(__alpha__)
985 
cpu_get_host_ticks(void)986 static inline int64_t cpu_get_host_ticks(void)
987 {
988     uint64_t cc;
989     uint32_t cur, ofs;
990 
991     asm volatile("rpcc %0" : "=r"(cc));
992     cur = cc;
993     ofs = cc >> 32;
994     return cur - ofs;
995 }
996 
997 #elif defined(__riscv) && __riscv_xlen == 32
cpu_get_host_ticks(void)998 static inline int64_t cpu_get_host_ticks(void)
999 {
1000     uint32_t lo, hi, tmph;
1001     do {
1002         asm volatile("RDTIMEH %0\n\t"
1003                      "RDTIME %1\n\t"
1004                      "RDTIMEH %2"
1005                      : "=r"(hi), "=r"(lo), "=r"(tmph));
1006     } while (unlikely(tmph != hi));
1007     return lo | (uint64_t)hi << 32;
1008 }
1009 
1010 #elif defined(__riscv) && __riscv_xlen > 32
cpu_get_host_ticks(void)1011 static inline int64_t cpu_get_host_ticks(void)
1012 {
1013     int64_t val;
1014 
1015     asm volatile("RDTIME %0" : "=r"(val));
1016     return val;
1017 }
1018 
1019 #elif defined(__loongarch64)
cpu_get_host_ticks(void)1020 static inline int64_t cpu_get_host_ticks(void)
1021 {
1022     uint64_t val;
1023 
1024     asm volatile("rdtime.d %0, $zero" : "=r"(val));
1025     return val;
1026 }
1027 
1028 #else
1029 /* The host CPU doesn't have an easily accessible cycle counter.
1030    Just return a monotonically increasing value.  This will be
1031    totally wrong, but hopefully better than nothing.  */
cpu_get_host_ticks(void)1032 static inline int64_t cpu_get_host_ticks(void)
1033 {
1034     return get_clock();
1035 }
1036 #endif
1037 
1038 #endif
1039