Statistics
| Branch: | Revision:

root / qemu-timer.c @ c9f7383c

History | View | Annotate | Download (27.8 kB)

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

    
25
#include "sysemu.h"
26
#include "net.h"
27
#include "monitor.h"
28
#include "console.h"
29

    
30
#include "hw/hw.h"
31

    
32
#include <unistd.h>
33
#include <fcntl.h>
34
#include <time.h>
35
#include <errno.h>
36
#include <sys/time.h>
37
#include <signal.h>
38
#ifdef __FreeBSD__
39
#include <sys/param.h>
40
#endif
41

    
42
#ifdef __linux__
43
#include <sys/ioctl.h>
44
#include <linux/rtc.h>
45
/* For the benefit of older linux systems which don't supply it,
46
   we use a local copy of hpet.h. */
47
/* #include <linux/hpet.h> */
48
#include "hpet.h"
49
#endif
50

    
51
#ifdef _WIN32
52
#include <windows.h>
53
#include <mmsystem.h>
54
#endif
55

    
56
#include "qemu-timer.h"
57

    
58
/* Conversion factor from emulated instructions to virtual clock ticks.  */
59
int icount_time_shift;
60
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
61
#define MAX_ICOUNT_SHIFT 10
62
/* Compensate for varying guest execution speed.  */
63
int64_t qemu_icount_bias;
64
static QEMUTimer *icount_rt_timer;
65
static QEMUTimer *icount_vm_timer;
66

    
67
/***********************************************************/
68
/* guest cycle counter */
69

    
70
typedef struct TimersState {
71
    int64_t cpu_ticks_prev;
72
    int64_t cpu_ticks_offset;
73
    int64_t cpu_clock_offset;
74
    int32_t cpu_ticks_enabled;
75
    int64_t dummy;
76
} TimersState;
77

    
78
TimersState timers_state;
79

    
80
/* return the host CPU cycle counter and handle stop/restart */
81
int64_t cpu_get_ticks(void)
82
{
83
    if (use_icount) {
84
        return cpu_get_icount();
85
    }
86
    if (!timers_state.cpu_ticks_enabled) {
87
        return timers_state.cpu_ticks_offset;
88
    } else {
89
        int64_t ticks;
90
        ticks = cpu_get_real_ticks();
91
        if (timers_state.cpu_ticks_prev > ticks) {
92
            /* Note: non increasing ticks may happen if the host uses
93
               software suspend */
94
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
95
        }
96
        timers_state.cpu_ticks_prev = ticks;
97
        return ticks + timers_state.cpu_ticks_offset;
98
    }
99
}
100

    
101
/* return the host CPU monotonic timer and handle stop/restart */
102
static int64_t cpu_get_clock(void)
103
{
104
    int64_t ti;
105
    if (!timers_state.cpu_ticks_enabled) {
106
        return timers_state.cpu_clock_offset;
107
    } else {
108
        ti = get_clock();
109
        return ti + timers_state.cpu_clock_offset;
110
    }
111
}
112

    
113
static int64_t qemu_icount_delta(void)
114
{
115
    if (use_icount == 1) {
116
        /* When not using an adaptive execution frequency
117
           we tend to get badly out of sync with real time,
118
           so just delay for a reasonable amount of time.  */
119
        return 0;
120
    } else {
121
        return cpu_get_icount() - cpu_get_clock();
122
    }
123
}
124

    
125
/* enable cpu_get_ticks() */
126
void cpu_enable_ticks(void)
127
{
128
    if (!timers_state.cpu_ticks_enabled) {
129
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
130
        timers_state.cpu_clock_offset -= get_clock();
131
        timers_state.cpu_ticks_enabled = 1;
132
    }
133
}
134

    
135
/* disable cpu_get_ticks() : the clock is stopped. You must not call
136
   cpu_get_ticks() after that.  */
