xref: /openbmc/qemu/hw/i386/kvm/i8254.c (revision 436c831a)
1 /*
2  * KVM in-kernel PIT (i8254) support
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  * Copyright (c) 2012      Jan Kiszka, Siemens AG
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include <linux/kvm.h>
28 #include "qapi/qapi-types-machine.h"
29 #include "qapi/error.h"
30 #include "qemu/module.h"
31 #include "qemu/timer.h"
32 #include "sysemu/runstate.h"
33 #include "hw/timer/i8254.h"
34 #include "hw/timer/i8254_internal.h"
35 #include "hw/qdev-properties-system.h"
36 #include "sysemu/kvm.h"
37 #include "qom/object.h"
38 
39 #define KVM_PIT_REINJECT_BIT 0
40 
41 #define CALIBRATION_ROUNDS   3
42 
43 typedef struct KVMPITClass KVMPITClass;
44 typedef struct KVMPITState KVMPITState;
45 DECLARE_OBJ_CHECKERS(KVMPITState, KVMPITClass,
46                      KVM_PIT, TYPE_KVM_I8254)
47 
48 struct KVMPITState {
49     PITCommonState parent_obj;
50 
51     LostTickPolicy lost_tick_policy;
52     bool vm_stopped;
53     int64_t kernel_clock_offset;
54 };
55 
56 struct KVMPITClass {
57     PITCommonClass parent_class;
58 
59     DeviceRealize parent_realize;
60 };
61 
62 static int64_t abs64(int64_t v)
63 {
64     return v < 0 ? -v : v;
65 }
66 
67 static void kvm_pit_update_clock_offset(KVMPITState *s)
68 {
69     int64_t offset, clock_offset;
70     struct timespec ts;
71     int i;
72 
73     /*
74      * Measure the delta between CLOCK_MONOTONIC, the base used for
75      * kvm_pit_channel_state::count_load_time, and QEMU_CLOCK_VIRTUAL. Take the
76      * minimum of several samples to filter out scheduling noise.
77      */
78     clock_offset = INT64_MAX;
79     for (i = 0; i < CALIBRATION_ROUNDS; i++) {
80         offset = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
81         clock_gettime(CLOCK_MONOTONIC, &ts);
82         offset -= ts.tv_nsec;
83         offset -= (int64_t)ts.tv_sec * 1000000000;
84         if (abs64(offset) < abs64(clock_offset)) {
85             clock_offset = offset;
86         }
87     }
88     s->kernel_clock_offset = clock_offset;
89 }
90 
91 static void kvm_pit_get(PITCommonState *pit)
92 {
93     KVMPITState *s = KVM_PIT(pit);
94     struct kvm_pit_state2 kpit;
95     struct kvm_pit_channel_state *kchan;
96     struct PITChannelState *sc;
97     int i, ret;
98 
99     /* No need to re-read the state if VM is stopped. */
100     if (s->vm_stopped) {
101         return;
102     }
103 
104     if (kvm_has_pit_state2()) {
105         ret = kvm_vm_ioctl(kvm_state, KVM_GET_PIT2, &kpit);
106         if (ret < 0) {
107             fprintf(stderr, "KVM_GET_PIT2 failed: %s\n", strerror(-ret));
108             abort();
109         }
110         pit->channels[0].irq_disabled = kpit.flags & KVM_PIT_FLAGS_HPET_LEGACY;
111     } else {
112         /*
113          * kvm_pit_state2 is superset of kvm_pit_state struct,
114          * so we can use it for KVM_GET_PIT as well.
115          */
116         ret = kvm_vm_ioctl(kvm_state, KVM_GET_PIT, &kpit);
117         if (ret < 0) {
118             fprintf(stderr, "KVM_GET_PIT failed: %s\n", strerror(-ret));
119             abort();
120         }
121     }
122     for (i = 0; i < 3; i++) {
123         kchan = &kpit.channels[i];
124         sc = &pit->channels[i];
125         sc->count = kchan->count;
126         sc->latched_count = kchan->latched_count;
127         sc->count_latched = kchan->count_latched;
128         sc->status_latched = kchan->status_latched;
129         sc->status = kchan->status;
130         sc->read_state = kchan->read_state;
131         sc->write_state = kchan->write_state;
132         sc->write_latch = kchan->write_latch;
133         sc->rw_mode = kchan->rw_mode;
134         sc->mode = kchan->mode;
135         sc->bcd = kchan->bcd;
136         sc->gate = kchan->gate;
137         sc->count_load_time = kchan->count_load_time + s->kernel_clock_offset;
138     }
139 
140     sc = &pit->channels[0];
141     sc->next_transition_time =
142         pit_get_next_transition_time(sc, sc->count_load_time);
143 }
144 
145 static void kvm_pit_put(PITCommonState *pit)
146 {
147     KVMPITState *s = KVM_PIT(pit);
148     struct kvm_pit_state2 kpit = {};
149     struct kvm_pit_channel_state *kchan;
150     struct PITChannelState *sc;
151     int i, ret;
152 
153     /* The offset keeps changing as long as the VM is stopped. */
154     if (s->vm_stopped) {
155         kvm_pit_update_clock_offset(s);
156     }
157 
158     kpit.flags = pit->channels[0].irq_disabled ? KVM_PIT_FLAGS_HPET_LEGACY : 0;
159     for (i = 0; i < 3; i++) {
160         kchan = &kpit.channels[i];
161         sc = &pit->channels[i];
162         kchan->count = sc->count;
163         kchan->latched_count = sc->latched_count;
164         kchan->count_latched = sc->count_latched;
165         kchan->status_latched = sc->status_latched;
166         kchan->status = sc->status;
167         kchan->read_state = sc->read_state;
168         kchan->write_state = sc->write_state;
169         kchan->write_latch = sc->write_latch;
170         kchan->rw_mode = sc->rw_mode;
171         kchan->mode = sc->mode;
172         kchan->bcd = sc->bcd;
173         kchan->gate = sc->gate;
174         kchan->count_load_time = sc->count_load_time - s->kernel_clock_offset;
175     }
176 
177     ret = kvm_vm_ioctl(kvm_state,
178                        kvm_has_pit_state2() ? KVM_SET_PIT2 : KVM_SET_PIT,
179                        &kpit);
180     if (ret < 0) {
181         fprintf(stderr, "%s failed: %s\n",
182                 kvm_has_pit_state2() ? "KVM_SET_PIT2" : "KVM_SET_PIT",
183                 strerror(-ret));
184         abort();
185     }
186 }
187 
188 static void kvm_pit_set_gate(PITCommonState *s, PITChannelState *sc, int val)
189 {
190     kvm_pit_get(s);
191 
192     switch (sc->mode) {
193     default:
194     case 0:
195     case 4:
196         /* XXX: just disable/enable counting */
197         break;
198     case 1:
199     case 2:
200     case 3:
201     case 5:
202         if (sc->gate < val) {
203             /* restart counting on rising edge */
204             sc->count_load_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
205         }
206         break;
207     }
208     sc->gate = val;
209 
210     kvm_pit_put(s);
211 }
212 
213 static void kvm_pit_get_channel_info(PITCommonState *s, PITChannelState *sc,
214                                      PITChannelInfo *info)
215 {
216     kvm_pit_get(s);
217 
218     pit_get_channel_info_common(s, sc, info);
219 }
220 
221 static void kvm_pit_reset(DeviceState *dev)
222 {
223     PITCommonState *s = PIT_COMMON(dev);
224 
225     pit_reset_common(s);
226 
227     kvm_pit_put(s);
228 }
229 
230 static void kvm_pit_irq_control(void *opaque, int n, int enable)
231 {
232     PITCommonState *pit = opaque;
233     PITChannelState *s = &pit->channels[0];
234 
235     kvm_pit_get(pit);
236 
237     s->irq_disabled = !enable;
238 
239     kvm_pit_put(pit);
240 }
241 
242 static void kvm_pit_vm_state_change(void *opaque, bool running,
243                                     RunState state)
244 {
245     KVMPITState *s = opaque;
246 
247     if (running) {
248         kvm_pit_update_clock_offset(s);
249         kvm_pit_put(PIT_COMMON(s));
250         s->vm_stopped = false;
251     } else {
252         kvm_pit_update_clock_offset(s);
253         kvm_pit_get(PIT_COMMON(s));
254         s->vm_stopped = true;
255     }
256 }
257 
258 static void kvm_pit_realizefn(DeviceState *dev, Error **errp)
259 {
260     PITCommonState *pit = PIT_COMMON(dev);
261     KVMPITClass *kpc = KVM_PIT_GET_CLASS(dev);
262     KVMPITState *s = KVM_PIT(pit);
263     struct kvm_pit_config config = {
264         .flags = 0,
265     };
266     int ret;
267 
268     if (kvm_check_extension(kvm_state, KVM_CAP_PIT2)) {
269         ret = kvm_vm_ioctl(kvm_state, KVM_CREATE_PIT2, &config);
270     } else {
271         ret = kvm_vm_ioctl(kvm_state, KVM_CREATE_PIT);
272     }
273     if (ret < 0) {
274         error_setg(errp, "Create kernel PIC irqchip failed: %s",
275                    strerror(-ret));
276         return;
277     }
278     switch (s->lost_tick_policy) {
279     case LOST_TICK_POLICY_DELAY:
280         break; /* enabled by default */
281     case LOST_TICK_POLICY_DISCARD:
282         if (kvm_check_extension(kvm_state, KVM_CAP_REINJECT_CONTROL)) {
283             struct kvm_reinject_control control = { .pit_reinject = 0 };
284 
285             ret = kvm_vm_ioctl(kvm_state, KVM_REINJECT_CONTROL, &control);
286             if (ret < 0) {
287                 error_setg(errp,
288                            "Can't disable in-kernel PIT reinjection: %s",
289                            strerror(-ret));
290                 return;
291             }
292         }
293         break;
294     default:
295         error_setg(errp, "Lost tick policy not supported.");
296         return;
297     }
298 
299     memory_region_init_io(&pit->ioports, OBJECT(dev), NULL, NULL, "kvm-pit", 4);
300 
301     qdev_init_gpio_in(dev, kvm_pit_irq_control, 1);
302 
303     qemu_add_vm_change_state_handler(kvm_pit_vm_state_change, s);
304 
305     kpc->parent_realize(dev, errp);
306 }
307 
308 static Property kvm_pit_properties[] = {
309     DEFINE_PROP_UINT32("iobase", PITCommonState, iobase,  -1),
310     DEFINE_PROP_LOSTTICKPOLICY("lost_tick_policy", KVMPITState,
311                                lost_tick_policy, LOST_TICK_POLICY_DELAY),
312     DEFINE_PROP_END_OF_LIST(),
313 };
314 
315 static void kvm_pit_class_init(ObjectClass *klass, void *data)
316 {
317     KVMPITClass *kpc = KVM_PIT_CLASS(klass);
318     PITCommonClass *k = PIT_COMMON_CLASS(klass);
319     DeviceClass *dc = DEVICE_CLASS(klass);
320 
321     device_class_set_parent_realize(dc, kvm_pit_realizefn,
322                                     &kpc->parent_realize);
323     k->set_channel_gate = kvm_pit_set_gate;
324     k->get_channel_info = kvm_pit_get_channel_info;
325     dc->reset = kvm_pit_reset;
326     device_class_set_props(dc, kvm_pit_properties);
327 }
328 
329 static const TypeInfo kvm_pit_info = {
330     .name          = TYPE_KVM_I8254,
331     .parent        = TYPE_PIT_COMMON,
332     .instance_size = sizeof(KVMPITState),
333     .class_init = kvm_pit_class_init,
334     .class_size = sizeof(KVMPITClass),
335 };
336 
337 static void kvm_pit_register(void)
338 {
339     type_register_static(&kvm_pit_info);
340 }
341 
342 type_init(kvm_pit_register)
343