Statistics
| Branch: | Revision:

root / qemu-timer.c @ 29e922b6

History | View | Annotate | Download (29.4 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
/***********************************************************/
69
/* real time host monotonic timer */
70

    
71

    
72
static int64_t get_clock_realtime(void)
73
{
74
    struct timeval tv;
75

    
76
    gettimeofday(&tv, NULL);
77
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
78
}
79

    
80
#ifdef WIN32
81

    
82
static int64_t clock_freq;
83

    
84
static void init_get_clock(void)
85
{
86
    LARGE_INTEGER freq;
87
    int ret;
88
    ret = QueryPerformanceFrequency(&freq);
89
    if (ret == 0) {
90
        fprintf(stderr, "Could not calibrate ticks\n");
91
        exit(1);
92
    }
93
    clock_freq = freq.QuadPart;
94
}
95

    
96
static int64_t get_clock(void)
97
{
98
    LARGE_INTEGER ti;
99
    QueryPerformanceCounter(&ti);
100
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
101
}
102

    
103
#else
104

    
105
static int use_rt_clock;
106

    
107
static void init_get_clock(void)
108
{
109
    use_rt_clock = 0;
110
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
111
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
112
    {
113
        struct timespec ts;
114
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
115
            use_rt_clock = 1;
116
        }
117
    }
118
#endif
119
}
120

    
121
static int64_t get_clock(void)
122
{
123
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
124
        || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
125
    if (use_rt_clock) {
126
        struct timespec ts;
127
        clock_gettime(CLOCK_MONOTONIC, &ts);
128
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
129
    } else
130
#endif
131
    {
132
        /* XXX: using gettimeofday leads to problems if the date
133
           changes, so it should be avoided. */
134
        return get_clock_realtime();
135
    }
136
}
137
#endif
138

    
139
/***********************************************************/
140
/* guest cycle counter */
141

    
142
typedef struct TimersState {
143
    int64_t cpu_ticks_prev;
144
    int64_t cpu_ticks_offset;
145
    int64_t cpu_clock_offset;
146
    int32_t cpu_ticks_enabled;
147
    int64_t dummy;
148
} TimersState;
149

    
150
TimersState timers_state;
151

    
152
/* return the host CPU cycle counter and handle stop/restart */
153
int64_t cpu_get_ticks(void)
154
{
155
    if (use_icount) {
156
        return cpu_get_icount();
157
    }
158
    if (!timers_state.cpu_ticks_enabled) {
159
        return timers_state.cpu_ticks_offset;
160
    } else {
161
        int64_t ticks;
162
        ticks = cpu_get_real_ticks();
163
        if (timers_state.cpu_ticks_prev > ticks) {
164
            /* Note: non increasing ticks may happen if the host uses
165
               software suspend */
166
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
167
        }
168
        timers_state.cpu_ticks_prev = ticks;
169
        return ticks + timers_state.cpu_ticks_offset;
170
    }
171
}
172

    
173
/* return the host CPU monotonic timer and handle stop/restart */
174
static int64_t cpu_get_clock(void)
175
{
176
    int64_t ti;
177
    if (!timers_state.cpu_ticks_enabled) {
178
        return timers_state.cpu_clock_offset;
179
    } else {
180
        ti = get_clock();
181
        return ti + timers_state.cpu_clock_offset;
182
    }
183
}
184

    
185
#ifndef CONFIG_IOTHREAD
186
static int64_t qemu_icount_delta(void)
187
{
188
    if (!use_icount) {
189
        return 5000 * (int64_t) 1000000;
190
    } else if (use_icount == 1) {
191
        /* When not using an adaptive execution frequency
192
           we tend to get badly out of sync with real time,
193
           so just delay for a reasonable amount of time.  */
194
        return 0;
195
    } else {
196
        return cpu_get_icount() - cpu_get_clock();
197
    }
198
}
199
#endif
200

    
201
/* enable cpu_get_ticks() */
202
void cpu_enable_ticks(void)
203
{
204
    if (!timers_state.cpu_ticks_enabled) {
205
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
206
        timers_state.cpu_clock_offset -= get_clock();
207
        timers_state.cpu_ticks_enabled = 1;
208
    }
209
}
210

    
211
/* disable cpu_get_ticks() : the clock is stopped. You must not call
212
   cpu_get_ticks() after that.  */
