xref: /linux/arch/arm64/kvm/arch_timer.c (revision 5ea5880764cbb164afb17a62e76ca75dc371409d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 ARM Ltd.
4  * Author: Marc Zyngier <marc.zyngier@arm.com>
5  */
6 
7 #include <linux/cpu.h>
8 #include <linux/kvm.h>
9 #include <linux/kvm_host.h>
10 #include <linux/interrupt.h>
11 #include <linux/irq.h>
12 #include <linux/irqdomain.h>
13 #include <linux/uaccess.h>
14 
15 #include <clocksource/arm_arch_timer.h>
16 #include <asm/arch_timer.h>
17 #include <asm/kvm_emulate.h>
18 #include <asm/kvm_hyp.h>
19 #include <asm/kvm_nested.h>
20 
21 #include <kvm/arm_vgic.h>
22 #include <kvm/arm_arch_timer.h>
23 
24 #include "trace.h"
25 
26 static struct timecounter *timecounter;
27 static unsigned int host_vtimer_irq;
28 static unsigned int host_ptimer_irq;
29 static u32 host_vtimer_irq_flags;
30 static u32 host_ptimer_irq_flags;
31 
32 static DEFINE_STATIC_KEY_FALSE(has_gic_active_state);
33 DEFINE_STATIC_KEY_FALSE(broken_cntvoff_key);
34 
35 static const u8 default_ppi[] = {
36 	[TIMER_PTIMER]  = 30,
37 	[TIMER_VTIMER]  = 27,
38 	[TIMER_HPTIMER] = 26,
39 	[TIMER_HVTIMER] = 28,
40 };
41 
42 static bool kvm_timer_irq_can_fire(struct arch_timer_context *timer_ctx);
43 static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
44 				 struct arch_timer_context *timer_ctx);
45 static bool kvm_timer_should_fire(struct arch_timer_context *timer_ctx);
46 static void kvm_arm_timer_write(struct kvm_vcpu *vcpu,
47 				struct arch_timer_context *timer,
48 				enum kvm_arch_timer_regs treg,
49 				u64 val);
50 static u64 kvm_arm_timer_read(struct kvm_vcpu *vcpu,
51 			      struct arch_timer_context *timer,
52 			      enum kvm_arch_timer_regs treg);
53 static bool kvm_arch_timer_get_input_level(int vintid);
54 
55 static struct irq_ops arch_timer_irq_ops = {
56 	.get_input_level = kvm_arch_timer_get_input_level,
57 };
58 
59 static struct irq_ops arch_timer_irq_ops_vgic_v5 = {
60 	.get_input_level = kvm_arch_timer_get_input_level,
61 	.queue_irq_unlock = vgic_v5_ppi_queue_irq_unlock,
62 	.set_direct_injection = vgic_v5_set_ppi_dvi,
63 };
64 
65 static int nr_timers(struct kvm_vcpu *vcpu)
66 {
67 	if (!vcpu_has_nv(vcpu))
68 		return NR_KVM_EL0_TIMERS;
69 
70 	return NR_KVM_TIMERS;
71 }
72 
73 u32 timer_get_ctl(struct arch_timer_context *ctxt)
74 {
75 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctxt);
76 
77 	switch(arch_timer_ctx_index(ctxt)) {
78 	case TIMER_VTIMER:
79 		return __vcpu_sys_reg(vcpu, CNTV_CTL_EL0);
80 	case TIMER_PTIMER:
81 		return __vcpu_sys_reg(vcpu, CNTP_CTL_EL0);
82 	case TIMER_HVTIMER:
83 		return __vcpu_sys_reg(vcpu, CNTHV_CTL_EL2);
84 	case TIMER_HPTIMER:
85 		return __vcpu_sys_reg(vcpu, CNTHP_CTL_EL2);
86 	default:
87 		WARN_ON(1);
88 		return 0;
89 	}
90 }
91 
92 u64 timer_get_cval(struct arch_timer_context *ctxt)
93 {
94 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctxt);
95 
96 	switch(arch_timer_ctx_index(ctxt)) {
97 	case TIMER_VTIMER:
98 		return __vcpu_sys_reg(vcpu, CNTV_CVAL_EL0);
99 	case TIMER_PTIMER:
100 		return __vcpu_sys_reg(vcpu, CNTP_CVAL_EL0);
101 	case TIMER_HVTIMER:
102 		return __vcpu_sys_reg(vcpu, CNTHV_CVAL_EL2);
103 	case TIMER_HPTIMER:
104 		return __vcpu_sys_reg(vcpu, CNTHP_CVAL_EL2);
105 	default:
106 		WARN_ON(1);
107 		return 0;
108 	}
109 }
110 
111 static void timer_set_ctl(struct arch_timer_context *ctxt, u32 ctl)
112 {
113 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctxt);
114 
115 	switch(arch_timer_ctx_index(ctxt)) {
116 	case TIMER_VTIMER:
117 		__vcpu_assign_sys_reg(vcpu, CNTV_CTL_EL0, ctl);
118 		break;
119 	case TIMER_PTIMER:
120 		__vcpu_assign_sys_reg(vcpu, CNTP_CTL_EL0, ctl);
121 		break;
122 	case TIMER_HVTIMER:
123 		__vcpu_assign_sys_reg(vcpu, CNTHV_CTL_EL2, ctl);
124 		break;
125 	case TIMER_HPTIMER:
126 		__vcpu_assign_sys_reg(vcpu, CNTHP_CTL_EL2, ctl);
127 		break;
128 	default:
129 		WARN_ON(1);
130 	}
131 }
132 
133 static void timer_set_cval(struct arch_timer_context *ctxt, u64 cval)
134 {
135 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctxt);
136 
137 	switch(arch_timer_ctx_index(ctxt)) {
138 	case TIMER_VTIMER:
139 		__vcpu_assign_sys_reg(vcpu, CNTV_CVAL_EL0, cval);
140 		break;
141 	case TIMER_PTIMER:
142 		__vcpu_assign_sys_reg(vcpu, CNTP_CVAL_EL0, cval);
143 		break;
144 	case TIMER_HVTIMER:
145 		__vcpu_assign_sys_reg(vcpu, CNTHV_CVAL_EL2, cval);
146 		break;
147 	case TIMER_HPTIMER:
148 		__vcpu_assign_sys_reg(vcpu, CNTHP_CVAL_EL2, cval);
149 		break;
150 	default:
151 		WARN_ON(1);
152 	}
153 }
154 
155 u64 kvm_phys_timer_read(void)
156 {
157 	return timecounter->cc->read(timecounter->cc);
158 }
159 
160 void get_timer_map(struct kvm_vcpu *vcpu, struct timer_map *map)
161 {
162 	if (vcpu_has_nv(vcpu)) {
163 		if (is_hyp_ctxt(vcpu)) {
164 			map->direct_vtimer = vcpu_hvtimer(vcpu);
165 			map->direct_ptimer = vcpu_hptimer(vcpu);
166 			map->emul_vtimer = vcpu_vtimer(vcpu);
167 			map->emul_ptimer = vcpu_ptimer(vcpu);
168 		} else {
169 			map->direct_vtimer = vcpu_vtimer(vcpu);
170 			map->direct_ptimer = vcpu_ptimer(vcpu);
171 			map->emul_vtimer = vcpu_hvtimer(vcpu);
172 			map->emul_ptimer = vcpu_hptimer(vcpu);
173 		}
174 	} else if (has_vhe()) {
175 		map->direct_vtimer = vcpu_vtimer(vcpu);
176 		map->direct_ptimer = vcpu_ptimer(vcpu);
177 		map->emul_vtimer = NULL;
178 		map->emul_ptimer = NULL;
179 	} else {
180 		map->direct_vtimer = vcpu_vtimer(vcpu);
181 		map->direct_ptimer = NULL;
182 		map->emul_vtimer = NULL;
183 		map->emul_ptimer = vcpu_ptimer(vcpu);
184 	}
185 
186 	trace_kvm_get_timer_map(vcpu->vcpu_id, map);
187 }
188 
189 static inline bool userspace_irqchip(struct kvm *kvm)
190 {
191 	return unlikely(!irqchip_in_kernel(kvm));
192 }
193 
194 static void soft_timer_start(struct hrtimer *hrt, u64 ns)
195 {
196 	hrtimer_start(hrt, ktime_add_ns(ktime_get(), ns),
197 		      HRTIMER_MODE_ABS_HARD);
198 }
199 
200 static void soft_timer_cancel(struct hrtimer *hrt)
201 {
202 	hrtimer_cancel(hrt);
203 }
204 
205 static irqreturn_t kvm_arch_timer_handler(int irq, void *dev_id)
206 {
207 	struct kvm_vcpu *vcpu = *(struct kvm_vcpu **)dev_id;
208 	struct arch_timer_context *ctx;
209 	struct timer_map map;
210 
211 	/*
212 	 * We may see a timer interrupt after vcpu_put() has been called which
213 	 * sets the CPU's vcpu pointer to NULL, because even though the timer
214 	 * has been disabled in timer_save_state(), the hardware interrupt
215 	 * signal may not have been retired from the interrupt controller yet.
216 	 */
217 	if (!vcpu)
218 		return IRQ_HANDLED;
219 
220 	get_timer_map(vcpu, &map);
221 
222 	if (irq == host_vtimer_irq)
223 		ctx = map.direct_vtimer;
224 	else
225 		ctx = map.direct_ptimer;
226 
227 	if (kvm_timer_should_fire(ctx))
228 		kvm_timer_update_irq(vcpu, true, ctx);
229 
230 	if (userspace_irqchip(vcpu->kvm) &&
231 	    !static_branch_unlikely(&has_gic_active_state))
232 		disable_percpu_irq(host_vtimer_irq);
233 
234 	return IRQ_HANDLED;
235 }
236 
237 static u64 kvm_counter_compute_delta(struct arch_timer_context *timer_ctx,
238 				     u64 val)
239 {
240 	u64 now = kvm_phys_timer_read() - timer_get_offset(timer_ctx);
241 
242 	if (now < val) {
243 		u64 ns;
244 
245 		ns = cyclecounter_cyc2ns(timecounter->cc,
246 					 val - now,
247 					 timecounter->mask,
248 					 &timer_ctx->ns_frac);
249 		return ns;
250 	}
251 
252 	return 0;
253 }
254 
255 static u64 kvm_timer_compute_delta(struct arch_timer_context *timer_ctx)
256 {
257 	return kvm_counter_compute_delta(timer_ctx, timer_get_cval(timer_ctx));
258 }
259 
260 static bool kvm_timer_irq_can_fire(struct arch_timer_context *timer_ctx)
261 {
262 	WARN_ON(timer_ctx && timer_ctx->loaded);
263 	return timer_ctx &&
264 		((timer_get_ctl(timer_ctx) &
265 		  (ARCH_TIMER_CTRL_IT_MASK | ARCH_TIMER_CTRL_ENABLE)) == ARCH_TIMER_CTRL_ENABLE);
266 }
267 
268 static bool vcpu_has_wfit_active(struct kvm_vcpu *vcpu)
269 {
270 	return (cpus_have_final_cap(ARM64_HAS_WFXT) &&
271 		vcpu_get_flag(vcpu, IN_WFIT));
272 }
273 
274 static u64 wfit_delay_ns(struct kvm_vcpu *vcpu)
275 {
276 	u64 val = vcpu_get_reg(vcpu, kvm_vcpu_sys_get_rt(vcpu));
277 	struct arch_timer_context *ctx;
278 
279 	ctx = is_hyp_ctxt(vcpu) ? vcpu_hvtimer(vcpu) : vcpu_vtimer(vcpu);
280 
281 	return kvm_counter_compute_delta(ctx, val);
282 }
283 
284 /*
285  * Returns the earliest expiration time in ns among guest timers.
286  * Note that it will return 0 if none of timers can fire.
287  */
288 static u64 kvm_timer_earliest_exp(struct kvm_vcpu *vcpu)
289 {
290 	u64 min_delta = ULLONG_MAX;
291 	int i;
292 
293 	for (i = 0; i < nr_timers(vcpu); i++) {
294 		struct arch_timer_context *ctx = &vcpu->arch.timer_cpu.timers[i];
295 
296 		WARN(ctx->loaded, "timer %d loaded\n", i);
297 		if (kvm_timer_irq_can_fire(ctx))
298 			min_delta = min(min_delta, kvm_timer_compute_delta(ctx));
299 	}
300 
301 	if (vcpu_has_wfit_active(vcpu))
302 		min_delta = min(min_delta, wfit_delay_ns(vcpu));
303 
304 	/* If none of timers can fire, then return 0 */
305 	if (min_delta == ULLONG_MAX)
306 		return 0;
307 
308 	return min_delta;
309 }
310 
311 static enum hrtimer_restart kvm_bg_timer_expire(struct hrtimer *hrt)
312 {
313 	struct arch_timer_cpu *timer;
314 	struct kvm_vcpu *vcpu;
315 	u64 ns;
316 
317 	timer = container_of(hrt, struct arch_timer_cpu, bg_timer);
318 	vcpu = container_of(timer, struct kvm_vcpu, arch.timer_cpu);
319 
320 	/*
321 	 * Check that the timer has really expired from the guest's
322 	 * PoV (NTP on the host may have forced it to expire
323 	 * early). If we should have slept longer, restart it.
324 	 */
325 	ns = kvm_timer_earliest_exp(vcpu);
326 	if (unlikely(ns)) {
327 		hrtimer_forward_now(hrt, ns_to_ktime(ns));
328 		return HRTIMER_RESTART;
329 	}
330 
331 	kvm_vcpu_wake_up(vcpu);
332 	return HRTIMER_NORESTART;
333 }
334 
335 static enum hrtimer_restart kvm_hrtimer_expire(struct hrtimer *hrt)
336 {
337 	struct arch_timer_context *ctx;
338 	struct kvm_vcpu *vcpu;
339 	u64 ns;
340 
341 	ctx = container_of(hrt, struct arch_timer_context, hrtimer);
342 	vcpu = timer_context_to_vcpu(ctx);
343 
344 	trace_kvm_timer_hrtimer_expire(ctx);
345 
346 	/*
347 	 * Check that the timer has really expired from the guest's
348 	 * PoV (NTP on the host may have forced it to expire
349 	 * early). If not ready, schedule for a later time.
350 	 */
351 	ns = kvm_timer_compute_delta(ctx);
352 	if (unlikely(ns)) {
353 		hrtimer_forward_now(hrt, ns_to_ktime(ns));
354 		return HRTIMER_RESTART;
355 	}
356 
357 	kvm_timer_update_irq(vcpu, true, ctx);
358 	return HRTIMER_NORESTART;
359 }
360 
361 static bool kvm_timer_should_fire(struct arch_timer_context *timer_ctx)
362 {
363 	enum kvm_arch_timers index;
364 	u64 cval, now;
365 
366 	if (!timer_ctx)
367 		return false;
368 
369 	index = arch_timer_ctx_index(timer_ctx);
370 
371 	if (timer_ctx->loaded) {
372 		u32 cnt_ctl = 0;
373 
374 		switch (index) {
375 		case TIMER_VTIMER:
376 		case TIMER_HVTIMER:
377 			cnt_ctl = read_sysreg_el0(SYS_CNTV_CTL);
378 			break;
379 		case TIMER_PTIMER:
380 		case TIMER_HPTIMER:
381 			cnt_ctl = read_sysreg_el0(SYS_CNTP_CTL);
382 			break;
383 		case NR_KVM_TIMERS:
384 			/* GCC is braindead */
385 			cnt_ctl = 0;
386 			break;
387 		}
388 
389 		return  (cnt_ctl & ARCH_TIMER_CTRL_ENABLE) &&
390 		        (cnt_ctl & ARCH_TIMER_CTRL_IT_STAT) &&
391 		       !(cnt_ctl & ARCH_TIMER_CTRL_IT_MASK);
392 	}
393 
394 	if (!kvm_timer_irq_can_fire(timer_ctx))
395 		return false;
396 
397 	cval = timer_get_cval(timer_ctx);
398 	now = kvm_phys_timer_read() - timer_get_offset(timer_ctx);
399 
400 	return cval <= now;
401 }
402 
403 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
404 {
405 	return vcpu_has_wfit_active(vcpu) && wfit_delay_ns(vcpu) == 0;
406 }
407 
408 /*
409  * Reflect the timer output level into the kvm_run structure
410  */
411 void kvm_timer_update_run(struct kvm_vcpu *vcpu)
412 {
413 	struct arch_timer_context *vtimer = vcpu_vtimer(vcpu);
414 	struct arch_timer_context *ptimer = vcpu_ptimer(vcpu);
415 	struct kvm_sync_regs *regs = &vcpu->run->s.regs;
416 
417 	/* Populate the device bitmap with the timer states */
418 	regs->device_irq_level &= ~(KVM_ARM_DEV_EL1_VTIMER |
419 				    KVM_ARM_DEV_EL1_PTIMER);
420 	if (kvm_timer_should_fire(vtimer))
421 		regs->device_irq_level |= KVM_ARM_DEV_EL1_VTIMER;
422 	if (kvm_timer_should_fire(ptimer))
423 		regs->device_irq_level |= KVM_ARM_DEV_EL1_PTIMER;
424 }
425 
426 static void kvm_timer_update_status(struct arch_timer_context *ctx, bool level)
427 {
428 	/*
429 	 * Paper over NV2 brokenness by publishing the interrupt status
430 	 * bit. This still results in a poor quality of emulation (guest
431 	 * writes will have no effect until the next exit).
432 	 *
433 	 * But hey, it's fast, right?
434 	 */
435 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctx);
436 	if (is_hyp_ctxt(vcpu) &&
437 	    (ctx == vcpu_vtimer(vcpu) || ctx == vcpu_ptimer(vcpu))) {
438 		unsigned long val = timer_get_ctl(ctx);
439 		__assign_bit(__ffs(ARCH_TIMER_CTRL_IT_STAT), &val, level);
440 		timer_set_ctl(ctx, val);
441 	}
442 }
443 
444 static void kvm_timer_update_irq(struct kvm_vcpu *vcpu, bool new_level,
445 				 struct arch_timer_context *timer_ctx)
446 {
447 	kvm_timer_update_status(timer_ctx, new_level);
448 
449 	timer_ctx->irq.level = new_level;
450 	trace_kvm_timer_update_irq(vcpu->vcpu_id, timer_irq(timer_ctx),
451 				   timer_ctx->irq.level);
452 
453 	if (userspace_irqchip(vcpu->kvm))
454 		return;
455 
456 	/* Skip injecting on GICv5 for directly injected (DVI'd) timers */
457 	if (vgic_is_v5(vcpu->kvm)) {
458 		struct timer_map map;
459 
460 		get_timer_map(vcpu, &map);
461 
462 		if (map.direct_ptimer == timer_ctx ||
463 		    map.direct_vtimer == timer_ctx)
464 			return;
465 	}
466 
467 	kvm_vgic_inject_irq(vcpu->kvm, vcpu,
468 			    timer_irq(timer_ctx),
469 			    timer_ctx->irq.level,
470 			    timer_ctx);
471 }
472 
473 /* Only called for a fully emulated timer */
474 static void timer_emulate(struct arch_timer_context *ctx)
475 {
476 	bool should_fire = kvm_timer_should_fire(ctx);
477 
478 	trace_kvm_timer_emulate(ctx, should_fire);
479 
480 	if (should_fire != ctx->irq.level)
481 		kvm_timer_update_irq(timer_context_to_vcpu(ctx), should_fire, ctx);
482 
483 	kvm_timer_update_status(ctx, should_fire);
484 
485 	/*
486 	 * If the timer can fire now, we don't need to have a soft timer
487 	 * scheduled for the future.  If the timer cannot fire at all,
488 	 * then we also don't need a soft timer.
489 	 */
490 	if (should_fire || !kvm_timer_irq_can_fire(ctx))
491 		return;
492 
493 	soft_timer_start(&ctx->hrtimer, kvm_timer_compute_delta(ctx));
494 }
495 
496 static void set_cntvoff(u64 cntvoff)
497 {
498 	kvm_call_hyp(__kvm_timer_set_cntvoff, cntvoff);
499 }
500 
501 static void set_cntpoff(u64 cntpoff)
502 {
503 	if (has_cntpoff())
504 		write_sysreg_s(cntpoff, SYS_CNTPOFF_EL2);
505 }
506 
507 static void timer_save_state(struct arch_timer_context *ctx)
508 {
509 	struct arch_timer_cpu *timer = vcpu_timer(timer_context_to_vcpu(ctx));
510 	enum kvm_arch_timers index = arch_timer_ctx_index(ctx);
511 	unsigned long flags;
512 
513 	if (!timer->enabled)
514 		return;
515 
516 	local_irq_save(flags);
517 
518 	if (!ctx->loaded)
519 		goto out;
520 
521 	switch (index) {
522 		u64 cval;
523 
524 	case TIMER_VTIMER:
525 	case TIMER_HVTIMER:
526 		timer_set_ctl(ctx, read_sysreg_el0(SYS_CNTV_CTL));
527 		cval = read_sysreg_el0(SYS_CNTV_CVAL);
528 
529 		if (has_broken_cntvoff())
530 			cval -= timer_get_offset(ctx);
531 
532 		timer_set_cval(ctx, cval);
533 
534 		/* Disable the timer */
535 		write_sysreg_el0(0, SYS_CNTV_CTL);
536 		isb();
537 
538 		/*
539 		 * The kernel may decide to run userspace after
540 		 * calling vcpu_put, so we reset cntvoff to 0 to
541 		 * ensure a consistent read between user accesses to
542 		 * the virtual counter and kernel access to the
543 		 * physical counter of non-VHE case.
544 		 *
545 		 * For VHE, the virtual counter uses a fixed virtual
546 		 * offset of zero, so no need to zero CNTVOFF_EL2
547 		 * register, but this is actually useful when switching
548 		 * between EL1/vEL2 with NV.
549 		 *
550 		 * Do it unconditionally, as this is either unavoidable
551 		 * or dirt cheap.
552 		 */
553 		set_cntvoff(0);
554 		break;
555 	case TIMER_PTIMER:
556 	case TIMER_HPTIMER:
557 		timer_set_ctl(ctx, read_sysreg_el0(SYS_CNTP_CTL));
558 		cval = read_sysreg_el0(SYS_CNTP_CVAL);
559 
560 		cval -= timer_get_offset(ctx);
561 
562 		timer_set_cval(ctx, cval);
563 
564 		/* Disable the timer */
565 		write_sysreg_el0(0, SYS_CNTP_CTL);
566 		isb();
567 
568 		set_cntpoff(0);
569 		break;
570 	case NR_KVM_TIMERS:
571 		BUG();
572 	}
573 
574 	trace_kvm_timer_save_state(ctx);
575 
576 	ctx->loaded = false;
577 out:
578 	local_irq_restore(flags);
579 }
580 
581 /*
582  * Schedule the background timer before calling kvm_vcpu_halt, so that this
583  * thread is removed from its waitqueue and made runnable when there's a timer
584  * interrupt to handle.
585  */
586 static void kvm_timer_blocking(struct kvm_vcpu *vcpu)
587 {
588 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
589 	struct timer_map map;
590 
591 	get_timer_map(vcpu, &map);
592 
593 	/*
594 	 * If no timers are capable of raising interrupts (disabled or
595 	 * masked), then there's no more work for us to do.
596 	 */
597 	if (!kvm_timer_irq_can_fire(map.direct_vtimer) &&
598 	    !kvm_timer_irq_can_fire(map.direct_ptimer) &&
599 	    !kvm_timer_irq_can_fire(map.emul_vtimer) &&
600 	    !kvm_timer_irq_can_fire(map.emul_ptimer) &&
601 	    !vcpu_has_wfit_active(vcpu))
602 		return;
603 
604 	/*
605 	 * At least one guest time will expire. Schedule a background timer.
606 	 * Set the earliest expiration time among the guest timers.
607 	 */
608 	soft_timer_start(&timer->bg_timer, kvm_timer_earliest_exp(vcpu));
609 }
610 
611 static void kvm_timer_unblocking(struct kvm_vcpu *vcpu)
612 {
613 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
614 
615 	soft_timer_cancel(&timer->bg_timer);
616 }
617 
618 static void timer_restore_state(struct arch_timer_context *ctx)
619 {
620 	struct arch_timer_cpu *timer = vcpu_timer(timer_context_to_vcpu(ctx));
621 	enum kvm_arch_timers index = arch_timer_ctx_index(ctx);
622 	unsigned long flags;
623 
624 	if (!timer->enabled)
625 		return;
626 
627 	local_irq_save(flags);
628 
629 	if (ctx->loaded)
630 		goto out;
631 
632 	switch (index) {
633 		u64 cval, offset;
634 
635 	case TIMER_VTIMER:
636 	case TIMER_HVTIMER:
637 		cval = timer_get_cval(ctx);
638 		offset = timer_get_offset(ctx);
639 		if (has_broken_cntvoff()) {
640 			set_cntvoff(0);
641 			cval += offset;
642 		} else {
643 			set_cntvoff(offset);
644 		}
645 		write_sysreg_el0(cval, SYS_CNTV_CVAL);
646 		isb();
647 		write_sysreg_el0(timer_get_ctl(ctx), SYS_CNTV_CTL);
648 		break;
649 	case TIMER_PTIMER:
650 	case TIMER_HPTIMER:
651 		cval = timer_get_cval(ctx);
652 		offset = timer_get_offset(ctx);
653 		set_cntpoff(offset);
654 		cval += offset;
655 		write_sysreg_el0(cval, SYS_CNTP_CVAL);
656 		isb();
657 		write_sysreg_el0(timer_get_ctl(ctx), SYS_CNTP_CTL);
658 		break;
659 	case NR_KVM_TIMERS:
660 		BUG();
661 	}
662 
663 	trace_kvm_timer_restore_state(ctx);
664 
665 	ctx->loaded = true;
666 out:
667 	local_irq_restore(flags);
668 }
669 
670 static inline void set_timer_irq_phys_active(struct arch_timer_context *ctx, bool active)
671 {
672 	int r;
673 	r = irq_set_irqchip_state(ctx->host_timer_irq, IRQCHIP_STATE_ACTIVE, active);
674 	WARN_ON(r);
675 }
676 
677 static void kvm_timer_vcpu_load_gic(struct arch_timer_context *ctx)
678 {
679 	struct kvm_vcpu *vcpu = timer_context_to_vcpu(ctx);
680 	bool phys_active = false;
681 
682 	/*
683 	 * Update the timer output so that it is likely to match the
684 	 * state we're about to restore. If the timer expires between
685 	 * this point and the register restoration, we'll take the
686 	 * interrupt anyway.
687 	 */
688 	kvm_timer_update_irq(vcpu, kvm_timer_should_fire(ctx), ctx);
689 
690 	if (irqchip_in_kernel(vcpu->kvm))
691 		phys_active = kvm_vgic_map_is_active(vcpu, timer_irq(ctx));
692 
693 	phys_active |= ctx->irq.level;
694 	phys_active |= vgic_is_v5(vcpu->kvm);
695 
696 	set_timer_irq_phys_active(ctx, phys_active);
697 }
698 
699 static void kvm_timer_vcpu_load_nogic(struct kvm_vcpu *vcpu)
700 {
701 	struct arch_timer_context *vtimer = vcpu_vtimer(vcpu);
702 
703 	/*
704 	 * Update the timer output so that it is likely to match the
705 	 * state we're about to restore. If the timer expires between
706 	 * this point and the register restoration, we'll take the
707 	 * interrupt anyway.
708 	 */
709 	kvm_timer_update_irq(vcpu, kvm_timer_should_fire(vtimer), vtimer);
710 
711 	/*
712 	 * When using a userspace irqchip with the architected timers and a
713 	 * host interrupt controller that doesn't support an active state, we
714 	 * must still prevent continuously exiting from the guest, and
715 	 * therefore mask the physical interrupt by disabling it on the host
716 	 * interrupt controller when the virtual level is high, such that the
717 	 * guest can make forward progress.  Once we detect the output level
718 	 * being de-asserted, we unmask the interrupt again so that we exit
719 	 * from the guest when the timer fires.
720 	 */
721 	if (vtimer->irq.level)
722 		disable_percpu_irq(host_vtimer_irq);
723 	else
724 		enable_percpu_irq(host_vtimer_irq, host_vtimer_irq_flags);
725 }
726 
727 /* If _pred is true, set bit in _set, otherwise set it in _clr */
728 #define assign_clear_set_bit(_pred, _bit, _clr, _set)			\
729 	do {								\
730 		if (_pred)						\
731 			(_set) |= (_bit);				\
732 		else							\
733 			(_clr) |= (_bit);				\
734 	} while (0)
735 
736 static void kvm_timer_vcpu_load_nested_switch(struct kvm_vcpu *vcpu,
737 					      struct timer_map *map)
738 {
739 	int hw, ret;
740 
741 	if (!irqchip_in_kernel(vcpu->kvm))
742 		return;
743 
744 	/*
745 	 * We only ever unmap the vtimer irq on a VHE system that runs nested
746 	 * virtualization, in which case we have both a valid emul_vtimer,
747 	 * emul_ptimer, direct_vtimer, and direct_ptimer.
748 	 *
749 	 * Since this is called from kvm_timer_vcpu_load(), a change between
750 	 * vEL2 and vEL1/0 will have just happened, and the timer_map will
751 	 * represent this, and therefore we switch the emul/direct mappings
752 	 * below.
753 	 */
754 	hw = kvm_vgic_get_map(vcpu, timer_irq(map->direct_vtimer));
755 	if (hw < 0) {
756 		kvm_vgic_unmap_phys_irq(vcpu, timer_irq(map->emul_vtimer));
757 		kvm_vgic_unmap_phys_irq(vcpu, timer_irq(map->emul_ptimer));
758 
759 		ret = kvm_vgic_map_phys_irq(vcpu,
760 					    map->direct_vtimer->host_timer_irq,
761 					    timer_irq(map->direct_vtimer));
762 		WARN_ON_ONCE(ret);
763 		ret = kvm_vgic_map_phys_irq(vcpu,
764 					    map->direct_ptimer->host_timer_irq,
765 					    timer_irq(map->direct_ptimer));
766 		WARN_ON_ONCE(ret);
767 	}
768 }
769 
770 static void timer_set_traps(struct kvm_vcpu *vcpu, struct timer_map *map)
771 {
772 	bool tvt, tpt, tvc, tpc, tvt02, tpt02;
773 	u64 clr, set;
774 
775 	/*
776 	 * No trapping gets configured here with nVHE. See
777 	 * __timer_enable_traps(), which is where the stuff happens.
778 	 */
779 	if (!has_vhe())
780 		return;
781 
782 	/*
783 	 * Our default policy is not to trap anything. As we progress
784 	 * within this function, reality kicks in and we start adding
785 	 * traps based on emulation requirements.
786 	 */
787 	tvt = tpt = tvc = tpc = false;
788 	tvt02 = tpt02 = false;
789 
790 	/*
791 	 * NV2 badly breaks the timer semantics by redirecting accesses to
792 	 * the EL1 timer state to memory, so let's call ECV to the rescue if
793 	 * available: we trap all CNT{P,V}_{CTL,CVAL,TVAL}_EL0 accesses.
794 	 *
795 	 * The treatment slightly varies depending whether we run a nVHE or
796 	 * VHE guest: nVHE will use the _EL0 registers directly, while VHE
797 	 * will use the _EL02 accessors. This translates in different trap
798 	 * bits.
799 	 *
800 	 * None of the trapping is required when running in non-HYP context,
801 	 * unless required by the L1 hypervisor settings once we advertise
802 	 * ECV+NV in the guest, or that we need trapping for other reasons.
803 	 */
804 	if (cpus_have_final_cap(ARM64_HAS_ECV) && is_hyp_ctxt(vcpu)) {
805 		if (vcpu_el2_e2h_is_set(vcpu))
806 			tvt02 = tpt02 = true;
807 		else
808 			tvt = tpt = true;
809 	}
810 
811 	/*
812 	 * We have two possibility to deal with a physical offset:
813 	 *
814 	 * - Either we have CNTPOFF (yay!) or the offset is 0:
815 	 *   we let the guest freely access the HW
816 	 *
817 	 * - or neither of these condition apply:
818 	 *   we trap accesses to the HW, but still use it
819 	 *   after correcting the physical offset
820 	 */
821 	if (!has_cntpoff() && timer_get_offset(map->direct_ptimer))
822 		tpt = tpc = true;
823 
824 	/*
825 	 * For the poor sods that could not correctly subtract one value
826 	 * from another, trap the full virtual timer and counter.
827 	 */
828 	if (has_broken_cntvoff() && timer_get_offset(map->direct_vtimer))
829 		tvt = tvc = true;
830 
831 	/*
832 	 * Apply the enable bits that the guest hypervisor has requested for
833 	 * its own guest. We can only add traps that wouldn't have been set
834 	 * above.
835 	 * Implementation choices: we do not support NV when E2H=0 in the
836 	 * guest, and we don't support configuration where E2H is writable
837 	 * by the guest (either FEAT_VHE or FEAT_E2H0 is implemented, but
838 	 * not both). This simplifies the handling of the EL1NV* bits.
839 	 */
840 	if (is_nested_ctxt(vcpu)) {
841 		u64 val = __vcpu_sys_reg(vcpu, CNTHCTL_EL2);
842 
843 		/* Use the VHE format for mental sanity */
844 		if (!vcpu_el2_e2h_is_set(vcpu))
845 			val = (val & (CNTHCTL_EL1PCEN | CNTHCTL_EL1PCTEN)) << 10;
846 
847 		tpt |= !(val & (CNTHCTL_EL1PCEN << 10));
848 		tpc |= !(val & (CNTHCTL_EL1PCTEN << 10));
849 
850 		tpt02 |= (val & CNTHCTL_EL1NVPCT);
851 		tvt02 |= (val & CNTHCTL_EL1NVVCT);
852 	}
853 
854 	/*
855 	 * Now that we have collected our requirements, compute the
856 	 * trap and enable bits.
857 	 */
858 	set = 0;
859 	clr = 0;
860 
861 	assign_clear_set_bit(tpt, CNTHCTL_EL1PCEN << 10, set, clr);
862 	assign_clear_set_bit(tpc, CNTHCTL_EL1PCTEN << 10, set, clr);
863 	assign_clear_set_bit(tvt, CNTHCTL_EL1TVT, clr, set);
864 	assign_clear_set_bit(tvc, CNTHCTL_EL1TVCT, clr, set);
865 	assign_clear_set_bit(tvt02, CNTHCTL_EL1NVVCT, clr, set);
866 	assign_clear_set_bit(tpt02, CNTHCTL_EL1NVPCT, clr, set);
867 
868 	/* This only happens on VHE, so use the CNTHCTL_EL2 accessor. */
869 	sysreg_clear_set(cnthctl_el2, clr, set);
870 }
871 
872 void kvm_timer_vcpu_load(struct kvm_vcpu *vcpu)
873 {
874 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
875 	struct timer_map map;
876 
877 	if (unlikely(!timer->enabled))
878 		return;
879 
880 	get_timer_map(vcpu, &map);
881 
882 	if (static_branch_likely(&has_gic_active_state)) {
883 		/* We don't do NV on GICv5, yet */
884 		if (vcpu_has_nv(vcpu) && !vgic_is_v5(vcpu->kvm))
885 			kvm_timer_vcpu_load_nested_switch(vcpu, &map);
886 
887 		kvm_timer_vcpu_load_gic(map.direct_vtimer);
888 		if (map.direct_ptimer)
889 			kvm_timer_vcpu_load_gic(map.direct_ptimer);
890 	} else {
891 		kvm_timer_vcpu_load_nogic(vcpu);
892 	}
893 
894 	kvm_timer_unblocking(vcpu);
895 
896 	timer_restore_state(map.direct_vtimer);
897 	if (map.direct_ptimer)
898 		timer_restore_state(map.direct_ptimer);
899 	if (map.emul_vtimer)
900 		timer_emulate(map.emul_vtimer);
901 	if (map.emul_ptimer)
902 		timer_emulate(map.emul_ptimer);
903 
904 	timer_set_traps(vcpu, &map);
905 }
906 
907 bool kvm_timer_should_notify_user(struct kvm_vcpu *vcpu)
908 {
909 	struct arch_timer_context *vtimer = vcpu_vtimer(vcpu);
910 	struct arch_timer_context *ptimer = vcpu_ptimer(vcpu);
911 	struct kvm_sync_regs *sregs = &vcpu->run->s.regs;
912 	bool vlevel, plevel;
913 
914 	if (likely(irqchip_in_kernel(vcpu->kvm)))
915 		return false;
916 
917 	vlevel = sregs->device_irq_level & KVM_ARM_DEV_EL1_VTIMER;
918 	plevel = sregs->device_irq_level & KVM_ARM_DEV_EL1_PTIMER;
919 
920 	return kvm_timer_should_fire(vtimer) != vlevel ||
921 	       kvm_timer_should_fire(ptimer) != plevel;
922 }
923 
924 void kvm_timer_vcpu_put(struct kvm_vcpu *vcpu)
925 {
926 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
927 	struct timer_map map;
928 
929 	if (unlikely(!timer->enabled))
930 		return;
931 
932 	get_timer_map(vcpu, &map);
933 
934 	timer_save_state(map.direct_vtimer);
935 	if (map.direct_ptimer)
936 		timer_save_state(map.direct_ptimer);
937 
938 	/*
939 	 * Cancel soft timer emulation, because the only case where we
940 	 * need it after a vcpu_put is in the context of a sleeping VCPU, and
941 	 * in that case we already factor in the deadline for the physical
942 	 * timer when scheduling the bg_timer.
943 	 *
944 	 * In any case, we re-schedule the hrtimer for the physical timer when
945 	 * coming back to the VCPU thread in kvm_timer_vcpu_load().
946 	 */
947 	if (map.emul_vtimer)
948 		soft_timer_cancel(&map.emul_vtimer->hrtimer);
949 	if (map.emul_ptimer)
950 		soft_timer_cancel(&map.emul_ptimer->hrtimer);
951 
952 	if (kvm_vcpu_is_blocking(vcpu))
953 		kvm_timer_blocking(vcpu);
954 
955 	if (vgic_is_v5(vcpu->kvm)) {
956 		set_timer_irq_phys_active(map.direct_vtimer, false);
957 		if (map.direct_ptimer)
958 			set_timer_irq_phys_active(map.direct_ptimer, false);
959 	}
960 }
961 
962 void kvm_timer_sync_nested(struct kvm_vcpu *vcpu)
963 {
964 	/*
965 	 * When NV2 is on, guest hypervisors have their EL1 timer register
966 	 * accesses redirected to the VNCR page. Any guest action taken on
967 	 * the timer is postponed until the next exit, leading to a very
968 	 * poor quality of emulation.
969 	 *
970 	 * This is an unmitigated disaster, only papered over by FEAT_ECV,
971 	 * which allows trapping of the timer registers even with NV2.
972 	 * Still, this is still worse than FEAT_NV on its own. Meh.
973 	 */
974 	if (!cpus_have_final_cap(ARM64_HAS_ECV)) {
975 		/*
976 		 * For a VHE guest hypervisor, the EL2 state is directly
977 		 * stored in the host EL1 timers, while the emulated EL1
978 		 * state is stored in the VNCR page. The latter could have
979 		 * been updated behind our back, and we must reset the
980 		 * emulation of the timers.
981 		 *
982 		 * A non-VHE guest hypervisor doesn't have any direct access
983 		 * to its timers: the EL2 registers trap despite being
984 		 * notionally direct (we use the EL1 HW, as for VHE), while
985 		 * the EL1 registers access memory.
986 		 *
987 		 * In both cases, process the emulated timers on each guest
988 		 * exit. Boo.
989 		 */
990 		struct timer_map map;
991 		get_timer_map(vcpu, &map);
992 
993 		soft_timer_cancel(&map.emul_vtimer->hrtimer);
994 		soft_timer_cancel(&map.emul_ptimer->hrtimer);
995 		timer_emulate(map.emul_vtimer);
996 		timer_emulate(map.emul_ptimer);
997 	}
998 }
999 
1000 /*
1001  * With a userspace irqchip we have to check if the guest de-asserted the
1002  * timer and if so, unmask the timer irq signal on the host interrupt
1003  * controller to ensure that we see future timer signals.
1004  */
1005 static void unmask_vtimer_irq_user(struct kvm_vcpu *vcpu)
1006 {
1007 	struct arch_timer_context *vtimer = vcpu_vtimer(vcpu);
1008 
1009 	if (!kvm_timer_should_fire(vtimer)) {
1010 		kvm_timer_update_irq(vcpu, false, vtimer);
1011 		if (static_branch_likely(&has_gic_active_state))
1012 			set_timer_irq_phys_active(vtimer, false);
1013 		else
1014 			enable_percpu_irq(host_vtimer_irq, host_vtimer_irq_flags);
1015 	}
1016 }
1017 
1018 void kvm_timer_sync_user(struct kvm_vcpu *vcpu)
1019 {
1020 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
1021 
1022 	if (unlikely(!timer->enabled))
1023 		return;
1024 
1025 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1026 		unmask_vtimer_irq_user(vcpu);
1027 }
1028 
1029 void kvm_timer_vcpu_reset(struct kvm_vcpu *vcpu)
1030 {
1031 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
1032 	struct timer_map map;
1033 
1034 	get_timer_map(vcpu, &map);
1035 
1036 	/*
1037 	 * The bits in CNTV_CTL are architecturally reset to UNKNOWN for ARMv8
1038 	 * and to 0 for ARMv7.  We provide an implementation that always
1039 	 * resets the timer to be disabled and unmasked and is compliant with
1040 	 * the ARMv7 architecture.
1041 	 */
1042 	for (int i = 0; i < nr_timers(vcpu); i++)
1043 		timer_set_ctl(vcpu_get_timer(vcpu, i), 0);
1044 
1045 	/*
1046 	 * A vcpu running at EL2 is in charge of the offset applied to
1047 	 * the virtual timer, so use the physical VM offset, and point
1048 	 * the vcpu offset to CNTVOFF_EL2.
1049 	 */
1050 	if (vcpu_has_nv(vcpu)) {
1051 		struct arch_timer_offset *offs = &vcpu_vtimer(vcpu)->offset;
1052 
1053 		offs->vcpu_offset = __ctxt_sys_reg(&vcpu->arch.ctxt, CNTVOFF_EL2);
1054 		offs->vm_offset = &vcpu->kvm->arch.timer_data.poffset;
1055 	}
1056 
1057 	if (timer->enabled) {
1058 		for (int i = 0; i < nr_timers(vcpu); i++)
1059 			kvm_timer_update_irq(vcpu, false,
1060 					     vcpu_get_timer(vcpu, i));
1061 
1062 		if (irqchip_in_kernel(vcpu->kvm)) {
1063 			kvm_vgic_reset_mapped_irq(vcpu, timer_irq(map.direct_vtimer));
1064 			if (map.direct_ptimer)
1065 				kvm_vgic_reset_mapped_irq(vcpu, timer_irq(map.direct_ptimer));
1066 		}
1067 	}
1068 
1069 	if (map.emul_vtimer)
1070 		soft_timer_cancel(&map.emul_vtimer->hrtimer);
1071 	if (map.emul_ptimer)
1072 		soft_timer_cancel(&map.emul_ptimer->hrtimer);
1073 }
1074 
1075 static void timer_context_init(struct kvm_vcpu *vcpu, int timerid)
1076 {
1077 	struct arch_timer_context *ctxt = vcpu_get_timer(vcpu, timerid);
1078 	struct kvm *kvm = vcpu->kvm;
1079 
1080 	ctxt->timer_id = timerid;
1081 
1082 	if (!kvm_vm_is_protected(vcpu->kvm)) {
1083 		if (timerid == TIMER_VTIMER)
1084 			ctxt->offset.vm_offset = &kvm->arch.timer_data.voffset;
1085 		else
1086 			ctxt->offset.vm_offset = &kvm->arch.timer_data.poffset;
1087 	} else {
1088 		ctxt->offset.vm_offset = NULL;
1089 	}
1090 
1091 	hrtimer_setup(&ctxt->hrtimer, kvm_hrtimer_expire, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1092 
1093 	switch (timerid) {
1094 	case TIMER_PTIMER:
1095 	case TIMER_HPTIMER:
1096 		ctxt->host_timer_irq = host_ptimer_irq;
1097 		break;
1098 	case TIMER_VTIMER:
1099 	case TIMER_HVTIMER:
1100 		ctxt->host_timer_irq = host_vtimer_irq;
1101 		break;
1102 	}
1103 }
1104 
1105 void kvm_timer_vcpu_init(struct kvm_vcpu *vcpu)
1106 {
1107 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
1108 
1109 	for (int i = 0; i < NR_KVM_TIMERS; i++)
1110 		timer_context_init(vcpu, i);
1111 
1112 	/* Synchronize offsets across timers of a VM if not already provided */
1113 	if (!vcpu_is_protected(vcpu) &&
1114 	    !test_bit(KVM_ARCH_FLAG_VM_COUNTER_OFFSET, &vcpu->kvm->arch.flags)) {
1115 		timer_set_offset(vcpu_vtimer(vcpu), kvm_phys_timer_read());
1116 		timer_set_offset(vcpu_ptimer(vcpu), 0);
1117 	}
1118 
1119 	hrtimer_setup(&timer->bg_timer, kvm_bg_timer_expire, CLOCK_MONOTONIC,
1120 		      HRTIMER_MODE_ABS_HARD);
1121 }
1122 
1123 /*
1124  * This is always called during kvm_arch_init_vm, but will also be
1125  * called from kvm_vgic_create if we have a vGICv5.
1126  */
1127 void kvm_timer_init_vm(struct kvm *kvm)
1128 {
1129 	/*
1130 	 * Set up the default PPIs - note that we adjust them based on
1131 	 * the model of the GIC as GICv5 uses a different way to
1132 	 * describing interrupts.
1133 	 */
1134 	for (int i = 0; i < NR_KVM_TIMERS; i++)
1135 		kvm->arch.timer_data.ppi[i] = get_vgic_ppi(kvm, default_ppi[i]);
1136 }
1137 
1138 void kvm_timer_cpu_up(void)
1139 {
1140 	enable_percpu_irq(host_vtimer_irq, host_vtimer_irq_flags);
1141 	if (host_ptimer_irq)
1142 		enable_percpu_irq(host_ptimer_irq, host_ptimer_irq_flags);
1143 }
1144 
1145 void kvm_timer_cpu_down(void)
1146 {
1147 	disable_percpu_irq(host_vtimer_irq);
1148 	if (host_ptimer_irq)
1149 		disable_percpu_irq(host_ptimer_irq);
1150 }
1151 
1152 static u64 read_timer_ctl(struct arch_timer_context *timer)
1153 {
1154 	/*
1155 	 * Set ISTATUS bit if it's expired.
1156 	 * Note that according to ARMv8 ARM Issue A.k, ISTATUS bit is
1157 	 * UNKNOWN when ENABLE bit is 0, so we chose to set ISTATUS bit
1158 	 * regardless of ENABLE bit for our implementation convenience.
1159 	 */
1160 	u32 ctl = timer_get_ctl(timer);
1161 
1162 	if (!kvm_timer_compute_delta(timer))
1163 		ctl |= ARCH_TIMER_CTRL_IT_STAT;
1164 
1165 	return ctl;
1166 }
1167 
1168 static u64 kvm_arm_timer_read(struct kvm_vcpu *vcpu,
1169 			      struct arch_timer_context *timer,
1170 			      enum kvm_arch_timer_regs treg)
1171 {
1172 	u64 val;
1173 
1174 	switch (treg) {
1175 	case TIMER_REG_TVAL:
1176 		val = timer_get_cval(timer) - kvm_phys_timer_read() + timer_get_offset(timer);
1177 		val = lower_32_bits(val);
1178 		break;
1179 
1180 	case TIMER_REG_CTL:
1181 		val = read_timer_ctl(timer);
1182 		break;
1183 
1184 	case TIMER_REG_CVAL:
1185 		val = timer_get_cval(timer);
1186 		break;
1187 
1188 	case TIMER_REG_CNT:
1189 		val = kvm_phys_timer_read() - timer_get_offset(timer);
1190 		break;
1191 
1192 	case TIMER_REG_VOFF:
1193 		val = *timer->offset.vcpu_offset;
1194 		break;
1195 
1196 	default:
1197 		BUG();
1198 	}
1199 
1200 	return val;
1201 }
1202 
1203 u64 kvm_arm_timer_read_sysreg(struct kvm_vcpu *vcpu,
1204 			      enum kvm_arch_timers tmr,
1205 			      enum kvm_arch_timer_regs treg)
1206 {
1207 	struct arch_timer_context *timer;
1208 	struct timer_map map;
1209 	u64 val;
1210 
1211 	get_timer_map(vcpu, &map);
1212 	timer = vcpu_get_timer(vcpu, tmr);
1213 
1214 	if (timer == map.emul_vtimer || timer == map.emul_ptimer)
1215 		return kvm_arm_timer_read(vcpu, timer, treg);
1216 
1217 	preempt_disable();
1218 	timer_save_state(timer);
1219 
1220 	val = kvm_arm_timer_read(vcpu, timer, treg);
1221 
1222 	timer_restore_state(timer);
1223 	preempt_enable();
1224 
1225 	return val;
1226 }
1227 
1228 static void kvm_arm_timer_write(struct kvm_vcpu *vcpu,
1229 				struct arch_timer_context *timer,
1230 				enum kvm_arch_timer_regs treg,
1231 				u64 val)
1232 {
1233 	switch (treg) {
1234 	case TIMER_REG_TVAL:
1235 		timer_set_cval(timer, kvm_phys_timer_read() - timer_get_offset(timer) + (s32)val);
1236 		break;
1237 
1238 	case TIMER_REG_CTL:
1239 		timer_set_ctl(timer, val & ~ARCH_TIMER_CTRL_IT_STAT);
1240 		break;
1241 
1242 	case TIMER_REG_CVAL:
1243 		timer_set_cval(timer, val);
1244 		break;
1245 
1246 	case TIMER_REG_VOFF:
1247 		*timer->offset.vcpu_offset = val;
1248 		break;
1249 
1250 	default:
1251 		BUG();
1252 	}
1253 }
1254 
1255 void kvm_arm_timer_write_sysreg(struct kvm_vcpu *vcpu,
1256 				enum kvm_arch_timers tmr,
1257 				enum kvm_arch_timer_regs treg,
1258 				u64 val)
1259 {
1260 	struct arch_timer_context *timer;
1261 	struct timer_map map;
1262 
1263 	get_timer_map(vcpu, &map);
1264 	timer = vcpu_get_timer(vcpu, tmr);
1265 	if (timer == map.emul_vtimer || timer == map.emul_ptimer) {
1266 		soft_timer_cancel(&timer->hrtimer);
1267 		kvm_arm_timer_write(vcpu, timer, treg, val);
1268 		timer_emulate(timer);
1269 	} else {
1270 		preempt_disable();
1271 		timer_save_state(timer);
1272 		kvm_arm_timer_write(vcpu, timer, treg, val);
1273 		timer_restore_state(timer);
1274 		preempt_enable();
1275 	}
1276 }
1277 
1278 static int timer_irq_set_vcpu_affinity(struct irq_data *d, void *vcpu)
1279 {
1280 	if (vcpu)
1281 		irqd_set_forwarded_to_vcpu(d);
1282 	else
1283 		irqd_clr_forwarded_to_vcpu(d);
1284 
1285 	return 0;
1286 }
1287 
1288 static int timer_irq_set_irqchip_state(struct irq_data *d,
1289 				       enum irqchip_irq_state which, bool val)
1290 {
1291 	if (which != IRQCHIP_STATE_ACTIVE || !irqd_is_forwarded_to_vcpu(d))
1292 		return irq_chip_set_parent_state(d, which, val);
1293 
1294 	if (val)
1295 		irq_chip_mask_parent(d);
1296 	else
1297 		irq_chip_unmask_parent(d);
1298 
1299 	return 0;
1300 }
1301 
1302 static void timer_irq_eoi(struct irq_data *d)
1303 {
1304 	/*
1305 	 * On a GICv5 host, we still need to call EOI on the parent for
1306 	 * PPIs. The host driver already handles irqs which are forwarded to
1307 	 * vcpus, and skips the GIC CDDI while still doing the GIC CDEOI. This
1308 	 * is required to emulate the EOIMode=1 on GICv5 hardware. Failure to
1309 	 * call EOI unsurprisingly results in *BAD* lock-ups.
1310 	 */
1311 	if (!irqd_is_forwarded_to_vcpu(d) ||
1312 	    kvm_vgic_global_state.type == VGIC_V5)
1313 		irq_chip_eoi_parent(d);
1314 }
1315 
1316 static void timer_irq_ack(struct irq_data *d)
1317 {
1318 	d = d->parent_data;
1319 	if (d->chip->irq_ack)
1320 		d->chip->irq_ack(d);
1321 }
1322 
1323 static struct irq_chip timer_chip = {
1324 	.name			= "KVM",
1325 	.irq_ack		= timer_irq_ack,
1326 	.irq_mask		= irq_chip_mask_parent,
1327 	.irq_unmask		= irq_chip_unmask_parent,
1328 	.irq_eoi		= timer_irq_eoi,
1329 	.irq_set_type		= irq_chip_set_type_parent,
1330 	.irq_set_vcpu_affinity	= timer_irq_set_vcpu_affinity,
1331 	.irq_set_irqchip_state	= timer_irq_set_irqchip_state,
1332 };
1333 
1334 static int timer_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
1335 				  unsigned int nr_irqs, void *arg)
1336 {
1337 	irq_hw_number_t hwirq = (uintptr_t)arg;
1338 
1339 	return irq_domain_set_hwirq_and_chip(domain, virq, hwirq,
1340 					     &timer_chip, NULL);
1341 }
1342 
1343 static void timer_irq_domain_free(struct irq_domain *domain, unsigned int virq,
1344 				  unsigned int nr_irqs)
1345 {
1346 }
1347 
1348 static const struct irq_domain_ops timer_domain_ops = {
1349 	.alloc	= timer_irq_domain_alloc,
1350 	.free	= timer_irq_domain_free,
1351 };
1352 
1353 static void kvm_irq_fixup_flags(unsigned int virq, u32 *flags)
1354 {
1355 	*flags = irq_get_trigger_type(virq);
1356 	if (*flags != IRQF_TRIGGER_HIGH && *flags != IRQF_TRIGGER_LOW) {
1357 		kvm_err("Invalid trigger for timer IRQ%d, assuming level low\n",
1358 			virq);
1359 		*flags = IRQF_TRIGGER_LOW;
1360 	}
1361 }
1362 
1363 static int kvm_irq_init(struct arch_timer_kvm_info *info)
1364 {
1365 	struct irq_domain *domain = NULL;
1366 
1367 	if (info->virtual_irq <= 0) {
1368 		kvm_err("kvm_arch_timer: invalid virtual timer IRQ: %d\n",
1369 			info->virtual_irq);
1370 		return -ENODEV;
1371 	}
1372 
1373 	host_vtimer_irq = info->virtual_irq;
1374 	kvm_irq_fixup_flags(host_vtimer_irq, &host_vtimer_irq_flags);
1375 
1376 	if (kvm_vgic_global_state.no_hw_deactivation ||
1377 	    kvm_vgic_global_state.type == VGIC_V5) {
1378 		struct fwnode_handle *fwnode;
1379 		struct irq_data *data;
1380 
1381 		fwnode = irq_domain_alloc_named_fwnode("kvm-timer");
1382 		if (!fwnode)
1383 			return -ENOMEM;
1384 
1385 		/* Assume both vtimer and ptimer in the same parent */
1386 		data = irq_get_irq_data(host_vtimer_irq);
1387 		domain = irq_domain_create_hierarchy(data->domain, 0,
1388 						     NR_KVM_TIMERS, fwnode,
1389 						     &timer_domain_ops, NULL);
1390 		if (!domain) {
1391 			irq_domain_free_fwnode(fwnode);
1392 			return -ENOMEM;
1393 		}
1394 
1395 		if (kvm_vgic_global_state.no_hw_deactivation)
1396 			arch_timer_irq_ops.flags |= VGIC_IRQ_SW_RESAMPLE;
1397 		WARN_ON(irq_domain_push_irq(domain, host_vtimer_irq,
1398 					    (void *)TIMER_VTIMER));
1399 	}
1400 
1401 	if (info->physical_irq > 0) {
1402 		host_ptimer_irq = info->physical_irq;
1403 		kvm_irq_fixup_flags(host_ptimer_irq, &host_ptimer_irq_flags);
1404 
1405 		if (domain)
1406 			WARN_ON(irq_domain_push_irq(domain, host_ptimer_irq,
1407 						    (void *)TIMER_PTIMER));
1408 	}
1409 
1410 	return 0;
1411 }
1412 
1413 static void kvm_timer_handle_errata(void)
1414 {
1415 	u64 mmfr0, mmfr1, mmfr4;
1416 
1417 	/*
1418 	 * CNTVOFF_EL2 is broken on some implementations. For those, we trap
1419 	 * all virtual timer/counter accesses, requiring FEAT_ECV.
1420 	 *
1421 	 * However, a hypervisor supporting nesting is likely to mitigate the
1422 	 * erratum at L0, and not require other levels to mitigate it (which
1423 	 * would otherwise be a terrible performance sink due to trap
1424 	 * amplification).
1425 	 *
1426 	 * Given that the affected HW implements both FEAT_VHE and FEAT_E2H0,
1427 	 * and that NV is likely not to (because of limitations of the
1428 	 * architecture), only enable the workaround when FEAT_VHE and
1429 	 * FEAT_E2H0 are both detected. Time will tell if this actually holds.
1430 	 */
1431 	mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
1432 	mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
1433 	mmfr4 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR4_EL1);
1434 	if (SYS_FIELD_GET(ID_AA64MMFR1_EL1, VH, mmfr1)		&&
1435 	    !SYS_FIELD_GET(ID_AA64MMFR4_EL1, E2H0, mmfr4)	&&
1436 	    SYS_FIELD_GET(ID_AA64MMFR0_EL1, ECV, mmfr0)		&&
1437 	    (has_vhe() || has_hvhe())				&&
1438 	    cpus_have_final_cap(ARM64_WORKAROUND_QCOM_ORYON_CNTVOFF)) {
1439 		static_branch_enable(&broken_cntvoff_key);
1440 		kvm_info("Broken CNTVOFF_EL2, trapping virtual timer\n");
1441 	}
1442 }
1443 
1444 int __init kvm_timer_hyp_init(bool has_gic)
1445 {
1446 	struct arch_timer_kvm_info *info;
1447 	int err;
1448 
1449 	info = arch_timer_get_kvm_info();
1450 	timecounter = &info->timecounter;
1451 
1452 	if (!timecounter->cc) {
1453 		kvm_err("kvm_arch_timer: uninitialized timecounter\n");
1454 		return -ENODEV;
1455 	}
1456 
1457 	err = kvm_irq_init(info);
1458 	if (err)
1459 		return err;
1460 
1461 	/* First, do the virtual EL1 timer irq */
1462 
1463 	err = request_percpu_irq(host_vtimer_irq, kvm_arch_timer_handler,
1464 				 "kvm guest vtimer", kvm_get_running_vcpus());
1465 	if (err) {
1466 		kvm_err("kvm_arch_timer: can't request vtimer interrupt %d (%d)\n",
1467 			host_vtimer_irq, err);
1468 		return err;
1469 	}
1470 
1471 	if (has_gic) {
1472 		err = irq_set_vcpu_affinity(host_vtimer_irq,
1473 					    kvm_get_running_vcpus());
1474 		if (err) {
1475 			kvm_err("kvm_arch_timer: error setting vcpu affinity\n");
1476 			goto out_free_vtimer_irq;
1477 		}
1478 
1479 		static_branch_enable(&has_gic_active_state);
1480 	}
1481 
1482 	kvm_debug("virtual timer IRQ%d\n", host_vtimer_irq);
1483 
1484 	/* Now let's do the physical EL1 timer irq */
1485 
1486 	if (info->physical_irq > 0) {
1487 		err = request_percpu_irq(host_ptimer_irq, kvm_arch_timer_handler,
1488 					 "kvm guest ptimer", kvm_get_running_vcpus());
1489 		if (err) {
1490 			kvm_err("kvm_arch_timer: can't request ptimer interrupt %d (%d)\n",
1491 				host_ptimer_irq, err);
1492 			goto out_free_vtimer_irq;
1493 		}
1494 
1495 		if (has_gic) {
1496 			err = irq_set_vcpu_affinity(host_ptimer_irq,
1497 						    kvm_get_running_vcpus());
1498 			if (err) {
1499 				kvm_err("kvm_arch_timer: error setting vcpu affinity\n");
1500 				goto out_free_ptimer_irq;
1501 			}
1502 		}
1503 
1504 		kvm_debug("physical timer IRQ%d\n", host_ptimer_irq);
1505 	} else if (has_vhe()) {
1506 		kvm_err("kvm_arch_timer: invalid physical timer IRQ: %d\n",
1507 			info->physical_irq);
1508 		err = -ENODEV;
1509 		goto out_free_vtimer_irq;
1510 	}
1511 
1512 	kvm_timer_handle_errata();
1513 	return 0;
1514 
1515 out_free_ptimer_irq:
1516 	if (info->physical_irq > 0)
1517 		free_percpu_irq(host_ptimer_irq, kvm_get_running_vcpus());
1518 out_free_vtimer_irq:
1519 	free_percpu_irq(host_vtimer_irq, kvm_get_running_vcpus());
1520 	return err;
1521 }
1522 
1523 void kvm_timer_vcpu_terminate(struct kvm_vcpu *vcpu)
1524 {
1525 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
1526 
1527 	soft_timer_cancel(&timer->bg_timer);
1528 }
1529 
1530 static bool timer_irqs_are_valid(struct kvm_vcpu *vcpu)
1531 {
1532 	u32 ppis = 0;
1533 	bool valid;
1534 
1535 	mutex_lock(&vcpu->kvm->arch.config_lock);
1536 
1537 	for (int i = 0; i < nr_timers(vcpu); i++) {
1538 		struct arch_timer_context *ctx;
1539 		int irq;
1540 
1541 		ctx = vcpu_get_timer(vcpu, i);
1542 		irq = timer_irq(ctx);
1543 		if (kvm_vgic_set_owner(vcpu, irq, ctx))
1544 			break;
1545 
1546 		/* With GICv5, the default PPI is what you get -- nothing else */
1547 		if (vgic_is_v5(vcpu->kvm) && irq != get_vgic_ppi(vcpu->kvm, default_ppi[i]))
1548 			break;
1549 
1550 		/*
1551 		 * We know by construction that we only have PPIs, so all values
1552 		 * are less than 32 for non-GICv5 VGICs. On GICv5, they are
1553 		 * architecturally defined to be under 32 too. However, we mask
1554 		 * off most of the bits as we might be presented with a GICv5
1555 		 * style PPI where the type is encoded in the top-bits.
1556 		 */
1557 		ppis |= BIT(irq & 0x1f);
1558 	}
1559 
1560 	valid = hweight32(ppis) == nr_timers(vcpu);
1561 
1562 	if (valid)
1563 		set_bit(KVM_ARCH_FLAG_TIMER_PPIS_IMMUTABLE, &vcpu->kvm->arch.flags);
1564 
1565 	mutex_unlock(&vcpu->kvm->arch.config_lock);
1566 
1567 	return valid;
1568 }
1569 
1570 static bool kvm_arch_timer_get_input_level(int vintid)
1571 {
1572 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
1573 
1574 	if (WARN(!vcpu, "No vcpu context!\n"))
1575 		return false;
1576 
1577 	for (int i = 0; i < nr_timers(vcpu); i++) {
1578 		struct arch_timer_context *ctx;
1579 
1580 		ctx = vcpu_get_timer(vcpu, i);
1581 		if (timer_irq(ctx) == vintid)
1582 			return kvm_timer_should_fire(ctx);
1583 	}
1584 
1585 	/* A timer IRQ has fired, but no matching timer was found? */
1586 	WARN_RATELIMIT(1, "timer INTID%d unknown\n", vintid);
1587 
1588 	return false;
1589 }
1590 
1591 int kvm_timer_enable(struct kvm_vcpu *vcpu)
1592 {
1593 	struct arch_timer_cpu *timer = vcpu_timer(vcpu);
1594 	struct timer_map map;
1595 	struct irq_ops *ops;
1596 	int ret;
1597 
1598 	if (timer->enabled)
1599 		return 0;
1600 
1601 	/* Without a VGIC we do not map virtual IRQs to physical IRQs */
1602 	if (!irqchip_in_kernel(vcpu->kvm))
1603 		goto no_vgic;
1604 
1605 	/*
1606 	 * At this stage, we have the guarantee that the vgic is both
1607 	 * available and initialized.
1608 	 */
1609 	if (!timer_irqs_are_valid(vcpu)) {
1610 		kvm_debug("incorrectly configured timer irqs\n");
1611 		return -EINVAL;
1612 	}
1613 
1614 	get_timer_map(vcpu, &map);
1615 
1616 	ops = vgic_is_v5(vcpu->kvm) ? &arch_timer_irq_ops_vgic_v5 :
1617 				      &arch_timer_irq_ops;
1618 
1619 	for (int i = 0; i < nr_timers(vcpu); i++)
1620 		kvm_vgic_set_irq_ops(vcpu, timer_irq(vcpu_get_timer(vcpu, i)), ops);
1621 
1622 	ret = kvm_vgic_map_phys_irq(vcpu,
1623 				    map.direct_vtimer->host_timer_irq,
1624 				    timer_irq(map.direct_vtimer));
1625 	if (ret)
1626 		return ret;
1627 
1628 	if (map.direct_ptimer)
1629 		ret = kvm_vgic_map_phys_irq(vcpu,
1630 					    map.direct_ptimer->host_timer_irq,
1631 					    timer_irq(map.direct_ptimer));
1632 	if (ret)
1633 		return ret;
1634 
1635 no_vgic:
1636 	timer->enabled = 1;
1637 	return 0;
1638 }
1639 
1640 /* If we have CNTPOFF, permanently set ECV to enable it */
1641 void kvm_timer_init_vhe(void)
1642 {
1643 	if (cpus_have_final_cap(ARM64_HAS_ECV_CNTPOFF))
1644 		sysreg_clear_set(cnthctl_el2, 0, CNTHCTL_ECV);
1645 }
1646 
1647 int kvm_arm_timer_set_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1648 {
1649 	int __user *uaddr = (int __user *)(long)attr->addr;
1650 	int irq, idx, ret = 0;
1651 
1652 	if (!irqchip_in_kernel(vcpu->kvm))
1653 		return -EINVAL;
1654 
1655 	if (get_user(irq, uaddr))
1656 		return -EFAULT;
1657 
1658 	if (!(irq_is_ppi(vcpu->kvm, irq)))
1659 		return -EINVAL;
1660 
1661 	guard(mutex)(&vcpu->kvm->arch.config_lock);
1662 
1663 	if (test_bit(KVM_ARCH_FLAG_TIMER_PPIS_IMMUTABLE,
1664 		     &vcpu->kvm->arch.flags)) {
1665 		return -EBUSY;
1666 	}
1667 
1668 	switch (attr->attr) {
1669 	case KVM_ARM_VCPU_TIMER_IRQ_VTIMER:
1670 		idx = TIMER_VTIMER;
1671 		break;
1672 	case KVM_ARM_VCPU_TIMER_IRQ_PTIMER:
1673 		idx = TIMER_PTIMER;
1674 		break;
1675 	case KVM_ARM_VCPU_TIMER_IRQ_HVTIMER:
1676 		idx = TIMER_HVTIMER;
1677 		break;
1678 	case KVM_ARM_VCPU_TIMER_IRQ_HPTIMER:
1679 		idx = TIMER_HPTIMER;
1680 		break;
1681 	default:
1682 		return -ENXIO;
1683 	}
1684 
1685 	/*
1686 	 * We cannot validate the IRQ unicity before we run, so take it at
1687 	 * face value. The verdict will be given on first vcpu run, for each
1688 	 * vcpu. Yes this is late. Blame it on the stupid API.
1689 	 */
1690 	vcpu->kvm->arch.timer_data.ppi[idx] = irq;
1691 
1692 	return ret;
1693 }
1694 
1695 int kvm_arm_timer_get_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1696 {
1697 	int __user *uaddr = (int __user *)(long)attr->addr;
1698 	struct arch_timer_context *timer;
1699 	int irq;
1700 
1701 	switch (attr->attr) {
1702 	case KVM_ARM_VCPU_TIMER_IRQ_VTIMER:
1703 		timer = vcpu_vtimer(vcpu);
1704 		break;
1705 	case KVM_ARM_VCPU_TIMER_IRQ_PTIMER:
1706 		timer = vcpu_ptimer(vcpu);
1707 		break;
1708 	case KVM_ARM_VCPU_TIMER_IRQ_HVTIMER:
1709 		timer = vcpu_hvtimer(vcpu);
1710 		break;
1711 	case KVM_ARM_VCPU_TIMER_IRQ_HPTIMER:
1712 		timer = vcpu_hptimer(vcpu);
1713 		break;
1714 	default:
1715 		return -ENXIO;
1716 	}
1717 
1718 	irq = timer_irq(timer);
1719 	return put_user(irq, uaddr);
1720 }
1721 
1722 int kvm_arm_timer_has_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1723 {
1724 	switch (attr->attr) {
1725 	case KVM_ARM_VCPU_TIMER_IRQ_VTIMER:
1726 	case KVM_ARM_VCPU_TIMER_IRQ_PTIMER:
1727 	case KVM_ARM_VCPU_TIMER_IRQ_HVTIMER:
1728 	case KVM_ARM_VCPU_TIMER_IRQ_HPTIMER:
1729 		return 0;
1730 	}
1731 
1732 	return -ENXIO;
1733 }
1734 
1735 int kvm_vm_ioctl_set_counter_offset(struct kvm *kvm,
1736 				    struct kvm_arm_counter_offset *offset)
1737 {
1738 	int ret = 0;
1739 
1740 	if (offset->reserved)
1741 		return -EINVAL;
1742 
1743 	if (kvm_vm_is_protected(kvm))
1744 		return -EINVAL;
1745 
1746 	mutex_lock(&kvm->lock);
1747 
1748 	if (!kvm_trylock_all_vcpus(kvm)) {
1749 		set_bit(KVM_ARCH_FLAG_VM_COUNTER_OFFSET, &kvm->arch.flags);
1750 
1751 		/*
1752 		 * If userspace decides to set the offset using this
1753 		 * API rather than merely restoring the counter
1754 		 * values, the offset applies to both the virtual and
1755 		 * physical views.
1756 		 */
1757 		kvm->arch.timer_data.voffset = offset->counter_offset;
1758 		kvm->arch.timer_data.poffset = offset->counter_offset;
1759 
1760 		kvm_unlock_all_vcpus(kvm);
1761 	} else {
1762 		ret = -EBUSY;
1763 	}
1764 
1765 	mutex_unlock(&kvm->lock);
1766 
1767 	return ret;
1768 }
1769