qemu-timer.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. /*
  2. * QEMU System Emulator
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "sysemu.h"
  25. #include "net.h"
  26. #include "monitor.h"
  27. #include "console.h"
  28. #include "hw/hw.h"
  29. #include <unistd.h>
  30. #include <fcntl.h>
  31. #include <time.h>
  32. #include <errno.h>
  33. #include <sys/time.h>
  34. #include <signal.h>
  35. #ifdef __FreeBSD__
  36. #include <sys/param.h>
  37. #endif
  38. #ifdef _WIN32
  39. #include <windows.h>
  40. #include <mmsystem.h>
  41. #endif
  42. #include "qemu-timer.h"
  43. /* Conversion factor from emulated instructions to virtual clock ticks. */
  44. int icount_time_shift;
  45. /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
  46. #define MAX_ICOUNT_SHIFT 10
  47. /* Compensate for varying guest execution speed. */
  48. int64_t qemu_icount_bias;
  49. static QEMUTimer *icount_rt_timer;
  50. static QEMUTimer *icount_vm_timer;
  51. /***********************************************************/
  52. /* guest cycle counter */
  53. typedef struct TimersState {
  54. int64_t cpu_ticks_prev;
  55. int64_t cpu_ticks_offset;
  56. int64_t cpu_clock_offset;
  57. int32_t cpu_ticks_enabled;
  58. int64_t dummy;
  59. } TimersState;
  60. TimersState timers_state;
  61. /* return the host CPU cycle counter and handle stop/restart */
  62. int64_t cpu_get_ticks(void)
  63. {
  64. if (use_icount) {
  65. return cpu_get_icount();
  66. }
  67. if (!timers_state.cpu_ticks_enabled) {
  68. return timers_state.cpu_ticks_offset;
  69. } else {
  70. int64_t ticks;
  71. ticks = cpu_get_real_ticks();
  72. if (timers_state.cpu_ticks_prev > ticks) {
  73. /* Note: non increasing ticks may happen if the host uses
  74. software suspend */
  75. timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
  76. }
  77. timers_state.cpu_ticks_prev = ticks;
  78. return ticks + timers_state.cpu_ticks_offset;
  79. }
  80. }
  81. /* return the host CPU monotonic timer and handle stop/restart */
  82. static int64_t cpu_get_clock(void)
  83. {
  84. int64_t ti;
  85. if (!timers_state.cpu_ticks_enabled) {
  86. return timers_state.cpu_clock_offset;
  87. } else {
  88. ti = get_clock();
  89. return ti + timers_state.cpu_clock_offset;
  90. }
  91. }
  92. #ifndef CONFIG_IOTHREAD
  93. static int64_t qemu_icount_delta(void)
  94. {
  95. if (!use_icount) {
  96. return 5000 * (int64_t) 1000000;
  97. } else if (use_icount == 1) {
  98. /* When not using an adaptive execution frequency
  99. we tend to get badly out of sync with real time,
  100. so just delay for a reasonable amount of time. */
  101. return 0;
  102. } else {
  103. return cpu_get_icount() - cpu_get_clock();
  104. }
  105. }
  106. #endif
  107. /* enable cpu_get_ticks() */
  108. void cpu_enable_ticks(void)
  109. {
  110. if (!timers_state.cpu_ticks_enabled) {
  111. timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
  112. timers_state.cpu_clock_offset -= get_clock();
  113. timers_state.cpu_ticks_enabled = 1;
  114. }
  115. }
  116. /* disable cpu_get_ticks() : the clock is stopped. You must not call
  117. cpu_get_ticks() after that. */
  118. void cpu_disable_ticks(void)
  119. {
  120. if (timers_state.cpu_ticks_enabled) {
  121. timers_state.cpu_ticks_offset = cpu_get_ticks();
  122. timers_state.cpu_clock_offset = cpu_get_clock();
  123. timers_state.cpu_ticks_enabled = 0;
  124. }
  125. }
  126. /***********************************************************/
  127. /* timers */
  128. #define QEMU_CLOCK_REALTIME 0
  129. #define QEMU_CLOCK_VIRTUAL 1
  130. #define QEMU_CLOCK_HOST 2
  131. struct QEMUClock {
  132. int type;
  133. int enabled;
  134. QEMUTimer *warp_timer;
  135. NotifierList reset_notifiers;
  136. int64_t last;
  137. };
  138. struct QEMUTimer {
  139. QEMUClock *clock;
  140. int64_t expire_time; /* in nanoseconds */
  141. int scale;
  142. QEMUTimerCB *cb;
  143. void *opaque;
  144. struct QEMUTimer *next;
  145. };
  146. struct qemu_alarm_timer {
  147. char const *name;
  148. int (*start)(struct qemu_alarm_timer *t);
  149. void (*stop)(struct qemu_alarm_timer *t);
  150. void (*rearm)(struct qemu_alarm_timer *t);
  151. #if defined(__linux__)
  152. int fd;
  153. timer_t timer;
  154. #elif defined(_WIN32)
  155. HANDLE timer;
  156. #endif
  157. char expired;
  158. char pending;
  159. };
  160. static struct qemu_alarm_timer *alarm_timer;
  161. static bool qemu_timer_expired_ns(QEMUTimer *timer_head, int64_t current_time)
  162. {
  163. return timer_head && (timer_head->expire_time <= current_time);
  164. }
  165. int qemu_alarm_pending(void)
  166. {
  167. return alarm_timer->pending;
  168. }
  169. static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
  170. {
  171. return !!t->rearm;
  172. }
  173. static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
  174. {
  175. if (!alarm_has_dynticks(t))
  176. return;
  177. t->rearm(t);
  178. }
  179. /* TODO: MIN_TIMER_REARM_NS should be optimized */
  180. #define MIN_TIMER_REARM_NS 250000
  181. #ifdef _WIN32
  182. static int mm_start_timer(struct qemu_alarm_timer *t);
  183. static void mm_stop_timer(struct qemu_alarm_timer *t);
  184. static void mm_rearm_timer(struct qemu_alarm_timer *t);
  185. static int win32_start_timer(struct qemu_alarm_timer *t);
  186. static void win32_stop_timer(struct qemu_alarm_timer *t);
  187. static void win32_rearm_timer(struct qemu_alarm_timer *t);
  188. #else
  189. static int unix_start_timer(struct qemu_alarm_timer *t);
  190. static void unix_stop_timer(struct qemu_alarm_timer *t);
  191. static void unix_rearm_timer(struct qemu_alarm_timer *t);
  192. #ifdef __linux__
  193. static int dynticks_start_timer(struct qemu_alarm_timer *t);
  194. static void dynticks_stop_timer(struct qemu_alarm_timer *t);
  195. static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
  196. #endif /* __linux__ */
  197. #endif /* _WIN32 */
  198. /* Correlation between real and virtual time is always going to be
  199. fairly approximate, so ignore small variation.
  200. When the guest is idle real and virtual time will be aligned in
  201. the IO wait loop. */
  202. #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
  203. static void icount_adjust(void)
  204. {
  205. int64_t cur_time;
  206. int64_t cur_icount;
  207. int64_t delta;
  208. static int64_t last_delta;
  209. /* If the VM is not running, then do nothing. */
  210. if (!vm_running)
  211. return;
  212. cur_time = cpu_get_clock();
  213. cur_icount = qemu_get_clock_ns(vm_clock);
  214. delta = cur_icount - cur_time;
  215. /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
  216. if (delta > 0
  217. && last_delta + ICOUNT_WOBBLE < delta * 2
  218. && icount_time_shift > 0) {
  219. /* The guest is getting too far ahead. Slow time down. */
  220. icount_time_shift--;
  221. }
  222. if (delta < 0
  223. && last_delta - ICOUNT_WOBBLE > delta * 2
  224. && icount_time_shift < MAX_ICOUNT_SHIFT) {
  225. /* The guest is getting too far behind. Speed time up. */
  226. icount_time_shift++;
  227. }
  228. last_delta = delta;
  229. qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
  230. }
  231. static void icount_adjust_rt(void * opaque)
  232. {
  233. qemu_mod_timer(icount_rt_timer,
  234. qemu_get_clock_ms(rt_clock) + 1000);
  235. icount_adjust();
  236. }
  237. static void icount_adjust_vm(void * opaque)
  238. {
  239. qemu_mod_timer(icount_vm_timer,
  240. qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
  241. icount_adjust();
  242. }
  243. int64_t qemu_icount_round(int64_t count)
  244. {
  245. return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
  246. }
  247. static struct qemu_alarm_timer alarm_timers[] = {
  248. #ifndef _WIN32
  249. #ifdef __linux__
  250. {"dynticks", dynticks_start_timer,
  251. dynticks_stop_timer, dynticks_rearm_timer},
  252. #endif
  253. {"unix", unix_start_timer, unix_stop_timer, unix_rearm_timer},
  254. #else
  255. {"mmtimer", mm_start_timer, mm_stop_timer, NULL},
  256. {"mmtimer2", mm_start_timer, mm_stop_timer, mm_rearm_timer},
  257. {"dynticks", win32_start_timer, win32_stop_timer, win32_rearm_timer},
  258. {"win32", win32_start_timer, win32_stop_timer, NULL},
  259. #endif
  260. {NULL, }
  261. };
  262. static void show_available_alarms(void)
  263. {
  264. int i;
  265. printf("Available alarm timers, in order of precedence:\n");
  266. for (i = 0; alarm_timers[i].name; i++)
  267. printf("%s\n", alarm_timers[i].name);
  268. }
  269. void configure_alarms(char const *opt)
  270. {
  271. int i;
  272. int cur = 0;
  273. int count = ARRAY_SIZE(alarm_timers) - 1;
  274. char *arg;
  275. char *name;
  276. struct qemu_alarm_timer tmp;
  277. if (!strcmp(opt, "?")) {
  278. show_available_alarms();
  279. exit(0);
  280. }
  281. arg = g_strdup(opt);
  282. /* Reorder the array */
  283. name = strtok(arg, ",");
  284. while (name) {
  285. for (i = 0; i < count && alarm_timers[i].name; i++) {
  286. if (!strcmp(alarm_timers[i].name, name))
  287. break;
  288. }
  289. if (i == count) {
  290. fprintf(stderr, "Unknown clock %s\n", name);
  291. goto next;
  292. }
  293. if (i < cur)
  294. /* Ignore */
  295. goto next;
  296. /* Swap */
  297. tmp = alarm_timers[i];
  298. alarm_timers[i] = alarm_timers[cur];
  299. alarm_timers[cur] = tmp;
  300. cur++;
  301. next:
  302. name = strtok(NULL, ",");
  303. }
  304. g_free(arg);
  305. if (cur) {
  306. /* Disable remaining timers */
  307. for (i = cur; i < count; i++)
  308. alarm_timers[i].name = NULL;
  309. } else {
  310. show_available_alarms();
  311. exit(1);
  312. }
  313. }
  314. #define QEMU_NUM_CLOCKS 3
  315. QEMUClock *rt_clock;
  316. QEMUClock *vm_clock;
  317. QEMUClock *host_clock;
  318. static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
  319. static QEMUClock *qemu_new_clock(int type)
  320. {
  321. QEMUClock *clock;
  322. clock = g_malloc0(sizeof(QEMUClock));
  323. clock->type = type;
  324. clock->enabled = 1;
  325. notifier_list_init(&clock->reset_notifiers);
  326. /* required to detect & report backward jumps */
  327. if (type == QEMU_CLOCK_HOST) {
  328. clock->last = get_clock_realtime();
  329. }
  330. return clock;
  331. }
  332. void qemu_clock_enable(QEMUClock *clock, int enabled)
  333. {
  334. clock->enabled = enabled;
  335. }
  336. static int64_t vm_clock_warp_start;
  337. static void icount_warp_rt(void *opaque)
  338. {
  339. if (vm_clock_warp_start == -1) {
  340. return;
  341. }
  342. if (vm_running) {
  343. int64_t clock = qemu_get_clock_ns(rt_clock);
  344. int64_t warp_delta = clock - vm_clock_warp_start;
  345. if (use_icount == 1) {
  346. qemu_icount_bias += warp_delta;
  347. } else {
  348. /*
  349. * In adaptive mode, do not let the vm_clock run too
  350. * far ahead of real time.
  351. */
  352. int64_t cur_time = cpu_get_clock();
  353. int64_t cur_icount = qemu_get_clock_ns(vm_clock);
  354. int64_t delta = cur_time - cur_icount;
  355. qemu_icount_bias += MIN(warp_delta, delta);
  356. }
  357. if (qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
  358. qemu_get_clock_ns(vm_clock))) {
  359. qemu_notify_event();
  360. }
  361. }
  362. vm_clock_warp_start = -1;
  363. }
  364. void qemu_clock_warp(QEMUClock *clock)
  365. {
  366. int64_t deadline;
  367. if (!clock->warp_timer) {
  368. return;
  369. }
  370. /*
  371. * There are too many global variables to make the "warp" behavior
  372. * applicable to other clocks. But a clock argument removes the
  373. * need for if statements all over the place.
  374. */
  375. assert(clock == vm_clock);
  376. /*
  377. * If the CPUs have been sleeping, advance the vm_clock timer now. This
  378. * ensures that the deadline for the timer is computed correctly below.
  379. * This also makes sure that the insn counter is synchronized before the
  380. * CPU starts running, in case the CPU is woken by an event other than
  381. * the earliest vm_clock timer.
  382. */
  383. icount_warp_rt(NULL);
  384. if (!all_cpu_threads_idle() || !active_timers[clock->type]) {
  385. qemu_del_timer(clock->warp_timer);
  386. return;
  387. }
  388. vm_clock_warp_start = qemu_get_clock_ns(rt_clock);
  389. deadline = qemu_next_icount_deadline();
  390. if (deadline > 0) {
  391. /*
  392. * Ensure the vm_clock proceeds even when the virtual CPU goes to
  393. * sleep. Otherwise, the CPU might be waiting for a future timer
  394. * interrupt to wake it up, but the interrupt never comes because
  395. * the vCPU isn't running any insns and thus doesn't advance the
  396. * vm_clock.
  397. *
  398. * An extreme solution for this problem would be to never let VCPUs
  399. * sleep in icount mode if there is a pending vm_clock timer; rather
  400. * time could just advance to the next vm_clock event. Instead, we
  401. * do stop VCPUs and only advance vm_clock after some "real" time,
  402. * (related to the time left until the next event) has passed. This
  403. * rt_clock timer will do this. This avoids that the warps are too
  404. * visible externally---for example, you will not be sending network
  405. * packets continously instead of every 100ms.
  406. */
  407. qemu_mod_timer(clock->warp_timer, vm_clock_warp_start + deadline);
  408. } else {
  409. qemu_notify_event();
  410. }
  411. }
  412. QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
  413. QEMUTimerCB *cb, void *opaque)
  414. {
  415. QEMUTimer *ts;
  416. ts = g_malloc0(sizeof(QEMUTimer));
  417. ts->clock = clock;
  418. ts->cb = cb;
  419. ts->opaque = opaque;
  420. ts->scale = scale;
  421. return ts;
  422. }
  423. void qemu_free_timer(QEMUTimer *ts)
  424. {
  425. g_free(ts);
  426. }
  427. /* stop a timer, but do not dealloc it */
  428. void qemu_del_timer(QEMUTimer *ts)
  429. {
  430. QEMUTimer **pt, *t;
  431. /* NOTE: this code must be signal safe because
  432. qemu_timer_expired() can be called from a signal. */
  433. pt = &active_timers[ts->clock->type];
  434. for(;;) {
  435. t = *pt;
  436. if (!t)
  437. break;
  438. if (t == ts) {
  439. *pt = t->next;
  440. break;
  441. }
  442. pt = &t->next;
  443. }
  444. }
  445. /* modify the current timer so that it will be fired when current_time
  446. >= expire_time. The corresponding callback will be called. */
  447. static void qemu_mod_timer_ns(QEMUTimer *ts, int64_t expire_time)
  448. {
  449. QEMUTimer **pt, *t;
  450. qemu_del_timer(ts);
  451. /* add the timer in the sorted list */
  452. /* NOTE: this code must be signal safe because
  453. qemu_timer_expired() can be called from a signal. */
  454. pt = &active_timers[ts->clock->type];
  455. for(;;) {
  456. t = *pt;
  457. if (!qemu_timer_expired_ns(t, expire_time)) {
  458. break;
  459. }
  460. pt = &t->next;
  461. }
  462. ts->expire_time = expire_time;
  463. ts->next = *pt;
  464. *pt = ts;
  465. /* Rearm if necessary */
  466. if (pt == &active_timers[ts->clock->type]) {
  467. if (!alarm_timer->pending) {
  468. qemu_rearm_alarm_timer(alarm_timer);
  469. }
  470. /* Interrupt execution to force deadline recalculation. */
  471. qemu_clock_warp(ts->clock);
  472. if (use_icount) {
  473. qemu_notify_event();
  474. }
  475. }
  476. }
  477. /* modify the current timer so that it will be fired when current_time
  478. >= expire_time. The corresponding callback will be called. */
  479. void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
  480. {
  481. qemu_mod_timer_ns(ts, expire_time * ts->scale);
  482. }
  483. int qemu_timer_pending(QEMUTimer *ts)
  484. {
  485. QEMUTimer *t;
  486. for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
  487. if (t == ts)
  488. return 1;
  489. }
  490. return 0;
  491. }
  492. int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
  493. {
  494. return qemu_timer_expired_ns(timer_head, current_time * timer_head->scale);
  495. }
  496. static void qemu_run_timers(QEMUClock *clock)
  497. {
  498. QEMUTimer **ptimer_head, *ts;
  499. int64_t current_time;
  500. if (!clock->enabled)
  501. return;
  502. current_time = qemu_get_clock_ns(clock);
  503. ptimer_head = &active_timers[clock->type];
  504. for(;;) {
  505. ts = *ptimer_head;
  506. if (!qemu_timer_expired_ns(ts, current_time)) {
  507. break;
  508. }
  509. /* remove timer from the list before calling the callback */
  510. *ptimer_head = ts->next;
  511. ts->next = NULL;
  512. /* run the callback (the timer list can be modified) */
  513. ts->cb(ts->opaque);
  514. }
  515. }
  516. int64_t qemu_get_clock_ns(QEMUClock *clock)
  517. {
  518. int64_t now, last;
  519. switch(clock->type) {
  520. case QEMU_CLOCK_REALTIME:
  521. return get_clock();
  522. default:
  523. case QEMU_CLOCK_VIRTUAL:
  524. if (use_icount) {
  525. return cpu_get_icount();
  526. } else {
  527. return cpu_get_clock();
  528. }
  529. case QEMU_CLOCK_HOST:
  530. now = get_clock_realtime();
  531. last = clock->last;
  532. clock->last = now;
  533. if (now < last) {
  534. notifier_list_notify(&clock->reset_notifiers, &now);
  535. }
  536. return now;
  537. }
  538. }
  539. void qemu_register_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
  540. {
  541. notifier_list_add(&clock->reset_notifiers, notifier);
  542. }
  543. void qemu_unregister_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
  544. {
  545. notifier_list_remove(&clock->reset_notifiers, notifier);
  546. }
  547. void init_clocks(void)
  548. {
  549. rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
  550. vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
  551. host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
  552. rtc_clock = host_clock;
  553. }
  554. /* save a timer */
  555. void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
  556. {
  557. uint64_t expire_time;
  558. if (qemu_timer_pending(ts)) {
  559. expire_time = ts->expire_time;
  560. } else {
  561. expire_time = -1;
  562. }
  563. qemu_put_be64(f, expire_time);
  564. }
  565. void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
  566. {
  567. uint64_t expire_time;
  568. expire_time = qemu_get_be64(f);
  569. if (expire_time != -1) {
  570. qemu_mod_timer_ns(ts, expire_time);
  571. } else {
  572. qemu_del_timer(ts);
  573. }
  574. }
  575. static const VMStateDescription vmstate_timers = {
  576. .name = "timer",
  577. .version_id = 2,
  578. .minimum_version_id = 1,
  579. .minimum_version_id_old = 1,
  580. .fields = (VMStateField []) {
  581. VMSTATE_INT64(cpu_ticks_offset, TimersState),
  582. VMSTATE_INT64(dummy, TimersState),
  583. VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
  584. VMSTATE_END_OF_LIST()
  585. }
  586. };
  587. void configure_icount(const char *option)
  588. {
  589. vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
  590. if (!option)
  591. return;
  592. #ifdef CONFIG_IOTHREAD
  593. vm_clock->warp_timer = qemu_new_timer_ns(rt_clock, icount_warp_rt, NULL);
  594. #endif
  595. if (strcmp(option, "auto") != 0) {
  596. icount_time_shift = strtol(option, NULL, 0);
  597. use_icount = 1;
  598. return;
  599. }
  600. use_icount = 2;
  601. /* 125MIPS seems a reasonable initial guess at the guest speed.
  602. It will be corrected fairly quickly anyway. */
  603. icount_time_shift = 3;
  604. /* Have both realtime and virtual time triggers for speed adjustment.
  605. The realtime trigger catches emulated time passing too slowly,
  606. the virtual time trigger catches emulated time passing too fast.
  607. Realtime triggers occur even when idle, so use them less frequently
  608. than VM triggers. */
  609. icount_rt_timer = qemu_new_timer_ms(rt_clock, icount_adjust_rt, NULL);
  610. qemu_mod_timer(icount_rt_timer,
  611. qemu_get_clock_ms(rt_clock) + 1000);
  612. icount_vm_timer = qemu_new_timer_ns(vm_clock, icount_adjust_vm, NULL);
  613. qemu_mod_timer(icount_vm_timer,
  614. qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
  615. }
  616. void qemu_run_all_timers(void)
  617. {
  618. alarm_timer->pending = 0;
  619. /* rearm timer, if not periodic */
  620. if (alarm_timer->expired) {
  621. alarm_timer->expired = 0;
  622. qemu_rearm_alarm_timer(alarm_timer);
  623. }
  624. /* vm time timers */
  625. if (vm_running) {
  626. qemu_run_timers(vm_clock);
  627. }
  628. qemu_run_timers(rt_clock);
  629. qemu_run_timers(host_clock);
  630. }
  631. static int64_t qemu_next_alarm_deadline(void);
  632. #ifdef _WIN32
  633. static void CALLBACK host_alarm_handler(PVOID lpParam, BOOLEAN unused)
  634. #else
  635. static void host_alarm_handler(int host_signum)
  636. #endif
  637. {
  638. struct qemu_alarm_timer *t = alarm_timer;
  639. if (!t)
  640. return;
  641. #if 0
  642. #define DISP_FREQ 1000
  643. {
  644. static int64_t delta_min = INT64_MAX;
  645. static int64_t delta_max, delta_cum, last_clock, delta, ti;
  646. static int count;
  647. ti = qemu_get_clock_ns(vm_clock);
  648. if (last_clock != 0) {
  649. delta = ti - last_clock;
  650. if (delta < delta_min)
  651. delta_min = delta;
  652. if (delta > delta_max)
  653. delta_max = delta;
  654. delta_cum += delta;
  655. if (++count == DISP_FREQ) {
  656. printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
  657. muldiv64(delta_min, 1000000, get_ticks_per_sec()),
  658. muldiv64(delta_max, 1000000, get_ticks_per_sec()),
  659. muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
  660. (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
  661. count = 0;
  662. delta_min = INT64_MAX;
  663. delta_max = 0;
  664. delta_cum = 0;
  665. }
  666. }
  667. last_clock = ti;
  668. }
  669. #endif
  670. if (alarm_has_dynticks(t) ||
  671. qemu_next_alarm_deadline () <= 0) {
  672. t->expired = alarm_has_dynticks(t);
  673. t->pending = 1;
  674. qemu_notify_event();
  675. }
  676. }
  677. int64_t qemu_next_icount_deadline(void)
  678. {
  679. /* To avoid problems with overflow limit this to 2^32. */
  680. int64_t delta = INT32_MAX;
  681. assert(use_icount);
  682. if (active_timers[QEMU_CLOCK_VIRTUAL]) {
  683. delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
  684. qemu_get_clock_ns(vm_clock);
  685. }
  686. if (delta < 0)
  687. delta = 0;
  688. return delta;
  689. }
  690. static int64_t qemu_next_alarm_deadline(void)
  691. {
  692. int64_t delta;
  693. int64_t rtdelta;
  694. if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
  695. delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
  696. qemu_get_clock_ns(vm_clock);
  697. } else {
  698. delta = INT32_MAX;
  699. }
  700. if (active_timers[QEMU_CLOCK_HOST]) {
  701. int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
  702. qemu_get_clock_ns(host_clock);
  703. if (hdelta < delta)
  704. delta = hdelta;
  705. }
  706. if (active_timers[QEMU_CLOCK_REALTIME]) {
  707. rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
  708. qemu_get_clock_ns(rt_clock));
  709. if (rtdelta < delta)
  710. delta = rtdelta;
  711. }
  712. return delta;
  713. }
  714. #if defined(__linux__)
  715. #include "compatfd.h"
  716. static int dynticks_start_timer(struct qemu_alarm_timer *t)
  717. {
  718. struct sigevent ev;
  719. timer_t host_timer;
  720. struct sigaction act;
  721. sigfillset(&act.sa_mask);
  722. act.sa_flags = 0;
  723. act.sa_handler = host_alarm_handler;
  724. sigaction(SIGALRM, &act, NULL);
  725. /*
  726. * Initialize ev struct to 0 to avoid valgrind complaining
  727. * about uninitialized data in timer_create call
  728. */
  729. memset(&ev, 0, sizeof(ev));
  730. ev.sigev_value.sival_int = 0;
  731. ev.sigev_notify = SIGEV_SIGNAL;
  732. #ifdef SIGEV_THREAD_ID
  733. if (qemu_signalfd_available()) {
  734. ev.sigev_notify = SIGEV_THREAD_ID;
  735. ev._sigev_un._tid = qemu_get_thread_id();
  736. }
  737. #endif /* SIGEV_THREAD_ID */
  738. ev.sigev_signo = SIGALRM;
  739. if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
  740. perror("timer_create");
  741. /* disable dynticks */
  742. fprintf(stderr, "Dynamic Ticks disabled\n");
  743. return -1;
  744. }
  745. t->timer = host_timer;
  746. return 0;
  747. }
  748. static void dynticks_stop_timer(struct qemu_alarm_timer *t)
  749. {
  750. timer_t host_timer = t->timer;
  751. timer_delete(host_timer);
  752. }
  753. static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
  754. {
  755. timer_t host_timer = t->timer;
  756. struct itimerspec timeout;
  757. int64_t nearest_delta_ns = INT64_MAX;
  758. int64_t current_ns;
  759. assert(alarm_has_dynticks(t));
  760. if (!active_timers[QEMU_CLOCK_REALTIME] &&
  761. !active_timers[QEMU_CLOCK_VIRTUAL] &&
  762. !active_timers[QEMU_CLOCK_HOST])
  763. return;
  764. nearest_delta_ns = qemu_next_alarm_deadline();
  765. if (nearest_delta_ns < MIN_TIMER_REARM_NS)
  766. nearest_delta_ns = MIN_TIMER_REARM_NS;
  767. /* check whether a timer is already running */
  768. if (timer_gettime(host_timer, &timeout)) {
  769. perror("gettime");
  770. fprintf(stderr, "Internal timer error: aborting\n");
  771. exit(1);
  772. }
  773. current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
  774. if (current_ns && current_ns <= nearest_delta_ns)
  775. return;
  776. timeout.it_interval.tv_sec = 0;
  777. timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
  778. timeout.it_value.tv_sec = nearest_delta_ns / 1000000000;
  779. timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
  780. if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
  781. perror("settime");
  782. fprintf(stderr, "Internal timer error: aborting\n");
  783. exit(1);
  784. }
  785. }
  786. #endif /* defined(__linux__) */
  787. #if !defined(_WIN32)
  788. static int unix_start_timer(struct qemu_alarm_timer *t)
  789. {
  790. struct sigaction act;
  791. /* timer signal */
  792. sigfillset(&act.sa_mask);
  793. act.sa_flags = 0;
  794. act.sa_handler = host_alarm_handler;
  795. sigaction(SIGALRM, &act, NULL);
  796. return 0;
  797. }
  798. static void unix_rearm_timer(struct qemu_alarm_timer *t)
  799. {
  800. struct itimerval itv;
  801. int64_t nearest_delta_ns = INT64_MAX;
  802. int err;
  803. assert(alarm_has_dynticks(t));
  804. if (!active_timers[QEMU_CLOCK_REALTIME] &&
  805. !active_timers[QEMU_CLOCK_VIRTUAL] &&
  806. !active_timers[QEMU_CLOCK_HOST])
  807. return;
  808. nearest_delta_ns = qemu_next_alarm_deadline();
  809. if (nearest_delta_ns < MIN_TIMER_REARM_NS)
  810. nearest_delta_ns = MIN_TIMER_REARM_NS;
  811. itv.it_interval.tv_sec = 0;
  812. itv.it_interval.tv_usec = 0; /* 0 for one-shot timer */
  813. itv.it_value.tv_sec = nearest_delta_ns / 1000000000;
  814. itv.it_value.tv_usec = (nearest_delta_ns % 1000000000) / 1000;
  815. err = setitimer(ITIMER_REAL, &itv, NULL);
  816. if (err) {
  817. perror("setitimer");
  818. fprintf(stderr, "Internal timer error: aborting\n");
  819. exit(1);
  820. }
  821. }
  822. static void unix_stop_timer(struct qemu_alarm_timer *t)
  823. {
  824. struct itimerval itv;
  825. memset(&itv, 0, sizeof(itv));
  826. setitimer(ITIMER_REAL, &itv, NULL);
  827. }
  828. #endif /* !defined(_WIN32) */
  829. #ifdef _WIN32
  830. static MMRESULT mm_timer;
  831. static unsigned mm_period;
  832. static void CALLBACK mm_alarm_handler(UINT uTimerID, UINT uMsg,
  833. DWORD_PTR dwUser, DWORD_PTR dw1,
  834. DWORD_PTR dw2)
  835. {
  836. struct qemu_alarm_timer *t = alarm_timer;
  837. if (!t) {
  838. return;
  839. }
  840. if (alarm_has_dynticks(t) || qemu_next_alarm_deadline() <= 0) {
  841. t->expired = alarm_has_dynticks(t);
  842. t->pending = 1;
  843. qemu_notify_event();
  844. }
  845. }
  846. static int mm_start_timer(struct qemu_alarm_timer *t)
  847. {
  848. TIMECAPS tc;
  849. UINT flags;
  850. memset(&tc, 0, sizeof(tc));
  851. timeGetDevCaps(&tc, sizeof(tc));
  852. mm_period = tc.wPeriodMin;
  853. timeBeginPeriod(mm_period);
  854. flags = TIME_CALLBACK_FUNCTION;
  855. if (alarm_has_dynticks(t)) {
  856. flags |= TIME_ONESHOT;
  857. } else {
  858. flags |= TIME_PERIODIC;
  859. }
  860. mm_timer = timeSetEvent(1, /* interval (ms) */
  861. mm_period, /* resolution */
  862. mm_alarm_handler, /* function */
  863. (DWORD_PTR)t, /* parameter */
  864. flags);
  865. if (!mm_timer) {
  866. fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
  867. GetLastError());
  868. timeEndPeriod(mm_period);
  869. return -1;
  870. }
  871. return 0;
  872. }
  873. static void mm_stop_timer(struct qemu_alarm_timer *t)
  874. {
  875. timeKillEvent(mm_timer);
  876. timeEndPeriod(mm_period);
  877. }
  878. static void mm_rearm_timer(struct qemu_alarm_timer *t)
  879. {
  880. int nearest_delta_ms;
  881. assert(alarm_has_dynticks(t));
  882. if (!active_timers[QEMU_CLOCK_REALTIME] &&
  883. !active_timers[QEMU_CLOCK_VIRTUAL] &&
  884. !active_timers[QEMU_CLOCK_HOST]) {
  885. return;
  886. }
  887. timeKillEvent(mm_timer);
  888. nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
  889. if (nearest_delta_ms < 1) {
  890. nearest_delta_ms = 1;
  891. }
  892. mm_timer = timeSetEvent(nearest_delta_ms,
  893. mm_period,
  894. mm_alarm_handler,
  895. (DWORD_PTR)t,
  896. TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
  897. if (!mm_timer) {
  898. fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
  899. GetLastError());
  900. timeEndPeriod(mm_period);
  901. exit(1);
  902. }
  903. }
  904. static int win32_start_timer(struct qemu_alarm_timer *t)
  905. {
  906. HANDLE hTimer;
  907. BOOLEAN success;
  908. /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
  909. is zero) that has already expired, the timer is not updated. Since
  910. creating a new timer is relatively expensive, set a bogus one-hour
  911. interval in the dynticks case. */
  912. success = CreateTimerQueueTimer(&hTimer,
  913. NULL,
  914. host_alarm_handler,
  915. t,
  916. 1,
  917. alarm_has_dynticks(t) ? 3600000 : 1,
  918. WT_EXECUTEINTIMERTHREAD);
  919. if (!success) {
  920. fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
  921. GetLastError());
  922. return -1;
  923. }
  924. t->timer = hTimer;
  925. return 0;
  926. }
  927. static void win32_stop_timer(struct qemu_alarm_timer *t)
  928. {
  929. HANDLE hTimer = t->timer;
  930. if (hTimer) {
  931. DeleteTimerQueueTimer(NULL, hTimer, NULL);
  932. }
  933. }
  934. static void win32_rearm_timer(struct qemu_alarm_timer *t)
  935. {
  936. HANDLE hTimer = t->timer;
  937. int nearest_delta_ms;
  938. BOOLEAN success;
  939. assert(alarm_has_dynticks(t));
  940. if (!active_timers[QEMU_CLOCK_REALTIME] &&
  941. !active_timers[QEMU_CLOCK_VIRTUAL] &&
  942. !active_timers[QEMU_CLOCK_HOST])
  943. return;
  944. nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
  945. if (nearest_delta_ms < 1) {
  946. nearest_delta_ms = 1;
  947. }
  948. success = ChangeTimerQueueTimer(NULL,
  949. hTimer,
  950. nearest_delta_ms,
  951. 3600000);
  952. if (!success) {
  953. fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",
  954. GetLastError());
  955. exit(-1);
  956. }
  957. }
  958. #endif /* _WIN32 */
  959. static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
  960. {
  961. if (running)
  962. qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
  963. }
  964. int init_timer_alarm(void)
  965. {
  966. struct qemu_alarm_timer *t = NULL;
  967. int i, err = -1;
  968. for (i = 0; alarm_timers[i].name; i++) {
  969. t = &alarm_timers[i];
  970. err = t->start(t);
  971. if (!err)
  972. break;
  973. }
  974. if (err) {
  975. err = -ENOENT;
  976. goto fail;
  977. }
  978. /* first event is at time 0 */
  979. t->pending = 1;
  980. alarm_timer = t;
  981. qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
  982. return 0;
  983. fail:
  984. return err;
  985. }
  986. void quit_timers(void)
  987. {
  988. struct qemu_alarm_timer *t = alarm_timer;
  989. alarm_timer = NULL;
  990. t->stop(t);
  991. }
  992. int qemu_calculate_timeout(void)
  993. {
  994. #ifndef CONFIG_IOTHREAD
  995. int timeout;
  996. if (!vm_running)
  997. timeout = 5000;
  998. else {
  999. /* XXX: use timeout computed from timers */
  1000. int64_t add;
  1001. int64_t delta;
  1002. /* Advance virtual time to the next event. */
  1003. delta = qemu_icount_delta();
  1004. if (delta > 0) {
  1005. /* If virtual time is ahead of real time then just
  1006. wait for IO. */
  1007. timeout = (delta + 999999) / 1000000;
  1008. } else {
  1009. /* Wait for either IO to occur or the next
  1010. timer event. */
  1011. add = qemu_next_icount_deadline();
  1012. /* We advance the timer before checking for IO.
  1013. Limit the amount we advance so that early IO
  1014. activity won't get the guest too far ahead. */
  1015. if (add > 10000000)
  1016. add = 10000000;
  1017. delta += add;
  1018. qemu_icount += qemu_icount_round (add);
  1019. timeout = delta / 1000000;
  1020. if (timeout < 0)
  1021. timeout = 0;
  1022. }
  1023. }
  1024. return timeout;
  1025. #else /* CONFIG_IOTHREAD */
  1026. return 1000;
  1027. #endif
  1028. }