213
void cpu_disable_ticks(void)
214
{
215
    if (timers_state.cpu_ticks_enabled) {
216
        timers_state.cpu_ticks_offset = cpu_get_ticks();
217
        timers_state.cpu_clock_offset = cpu_get_clock();
218
        timers_state.cpu_ticks_enabled = 0;
219
    }
220
}
221

    
222
/***********************************************************/
223
/* timers */
224

    
225
#define QEMU_CLOCK_REALTIME 0
226
#define QEMU_CLOCK_VIRTUAL  1
227
#define QEMU_CLOCK_HOST     2
228

    
229
struct QEMUClock {
230
    int type;
231
    int enabled;
232
    /* XXX: add frequency */
233
};
234

    
235
struct QEMUTimer {
236
    QEMUClock *clock;
237
    int64_t expire_time;
238
    QEMUTimerCB *cb;
239
    void *opaque;
240
    struct QEMUTimer *next;
241
};
242

    
243
struct qemu_alarm_timer {
244
    char const *name;
245
    int (*start)(struct qemu_alarm_timer *t);
246
    void (*stop)(struct qemu_alarm_timer *t);
247
    void (*rearm)(struct qemu_alarm_timer *t);
248
    void *priv;
249

    
250
    char expired;
251
    char pending;
252
};
253

    
254
static struct qemu_alarm_timer *alarm_timer;
255

    
256
int qemu_alarm_pending(void)
257
{
258
    return alarm_timer->pending;
259
}
260

    
261
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
262
{
263
    return !!t->rearm;
264
}
265

    
266
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
267
{
268
    if (!alarm_has_dynticks(t))
269
        return;
270

    
271
    t->rearm(t);
272
}
273

    
274
/* TODO: MIN_TIMER_REARM_US should be optimized */
275
#define MIN_TIMER_REARM_US 250
276

    
277
#ifdef _WIN32
278

    
279
struct qemu_alarm_win32 {
280
    MMRESULT timerId;
281
    unsigned int period;
282
} alarm_win32_data = {0, 0};
283

    
284
static int win32_start_timer(struct qemu_alarm_timer *t);
285
static void win32_stop_timer(struct qemu_alarm_timer *t);
286
static void win32_rearm_timer(struct qemu_alarm_timer *t);
287

    
288
#else
289

    
290
static int unix_start_timer(struct qemu_alarm_timer *t);
291
static void unix_stop_timer(struct qemu_alarm_timer *t);
292

    
293
#ifdef __linux__
294

    
295
static int dynticks_start_timer(struct qemu_alarm_timer *t);
296
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
297
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
298

    
299
static int hpet_start_timer(struct qemu_alarm_timer *t);
300
static void hpet_stop_timer(struct qemu_alarm_timer *t);
301

    
302
static int rtc_start_timer(struct qemu_alarm_timer *t);
303
static void rtc_stop_timer(struct qemu_alarm_timer *t);
304

    
305
#endif /* __linux__ */
306

    
307
#endif /* _WIN32 */
308

    
309
/* Correlation between real and virtual time is always going to be
310
   fairly approximate, so ignore small variation.
311
   When the guest is idle real and virtual time will be aligned in
312
   the IO wait loop.  */
