xref: /linux/arch/x86/kvm/xen.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright © 2019 Oracle and/or its affiliates. All rights reserved.
4  * Copyright © 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5  *
6  * KVM Xen emulation
7  */
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include "x86.h"
11 #include "xen.h"
12 #include "hyperv.h"
13 #include "irq.h"
14 
15 #include <linux/eventfd.h>
16 #include <linux/kvm_host.h>
17 #include <linux/sched/stat.h>
18 
19 #include <trace/events/kvm.h>
20 #include <xen/interface/xen.h>
21 #include <xen/interface/vcpu.h>
22 #include <xen/interface/version.h>
23 #include <xen/interface/event_channel.h>
24 #include <xen/interface/sched.h>
25 #include <xen/xen-ops.h>
26 
27 #include <asm/xen/cpuid.h>
28 #include <asm/pvclock.h>
29 
30 #include "cpuid.h"
31 #include "trace.h"
32 
33 static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm);
34 static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data);
35 static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);
36 
37 DEFINE_STATIC_KEY_DEFERRED_FALSE(kvm_xen_enabled, HZ);
38 
39 static int kvm_xen_shared_info_init(struct kvm *kvm)
40 {
41 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
42 	struct pvclock_wall_clock *wc;
43 	u32 *wc_sec_hi;
44 	u32 wc_version;
45 	u64 wall_nsec;
46 	int ret = 0;
47 	int idx = srcu_read_lock(&kvm->srcu);
48 
49 	read_lock_irq(&gpc->lock);
50 	while (!kvm_gpc_check(gpc, PAGE_SIZE)) {
51 		read_unlock_irq(&gpc->lock);
52 
53 		ret = kvm_gpc_refresh(gpc, PAGE_SIZE);
54 		if (ret)
55 			goto out;
56 
57 		read_lock_irq(&gpc->lock);
58 	}
59 
60 	/*
61 	 * This code mirrors kvm_write_wall_clock() except that it writes
62 	 * directly through the pfn cache and doesn't mark the page dirty.
63 	 */
64 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
65 
66 	/* Paranoia checks on the 32-bit struct layout */
67 	BUILD_BUG_ON(offsetof(struct compat_shared_info, wc) != 0x900);
68 	BUILD_BUG_ON(offsetof(struct compat_shared_info, arch.wc_sec_hi) != 0x924);
69 	BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
70 
71 #ifdef CONFIG_X86_64
72 	/* Paranoia checks on the 64-bit struct layout */
73 	BUILD_BUG_ON(offsetof(struct shared_info, wc) != 0xc00);
74 	BUILD_BUG_ON(offsetof(struct shared_info, wc_sec_hi) != 0xc0c);
75 
76 	if (IS_ENABLED(CONFIG_64BIT) && kvm->arch.xen.long_mode) {
77 		struct shared_info *shinfo = gpc->khva;
78 
79 		wc_sec_hi = &shinfo->wc_sec_hi;
80 		wc = &shinfo->wc;
81 	} else
82 #endif
83 	{
84 		struct compat_shared_info *shinfo = gpc->khva;
85 
86 		wc_sec_hi = &shinfo->arch.wc_sec_hi;
87 		wc = &shinfo->wc;
88 	}
89 
90 	/* Increment and ensure an odd value */
91 	wc_version = wc->version = (wc->version + 1) | 1;
92 	smp_wmb();
93 
94 	wc->nsec = do_div(wall_nsec, NSEC_PER_SEC);
95 	wc->sec = (u32)wall_nsec;
96 	*wc_sec_hi = wall_nsec >> 32;
97 	smp_wmb();
98 
99 	wc->version = wc_version + 1;
100 	read_unlock_irq(&gpc->lock);
101 
102 out:
103 	srcu_read_unlock(&kvm->srcu, idx);
104 	return ret;
105 }
106 
107 void kvm_xen_inject_timer_irqs(struct kvm_vcpu *vcpu)
108 {
109 	if (atomic_read(&vcpu->arch.xen.timer_pending) > 0) {
110 		struct kvm_xen_evtchn e;
111 
112 		e.vcpu_id = vcpu->vcpu_id;
113 		e.vcpu_idx = vcpu->vcpu_idx;
114 		e.port = vcpu->arch.xen.timer_virq;
115 		e.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;
116 
117 		kvm_xen_set_evtchn(&e, vcpu->kvm);
118 
119 		vcpu->arch.xen.timer_expires = 0;
120 		atomic_set(&vcpu->arch.xen.timer_pending, 0);
121 	}
122 }
123 
124 static enum hrtimer_restart xen_timer_callback(struct hrtimer *timer)
125 {
126 	struct kvm_vcpu *vcpu = container_of(timer, struct kvm_vcpu,
127 					     arch.xen.timer);
128 	struct kvm_xen_evtchn e;
129 	int rc;
130 
131 	if (atomic_read(&vcpu->arch.xen.timer_pending))
132 		return HRTIMER_NORESTART;
133 
134 	e.vcpu_id = vcpu->vcpu_id;
135 	e.vcpu_idx = vcpu->vcpu_idx;
136 	e.port = vcpu->arch.xen.timer_virq;
137 	e.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;
138 
139 	rc = kvm_xen_set_evtchn_fast(&e, vcpu->kvm);
140 	if (rc != -EWOULDBLOCK) {
141 		vcpu->arch.xen.timer_expires = 0;
142 		return HRTIMER_NORESTART;
143 	}
144 
145 	atomic_inc(&vcpu->arch.xen.timer_pending);
146 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
147 	kvm_vcpu_kick(vcpu);
148 
149 	return HRTIMER_NORESTART;
150 }
151 
152 static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,
153 				 struct pvclock_vcpu_time_info *hv_clock,
154 				 struct gfn_to_pfn_cache *gpc,
155 				 unsigned int offset)
156 {
157 	unsigned long flags;
158 	int r;
159 
160 	read_lock_irqsave(&gpc->lock, flags);
161 	while (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {
162 		read_unlock_irqrestore(&gpc->lock, flags);
163 
164 		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));
165 		if (r)
166 			return r;
167 
168 		read_lock_irqsave(&gpc->lock, flags);
169 	}
170 
171 	memcpy(hv_clock, gpc->khva + offset, sizeof(*hv_clock));
172 	read_unlock_irqrestore(&gpc->lock, flags);
173 
174 	/*
175 	 * Sanity check TSC shift+multiplier to verify the guest's view of time
176 	 * is more or less consistent.
177 	 */
178 	if (hv_clock->tsc_shift != vcpu->arch.pvclock_tsc_shift ||
179 	    hv_clock->tsc_to_system_mul != vcpu->arch.pvclock_tsc_mul)
180 		return -EINVAL;
181 
182 	return 0;
183 }
184 
185 static void kvm_xen_start_timer(struct kvm_vcpu *vcpu, u64 guest_abs,
186 				bool linux_wa)
187 {
188 	struct kvm_vcpu_xen *xen = &vcpu->arch.xen;
189 	int64_t kernel_now, delta;
190 	uint64_t guest_now;
191 	int r = -EOPNOTSUPP;
192 
193 	/*
194 	 * The guest provides the requested timeout in absolute nanoseconds
195 	 * of the KVM clock — as *it* sees it, based on the scaled TSC and
196 	 * the pvclock information provided by KVM.
197 	 *
198 	 * The kernel doesn't support hrtimers based on CLOCK_MONOTONIC_RAW
199 	 * so use CLOCK_MONOTONIC. In the timescales covered by timers, the
200 	 * difference won't matter much as there is no cumulative effect.
201 	 *
202 	 * Calculate the time for some arbitrary point in time around "now"
203 	 * in terms of both kvmclock and CLOCK_MONOTONIC. Calculate the
204 	 * delta between the kvmclock "now" value and the guest's requested
205 	 * timeout, apply the "Linux workaround" described below, and add
206 	 * the resulting delta to the CLOCK_MONOTONIC "now" value, to get
207 	 * the absolute CLOCK_MONOTONIC time at which the timer should
208 	 * fire.
209 	 */
210 	do {
211 		struct pvclock_vcpu_time_info hv_clock;
212 		uint64_t host_tsc, guest_tsc;
213 
214 		if (!cpu_feature_enabled(X86_FEATURE_CONSTANT_TSC) ||
215 		    !vcpu->kvm->arch.use_master_clock)
216 			break;
217 
218 		/*
219 		 * If both Xen PV clocks are active, arbitrarily try to use the
220 		 * compat clock first, but also try to use the non-compat clock
221 		 * if the compat clock is unusable.  The two PV clocks hold the
222 		 * same information, but it's possible one (or both) is stale
223 		 * and/or currently unreachable.
224 		 */
225 		if (xen->vcpu_info_cache.active)
226 			r = xen_get_guest_pvclock(vcpu, &hv_clock, &xen->vcpu_info_cache,
227 						  offsetof(struct compat_vcpu_info, time));
228 		if (r && xen->vcpu_time_info_cache.active)
229 			r = xen_get_guest_pvclock(vcpu, &hv_clock, &xen->vcpu_time_info_cache, 0);
230 		if (r)
231 			break;
232 
233 		if (!IS_ENABLED(CONFIG_64BIT) ||
234 		    !kvm_get_monotonic_and_clockread(&kernel_now, &host_tsc)) {
235 			/*
236 			 * Don't fall back to get_kvmclock_ns() because it's
237 			 * broken; it has a systemic error in its results
238 			 * because it scales directly from host TSC to
239 			 * nanoseconds, and doesn't scale first to guest TSC
240 			 * and *then* to nanoseconds as the guest does.
241 			 *
242 			 * There is a small error introduced here because time
243 			 * continues to elapse between the ktime_get() and the
244 			 * subsequent rdtsc(). But not the systemic drift due
245 			 * to get_kvmclock_ns().
246 			 */
247 			kernel_now = ktime_get(); /* This is CLOCK_MONOTONIC */
248 			host_tsc = rdtsc();
249 		}
250 
251 		/* Calculate the guest kvmclock as the guest would do it. */
252 		guest_tsc = kvm_read_l1_tsc(vcpu, host_tsc);
253 		guest_now = __pvclock_read_cycles(&hv_clock, guest_tsc);
254 	} while (0);
255 
256 	if (r) {
257 		/*
258 		 * Without CONSTANT_TSC, get_kvmclock_ns() is the only option.
259 		 *
260 		 * Also if the guest PV clock hasn't been set up yet, as is
261 		 * likely to be the case during migration when the vCPU has
262 		 * not been run yet. It would be possible to calculate the
263 		 * scaling factors properly in that case but there's not much
264 		 * point in doing so. The get_kvmclock_ns() drift accumulates
265 		 * over time, so it's OK to use it at startup. Besides, on
266 		 * migration there's going to be a little bit of skew in the
267 		 * precise moment at which timers fire anyway. Often they'll
268 		 * be in the "past" by the time the VM is running again after
269 		 * migration.
270 		 */
271 		guest_now = get_kvmclock_ns(vcpu->kvm);
272 		kernel_now = ktime_get();
273 	}
274 
275 	delta = guest_abs - guest_now;
276 
277 	/*
278 	 * Xen has a 'Linux workaround' in do_set_timer_op() which checks for
279 	 * negative absolute timeout values (caused by integer overflow), and
280 	 * for values about 13 days in the future (2^50ns) which would be
281 	 * caused by jiffies overflow. For those cases, Xen sets the timeout
282 	 * 100ms in the future (not *too* soon, since if a guest really did
283 	 * set a long timeout on purpose we don't want to keep churning CPU
284 	 * time by waking it up).  Emulate Xen's workaround when starting the
285 	 * timer in response to __HYPERVISOR_set_timer_op.
286 	 */
287 	if (linux_wa &&
288 	    unlikely((int64_t)guest_abs < 0 ||
289 		     (delta > 0 && (uint32_t) (delta >> 50) != 0))) {
290 		delta = 100 * NSEC_PER_MSEC;
291 		guest_abs = guest_now + delta;
292 	}
293 
294 	/*
295 	 * Avoid races with the old timer firing. Checking timer_expires
296 	 * to avoid calling hrtimer_cancel() will only have false positives
297 	 * so is fine.
298 	 */
299 	if (vcpu->arch.xen.timer_expires)
300 		hrtimer_cancel(&vcpu->arch.xen.timer);
301 
302 	atomic_set(&vcpu->arch.xen.timer_pending, 0);
303 	vcpu->arch.xen.timer_expires = guest_abs;
304 
305 	if (delta <= 0)
306 		xen_timer_callback(&vcpu->arch.xen.timer);
307 	else
308 		hrtimer_start(&vcpu->arch.xen.timer,
309 			      ktime_add_ns(kernel_now, delta),
310 			      HRTIMER_MODE_ABS_HARD);
311 }
312 
313 static void kvm_xen_stop_timer(struct kvm_vcpu *vcpu)
314 {
315 	hrtimer_cancel(&vcpu->arch.xen.timer);
316 	vcpu->arch.xen.timer_expires = 0;
317 	atomic_set(&vcpu->arch.xen.timer_pending, 0);
318 }
319 
320 static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)
321 {
322 	struct kvm_vcpu_xen *vx = &v->arch.xen;
323 	struct gfn_to_pfn_cache *gpc1 = &vx->runstate_cache;
324 	struct gfn_to_pfn_cache *gpc2 = &vx->runstate2_cache;
325 	size_t user_len, user_len1, user_len2;
326 	struct vcpu_runstate_info rs;
327 	unsigned long flags;
328 	size_t times_ofs;
329 	uint8_t *update_bit = NULL;
330 	uint64_t entry_time;
331 	uint64_t *rs_times;
332 	int *rs_state;
333 
334 	/*
335 	 * The only difference between 32-bit and 64-bit versions of the
336 	 * runstate struct is the alignment of uint64_t in 32-bit, which
337 	 * means that the 64-bit version has an additional 4 bytes of
338 	 * padding after the first field 'state'. Let's be really really
339 	 * paranoid about that, and matching it with our internal data
340 	 * structures that we memcpy into it...
341 	 */
342 	BUILD_BUG_ON(offsetof(struct vcpu_runstate_info, state) != 0);
343 	BUILD_BUG_ON(offsetof(struct compat_vcpu_runstate_info, state) != 0);
344 	BUILD_BUG_ON(sizeof(struct compat_vcpu_runstate_info) != 0x2c);
345 #ifdef CONFIG_X86_64
346 	/*
347 	 * The 64-bit structure has 4 bytes of padding before 'state_entry_time'
348 	 * so each subsequent field is shifted by 4, and it's 4 bytes longer.
349 	 */
350 	BUILD_BUG_ON(offsetof(struct vcpu_runstate_info, state_entry_time) !=
351 		     offsetof(struct compat_vcpu_runstate_info, state_entry_time) + 4);
352 	BUILD_BUG_ON(offsetof(struct vcpu_runstate_info, time) !=
353 		     offsetof(struct compat_vcpu_runstate_info, time) + 4);
354 	BUILD_BUG_ON(sizeof(struct vcpu_runstate_info) != 0x2c + 4);
355 #endif
356 	/*
357 	 * The state field is in the same place at the start of both structs,
358 	 * and is the same size (int) as vx->current_runstate.
359 	 */
360 	BUILD_BUG_ON(offsetof(struct vcpu_runstate_info, state) !=
361 		     offsetof(struct compat_vcpu_runstate_info, state));
362 	BUILD_BUG_ON(sizeof_field(struct vcpu_runstate_info, state) !=
363 		     sizeof(vx->current_runstate));
364 	BUILD_BUG_ON(sizeof_field(struct compat_vcpu_runstate_info, state) !=
365 		     sizeof(vx->current_runstate));
366 
367 	/*
368 	 * The state_entry_time field is 64 bits in both versions, and the
369 	 * XEN_RUNSTATE_UPDATE flag is in the top bit, which given that x86
370 	 * is little-endian means that it's in the last *byte* of the word.
371 	 * That detail is important later.
372 	 */
373 	BUILD_BUG_ON(sizeof_field(struct vcpu_runstate_info, state_entry_time) !=
374 		     sizeof(uint64_t));
375 	BUILD_BUG_ON(sizeof_field(struct compat_vcpu_runstate_info, state_entry_time) !=
376 		     sizeof(uint64_t));
377 	BUILD_BUG_ON((XEN_RUNSTATE_UPDATE >> 56) != 0x80);
378 
379 	/*
380 	 * The time array is four 64-bit quantities in both versions, matching
381 	 * the vx->runstate_times and immediately following state_entry_time.
382 	 */
383 	BUILD_BUG_ON(offsetof(struct vcpu_runstate_info, state_entry_time) !=
384 		     offsetof(struct vcpu_runstate_info, time) - sizeof(uint64_t));
385 	BUILD_BUG_ON(offsetof(struct compat_vcpu_runstate_info, state_entry_time) !=
386 		     offsetof(struct compat_vcpu_runstate_info, time) - sizeof(uint64_t));
387 	BUILD_BUG_ON(sizeof_field(struct vcpu_runstate_info, time) !=
388 		     sizeof_field(struct compat_vcpu_runstate_info, time));
389 	BUILD_BUG_ON(sizeof_field(struct vcpu_runstate_info, time) !=
390 		     sizeof(vx->runstate_times));
391 
392 	if (IS_ENABLED(CONFIG_64BIT) && v->kvm->arch.xen.long_mode) {
393 		user_len = sizeof(struct vcpu_runstate_info);
394 		times_ofs = offsetof(struct vcpu_runstate_info,
395 				     state_entry_time);
396 	} else {
397 		user_len = sizeof(struct compat_vcpu_runstate_info);
398 		times_ofs = offsetof(struct compat_vcpu_runstate_info,
399 				     state_entry_time);
400 	}
401 
402 	/*
403 	 * There are basically no alignment constraints. The guest can set it
404 	 * up so it crosses from one page to the next, and at arbitrary byte
405 	 * alignment (and the 32-bit ABI doesn't align the 64-bit integers
406 	 * anyway, even if the overall struct had been 64-bit aligned).
407 	 */
408 	if ((gpc1->gpa & ~PAGE_MASK) + user_len >= PAGE_SIZE) {
409 		user_len1 = PAGE_SIZE - (gpc1->gpa & ~PAGE_MASK);
410 		user_len2 = user_len - user_len1;
411 	} else {
412 		user_len1 = user_len;
413 		user_len2 = 0;
414 	}
415 	BUG_ON(user_len1 + user_len2 != user_len);
416 
417  retry:
418 	/*
419 	 * Attempt to obtain the GPC lock on *both* (if there are two)
420 	 * gfn_to_pfn caches that cover the region.
421 	 */
422 	if (atomic) {
423 		local_irq_save(flags);
424 		if (!read_trylock(&gpc1->lock)) {
425 			local_irq_restore(flags);
426 			return;
427 		}
428 	} else {
429 		read_lock_irqsave(&gpc1->lock, flags);
430 	}
431 	while (!kvm_gpc_check(gpc1, user_len1)) {
432 		read_unlock_irqrestore(&gpc1->lock, flags);
433 
434 		/* When invoked from kvm_sched_out() we cannot sleep */
435 		if (atomic)
436 			return;
437 
438 		if (kvm_gpc_refresh(gpc1, user_len1))
439 			return;
440 
441 		read_lock_irqsave(&gpc1->lock, flags);
442 	}
443 
444 	if (likely(!user_len2)) {
445 		/*
446 		 * Set up three pointers directly to the runstate_info
447 		 * struct in the guest (via the GPC).
448 		 *
449 		 *  • @rs_state   → state field
450 		 *  • @rs_times   → state_entry_time field.
451 		 *  • @update_bit → last byte of state_entry_time, which
452 		 *                  contains the XEN_RUNSTATE_UPDATE bit.
453 		 */
454 		rs_state = gpc1->khva;
455 		rs_times = gpc1->khva + times_ofs;
456 		if (v->kvm->arch.xen.runstate_update_flag)
457 			update_bit = ((void *)(&rs_times[1])) - 1;
458 	} else {
459 		/*
460 		 * The guest's runstate_info is split across two pages and we
461 		 * need to hold and validate both GPCs simultaneously. We can
462 		 * declare a lock ordering GPC1 > GPC2 because nothing else
463 		 * takes them more than one at a time. Set a subclass on the
464 		 * gpc1 lock to make lockdep shut up about it.
465 		 */
466 		lock_set_subclass(&gpc1->lock.dep_map, 1, _THIS_IP_);
467 		if (atomic) {
468 			if (!read_trylock(&gpc2->lock)) {
469 				read_unlock_irqrestore(&gpc1->lock, flags);
470 				return;
471 			}
472 		} else {
473 			read_lock(&gpc2->lock);
474 		}
475 
476 		if (!kvm_gpc_check(gpc2, user_len2)) {
477 			read_unlock(&gpc2->lock);
478 			read_unlock_irqrestore(&gpc1->lock, flags);
479 
480 			/* When invoked from kvm_sched_out() we cannot sleep */
481 			if (atomic)
482 				return;
483 
484 			/*
485 			 * Use kvm_gpc_activate() here because if the runstate
486 			 * area was configured in 32-bit mode and only extends
487 			 * to the second page now because the guest changed to
488 			 * 64-bit mode, the second GPC won't have been set up.
489 			 */
490 			if (kvm_gpc_activate(gpc2, gpc1->gpa + user_len1,
491 					     user_len2))
492 				return;
493 
494 			/*
495 			 * We dropped the lock on GPC1 so we have to go all the
496 			 * way back and revalidate that too.
497 			 */
498 			goto retry;
499 		}
500 
501 		/*
502 		 * In this case, the runstate_info struct will be assembled on
503 		 * the kernel stack (compat or not as appropriate) and will
504 		 * be copied to GPC1/GPC2 with a dual memcpy. Set up the three
505 		 * rs pointers accordingly.
506 		 */
507 		rs_times = &rs.state_entry_time;
508 
509 		/*
510 		 * The rs_state pointer points to the start of what we'll
511 		 * copy to the guest, which in the case of a compat guest
512 		 * is the 32-bit field that the compiler thinks is padding.
513 		 */
514 		rs_state = ((void *)rs_times) - times_ofs;
515 
516 		/*
517 		 * The update_bit is still directly in the guest memory,
518 		 * via one GPC or the other.
519 		 */
520 		if (v->kvm->arch.xen.runstate_update_flag) {
521 			if (user_len1 >= times_ofs + sizeof(uint64_t))
522 				update_bit = gpc1->khva + times_ofs +
523 					sizeof(uint64_t) - 1;
524 			else
525 				update_bit = gpc2->khva + times_ofs +
526 					sizeof(uint64_t) - 1 - user_len1;
527 		}
528 
529 #ifdef CONFIG_X86_64
530 		/*
531 		 * Don't leak kernel memory through the padding in the 64-bit
532 		 * version of the struct.
533 		 */
534 		memset(&rs, 0, offsetof(struct vcpu_runstate_info, state_entry_time));
535 #endif
536 	}
537 
538 	/*
539 	 * First, set the XEN_RUNSTATE_UPDATE bit in the top bit of the
540 	 * state_entry_time field, directly in the guest. We need to set
541 	 * that (and write-barrier) before writing to the rest of the
542 	 * structure, and clear it last. Just as Xen does, we address the
543 	 * single *byte* in which it resides because it might be in a
544 	 * different cache line to the rest of the 64-bit word, due to
545 	 * the (lack of) alignment constraints.
546 	 */
547 	entry_time = vx->runstate_entry_time;
548 	if (update_bit) {
549 		entry_time |= XEN_RUNSTATE_UPDATE;
550 		*update_bit = (vx->runstate_entry_time | XEN_RUNSTATE_UPDATE) >> 56;
551 		smp_wmb();
552 	}
553 
554 	/*
555 	 * Now assemble the actual structure, either on our kernel stack
556 	 * or directly in the guest according to how the rs_state and
557 	 * rs_times pointers were set up above.
558 	 */
559 	*rs_state = vx->current_runstate;
560 	rs_times[0] = entry_time;
561 	memcpy(rs_times + 1, vx->runstate_times, sizeof(vx->runstate_times));
562 
563 	/* For the split case, we have to then copy it to the guest. */
564 	if (user_len2) {
565 		memcpy(gpc1->khva, rs_state, user_len1);
566 		memcpy(gpc2->khva, ((void *)rs_state) + user_len1, user_len2);
567 	}
568 	smp_wmb();
569 
570 	/* Finally, clear the XEN_RUNSTATE_UPDATE bit. */
571 	if (update_bit) {
572 		entry_time &= ~XEN_RUNSTATE_UPDATE;
573 		*update_bit = entry_time >> 56;
574 		smp_wmb();
575 	}
576 
577 	if (user_len2) {
578 		kvm_gpc_mark_dirty_in_slot(gpc2);
579 		read_unlock(&gpc2->lock);
580 	}
581 
582 	kvm_gpc_mark_dirty_in_slot(gpc1);
583 	read_unlock_irqrestore(&gpc1->lock, flags);
584 }
585 
586 void kvm_xen_update_runstate(struct kvm_vcpu *v, int state)
587 {
588 	struct kvm_vcpu_xen *vx = &v->arch.xen;
589 	u64 now = get_kvmclock_ns(v->kvm);
590 	u64 run_delay = current->sched_info.run_delay;
591 	s64 delta_ns = now - vx->runstate_entry_time;
592 	s64 steal_ns = run_delay - vx->last_steal;
593 
594 	/*
595 	 * If the vCPU was never run before, its prior state should
596 	 * be considered RUNSTATE_offline.
597 	 */
598 	if (unlikely(!vx->runstate_entry_time))
599 		vx->current_runstate = RUNSTATE_offline;
600 
601 	/*
602 	 * If KVM clock went backwards, just update the current runstate
603 	 * but don't account any time. Leave entry_time unchanged so the
604 	 * next positive delta covers the full period once the clock
605 	 * catches up. Update last_steal every time so stolen time only
606 	 * reflects the interval since the most recent call.
607 	 */
608 	if (delta_ns < 0)
609 		goto update_guest;
610 
611 	/*
612 	 * Time waiting for the scheduler isn't "stolen" if the
613 	 * vCPU wasn't running anyway.
614 	 */
615 	if (vx->current_runstate == RUNSTATE_running && steal_ns > 0) {
616 		if (steal_ns > delta_ns)
617 			steal_ns = delta_ns;
618 
619 		delta_ns -= steal_ns;
620 		vx->runstate_times[RUNSTATE_runnable] += steal_ns;
621 	}
622 
623 	vx->runstate_times[vx->current_runstate] += delta_ns;
624 	vx->runstate_entry_time = now;
625 
626  update_guest:
627 	vx->current_runstate = state;
628 	vx->last_steal = run_delay;
629 	if (vx->runstate_cache.active)
630 		kvm_xen_update_runstate_guest(v, state == RUNSTATE_runnable);
631 }
632 
633 void kvm_xen_inject_vcpu_vector(struct kvm_vcpu *v)
634 {
635 	struct kvm_lapic_irq irq = { };
636 
637 	irq.dest_id = v->vcpu_id;
638 	irq.vector = v->arch.xen.upcall_vector;
639 	irq.dest_mode = APIC_DEST_PHYSICAL;
640 	irq.shorthand = APIC_DEST_NOSHORT;
641 	irq.delivery_mode = APIC_DM_FIXED;
642 	irq.level = 1;
643 
644 	kvm_irq_delivery_to_apic(v->kvm, NULL, &irq);
645 }
646 
647 /*
648  * On event channel delivery, the vcpu_info may not have been accessible.
649  * In that case, there are bits in vcpu->arch.xen.evtchn_pending_sel which
650  * need to be marked into the vcpu_info (and evtchn_upcall_pending set).
651  * Do so now that we can sleep in the context of the vCPU to bring the
652  * page in, and refresh the pfn cache for it.
653  */
654 void kvm_xen_inject_pending_events(struct kvm_vcpu *v)
655 {
656 	unsigned long evtchn_pending_sel = READ_ONCE(v->arch.xen.evtchn_pending_sel);
657 	struct gfn_to_pfn_cache *gpc = &v->arch.xen.vcpu_info_cache;
658 	unsigned long flags;
659 
660 	if (!evtchn_pending_sel)
661 		return;
662 
663 	/*
664 	 * Yes, this is an open-coded loop. But that's just what put_user()
665 	 * does anyway. Page it in and retry the instruction. We're just a
666 	 * little more honest about it.
667 	 */
668 	read_lock_irqsave(&gpc->lock, flags);
669 	while (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
670 		read_unlock_irqrestore(&gpc->lock, flags);
671 
672 		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info)))
673 			return;
674 
675 		read_lock_irqsave(&gpc->lock, flags);
676 	}
677 
678 	/* Now gpc->khva is a valid kernel address for the vcpu_info */
679 	if (IS_ENABLED(CONFIG_64BIT) && v->kvm->arch.xen.long_mode) {
680 		struct vcpu_info *vi = gpc->khva;
681 
682 		asm volatile(LOCK_PREFIX "orq %0, %1\n"
683 			     "notq %0\n"
684 			     LOCK_PREFIX "andq %0, %2\n"
685 			     : "=r" (evtchn_pending_sel),
686 			       "+m" (vi->evtchn_pending_sel),
687 			       "+m" (v->arch.xen.evtchn_pending_sel)
688 			     : "0" (evtchn_pending_sel));
689 		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
690 	} else {
691 		u32 evtchn_pending_sel32 = evtchn_pending_sel;
692 		struct compat_vcpu_info *vi = gpc->khva;
693 
694 		asm volatile(LOCK_PREFIX "orl %0, %1\n"
695 			     "notl %0\n"
696 			     LOCK_PREFIX "andl %0, %2\n"
697 			     : "=r" (evtchn_pending_sel32),
698 			       "+m" (vi->evtchn_pending_sel),
699 			       "+m" (v->arch.xen.evtchn_pending_sel)
700 			     : "0" (evtchn_pending_sel32));
701 		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
702 	}
703 
704 	kvm_gpc_mark_dirty_in_slot(gpc);
705 	read_unlock_irqrestore(&gpc->lock, flags);
706 
707 	/* For the per-vCPU lapic vector, deliver it as MSI. */
708 	if (v->arch.xen.upcall_vector)
709 		kvm_xen_inject_vcpu_vector(v);
710 }
711 
712 int __kvm_xen_has_interrupt(struct kvm_vcpu *v)
713 {
714 	struct gfn_to_pfn_cache *gpc = &v->arch.xen.vcpu_info_cache;
715 	unsigned long flags;
716 	u8 rc = 0;
717 
718 	/*
719 	 * If the global upcall vector (HVMIRQ_callback_vector) is set and
720 	 * the vCPU's evtchn_upcall_pending flag is set, the IRQ is pending.
721 	 */
722 
723 	/* No need for compat handling here */
724 	BUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=
725 		     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));
726 	BUILD_BUG_ON(sizeof(rc) !=
727 		     sizeof_field(struct vcpu_info, evtchn_upcall_pending));
728 	BUILD_BUG_ON(sizeof(rc) !=
729 		     sizeof_field(struct compat_vcpu_info, evtchn_upcall_pending));
730 
731 	read_lock_irqsave(&gpc->lock, flags);
732 	while (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
733 		read_unlock_irqrestore(&gpc->lock, flags);
734 
735 		/*
736 		 * This function gets called from kvm_vcpu_block() after setting the
737 		 * task to TASK_INTERRUPTIBLE, to see if it needs to wake immediately
738 		 * from a HLT. So we really mustn't sleep. If the page ended up absent
739 		 * at that point, just return 1 in order to trigger an immediate wake,
740 		 * and we'll end up getting called again from a context where we *can*
741 		 * fault in the page and wait for it.
742 		 */
743 		if (in_atomic() || !task_is_running(current))
744 			return 1;
745 
746 		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info))) {
747 			/*
748 			 * If this failed, userspace has screwed up the
749 			 * vcpu_info mapping. No interrupts for you.
750 			 */
751 			return 0;
752 		}
753 		read_lock_irqsave(&gpc->lock, flags);
754 	}
755 
756 	rc = ((struct vcpu_info *)gpc->khva)->evtchn_upcall_pending;
757 	read_unlock_irqrestore(&gpc->lock, flags);
758 	return rc;
759 }
760 
761 int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
762 {
763 	int r = -ENOENT;
764 
765 
766 	switch (data->type) {
767 	case KVM_XEN_ATTR_TYPE_LONG_MODE:
768 		if (!IS_ENABLED(CONFIG_64BIT) && data->u.long_mode) {
769 			r = -EINVAL;
770 		} else {
771 			mutex_lock(&kvm->arch.xen.xen_lock);
772 			kvm->arch.xen.long_mode = !!data->u.long_mode;
773 
774 			/*
775 			 * Re-initialize shared_info to put the wallclock in the
776 			 * correct place. Whilst it's not necessary to do this
777 			 * unless the mode is actually changed, it does no harm
778 			 * to make the call anyway.
779 			 */
780 			r = kvm->arch.xen.shinfo_cache.active ?
781 				kvm_xen_shared_info_init(kvm) : 0;
782 			mutex_unlock(&kvm->arch.xen.xen_lock);
783 		}
784 		break;
785 
786 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
787 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {
788 		int idx;
789 
790 		mutex_lock(&kvm->arch.xen.xen_lock);
791 
792 		idx = srcu_read_lock(&kvm->srcu);
793 
794 		if (data->type == KVM_XEN_ATTR_TYPE_SHARED_INFO) {
795 			gfn_t gfn = data->u.shared_info.gfn;
796 
797 			if (gfn == KVM_XEN_INVALID_GFN) {
798 				kvm_gpc_deactivate(&kvm->arch.xen.shinfo_cache);
799 				r = 0;
800 			} else {
801 				r = kvm_gpc_activate(&kvm->arch.xen.shinfo_cache,
802 						     gfn_to_gpa(gfn), PAGE_SIZE);
803 			}
804 		} else {
805 			void __user * hva = u64_to_user_ptr(data->u.shared_info.hva);
806 
807 			if (!PAGE_ALIGNED(hva)) {
808 				r = -EINVAL;
809 			} else if (!hva) {
810 				kvm_gpc_deactivate(&kvm->arch.xen.shinfo_cache);
811 				r = 0;
812 			} else {
813 				r = kvm_gpc_activate_hva(&kvm->arch.xen.shinfo_cache,
814 							 (unsigned long)hva, PAGE_SIZE);
815 			}
816 		}
817 
818 		srcu_read_unlock(&kvm->srcu, idx);
819 
820 		if (!r && kvm->arch.xen.shinfo_cache.active)
821 			r = kvm_xen_shared_info_init(kvm);
822 
823 		mutex_unlock(&kvm->arch.xen.xen_lock);
824 		break;
825 	}
826 	case KVM_XEN_ATTR_TYPE_UPCALL_VECTOR:
827 		if (data->u.vector && data->u.vector < 0x10)
828 			r = -EINVAL;
829 		else {
830 			mutex_lock(&kvm->arch.xen.xen_lock);
831 			kvm->arch.xen.upcall_vector = data->u.vector;
832 			mutex_unlock(&kvm->arch.xen.xen_lock);
833 			r = 0;
834 		}
835 		break;
836 
837 	case KVM_XEN_ATTR_TYPE_EVTCHN:
838 		r = kvm_xen_setattr_evtchn(kvm, data);
839 		break;
840 
841 	case KVM_XEN_ATTR_TYPE_XEN_VERSION:
842 		mutex_lock(&kvm->arch.xen.xen_lock);
843 		kvm->arch.xen.xen_version = data->u.xen_version;
844 		mutex_unlock(&kvm->arch.xen.xen_lock);
845 		r = 0;
846 		break;
847 
848 	case KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG:
849 		if (!sched_info_on()) {
850 			r = -EOPNOTSUPP;
851 			break;
852 		}
853 		mutex_lock(&kvm->arch.xen.xen_lock);
854 		kvm->arch.xen.runstate_update_flag = !!data->u.runstate_update_flag;
855 		mutex_unlock(&kvm->arch.xen.xen_lock);
856 		r = 0;
857 		break;
858 
859 	default:
860 		break;
861 	}
862 
863 	return r;
864 }
865 
866 int kvm_xen_hvm_get_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
867 {
868 	int r = -ENOENT;
869 
870 	mutex_lock(&kvm->arch.xen.xen_lock);
871 
872 	switch (data->type) {
873 	case KVM_XEN_ATTR_TYPE_LONG_MODE:
874 		data->u.long_mode = kvm->arch.xen.long_mode;
875 		r = 0;
876 		break;
877 
878 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
879 		if (kvm_gpc_is_gpa_active(&kvm->arch.xen.shinfo_cache))
880 			data->u.shared_info.gfn = gpa_to_gfn(kvm->arch.xen.shinfo_cache.gpa);
881 		else
882 			data->u.shared_info.gfn = KVM_XEN_INVALID_GFN;
883 		r = 0;
884 		break;
885 
886 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA:
887 		if (kvm_gpc_is_hva_active(&kvm->arch.xen.shinfo_cache))
888 			data->u.shared_info.hva = kvm->arch.xen.shinfo_cache.uhva;
889 		else
890 			data->u.shared_info.hva = 0;
891 		r = 0;
892 		break;
893 
894 	case KVM_XEN_ATTR_TYPE_UPCALL_VECTOR:
895 		data->u.vector = kvm->arch.xen.upcall_vector;
896 		r = 0;
897 		break;
898 
899 	case KVM_XEN_ATTR_TYPE_XEN_VERSION:
900 		data->u.xen_version = kvm->arch.xen.xen_version;
901 		r = 0;
902 		break;
903 
904 	case KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG:
905 		if (!sched_info_on()) {
906 			r = -EOPNOTSUPP;
907 			break;
908 		}
909 		data->u.runstate_update_flag = kvm->arch.xen.runstate_update_flag;
910 		r = 0;
911 		break;
912 
913 	default:
914 		break;
915 	}
916 
917 	mutex_unlock(&kvm->arch.xen.xen_lock);
918 	return r;
919 }
920 
921 int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
922 {
923 	int idx, r = -ENOENT;
924 
925 	mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
926 	idx = srcu_read_lock(&vcpu->kvm->srcu);
927 
928 	switch (data->type) {
929 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:
930 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA:
931 		/* No compat necessary here. */
932 		BUILD_BUG_ON(sizeof(struct vcpu_info) !=
933 			     sizeof(struct compat_vcpu_info));
934 		BUILD_BUG_ON(offsetof(struct vcpu_info, time) !=
935 			     offsetof(struct compat_vcpu_info, time));
936 
937 		if (data->type == KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO) {
938 			if (data->u.gpa == KVM_XEN_INVALID_GPA) {
939 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
940 				r = 0;
941 				break;
942 			}
943 
944 			r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_info_cache,
945 					     data->u.gpa, sizeof(struct vcpu_info));
946 		} else {
947 			if (data->u.hva == 0) {
948 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
949 				r = 0;
950 				break;
951 			}
952 
953 			r = kvm_gpc_activate_hva(&vcpu->arch.xen.vcpu_info_cache,
954 						 data->u.hva, sizeof(struct vcpu_info));
955 		}
956 
957 		if (!r)
958 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
959 
960 		break;
961 
962 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO:
963 		if (data->u.gpa == KVM_XEN_INVALID_GPA) {
964 			kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_time_info_cache);
965 			r = 0;
966 			break;
967 		}
968 
969 		r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_time_info_cache,
970 				     data->u.gpa,
971 				     sizeof(struct pvclock_vcpu_time_info));
972 		if (!r)
973 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
974 		break;
975 
976 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR: {
977 		size_t sz, sz1, sz2;
978 
979 		if (!sched_info_on()) {
980 			r = -EOPNOTSUPP;
981 			break;
982 		}
983 		if (data->u.gpa == KVM_XEN_INVALID_GPA) {
984 			r = 0;
985 		deactivate_out:
986 			kvm_gpc_deactivate(&vcpu->arch.xen.runstate_cache);
987 			kvm_gpc_deactivate(&vcpu->arch.xen.runstate2_cache);
988 			break;
989 		}
990 
991 		/*
992 		 * If the guest switches to 64-bit mode after setting the runstate
993 		 * address, that's actually OK. kvm_xen_update_runstate_guest()
994 		 * will cope.
995 		 */
996 		if (IS_ENABLED(CONFIG_64BIT) && vcpu->kvm->arch.xen.long_mode)
997 			sz = sizeof(struct vcpu_runstate_info);
998 		else
999 			sz = sizeof(struct compat_vcpu_runstate_info);
1000 
1001 		/* How much fits in the (first) page? */
1002 		sz1 = PAGE_SIZE - (data->u.gpa & ~PAGE_MASK);
1003 		r = kvm_gpc_activate(&vcpu->arch.xen.runstate_cache,
1004 				     data->u.gpa, sz1);
1005 		if (r)
1006 			goto deactivate_out;
1007 
1008 		/* Either map the second page, or deactivate the second GPC */
1009 		if (sz1 >= sz) {
1010 			kvm_gpc_deactivate(&vcpu->arch.xen.runstate2_cache);
1011 		} else {
1012 			sz2 = sz - sz1;
1013 			BUG_ON((data->u.gpa + sz1) & ~PAGE_MASK);
1014 			r = kvm_gpc_activate(&vcpu->arch.xen.runstate2_cache,
1015 					     data->u.gpa + sz1, sz2);
1016 			if (r)
1017 				goto deactivate_out;
1018 		}
1019 
1020 		kvm_xen_update_runstate_guest(vcpu, false);
1021 		break;
1022 	}
1023 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT:
1024 		if (!sched_info_on()) {
1025 			r = -EOPNOTSUPP;
1026 			break;
1027 		}
1028 		if (data->u.runstate.state > RUNSTATE_offline) {
1029 			r = -EINVAL;
1030 			break;
1031 		}
1032 
1033 		kvm_xen_update_runstate(vcpu, data->u.runstate.state);
1034 		r = 0;
1035 		break;
1036 
1037 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA:
1038 		if (!sched_info_on()) {
1039 			r = -EOPNOTSUPP;
1040 			break;
1041 		}
1042 		if (data->u.runstate.state > RUNSTATE_offline) {
1043 			r = -EINVAL;
1044 			break;
1045 		}
1046 		if (data->u.runstate.state_entry_time !=
1047 		    (data->u.runstate.time_running +
1048 		     data->u.runstate.time_runnable +
1049 		     data->u.runstate.time_blocked +
1050 		     data->u.runstate.time_offline)) {
1051 			r = -EINVAL;
1052 			break;
1053 		}
1054 		if (get_kvmclock_ns(vcpu->kvm) <
1055 		    data->u.runstate.state_entry_time) {
1056 			r = -EINVAL;
1057 			break;
1058 		}
1059 
1060 		vcpu->arch.xen.current_runstate = data->u.runstate.state;
1061 		vcpu->arch.xen.runstate_entry_time =
1062 			data->u.runstate.state_entry_time;
1063 		vcpu->arch.xen.runstate_times[RUNSTATE_running] =
1064 			data->u.runstate.time_running;
1065 		vcpu->arch.xen.runstate_times[RUNSTATE_runnable] =
1066 			data->u.runstate.time_runnable;
1067 		vcpu->arch.xen.runstate_times[RUNSTATE_blocked] =
1068 			data->u.runstate.time_blocked;
1069 		vcpu->arch.xen.runstate_times[RUNSTATE_offline] =
1070 			data->u.runstate.time_offline;
1071 		vcpu->arch.xen.last_steal = current->sched_info.run_delay;
1072 		r = 0;
1073 		break;
1074 
1075 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST:
1076 		if (!sched_info_on()) {
1077 			r = -EOPNOTSUPP;
1078 			break;
1079 		}
1080 		if (data->u.runstate.state > RUNSTATE_offline &&
1081 		    data->u.runstate.state != (u64)-1) {
1082 			r = -EINVAL;
1083 			break;
1084 		}
1085 		/* The adjustment must add up */
1086 		if (data->u.runstate.state_entry_time !=
1087 		    (data->u.runstate.time_running +
1088 		     data->u.runstate.time_runnable +
1089 		     data->u.runstate.time_blocked +
1090 		     data->u.runstate.time_offline)) {
1091 			r = -EINVAL;
1092 			break;
1093 		}
1094 
1095 		if (get_kvmclock_ns(vcpu->kvm) <
1096 		    (vcpu->arch.xen.runstate_entry_time +
1097 		     data->u.runstate.state_entry_time)) {
1098 			r = -EINVAL;
1099 			break;
1100 		}
1101 
1102 		vcpu->arch.xen.runstate_entry_time +=
1103 			data->u.runstate.state_entry_time;
1104 		vcpu->arch.xen.runstate_times[RUNSTATE_running] +=
1105 			data->u.runstate.time_running;
1106 		vcpu->arch.xen.runstate_times[RUNSTATE_runnable] +=
1107 			data->u.runstate.time_runnable;
1108 		vcpu->arch.xen.runstate_times[RUNSTATE_blocked] +=
1109 			data->u.runstate.time_blocked;
1110 		vcpu->arch.xen.runstate_times[RUNSTATE_offline] +=
1111 			data->u.runstate.time_offline;
1112 
1113 		if (data->u.runstate.state <= RUNSTATE_offline)
1114 			kvm_xen_update_runstate(vcpu, data->u.runstate.state);
1115 		else if (vcpu->arch.xen.runstate_cache.active)
1116 			kvm_xen_update_runstate_guest(vcpu, false);
1117 		r = 0;
1118 		break;
1119 
1120 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_ID:
1121 		BUILD_BUG_ON(XEN_VCPU_ID_INVALID < KVM_MAX_VCPUS);
1122 
1123 		if (data->u.vcpu_id >= KVM_MAX_VCPUS)
1124 			r = -EINVAL;
1125 		else {
1126 			vcpu->arch.xen.vcpu_id = data->u.vcpu_id;
1127 			r = 0;
1128 		}
1129 		break;
1130 
1131 	case KVM_XEN_VCPU_ATTR_TYPE_TIMER:
1132 		if (data->u.timer.port &&
1133 		    data->u.timer.priority != KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL) {
1134 			r = -EINVAL;
1135 			break;
1136 		}
1137 
1138 		/* Stop the timer (if it's running) before changing the vector */
1139 		kvm_xen_stop_timer(vcpu);
1140 		vcpu->arch.xen.timer_virq = data->u.timer.port;
1141 
1142 		/* Start the timer if the new value has a valid vector+expiry. */
1143 		if (data->u.timer.port && data->u.timer.expires_ns)
1144 			kvm_xen_start_timer(vcpu, data->u.timer.expires_ns, false);
1145 
1146 		r = 0;
1147 		break;
1148 
1149 	case KVM_XEN_VCPU_ATTR_TYPE_UPCALL_VECTOR:
1150 		if (data->u.vector && data->u.vector < 0x10)
1151 			r = -EINVAL;
1152 		else {
1153 			vcpu->arch.xen.upcall_vector = data->u.vector;
1154 			r = 0;
1155 		}
1156 		break;
1157 
1158 	default:
1159 		break;
1160 	}
1161 
1162 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
1163 	mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
1164 	return r;
1165 }
1166 
1167 int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
1168 {
1169 	int r = -ENOENT;
1170 
1171 	mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
1172 
1173 	switch (data->type) {
1174 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:
1175 		if (kvm_gpc_is_gpa_active(&vcpu->arch.xen.vcpu_info_cache))
1176 			data->u.gpa = vcpu->arch.xen.vcpu_info_cache.gpa;
1177 		else
1178 			data->u.gpa = KVM_XEN_INVALID_GPA;
1179 		r = 0;
1180 		break;
1181 
1182 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA:
1183 		if (kvm_gpc_is_hva_active(&vcpu->arch.xen.vcpu_info_cache))
1184 			data->u.hva = vcpu->arch.xen.vcpu_info_cache.uhva;
1185 		else
1186 			data->u.hva = 0;
1187 		r = 0;
1188 		break;
1189 
1190 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO:
1191 		if (vcpu->arch.xen.vcpu_time_info_cache.active)
1192 			data->u.gpa = vcpu->arch.xen.vcpu_time_info_cache.gpa;
1193 		else
1194 			data->u.gpa = KVM_XEN_INVALID_GPA;
1195 		r = 0;
1196 		break;
1197 
1198 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR:
1199 		if (!sched_info_on()) {
1200 			r = -EOPNOTSUPP;
1201 			break;
1202 		}
1203 		if (vcpu->arch.xen.runstate_cache.active) {
1204 			data->u.gpa = vcpu->arch.xen.runstate_cache.gpa;
1205 			r = 0;
1206 		}
1207 		break;
1208 
1209 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT:
1210 		if (!sched_info_on()) {
1211 			r = -EOPNOTSUPP;
1212 			break;
1213 		}
1214 		data->u.runstate.state = vcpu->arch.xen.current_runstate;
1215 		r = 0;
1216 		break;
1217 
1218 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA:
1219 		if (!sched_info_on()) {
1220 			r = -EOPNOTSUPP;
1221 			break;
1222 		}
1223 		data->u.runstate.state = vcpu->arch.xen.current_runstate;
1224 		data->u.runstate.state_entry_time =
1225 			vcpu->arch.xen.runstate_entry_time;
1226 		data->u.runstate.time_running =
1227 			vcpu->arch.xen.runstate_times[RUNSTATE_running];
1228 		data->u.runstate.time_runnable =
1229 			vcpu->arch.xen.runstate_times[RUNSTATE_runnable];
1230 		data->u.runstate.time_blocked =
1231 			vcpu->arch.xen.runstate_times[RUNSTATE_blocked];
1232 		data->u.runstate.time_offline =
1233 			vcpu->arch.xen.runstate_times[RUNSTATE_offline];
1234 		r = 0;
1235 		break;
1236 
1237 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST:
1238 		r = -EINVAL;
1239 		break;
1240 
1241 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_ID:
1242 		data->u.vcpu_id = vcpu->arch.xen.vcpu_id;
1243 		r = 0;
1244 		break;
1245 
1246 	case KVM_XEN_VCPU_ATTR_TYPE_TIMER:
1247 		/*
1248 		 * Ensure a consistent snapshot of state is captured, with a
1249 		 * timer either being pending, or the event channel delivered
1250 		 * to the corresponding bit in the shared_info. Not still
1251 		 * lurking in the timer_pending flag for deferred delivery.
1252 		 * Purely as an optimisation, if the timer_expires field is
1253 		 * zero, that means the timer isn't active (or even in the
1254 		 * timer_pending flag) and there is no need to cancel it.
1255 		 */
1256 		if (vcpu->arch.xen.timer_expires) {
1257 			hrtimer_cancel(&vcpu->arch.xen.timer);
1258 			kvm_xen_inject_timer_irqs(vcpu);
1259 		}
1260 
1261 		data->u.timer.port = vcpu->arch.xen.timer_virq;
1262 		data->u.timer.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;
1263 		data->u.timer.expires_ns = vcpu->arch.xen.timer_expires;
1264 
1265 		/*
1266 		 * The hrtimer may trigger and raise the IRQ immediately,
1267 		 * while the returned state causes it to be set up and
1268 		 * raised again on the destination system after migration.
1269 		 * That's fine, as the guest won't even have had a chance
1270 		 * to run and handle the interrupt. Asserting an already
1271 		 * pending event channel is idempotent.
1272 		 */
1273 		if (vcpu->arch.xen.timer_expires)
1274 			hrtimer_start_expires(&vcpu->arch.xen.timer,
1275 					      HRTIMER_MODE_ABS_HARD);
1276 
1277 		r = 0;
1278 		break;
1279 
1280 	case KVM_XEN_VCPU_ATTR_TYPE_UPCALL_VECTOR:
1281 		data->u.vector = vcpu->arch.xen.upcall_vector;
1282 		r = 0;
1283 		break;
1284 
1285 	default:
1286 		break;
1287 	}
1288 
1289 	mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
1290 	return r;
1291 }
1292 
1293 int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
1294 {
1295 	struct kvm *kvm = vcpu->kvm;
1296 	u32 page_num = data & ~PAGE_MASK;
1297 	u64 page_addr = data & PAGE_MASK;
1298 	bool lm = is_long_mode(vcpu);
1299 	int r = 0;
1300 
1301 	mutex_lock(&kvm->arch.xen.xen_lock);
1302 	if (kvm->arch.xen.long_mode != lm) {
1303 		kvm->arch.xen.long_mode = lm;
1304 
1305 		/*
1306 		 * Re-initialize shared_info to put the wallclock in the
1307 		 * correct place.
1308 		 */
1309 		if (kvm->arch.xen.shinfo_cache.active &&
1310 		    kvm_xen_shared_info_init(kvm))
1311 			r = 1;
1312 	}
1313 	mutex_unlock(&kvm->arch.xen.xen_lock);
1314 
1315 	if (r)
1316 		return r;
1317 
1318 	/*
1319 	 * If Xen hypercall intercept is enabled, fill the hypercall
1320 	 * page with VMCALL/VMMCALL instructions since that's what
1321 	 * we catch. Else the VMM has provided the hypercall pages
1322 	 * with instructions of its own choosing, so use those.
1323 	 */
1324 	if (kvm_xen_hypercall_enabled(kvm)) {
1325 		u8 instructions[32];
1326 		int i;
1327 
1328 		if (page_num)
1329 			return 1;
1330 
1331 		/* mov imm32, %eax */
1332 		instructions[0] = 0xb8;
1333 
1334 		/* vmcall / vmmcall */
1335 		kvm_x86_call(patch_hypercall)(vcpu, instructions + 5);
1336 
1337 		/* ret */
1338 		instructions[8] = 0xc3;
1339 
1340 		/* int3 to pad */
1341 		memset(instructions + 9, 0xcc, sizeof(instructions) - 9);
1342 
1343 		for (i = 0; i < PAGE_SIZE / sizeof(instructions); i++) {
1344 			*(u32 *)&instructions[1] = i;
1345 			if (kvm_vcpu_write_guest(vcpu,
1346 						 page_addr + (i * sizeof(instructions)),
1347 						 instructions, sizeof(instructions)))
1348 				return 1;
1349 		}
1350 	} else {
1351 		/*
1352 		 * Note, truncation is a non-issue as 'lm' is guaranteed to be
1353 		 * false for a 32-bit kernel, i.e. when hva_t is only 4 bytes.
1354 		 */
1355 		hva_t blob_addr = lm ? kvm->arch.xen.hvm_config.blob_addr_64
1356 				     : kvm->arch.xen.hvm_config.blob_addr_32;
1357 		u8 blob_size = lm ? kvm->arch.xen.hvm_config.blob_size_64
1358 				  : kvm->arch.xen.hvm_config.blob_size_32;
1359 		u8 *page;
1360 		int ret;
1361 
1362 		if (page_num >= blob_size)
1363 			return 1;
1364 
1365 		blob_addr += page_num * PAGE_SIZE;
1366 
1367 		page = memdup_user((u8 __user *)blob_addr, PAGE_SIZE);
1368 		if (IS_ERR(page))
1369 			return PTR_ERR(page);
1370 
1371 		ret = kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE);
1372 		kfree(page);
1373 		if (ret)
1374 			return 1;
1375 	}
1376 	return 0;
1377 }
1378 
1379 int kvm_xen_hvm_config(struct kvm *kvm, struct kvm_xen_hvm_config *xhc)
1380 {
1381 	/* Only some feature flags need to be *enabled* by userspace */
1382 	u32 permitted_flags = KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
1383 		KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
1384 		KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE;
1385 	u32 old_flags;
1386 
1387 	if (xhc->flags & ~permitted_flags)
1388 		return -EINVAL;
1389 
1390 	/*
1391 	 * With hypercall interception the kernel generates its own
1392 	 * hypercall page so it must not be provided.
1393 	 */
1394 	if ((xhc->flags & KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL) &&
1395 	    (xhc->blob_addr_32 || xhc->blob_addr_64 ||
1396 	     xhc->blob_size_32 || xhc->blob_size_64))
1397 		return -EINVAL;
1398 
1399 	/*
1400 	 * Restrict the MSR to the range that is unofficially reserved for
1401 	 * synthetic, virtualization-defined MSRs, e.g. to prevent confusing
1402 	 * KVM by colliding with a real MSR that requires special handling.
1403 	 */
1404 	if (xhc->msr &&
1405 	    (xhc->msr < KVM_XEN_MSR_MIN_INDEX || xhc->msr > KVM_XEN_MSR_MAX_INDEX))
1406 		return -EINVAL;
1407 
1408 	mutex_lock(&kvm->arch.xen.xen_lock);
1409 
1410 	if (xhc->msr && !kvm->arch.xen.hvm_config.msr)
1411 		static_branch_inc(&kvm_xen_enabled.key);
1412 	else if (!xhc->msr && kvm->arch.xen.hvm_config.msr)
1413 		static_branch_slow_dec_deferred(&kvm_xen_enabled);
1414 
1415 	old_flags = kvm->arch.xen.hvm_config.flags;
1416 	memcpy(&kvm->arch.xen.hvm_config, xhc, sizeof(*xhc));
1417 
1418 	mutex_unlock(&kvm->arch.xen.xen_lock);
1419 
1420 	if ((old_flags ^ xhc->flags) & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
1421 		kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
1422 
1423 	return 0;
1424 }
1425 
1426 static int kvm_xen_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
1427 {
1428 	kvm_rax_write_raw(vcpu, result);
1429 	return kvm_skip_emulated_instruction(vcpu);
1430 }
1431 
1432 static int kvm_xen_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
1433 {
1434 	struct kvm_run *run = vcpu->run;
1435 
1436 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.xen.hypercall_rip)))
1437 		return 1;
1438 
1439 	return kvm_xen_hypercall_set_result(vcpu, run->xen.u.hcall.result);
1440 }
1441 
1442 static inline int max_evtchn_port(struct kvm *kvm)
1443 {
1444 	if (IS_ENABLED(CONFIG_64BIT) && kvm->arch.xen.long_mode)
1445 		return EVTCHN_2L_NR_CHANNELS;
1446 	else
1447 		return COMPAT_EVTCHN_2L_NR_CHANNELS;
1448 }
1449 
1450 static bool wait_pending_event(struct kvm_vcpu *vcpu, int nr_ports,
1451 			       evtchn_port_t *ports)
1452 {
1453 	struct kvm *kvm = vcpu->kvm;
1454 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
1455 	unsigned long *pending_bits;
1456 	unsigned long flags;
1457 	bool ret = true;
1458 	int idx, i;
1459 
1460 	idx = srcu_read_lock(&kvm->srcu);
1461 	read_lock_irqsave(&gpc->lock, flags);
1462 	if (!kvm_gpc_check(gpc, PAGE_SIZE))
1463 		goto out_rcu;
1464 
1465 	ret = false;
1466 	if (IS_ENABLED(CONFIG_64BIT) && kvm->arch.xen.long_mode) {
1467 		struct shared_info *shinfo = gpc->khva;
1468 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
1469 	} else {
1470 		struct compat_shared_info *shinfo = gpc->khva;
1471 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
1472 	}
1473 
1474 	for (i = 0; i < nr_ports; i++) {
1475 		if (test_bit(ports[i], pending_bits)) {
1476 			ret = true;
1477 			break;
1478 		}
1479 	}
1480 
1481  out_rcu:
1482 	read_unlock_irqrestore(&gpc->lock, flags);
1483 	srcu_read_unlock(&kvm->srcu, idx);
1484 
1485 	return ret;
1486 }
1487 
1488 static bool kvm_xen_schedop_poll(struct kvm_vcpu *vcpu, bool longmode,
1489 				 u64 param, u64 *r)
1490 {
1491 	struct sched_poll sched_poll;
1492 	evtchn_port_t port, *ports;
1493 	struct x86_exception e;
1494 	int i;
1495 
1496 	if (!lapic_in_kernel(vcpu) ||
1497 	    !(vcpu->kvm->arch.xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_EVTCHN_SEND))
1498 		return false;
1499 
1500 	if (IS_ENABLED(CONFIG_64BIT) && !longmode) {
1501 		struct compat_sched_poll sp32;
1502 
1503 		/* Sanity check that the compat struct definition is correct */
1504 		BUILD_BUG_ON(sizeof(sp32) != 16);
1505 
1506 		if (kvm_read_guest_virt(vcpu, param, &sp32, sizeof(sp32), &e)) {
1507 			*r = -EFAULT;
1508 			return true;
1509 		}
1510 
1511 		/*
1512 		 * This is a 32-bit pointer to an array of evtchn_port_t which
1513 		 * are uint32_t, so once it's converted no further compat
1514 		 * handling is needed.
1515 		 */
1516 		sched_poll.ports = (void *)(unsigned long)(sp32.ports);
1517 		sched_poll.nr_ports = sp32.nr_ports;
1518 		sched_poll.timeout = sp32.timeout;
1519 	} else {
1520 		if (kvm_read_guest_virt(vcpu, param, &sched_poll,
1521 					sizeof(sched_poll), &e)) {
1522 			*r = -EFAULT;
1523 			return true;
1524 		}
1525 	}
1526 
1527 	if (unlikely(sched_poll.nr_ports > 1)) {
1528 		/* Xen (unofficially) limits number of pollers to 128 */
1529 		if (sched_poll.nr_ports > 128) {
1530 			*r = -EINVAL;
1531 			return true;
1532 		}
1533 
1534 		ports = kmalloc_objs(*ports, sched_poll.nr_ports);
1535 		if (!ports) {
1536 			*r = -ENOMEM;
1537 			return true;
1538 		}
1539 	} else
1540 		ports = &port;
1541 
1542 	if (kvm_read_guest_virt(vcpu, (gva_t)sched_poll.ports, ports,
1543 				sched_poll.nr_ports * sizeof(*ports), &e)) {
1544 		*r = -EFAULT;
1545 		goto out;
1546 	}
1547 
1548 	for (i = 0; i < sched_poll.nr_ports; i++) {
1549 		if (ports[i] >= max_evtchn_port(vcpu->kvm)) {
1550 			*r = -EINVAL;
1551 			goto out;
1552 		}
1553 	}
1554 
1555 	if (sched_poll.nr_ports == 1)
1556 		vcpu->arch.xen.poll_evtchn = port;
1557 	else
1558 		vcpu->arch.xen.poll_evtchn = -1;
1559 
1560 	set_bit(vcpu->vcpu_idx, vcpu->kvm->arch.xen.poll_mask);
1561 
1562 	if (!wait_pending_event(vcpu, sched_poll.nr_ports, ports)) {
1563 		kvm_set_mp_state(vcpu, KVM_MP_STATE_HALTED);
1564 
1565 		if (sched_poll.timeout)
1566 			mod_timer(&vcpu->arch.xen.poll_timer,
1567 				  jiffies + nsecs_to_jiffies(sched_poll.timeout));
1568 
1569 		kvm_vcpu_halt(vcpu);
1570 
1571 		if (sched_poll.timeout)
1572 			timer_delete(&vcpu->arch.xen.poll_timer);
1573 
1574 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
1575 	}
1576 
1577 	vcpu->arch.xen.poll_evtchn = 0;
1578 	*r = 0;
1579 out:
1580 	/* Really, this is only needed in case of timeout */
1581 	clear_bit(vcpu->vcpu_idx, vcpu->kvm->arch.xen.poll_mask);
1582 
1583 	if (unlikely(sched_poll.nr_ports > 1))
1584 		kfree(ports);
1585 	return true;
1586 }
1587 
1588 static void cancel_evtchn_poll(struct timer_list *t)
1589 {
1590 	struct kvm_vcpu *vcpu = timer_container_of(vcpu, t,
1591 						   arch.xen.poll_timer);
1592 
1593 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1594 	kvm_vcpu_kick(vcpu);
1595 }
1596 
1597 static bool kvm_xen_hcall_sched_op(struct kvm_vcpu *vcpu, bool longmode,
1598 				   int cmd, u64 param, u64 *r)
1599 {
1600 	switch (cmd) {
1601 	case SCHEDOP_poll:
1602 		if (kvm_xen_schedop_poll(vcpu, longmode, param, r))
1603 			return true;
1604 		fallthrough;
1605 	case SCHEDOP_yield:
1606 		kvm_vcpu_on_spin(vcpu, true);
1607 		*r = 0;
1608 		return true;
1609 	default:
1610 		break;
1611 	}
1612 
1613 	return false;
1614 }
1615 
1616 struct compat_vcpu_set_singleshot_timer {
1617     uint64_t timeout_abs_ns;
1618     uint32_t flags;
1619 } __attribute__((packed));
1620 
1621 static bool kvm_xen_hcall_vcpu_op(struct kvm_vcpu *vcpu, bool longmode, int cmd,
1622 				  int vcpu_id, u64 param, u64 *r)
1623 {
1624 	struct vcpu_set_singleshot_timer oneshot;
1625 	struct x86_exception e;
1626 
1627 	if (cmd != VCPUOP_set_singleshot_timer &&
1628 	    cmd != VCPUOP_stop_singleshot_timer)
1629 		return false;
1630 
1631 	if (!kvm_xen_timer_enabled(vcpu))
1632 		return false;
1633 
1634 	if (vcpu->arch.xen.vcpu_id == XEN_VCPU_ID_INVALID)
1635 		return false;
1636 
1637 	/*
1638 	 * Reject the hypercall if the guest is trying to start/stop the timer
1639 	 * for a different vCPU.  Xen per-vCPU hypercalls take a target vCPU as
1640 	 * a common parameter, as all per-vCPU hypercalls *except* single-shot
1641 	 * timer updates can be cross-vCPU.
1642 	 */
1643 	if (vcpu->arch.xen.vcpu_id != vcpu_id) {
1644 		*r = -EINVAL;
1645 		return true;
1646 	}
1647 
1648 	if (cmd == VCPUOP_set_singleshot_timer) {
1649 		/*
1650 		 * The only difference for 32-bit compat is the 4 bytes of
1651 		 * padding after the interesting part of the structure. So
1652 		 * for a faithful emulation of Xen we have to *try* to copy
1653 		 * the padding and return -EFAULT if we can't. Otherwise we
1654 		 * might as well just have copied the 12-byte 32-bit struct.
1655 		 */
1656 		BUILD_BUG_ON(offsetof(struct compat_vcpu_set_singleshot_timer, timeout_abs_ns) !=
1657 			     offsetof(struct vcpu_set_singleshot_timer, timeout_abs_ns));
1658 		BUILD_BUG_ON(sizeof_field(struct compat_vcpu_set_singleshot_timer, timeout_abs_ns) !=
1659 			     sizeof_field(struct vcpu_set_singleshot_timer, timeout_abs_ns));
1660 		BUILD_BUG_ON(offsetof(struct compat_vcpu_set_singleshot_timer, flags) !=
1661 			     offsetof(struct vcpu_set_singleshot_timer, flags));
1662 		BUILD_BUG_ON(sizeof_field(struct compat_vcpu_set_singleshot_timer, flags) !=
1663 			     sizeof_field(struct vcpu_set_singleshot_timer, flags));
1664 
1665 		if (kvm_read_guest_virt(vcpu, param, &oneshot, longmode ? sizeof(oneshot) :
1666 					sizeof(struct compat_vcpu_set_singleshot_timer), &e)) {
1667 			*r = -EFAULT;
1668 			return true;
1669 		}
1670 
1671 		kvm_xen_start_timer(vcpu, oneshot.timeout_abs_ns, false);
1672 	} else {
1673 		kvm_xen_stop_timer(vcpu);
1674 	}
1675 
1676 	*r = 0;
1677 	return true;
1678 }
1679 
1680 static bool kvm_xen_hcall_set_timer_op(struct kvm_vcpu *vcpu, uint64_t timeout,
1681 				       u64 *r)
1682 {
1683 	if (!kvm_xen_timer_enabled(vcpu))
1684 		return false;
1685 
1686 	if (timeout)
1687 		kvm_xen_start_timer(vcpu, timeout, true);
1688 	else
1689 		kvm_xen_stop_timer(vcpu);
1690 
1691 	*r = 0;
1692 	return true;
1693 }
1694 
1695 int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
1696 {
1697 	bool longmode;
1698 	u64 input, params[6], r = -ENOSYS;
1699 	bool handled = false;
1700 	u8 cpl;
1701 
1702 	/* Hyper-V hypercalls get bit 31 set in EAX */
1703 	if ((kvm_rax_read_raw(vcpu) & 0x80000000) &&
1704 	    kvm_hv_hypercall_enabled(vcpu))
1705 		return kvm_hv_hypercall(vcpu);
1706 
1707 	longmode = is_64_bit_hypercall(vcpu);
1708 	if (!longmode) {
1709 		input = kvm_eax_read(vcpu);
1710 		params[0] = kvm_ebx_read(vcpu);
1711 		params[1] = kvm_ecx_read(vcpu);
1712 		params[2] = kvm_edx_read(vcpu);
1713 		params[3] = kvm_esi_read(vcpu);
1714 		params[4] = kvm_edi_read(vcpu);
1715 		params[5] = kvm_ebp_read(vcpu);
1716 	}
1717 	else {
1718 #ifdef CONFIG_X86_64
1719 		input = (u64)kvm_rax_read_raw(vcpu);
1720 		params[0] = (u64)kvm_rdi_read_raw(vcpu);
1721 		params[1] = (u64)kvm_rsi_read_raw(vcpu);
1722 		params[2] = (u64)kvm_rdx_read_raw(vcpu);
1723 		params[3] = (u64)kvm_r10_read_raw(vcpu);
1724 		params[4] = (u64)kvm_r8_read_raw(vcpu);
1725 		params[5] = (u64)kvm_r9_read_raw(vcpu);
1726 #else
1727 		KVM_BUG_ON(1, vcpu->kvm);
1728 		return -EIO;
1729 #endif
1730 	}
1731 	cpl = kvm_x86_call(get_cpl)(vcpu);
1732 	trace_kvm_xen_hypercall(cpl, input, params[0], params[1], params[2],
1733 				params[3], params[4], params[5]);
1734 
1735 	/*
1736 	 * Only allow hypercall acceleration for CPL0. The rare hypercalls that
1737 	 * are permitted in guest userspace can be handled by the VMM.
1738 	 */
1739 	if (unlikely(cpl > 0))
1740 		goto handle_in_userspace;
1741 
1742 	switch (input) {
1743 	case __HYPERVISOR_xen_version:
1744 		if (params[0] == XENVER_version && vcpu->kvm->arch.xen.xen_version) {
1745 			r = vcpu->kvm->arch.xen.xen_version;
1746 			handled = true;
1747 		}
1748 		break;
1749 	case __HYPERVISOR_event_channel_op:
1750 		if (params[0] == EVTCHNOP_send)
1751 			handled = kvm_xen_hcall_evtchn_send(vcpu, params[1], &r);
1752 		break;
1753 	case __HYPERVISOR_sched_op:
1754 		handled = kvm_xen_hcall_sched_op(vcpu, longmode, params[0],
1755 						 params[1], &r);
1756 		break;
1757 	case __HYPERVISOR_vcpu_op:
1758 		handled = kvm_xen_hcall_vcpu_op(vcpu, longmode, params[0], params[1],
1759 						params[2], &r);
1760 		break;
1761 	case __HYPERVISOR_set_timer_op: {
1762 		u64 timeout = params[0];
1763 		/* In 32-bit mode, the 64-bit timeout is in two 32-bit params. */
1764 		if (!longmode)
1765 			timeout |= params[1] << 32;
1766 		handled = kvm_xen_hcall_set_timer_op(vcpu, timeout, &r);
1767 		break;
1768 	}
1769 	default:
1770 		break;
1771 	}
1772 
1773 	if (handled)
1774 		return kvm_xen_hypercall_set_result(vcpu, r);
1775 
1776 handle_in_userspace:
1777 	vcpu->run->exit_reason = KVM_EXIT_XEN;
1778 	vcpu->run->xen.type = KVM_EXIT_XEN_HCALL;
1779 	vcpu->run->xen.u.hcall.longmode = longmode;
1780 	vcpu->run->xen.u.hcall.cpl = cpl;
1781 	vcpu->run->xen.u.hcall.input = input;
1782 	vcpu->run->xen.u.hcall.params[0] = params[0];
1783 	vcpu->run->xen.u.hcall.params[1] = params[1];
1784 	vcpu->run->xen.u.hcall.params[2] = params[2];
1785 	vcpu->run->xen.u.hcall.params[3] = params[3];
1786 	vcpu->run->xen.u.hcall.params[4] = params[4];
1787 	vcpu->run->xen.u.hcall.params[5] = params[5];
1788 	vcpu->arch.xen.hypercall_rip = kvm_get_linear_rip(vcpu);
1789 	vcpu->arch.complete_userspace_io =
1790 		kvm_xen_hypercall_complete_userspace;
1791 
1792 	return 0;
1793 }
1794 
1795 static void kvm_xen_check_poller(struct kvm_vcpu *vcpu, int port)
1796 {
1797 	int poll_evtchn = vcpu->arch.xen.poll_evtchn;
1798 
1799 	if ((poll_evtchn == port || poll_evtchn == -1) &&
1800 	    test_and_clear_bit(vcpu->vcpu_idx, vcpu->kvm->arch.xen.poll_mask)) {
1801 		kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1802 		kvm_vcpu_kick(vcpu);
1803 	}
1804 }
1805 
1806 /*
1807  * The return value from this function is propagated to kvm_set_irq() API,
1808  * so it returns:
1809  *  < 0   Interrupt was ignored (masked or not delivered for other reasons)
1810  *  = 0   Interrupt was coalesced (previous irq is still pending)
1811  *  > 0   Number of CPUs interrupt was delivered to
1812  *
1813  * It is also called directly from kvm_arch_set_irq_inatomic(), where the
1814  * only check on its return value is a comparison with -EWOULDBLOCK'.
1815  */
1816 int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
1817 {
1818 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
1819 	struct kvm_vcpu *vcpu;
1820 	unsigned long *pending_bits, *mask_bits;
1821 	unsigned long flags;
1822 	int port_word_bit;
1823 	bool kick_vcpu = false;
1824 	int vcpu_idx, idx, rc;
1825 
1826 	vcpu_idx = READ_ONCE(xe->vcpu_idx);
1827 	if (vcpu_idx >= 0)
1828 		vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1829 	else {
1830 		vcpu = kvm_get_vcpu_by_id(kvm, xe->vcpu_id);
1831 		if (!vcpu)
1832 			return -EINVAL;
1833 		WRITE_ONCE(xe->vcpu_idx, vcpu->vcpu_idx);
1834 	}
1835 
1836 	if (xe->port >= max_evtchn_port(kvm))
1837 		return -EINVAL;
1838 
1839 	rc = -EWOULDBLOCK;
1840 
1841 	idx = srcu_read_lock(&kvm->srcu);
1842 
1843 	read_lock_irqsave(&gpc->lock, flags);
1844 	if (!kvm_gpc_check(gpc, PAGE_SIZE))
1845 		goto out_rcu;
1846 
1847 	if (IS_ENABLED(CONFIG_64BIT) && kvm->arch.xen.long_mode) {
1848 		struct shared_info *shinfo = gpc->khva;
1849 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
1850 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
1851 		port_word_bit = xe->port / 64;
1852 	} else {
1853 		struct compat_shared_info *shinfo = gpc->khva;
1854 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
1855 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
1856 		port_word_bit = xe->port / 32;
1857 	}
1858 
1859 	/*
1860 	 * If this port wasn't already set, and if it isn't masked, then
1861 	 * we try to set the corresponding bit in the in-kernel shadow of
1862 	 * evtchn_pending_sel for the target vCPU. And if *that* wasn't
1863 	 * already set, then we kick the vCPU in question to write to the
1864 	 * *real* evtchn_pending_sel in its own guest vcpu_info struct.
1865 	 */
1866 	if (test_and_set_bit(xe->port, pending_bits)) {
1867 		rc = 0; /* It was already raised */
1868 	} else if (test_bit(xe->port, mask_bits)) {
1869 		rc = -ENOTCONN; /* Masked */
1870 		kvm_xen_check_poller(vcpu, xe->port);
1871 	} else {
1872 		rc = 1; /* Delivered to the bitmap in shared_info. */
1873 		/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */
1874 		read_unlock_irqrestore(&gpc->lock, flags);
1875 		gpc = &vcpu->arch.xen.vcpu_info_cache;
1876 
1877 		read_lock_irqsave(&gpc->lock, flags);
1878 		if (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
1879 			/*
1880 			 * Could not access the vcpu_info. Set the bit in-kernel
1881 			 * and prod the vCPU to deliver it for itself.
1882 			 */
1883 			if (!test_and_set_bit(port_word_bit, &vcpu->arch.xen.evtchn_pending_sel))
1884 				kick_vcpu = true;
1885 			goto out_rcu;
1886 		}
1887 
1888 		if (IS_ENABLED(CONFIG_64BIT) && kvm->arch.xen.long_mode) {
1889 			struct vcpu_info *vcpu_info = gpc->khva;
1890 			if (!test_and_set_bit(port_word_bit, &vcpu_info->evtchn_pending_sel)) {
1891 				WRITE_ONCE(vcpu_info->evtchn_upcall_pending, 1);
1892 				kick_vcpu = true;
1893 			}
1894 		} else {
1895 			struct compat_vcpu_info *vcpu_info = gpc->khva;
1896 			if (!test_and_set_bit(port_word_bit,
1897 					      (unsigned long *)&vcpu_info->evtchn_pending_sel)) {
1898 				WRITE_ONCE(vcpu_info->evtchn_upcall_pending, 1);
1899 				kick_vcpu = true;
1900 			}
1901 		}
1902 
1903 		/* For the per-vCPU lapic vector, deliver it as MSI. */
1904 		if (kick_vcpu && vcpu->arch.xen.upcall_vector) {
1905 			kvm_xen_inject_vcpu_vector(vcpu);
1906 			kick_vcpu = false;
1907 		}
1908 	}
1909 
1910  out_rcu:
1911 	read_unlock_irqrestore(&gpc->lock, flags);
1912 	srcu_read_unlock(&kvm->srcu, idx);
1913 
1914 	if (kick_vcpu) {
1915 		kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1916 		kvm_vcpu_kick(vcpu);
1917 	}
1918 
1919 	return rc;
1920 }
1921 
1922 static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
1923 {
1924 	bool mm_borrowed = false;
1925 	int rc;
1926 
1927 	rc = kvm_xen_set_evtchn_fast(xe, kvm);
1928 	if (rc != -EWOULDBLOCK)
1929 		return rc;
1930 
1931 	if (current->mm != kvm->mm) {
1932 		/*
1933 		 * If not on a thread which already belongs to this KVM,
1934 		 * we'd better be in the irqfd workqueue.
1935 		 */
1936 		if (WARN_ON_ONCE(current->mm))
1937 			return -EINVAL;
1938 
1939 		kthread_use_mm(kvm->mm);
1940 		mm_borrowed = true;
1941 	}
1942 
1943 	/*
1944 	 * It is theoretically possible for the page to be unmapped
1945 	 * and the MMU notifier to invalidate the shared_info before
1946 	 * we even get to use it. In that case, this looks like an
1947 	 * infinite loop. It was tempting to do it via the userspace
1948 	 * HVA instead... but that just *hides* the fact that it's
1949 	 * an infinite loop, because if a fault occurs and it waits
1950 	 * for the page to come back, it can *still* immediately
1951 	 * fault and have to wait again, repeatedly.
1952 	 *
1953 	 * Conversely, the page could also have been reinstated by
1954 	 * another thread before we even obtain the mutex above, so
1955 	 * check again *first* before remapping it.
1956 	 */
1957 	do {
1958 		struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
1959 		int idx;
1960 
1961 		rc = kvm_xen_set_evtchn_fast(xe, kvm);
1962 		if (rc != -EWOULDBLOCK)
1963 			break;
1964 
1965 		idx = srcu_read_lock(&kvm->srcu);
1966 		rc = kvm_gpc_refresh(gpc, PAGE_SIZE);
1967 		srcu_read_unlock(&kvm->srcu, idx);
1968 	} while(!rc);
1969 
1970 	if (mm_borrowed)
1971 		kthread_unuse_mm(kvm->mm);
1972 
1973 	return rc;
1974 }
1975 
1976 /* This is the version called from kvm_set_irq() as the .set function */
1977 static int evtchn_set_fn(struct kvm_kernel_irq_routing_entry *e, struct kvm *kvm,
1978 			 int irq_source_id, int level, bool line_status)
1979 {
1980 	if (!level)
1981 		return -EINVAL;
1982 
1983 	return kvm_xen_set_evtchn(&e->xen_evtchn, kvm);
1984 }
1985 
1986 /*
1987  * Set up an event channel interrupt from the KVM IRQ routing table.
1988  * Used for e.g. PIRQ from passed through physical devices.
1989  */
1990 int kvm_xen_setup_evtchn(struct kvm *kvm,
1991 			 struct kvm_kernel_irq_routing_entry *e,
1992 			 const struct kvm_irq_routing_entry *ue)
1993 
1994 {
1995 	struct kvm_vcpu *vcpu;
1996 
1997 	/*
1998 	 * Don't check for the port being within range of max_evtchn_port().
1999 	 * Userspace can configure what ever targets it likes; events just won't
2000 	 * be delivered if/while the target is invalid, just like userspace can
2001 	 * configure MSIs which target non-existent APICs.
2002 	 *
2003 	 * This allow on Live Migration and Live Update, the IRQ routing table
2004 	 * can be restored *independently* of other things like creating vCPUs,
2005 	 * without imposing an ordering dependency on userspace.  In this
2006 	 * particular case, the problematic ordering would be with setting the
2007 	 * Xen 'long mode' flag, which changes max_evtchn_port() to allow 4096
2008 	 * instead of 1024 event channels.
2009 	 */
2010 
2011 	/* We only support 2 level event channels for now */
2012 	if (ue->u.xen_evtchn.priority != KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL)
2013 		return -EINVAL;
2014 
2015 	/*
2016 	 * Xen gives us interesting mappings from vCPU index to APIC ID,
2017 	 * which means kvm_get_vcpu_by_id() has to iterate over all vCPUs
2018 	 * to find it. Do that once at setup time, instead of every time.
2019 	 * But beware that on live update / live migration, the routing
2020 	 * table might be reinstated before the vCPU threads have finished
2021 	 * recreating their vCPUs.
2022 	 */
2023 	vcpu = kvm_get_vcpu_by_id(kvm, ue->u.xen_evtchn.vcpu);
2024 	if (vcpu)
2025 		e->xen_evtchn.vcpu_idx = vcpu->vcpu_idx;
2026 	else
2027 		e->xen_evtchn.vcpu_idx = -1;
2028 
2029 	e->xen_evtchn.port = ue->u.xen_evtchn.port;
2030 	e->xen_evtchn.vcpu_id = ue->u.xen_evtchn.vcpu;
2031 	e->xen_evtchn.priority = ue->u.xen_evtchn.priority;
2032 	e->set = evtchn_set_fn;
2033 
2034 	return 0;
2035 }
2036 
2037 /*
2038  * Explicit event sending from userspace with KVM_XEN_HVM_EVTCHN_SEND ioctl.
2039  */
2040 int kvm_xen_hvm_evtchn_send(struct kvm *kvm, struct kvm_irq_routing_xen_evtchn *uxe)
2041 {
2042 	struct kvm_xen_evtchn e;
2043 	int ret;
2044 
2045 	if (!uxe->port || uxe->port >= max_evtchn_port(kvm))
2046 		return -EINVAL;
2047 
2048 	/* We only support 2 level event channels for now */
2049 	if (uxe->priority != KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL)
2050 		return -EINVAL;
2051 
2052 	e.port = uxe->port;
2053 	e.vcpu_id = uxe->vcpu;
2054 	e.vcpu_idx = -1;
2055 	e.priority = uxe->priority;
2056 
2057 	ret = kvm_xen_set_evtchn(&e, kvm);
2058 
2059 	/*
2060 	 * None of that 'return 1 if it actually got delivered' nonsense.
2061 	 * We don't care if it was masked (-ENOTCONN) either.
2062 	 */
2063 	if (ret > 0 || ret == -ENOTCONN)
2064 		ret = 0;
2065 
2066 	return ret;
2067 }
2068 
2069 /*
2070  * Support for *outbound* event channel events via the EVTCHNOP_send hypercall.
2071  */
2072 struct evtchnfd {
2073 	u32 send_port;
2074 	u32 type;
2075 	union {
2076 		struct kvm_xen_evtchn port;
2077 		struct {
2078 			u32 port; /* zero */
2079 			struct eventfd_ctx *ctx;
2080 		} eventfd;
2081 	} deliver;
2082 };
2083 
2084 /*
2085  * Update target vCPU or priority for a registered sending channel.
2086  */
2087 static int kvm_xen_eventfd_update(struct kvm *kvm,
2088 				  struct kvm_xen_hvm_attr *data)
2089 {
2090 	u32 port = data->u.evtchn.send_port;
2091 	struct evtchnfd *evtchnfd;
2092 	int ret;
2093 
2094 	/* Protect writes to evtchnfd as well as the idr lookup.  */
2095 	mutex_lock(&kvm->arch.xen.xen_lock);
2096 	evtchnfd = idr_find(&kvm->arch.xen.evtchn_ports, port);
2097 
2098 	ret = -ENOENT;
2099 	if (!evtchnfd)
2100 		goto out_unlock;
2101 
2102 	/* For an UPDATE, nothing may change except the priority/vcpu */
2103 	ret = -EINVAL;
2104 	if (evtchnfd->type != data->u.evtchn.type)
2105 		goto out_unlock;
2106 
2107 	/*
2108 	 * Port cannot change, and if it's zero that was an eventfd
2109 	 * which can't be changed either.
2110 	 */
2111 	if (!evtchnfd->deliver.port.port ||
2112 	    evtchnfd->deliver.port.port != data->u.evtchn.deliver.port.port)
2113 		goto out_unlock;
2114 
2115 	/* We only support 2 level event channels for now */
2116 	if (data->u.evtchn.deliver.port.priority != KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL)
2117 		goto out_unlock;
2118 
2119 	evtchnfd->deliver.port.priority = data->u.evtchn.deliver.port.priority;
2120 	if (evtchnfd->deliver.port.vcpu_id != data->u.evtchn.deliver.port.vcpu) {
2121 		evtchnfd->deliver.port.vcpu_id = data->u.evtchn.deliver.port.vcpu;
2122 		evtchnfd->deliver.port.vcpu_idx = -1;
2123 	}
2124 	ret = 0;
2125 out_unlock:
2126 	mutex_unlock(&kvm->arch.xen.xen_lock);
2127 	return ret;
2128 }
2129 
2130 /*
2131  * Configure the target (eventfd or local port delivery) for sending on
2132  * a given event channel.
2133  */
2134 static int kvm_xen_eventfd_assign(struct kvm *kvm,
2135 				  struct kvm_xen_hvm_attr *data)
2136 {
2137 	u32 port = data->u.evtchn.send_port;
2138 	struct eventfd_ctx *eventfd = NULL;
2139 	struct evtchnfd *evtchnfd;
2140 	int ret = -EINVAL;
2141 
2142 	evtchnfd = kzalloc_obj(struct evtchnfd);
2143 	if (!evtchnfd)
2144 		return -ENOMEM;
2145 
2146 	switch(data->u.evtchn.type) {
2147 	case EVTCHNSTAT_ipi:
2148 		/* IPI  must map back to the same port# */
2149 		if (data->u.evtchn.deliver.port.port != data->u.evtchn.send_port)
2150 			goto out_noeventfd; /* -EINVAL */
2151 		break;
2152 
2153 	case EVTCHNSTAT_interdomain:
2154 		if (data->u.evtchn.deliver.port.port) {
2155 			if (data->u.evtchn.deliver.port.port >= max_evtchn_port(kvm))
2156 				goto out_noeventfd; /* -EINVAL */
2157 		} else {
2158 			eventfd = eventfd_ctx_fdget(data->u.evtchn.deliver.eventfd.fd);
2159 			if (IS_ERR(eventfd)) {
2160 				ret = PTR_ERR(eventfd);
2161 				goto out_noeventfd;
2162 			}
2163 		}
2164 		break;
2165 
2166 	case EVTCHNSTAT_virq:
2167 	case EVTCHNSTAT_closed:
2168 	case EVTCHNSTAT_unbound:
2169 	case EVTCHNSTAT_pirq:
2170 	default: /* Unknown event channel type */
2171 		goto out; /* -EINVAL */
2172 	}
2173 
2174 	evtchnfd->send_port = data->u.evtchn.send_port;
2175 	evtchnfd->type = data->u.evtchn.type;
2176 	if (eventfd) {
2177 		evtchnfd->deliver.eventfd.ctx = eventfd;
2178 	} else {
2179 		/* We only support 2 level event channels for now */
2180 		if (data->u.evtchn.deliver.port.priority != KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL)
2181 			goto out; /* -EINVAL; */
2182 
2183 		evtchnfd->deliver.port.port = data->u.evtchn.deliver.port.port;
2184 		evtchnfd->deliver.port.vcpu_id = data->u.evtchn.deliver.port.vcpu;
2185 		evtchnfd->deliver.port.vcpu_idx = -1;
2186 		evtchnfd->deliver.port.priority = data->u.evtchn.deliver.port.priority;
2187 	}
2188 
2189 	mutex_lock(&kvm->arch.xen.xen_lock);
2190 	ret = idr_alloc(&kvm->arch.xen.evtchn_ports, evtchnfd, port, port + 1,
2191 			GFP_KERNEL);
2192 	mutex_unlock(&kvm->arch.xen.xen_lock);
2193 	if (ret >= 0)
2194 		return 0;
2195 
2196 	if (ret == -ENOSPC)
2197 		ret = -EEXIST;
2198 out:
2199 	if (eventfd)
2200 		eventfd_ctx_put(eventfd);
2201 out_noeventfd:
2202 	kfree(evtchnfd);
2203 	return ret;
2204 }
2205 
2206 static int kvm_xen_eventfd_deassign(struct kvm *kvm, u32 port)
2207 {
2208 	struct evtchnfd *evtchnfd;
2209 
2210 	mutex_lock(&kvm->arch.xen.xen_lock);
2211 	evtchnfd = idr_remove(&kvm->arch.xen.evtchn_ports, port);
2212 	mutex_unlock(&kvm->arch.xen.xen_lock);
2213 
2214 	if (!evtchnfd)
2215 		return -ENOENT;
2216 
2217 	synchronize_srcu(&kvm->srcu);
2218 	if (!evtchnfd->deliver.port.port)
2219 		eventfd_ctx_put(evtchnfd->deliver.eventfd.ctx);
2220 	kfree(evtchnfd);
2221 	return 0;
2222 }
2223 
2224 static int kvm_xen_eventfd_reset(struct kvm *kvm)
2225 {
2226 	struct evtchnfd *evtchnfd, **all_evtchnfds;
2227 	int i;
2228 	int n = 0;
2229 
2230 	mutex_lock(&kvm->arch.xen.xen_lock);
2231 
2232 	/*
2233 	 * Because synchronize_srcu() cannot be called inside the
2234 	 * critical section, first collect all the evtchnfd objects
2235 	 * in an array as they are removed from evtchn_ports.
2236 	 */
2237 	idr_for_each_entry(&kvm->arch.xen.evtchn_ports, evtchnfd, i)
2238 		n++;
2239 
2240 	all_evtchnfds = kmalloc_objs(struct evtchnfd *, n);
2241 	if (!all_evtchnfds) {
2242 		mutex_unlock(&kvm->arch.xen.xen_lock);
2243 		return -ENOMEM;
2244 	}
2245 
2246 	n = 0;
2247 	idr_for_each_entry(&kvm->arch.xen.evtchn_ports, evtchnfd, i) {
2248 		all_evtchnfds[n++] = evtchnfd;
2249 		idr_remove(&kvm->arch.xen.evtchn_ports, evtchnfd->send_port);
2250 	}
2251 	mutex_unlock(&kvm->arch.xen.xen_lock);
2252 
2253 	synchronize_srcu(&kvm->srcu);
2254 
2255 	while (n--) {
2256 		evtchnfd = all_evtchnfds[n];
2257 		if (!evtchnfd->deliver.port.port)
2258 			eventfd_ctx_put(evtchnfd->deliver.eventfd.ctx);
2259 		kfree(evtchnfd);
2260 	}
2261 	kfree(all_evtchnfds);
2262 
2263 	return 0;
2264 }
2265 
2266 static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
2267 {
2268 	u32 port = data->u.evtchn.send_port;
2269 
2270 	if (data->u.evtchn.flags == KVM_XEN_EVTCHN_RESET)
2271 		return kvm_xen_eventfd_reset(kvm);
2272 
2273 	if (!port || port >= max_evtchn_port(kvm))
2274 		return -EINVAL;
2275 
2276 	if (data->u.evtchn.flags == KVM_XEN_EVTCHN_DEASSIGN)
2277 		return kvm_xen_eventfd_deassign(kvm, port);
2278 	if (data->u.evtchn.flags == KVM_XEN_EVTCHN_UPDATE)
2279 		return kvm_xen_eventfd_update(kvm, data);
2280 	if (data->u.evtchn.flags)
2281 		return -EINVAL;
2282 
2283 	return kvm_xen_eventfd_assign(kvm, data);
2284 }
2285 
2286 static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
2287 {
2288 	struct evtchnfd *evtchnfd;
2289 	struct evtchn_send send;
2290 	struct x86_exception e;
2291 
2292 	/* Sanity check: this structure is the same for 32-bit and 64-bit */
2293 	BUILD_BUG_ON(sizeof(send) != 4);
2294 	if (kvm_read_guest_virt(vcpu, param, &send, sizeof(send), &e)) {
2295 		*r = -EFAULT;
2296 		return true;
2297 	}
2298 
2299 	/*
2300 	 * evtchnfd is protected by kvm->srcu; the idr lookup instead
2301 	 * is protected by RCU.
2302 	 */
2303 	rcu_read_lock();
2304 	evtchnfd = idr_find(&vcpu->kvm->arch.xen.evtchn_ports, send.port);
2305 	rcu_read_unlock();
2306 	if (!evtchnfd)
2307 		return false;
2308 
2309 	if (evtchnfd->deliver.port.port) {
2310 		int ret = kvm_xen_set_evtchn(&evtchnfd->deliver.port, vcpu->kvm);
2311 		if (ret < 0 && ret != -ENOTCONN)
2312 			return false;
2313 	} else {
2314 		eventfd_signal(evtchnfd->deliver.eventfd.ctx);
2315 	}
2316 
2317 	*r = 0;
2318 	return true;
2319 }
2320 
2321 void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)
2322 {
2323 	vcpu->arch.xen.vcpu_id = XEN_VCPU_ID_INVALID;
2324 	vcpu->arch.xen.poll_evtchn = 0;
2325 
2326 	timer_setup(&vcpu->arch.xen.poll_timer, cancel_evtchn_poll, 0);
2327 	hrtimer_setup(&vcpu->arch.xen.timer, xen_timer_callback, CLOCK_MONOTONIC,
2328 		      HRTIMER_MODE_ABS_HARD);
2329 
2330 	kvm_gpc_init(&vcpu->arch.xen.runstate_cache, vcpu->kvm);
2331 	kvm_gpc_init(&vcpu->arch.xen.runstate2_cache, vcpu->kvm);
2332 	kvm_gpc_init(&vcpu->arch.xen.vcpu_info_cache, vcpu->kvm);
2333 	kvm_gpc_init(&vcpu->arch.xen.vcpu_time_info_cache, vcpu->kvm);
2334 }
2335 
2336 void kvm_xen_destroy_vcpu(struct kvm_vcpu *vcpu)
2337 {
2338 	if (kvm_xen_timer_enabled(vcpu))
2339 		kvm_xen_stop_timer(vcpu);
2340 
2341 	kvm_gpc_deactivate(&vcpu->arch.xen.runstate_cache);
2342 	kvm_gpc_deactivate(&vcpu->arch.xen.runstate2_cache);
2343 	kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
2344 	kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_time_info_cache);
2345 
2346 	timer_delete_sync(&vcpu->arch.xen.poll_timer);
2347 }
2348 
2349 void kvm_xen_init_vm(struct kvm *kvm)
2350 {
2351 	mutex_init(&kvm->arch.xen.xen_lock);
2352 	idr_init(&kvm->arch.xen.evtchn_ports);
2353 	kvm_gpc_init(&kvm->arch.xen.shinfo_cache, kvm);
2354 }
2355 
2356 void kvm_xen_destroy_vm(struct kvm *kvm)
2357 {
2358 	struct evtchnfd *evtchnfd;
2359 	int i;
2360 
2361 	kvm_gpc_deactivate(&kvm->arch.xen.shinfo_cache);
2362 
2363 	idr_for_each_entry(&kvm->arch.xen.evtchn_ports, evtchnfd, i) {
2364 		if (!evtchnfd->deliver.port.port)
2365 			eventfd_ctx_put(evtchnfd->deliver.eventfd.ctx);
2366 		kfree(evtchnfd);
2367 	}
2368 	idr_destroy(&kvm->arch.xen.evtchn_ports);
2369 
2370 	if (kvm->arch.xen.hvm_config.msr)
2371 		static_branch_slow_dec_deferred(&kvm_xen_enabled);
2372 }
2373