Linux Audio

Check our new training course

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