313
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
314

    
315
static void icount_adjust(void)
316
{
317
    int64_t cur_time;
318
    int64_t cur_icount;
319
    int64_t delta;
320
    static int64_t last_delta;
321
    /* If the VM is not running, then do nothing.  */
322
    if (!vm_running)
323
        return;
324

    
325
    cur_time = cpu_get_clock();
326
    cur_icount = qemu_get_clock(vm_clock);
327
    delta = cur_icount - cur_time;
328
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
329
    if (delta > 0
330
        && last_delta + ICOUNT_WOBBLE < delta * 2
331
        && icount_time_shift > 0) {
332
        /* The guest is getting too far ahead.  Slow time down.  */
333
        icount_time_shift--;
334
    }
335
    if (delta < 0
336
        && last_delta - ICOUNT_WOBBLE > delta * 2
337
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
338
        /* The guest is getting too far behind.  Speed time up.  */
339
        icount_time_shift++;
340
    }
341
    last_delta = delta;
342
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
343
}
344

    
345
static void icount_adjust_rt(void * opaque)
346
{
347
    qemu_mod_timer(icount_rt_timer,
348
                   qemu_get_clock(rt_clock) + 1000);
349
    icount_adjust();
350
}
351

    
352
static void icount_adjust_vm(void * opaque)
353
{
354
    qemu_mod_timer(icount_vm_timer,
355
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
356
    icount_adjust();
357
}
358

    
359
int64_t qemu_icount_round(int64_t count)
360
{
361
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
362
}
363

    
364
static struct qemu_alarm_timer alarm_timers[] = {
365
#ifndef _WIN32
366
#ifdef __linux__
367
    {"dynticks", dynticks_start_timer,
368
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
369
    /* HPET - if available - is preferred */
370
    {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
371
    /* ...otherwise try RTC */
372
    {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
373
#endif
374
    {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
375
#else
376
    {"dynticks", win32_start_timer,
377
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
378
    {"win32", win32_start_timer,
379
     win32_stop_timer, NULL, &alarm_win32_data},
380
#endif
381
    {NULL, }
382
};
383

    
384
static void show_available_alarms(void)
385
{
386
    int i;
387

    
388
    printf("Available alarm timers, in order of precedence:\n");
389
    for (i = 0; alarm_timers[i].name; i++)
390
        printf("%s\n", alarm_timers[i].name);
391
}
392

    
393
void configure_alarms(char const *opt)
394
{
395
    int i;
396
    int cur = 0;
397
    int count = ARRAY_SIZE(alarm_timers) - 1;
398
    char *arg;
399
    char *name;
400
    struct qemu_alarm_timer tmp;
401

    
402
    if (!strcmp(opt, "?")) {
403
        show_available_alarms();
404
        exit(0);
405
    }
406

    
407
    arg = qemu_strdup(opt);
408

    
409
    /* Reorder the array */
410
    name = strtok(arg, ",");
411
    while (name) {
412
        for (i = 0; i < count && alarm_timers[i].name; i++) {
413
            if (!strcmp(alarm_timers[i].name, name))
414
                break;
415
        }
416

    
417
        if (i == count) {
418
            fprintf(stderr, "Unknown clock %s\n", name);
419
            goto next;
420
        }
421

    
422
        if (i < cur)
423
            /* Ignore */
424
            goto next;
425

    
426
        /* Swap */
427
        tmp = alarm_timers[i];
428
        alarm_timers[i] = alarm_timers[cur];
429
        alarm_timers[cur] = tmp;
430

    
431
        cur++;
432
next:
433
        name = strtok(NULL, ",");
434
    }
435

    
436
    qemu_free(arg);
437

    
438
    if (cur) {
439
        /* Disable remaining timers */
440
        for (i = cur; i < count; i++)
441
            alarm_timers[i].name = NULL;
442
    } else {
443
        show_available_alarms();
444
        exit(1);
445
    }
446
}
447

    
448
#define QEMU_NUM_CLOCKS 3
449

    
450
QEMUClock *rt_clock;
451
QEMUClock *vm_clock;
452
QEMUClock *host_clock;
453

    
454
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
455

    
456
static QEMUClock *qemu_new_clock(int type)
457
{
458
    QEMUClock *clock;
459
    clock = qemu_mallocz(sizeof(QEMUClock));
460
    clock->type = type;
461
    clock->enabled = 1;
462
    return clock;
463
}
464

    
465
void qemu_clock_enable(QEMUClock *clock, int enabled)
466
{
467
    clock->enabled = enabled;
468
}
469

    
470
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
471
{
472
    QEMUTimer *ts;
473

    
474
    ts = qemu_mallocz(sizeof(QEMUTimer));
475
    ts->clock = clock;
476
    ts->cb = cb;
477
    ts->opaque = opaque;
478
    return ts;
479
}
480

    
481
void qemu_free_timer(QEMUTimer *ts)
482
{
483
    qemu_free(ts);
484
}
485

    
486
/* stop a timer, but do not dealloc it */
487
void qemu_del_timer(QEMUTimer *ts)
488
{
489
    QEMUTimer **pt, *t;
490

    
491
    /* NOTE: this code must be signal safe because
492
       qemu_timer_expired() can be called from a signal. */
493
    pt = &active_timers[ts->clock->type];
494
    for(;;) {
495
        t = *pt;
496
        if (!t)
497
            break;
498
        if (t == ts) {
499
            *pt = t->next;
500
            break;
501
        }
502
        pt = &t->next;
503
    }
504
}
505

    
506
/* modify the current timer so that it will be fired when current_time
507
   >= expire_time. The corresponding callback will be called. */
508
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
509
{
510
    QEMUTimer **pt, *t;
511

    
512
    qemu_del_timer(ts);
513

    
514
    /* add the timer in the sorted list */
515
    /* NOTE: this code must be signal safe because
516
       qemu_timer_expired() can be called from a signal. */
517
    pt = &active_timers[ts->clock->type];
518
    for(;;) {
519
        t = *pt;
520
        if (!t)
521
            break;
522
        if (t->expire_time > expire_time)
523
            break;
524
        pt = &t->next;
525
    }
526
    ts->expire_time = expire_time;
527
    ts->next = *pt;
528
    *pt = ts;
529

    
530
    /* Rearm if necessary  */
531
    if (pt == &active_timers[ts->clock->type]) {
532
        if (!alarm_timer->pending) {
533
            qemu_rearm_alarm_timer(alarm_timer);
534
        }
535
        /* Interrupt execution to force deadline recalculation.  */
536
        if (use_icount)
537
            qemu_notify_event();
538
    }
539
}
540

    
541
int qemu_timer_pending(QEMUTimer *ts)
542
{
543
    QEMUTimer *t;
544
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
545
        if (t == ts)
546
            return 1;
547
    }
548
    return 0;
549
}
550

    
551
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
552
{
553
    if (!timer_head)
554
        return 0;
555
    return (timer_head->expire_time <= current_time);
556
}
557

    
558
static void qemu_run_timers(QEMUClock *clock)
559
{
560
    QEMUTimer **ptimer_head, *ts;
561
    int64_t current_time;
562
   
563
    if (!clock->enabled)
564
        return;
565

    
566
    current_time = qemu_get_clock (clock);
567
    ptimer_head = &active_timers[clock->type];
568
    for(;;) {
569
        ts = *ptimer_head;
570
        if (!ts || ts->expire_time > current_time)
571
            break;
572
        /* remove timer from the list before calling the callback */
573
        *ptimer_head = ts->next;
574
        ts->next = NULL;
575

    
576
        /* run the callback (the timer list can be modified) */
577
        ts->cb(ts->opaque);
578
    }
579
}
580

    
581
int64_t qemu_get_clock(QEMUClock *clock)
582
{
583
    switch(clock->type) {
584
    case QEMU_CLOCK_REALTIME:
585
        return get_clock() / 1000000;
586
    default:
587
    case QEMU_CLOCK_VIRTUAL:
588
        if (use_icount) {
589
            return cpu_get_icount();
590
        } else {
591
            return cpu_get_clock();
592
        }
593
    case QEMU_CLOCK_HOST:
594
        return get_clock_realtime();
595
    }
596
}
597

    
598
int64_t qemu_get_clock_ns(QEMUClock *clock)
599
{
600
    switch(clock->type) {
601
    case QEMU_CLOCK_REALTIME:
602
        return get_clock();
603
    default:
604
    case QEMU_CLOCK_VIRTUAL:
605
        if (use_icount) {
606
            return cpu_get_icount();
607
        } else {
608
            return cpu_get_clock();
609
        }
610
    case QEMU_CLOCK_HOST:
611
        return get_clock_realtime();
612
    }
613
}
614

    
615
void init_clocks(void)
616
{
617
    init_get_clock();
618
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
619
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
620
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
621

    
622
    rtc_clock = host_clock;
623
}
624

    
625
/* save a timer */
626
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
627
{
628
    uint64_t expire_time;
629

    
630
    if (qemu_timer_pending(ts)) {
631
        expire_time = ts->expire_time;
632
    } else {
633
        expire_time = -1;
634
    }
635
    qemu_put_be64(f, expire_time);
636
}
637

    
638
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
639
{
640
    uint64_t expire_time;
641

    
642
    expire_time = qemu_get_be64(f);
643
    if (expire_time != -1) {
644
        qemu_mod_timer(ts, expire_time);
645
    } else {
646
        qemu_del_timer(ts);
647
    }
648
}
649

    
650
static const VMStateDescription vmstate_timers = {
651
    .name = "timer",
652
    .version_id = 2,
653
    .minimum_version_id = 1,
654
    .minimum_version_id_old = 1,
655
    .fields      = (VMStateField []) {
656
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
657
        VMSTATE_INT64(dummy, TimersState),
658
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
659
        VMSTATE_END_OF_LIST()
660
    }
661
};
662

    
663
void configure_icount(const char *option)
664
{
665
    vmstate_register(0, &vmstate_timers, &timers_state);
666
    if (!option)
667
        return;
668

    
669
    if (strcmp(option, "auto") != 0) {
670
        icount_time_shift = strtol(option, NULL, 0);
671
        use_icount = 1;
672
        return;
673
    }
674

    
675
    use_icount = 2;
676

    
677
    /* 125MIPS seems a reasonable initial guess at the guest speed.
678
       It will be corrected fairly quickly anyway.  */
679
    icount_time_shift = 3;
680

    
681
    /* Have both realtime and virtual time triggers for speed adjustment.
682
       The realtime trigger catches emulated time passing too slowly,
683
       the virtual time trigger catches emulated time passing too fast.
684
       Realtime triggers occur even when idle, so use them less frequently
685
       than VM triggers.  */
686
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
687
    qemu_mod_timer(icount_rt_timer,
688
                   qemu_get_clock(rt_clock) + 1000);
689
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
690
    qemu_mod_timer(icount_vm_timer,
691
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
692
}
693

    
694
void qemu_run_all_timers(void)
695
{
696
    alarm_timer->pending = 0;
697

    
698
    /* rearm timer, if not periodic */
699
    if (alarm_timer->expired) {
700
        alarm_timer->expired = 0;
701
        qemu_rearm_alarm_timer(alarm_timer);
702
    }
703

    
704
    /* vm time timers */
705
    if (vm_running) {
706
        qemu_run_timers(vm_clock);
707
    }
708

    
709
    qemu_run_timers(rt_clock);
710
    qemu_run_timers(host_clock);
711
}
712

    
713
#ifdef _WIN32
714
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
715
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
716
                                        DWORD_PTR dw2)
717
#else
718
static void host_alarm_handler(int host_signum)
719
#endif
720
{
721
    struct qemu_alarm_timer *t = alarm_timer;
722
    if (!t)
723
        return;
724

    
725
#if 0
726
#define DISP_FREQ 1000
727
    {
728
        static int64_t delta_min = INT64_MAX;
729
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
730
        static int count;
731
        ti = qemu_get_clock(vm_clock);
732
        if (last_clock != 0) {
733
            delta = ti - last_clock;
734
            if (delta < delta_min)
735
                delta_min = delta;
736
            if (delta > delta_max)
737
                delta_max = delta;
738
            delta_cum += delta;
739
            if (++count == DISP_FREQ) {
740
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
741
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
742
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
743
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
744
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
745
                count = 0;
746
                delta_min = INT64_MAX;
747
                delta_max = 0;
748
                delta_cum = 0;
749
            }
750
        }
751
        last_clock = ti;
752
    }
753
#endif
754
    if (alarm_has_dynticks(t) ||
755
        (!use_icount &&
756
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
757
                               qemu_get_clock(vm_clock))) ||
758
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
759
                           qemu_get_clock(rt_clock)) ||
760
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
761
                           qemu_get_clock(host_clock))) {
762

    
763
        t->expired = alarm_has_dynticks(t);
764
        t->pending = 1;
765
        qemu_notify_event();
766
    }
767
}
768

    
769
int64_t qemu_next_deadline(void)
770
{
771
    /* To avoid problems with overflow limit this to 2^32.  */
772
    int64_t delta = INT32_MAX;
773

    
774
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
775
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
776
                     qemu_get_clock(vm_clock);
777
    }
778
    if (active_timers[QEMU_CLOCK_HOST]) {
779
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
780
                 qemu_get_clock(host_clock);
781
        if (hdelta < delta)
782
            delta = hdelta;
783
    }
784

    
785
    if (delta < 0)
786
        delta = 0;
787

    
788
    return delta;
789
}
790

    
791
#ifndef _WIN32
792

    
793
#if defined(__linux__)
794

    
795
#define RTC_FREQ 1024
796

    
797
static uint64_t qemu_next_deadline_dyntick(void)
798
{
799
    int64_t delta;
800
    int64_t rtdelta;
801

    
802
    if (use_icount)
803
        delta = INT32_MAX;
804
    else
805
        delta = (qemu_next_deadline() + 999) / 1000;
806

    
807
    if (active_timers[QEMU_CLOCK_REALTIME]) {
808
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
809
                 qemu_get_clock(rt_clock))*1000;
810
        if (rtdelta < delta)
811
            delta = rtdelta;
812
    }
813

    
814
    if (delta < MIN_TIMER_REARM_US)
815
        delta = MIN_TIMER_REARM_US;
816

    
817
    return delta;
818
}
819

    
820
static void enable_sigio_timer(int fd)
821
{
822
    struct sigaction act;
823

    
824
    /* timer signal */
825
    sigfillset(&act.sa_mask);
826
    act.sa_flags = 0;
827
    act.sa_handler = host_alarm_handler;
828

    
829
    sigaction(SIGIO, &act, NULL);
830
    fcntl_setfl(fd, O_ASYNC);
831
    fcntl(fd, F_SETOWN, getpid());
832
}
833

    
834
static int hpet_start_timer(struct qemu_alarm_timer *t)
835
{
836
    struct hpet_info info;
837
    int r, fd;
838

    
839
    fd = qemu_open("/dev/hpet", O_RDONLY);
840
    if (fd < 0)
841
        return -1;
842

    
843
    /* Set frequency */
844
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
845
    if (r < 0) {
846
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
847
                "error, but for better emulation accuracy type:\n"
848
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
849
        goto fail;
850
    }
851

    
852
    /* Check capabilities */
853
    r = ioctl(fd, HPET_INFO, &info);
854
    if (r < 0)
855
        goto fail;
856

    
857
    /* Enable periodic mode */
858
    r = ioctl(fd, HPET_EPI, 0);
859
    if (info.hi_flags && (r < 0))
860
        goto fail;
861

    
862
    /* Enable interrupt */
863
    r = ioctl(fd, HPET_IE_ON, 0);
864
    if (r < 0)
865
        goto fail;
866

    
867
    enable_sigio_timer(fd);
868
    t->priv = (void *)(long)fd;
869

    
870
    return 0;
871
fail:
872
    close(fd);
873
    return -1;
874
}
875

    
876
static void hpet_stop_timer(struct qemu_alarm_timer *t)
877
{
878
    int fd = (long)t->priv;
879

    
880
    close(fd);
881
}
882

    
883
static int rtc_start_timer(struct qemu_alarm_timer *t)
884
{
885
    int rtc_fd;
886
    unsigned long current_rtc_freq = 0;
887

    
888
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
889
    if (rtc_fd < 0)
890
        return -1;
891
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
892
    if (current_rtc_freq != RTC_FREQ &&
893
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
894
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
895
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
896
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
897
        goto fail;
898
    }
899
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
900
    fail:
901
        close(rtc_fd);
902
        return -1;
903
    }
