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