137
void cpu_disable_ticks(void)
138
{
139
    if (timers_state.cpu_ticks_enabled) {
140
        timers_state.cpu_ticks_offset = cpu_get_ticks();
141
        timers_state.cpu_clock_offset = cpu_get_clock();
142
        timers_state.cpu_ticks_enabled = 0;
143
    }
144
}
145

    
146
/***********************************************************/
147
/* timers */
148

    
149
#define QEMU_CLOCK_REALTIME 0
150
#define QEMU_CLOCK_VIRTUAL  1
151
#define QEMU_CLOCK_HOST     2
152

    
153
struct QEMUClock {
154
    int type;
155
    int enabled;
156
    /* XXX: add frequency */
157
};
158

    
159
struct QEMUTimer {
160
    QEMUClock *clock;
161
    int64_t expire_time;
162
    QEMUTimerCB *cb;
163
    void *opaque;
164
    struct QEMUTimer *next;
165
};
166

    
167
struct qemu_alarm_timer {
168
    char const *name;
169
    int (*start)(struct qemu_alarm_timer *t);
170
    void (*stop)(struct qemu_alarm_timer *t);
171
    void (*rearm)(struct qemu_alarm_timer *t);
172
    void *priv;
173

    
174
    char expired;
175
    char pending;
176
};
177

    
178
static struct qemu_alarm_timer *alarm_timer;
179

    
180
int qemu_alarm_pending(void)
181
{
182
    return alarm_timer->pending;
183
}
184

    
185
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
186
{
187
    return !!t->rearm;
188
}
189

    
190
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
191
{
192
    if (!alarm_has_dynticks(t))
193
        return;
194

    
195
    t->rearm(t);
196
}
197

    
198
/* TODO: MIN_TIMER_REARM_NS should be optimized */
199
#define MIN_TIMER_REARM_NS 250000
200

    
201
#ifdef _WIN32
202

    
203
struct qemu_alarm_win32 {
204
    MMRESULT timerId;
205
    unsigned int period;
206
} alarm_win32_data = {0, 0};
207

    
208
static int win32_start_timer(struct qemu_alarm_timer *t);
209
static void win32_stop_timer(struct qemu_alarm_timer *t);
210
static void win32_rearm_timer(struct qemu_alarm_timer *t);
211

    
212
#else
213

    
214
static int unix_start_timer(struct qemu_alarm_timer *t);
215
static void unix_stop_timer(struct qemu_alarm_timer *t);
216

    
217
#ifdef __linux__
218

    
219
static int dynticks_start_timer(struct qemu_alarm_timer *t);
220
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
221
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
222

    
223
static int hpet_start_timer(struct qemu_alarm_timer *t);
224
static void hpet_stop_timer(struct qemu_alarm_timer *t);
225

    
226
static int rtc_start_timer(struct qemu_alarm_timer *t);
227
static void rtc_stop_timer(struct qemu_alarm_timer *t);
228

    
229
#endif /* __linux__ */
230

    
231
#endif /* _WIN32 */
232

    
233
/* Correlation between real and virtual time is always going to be
234
   fairly approximate, so ignore small variation.
235
   When the guest is idle real and virtual time will be aligned in
236
   the IO wait loop.  */
