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