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