237
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
238

    
239
static void icount_adjust(void)
240
{
241
    int64_t cur_time;
242
    int64_t cur_icount;
243
    int64_t delta;
244
    static int64_t last_delta;
245
    /* If the VM is not running, then do nothing.  */
246
    if (!vm_running)
247
        return;
248

    
249
    cur_time = cpu_get_clock();
250
    cur_icount = qemu_get_clock(vm_clock);
251
    delta = cur_icount - cur_time;
252
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
253
    if (delta > 0
254
        && last_delta + ICOUNT_WOBBLE < delta * 2
255
        && icount_time_shift > 0) {
256
        /* The guest is getting too far ahead.  Slow time down.  */
257
        icount_time_shift--;
258
    }
259
    if (delta < 0
260
        && last_delta - ICOUNT_WOBBLE > delta * 2
261
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
262
        /* The guest is getting too far behind.  Speed time up.  */
263
        icount_time_shift++;
264
    }
265
    last_delta = delta;
266
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
267
}
268

    
269
static void icount_adjust_rt(void * opaque)
270
{
271
    qemu_mod_timer(icount_rt_timer,
272
                   qemu_get_clock(rt_clock) + 1000);
273
    icount_adjust();
274
}
275

    
276
static void icount_adjust_vm(void * opaque)
277
{
278
    qemu_mod_timer(icount_vm_timer,
279
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
280
    icount_adjust();
281
}
282

    
283
int64_t qemu_icount_round(int64_t count)
284
{
285
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
286
}
287

    
288
static struct qemu_alarm_timer alarm_timers[] = {
289
#ifndef _WIN32
290
#ifdef __linux__
291
    {"dynticks", dynticks_start_timer,
292
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
293
    /* HPET - if available - is preferred */
294
    {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
295
    /* ...otherwise try RTC */
296
    {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
297
#endif
298
    {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
299
#else
300
    {"dynticks", win32_start_timer,
301
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
302
    {"win32", win32_start_timer,
303
     win32_stop_timer, NULL, &alarm_win32_data},
304
#endif
305
    {NULL, }
306
};
307

    
308
static void show_available_alarms(void)
309
{
310
    int i;
311

    
312
    printf("Available alarm timers, in order of precedence:\n");
313
    for (i = 0; alarm_timers[i].name; i++)
314
        printf("%s\n", alarm_timers[i].name);
315
}
316

    
317
void configure_alarms(char const *opt)
318
{
319
    int i;
320
    int cur = 0;
321
    int count = ARRAY_SIZE(alarm_timers) - 1;
322
    char *arg;
323
    char *name;
324
    struct qemu_alarm_timer tmp;
325

    
326
    if (!strcmp(opt, "?")) {
327
        show_available_alarms();
328
        exit(0);
329
    }
330

    
331
    arg = qemu_strdup(opt);
332

    
333
    /* Reorder the array */
334
    name = strtok(arg, ",");
335
    while (name) {
336
        for (i = 0; i < count && alarm_timers[i].name; i++) {
337
            if (!strcmp(alarm_timers[i].name, name))
338
                break;
339
        }
340

    
341
        if (i == count) {
342
            fprintf(stderr, "Unknown clock %s\n", name);
343
            goto next;
344
        }
345

    
346
        if (i < cur)
347
            /* Ignore */
348
            goto next;
349

    
350
        /* Swap */
351
        tmp = alarm_timers[i];
352
        alarm_timers[i] = alarm_timers[cur];
353
        alarm_timers[cur] = tmp;
354

    
355
        cur++;
356
next:
357
        name = strtok(NULL, ",");
358
    }
359

    
360
    qemu_free(arg);
361

    
362
    if (cur) {
363
        /* Disable remaining timers */
364
        for (i = cur; i < count; i++)
365
            alarm_timers[i].name = NULL;
366
    } else {
367
        show_available_alarms();
368
        exit(1);
369
    }
370
}
371

    
372
#define QEMU_NUM_CLOCKS 3
373

    
374
QEMUClock *rt_clock;
375
QEMUClock *vm_clock;
376
QEMUClock *host_clock;
377

    
378
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
379

    
380
static QEMUClock *qemu_new_clock(int type)
381
{
382
    QEMUClock *clock;
383
    clock = qemu_mallocz(sizeof(QEMUClock));
384
    clock->type = type;
385
    clock->enabled = 1;
386
    return clock;
387
}
388

    
389
void qemu_clock_enable(QEMUClock *clock, int enabled)
390
{
391
    clock->enabled = enabled;
392
}
393

    
394
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
395
{
396
    QEMUTimer *ts;
397

    
398
    ts = qemu_mallocz(sizeof(QEMUTimer));
399
    ts->clock = clock;
400
    ts->cb = cb;
401
    ts->opaque = opaque;
402
    return ts;
403
}
404

    
405
void qemu_free_timer(QEMUTimer *ts)
406
{
407
    qemu_free(ts);
408
}
409

    
410
/* stop a timer, but do not dealloc it */
411
void qemu_del_timer(QEMUTimer *ts)
412
{
413
    QEMUTimer **pt, *t;
414

    
415
    /* NOTE: this code must be signal safe because
416
       qemu_timer_expired() can be called from a signal. */
417
    pt = &active_timers[ts->clock->type];
418
    for(;;) {
419
        t = *pt;
420
        if (!t)
421
            break;
422
        if (t == ts) {
423
            *pt = t->next;
424
            break;
425
        }
426
        pt = &t->next;
427
    }
428
}
429

    
430
/* modify the current timer so that it will be fired when current_time
431
   >= expire_time. The corresponding callback will be called. */
432
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
433
{
434
    QEMUTimer **pt, *t;
435

    
436
    qemu_del_timer(ts);
437

    
438
    /* add the timer in the sorted list */
439
    /* NOTE: this code must be signal safe because
440
       qemu_timer_expired() can be called from a signal. */
441
    pt = &active_timers[ts->clock->type];
442
    for(;;) {
443
        t = *pt;
444
        if (!t)
445
            break;
446
        if (t->expire_time > expire_time)
447
            break;
448
        pt = &t->next;
449
    }
450
    ts->expire_time = expire_time;
451
    ts->next = *pt;
452
    *pt = ts;
453

    
454
    /* Rearm if necessary  */
455
    if (pt == &active_timers[ts->clock->type]) {
456
        if (!alarm_timer->pending) {
457
            qemu_rearm_alarm_timer(alarm_timer);
458
        }
459
        /* Interrupt execution to force deadline recalculation.  */
460
        if (use_icount)
461
            qemu_notify_event();
462
    }
463
}
464

    
465
int qemu_timer_pending(QEMUTimer *ts)
466
{
467
    QEMUTimer *t;
468
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
469
        if (t == ts)
470
            return 1;
471
    }
472
    return 0;
473
}
474

    
475
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
476
{
477
    if (!timer_head)
478
        return 0;
479
    return (timer_head->expire_time <= current_time);
480
}
481

    
482
static void qemu_run_timers(QEMUClock *clock)
483
{
484
    QEMUTimer **ptimer_head, *ts;
485
    int64_t current_time;
486
   
487
    if (!clock->enabled)
488
        return;
489

    
490
    current_time = qemu_get_clock (clock);
491
    ptimer_head = &active_timers[clock->type];
492
    for(;;) {
493
        ts = *ptimer_head;
494
        if (!ts || ts->expire_time > current_time)
495
            break;
496
        /* remove timer from the list before calling the callback */
497
        *ptimer_head = ts->next;
498
        ts->next = NULL;
499

    
500
        /* run the callback (the timer list can be modified) */
501
        ts->cb(ts->opaque);
502
    }
503
}
504

    
505
int64_t qemu_get_clock(QEMUClock *clock)
506
{
507
    switch(clock->type) {
508
    case QEMU_CLOCK_REALTIME:
509
        return get_clock() / 1000000;
510
    default:
511
    case QEMU_CLOCK_VIRTUAL:
512
        if (use_icount) {
513
            return cpu_get_icount();
514
        } else {
515
            return cpu_get_clock();
516
        }
517
    case QEMU_CLOCK_HOST:
518
        return get_clock_realtime();
519
    }
520
}
521

    
522
int64_t qemu_get_clock_ns(QEMUClock *clock)
523
{
524
    switch(clock->type) {
525
    case QEMU_CLOCK_REALTIME:
526
        return get_clock();
527
    default:
528
    case QEMU_CLOCK_VIRTUAL:
529
        if (use_icount) {
530
            return cpu_get_icount();
531
        } else {
532
            return cpu_get_clock();
533
        }
534
    case QEMU_CLOCK_HOST:
535
        return get_clock_realtime();
536
    }
537
}
538

    
539
void init_clocks(void)
540
{
541
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
542
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
543
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
544

    
545
    rtc_clock = host_clock;
546
}
547

    
548
/* save a timer */
549
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
550
{
551
    uint64_t expire_time;
552

    
553
    if (qemu_timer_pending(ts)) {
554
        expire_time = ts->expire_time;
555
    } else {
556
        expire_time = -1;
557
    }
558
    qemu_put_be64(f, expire_time);
559
}
560

    
561
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
562
{
563
    uint64_t expire_time;
564

    
565
    expire_time = qemu_get_be64(f);
566
    if (expire_time != -1) {
567
        qemu_mod_timer(ts, expire_time);
568
    } else {
569
        qemu_del_timer(ts);
570
    }
571
}
572

    
573
static const VMStateDescription vmstate_timers = {
574
    .name = "timer",
575
    .version_id = 2,
576
    .minimum_version_id = 1,
577
    .minimum_version_id_old = 1,
578
    .fields      = (VMStateField []) {
579
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
580
        VMSTATE_INT64(dummy, TimersState),
581
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
582
        VMSTATE_END_OF_LIST()
583
    }
584
};
585

    
586
void configure_icount(const char *option)
587
{
588
    vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
589
    if (!option)
590
        return;
591

    
592
    if (strcmp(option, "auto") != 0) {
593
        icount_time_shift = strtol(option, NULL, 0);
594
        use_icount = 1;
595
        return;
596
    }
597

    
598
    use_icount = 2;
599

    
600
    /* 125MIPS seems a reasonable initial guess at the guest speed.
601
       It will be corrected fairly quickly anyway.  */
602
    icount_time_shift = 3;
603

    
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(rt_clock, icount_adjust_rt, NULL);
610
    qemu_mod_timer(icount_rt_timer,
611
                   qemu_get_clock(rt_clock) + 1000);
612
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
613
    qemu_mod_timer(icount_vm_timer,
614
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
615
}
616

    
617
void qemu_run_all_timers(void)
618
{
619
    alarm_timer->pending = 0;
620

    
621
    /* rearm timer, if not periodic */
622
    if (alarm_timer->expired) {
623
        alarm_timer->expired = 0;
624
        qemu_rearm_alarm_timer(alarm_timer);
625
    }
626

    
627
    /* vm time timers */
628
    if (vm_running) {
629
        qemu_run_timers(vm_clock);
630
    }
631

    
632
    qemu_run_timers(rt_clock);
633
    qemu_run_timers(host_clock);
634
}
635

    
636
static int64_t qemu_next_alarm_deadline(void);
637

    
638
#ifdef _WIN32
639
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
640
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
641
                                        DWORD_PTR dw2)
642
#else
643
static void host_alarm_handler(int host_signum)
644
#endif
645
{
646
    struct qemu_alarm_timer *t = alarm_timer;
647
    if (!t)
648
        return;
649

    
650
#if 0
651
#define DISP_FREQ 1000
652
    {
653
        static int64_t delta_min = INT64_MAX;
654
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
655
        static int count;
656
        ti = qemu_get_clock(vm_clock);
657
        if (last_clock != 0) {
658
            delta = ti - last_clock;
659
            if (delta < delta_min)
660
                delta_min = delta;
661
            if (delta > delta_max)
662
                delta_max = delta;
663
            delta_cum += delta;
664
            if (++count == DISP_FREQ) {
665
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
666
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
667
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
668
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
669
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
670
                count = 0;
671
                delta_min = INT64_MAX;
672
                delta_max = 0;
673
                delta_cum = 0;
674
            }
675
        }
676
        last_clock = ti;
677
    }
678
#endif
679
    if (alarm_has_dynticks(t) ||
680
        qemu_next_alarm_deadline () <= 0) {
681
        t->expired = alarm_has_dynticks(t);
682
        t->pending = 1;
683
        qemu_notify_event();
684
    }
685
}
686

    
687
int64_t qemu_next_deadline(void)
688
{
689
    /* To avoid problems with overflow limit this to 2^32.  */
690
    int64_t delta = INT32_MAX;
691

    
692
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
693
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
694
                     qemu_get_clock_ns(vm_clock);
695
    }
696
    if (active_timers[QEMU_CLOCK_HOST]) {
697
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
698
                 qemu_get_clock_ns(host_clock);
699
        if (hdelta < delta)
700
            delta = hdelta;
701
    }
702

    
703
    if (delta < 0)
704
        delta = 0;
705

    
706
    return delta;
707
}
708

    
709
static int64_t qemu_next_alarm_deadline(void)
710
{
711
    int64_t delta;
712
    int64_t rtdelta;
713

    
714
    if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
715
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
716
                     qemu_get_clock(vm_clock);
717
    } else {
718
        delta = INT32_MAX;
719
    }
720
    if (active_timers[QEMU_CLOCK_HOST]) {
721
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
722
                 qemu_get_clock_ns(host_clock);
723
        if (hdelta < delta)
724
            delta = hdelta;
725
    }
726
    if (active_timers[QEMU_CLOCK_REALTIME]) {
727
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time * 1000000 -
728
                 qemu_get_clock_ns(rt_clock));
729
        if (rtdelta < delta)
730
            delta = rtdelta;
731
    }
732

    
733
    return delta;
734
}
735

    
736
#if defined(__linux__)
737

    
738
#define RTC_FREQ 1024
739

    
740
static void enable_sigio_timer(int fd)
741
{
742
    struct sigaction act;
743

    
744
    /* timer signal */
745
    sigfillset(&act.sa_mask);
746
    act.sa_flags = 0;
747
    act.sa_handler = host_alarm_handler;
748

    
749
    sigaction(SIGIO, &act, NULL);
750
    fcntl_setfl(fd, O_ASYNC);
751
    fcntl(fd, F_SETOWN, getpid());
752
}
753

    
754
static int hpet_start_timer(struct qemu_alarm_timer *t)
755
{
756
    struct hpet_info info;
757
    int r, fd;
758

    
759
    fd = qemu_open("/dev/hpet", O_RDONLY);
760
    if (fd < 0)
761
        return -1;
762

    
763
    /* Set frequency */
764
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
765
    if (r < 0) {
766
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
767
                "error, but for better emulation accuracy type:\n"
768
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
769
        goto fail;
770
    }
771

    
772
    /* Check capabilities */
773
    r = ioctl(fd, HPET_INFO, &info);
774
    if (r < 0)
775
        goto fail;
776

    
777
    /* Enable periodic mode */
778
    r = ioctl(fd, HPET_EPI, 0);
779
    if (info.hi_flags && (r < 0))
780
        goto fail;
781

    
782
    /* Enable interrupt */
783
    r = ioctl(fd, HPET_IE_ON, 0);
784
    if (r < 0)
785
        goto fail;
786

    
787
    enable_sigio_timer(fd);
788
    t->priv = (void *)(long)fd;
789

    
790
    return 0;
791
fail:
792
    close(fd);
793
    return -1;
794
}
795

    
796
static void hpet_stop_timer(struct qemu_alarm_timer *t)
797
{
798
    int fd = (long)t->priv;
799

    
800
    close(fd);
801
}
802

    
803
static int rtc_start_timer(struct qemu_alarm_timer *t)
804
{
805
    int rtc_fd;
806
    unsigned long current_rtc_freq = 0;
807

    
808
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
809
    if (rtc_fd < 0)
810
        return -1;
811
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
812
    if (current_rtc_freq != RTC_FREQ &&
813
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
814
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
815
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
816
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
817
        goto fail;
818
    }
819
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
820
    fail:
821
        close(rtc_fd);
822
        return -1;
823
    }
824

    
825
    enable_sigio_timer(rtc_fd);
826

    
827
    t->priv = (void *)(long)rtc_fd;
828

    
829
    return 0;
830
}
831

    
832
static void rtc_stop_timer(struct qemu_alarm_timer *t)
833
{
834
    int rtc_fd = (long)t->priv;
835

    
836
    close(rtc_fd);
837
}
838

    
839
static int dynticks_start_timer(struct qemu_alarm_timer *t)
840
{
841
    struct sigevent ev;
842
    timer_t host_timer;
843
    struct sigaction act;
844

    
845
    sigfillset(&act.sa_mask);
846
    act.sa_flags = 0;
847
    act.sa_handler = host_alarm_handler;
848

    
849
    sigaction(SIGALRM, &act, NULL);
850

    
851
    /* 
852
     * Initialize ev struct to 0 to avoid valgrind complaining
853
     * about uninitialized data in timer_create call
854
     */
855
    memset(&ev, 0, sizeof(ev));
856
    ev.sigev_value.sival_int = 0;
857
    ev.sigev_notify = SIGEV_SIGNAL;
858
    ev.sigev_signo = SIGALRM;
859

    
860
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
861
        perror("timer_create");
862

    
863
        /* disable dynticks */
864
        fprintf(stderr, "Dynamic Ticks disabled\n");
865

    
866
        return -1;
867
    }
868

    
869
    t->priv = (void *)(long)host_timer;
870

    
871
    return 0;
872
}
873

    
874
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
875
{
876
    timer_t host_timer = (timer_t)(long)t->priv;
877

    
878
    timer_delete(host_timer);
879
}
880

    
881
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
882
{
883
    timer_t host_timer = (timer_t)(long)t->priv;
884
    struct itimerspec timeout;
885
    int64_t nearest_delta_ns = INT64_MAX;
886
    int64_t current_ns;
887

    
888
    assert(alarm_has_dynticks(t));
889
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
890
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
891
        !active_timers[QEMU_CLOCK_HOST])
