2 * General purpose implementation of a simple periodic countdown timer.
4 * Copyright (c) 2007 CodeSourcery.
6 * This code is licenced under the GNU LGPL.
13 int enabled; /* 0 = disabled, 1 = periodic, 2 = oneshot. */
24 /* Use a bottom-half routine to avoid reentrancy issues. */
25 static void ptimer_trigger(ptimer_state *s)
28 qemu_bh_schedule(s->bh);
32 static void ptimer_reload(ptimer_state *s)
38 if (s->delta == 0 || s->period == 0) {
39 fprintf(stderr, "Timer with period zero, disabling\n");
44 s->last_event = s->next_event;
45 s->next_event = s->last_event + s->delta * s->period;
47 s->next_event += ((int64_t)s->period_frac * s->delta) >> 32;
49 qemu_mod_timer(s->timer, s->next_event);
52 static void ptimer_tick(void *opaque)
54 ptimer_state *s = (ptimer_state *)opaque;
57 if (s->enabled == 2) {
64 uint32_t ptimer_get_count(ptimer_state *s)
70 now = qemu_get_clock(vm_clock);
71 /* Figure out the current counter value. */
72 if (now - s->next_event > 0
74 /* Prevent timer underflowing if it should already have
81 rem = s->next_event - now;
91 void ptimer_set_count(ptimer_state *s, uint32_t count)
95 s->next_event = qemu_get_clock(vm_clock);
100 void ptimer_run(ptimer_state *s, int oneshot)
102 if (s->period == 0) {
103 fprintf(stderr, "Timer with period zero, disabling\n");
106 s->enabled = oneshot ? 2 : 1;
107 s->next_event = qemu_get_clock(vm_clock);
111 /* Pause a timer. Note that this may cause it to "loose" time, even if it
112 is immediately restarted. */
113 void ptimer_stop(ptimer_state *s)
118 s->delta = ptimer_get_count(s);
119 qemu_del_timer(s->timer);
123 /* Set counter increment interval in nanoseconds. */
124 void ptimer_set_period(ptimer_state *s, int64_t period)
127 fprintf(stderr, "FIXME: ptimer_set_period with running timer");
133 /* Set counter frequency in Hz. */
134 void ptimer_set_freq(ptimer_state *s, uint32_t freq)
137 fprintf(stderr, "FIXME: ptimer_set_freq with running timer");
139 s->period = 1000000000ll / freq;
140 s->period_frac = (1000000000ll << 32) / freq;
143 /* Set the initial countdown value. If reload is nonzero then also set
145 void ptimer_set_limit(ptimer_state *s, uint32_t limit, int reload)
148 fprintf(stderr, "FIXME: ptimer_set_limit with running timer");
155 ptimer_state *ptimer_init(QEMUBH *bh)
159 s = (ptimer_state *)qemu_mallocz(sizeof(ptimer_state));
161 s->timer = qemu_new_timer(vm_clock, ptimer_tick, s);