904

    
905
    enable_sigio_timer(rtc_fd);
906

    
907
    t->priv = (void *)(long)rtc_fd;
908

    
909
    return 0;
910
}
911

    
912
static void rtc_stop_timer(struct qemu_alarm_timer *t)
913
{
914
    int rtc_fd = (long)t->priv;
915

    
916
    close(rtc_fd);
917
}
918

    
919
static int dynticks_start_timer(struct qemu_alarm_timer *t)
920
{
921
    struct sigevent ev;
922
    timer_t host_timer;
923
    struct sigaction act;
924

    
925
    sigfillset(&act.sa_mask);
926
    act.sa_flags = 0;
927
    act.sa_handler = host_alarm_handler;
928

    
929
    sigaction(SIGALRM, &act, NULL);
930

    
931
    /* 
932
     * Initialize ev struct to 0 to avoid valgrind complaining
933
     * about uninitialized data in timer_create call
934
     */
935
    memset(&ev, 0, sizeof(ev));
936
    ev.sigev_value.sival_int = 0;
937
    ev.sigev_notify = SIGEV_SIGNAL;
938
    ev.sigev_signo = SIGALRM;
939

    
940
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
941
        perror("timer_create");
942

    
943
        /* disable dynticks */
944
        fprintf(stderr, "Dynamic Ticks disabled\n");
945

    
946
        return -1;
947
    }
