xref: /openbmc/qemu/include/qemu/timer.h (revision a3500b22a18ec4195793037c0f45a47bd5a59e51)
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  * Returns: a pointer to the timer
511  */
timer_new_full(QEMUTimerListGroup * timer_list_group,QEMUClockType type,int scale,int attributes,QEMUTimerCB * cb,void * opaque)512 static inline QEMUTimer *timer_new_full(QEMUTimerListGroup *timer_list_group,
513                                         QEMUClockType type,
514                                         int scale, int attributes,
515                                         QEMUTimerCB *cb, void *opaque)
516 {
517     QEMUTimer *ts = g_new0(QEMUTimer, 1);
518     timer_init_full(ts, timer_list_group, type, scale, attributes, cb, opaque);
519     return ts;
520 }
521 
522 /**
523  * timer_new:
524  * @type: the clock type to use
525  * @scale: the scale value for the timer
526  * @cb: the callback to be called when the timer expires
527  * @opaque: the opaque pointer to be passed to the callback
528  *
529  * Create a new timer with the given scale,
530  * and associate it with the default timer list for the clock type @type.
531  * See timer_new_full for details.
532  *
533  * Returns: a pointer to the timer
534  */
timer_new(QEMUClockType type,int scale,QEMUTimerCB * cb,void * opaque)535 static inline QEMUTimer *timer_new(QEMUClockType type, int scale,
536                                    QEMUTimerCB *cb, void *opaque)
537 {
538     return timer_new_full(NULL, type, scale, 0, cb, opaque);
539 }
540 
541 /**
542  * timer_new_ns:
543  * @type: the clock type to associate with the timer
544  * @cb: the callback to call when the timer expires
545  * @opaque: the opaque pointer to pass to the callback
546  *
547  * Create a new timer with nanosecond scale on the default timer list
548  * associated with the clock.
549  * See timer_new_full for details.
550  *
551  * Returns: a pointer to the newly created timer
552  */
timer_new_ns(QEMUClockType type,QEMUTimerCB * cb,void * opaque)553 static inline QEMUTimer *timer_new_ns(QEMUClockType type, QEMUTimerCB *cb,
554                                       void *opaque)
555 {
556     return timer_new(type, SCALE_NS, cb, opaque);
557 }
558 
559 /**
560  * timer_new_us:
561  * @type: the clock type to associate with the timer
562  * @cb: the callback to call when the timer expires
563  * @opaque: the opaque pointer to pass to the callback
564  *
565  * Create a new timer with microsecond scale on the default timer list
566  * associated with the clock.
567  * See timer_new_full for details.
568  *
569  * Returns: a pointer to the newly created timer
570  */
timer_new_us(QEMUClockType type,QEMUTimerCB * cb,void * opaque)571 static inline QEMUTimer *timer_new_us(QEMUClockType type, QEMUTimerCB *cb,
572                                       void *opaque)
573 {
574     return timer_new(type, SCALE_US, cb, opaque);
575 }
576 
577 /**
578  * timer_new_ms:
579  * @type: the clock type to associate with the timer
580  * @cb: the callback to call when the timer expires
581  * @opaque: the opaque pointer to pass to the callback
582  *
583  * Create a new timer with millisecond scale on the default timer list
584  * associated with the clock.
585  * See timer_new_full for details.
586  *
587  * Returns: a pointer to the newly created timer
588  */
timer_new_ms(QEMUClockType type,QEMUTimerCB * cb,void * opaque)589 static inline QEMUTimer *timer_new_ms(QEMUClockType type, QEMUTimerCB *cb,
590                                       void *opaque)
591 {
592     return timer_new(type, SCALE_MS, cb, opaque);
593 }
594 
595 /**
596  * timer_deinit:
597  * @ts: the timer to be de-initialised
598  *
599  * Deassociate the timer from any timerlist.  You should
600  * call timer_del before.  After this call, any further
601  * timer_del call cannot cause dangling pointer accesses
602  * even if the previously used timerlist is freed.
603  */
604 void timer_deinit(QEMUTimer *ts);
605 
606 /**
607  * timer_del:
608  * @ts: the timer
609  *
610  * Delete a timer from the active list.
611  *
612  * This function is thread-safe but the timer and its timer list must not be
613  * freed while this function is running.
614  */
615 void timer_del(QEMUTimer *ts);
616 
617 /**
618  * timer_free:
619  * @ts: the timer
620  *
621  * Free a timer. This will call timer_del() for you to remove
622  * the timer from the active list if it was still active.
623  */
timer_free(QEMUTimer * ts)624 static inline void timer_free(QEMUTimer *ts)
625 {
626     if (ts) {
627         timer_del(ts);
628         g_free(ts);
629     }
630 }
631 
632 /**
633  * timer_mod_ns:
634  * @ts: the timer
635  * @expire_time: the expiry time in nanoseconds
636  *
637  * Modify a timer to expire at @expire_time
638  *
639  * This function is thread-safe but the timer and its timer list must not be
640  * freed while this function is running.
641  */
642 void timer_mod_ns(QEMUTimer *ts, int64_t expire_time);
643 
644 /**
645  * timer_mod_anticipate_ns:
646  * @ts: the timer
647  * @expire_time: the expiry time in nanoseconds
648  *
649  * Modify a timer to expire at @expire_time or the current time,
650  * whichever comes earlier.
651  *
652  * This function is thread-safe but the timer and its timer list must not be
653  * freed while this function is running.
654  */
655 void timer_mod_anticipate_ns(QEMUTimer *ts, int64_t expire_time);
656 
657 /**
658  * timer_mod:
659  * @ts: the timer
660  * @expire_time: the expire time in the units associated with the timer
661  *
662  * Modify a timer to expiry at @expire_time, taking into
663  * account the scale associated with the timer.
664  *
665  * This function is thread-safe but the timer and its timer list must not be
666  * freed while this function is running.
667  */
668 void timer_mod(QEMUTimer *ts, int64_t expire_timer);
669 
670 /**
671  * timer_mod_anticipate:
672  * @ts: the timer
673  * @expire_time: the expire time in the units associated with the timer
674  *
675  * Modify a timer to expire at @expire_time or the current time, whichever
676  * comes earlier, taking into account the scale associated with the timer.
677  *
678  * This function is thread-safe but the timer and its timer list must not be
679  * freed while this function is running.
680  */
681 void timer_mod_anticipate(QEMUTimer *ts, int64_t expire_time);
682 
683 /**
684  * timer_pending:
685  * @ts: the timer
686  *
687  * Determines whether a timer is pending (i.e. is on the
688  * active list of timers, whether or not it has not yet expired).
689  *
690  * Returns: true if the timer is pending
691  */
692 bool timer_pending(QEMUTimer *ts);
693 
694 /**
695  * timer_expired:
696  * @ts: the timer
697  * @current_time: the current time
698  *
699  * Determines whether a timer has expired.
700  *
701  * Returns: true if the timer has expired
702  */
703 bool timer_expired(QEMUTimer *timer_head, int64_t current_time);
704 
705 /**
706  * timer_expire_time_ns:
707  * @ts: the timer
708  *
709  * Determine the expiry time of a timer
710  *
711  * Returns: the expiry time in nanoseconds
712  */
713 uint64_t timer_expire_time_ns(QEMUTimer *ts);
714 
715 /**
716  * timer_get:
717  * @f: the file
718  * @ts: the timer
719  *
720  * Read a timer @ts from a file @f
721  */
722 void timer_get(QEMUFile *f, QEMUTimer *ts);
723 
724 /**
725  * timer_put:
726  * @f: the file
727  * @ts: the timer
728  */
729 void timer_put(QEMUFile *f, QEMUTimer *ts);
730 
731 /*
732  * General utility functions
733  */
734 
735 /**
736  * qemu_timeout_ns_to_ms:
737  * @ns: nanosecond timeout value
738  *
739  * Convert a nanosecond timeout value (or -1) to
740  * a millisecond value (or -1), always rounding up.
741  *
742  * Returns: millisecond timeout value
743  */
744 int qemu_timeout_ns_to_ms(int64_t ns);
745 
746 /**
747  * qemu_poll_ns:
748  * @fds: Array of file descriptors
749  * @nfds: number of file descriptors
750  * @timeout: timeout in nanoseconds
751  *
752  * Perform a poll like g_poll but with a timeout in nanoseconds.
753  * See g_poll documentation for further details.
754  *
755  * Returns: number of fds ready
756  */
757 int qemu_poll_ns(GPollFD *fds, guint nfds, int64_t timeout);
758 
759 /**
760  * qemu_soonest_timeout:
761  * @timeout1: first timeout in nanoseconds (or -1 for infinite)
762  * @timeout2: second timeout in nanoseconds (or -1 for infinite)
763  *
764  * Calculates the soonest of two timeout values. -1 means infinite, which
765  * is later than any other value.
766  *
767  * Returns: soonest timeout value in nanoseconds (or -1 for infinite)
768  */
qemu_soonest_timeout(int64_t timeout1,int64_t timeout2)769 static inline int64_t qemu_soonest_timeout(int64_t timeout1, int64_t timeout2)
770 {
771     /* we can abuse the fact that -1 (which means infinite) is a maximal
772      * value when cast to unsigned. As this is disgusting, it's kept in
773      * one inline function.
774      */
775     return ((uint64_t) timeout1 < (uint64_t) timeout2) ? timeout1 : timeout2;
776 }
777 
778 /**
779  * initclocks:
780  *
781  * Initialise the clock & timer infrastructure
782  */
783 void init_clocks(QEMUTimerListNotifyCB *notify_cb);
784 
get_max_clock_jump(void)785 static inline int64_t get_max_clock_jump(void)
786 {
787     /* This should be small enough to prevent excessive interrupts from being
788      * generated by the RTC on clock jumps, but large enough to avoid frequent
789      * unnecessary resets in idle VMs.
790      */
791     return 60 * NANOSECONDS_PER_SECOND;
792 }
793 
794 /*
795  * Low level clock functions
796  */
797 
798 /* get host real time in nanosecond */
get_clock_realtime(void)799 static inline int64_t get_clock_realtime(void)
800 {
801     struct timeval tv;
802 
803     gettimeofday(&tv, NULL);
804     return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
805 }
806 
807 extern int64_t clock_start;
808 
809 /* Warning: don't insert tracepoints into these functions, they are
810    also used by simpletrace backend and tracepoints would cause
811    an infinite recursion! */
812 #ifdef _WIN32
813 extern int64_t clock_freq;
814 
get_clock(void)815 static inline int64_t get_clock(void)
816 {
817     LARGE_INTEGER ti;
818     QueryPerformanceCounter(&ti);
819     return muldiv64(ti.QuadPart, NANOSECONDS_PER_SECOND, clock_freq);
820 }
821 
822 #else
823 
824 extern int use_rt_clock;
825 
get_clock(void)826 static inline int64_t get_clock(void)
827 {
828     if (use_rt_clock) {
829         struct timespec ts;
830         clock_gettime(CLOCK_MONOTONIC, &ts);
831         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
832     } else {
833         /* XXX: using gettimeofday leads to problems if the date
834            changes, so it should be avoided. */
835         return get_clock_realtime();
836     }
837 }
838 #endif
839 
840 /*******************************************/
841 /* host CPU ticks (if available) */
842 
843 #if defined(_ARCH_PPC)
844 
cpu_get_host_ticks(void)845 static inline int64_t cpu_get_host_ticks(void)
846 {
847     int64_t retval;
848 #ifdef _ARCH_PPC64
849     /* This reads timebase in one 64bit go and includes Cell workaround from:
850        http://ozlabs.org/pipermail/linuxppc-dev/2006-October/027052.html
851     */
852     __asm__ __volatile__ ("mftb    %0\n\t"
853                           "cmpwi   %0,0\n\t"
854                           "beq-    $-8"
855                           : "=r" (retval));
856 #else
857     /* http://ozlabs.org/pipermail/linuxppc-dev/1999-October/003889.html */
858     unsigned long junk;
859     __asm__ __volatile__ ("mfspr   %1,269\n\t"  /* mftbu */
860                           "mfspr   %L0,268\n\t" /* mftb */
861                           "mfspr   %0,269\n\t"  /* mftbu */
862                           "cmpw    %0,%1\n\t"
863                           "bne     $-16"
864                           : "=r" (retval), "=r" (junk));
865 #endif
866     return retval;
867 }
868 
869 #elif defined(__i386__)
870 
cpu_get_host_ticks(void)871 static inline int64_t cpu_get_host_ticks(void)
872 {
873     int64_t val;
874     asm volatile ("rdtsc" : "=A" (val));
875     return val;
876 }
877 
878 #elif defined(__x86_64__)
879 
cpu_get_host_ticks(void)880 static inline int64_t cpu_get_host_ticks(void)
881 {
882     uint32_t low,high;
883     int64_t val;
884     asm volatile("rdtsc" : "=a" (low), "=d" (high));
885     val = high;
886     val <<= 32;
887     val |= low;
888     return val;
889 }
890 
891 #elif defined(__hppa__)
892 
cpu_get_host_ticks(void)893 static inline int64_t cpu_get_host_ticks(void)
894 {
895     int val;
896     asm volatile ("mfctl %%cr16, %0" : "=r"(val));
897     return val;
898 }
899 
900 #elif defined(__s390__)
901 
cpu_get_host_ticks(void)902 static inline int64_t cpu_get_host_ticks(void)
903 {
904     int64_t val;
905     asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
906     return val;
907 }
908 
909 #elif defined(__sparc__)
910 
cpu_get_host_ticks(void)911 static inline int64_t cpu_get_host_ticks (void)
912 {
913 #if defined(_LP64)
914     uint64_t        rval;
915     asm volatile("rd %%tick,%0" : "=r"(rval));
916     return rval;
917 #else
918     /* We need an %o or %g register for this.  For recent enough gcc
919        there is an "h" constraint for that.  Don't bother with that.  */
920     union {
921         uint64_t i64;
922         struct {
923             uint32_t high;
924             uint32_t low;
925         }       i32;
926     } rval;
927     asm volatile("rd %%tick,%%g1; srlx %%g1,32,%0; mov %%g1,%1"
928                  : "=r"(rval.i32.high), "=r"(rval.i32.low) : : "g1");
929     return rval.i64;
930 #endif
931 }
932 
933 #elif defined(__mips__) && \
934     ((defined(__mips_isa_rev) && __mips_isa_rev >= 2) || defined(__linux__))
935 /*
936  * binutils wants to use rdhwr only on mips32r2
937  * but as linux kernel emulate it, it's fine
938  * to use it.
939  *
940  */
941 #define MIPS_RDHWR(rd, value) {                         \
942         __asm__ __volatile__ (".set   push\n\t"         \
943                               ".set mips32r2\n\t"       \
944                               "rdhwr  %0, "rd"\n\t"     \
945                               ".set   pop"              \
946                               : "=r" (value));          \
947     }
948 
cpu_get_host_ticks(void)949 static inline int64_t cpu_get_host_ticks(void)
950 {
951     /* On kernels >= 2.6.25 rdhwr <reg>, $2 and $3 are emulated */
952     uint32_t count;
953     static uint32_t cyc_per_count = 0;
954 
955     if (!cyc_per_count) {
956         MIPS_RDHWR("$3", cyc_per_count);
957     }
958 
959     MIPS_RDHWR("$2", count);
960     return (int64_t)(count * cyc_per_count);
961 }
962 
963 #elif defined(__alpha__)
964 
cpu_get_host_ticks(void)965 static inline int64_t cpu_get_host_ticks(void)
966 {
967     uint64_t cc;
968     uint32_t cur, ofs;
969 
970     asm volatile("rpcc %0" : "=r"(cc));
971     cur = cc;
972     ofs = cc >> 32;
973     return cur - ofs;
974 }
975 
976 #elif defined(__riscv) && __riscv_xlen == 32
cpu_get_host_ticks(void)977 static inline int64_t cpu_get_host_ticks(void)
978 {
979     uint32_t lo, hi, tmph;
980     do {
981         asm volatile("RDTIMEH %0\n\t"
982                      "RDTIME %1\n\t"
983                      "RDTIMEH %2"
984                      : "=r"(hi), "=r"(lo), "=r"(tmph));
985     } while (unlikely(tmph != hi));
986     return lo | (uint64_t)hi << 32;
987 }
988 
989 #elif defined(__riscv) && __riscv_xlen > 32
cpu_get_host_ticks(void)990 static inline int64_t cpu_get_host_ticks(void)
991 {
992     int64_t val;
993 
994     asm volatile("RDTIME %0" : "=r"(val));
995     return val;
996 }
997 
998 #elif defined(__loongarch64)
cpu_get_host_ticks(void)999 static inline int64_t cpu_get_host_ticks(void)
1000 {
1001     uint64_t val;
1002 
1003     asm volatile("rdtime.d %0, $zero" : "=r"(val));
1004     return val;
1005 }
1006 
1007 #else
1008 /* The host CPU doesn't have an easily accessible cycle counter.
1009    Just return a monotonically increasing value.  This will be
1010    totally wrong, but hopefully better than nothing.  */
cpu_get_host_ticks(void)1011 static inline int64_t cpu_get_host_ticks(void)
1012 {
1013     return get_clock();
1014 }
1015 #endif
1016 
1017 #endif
1018