xref: /linux/arch/x86/xen/enlighten_pv.c (revision 4cff5c05e076d2ee4e34122aa956b84a2eaac587)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Core of Xen paravirt_ops implementation.
4  *
5  * This file contains the xen_paravirt_ops structure itself, and the
6  * implementations for:
7  * - privileged instructions
8  * - interrupt flags
9  * - segment operations
10  * - booting and setup
11  *
12  * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
13  */
14 
15 #include <linux/cpu.h>
16 #include <linux/kernel.h>
17 #include <linux/init.h>
18 #include <linux/smp.h>
19 #include <linux/preempt.h>
20 #include <linux/hardirq.h>
21 #include <linux/percpu.h>
22 #include <linux/delay.h>
23 #include <linux/start_kernel.h>
24 #include <linux/sched.h>
25 #include <linux/kprobes.h>
26 #include <linux/kstrtox.h>
27 #include <linux/memblock.h>
28 #include <linux/export.h>
29 #include <linux/mm.h>
30 #include <linux/page-flags.h>
31 #include <linux/pci.h>
32 #include <linux/gfp.h>
33 #include <linux/edd.h>
34 #include <linux/reboot.h>
35 #include <linux/virtio_anchor.h>
36 #include <linux/stackprotector.h>
37 
38 #include <xen/xen.h>
39 #include <xen/events.h>
40 #include <xen/interface/xen.h>
41 #include <xen/interface/version.h>
42 #include <xen/interface/physdev.h>
43 #include <xen/interface/vcpu.h>
44 #include <xen/interface/memory.h>
45 #include <xen/interface/nmi.h>
46 #include <xen/interface/xen-mca.h>
47 #include <xen/features.h>
48 #include <xen/page.h>
49 #include <xen/hvc-console.h>
50 #include <xen/acpi.h>
51 
52 #include <asm/cpuid/api.h>
53 #include <asm/paravirt.h>
54 #include <asm/apic.h>
55 #include <asm/page.h>
56 #include <asm/xen/pci.h>
57 #include <asm/xen/hypercall.h>
58 #include <asm/xen/hypervisor.h>
59 #include <asm/xen/cpuid.h>
60 #include <asm/fixmap.h>
61 #include <asm/processor.h>
62 #include <asm/proto.h>
63 #include <asm/msr-index.h>
64 #include <asm/msr.h>
65 #include <asm/traps.h>
66 #include <asm/setup.h>
67 #include <asm/desc.h>
68 #include <asm/pgalloc.h>
69 #include <asm/tlbflush.h>
70 #include <asm/reboot.h>
71 #include <asm/hypervisor.h>
72 #include <asm/mach_traps.h>
73 #include <asm/mtrr.h>
74 #include <asm/mwait.h>
75 #include <asm/pci_x86.h>
76 #include <asm/cpu.h>
77 #include <asm/irq_stack.h>
78 #ifdef CONFIG_X86_IOPL_IOPERM
79 #include <asm/io_bitmap.h>
80 #endif
81 
82 #ifdef CONFIG_ACPI
83 #include <linux/acpi.h>
84 #include <asm/acpi.h>
85 #include <acpi/proc_cap_intel.h>
86 #include <acpi/processor.h>
87 #include <xen/interface/platform.h>
88 #endif
89 
90 #include "xen-ops.h"
91 
92 #include "../kernel/cpu/cpu.h" /* get_cpu_cap() */
93 
94 void *xen_initial_gdt;
95 
96 static int xen_cpu_up_prepare_pv(unsigned int cpu);
97 static int xen_cpu_dead_pv(unsigned int cpu);
98 
99 #ifndef CONFIG_PREEMPTION
100 /*
101  * Some hypercalls issued by the toolstack can take many 10s of
102  * seconds. Allow tasks running hypercalls via the privcmd driver to
103  * be voluntarily preempted even if full kernel preemption is
104  * disabled.
105  *
106  * Such preemptible hypercalls are bracketed by
107  * xen_preemptible_hcall_begin() and xen_preemptible_hcall_end()
108  * calls.
109  */
110 DEFINE_PER_CPU(bool, xen_in_preemptible_hcall);
111 EXPORT_PER_CPU_SYMBOL_GPL(xen_in_preemptible_hcall);
112 
113 /*
114  * In case of scheduling the flag must be cleared and restored after
115  * returning from schedule as the task might move to a different CPU.
116  */
117 static __always_inline bool get_and_clear_inhcall(void)
118 {
119 	bool inhcall = __this_cpu_read(xen_in_preemptible_hcall);
120 
121 	__this_cpu_write(xen_in_preemptible_hcall, false);
122 	return inhcall;
123 }
124 
125 static __always_inline void restore_inhcall(bool inhcall)
126 {
127 	__this_cpu_write(xen_in_preemptible_hcall, inhcall);
128 }
129 
130 #else
131 
132 static __always_inline bool get_and_clear_inhcall(void) { return false; }
133 static __always_inline void restore_inhcall(bool inhcall) { }
134 
135 #endif
136 
137 struct tls_descs {
138 	struct desc_struct desc[3];
139 };
140 
141 DEFINE_PER_CPU(enum xen_lazy_mode, xen_lazy_mode) = XEN_LAZY_NONE;
142 
143 enum xen_lazy_mode xen_get_lazy_mode(void)
144 {
145 	if (in_interrupt())
146 		return XEN_LAZY_NONE;
147 
148 	return this_cpu_read(xen_lazy_mode);
149 }
150 
151 /*
152  * Updating the 3 TLS descriptors in the GDT on every task switch is
153  * surprisingly expensive so we avoid updating them if they haven't
154  * changed.  Since Xen writes different descriptors than the one
155  * passed in the update_descriptor hypercall we keep shadow copies to
156  * compare against.
157  */
158 static DEFINE_PER_CPU(struct tls_descs, shadow_tls_desc);
159 
160 static __read_mostly bool xen_msr_safe = IS_ENABLED(CONFIG_XEN_PV_MSR_SAFE);
161 
162 static int __init parse_xen_msr_safe(char *str)
163 {
164 	if (str)
165 		return kstrtobool(str, &xen_msr_safe);
166 	return -EINVAL;
167 }
168 early_param("xen_msr_safe", parse_xen_msr_safe);
169 
170 /* Get MTRR settings from Xen and put them into mtrr_state. */
171 static void __init xen_set_mtrr_data(void)
172 {
173 #ifdef CONFIG_MTRR
174 	struct xen_platform_op op = {
175 		.cmd = XENPF_read_memtype,
176 		.interface_version = XENPF_INTERFACE_VERSION,
177 	};
178 	unsigned int reg;
179 	unsigned long mask;
180 	uint32_t eax, width;
181 	static struct mtrr_var_range var[MTRR_MAX_VAR_RANGES] __initdata;
182 
183 	/* Get physical address width (only 64-bit cpus supported). */
184 	width = 36;
185 	eax = cpuid_eax(0x80000000);
186 	if ((eax >> 16) == 0x8000 && eax >= 0x80000008) {
187 		eax = cpuid_eax(0x80000008);
188 		width = eax & 0xff;
189 	}
190 
191 	for (reg = 0; reg < MTRR_MAX_VAR_RANGES; reg++) {
192 		op.u.read_memtype.reg = reg;
193 		if (HYPERVISOR_platform_op(&op))
194 			break;
195 
196 		/*
197 		 * Only called in dom0, which has all RAM PFNs mapped at
198 		 * RAM MFNs, and all PCI space etc. is identity mapped.
199 		 * This means we can treat MFN == PFN regarding MTRR settings.
200 		 */
201 		var[reg].base_lo = op.u.read_memtype.type;
202 		var[reg].base_lo |= op.u.read_memtype.mfn << PAGE_SHIFT;
203 		var[reg].base_hi = op.u.read_memtype.mfn >> (32 - PAGE_SHIFT);
204 		mask = ~((op.u.read_memtype.nr_mfns << PAGE_SHIFT) - 1);
205 		mask &= (1UL << width) - 1;
206 		if (mask)
207 			mask |= MTRR_PHYSMASK_V;
208 		var[reg].mask_lo = mask;
209 		var[reg].mask_hi = mask >> 32;
210 	}
211 
212 	/* Only overwrite MTRR state if any MTRR could be got from Xen. */
213 	if (reg)
214 		guest_force_mtrr_state(var, reg, MTRR_TYPE_UNCACHABLE);
215 #endif
216 }
217 
218 static void __init xen_pv_init_platform(void)
219 {
220 	/* PV guests can't operate virtio devices without grants. */
221 	if (IS_ENABLED(CONFIG_XEN_VIRTIO))
222 		virtio_set_mem_acc_cb(xen_virtio_restricted_mem_acc);
223 
224 	populate_extra_pte(fix_to_virt(FIX_PARAVIRT_BOOTMAP));
225 
226 	set_fixmap(FIX_PARAVIRT_BOOTMAP, xen_start_info->shared_info);
227 	HYPERVISOR_shared_info = (void *)fix_to_virt(FIX_PARAVIRT_BOOTMAP);
228 
229 	/* xen clock uses per-cpu vcpu_info, need to init it for boot cpu */
230 	xen_vcpu_info_reset(0);
231 
232 	/* pvclock is in shared info area */
233 	xen_init_time_ops();
234 
235 	if (xen_initial_domain())
236 		xen_set_mtrr_data();
237 	else
238 		guest_force_mtrr_state(NULL, 0, MTRR_TYPE_WRBACK);
239 
240 	/* Adjust nr_cpu_ids before "enumeration" happens */
241 	xen_smp_count_cpus();
242 }
243 
244 static void __init xen_pv_guest_late_init(void)
245 {
246 #ifndef CONFIG_SMP
247 	/* Setup shared vcpu info for non-smp configurations */
248 	xen_setup_vcpu_info_placement();
249 #endif
250 }
251 
252 static __read_mostly unsigned int cpuid_leaf5_ecx_val;
253 static __read_mostly unsigned int cpuid_leaf5_edx_val;
254 
255 static void xen_cpuid(unsigned int *ax, unsigned int *bx,
256 		      unsigned int *cx, unsigned int *dx)
257 {
258 	unsigned int maskebx = ~0;
259 	unsigned int or_ebx = 0;
260 
261 	/*
262 	 * Mask out inconvenient features, to try and disable as many
263 	 * unsupported kernel subsystems as possible.
264 	 */
265 	switch (*ax) {
266 	case 0x1:
267 		/* Replace initial APIC ID in bits 24-31 of EBX. */
268 		/* See xen_pv_smp_config() for related topology preparations. */
269 		maskebx = 0x00ffffff;
270 		or_ebx = smp_processor_id() << 24;
271 		break;
272 
273 	case CPUID_LEAF_MWAIT:
274 		/* Synthesize the values.. */
275 		*ax = 0;
276 		*bx = 0;
277 		*cx = cpuid_leaf5_ecx_val;
278 		*dx = cpuid_leaf5_edx_val;
279 		return;
280 
281 	case 0xb:
282 		/* Suppress extended topology stuff */
283 		maskebx = 0;
284 		break;
285 	}
286 
287 	asm(XEN_EMULATE_PREFIX "cpuid"
288 		: "=a" (*ax),
289 		  "=b" (*bx),
290 		  "=c" (*cx),
291 		  "=d" (*dx)
292 		: "0" (*ax), "2" (*cx));
293 
294 	*bx &= maskebx;
295 	*bx |= or_ebx;
296 }
297 
298 static bool __init xen_check_mwait(void)
299 {
300 #ifdef CONFIG_ACPI
301 	struct xen_platform_op op = {
302 		.cmd			= XENPF_set_processor_pminfo,
303 		.u.set_pminfo.id	= -1,
304 		.u.set_pminfo.type	= XEN_PM_PDC,
305 	};
306 	uint32_t buf[3];
307 	unsigned int ax, bx, cx, dx;
308 	unsigned int mwait_mask;
309 
310 	/* We need to determine whether it is OK to expose the MWAIT
311 	 * capability to the kernel to harvest deeper than C3 states from ACPI
312 	 * _CST using the processor_harvest_xen.c module. For this to work, we
313 	 * need to gather the MWAIT_LEAF values (which the cstate.c code
314 	 * checks against). The hypervisor won't expose the MWAIT flag because
315 	 * it would break backwards compatibility; so we will find out directly
316 	 * from the hardware and hypercall.
317 	 */
318 	if (!xen_initial_domain())
319 		return false;
320 
321 	/*
322 	 * When running under platform earlier than Xen4.2, do not expose
323 	 * mwait, to avoid the risk of loading native acpi pad driver
324 	 */
325 	if (!xen_running_on_version_or_later(4, 2))
326 		return false;
327 
328 	ax = 1;
329 	cx = 0;
330 
331 	native_cpuid(&ax, &bx, &cx, &dx);
332 
333 	mwait_mask = (1 << (X86_FEATURE_EST % 32)) |
334 		     (1 << (X86_FEATURE_MWAIT % 32));
335 
336 	if ((cx & mwait_mask) != mwait_mask)
337 		return false;
338 
339 	/* We need to emulate the MWAIT_LEAF and for that we need both
340 	 * ecx and edx. The hypercall provides only partial information.
341 	 */
342 
343 	ax = CPUID_LEAF_MWAIT;
344 	bx = 0;
345 	cx = 0;
346 	dx = 0;
347 
348 	native_cpuid(&ax, &bx, &cx, &dx);
349 
350 	/* Ask the Hypervisor whether to clear ACPI_PROC_CAP_C_C2C3_FFH. If so,
351 	 * don't expose MWAIT_LEAF and let ACPI pick the IOPORT version of C3.
352 	 */
353 	buf[0] = ACPI_PDC_REVISION_ID;
354 	buf[1] = 1;
355 	buf[2] = (ACPI_PROC_CAP_C_CAPABILITY_SMP | ACPI_PROC_CAP_EST_CAPABILITY_SWSMP);
356 
357 	set_xen_guest_handle(op.u.set_pminfo.pdc, buf);
358 
359 	if ((HYPERVISOR_platform_op(&op) == 0) &&
360 	    (buf[2] & (ACPI_PROC_CAP_C_C1_FFH | ACPI_PROC_CAP_C_C2C3_FFH))) {
361 		cpuid_leaf5_ecx_val = cx;
362 		cpuid_leaf5_edx_val = dx;
363 	}
364 	return true;
365 #else
366 	return false;
367 #endif
368 }
369 
370 static bool __init xen_check_xsave(void)
371 {
372 	unsigned int cx, xsave_mask;
373 
374 	cx = cpuid_ecx(1);
375 
376 	xsave_mask = (1 << (X86_FEATURE_XSAVE % 32)) |
377 		     (1 << (X86_FEATURE_OSXSAVE % 32));
378 
379 	/* Xen will set CR4.OSXSAVE if supported and not disabled by force */
380 	return (cx & xsave_mask) == xsave_mask;
381 }
382 
383 static void __init xen_init_capabilities(void)
384 {
385 	setup_clear_cpu_cap(X86_FEATURE_DCA);
386 	setup_clear_cpu_cap(X86_FEATURE_APERFMPERF);
387 	setup_clear_cpu_cap(X86_FEATURE_MTRR);
388 	setup_clear_cpu_cap(X86_FEATURE_ACC);
389 	setup_clear_cpu_cap(X86_FEATURE_X2APIC);
390 	setup_clear_cpu_cap(X86_FEATURE_SME);
391 	setup_clear_cpu_cap(X86_FEATURE_LKGS);
392 
393 	/*
394 	 * Xen PV would need some work to support PCID: CR3 handling as well
395 	 * as xen_flush_tlb_others() would need updating.
396 	 */
397 	setup_clear_cpu_cap(X86_FEATURE_PCID);
398 
399 	if (!xen_initial_domain())
400 		setup_clear_cpu_cap(X86_FEATURE_ACPI);
401 
402 	if (xen_check_mwait())
403 		setup_force_cpu_cap(X86_FEATURE_MWAIT);
404 	else
405 		setup_clear_cpu_cap(X86_FEATURE_MWAIT);
406 
407 	if (!xen_check_xsave()) {
408 		setup_clear_cpu_cap(X86_FEATURE_XSAVE);
409 		setup_clear_cpu_cap(X86_FEATURE_OSXSAVE);
410 	}
411 }
412 
413 static noinstr void xen_set_debugreg(int reg, unsigned long val)
414 {
415 	HYPERVISOR_set_debugreg(reg, val);
416 }
417 
418 static noinstr unsigned long xen_get_debugreg(int reg)
419 {
420 	return HYPERVISOR_get_debugreg(reg);
421 }
422 
423 static void xen_start_context_switch(struct task_struct *prev)
424 {
425 	BUG_ON(preemptible());
426 
427 	if (this_cpu_read(xen_lazy_mode) == XEN_LAZY_MMU) {
428 		arch_leave_lazy_mmu_mode();
429 	}
430 	enter_lazy(XEN_LAZY_CPU);
431 }
432 
433 static void xen_end_context_switch(struct task_struct *next)
434 {
435 	BUG_ON(preemptible());
436 
437 	xen_mc_flush();
438 	leave_lazy(XEN_LAZY_CPU);
439 	if (__task_lazy_mmu_mode_active(next))
440 		arch_enter_lazy_mmu_mode();
441 }
442 
443 static unsigned long xen_store_tr(void)
444 {
445 	return 0;
446 }
447 
448 /*
449  * Set the page permissions for a particular virtual address.  If the
450  * address is a vmalloc mapping (or other non-linear mapping), then
451  * find the linear mapping of the page and also set its protections to
452  * match.
453  */
454 static void set_aliased_prot(void *v, pgprot_t prot)
455 {
456 	int level;
457 	pte_t *ptep;
458 	pte_t pte;
459 	unsigned long pfn;
460 	unsigned char dummy;
461 	void *va;
462 
463 	ptep = lookup_address((unsigned long)v, &level);
464 	BUG_ON(ptep == NULL);
465 
466 	pfn = pte_pfn(*ptep);
467 	pte = pfn_pte(pfn, prot);
468 
469 	/*
470 	 * Careful: update_va_mapping() will fail if the virtual address
471 	 * we're poking isn't populated in the page tables.  We don't
472 	 * need to worry about the direct map (that's always in the page
473 	 * tables), but we need to be careful about vmap space.  In
474 	 * particular, the top level page table can lazily propagate
475 	 * entries between processes, so if we've switched mms since we
476 	 * vmapped the target in the first place, we might not have the
477 	 * top-level page table entry populated.
478 	 *
479 	 * We disable preemption because we want the same mm active when
480 	 * we probe the target and when we issue the hypercall.  We'll
481 	 * have the same nominal mm, but if we're a kernel thread, lazy
482 	 * mm dropping could change our pgd.
483 	 *
484 	 * Out of an abundance of caution, this uses __get_user() to fault
485 	 * in the target address just in case there's some obscure case
486 	 * in which the target address isn't readable.
487 	 */
488 
489 	preempt_disable();
490 
491 	copy_from_kernel_nofault(&dummy, v, 1);
492 
493 	if (HYPERVISOR_update_va_mapping((unsigned long)v, pte, 0))
494 		BUG();
495 
496 	va = __va(PFN_PHYS(pfn));
497 
498 	if (va != v && HYPERVISOR_update_va_mapping((unsigned long)va, pte, 0))
499 		BUG();
500 
501 	preempt_enable();
502 }
503 
504 static void xen_alloc_ldt(struct desc_struct *ldt, unsigned entries)
505 {
506 	const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
507 	int i;
508 
509 	/*
510 	 * We need to mark the all aliases of the LDT pages RO.  We
511 	 * don't need to call vm_flush_aliases(), though, since that's
512 	 * only responsible for flushing aliases out the TLBs, not the
513 	 * page tables, and Xen will flush the TLB for us if needed.
514 	 *
515 	 * To avoid confusing future readers: none of this is necessary
516 	 * to load the LDT.  The hypervisor only checks this when the
517 	 * LDT is faulted in due to subsequent descriptor access.
518 	 */
519 
520 	for (i = 0; i < entries; i += entries_per_page)
521 		set_aliased_prot(ldt + i, PAGE_KERNEL_RO);
522 }
523 
524 static void xen_free_ldt(struct desc_struct *ldt, unsigned entries)
525 {
526 	const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
527 	int i;
528 
529 	for (i = 0; i < entries; i += entries_per_page)
530 		set_aliased_prot(ldt + i, PAGE_KERNEL);
531 }
532 
533 static void xen_set_ldt(const void *addr, unsigned entries)
534 {
535 	struct mmuext_op *op;
536 	struct multicall_space mcs = xen_mc_entry(sizeof(*op));
537 
538 	trace_xen_cpu_set_ldt(addr, entries);
539 
540 	op = mcs.args;
541 	op->cmd = MMUEXT_SET_LDT;
542 	op->arg1.linear_addr = (unsigned long)addr;
543 	op->arg2.nr_ents = entries;
544 
545 	MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
546 
547 	xen_mc_issue(XEN_LAZY_CPU);
548 }
549 
550 static void xen_load_gdt(const struct desc_ptr *dtr)
551 {
552 	unsigned long va = dtr->address;
553 	unsigned int size = dtr->size + 1;
554 	unsigned long pfn, mfn;
555 	int level;
556 	pte_t *ptep;
557 	void *virt;
558 
559 	/* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */
560 	BUG_ON(size > PAGE_SIZE);
561 	BUG_ON(va & ~PAGE_MASK);
562 
563 	/*
564 	 * The GDT is per-cpu and is in the percpu data area.
565 	 * That can be virtually mapped, so we need to do a
566 	 * page-walk to get the underlying MFN for the
567 	 * hypercall.  The page can also be in the kernel's
568 	 * linear range, so we need to RO that mapping too.
569 	 */
570 	ptep = lookup_address(va, &level);
571 	BUG_ON(ptep == NULL);
572 
573 	pfn = pte_pfn(*ptep);
574 	mfn = pfn_to_mfn(pfn);
575 	virt = __va(PFN_PHYS(pfn));
576 
577 	make_lowmem_page_readonly((void *)va);
578 	make_lowmem_page_readonly(virt);
579 
580 	if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct)))
581 		BUG();
582 }
583 
584 /*
585  * load_gdt for early boot, when the gdt is only mapped once
586  */
587 static void __init xen_load_gdt_boot(const struct desc_ptr *dtr)
588 {
589 	unsigned long va = dtr->address;
590 	unsigned int size = dtr->size + 1;
591 	unsigned long pfn, mfn;
592 	pte_t pte;
593 
594 	/* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */
595 	BUG_ON(size > PAGE_SIZE);
596 	BUG_ON(va & ~PAGE_MASK);
597 
598 	pfn = virt_to_pfn((void *)va);
599 	mfn = pfn_to_mfn(pfn);
600 
601 	pte = pfn_pte(pfn, PAGE_KERNEL_RO);
602 
603 	if (HYPERVISOR_update_va_mapping((unsigned long)va, pte, 0))
604 		BUG();
605 
606 	if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct)))
607 		BUG();
608 }
609 
610 static inline bool desc_equal(const struct desc_struct *d1,
611 			      const struct desc_struct *d2)
612 {
613 	return !memcmp(d1, d2, sizeof(*d1));
614 }
615 
616 static void load_TLS_descriptor(struct thread_struct *t,
617 				unsigned int cpu, unsigned int i)
618 {
619 	struct desc_struct *shadow = &per_cpu(shadow_tls_desc, cpu).desc[i];
620 	struct desc_struct *gdt;
621 	xmaddr_t maddr;
622 	struct multicall_space mc;
623 
624 	if (desc_equal(shadow, &t->tls_array[i]))
625 		return;
626 
627 	*shadow = t->tls_array[i];
628 
629 	gdt = get_cpu_gdt_rw(cpu);
630 	maddr = arbitrary_virt_to_machine(&gdt[GDT_ENTRY_TLS_MIN+i]);
631 	mc = __xen_mc_entry(0);
632 
633 	MULTI_update_descriptor(mc.mc, maddr.maddr, t->tls_array[i]);
634 }
635 
636 static void xen_load_tls(struct thread_struct *t, unsigned int cpu)
637 {
638 	/*
639 	 * In lazy mode we need to zero %fs, otherwise we may get an
640 	 * exception between the new %fs descriptor being loaded and
641 	 * %fs being effectively cleared at __switch_to().
642 	 */
643 	if (xen_get_lazy_mode() == XEN_LAZY_CPU)
644 		loadsegment(fs, 0);
645 
646 	xen_mc_batch();
647 
648 	load_TLS_descriptor(t, cpu, 0);
649 	load_TLS_descriptor(t, cpu, 1);
650 	load_TLS_descriptor(t, cpu, 2);
651 
652 	xen_mc_issue(XEN_LAZY_CPU);
653 }
654 
655 static void xen_load_gs_index(unsigned int idx)
656 {
657 	if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL, idx))
658 		BUG();
659 }
660 
661 static void xen_write_ldt_entry(struct desc_struct *dt, int entrynum,
662 				const void *ptr)
663 {
664 	xmaddr_t mach_lp = arbitrary_virt_to_machine(&dt[entrynum]);
665 	u64 entry = *(u64 *)ptr;
666 
667 	trace_xen_cpu_write_ldt_entry(dt, entrynum, entry);
668 
669 	preempt_disable();
670 
671 	xen_mc_flush();
672 	if (HYPERVISOR_update_descriptor(mach_lp.maddr, entry))
673 		BUG();
674 
675 	preempt_enable();
676 }
677 
678 void noist_exc_debug(struct pt_regs *regs);
679 
680 DEFINE_IDTENTRY_RAW(xenpv_exc_nmi)
681 {
682 	/* On Xen PV, NMI doesn't use IST.  The C part is the same as native. */
683 	exc_nmi(regs);
684 }
685 
686 DEFINE_IDTENTRY_RAW_ERRORCODE(xenpv_exc_double_fault)
687 {
688 	/* On Xen PV, DF doesn't use IST.  The C part is the same as native. */
689 	exc_double_fault(regs, error_code);
690 }
691 
692 DEFINE_IDTENTRY_RAW(xenpv_exc_debug)
693 {
694 	/*
695 	 * There's no IST on Xen PV, but we still need to dispatch
696 	 * to the correct handler.
697 	 */
698 	if (user_mode(regs))
699 		noist_exc_debug(regs);
700 	else
701 		exc_debug(regs);
702 }
703 
704 DEFINE_IDTENTRY_RAW(exc_xen_unknown_trap)
705 {
706 	/* This should never happen and there is no way to handle it. */
707 	instrumentation_begin();
708 	pr_err("Unknown trap in Xen PV mode.");
709 	BUG();
710 	instrumentation_end();
711 }
712 
713 #ifdef CONFIG_X86_MCE
714 DEFINE_IDTENTRY_RAW(xenpv_exc_machine_check)
715 {
716 	/*
717 	 * There's no IST on Xen PV, but we still need to dispatch
718 	 * to the correct handler.
719 	 */
720 	if (user_mode(regs))
721 		noist_exc_machine_check(regs);
722 	else
723 		exc_machine_check(regs);
724 }
725 #endif
726 
727 static void __xen_pv_evtchn_do_upcall(struct pt_regs *regs)
728 {
729 	struct pt_regs *old_regs = set_irq_regs(regs);
730 
731 	inc_irq_stat(irq_hv_callback_count);
732 
733 	xen_evtchn_do_upcall();
734 
735 	set_irq_regs(old_regs);
736 }
737 
738 __visible noinstr void xen_pv_evtchn_do_upcall(struct pt_regs *regs)
739 {
740 	irqentry_state_t state = irqentry_enter(regs);
741 	bool inhcall;
742 
743 	instrumentation_begin();
744 	run_sysvec_on_irqstack_cond(__xen_pv_evtchn_do_upcall, regs);
745 
746 	inhcall = get_and_clear_inhcall();
747 	if (inhcall && !WARN_ON_ONCE(state.exit_rcu)) {
748 		irqentry_exit_cond_resched();
749 		instrumentation_end();
750 		restore_inhcall(inhcall);
751 	} else {
752 		instrumentation_end();
753 		irqentry_exit(regs, state);
754 	}
755 }
756 
757 struct trap_array_entry {
758 	void (*orig)(void);
759 	void (*xen)(void);
760 	bool ist_okay;
761 };
762 
763 #define TRAP_ENTRY(func, ist_ok) {			\
764 	.orig		= asm_##func,			\
765 	.xen		= xen_asm_##func,		\
766 	.ist_okay	= ist_ok }
767 
768 #define TRAP_ENTRY_REDIR(func, ist_ok) {		\
769 	.orig		= asm_##func,			\
770 	.xen		= xen_asm_xenpv_##func,		\
771 	.ist_okay	= ist_ok }
772 
773 static struct trap_array_entry trap_array[] = {
774 	TRAP_ENTRY_REDIR(exc_debug,			true  ),
775 	TRAP_ENTRY_REDIR(exc_double_fault,		true  ),
776 #ifdef CONFIG_X86_MCE
777 	TRAP_ENTRY_REDIR(exc_machine_check,		true  ),
778 #endif
779 	TRAP_ENTRY_REDIR(exc_nmi,			true  ),
780 	TRAP_ENTRY(exc_int3,				false ),
781 	TRAP_ENTRY(exc_overflow,			false ),
782 #ifdef CONFIG_IA32_EMULATION
783 	TRAP_ENTRY(int80_emulation,			false ),
784 #endif
785 	TRAP_ENTRY(exc_page_fault,			false ),
786 	TRAP_ENTRY(exc_divide_error,			false ),
787 	TRAP_ENTRY(exc_bounds,				false ),
788 	TRAP_ENTRY(exc_invalid_op,			false ),
789 	TRAP_ENTRY(exc_device_not_available,		false ),
790 	TRAP_ENTRY(exc_coproc_segment_overrun,		false ),
791 	TRAP_ENTRY(exc_invalid_tss,			false ),
792 	TRAP_ENTRY(exc_segment_not_present,		false ),
793 	TRAP_ENTRY(exc_stack_segment,			false ),
794 	TRAP_ENTRY(exc_general_protection,		false ),
795 	TRAP_ENTRY(exc_spurious_interrupt_bug,		false ),
796 	TRAP_ENTRY(exc_coprocessor_error,		false ),
797 	TRAP_ENTRY(exc_alignment_check,			false ),
798 	TRAP_ENTRY(exc_simd_coprocessor_error,		false ),
799 #ifdef CONFIG_X86_CET
800 	TRAP_ENTRY(exc_control_protection,		false ),
801 #endif
802 };
803 
804 static bool __ref get_trap_addr(void **addr, unsigned int ist)
805 {
806 	unsigned int nr;
807 	bool ist_okay = false;
808 	bool found = false;
809 
810 	/*
811 	 * Replace trap handler addresses by Xen specific ones.
812 	 * Check for known traps using IST and whitelist them.
813 	 * The debugger ones are the only ones we care about.
814 	 * Xen will handle faults like double_fault, so we should never see
815 	 * them.  Warn if there's an unexpected IST-using fault handler.
816 	 */
817 	for (nr = 0; nr < ARRAY_SIZE(trap_array); nr++) {
818 		struct trap_array_entry *entry = trap_array + nr;
819 
820 		if (*addr == entry->orig) {
821 			*addr = entry->xen;
822 			ist_okay = entry->ist_okay;
823 			found = true;
824 			break;
825 		}
826 	}
827 
828 	if (nr == ARRAY_SIZE(trap_array) &&
829 	    *addr >= (void *)early_idt_handler_array[0] &&
830 	    *addr < (void *)early_idt_handler_array[NUM_EXCEPTION_VECTORS]) {
831 		nr = (*addr - (void *)early_idt_handler_array[0]) /
832 		     EARLY_IDT_HANDLER_SIZE;
833 		*addr = (void *)xen_early_idt_handler_array[nr];
834 		found = true;
835 	}
836 
837 	if (!found)
838 		*addr = (void *)xen_asm_exc_xen_unknown_trap;
839 
840 	if (WARN_ON(found && ist != 0 && !ist_okay))
841 		return false;
842 
843 	return true;
844 }
845 
846 static int cvt_gate_to_trap(int vector, const gate_desc *val,
847 			    struct trap_info *info)
848 {
849 	unsigned long addr;
850 
851 	if (val->bits.type != GATE_TRAP && val->bits.type != GATE_INTERRUPT)
852 		return 0;
853 
854 	info->vector = vector;
855 
856 	addr = gate_offset(val);
857 	if (!get_trap_addr((void **)&addr, val->bits.ist))
858 		return 0;
859 	info->address = addr;
860 
861 	info->cs = gate_segment(val);
862 	info->flags = val->bits.dpl;
863 	/* interrupt gates clear IF */
864 	if (val->bits.type == GATE_INTERRUPT)
865 		info->flags |= 1 << 2;
866 
867 	return 1;
868 }
869 
870 /* Locations of each CPU's IDT */
871 static DEFINE_PER_CPU(struct desc_ptr, idt_desc);
872 
873 /* Set an IDT entry.  If the entry is part of the current IDT, then
874    also update Xen. */
875 static void xen_write_idt_entry(gate_desc *dt, int entrynum, const gate_desc *g)
876 {
877 	unsigned long p = (unsigned long)&dt[entrynum];
878 	unsigned long start, end;
879 
880 	trace_xen_cpu_write_idt_entry(dt, entrynum, g);
881 
882 	preempt_disable();
883 
884 	start = __this_cpu_read(idt_desc.address);
885 	end = start + __this_cpu_read(idt_desc.size) + 1;
886 
887 	xen_mc_flush();
888 
889 	native_write_idt_entry(dt, entrynum, g);
890 
891 	if (p >= start && (p + 8) <= end) {
892 		struct trap_info info[2];
893 
894 		info[1].address = 0;
895 
896 		if (cvt_gate_to_trap(entrynum, g, &info[0]))
897 			if (HYPERVISOR_set_trap_table(info))
898 				BUG();
899 	}
900 
901 	preempt_enable();
902 }
903 
904 static unsigned xen_convert_trap_info(const struct desc_ptr *desc,
905 				      struct trap_info *traps, bool full)
906 {
907 	unsigned in, out, count;
908 
909 	count = (desc->size+1) / sizeof(gate_desc);
910 	BUG_ON(count > 256);
911 
912 	for (in = out = 0; in < count; in++) {
913 		gate_desc *entry = (gate_desc *)(desc->address) + in;
914 
915 		if (cvt_gate_to_trap(in, entry, &traps[out]) || full)
916 			out++;
917 	}
918 
919 	return out;
920 }
921 
922 void xen_copy_trap_info(struct trap_info *traps)
923 {
924 	const struct desc_ptr *desc = this_cpu_ptr(&idt_desc);
925 
926 	xen_convert_trap_info(desc, traps, true);
927 }
928 
929 /* Load a new IDT into Xen.  In principle this can be per-CPU, so we
930    hold a spinlock to protect the static traps[] array (static because
931    it avoids allocation, and saves stack space). */
932 static void xen_load_idt(const struct desc_ptr *desc)
933 {
934 	static DEFINE_SPINLOCK(lock);
935 	static struct trap_info traps[257];
936 	static const struct trap_info zero = { };
937 	unsigned out;
938 
939 	trace_xen_cpu_load_idt(desc);
940 
941 	spin_lock(&lock);
942 
943 	memcpy(this_cpu_ptr(&idt_desc), desc, sizeof(idt_desc));
944 
945 	out = xen_convert_trap_info(desc, traps, false);
946 	traps[out] = zero;
947 
948 	xen_mc_flush();
949 	if (HYPERVISOR_set_trap_table(traps))
950 		BUG();
951 
952 	spin_unlock(&lock);
953 }
954 
955 /* Write a GDT descriptor entry.  Ignore LDT descriptors, since
956    they're handled differently. */
957 static void xen_write_gdt_entry(struct desc_struct *dt, int entry,
958 				const void *desc, int type)
959 {
960 	trace_xen_cpu_write_gdt_entry(dt, entry, desc, type);
961 
962 	preempt_disable();
963 
964 	switch (type) {
965 	case DESC_LDT:
966 	case DESC_TSS:
967 		/* ignore */
968 		break;
969 
970 	default: {
971 		xmaddr_t maddr = arbitrary_virt_to_machine(&dt[entry]);
972 
973 		xen_mc_flush();
974 		if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc))
975 			BUG();
976 	}
977 
978 	}
979 
980 	preempt_enable();
981 }
982 
983 /*
984  * Version of write_gdt_entry for use at early boot-time needed to
985  * update an entry as simply as possible.
986  */
987 static void __init xen_write_gdt_entry_boot(struct desc_struct *dt, int entry,
988 					    const void *desc, int type)
989 {
990 	trace_xen_cpu_write_gdt_entry(dt, entry, desc, type);
991 
992 	switch (type) {
993 	case DESC_LDT:
994 	case DESC_TSS:
995 		/* ignore */
996 		break;
997 
998 	default: {
999 		xmaddr_t maddr = virt_to_machine(&dt[entry]);
1000 
1001 		if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc))
1002 			dt[entry] = *(struct desc_struct *)desc;
1003 	}
1004 
1005 	}
1006 }
1007 
1008 static void xen_load_sp0(unsigned long sp0)
1009 {
1010 	struct multicall_space mcs;
1011 
1012 	mcs = xen_mc_entry(0);
1013 	MULTI_stack_switch(mcs.mc, __KERNEL_DS, sp0);
1014 	xen_mc_issue(XEN_LAZY_CPU);
1015 	this_cpu_write(cpu_tss_rw.x86_tss.sp0, sp0);
1016 }
1017 
1018 #ifdef CONFIG_X86_IOPL_IOPERM
1019 static void xen_invalidate_io_bitmap(void)
1020 {
1021 	struct physdev_set_iobitmap iobitmap = {
1022 		.bitmap = NULL,
1023 		.nr_ports = 0,
1024 	};
1025 
1026 	native_tss_invalidate_io_bitmap();
1027 	HYPERVISOR_physdev_op(PHYSDEVOP_set_iobitmap, &iobitmap);
1028 }
1029 
1030 static void xen_update_io_bitmap(void)
1031 {
1032 	struct physdev_set_iobitmap iobitmap;
1033 	struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw);
1034 
1035 	native_tss_update_io_bitmap();
1036 
1037 	iobitmap.bitmap = (uint8_t *)(&tss->x86_tss) +
1038 			  tss->x86_tss.io_bitmap_base;
1039 	if (tss->x86_tss.io_bitmap_base == IO_BITMAP_OFFSET_INVALID)
1040 		iobitmap.nr_ports = 0;
1041 	else
1042 		iobitmap.nr_ports = IO_BITMAP_BITS;
1043 
1044 	HYPERVISOR_physdev_op(PHYSDEVOP_set_iobitmap, &iobitmap);
1045 }
1046 #endif
1047 
1048 static void xen_io_delay(void)
1049 {
1050 }
1051 
1052 static DEFINE_PER_CPU(unsigned long, xen_cr0_value);
1053 
1054 static unsigned long xen_read_cr0(void)
1055 {
1056 	unsigned long cr0 = this_cpu_read(xen_cr0_value);
1057 
1058 	if (unlikely(cr0 == 0)) {
1059 		cr0 = native_read_cr0();
1060 		this_cpu_write(xen_cr0_value, cr0);
1061 	}
1062 
1063 	return cr0;
1064 }
1065 
1066 static void xen_write_cr0(unsigned long cr0)
1067 {
1068 	struct multicall_space mcs;
1069 
1070 	this_cpu_write(xen_cr0_value, cr0);
1071 
1072 	/* Only pay attention to cr0.TS; everything else is
1073 	   ignored. */
1074 	mcs = xen_mc_entry(0);
1075 
1076 	MULTI_fpu_taskswitch(mcs.mc, (cr0 & X86_CR0_TS) != 0);
1077 
1078 	xen_mc_issue(XEN_LAZY_CPU);
1079 }
1080 
1081 static void xen_write_cr4(unsigned long cr4)
1082 {
1083 	cr4 &= ~(X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PCE);
1084 
1085 	native_write_cr4(cr4);
1086 }
1087 
1088 static u64 xen_do_read_msr(u32 msr, int *err)
1089 {
1090 	u64 val = 0;	/* Avoid uninitialized value for safe variant. */
1091 
1092 	if (pmu_msr_chk_emulated(msr, &val, true))
1093 		return val;
1094 
1095 	if (err)
1096 		*err = native_read_msr_safe(msr, &val);
1097 	else
1098 		val = native_read_msr(msr);
1099 
1100 	switch (msr) {
1101 	case MSR_IA32_APICBASE:
1102 		val &= ~X2APIC_ENABLE;
1103 		if (smp_processor_id() == 0)
1104 			val |= MSR_IA32_APICBASE_BSP;
1105 		else
1106 			val &= ~MSR_IA32_APICBASE_BSP;
1107 		break;
1108 	}
1109 	return val;
1110 }
1111 
1112 static void set_seg(u32 which, u64 base)
1113 {
1114 	if (HYPERVISOR_set_segment_base(which, base))
1115 		WARN(1, "Xen set_segment_base(%u, %llx) failed\n", which, base);
1116 }
1117 
1118 /*
1119  * Support write_msr_safe() and write_msr() semantics.
1120  * With err == NULL write_msr() semantics are selected.
1121  * Supplying an err pointer requires err to be pre-initialized with 0.
1122  */
1123 static void xen_do_write_msr(u32 msr, u64 val, int *err)
1124 {
1125 	switch (msr) {
1126 	case MSR_FS_BASE:
1127 		set_seg(SEGBASE_FS, val);
1128 		break;
1129 
1130 	case MSR_KERNEL_GS_BASE:
1131 		set_seg(SEGBASE_GS_USER, val);
1132 		break;
1133 
1134 	case MSR_GS_BASE:
1135 		set_seg(SEGBASE_GS_KERNEL, val);
1136 		break;
1137 
1138 	case MSR_STAR:
1139 	case MSR_CSTAR:
1140 	case MSR_LSTAR:
1141 	case MSR_SYSCALL_MASK:
1142 	case MSR_IA32_SYSENTER_CS:
1143 	case MSR_IA32_SYSENTER_ESP:
1144 	case MSR_IA32_SYSENTER_EIP:
1145 		/* Fast syscall setup is all done in hypercalls, so
1146 		   these are all ignored.  Stub them out here to stop
1147 		   Xen console noise. */
1148 		break;
1149 
1150 	default:
1151 		if (pmu_msr_chk_emulated(msr, &val, false))
1152 			return;
1153 
1154 		if (err)
1155 			*err = native_write_msr_safe(msr, val);
1156 		else
1157 			native_write_msr(msr, val);
1158 	}
1159 }
1160 
1161 static int xen_read_msr_safe(u32 msr, u64 *val)
1162 {
1163 	int err = 0;
1164 
1165 	*val = xen_do_read_msr(msr, &err);
1166 	return err;
1167 }
1168 
1169 static int xen_write_msr_safe(u32 msr, u64 val)
1170 {
1171 	int err = 0;
1172 
1173 	xen_do_write_msr(msr, val, &err);
1174 
1175 	return err;
1176 }
1177 
1178 static u64 xen_read_msr(u32 msr)
1179 {
1180 	int err = 0;
1181 
1182 	return xen_do_read_msr(msr, xen_msr_safe ? &err : NULL);
1183 }
1184 
1185 static void xen_write_msr(u32 msr, u64 val)
1186 {
1187 	int err;
1188 
1189 	xen_do_write_msr(msr, val, xen_msr_safe ? &err : NULL);
1190 }
1191 
1192 /* This is called once we have the cpu_possible_mask */
1193 void __init xen_setup_vcpu_info_placement(void)
1194 {
1195 	int cpu;
1196 
1197 	for_each_possible_cpu(cpu) {
1198 		/* Set up direct vCPU id mapping for PV guests. */
1199 		per_cpu(xen_vcpu_id, cpu) = cpu;
1200 		xen_vcpu_setup(cpu);
1201 	}
1202 
1203 	pv_ops.irq.save_fl = __PV_IS_CALLEE_SAVE(xen_save_fl_direct);
1204 	pv_ops.irq.irq_disable = __PV_IS_CALLEE_SAVE(xen_irq_disable_direct);
1205 	pv_ops.irq.irq_enable = __PV_IS_CALLEE_SAVE(xen_irq_enable_direct);
1206 	pv_ops.mmu.read_cr2 = __PV_IS_CALLEE_SAVE(xen_read_cr2_direct);
1207 }
1208 
1209 static const struct pv_info xen_info __initconst = {
1210 	.extra_user_64bit_cs = FLAT_USER_CS64,
1211 	.name = "Xen",
1212 };
1213 
1214 static void xen_restart(char *msg)
1215 {
1216 	xen_reboot(SHUTDOWN_reboot);
1217 }
1218 
1219 static void xen_machine_halt(void)
1220 {
1221 	xen_reboot(SHUTDOWN_poweroff);
1222 }
1223 
1224 static void xen_machine_power_off(void)
1225 {
1226 	do_kernel_power_off();
1227 	xen_reboot(SHUTDOWN_poweroff);
1228 }
1229 
1230 static void xen_crash_shutdown(struct pt_regs *regs)
1231 {
1232 	xen_reboot(SHUTDOWN_crash);
1233 }
1234 
1235 static const struct machine_ops xen_machine_ops __initconst = {
1236 	.restart = xen_restart,
1237 	.halt = xen_machine_halt,
1238 	.power_off = xen_machine_power_off,
1239 	.shutdown = xen_machine_halt,
1240 	.crash_shutdown = xen_crash_shutdown,
1241 	.emergency_restart = xen_emergency_restart,
1242 };
1243 
1244 static unsigned char xen_get_nmi_reason(void)
1245 {
1246 	unsigned char reason = 0;
1247 
1248 	/* Construct a value which looks like it came from port 0x61. */
1249 	if (test_bit(_XEN_NMIREASON_io_error,
1250 		     &HYPERVISOR_shared_info->arch.nmi_reason))
1251 		reason |= NMI_REASON_IOCHK;
1252 	if (test_bit(_XEN_NMIREASON_pci_serr,
1253 		     &HYPERVISOR_shared_info->arch.nmi_reason))
1254 		reason |= NMI_REASON_SERR;
1255 
1256 	return reason;
1257 }
1258 
1259 static void __init xen_boot_params_init_edd(void)
1260 {
1261 #if IS_ENABLED(CONFIG_EDD)
1262 	struct xen_platform_op op;
1263 	struct edd_info *edd_info;
1264 	u32 *mbr_signature;
1265 	unsigned nr;
1266 	int ret;
1267 
1268 	edd_info = boot_params.eddbuf;
1269 	mbr_signature = boot_params.edd_mbr_sig_buffer;
1270 
1271 	op.cmd = XENPF_firmware_info;
1272 
1273 	op.u.firmware_info.type = XEN_FW_DISK_INFO;
1274 	for (nr = 0; nr < EDDMAXNR; nr++) {
1275 		struct edd_info *info = edd_info + nr;
1276 
1277 		op.u.firmware_info.index = nr;
1278 		info->params.length = sizeof(info->params);
1279 		set_xen_guest_handle(op.u.firmware_info.u.disk_info.edd_params,
1280 				     &info->params);
1281 		ret = HYPERVISOR_platform_op(&op);
1282 		if (ret)
1283 			break;
1284 
1285 #define C(x) info->x = op.u.firmware_info.u.disk_info.x
1286 		C(device);
1287 		C(version);
1288 		C(interface_support);
1289 		C(legacy_max_cylinder);
1290 		C(legacy_max_head);
1291 		C(legacy_sectors_per_track);
1292 #undef C
1293 	}
1294 	boot_params.eddbuf_entries = nr;
1295 
1296 	op.u.firmware_info.type = XEN_FW_DISK_MBR_SIGNATURE;
1297 	for (nr = 0; nr < EDD_MBR_SIG_MAX; nr++) {
1298 		op.u.firmware_info.index = nr;
1299 		ret = HYPERVISOR_platform_op(&op);
1300 		if (ret)
1301 			break;
1302 		mbr_signature[nr] = op.u.firmware_info.u.disk_mbr_signature.mbr_signature;
1303 	}
1304 	boot_params.edd_mbr_sig_buf_entries = nr;
1305 #endif
1306 }
1307 
1308 /*
1309  * Set up the GDT and segment registers for -fstack-protector.  Until
1310  * we do this, we have to be careful not to call any stack-protected
1311  * function, which is most of the kernel.
1312  */
1313 static void __init xen_setup_gdt(int cpu)
1314 {
1315 	pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry_boot;
1316 	pv_ops.cpu.load_gdt = xen_load_gdt_boot;
1317 
1318 	switch_gdt_and_percpu_base(cpu);
1319 
1320 	pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry;
1321 	pv_ops.cpu.load_gdt = xen_load_gdt;
1322 }
1323 
1324 static void __init xen_dom0_set_legacy_features(void)
1325 {
1326 	x86_platform.legacy.rtc = 1;
1327 }
1328 
1329 static void __init xen_domu_set_legacy_features(void)
1330 {
1331 	x86_platform.legacy.rtc = 0;
1332 }
1333 
1334 extern void early_xen_iret_patch(void);
1335 
1336 /* First C function to be called on Xen boot */
1337 asmlinkage __visible void __init xen_start_kernel(struct start_info *si)
1338 {
1339 	struct physdev_set_iopl set_iopl;
1340 	unsigned long initrd_start = 0;
1341 	int rc;
1342 
1343 	if (!si)
1344 		return;
1345 
1346 	clear_bss();
1347 
1348 	xen_start_info = si;
1349 
1350 	__text_gen_insn(&early_xen_iret_patch,
1351 			JMP32_INSN_OPCODE, &early_xen_iret_patch, &xen_iret,
1352 			JMP32_INSN_SIZE);
1353 
1354 	xen_domain_type = XEN_PV_DOMAIN;
1355 	setup_force_cpu_cap(X86_FEATURE_XENPV);
1356 	xen_start_flags = xen_start_info->flags;
1357 	/* Interrupts are guaranteed to be off initially. */
1358 	early_boot_irqs_disabled = true;
1359 	static_call_update_early(xen_hypercall, xen_hypercall_pv);
1360 
1361 	xen_setup_features();
1362 
1363 	/* Install Xen paravirt ops */
1364 	pv_info = xen_info;
1365 
1366 	pv_ops.cpu.cpuid = xen_cpuid;
1367 	pv_ops.cpu.set_debugreg = xen_set_debugreg;
1368 	pv_ops.cpu.get_debugreg = xen_get_debugreg;
1369 	pv_ops.cpu.read_cr0 = xen_read_cr0;
1370 	pv_ops.cpu.write_cr0 = xen_write_cr0;
1371 	pv_ops.cpu.write_cr4 = xen_write_cr4;
1372 	pv_ops.cpu.read_msr = xen_read_msr;
1373 	pv_ops.cpu.write_msr = xen_write_msr;
1374 	pv_ops.cpu.read_msr_safe = xen_read_msr_safe;
1375 	pv_ops.cpu.write_msr_safe = xen_write_msr_safe;
1376 	pv_ops.cpu.read_pmc = xen_read_pmc;
1377 	pv_ops.cpu.load_tr_desc = paravirt_nop;
1378 	pv_ops.cpu.set_ldt = xen_set_ldt;
1379 	pv_ops.cpu.load_gdt = xen_load_gdt;
1380 	pv_ops.cpu.load_idt = xen_load_idt;
1381 	pv_ops.cpu.load_tls = xen_load_tls;
1382 	pv_ops.cpu.load_gs_index = xen_load_gs_index;
1383 	pv_ops.cpu.alloc_ldt = xen_alloc_ldt;
1384 	pv_ops.cpu.free_ldt = xen_free_ldt;
1385 	pv_ops.cpu.store_tr = xen_store_tr;
1386 	pv_ops.cpu.write_ldt_entry = xen_write_ldt_entry;
1387 	pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry;
1388 	pv_ops.cpu.write_idt_entry = xen_write_idt_entry;
1389 	pv_ops.cpu.load_sp0 = xen_load_sp0;
1390 #ifdef CONFIG_X86_IOPL_IOPERM
1391 	pv_ops.cpu.invalidate_io_bitmap = xen_invalidate_io_bitmap;
1392 	pv_ops.cpu.update_io_bitmap = xen_update_io_bitmap;
1393 #endif
1394 	pv_ops.cpu.io_delay = xen_io_delay;
1395 	pv_ops.cpu.start_context_switch = xen_start_context_switch;
1396 	pv_ops.cpu.end_context_switch = xen_end_context_switch;
1397 
1398 	xen_init_irq_ops();
1399 
1400 	/*
1401 	 * Setup xen_vcpu early because it is needed for
1402 	 * local_irq_disable(), irqs_disabled(), e.g. in printk().
1403 	 *
1404 	 * Don't do the full vcpu_info placement stuff until we have
1405 	 * the cpu_possible_mask and a non-dummy shared_info.
1406 	 */
1407 	xen_vcpu_info_reset(0);
1408 
1409 	x86_platform.get_nmi_reason = xen_get_nmi_reason;
1410 	x86_platform.realmode_reserve = x86_init_noop;
1411 	x86_platform.realmode_init = x86_init_noop;
1412 
1413 	x86_init.resources.memory_setup = xen_memory_setup;
1414 	x86_init.irqs.intr_mode_select	= x86_init_noop;
1415 	x86_init.irqs.intr_mode_init	= x86_64_probe_apic;
1416 	x86_init.oem.arch_setup = xen_arch_setup;
1417 	x86_init.oem.banner = xen_banner;
1418 	x86_init.hyper.init_platform = xen_pv_init_platform;
1419 	x86_init.hyper.guest_late_init = xen_pv_guest_late_init;
1420 
1421 	/*
1422 	 * Set up some pagetable state before starting to set any ptes.
1423 	 */
1424 
1425 	xen_setup_machphys_mapping();
1426 	xen_init_mmu_ops();
1427 
1428 	/* Prevent unwanted bits from being set in PTEs. */
1429 	__supported_pte_mask &= ~_PAGE_GLOBAL;
1430 	__default_kernel_pte_mask &= ~_PAGE_GLOBAL;
1431 
1432 	/* Get mfn list */
1433 	xen_build_dynamic_phys_to_machine();
1434 
1435 	/* Work out if we support NX */
1436 	get_cpu_cap(&boot_cpu_data);
1437 	x86_configure_nx();
1438 
1439 	/*
1440 	 * Set up kernel GDT and segment registers, mainly so that
1441 	 * -fstack-protector code can be executed.
1442 	 */
1443 	xen_setup_gdt(0);
1444 
1445 	/* Determine virtual and physical address sizes */
1446 	get_cpu_address_sizes(&boot_cpu_data);
1447 
1448 	/* Let's presume PV guests always boot on vCPU with id 0. */
1449 	per_cpu(xen_vcpu_id, 0) = 0;
1450 
1451 	idt_setup_early_handler();
1452 
1453 	xen_init_capabilities();
1454 
1455 	/*
1456 	 * set up the basic apic ops.
1457 	 */
1458 	xen_init_apic();
1459 
1460 	machine_ops = xen_machine_ops;
1461 
1462 	/*
1463 	 * The only reliable way to retain the initial address of the
1464 	 * percpu gdt_page is to remember it here, so we can go and
1465 	 * mark it RW later, when the initial percpu area is freed.
1466 	 */
1467 	xen_initial_gdt = &per_cpu(gdt_page, 0);
1468 
1469 	xen_smp_init();
1470 
1471 #ifdef CONFIG_ACPI_NUMA
1472 	/*
1473 	 * The pages we from Xen are not related to machine pages, so
1474 	 * any NUMA information the kernel tries to get from ACPI will
1475 	 * be meaningless.  Prevent it from trying.
1476 	 */
1477 	disable_srat();
1478 #endif
1479 	WARN_ON(xen_cpuhp_setup(xen_cpu_up_prepare_pv, xen_cpu_dead_pv));
1480 
1481 	local_irq_disable();
1482 
1483 	xen_raw_console_write("mapping kernel into physical memory\n");
1484 	xen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base,
1485 				   xen_start_info->nr_pages);
1486 	xen_reserve_special_pages();
1487 
1488 	/*
1489 	 * We used to do this in xen_arch_setup, but that is too late
1490 	 * on AMD were early_cpu_init (run before ->arch_setup()) calls
1491 	 * early_amd_init which pokes 0xcf8 port.
1492 	 */
1493 	set_iopl.iopl = 1;
1494 	rc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);
1495 	if (rc != 0)
1496 		xen_raw_printk("physdev_op failed %d\n", rc);
1497 
1498 
1499 	if (xen_start_info->mod_start) {
1500 	    if (xen_start_info->flags & SIF_MOD_START_PFN)
1501 		initrd_start = PFN_PHYS(xen_start_info->mod_start);
1502 	    else
1503 		initrd_start = __pa(xen_start_info->mod_start);
1504 	}
1505 
1506 	/* Poke various useful things into boot_params */
1507 	boot_params.hdr.type_of_loader = (9 << 4) | 0;
1508 	boot_params.hdr.ramdisk_image = initrd_start;
1509 	boot_params.hdr.ramdisk_size = xen_start_info->mod_len;
1510 	boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line);
1511 	boot_params.hdr.hardware_subarch = X86_SUBARCH_XEN;
1512 
1513 	if (!xen_initial_domain()) {
1514 		if (pci_xen)
1515 			x86_init.pci.arch_init = pci_xen_init;
1516 		x86_platform.set_legacy_features =
1517 				xen_domu_set_legacy_features;
1518 	} else {
1519 		const struct dom0_vga_console_info *info =
1520 			(void *)((char *)xen_start_info +
1521 				 xen_start_info->console.dom0.info_off);
1522 		struct xen_platform_op op = {
1523 			.cmd = XENPF_firmware_info,
1524 			.interface_version = XENPF_INTERFACE_VERSION,
1525 			.u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS,
1526 		};
1527 
1528 		x86_platform.set_legacy_features =
1529 				xen_dom0_set_legacy_features;
1530 		xen_init_vga(info, xen_start_info->console.dom0.info_size,
1531 			     &boot_params.screen_info);
1532 		xen_start_info->console.domU.mfn = 0;
1533 		xen_start_info->console.domU.evtchn = 0;
1534 
1535 		if (HYPERVISOR_platform_op(&op) == 0)
1536 			boot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags;
1537 
1538 		/* Make sure ACS will be enabled */
1539 		pci_request_acs();
1540 
1541 		xen_acpi_sleep_register();
1542 
1543 		xen_boot_params_init_edd();
1544 
1545 #ifdef CONFIG_ACPI
1546 		/*
1547 		 * Disable selecting "Firmware First mode" for correctable
1548 		 * memory errors, as this is the duty of the hypervisor to
1549 		 * decide.
1550 		 */
1551 		acpi_disable_cmcff = 1;
1552 #endif
1553 	}
1554 
1555 	xen_add_preferred_consoles();
1556 
1557 #ifdef CONFIG_PCI
1558 	/* PCI BIOS service won't work from a PV guest. */
1559 	pci_probe &= ~PCI_PROBE_BIOS;
1560 #endif
1561 	xen_raw_console_write("about to get started...\n");
1562 
1563 	/* We need this for printk timestamps */
1564 	xen_setup_runstate_info(0);
1565 
1566 	xen_efi_init(&boot_params);
1567 
1568 	/* Start the world */
1569 	cr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */
1570 	x86_64_start_reservations((char *)__pa_symbol(&boot_params));
1571 }
1572 
1573 static int xen_cpu_up_prepare_pv(unsigned int cpu)
1574 {
1575 	int rc;
1576 
1577 	if (per_cpu(xen_vcpu, cpu) == NULL)
1578 		return -ENODEV;
1579 
1580 	xen_setup_timer(cpu);
1581 
1582 	rc = xen_smp_intr_init(cpu);
1583 	if (rc) {
1584 		WARN(1, "xen_smp_intr_init() for CPU %d failed: %d\n",
1585 		     cpu, rc);
1586 		return rc;
1587 	}
1588 
1589 	rc = xen_smp_intr_init_pv(cpu);
1590 	if (rc) {
1591 		WARN(1, "xen_smp_intr_init_pv() for CPU %d failed: %d\n",
1592 		     cpu, rc);
1593 		return rc;
1594 	}
1595 
1596 	return 0;
1597 }
1598 
1599 static int xen_cpu_dead_pv(unsigned int cpu)
1600 {
1601 	xen_smp_intr_free(cpu);
1602 	xen_smp_intr_free_pv(cpu);
1603 
1604 	xen_teardown_timer(cpu);
1605 
1606 	return 0;
1607 }
1608 
1609 static uint32_t __init xen_platform_pv(void)
1610 {
1611 	if (xen_pv_domain())
1612 		return xen_cpuid_base();
1613 
1614 	return 0;
1615 }
1616 
1617 const __initconst struct hypervisor_x86 x86_hyper_xen_pv = {
1618 	.name                   = "Xen PV",
1619 	.detect                 = xen_platform_pv,
1620 	.type			= X86_HYPER_XEN_PV,
1621 	.runtime.pin_vcpu       = xen_pin_vcpu,
1622 	.ignore_nopv		= true,
1623 };
1624