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