892
        return;
893

    
894
    nearest_delta_ns = qemu_next_alarm_deadline();
895
    if (nearest_delta_ns < MIN_TIMER_REARM_NS)
896
        nearest_delta_ns = MIN_TIMER_REARM_NS;
897

    
898
    /* check whether a timer is already running */
899
    if (timer_gettime(host_timer, &timeout)) {
900
        perror("gettime");
901
        fprintf(stderr, "Internal timer error: aborting\n");
902
        exit(1);
903
    }
904
    current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
905
    if (current_ns && current_ns <= nearest_delta_ns)
906
        return;
907

    
908
    timeout.it_interval.tv_sec = 0;
909
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
910
    timeout.it_value.tv_sec =  nearest_delta_ns / 1000000000;
911
    timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
912
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
913
        perror("settime");
914
        fprintf(stderr, "Internal timer error: aborting\n");
915
        exit(1);
916
    }
917
}
918

    
919
#endif /* defined(__linux__) */
920

    
921
#if !defined(_WIN32)
922

    
923
static int unix_start_timer(struct qemu_alarm_timer *t)
924
{
925
    struct sigaction act;
926
    struct itimerval itv;
927
    int err;
928

    
929
    /* timer signal */
930
    sigfillset(&act.sa_mask);
931
    act.sa_flags = 0;
932
    act.sa_handler = host_alarm_handler;
933

    
934
    sigaction(SIGALRM, &act, NULL);
935

    
936
    itv.it_interval.tv_sec = 0;
937
    /* for i386 kernel 2.6 to get 1 ms */
938
    itv.it_interval.tv_usec = 999;
939
    itv.it_value.tv_sec = 0;
940
    itv.it_value.tv_usec = 10 * 1000;
941

    
942
    err = setitimer(ITIMER_REAL, &itv, NULL);
943
    if (err)
944
        return -1;
945

    
946
    return 0;
947
}
948

    
949
static void unix_stop_timer(struct qemu_alarm_timer *t)
950
{
951
    struct itimerval itv;
952

    
953
    memset(&itv, 0, sizeof(itv));
954
    setitimer(ITIMER_REAL, &itv, NULL);
955
}
956

    
957
#endif /* !defined(_WIN32) */
958

    
959

    
960
#ifdef _WIN32
961

    
962
static int win32_start_timer(struct qemu_alarm_timer *t)
963
{
964
    TIMECAPS tc;
965
    struct qemu_alarm_win32 *data = t->priv;
966
    UINT flags;
967

    
968
    memset(&tc, 0, sizeof(tc));
969
    timeGetDevCaps(&tc, sizeof(tc));
970

    
971
    data->period = tc.wPeriodMin;
972
    timeBeginPeriod(data->period);
973

    
974
    flags = TIME_CALLBACK_FUNCTION;
975
    if (alarm_has_dynticks(t))
976
        flags |= TIME_ONESHOT;
977
    else
978
        flags |= TIME_PERIODIC;
979

    
980
    data->timerId = timeSetEvent(1,         // interval (ms)
981
                        data->period,       // resolution
982
                        host_alarm_handler, // function
983
                        (DWORD)t,           // parameter
984
                        flags);
985

    
986
    if (!data->timerId) {
987
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
988
                GetLastError());
989
        timeEndPeriod(data->period);
990
        return -1;
991
    }
