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