948

    
949
    t->priv = (void *)(long)host_timer;
950

    
951
    return 0;
952
}
953

    
954
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
955
{
956
    timer_t host_timer = (timer_t)(long)t->priv;
957

    
958
    timer_delete(host_timer);
959
}
960

    
961
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
962
{
963
    timer_t host_timer = (timer_t)(long)t->priv;
964
    struct itimerspec timeout;
965
    int64_t nearest_delta_us = INT64_MAX;
966
    int64_t current_us;
967

    
968
    assert(alarm_has_dynticks(t));
969
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
970
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
971
        !active_timers[QEMU_CLOCK_HOST])
972
        return;
973

    
974
    nearest_delta_us = qemu_next_deadline_dyntick();
975

    
976
    /* check whether a timer is already running */
977
    if (timer_gettime(host_timer, &timeout)) {
978
        perror("gettime");
979
        fprintf(stderr, "Internal timer error: aborting\n");
980
        exit(1);
981
    }
982
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
983
    if (current_us && current_us <= nearest_delta_us)
984
        return;
985

    
986
    timeout.it_interval.tv_sec = 0;
987
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
988
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
989
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
990
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
991
        perror("settime");
992
        fprintf(stderr, "Internal timer error: aborting\n");
993
        exit(1);
994
    }