992

    
993
    return 0;
994
}
995

    
996
static void win32_stop_timer(struct qemu_alarm_timer *t)
997
{
998
    struct qemu_alarm_win32 *data = t->priv;
999

    
1000
    timeKillEvent(data->timerId);
1001
    timeEndPeriod(data->period);
1002
}
1003

    
1004
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1005
{
1006
    struct qemu_alarm_win32 *data = t->priv;
1007

    
1008
    assert(alarm_has_dynticks(t));
1009
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1010
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1011
        !active_timers[QEMU_CLOCK_HOST])
1012
        return;
1013

    
1014
    timeKillEvent(data->timerId);
1015

    
1016
    data->timerId = timeSetEvent(1,
1017
                        data->period,
1018
                        host_alarm_handler,
1019
                        (DWORD)t,
1020
                        TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1021

    
1022
    if (!data->timerId) {
1023
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1024
                GetLastError());
1025

    
1026
        timeEndPeriod(data->period);
1027
        exit(1);
1028
    }
1029
}
1030

    
1031
#endif /* _WIN32 */
1032

    
1033
static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1034
{
1035
    if (running)
1036
        qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1037
}
1038

    
1039
int init_timer_alarm(void)
1040
{
1041
    struct qemu_alarm_timer *t = NULL;
1042
    int i, err = -1;
1043

    
1044
    for (i = 0; alarm_timers[i].name; i++) {
1045
        t = &alarm_timers[i];
1046

    
1047
        err = t->start(t);
1048
        if (!err)
1049
            break;
1050
    }
1051

    
1052
    if (err) {
1053
        err = -ENOENT;
1054
        goto fail;
1055
    }
1056

    
1057
    /* first event is at time 0 */
1058
    t->pending = 1;
1059
    alarm_timer = t;
1060
    qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1061

    
1062
    return 0;
1063

    
1064
fail:
1065
    return err;
1066
}
1067

    
1068
void quit_timers(void)
1069
{
1070
    struct qemu_alarm_timer *t = alarm_timer;
1071
    alarm_timer = NULL;
1072
    t->stop(t);
1073
}
1074

    
1075
int qemu_calculate_timeout(void)
1076
{
1077
    int timeout;
1078
    int64_t add;
1079
    int64_t delta;
1080

    
1081
    /* When using icount, making forward progress with qemu_icount when the
1082
       guest CPU is idle is critical. We only use the static io-thread timeout
1083
       for non icount runs.  */
1084
    if (!use_icount || !vm_running) {
1085
        return 5000;
1086
    }
1087

    
1088
    /* Advance virtual time to the next event.  */
1089
    delta = qemu_icount_delta();
1090
    if (delta > 0) {
1091
        /* If virtual time is ahead of real time then just
1092
           wait for IO.  */
1093
        timeout = (delta + 999999) / 1000000;
1094
    } else {
1095
        /* Wait for either IO to occur or the next
1096
           timer event.  */
1097
        add = qemu_next_deadline();
1098
        /* We advance the timer before checking for IO.
1099
           Limit the amount we advance so that early IO
1100
           activity won't get the guest too far ahead.  */
1101
        if (add > 10000000)
1102
            add = 10000000;
1103
        delta += add;
1104
        qemu_icount += qemu_icount_round (add);
1105
        timeout = delta / 1000000;
1106
        if (timeout < 0)
1107
            timeout = 0;
1108
    }
1109

    
1110
    return timeout;
1111
}
1112