xref: /linux/arch/x86/kvm/i8254.c (revision 95e9fd10f06cb5642028b6b851e32b8c8afb4571)
1 /*
2  * 8253/8254 interval timer emulation
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  * Copyright (c) 2006 Intel Corporation
6  * Copyright (c) 2007 Keir Fraser, XenSource Inc
7  * Copyright (c) 2008 Intel Corporation
8  * Copyright 2009 Red Hat, Inc. and/or its affiliates.
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a copy
11  * of this software and associated documentation files (the "Software"), to deal
12  * in the Software without restriction, including without limitation the rights
13  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14  * copies of the Software, and to permit persons to whom the Software is
15  * furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26  * THE SOFTWARE.
27  *
28  * Authors:
29  *   Sheng Yang <sheng.yang@intel.com>
30  *   Based on QEMU and Xen.
31  */
32 
33 #define pr_fmt(fmt) "pit: " fmt
34 
35 #include <linux/kvm_host.h>
36 #include <linux/slab.h>
37 
38 #include "irq.h"
39 #include "i8254.h"
40 
41 #ifndef CONFIG_X86_64
42 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
43 #else
44 #define mod_64(x, y) ((x) % (y))
45 #endif
46 
47 #define RW_STATE_LSB 1
48 #define RW_STATE_MSB 2
49 #define RW_STATE_WORD0 3
50 #define RW_STATE_WORD1 4
51 
52 /* Compute with 96 bit intermediate result: (a*b)/c */
53 static u64 muldiv64(u64 a, u32 b, u32 c)
54 {
55 	union {
56 		u64 ll;
57 		struct {
58 			u32 low, high;
59 		} l;
60 	} u, res;
61 	u64 rl, rh;
62 
63 	u.ll = a;
64 	rl = (u64)u.l.low * (u64)b;
65 	rh = (u64)u.l.high * (u64)b;
66 	rh += (rl >> 32);
67 	res.l.high = div64_u64(rh, c);
68 	res.l.low = div64_u64(((mod_64(rh, c) << 32) + (rl & 0xffffffff)), c);
69 	return res.ll;
70 }
71 
72 static void pit_set_gate(struct kvm *kvm, int channel, u32 val)
73 {
74 	struct kvm_kpit_channel_state *c =
75 		&kvm->arch.vpit->pit_state.channels[channel];
76 
77 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
78 
79 	switch (c->mode) {
80 	default:
81 	case 0:
82 	case 4:
83 		/* XXX: just disable/enable counting */
84 		break;
85 	case 1:
86 	case 2:
87 	case 3:
88 	case 5:
89 		/* Restart counting on rising edge. */
90 		if (c->gate < val)
91 			c->count_load_time = ktime_get();
92 		break;
93 	}
94 
95 	c->gate = val;
96 }
97 
98 static int pit_get_gate(struct kvm *kvm, int channel)
99 {
100 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
101 
102 	return kvm->arch.vpit->pit_state.channels[channel].gate;
103 }
104 
105 static s64 __kpit_elapsed(struct kvm *kvm)
106 {
107 	s64 elapsed;
108 	ktime_t remaining;
109 	struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
110 
111 	if (!ps->pit_timer.period)
112 		return 0;
113 
114 	/*
115 	 * The Counter does not stop when it reaches zero. In
116 	 * Modes 0, 1, 4, and 5 the Counter ``wraps around'' to
117 	 * the highest count, either FFFF hex for binary counting
118 	 * or 9999 for BCD counting, and continues counting.
119 	 * Modes 2 and 3 are periodic; the Counter reloads
120 	 * itself with the initial count and continues counting
121 	 * from there.
122 	 */
123 	remaining = hrtimer_get_remaining(&ps->pit_timer.timer);
124 	elapsed = ps->pit_timer.period - ktime_to_ns(remaining);
125 	elapsed = mod_64(elapsed, ps->pit_timer.period);
126 
127 	return elapsed;
128 }
129 
130 static s64 kpit_elapsed(struct kvm *kvm, struct kvm_kpit_channel_state *c,
131 			int channel)
132 {
133 	if (channel == 0)
134 		return __kpit_elapsed(kvm);
135 
136 	return ktime_to_ns(ktime_sub(ktime_get(), c->count_load_time));
137 }
138 
139 static int pit_get_count(struct kvm *kvm, int channel)
140 {
141 	struct kvm_kpit_channel_state *c =
142 		&kvm->arch.vpit->pit_state.channels[channel];
143 	s64 d, t;
144 	int counter;
145 
146 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
147 
148 	t = kpit_elapsed(kvm, c, channel);
149 	d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
150 
151 	switch (c->mode) {
152 	case 0:
153 	case 1:
154 	case 4:
155 	case 5:
156 		counter = (c->count - d) & 0xffff;
157 		break;
158 	case 3:
159 		/* XXX: may be incorrect for odd counts */
160 		counter = c->count - (mod_64((2 * d), c->count));
161 		break;
162 	default:
163 		counter = c->count - mod_64(d, c->count);
164 		break;
165 	}
166 	return counter;
167 }
168 
169 static int pit_get_out(struct kvm *kvm, int channel)
170 {
171 	struct kvm_kpit_channel_state *c =
172 		&kvm->arch.vpit->pit_state.channels[channel];
173 	s64 d, t;
174 	int out;
175 
176 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
177 
178 	t = kpit_elapsed(kvm, c, channel);
179 	d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
180 
181 	switch (c->mode) {
182 	default:
183 	case 0:
184 		out = (d >= c->count);
185 		break;
186 	case 1:
187 		out = (d < c->count);
188 		break;
189 	case 2:
190 		out = ((mod_64(d, c->count) == 0) && (d != 0));
191 		break;
192 	case 3:
193 		out = (mod_64(d, c->count) < ((c->count + 1) >> 1));
194 		break;
195 	case 4:
196 	case 5:
197 		out = (d == c->count);
198 		break;
199 	}
200 
201 	return out;
202 }
203 
204 static void pit_latch_count(struct kvm *kvm, int channel)
205 {
206 	struct kvm_kpit_channel_state *c =
207 		&kvm->arch.vpit->pit_state.channels[channel];
208 
209 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
210 
211 	if (!c->count_latched) {
212 		c->latched_count = pit_get_count(kvm, channel);
213 		c->count_latched = c->rw_mode;
214 	}
215 }
216 
217 static void pit_latch_status(struct kvm *kvm, int channel)
218 {
219 	struct kvm_kpit_channel_state *c =
220 		&kvm->arch.vpit->pit_state.channels[channel];
221 
222 	WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
223 
224 	if (!c->status_latched) {
225 		/* TODO: Return NULL COUNT (bit 6). */
226 		c->status = ((pit_get_out(kvm, channel) << 7) |
227 				(c->rw_mode << 4) |
228 				(c->mode << 1) |
229 				c->bcd);
230 		c->status_latched = 1;
231 	}
232 }
233 
234 static void kvm_pit_ack_irq(struct kvm_irq_ack_notifier *kian)
235 {
236 	struct kvm_kpit_state *ps = container_of(kian, struct kvm_kpit_state,
237 						 irq_ack_notifier);
238 	int value;
239 
240 	spin_lock(&ps->inject_lock);
241 	value = atomic_dec_return(&ps->pit_timer.pending);
242 	if (value < 0)
243 		/* spurious acks can be generated if, for example, the
244 		 * PIC is being reset.  Handle it gracefully here
245 		 */
246 		atomic_inc(&ps->pit_timer.pending);
247 	else if (value > 0)
248 		/* in this case, we had multiple outstanding pit interrupts
249 		 * that we needed to inject.  Reinject
250 		 */
251 		queue_kthread_work(&ps->pit->worker, &ps->pit->expired);
252 	ps->irq_ack = 1;
253 	spin_unlock(&ps->inject_lock);
254 }
255 
256 void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
257 {
258 	struct kvm_pit *pit = vcpu->kvm->arch.vpit;
259 	struct hrtimer *timer;
260 
261 	if (!kvm_vcpu_is_bsp(vcpu) || !pit)
262 		return;
263 
264 	timer = &pit->pit_state.pit_timer.timer;
265 	if (hrtimer_cancel(timer))
266 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
267 }
268 
269 static void destroy_pit_timer(struct kvm_pit *pit)
270 {
271 	hrtimer_cancel(&pit->pit_state.pit_timer.timer);
272 	flush_kthread_work(&pit->expired);
273 }
274 
275 static bool kpit_is_periodic(struct kvm_timer *ktimer)
276 {
277 	struct kvm_kpit_state *ps = container_of(ktimer, struct kvm_kpit_state,
278 						 pit_timer);
279 	return ps->is_periodic;
280 }
281 
282 static struct kvm_timer_ops kpit_ops = {
283 	.is_periodic = kpit_is_periodic,
284 };
285 
286 static void pit_do_work(struct kthread_work *work)
287 {
288 	struct kvm_pit *pit = container_of(work, struct kvm_pit, expired);
289 	struct kvm *kvm = pit->kvm;
290 	struct kvm_vcpu *vcpu;
291 	int i;
292 	struct kvm_kpit_state *ps = &pit->pit_state;
293 	int inject = 0;
294 
295 	/* Try to inject pending interrupts when
296 	 * last one has been acked.
297 	 */
298 	spin_lock(&ps->inject_lock);
299 	if (ps->irq_ack) {
300 		ps->irq_ack = 0;
301 		inject = 1;
302 	}
303 	spin_unlock(&ps->inject_lock);
304 	if (inject) {
305 		kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 1);
306 		kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 0);
307 
308 		/*
309 		 * Provides NMI watchdog support via Virtual Wire mode.
310 		 * The route is: PIT -> PIC -> LVT0 in NMI mode.
311 		 *
312 		 * Note: Our Virtual Wire implementation is simplified, only
313 		 * propagating PIT interrupts to all VCPUs when they have set
314 		 * LVT0 to NMI delivery. Other PIC interrupts are just sent to
315 		 * VCPU0, and only if its LVT0 is in EXTINT mode.
316 		 */
317 		if (kvm->arch.vapics_in_nmi_mode > 0)
318 			kvm_for_each_vcpu(i, vcpu, kvm)
319 				kvm_apic_nmi_wd_deliver(vcpu);
320 	}
321 }
322 
323 static enum hrtimer_restart pit_timer_fn(struct hrtimer *data)
324 {
325 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
326 	struct kvm_pit *pt = ktimer->kvm->arch.vpit;
327 
328 	if (ktimer->reinject || !atomic_read(&ktimer->pending)) {
329 		atomic_inc(&ktimer->pending);
330 		queue_kthread_work(&pt->worker, &pt->expired);
331 	}
332 
333 	if (ktimer->t_ops->is_periodic(ktimer)) {
334 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
335 		return HRTIMER_RESTART;
336 	} else
337 		return HRTIMER_NORESTART;
338 }
339 
340 static void create_pit_timer(struct kvm *kvm, u32 val, int is_period)
341 {
342 	struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
343 	struct kvm_timer *pt = &ps->pit_timer;
344 	s64 interval;
345 
346 	if (!irqchip_in_kernel(kvm) || ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)
347 		return;
348 
349 	interval = muldiv64(val, NSEC_PER_SEC, KVM_PIT_FREQ);
350 
351 	pr_debug("create pit timer, interval is %llu nsec\n", interval);
352 
353 	/* TODO The new value only affected after the retriggered */
354 	hrtimer_cancel(&pt->timer);
355 	flush_kthread_work(&ps->pit->expired);
356 	pt->period = interval;
357 	ps->is_periodic = is_period;
358 
359 	pt->timer.function = pit_timer_fn;
360 	pt->t_ops = &kpit_ops;
361 	pt->kvm = ps->pit->kvm;
362 
363 	atomic_set(&pt->pending, 0);
364 	ps->irq_ack = 1;
365 
366 	hrtimer_start(&pt->timer, ktime_add_ns(ktime_get(), interval),
367 		      HRTIMER_MODE_ABS);
368 }
369 
370 static void pit_load_count(struct kvm *kvm, int channel, u32 val)
371 {
372 	struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
373 
374 	WARN_ON(!mutex_is_locked(&ps->lock));
375 
376 	pr_debug("load_count val is %d, channel is %d\n", val, channel);
377 
378 	/*
379 	 * The largest possible initial count is 0; this is equivalent
380 	 * to 216 for binary counting and 104 for BCD counting.
381 	 */
382 	if (val == 0)
383 		val = 0x10000;
384 
385 	ps->channels[channel].count = val;
386 
387 	if (channel != 0) {
388 		ps->channels[channel].count_load_time = ktime_get();
389 		return;
390 	}
391 
392 	/* Two types of timer
393 	 * mode 1 is one shot, mode 2 is period, otherwise del timer */
394 	switch (ps->channels[0].mode) {
395 	case 0:
396 	case 1:
397         /* FIXME: enhance mode 4 precision */
398 	case 4:
399 		create_pit_timer(kvm, val, 0);
400 		break;
401 	case 2:
402 	case 3:
403 		create_pit_timer(kvm, val, 1);
404 		break;
405 	default:
406 		destroy_pit_timer(kvm->arch.vpit);
407 	}
408 }
409 
410 void kvm_pit_load_count(struct kvm *kvm, int channel, u32 val, int hpet_legacy_start)
411 {
412 	u8 saved_mode;
413 	if (hpet_legacy_start) {
414 		/* save existing mode for later reenablement */
415 		saved_mode = kvm->arch.vpit->pit_state.channels[0].mode;
416 		kvm->arch.vpit->pit_state.channels[0].mode = 0xff; /* disable timer */
417 		pit_load_count(kvm, channel, val);
418 		kvm->arch.vpit->pit_state.channels[0].mode = saved_mode;
419 	} else {
420 		pit_load_count(kvm, channel, val);
421 	}
422 }
423 
424 static inline struct kvm_pit *dev_to_pit(struct kvm_io_device *dev)
425 {
426 	return container_of(dev, struct kvm_pit, dev);
427 }
428 
429 static inline struct kvm_pit *speaker_to_pit(struct kvm_io_device *dev)
430 {
431 	return container_of(dev, struct kvm_pit, speaker_dev);
432 }
433 
434 static inline int pit_in_range(gpa_t addr)
435 {
436 	return ((addr >= KVM_PIT_BASE_ADDRESS) &&
437 		(addr < KVM_PIT_BASE_ADDRESS + KVM_PIT_MEM_LENGTH));
438 }
439 
440 static int pit_ioport_write(struct kvm_io_device *this,
441 			    gpa_t addr, int len, const void *data)
442 {
443 	struct kvm_pit *pit = dev_to_pit(this);
444 	struct kvm_kpit_state *pit_state = &pit->pit_state;
445 	struct kvm *kvm = pit->kvm;
446 	int channel, access;
447 	struct kvm_kpit_channel_state *s;
448 	u32 val = *(u32 *) data;
449 	if (!pit_in_range(addr))
450 		return -EOPNOTSUPP;
451 
452 	val  &= 0xff;
453 	addr &= KVM_PIT_CHANNEL_MASK;
454 
455 	mutex_lock(&pit_state->lock);
456 
457 	if (val != 0)
458 		pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n",
459 			 (unsigned int)addr, len, val);
460 
461 	if (addr == 3) {
462 		channel = val >> 6;
463 		if (channel == 3) {
464 			/* Read-Back Command. */
465 			for (channel = 0; channel < 3; channel++) {
466 				s = &pit_state->channels[channel];
467 				if (val & (2 << channel)) {
468 					if (!(val & 0x20))
469 						pit_latch_count(kvm, channel);
470 					if (!(val & 0x10))
471 						pit_latch_status(kvm, channel);
472 				}
473 			}
474 		} else {
475 			/* Select Counter <channel>. */
476 			s = &pit_state->channels[channel];
477 			access = (val >> 4) & KVM_PIT_CHANNEL_MASK;
478 			if (access == 0) {
479 				pit_latch_count(kvm, channel);
480 			} else {
481 				s->rw_mode = access;
482 				s->read_state = access;
483 				s->write_state = access;
484 				s->mode = (val >> 1) & 7;
485 				if (s->mode > 5)
486 					s->mode -= 4;
487 				s->bcd = val & 1;
488 			}
489 		}
490 	} else {
491 		/* Write Count. */
492 		s = &pit_state->channels[addr];
493 		switch (s->write_state) {
494 		default:
495 		case RW_STATE_LSB:
496 			pit_load_count(kvm, addr, val);
497 			break;
498 		case RW_STATE_MSB:
499 			pit_load_count(kvm, addr, val << 8);
500 			break;
501 		case RW_STATE_WORD0:
502 			s->write_latch = val;
503 			s->write_state = RW_STATE_WORD1;
504 			break;
505 		case RW_STATE_WORD1:
506 			pit_load_count(kvm, addr, s->write_latch | (val << 8));
507 			s->write_state = RW_STATE_WORD0;
508 			break;
509 		}
510 	}
511 
512 	mutex_unlock(&pit_state->lock);
513 	return 0;
514 }
515 
516 static int pit_ioport_read(struct kvm_io_device *this,
517 			   gpa_t addr, int len, void *data)
518 {
519 	struct kvm_pit *pit = dev_to_pit(this);
520 	struct kvm_kpit_state *pit_state = &pit->pit_state;
521 	struct kvm *kvm = pit->kvm;
522 	int ret, count;
523 	struct kvm_kpit_channel_state *s;
524 	if (!pit_in_range(addr))
525 		return -EOPNOTSUPP;
526 
527 	addr &= KVM_PIT_CHANNEL_MASK;
528 	if (addr == 3)
529 		return 0;
530 
531 	s = &pit_state->channels[addr];
532 
533 	mutex_lock(&pit_state->lock);
534 
535 	if (s->status_latched) {
536 		s->status_latched = 0;
537 		ret = s->status;
538 	} else if (s->count_latched) {
539 		switch (s->count_latched) {
540 		default:
541 		case RW_STATE_LSB:
542 			ret = s->latched_count & 0xff;
543 			s->count_latched = 0;
544 			break;
545 		case RW_STATE_MSB:
546 			ret = s->latched_count >> 8;
547 			s->count_latched = 0;
548 			break;
549 		case RW_STATE_WORD0:
550 			ret = s->latched_count & 0xff;
551 			s->count_latched = RW_STATE_MSB;
552 			break;
553 		}
554 	} else {
555 		switch (s->read_state) {
556 		default:
557 		case RW_STATE_LSB:
558 			count = pit_get_count(kvm, addr);
559 			ret = count & 0xff;
560 			break;
561 		case RW_STATE_MSB:
562 			count = pit_get_count(kvm, addr);
563 			ret = (count >> 8) & 0xff;
564 			break;
565 		case RW_STATE_WORD0:
566 			count = pit_get_count(kvm, addr);
567 			ret = count & 0xff;
568 			s->read_state = RW_STATE_WORD1;
569 			break;
570 		case RW_STATE_WORD1:
571 			count = pit_get_count(kvm, addr);
572 			ret = (count >> 8) & 0xff;
573 			s->read_state = RW_STATE_WORD0;
574 			break;
575 		}
576 	}
577 
578 	if (len > sizeof(ret))
579 		len = sizeof(ret);
580 	memcpy(data, (char *)&ret, len);
581 
582 	mutex_unlock(&pit_state->lock);
583 	return 0;
584 }
585 
586 static int speaker_ioport_write(struct kvm_io_device *this,
587 				gpa_t addr, int len, const void *data)
588 {
589 	struct kvm_pit *pit = speaker_to_pit(this);
590 	struct kvm_kpit_state *pit_state = &pit->pit_state;
591 	struct kvm *kvm = pit->kvm;
592 	u32 val = *(u32 *) data;
593 	if (addr != KVM_SPEAKER_BASE_ADDRESS)
594 		return -EOPNOTSUPP;
595 
596 	mutex_lock(&pit_state->lock);
597 	pit_state->speaker_data_on = (val >> 1) & 1;
598 	pit_set_gate(kvm, 2, val & 1);
599 	mutex_unlock(&pit_state->lock);
600 	return 0;
601 }
602 
603 static int speaker_ioport_read(struct kvm_io_device *this,
604 			       gpa_t addr, int len, void *data)
605 {
606 	struct kvm_pit *pit = speaker_to_pit(this);
607 	struct kvm_kpit_state *pit_state = &pit->pit_state;
608 	struct kvm *kvm = pit->kvm;
609 	unsigned int refresh_clock;
610 	int ret;
611 	if (addr != KVM_SPEAKER_BASE_ADDRESS)
612 		return -EOPNOTSUPP;
613 
614 	/* Refresh clock toggles at about 15us. We approximate as 2^14ns. */
615 	refresh_clock = ((unsigned int)ktime_to_ns(ktime_get()) >> 14) & 1;
616 
617 	mutex_lock(&pit_state->lock);
618 	ret = ((pit_state->speaker_data_on << 1) | pit_get_gate(kvm, 2) |
619 		(pit_get_out(kvm, 2) << 5) | (refresh_clock << 4));
620 	if (len > sizeof(ret))
621 		len = sizeof(ret);
622 	memcpy(data, (char *)&ret, len);
623 	mutex_unlock(&pit_state->lock);
624 	return 0;
625 }
626 
627 void kvm_pit_reset(struct kvm_pit *pit)
628 {
629 	int i;
630 	struct kvm_kpit_channel_state *c;
631 
632 	mutex_lock(&pit->pit_state.lock);
633 	pit->pit_state.flags = 0;
634 	for (i = 0; i < 3; i++) {
635 		c = &pit->pit_state.channels[i];
636 		c->mode = 0xff;
637 		c->gate = (i != 2);
638 		pit_load_count(pit->kvm, i, 0);
639 	}
640 	mutex_unlock(&pit->pit_state.lock);
641 
642 	atomic_set(&pit->pit_state.pit_timer.pending, 0);
643 	pit->pit_state.irq_ack = 1;
644 }
645 
646 static void pit_mask_notifer(struct kvm_irq_mask_notifier *kimn, bool mask)
647 {
648 	struct kvm_pit *pit = container_of(kimn, struct kvm_pit, mask_notifier);
649 
650 	if (!mask) {
651 		atomic_set(&pit->pit_state.pit_timer.pending, 0);
652 		pit->pit_state.irq_ack = 1;
653 	}
654 }
655 
656 static const struct kvm_io_device_ops pit_dev_ops = {
657 	.read     = pit_ioport_read,
658 	.write    = pit_ioport_write,
659 };
660 
661 static const struct kvm_io_device_ops speaker_dev_ops = {
662 	.read     = speaker_ioport_read,
663 	.write    = speaker_ioport_write,
664 };
665 
666 /* Caller must hold slots_lock */
667 struct kvm_pit *kvm_create_pit(struct kvm *kvm, u32 flags)
668 {
669 	struct kvm_pit *pit;
670 	struct kvm_kpit_state *pit_state;
671 	struct pid *pid;
672 	pid_t pid_nr;
673 	int ret;
674 
675 	pit = kzalloc(sizeof(struct kvm_pit), GFP_KERNEL);
676 	if (!pit)
677 		return NULL;
678 
679 	pit->irq_source_id = kvm_request_irq_source_id(kvm);
680 	if (pit->irq_source_id < 0) {
681 		kfree(pit);
682 		return NULL;
683 	}
684 
685 	mutex_init(&pit->pit_state.lock);
686 	mutex_lock(&pit->pit_state.lock);
687 	spin_lock_init(&pit->pit_state.inject_lock);
688 
689 	pid = get_pid(task_tgid(current));
690 	pid_nr = pid_vnr(pid);
691 	put_pid(pid);
692 
693 	init_kthread_worker(&pit->worker);
694 	pit->worker_task = kthread_run(kthread_worker_fn, &pit->worker,
695 				       "kvm-pit/%d", pid_nr);
696 	if (IS_ERR(pit->worker_task)) {
697 		mutex_unlock(&pit->pit_state.lock);
698 		kvm_free_irq_source_id(kvm, pit->irq_source_id);
699 		kfree(pit);
700 		return NULL;
701 	}
702 	init_kthread_work(&pit->expired, pit_do_work);
703 
704 	kvm->arch.vpit = pit;
705 	pit->kvm = kvm;
706 
707 	pit_state = &pit->pit_state;
708 	pit_state->pit = pit;
709 	hrtimer_init(&pit_state->pit_timer.timer,
710 		     CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
711 	pit_state->irq_ack_notifier.gsi = 0;
712 	pit_state->irq_ack_notifier.irq_acked = kvm_pit_ack_irq;
713 	kvm_register_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier);
714 	pit_state->pit_timer.reinject = true;
715 	mutex_unlock(&pit->pit_state.lock);
716 
717 	kvm_pit_reset(pit);
718 
719 	pit->mask_notifier.func = pit_mask_notifer;
720 	kvm_register_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
721 
722 	kvm_iodevice_init(&pit->dev, &pit_dev_ops);
723 	ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS, KVM_PIT_BASE_ADDRESS,
724 				      KVM_PIT_MEM_LENGTH, &pit->dev);
725 	if (ret < 0)
726 		goto fail;
727 
728 	if (flags & KVM_PIT_SPEAKER_DUMMY) {
729 		kvm_iodevice_init(&pit->speaker_dev, &speaker_dev_ops);
730 		ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS,
731 					      KVM_SPEAKER_BASE_ADDRESS, 4,
732 					      &pit->speaker_dev);
733 		if (ret < 0)
734 			goto fail_unregister;
735 	}
736 
737 	return pit;
738 
739 fail_unregister:
740 	kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &pit->dev);
741 
742 fail:
743 	kvm_unregister_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
744 	kvm_unregister_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier);
745 	kvm_free_irq_source_id(kvm, pit->irq_source_id);
746 	kthread_stop(pit->worker_task);
747 	kfree(pit);
748 	return NULL;
749 }
750 
751 void kvm_free_pit(struct kvm *kvm)
752 {
753 	struct hrtimer *timer;
754 
755 	if (kvm->arch.vpit) {
756 		kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &kvm->arch.vpit->dev);
757 		kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
758 					      &kvm->arch.vpit->speaker_dev);
759 		kvm_unregister_irq_mask_notifier(kvm, 0,
760 					       &kvm->arch.vpit->mask_notifier);
761 		kvm_unregister_irq_ack_notifier(kvm,
762 				&kvm->arch.vpit->pit_state.irq_ack_notifier);
763 		mutex_lock(&kvm->arch.vpit->pit_state.lock);
764 		timer = &kvm->arch.vpit->pit_state.pit_timer.timer;
765 		hrtimer_cancel(timer);
766 		flush_kthread_work(&kvm->arch.vpit->expired);
767 		kthread_stop(kvm->arch.vpit->worker_task);
768 		kvm_free_irq_source_id(kvm, kvm->arch.vpit->irq_source_id);
769 		mutex_unlock(&kvm->arch.vpit->pit_state.lock);
770 		kfree(kvm->arch.vpit);
771 	}
772 }
773