995
}
996

    
997
#endif /* defined(__linux__) */
998

    
999
static int unix_start_timer(struct qemu_alarm_timer *t)
1000
{
1001
    struct sigaction act;
1002
    struct itimerval itv;
1003
    int err;
1004

    
1005
    /* timer signal */
1006
    sigfillset(&act.sa_mask);
1007
    act.sa_flags = 0;
1008
    act.sa_handler = host_alarm_handler;
1009

    
1010
    sigaction(SIGALRM, &act, NULL);
1011

    
1012
    itv.it_interval.tv_sec = 0;
1013
    /* for i386 kernel 2.6 to get 1 ms */
1014
    itv.it_interval.tv_usec = 999;
1015
    itv.it_value.tv_sec = 0;
1016
    itv.it_value.tv_usec = 10 * 1000;
1017

    
1018
    err = setitimer(ITIMER_REAL, &itv, NULL);
1019
    if (err)
1020
        return -1;
1021

    
1022
    return 0;
1023
}
1024

    
1025
static void unix_stop_timer(struct qemu_alarm_timer *t)
1026
{
1027
    struct itimerval itv;
1028

    
1029
    memset(&itv, 0, sizeof(itv));
1030
    setitimer(ITIMER_REAL, &itv, NULL);
1031
}
1032

    
1033
#endif /* !defined(_WIN32) */
1034

    
1035

    
1036
#ifdef _WIN32
1037

    
1038
static int win32_start_timer(struct qemu_alarm_timer *t)
1039
{
1040
    TIMECAPS tc;
1041
    struct qemu_alarm_win32 *data = t->priv;
1042
    UINT flags;
1043

    
1044
    memset(&tc, 0, sizeof(tc));
1045
    timeGetDevCaps(&tc, sizeof(tc));
1046

    
1047
    data->period = tc.wPeriodMin;
1048
    timeBeginPeriod(data->period);
1049

    
1050
    flags = TIME_CALLBACK_FUNCTION;
1051
    if (alarm_has_dynticks(t))
1052
        flags |= TIME_ONESHOT;
1053
    else
1054
        flags |= TIME_PERIODIC;
1055

    
1056
    data->timerId = timeSetEvent(1,         // interval (ms)
1057
                        data->period,       // resolution
1058
                        host_alarm_handler, // function
1059
                        (DWORD)t,           // parameter
1060
                        flags);
1061

    
1062
    if (!data->timerId) {
1063
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1064
                GetLastError());
1065
        timeEndPeriod(data->period);
1066
        return -1;
1067
    }
1068

    
1069
    return 0;
1070
}
1071

    
1072
static void win32_stop_timer(struct qemu_alarm_timer *t)
1073
{
1074
    struct qemu_alarm_win32 *data = t->priv;
1075

    
1076
    timeKillEvent(data->timerId);
1077
    timeEndPeriod(data->period);
1078
}
1079

    
1080
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1081
{
1082
    struct qemu_alarm_win32 *data = t->priv;
1083

    
1084
    assert(alarm_has_dynticks(t));
1085
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1086
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1087
        !active_timers[QEMU_CLOCK_HOST])
1088
        return;
1089

    
1090
    timeKillEvent(data->timerId);
1091

    
1092
    data->timerId = timeSetEvent(1,
1093
                        data->period,
1094
                        host_alarm_handler,
1095
                        (DWORD)t,
1096
                        TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1097

    
1098
    if (!data->timerId) {
1099
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1100
                GetLastError());
1101

    
1102
        timeEndPeriod(data->period);
1103
        exit(1);
1104
    }
1105
}
1106

    
1107
#endif /* _WIN32 */
1108

    
1109
static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1110
{
1111
    if (running)
1112
        qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1113
}
1114

    
1115
int init_timer_alarm(void)
1116
{
1117
    struct qemu_alarm_timer *t = NULL;
1118
    int i, err = -1;
1119

    
1120
    for (i = 0; alarm_timers[i].name; i++) {
1121
        t = &alarm_timers[i];
1122

    
1123
        err = t->start(t);
1124
        if (!err)
1125
            break;
1126
    }
1127

    
1128
    if (err) {
1129
        err = -ENOENT;
1130
        goto fail;
1131
    }
1132

    
1133
    /* first event is at time 0 */
1134
    t->pending = 1;
1135
    alarm_timer = t;
1136
    qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1137

    
1138
    return 0;
1139

    
1140
fail:
1141
    return err;
1142
}
1143

    
1144
void quit_timers(void)
1145
{
1146
    struct qemu_alarm_timer *t = alarm_timer;
1147
    alarm_timer = NULL;
1148
    t->stop(t);
1149
}
1150

    
1151
int qemu_calculate_timeout(void)
1152
{
1153
#ifndef CONFIG_IOTHREAD
1154
    int timeout;
1155

    
1156
    if (!vm_running)
1157
        timeout = 5000;
1158
    else {
1159
     /* XXX: use timeout computed from timers */
1160
        int64_t add;
1161
        int64_t delta;
1162
        /* Advance virtual time to the next event.  */
1163
        delta = qemu_icount_delta();
1164
        if (delta > 0) {
1165
            /* If virtual time is ahead of real time then just
1166
               wait for IO.  */
1167
            timeout = (delta + 999999) / 1000000;
1168
        } else {
1169
            /* Wait for either IO to occur or the next
1170
               timer event.  */
1171
            add = qemu_next_deadline();
1172
            /* We advance the timer before checking for IO.
1173
               Limit the amount we advance so that early IO
1174
               activity won't get the guest too far ahead.  */
1175
            if (add > 10000000)
1176
                add = 10000000;
1177
            delta += add;
1178
            qemu_icount += qemu_icount_round (add);
1179
            timeout = delta / 1000000;
1180
            if (timeout < 0)
1181
                timeout = 0;
1182
        }
1183
    }
1184

    
1185
    return timeout;
1186
#else /* CONFIG_IOTHREAD */
1187
    return 1000;
1188
#endif
1189
}
1190