x86/xen: use xen_vcpu_id mapping for HYPERVISOR_vcpu_op
[cascardo/linux.git] / arch / x86 / xen / enlighten.c
1 /*
2  * Core of Xen paravirt_ops implementation.
3  *
4  * This file contains the xen_paravirt_ops structure itself, and the
5  * implementations for:
6  * - privileged instructions
7  * - interrupt flags
8  * - segment operations
9  * - booting and setup
10  *
11  * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
12  */
13
14 #include <linux/cpu.h>
15 #include <linux/kernel.h>
16 #include <linux/init.h>
17 #include <linux/smp.h>
18 #include <linux/preempt.h>
19 #include <linux/hardirq.h>
20 #include <linux/percpu.h>
21 #include <linux/delay.h>
22 #include <linux/start_kernel.h>
23 #include <linux/sched.h>
24 #include <linux/kprobes.h>
25 #include <linux/bootmem.h>
26 #include <linux/module.h>
27 #include <linux/mm.h>
28 #include <linux/page-flags.h>
29 #include <linux/highmem.h>
30 #include <linux/console.h>
31 #include <linux/pci.h>
32 #include <linux/gfp.h>
33 #include <linux/memblock.h>
34 #include <linux/edd.h>
35 #include <linux/frame.h>
36
37 #ifdef CONFIG_KEXEC_CORE
38 #include <linux/kexec.h>
39 #endif
40
41 #include <xen/xen.h>
42 #include <xen/events.h>
43 #include <xen/interface/xen.h>
44 #include <xen/interface/version.h>
45 #include <xen/interface/physdev.h>
46 #include <xen/interface/vcpu.h>
47 #include <xen/interface/memory.h>
48 #include <xen/interface/nmi.h>
49 #include <xen/interface/xen-mca.h>
50 #include <xen/features.h>
51 #include <xen/page.h>
52 #include <xen/hvm.h>
53 #include <xen/hvc-console.h>
54 #include <xen/acpi.h>
55
56 #include <asm/paravirt.h>
57 #include <asm/apic.h>
58 #include <asm/page.h>
59 #include <asm/xen/pci.h>
60 #include <asm/xen/hypercall.h>
61 #include <asm/xen/hypervisor.h>
62 #include <asm/xen/cpuid.h>
63 #include <asm/fixmap.h>
64 #include <asm/processor.h>
65 #include <asm/proto.h>
66 #include <asm/msr-index.h>
67 #include <asm/traps.h>
68 #include <asm/setup.h>
69 #include <asm/desc.h>
70 #include <asm/pgalloc.h>
71 #include <asm/pgtable.h>
72 #include <asm/tlbflush.h>
73 #include <asm/reboot.h>
74 #include <asm/stackprotector.h>
75 #include <asm/hypervisor.h>
76 #include <asm/mach_traps.h>
77 #include <asm/mwait.h>
78 #include <asm/pci_x86.h>
79 #include <asm/cpu.h>
80
81 #ifdef CONFIG_ACPI
82 #include <linux/acpi.h>
83 #include <asm/acpi.h>
84 #include <acpi/pdc_intel.h>
85 #include <acpi/processor.h>
86 #include <xen/interface/platform.h>
87 #endif
88
89 #include "xen-ops.h"
90 #include "mmu.h"
91 #include "smp.h"
92 #include "multicalls.h"
93 #include "pmu.h"
94
95 EXPORT_SYMBOL_GPL(hypercall_page);
96
97 /*
98  * Pointer to the xen_vcpu_info structure or
99  * &HYPERVISOR_shared_info->vcpu_info[cpu]. See xen_hvm_init_shared_info
100  * and xen_vcpu_setup for details. By default it points to share_info->vcpu_info
101  * but if the hypervisor supports VCPUOP_register_vcpu_info then it can point
102  * to xen_vcpu_info. The pointer is used in __xen_evtchn_do_upcall to
103  * acknowledge pending events.
104  * Also more subtly it is used by the patched version of irq enable/disable
105  * e.g. xen_irq_enable_direct and xen_iret in PV mode.
106  *
107  * The desire to be able to do those mask/unmask operations as a single
108  * instruction by using the per-cpu offset held in %gs is the real reason
109  * vcpu info is in a per-cpu pointer and the original reason for this
110  * hypercall.
111  *
112  */
113 DEFINE_PER_CPU(struct vcpu_info *, xen_vcpu);
114
115 /*
116  * Per CPU pages used if hypervisor supports VCPUOP_register_vcpu_info
117  * hypercall. This can be used both in PV and PVHVM mode. The structure
118  * overrides the default per_cpu(xen_vcpu, cpu) value.
119  */
120 DEFINE_PER_CPU(struct vcpu_info, xen_vcpu_info);
121
122 /* Linux <-> Xen vCPU id mapping */
123 DEFINE_PER_CPU(int, xen_vcpu_id) = -1;
124 EXPORT_PER_CPU_SYMBOL(xen_vcpu_id);
125
126 enum xen_domain_type xen_domain_type = XEN_NATIVE;
127 EXPORT_SYMBOL_GPL(xen_domain_type);
128
129 unsigned long *machine_to_phys_mapping = (void *)MACH2PHYS_VIRT_START;
130 EXPORT_SYMBOL(machine_to_phys_mapping);
131 unsigned long  machine_to_phys_nr;
132 EXPORT_SYMBOL(machine_to_phys_nr);
133
134 struct start_info *xen_start_info;
135 EXPORT_SYMBOL_GPL(xen_start_info);
136
137 struct shared_info xen_dummy_shared_info;
138
139 void *xen_initial_gdt;
140
141 RESERVE_BRK(shared_info_page_brk, PAGE_SIZE);
142 __read_mostly int xen_have_vector_callback;
143 EXPORT_SYMBOL_GPL(xen_have_vector_callback);
144
145 /*
146  * Point at some empty memory to start with. We map the real shared_info
147  * page as soon as fixmap is up and running.
148  */
149 struct shared_info *HYPERVISOR_shared_info = &xen_dummy_shared_info;
150
151 /*
152  * Flag to determine whether vcpu info placement is available on all
153  * VCPUs.  We assume it is to start with, and then set it to zero on
154  * the first failure.  This is because it can succeed on some VCPUs
155  * and not others, since it can involve hypervisor memory allocation,
156  * or because the guest failed to guarantee all the appropriate
157  * constraints on all VCPUs (ie buffer can't cross a page boundary).
158  *
159  * Note that any particular CPU may be using a placed vcpu structure,
160  * but we can only optimise if the all are.
161  *
162  * 0: not available, 1: available
163  */
164 static int have_vcpu_info_placement = 1;
165
166 struct tls_descs {
167         struct desc_struct desc[3];
168 };
169
170 /*
171  * Updating the 3 TLS descriptors in the GDT on every task switch is
172  * surprisingly expensive so we avoid updating them if they haven't
173  * changed.  Since Xen writes different descriptors than the one
174  * passed in the update_descriptor hypercall we keep shadow copies to
175  * compare against.
176  */
177 static DEFINE_PER_CPU(struct tls_descs, shadow_tls_desc);
178
179 static void clamp_max_cpus(void)
180 {
181 #ifdef CONFIG_SMP
182         if (setup_max_cpus > MAX_VIRT_CPUS)
183                 setup_max_cpus = MAX_VIRT_CPUS;
184 #endif
185 }
186
187 static void xen_vcpu_setup(int cpu)
188 {
189         struct vcpu_register_vcpu_info info;
190         int err;
191         struct vcpu_info *vcpup;
192
193         BUG_ON(HYPERVISOR_shared_info == &xen_dummy_shared_info);
194
195         /*
196          * This path is called twice on PVHVM - first during bootup via
197          * smp_init -> xen_hvm_cpu_notify, and then if the VCPU is being
198          * hotplugged: cpu_up -> xen_hvm_cpu_notify.
199          * As we can only do the VCPUOP_register_vcpu_info once lets
200          * not over-write its result.
201          *
202          * For PV it is called during restore (xen_vcpu_restore) and bootup
203          * (xen_setup_vcpu_info_placement). The hotplug mechanism does not
204          * use this function.
205          */
206         if (xen_hvm_domain()) {
207                 if (per_cpu(xen_vcpu, cpu) == &per_cpu(xen_vcpu_info, cpu))
208                         return;
209         }
210         if (cpu < MAX_VIRT_CPUS)
211                 per_cpu(xen_vcpu,cpu) = &HYPERVISOR_shared_info->vcpu_info[cpu];
212
213         if (!have_vcpu_info_placement) {
214                 if (cpu >= MAX_VIRT_CPUS)
215                         clamp_max_cpus();
216                 return;
217         }
218
219         vcpup = &per_cpu(xen_vcpu_info, cpu);
220         info.mfn = arbitrary_virt_to_mfn(vcpup);
221         info.offset = offset_in_page(vcpup);
222
223         /* Check to see if the hypervisor will put the vcpu_info
224            structure where we want it, which allows direct access via
225            a percpu-variable.
226            N.B. This hypercall can _only_ be called once per CPU. Subsequent
227            calls will error out with -EINVAL. This is due to the fact that
228            hypervisor has no unregister variant and this hypercall does not
229            allow to over-write info.mfn and info.offset.
230          */
231         err = HYPERVISOR_vcpu_op(VCPUOP_register_vcpu_info, xen_vcpu_nr(cpu),
232                                  &info);
233
234         if (err) {
235                 printk(KERN_DEBUG "register_vcpu_info failed: err=%d\n", err);
236                 have_vcpu_info_placement = 0;
237                 clamp_max_cpus();
238         } else {
239                 /* This cpu is using the registered vcpu info, even if
240                    later ones fail to. */
241                 per_cpu(xen_vcpu, cpu) = vcpup;
242         }
243 }
244
245 /*
246  * On restore, set the vcpu placement up again.
247  * If it fails, then we're in a bad state, since
248  * we can't back out from using it...
249  */
250 void xen_vcpu_restore(void)
251 {
252         int cpu;
253
254         for_each_possible_cpu(cpu) {
255                 bool other_cpu = (cpu != smp_processor_id());
256                 bool is_up = HYPERVISOR_vcpu_op(VCPUOP_is_up, xen_vcpu_nr(cpu),
257                                                 NULL);
258
259                 if (other_cpu && is_up &&
260                     HYPERVISOR_vcpu_op(VCPUOP_down, xen_vcpu_nr(cpu), NULL))
261                         BUG();
262
263                 xen_setup_runstate_info(cpu);
264
265                 if (have_vcpu_info_placement)
266                         xen_vcpu_setup(cpu);
267
268                 if (other_cpu && is_up &&
269                     HYPERVISOR_vcpu_op(VCPUOP_up, xen_vcpu_nr(cpu), NULL))
270                         BUG();
271         }
272 }
273
274 static void __init xen_banner(void)
275 {
276         unsigned version = HYPERVISOR_xen_version(XENVER_version, NULL);
277         struct xen_extraversion extra;
278         HYPERVISOR_xen_version(XENVER_extraversion, &extra);
279
280         pr_info("Booting paravirtualized kernel %son %s\n",
281                 xen_feature(XENFEAT_auto_translated_physmap) ?
282                         "with PVH extensions " : "", pv_info.name);
283         printk(KERN_INFO "Xen version: %d.%d%s%s\n",
284                version >> 16, version & 0xffff, extra.extraversion,
285                xen_feature(XENFEAT_mmu_pt_update_preserve_ad) ? " (preserve-AD)" : "");
286 }
287 /* Check if running on Xen version (major, minor) or later */
288 bool
289 xen_running_on_version_or_later(unsigned int major, unsigned int minor)
290 {
291         unsigned int version;
292
293         if (!xen_domain())
294                 return false;
295
296         version = HYPERVISOR_xen_version(XENVER_version, NULL);
297         if ((((version >> 16) == major) && ((version & 0xffff) >= minor)) ||
298                 ((version >> 16) > major))
299                 return true;
300         return false;
301 }
302
303 #define CPUID_THERM_POWER_LEAF 6
304 #define APERFMPERF_PRESENT 0
305
306 static __read_mostly unsigned int cpuid_leaf1_edx_mask = ~0;
307 static __read_mostly unsigned int cpuid_leaf1_ecx_mask = ~0;
308
309 static __read_mostly unsigned int cpuid_leaf1_ecx_set_mask;
310 static __read_mostly unsigned int cpuid_leaf5_ecx_val;
311 static __read_mostly unsigned int cpuid_leaf5_edx_val;
312
313 static void xen_cpuid(unsigned int *ax, unsigned int *bx,
314                       unsigned int *cx, unsigned int *dx)
315 {
316         unsigned maskebx = ~0;
317         unsigned maskecx = ~0;
318         unsigned maskedx = ~0;
319         unsigned setecx = 0;
320         /*
321          * Mask out inconvenient features, to try and disable as many
322          * unsupported kernel subsystems as possible.
323          */
324         switch (*ax) {
325         case 1:
326                 maskecx = cpuid_leaf1_ecx_mask;
327                 setecx = cpuid_leaf1_ecx_set_mask;
328                 maskedx = cpuid_leaf1_edx_mask;
329                 break;
330
331         case CPUID_MWAIT_LEAF:
332                 /* Synthesize the values.. */
333                 *ax = 0;
334                 *bx = 0;
335                 *cx = cpuid_leaf5_ecx_val;
336                 *dx = cpuid_leaf5_edx_val;
337                 return;
338
339         case CPUID_THERM_POWER_LEAF:
340                 /* Disabling APERFMPERF for kernel usage */
341                 maskecx = ~(1 << APERFMPERF_PRESENT);
342                 break;
343
344         case 0xb:
345                 /* Suppress extended topology stuff */
346                 maskebx = 0;
347                 break;
348         }
349
350         asm(XEN_EMULATE_PREFIX "cpuid"
351                 : "=a" (*ax),
352                   "=b" (*bx),
353                   "=c" (*cx),
354                   "=d" (*dx)
355                 : "0" (*ax), "2" (*cx));
356
357         *bx &= maskebx;
358         *cx &= maskecx;
359         *cx |= setecx;
360         *dx &= maskedx;
361 }
362 STACK_FRAME_NON_STANDARD(xen_cpuid); /* XEN_EMULATE_PREFIX */
363
364 static bool __init xen_check_mwait(void)
365 {
366 #ifdef CONFIG_ACPI
367         struct xen_platform_op op = {
368                 .cmd                    = XENPF_set_processor_pminfo,
369                 .u.set_pminfo.id        = -1,
370                 .u.set_pminfo.type      = XEN_PM_PDC,
371         };
372         uint32_t buf[3];
373         unsigned int ax, bx, cx, dx;
374         unsigned int mwait_mask;
375
376         /* We need to determine whether it is OK to expose the MWAIT
377          * capability to the kernel to harvest deeper than C3 states from ACPI
378          * _CST using the processor_harvest_xen.c module. For this to work, we
379          * need to gather the MWAIT_LEAF values (which the cstate.c code
380          * checks against). The hypervisor won't expose the MWAIT flag because
381          * it would break backwards compatibility; so we will find out directly
382          * from the hardware and hypercall.
383          */
384         if (!xen_initial_domain())
385                 return false;
386
387         /*
388          * When running under platform earlier than Xen4.2, do not expose
389          * mwait, to avoid the risk of loading native acpi pad driver
390          */
391         if (!xen_running_on_version_or_later(4, 2))
392                 return false;
393
394         ax = 1;
395         cx = 0;
396
397         native_cpuid(&ax, &bx, &cx, &dx);
398
399         mwait_mask = (1 << (X86_FEATURE_EST % 32)) |
400                      (1 << (X86_FEATURE_MWAIT % 32));
401
402         if ((cx & mwait_mask) != mwait_mask)
403                 return false;
404
405         /* We need to emulate the MWAIT_LEAF and for that we need both
406          * ecx and edx. The hypercall provides only partial information.
407          */
408
409         ax = CPUID_MWAIT_LEAF;
410         bx = 0;
411         cx = 0;
412         dx = 0;
413
414         native_cpuid(&ax, &bx, &cx, &dx);
415
416         /* Ask the Hypervisor whether to clear ACPI_PDC_C_C2C3_FFH. If so,
417          * don't expose MWAIT_LEAF and let ACPI pick the IOPORT version of C3.
418          */
419         buf[0] = ACPI_PDC_REVISION_ID;
420         buf[1] = 1;
421         buf[2] = (ACPI_PDC_C_CAPABILITY_SMP | ACPI_PDC_EST_CAPABILITY_SWSMP);
422
423         set_xen_guest_handle(op.u.set_pminfo.pdc, buf);
424
425         if ((HYPERVISOR_platform_op(&op) == 0) &&
426             (buf[2] & (ACPI_PDC_C_C1_FFH | ACPI_PDC_C_C2C3_FFH))) {
427                 cpuid_leaf5_ecx_val = cx;
428                 cpuid_leaf5_edx_val = dx;
429         }
430         return true;
431 #else
432         return false;
433 #endif
434 }
435 static void __init xen_init_cpuid_mask(void)
436 {
437         unsigned int ax, bx, cx, dx;
438         unsigned int xsave_mask;
439
440         cpuid_leaf1_edx_mask =
441                 ~((1 << X86_FEATURE_MTRR) |  /* disable MTRR */
442                   (1 << X86_FEATURE_ACC));   /* thermal monitoring */
443
444         if (!xen_initial_domain())
445                 cpuid_leaf1_edx_mask &=
446                         ~((1 << X86_FEATURE_ACPI));  /* disable ACPI */
447
448         cpuid_leaf1_ecx_mask &= ~(1 << (X86_FEATURE_X2APIC % 32));
449
450         ax = 1;
451         cx = 0;
452         cpuid(1, &ax, &bx, &cx, &dx);
453
454         xsave_mask =
455                 (1 << (X86_FEATURE_XSAVE % 32)) |
456                 (1 << (X86_FEATURE_OSXSAVE % 32));
457
458         /* Xen will set CR4.OSXSAVE if supported and not disabled by force */
459         if ((cx & xsave_mask) != xsave_mask)
460                 cpuid_leaf1_ecx_mask &= ~xsave_mask; /* disable XSAVE & OSXSAVE */
461         if (xen_check_mwait())
462                 cpuid_leaf1_ecx_set_mask = (1 << (X86_FEATURE_MWAIT % 32));
463 }
464
465 static void xen_set_debugreg(int reg, unsigned long val)
466 {
467         HYPERVISOR_set_debugreg(reg, val);
468 }
469
470 static unsigned long xen_get_debugreg(int reg)
471 {
472         return HYPERVISOR_get_debugreg(reg);
473 }
474
475 static void xen_end_context_switch(struct task_struct *next)
476 {
477         xen_mc_flush();
478         paravirt_end_context_switch(next);
479 }
480
481 static unsigned long xen_store_tr(void)
482 {
483         return 0;
484 }
485
486 /*
487  * Set the page permissions for a particular virtual address.  If the
488  * address is a vmalloc mapping (or other non-linear mapping), then
489  * find the linear mapping of the page and also set its protections to
490  * match.
491  */
492 static void set_aliased_prot(void *v, pgprot_t prot)
493 {
494         int level;
495         pte_t *ptep;
496         pte_t pte;
497         unsigned long pfn;
498         struct page *page;
499         unsigned char dummy;
500
501         ptep = lookup_address((unsigned long)v, &level);
502         BUG_ON(ptep == NULL);
503
504         pfn = pte_pfn(*ptep);
505         page = pfn_to_page(pfn);
506
507         pte = pfn_pte(pfn, prot);
508
509         /*
510          * Careful: update_va_mapping() will fail if the virtual address
511          * we're poking isn't populated in the page tables.  We don't
512          * need to worry about the direct map (that's always in the page
513          * tables), but we need to be careful about vmap space.  In
514          * particular, the top level page table can lazily propagate
515          * entries between processes, so if we've switched mms since we
516          * vmapped the target in the first place, we might not have the
517          * top-level page table entry populated.
518          *
519          * We disable preemption because we want the same mm active when
520          * we probe the target and when we issue the hypercall.  We'll
521          * have the same nominal mm, but if we're a kernel thread, lazy
522          * mm dropping could change our pgd.
523          *
524          * Out of an abundance of caution, this uses __get_user() to fault
525          * in the target address just in case there's some obscure case
526          * in which the target address isn't readable.
527          */
528
529         preempt_disable();
530
531         pagefault_disable();    /* Avoid warnings due to being atomic. */
532         __get_user(dummy, (unsigned char __user __force *)v);
533         pagefault_enable();
534
535         if (HYPERVISOR_update_va_mapping((unsigned long)v, pte, 0))
536                 BUG();
537
538         if (!PageHighMem(page)) {
539                 void *av = __va(PFN_PHYS(pfn));
540
541                 if (av != v)
542                         if (HYPERVISOR_update_va_mapping((unsigned long)av, pte, 0))
543                                 BUG();
544         } else
545                 kmap_flush_unused();
546
547         preempt_enable();
548 }
549
550 static void xen_alloc_ldt(struct desc_struct *ldt, unsigned entries)
551 {
552         const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
553         int i;
554
555         /*
556          * We need to mark the all aliases of the LDT pages RO.  We
557          * don't need to call vm_flush_aliases(), though, since that's
558          * only responsible for flushing aliases out the TLBs, not the
559          * page tables, and Xen will flush the TLB for us if needed.
560          *
561          * To avoid confusing future readers: none of this is necessary
562          * to load the LDT.  The hypervisor only checks this when the
563          * LDT is faulted in due to subsequent descriptor access.
564          */
565
566         for(i = 0; i < entries; i += entries_per_page)
567                 set_aliased_prot(ldt + i, PAGE_KERNEL_RO);
568 }
569
570 static void xen_free_ldt(struct desc_struct *ldt, unsigned entries)
571 {
572         const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
573         int i;
574
575         for(i = 0; i < entries; i += entries_per_page)
576                 set_aliased_prot(ldt + i, PAGE_KERNEL);
577 }
578
579 static void xen_set_ldt(const void *addr, unsigned entries)
580 {
581         struct mmuext_op *op;
582         struct multicall_space mcs = xen_mc_entry(sizeof(*op));
583
584         trace_xen_cpu_set_ldt(addr, entries);
585
586         op = mcs.args;
587         op->cmd = MMUEXT_SET_LDT;
588         op->arg1.linear_addr = (unsigned long)addr;
589         op->arg2.nr_ents = entries;
590
591         MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
592
593         xen_mc_issue(PARAVIRT_LAZY_CPU);
594 }
595
596 static void xen_load_gdt(const struct desc_ptr *dtr)
597 {
598         unsigned long va = dtr->address;
599         unsigned int size = dtr->size + 1;
600         unsigned pages = DIV_ROUND_UP(size, PAGE_SIZE);
601         unsigned long frames[pages];
602         int f;
603
604         /*
605          * A GDT can be up to 64k in size, which corresponds to 8192
606          * 8-byte entries, or 16 4k pages..
607          */
608
609         BUG_ON(size > 65536);
610         BUG_ON(va & ~PAGE_MASK);
611
612         for (f = 0; va < dtr->address + size; va += PAGE_SIZE, f++) {
613                 int level;
614                 pte_t *ptep;
615                 unsigned long pfn, mfn;
616                 void *virt;
617
618                 /*
619                  * The GDT is per-cpu and is in the percpu data area.
620                  * That can be virtually mapped, so we need to do a
621                  * page-walk to get the underlying MFN for the
622                  * hypercall.  The page can also be in the kernel's
623                  * linear range, so we need to RO that mapping too.
624                  */
625                 ptep = lookup_address(va, &level);
626                 BUG_ON(ptep == NULL);
627
628                 pfn = pte_pfn(*ptep);
629                 mfn = pfn_to_mfn(pfn);
630                 virt = __va(PFN_PHYS(pfn));
631
632                 frames[f] = mfn;
633
634                 make_lowmem_page_readonly((void *)va);
635                 make_lowmem_page_readonly(virt);
636         }
637
638         if (HYPERVISOR_set_gdt(frames, size / sizeof(struct desc_struct)))
639                 BUG();
640 }
641
642 /*
643  * load_gdt for early boot, when the gdt is only mapped once
644  */
645 static void __init xen_load_gdt_boot(const struct desc_ptr *dtr)
646 {
647         unsigned long va = dtr->address;
648         unsigned int size = dtr->size + 1;
649         unsigned pages = DIV_ROUND_UP(size, PAGE_SIZE);
650         unsigned long frames[pages];
651         int f;
652
653         /*
654          * A GDT can be up to 64k in size, which corresponds to 8192
655          * 8-byte entries, or 16 4k pages..
656          */
657
658         BUG_ON(size > 65536);
659         BUG_ON(va & ~PAGE_MASK);
660
661         for (f = 0; va < dtr->address + size; va += PAGE_SIZE, f++) {
662                 pte_t pte;
663                 unsigned long pfn, mfn;
664
665                 pfn = virt_to_pfn(va);
666                 mfn = pfn_to_mfn(pfn);
667
668                 pte = pfn_pte(pfn, PAGE_KERNEL_RO);
669
670                 if (HYPERVISOR_update_va_mapping((unsigned long)va, pte, 0))
671                         BUG();
672
673                 frames[f] = mfn;
674         }
675
676         if (HYPERVISOR_set_gdt(frames, size / sizeof(struct desc_struct)))
677                 BUG();
678 }
679
680 static inline bool desc_equal(const struct desc_struct *d1,
681                               const struct desc_struct *d2)
682 {
683         return d1->a == d2->a && d1->b == d2->b;
684 }
685
686 static void load_TLS_descriptor(struct thread_struct *t,
687                                 unsigned int cpu, unsigned int i)
688 {
689         struct desc_struct *shadow = &per_cpu(shadow_tls_desc, cpu).desc[i];
690         struct desc_struct *gdt;
691         xmaddr_t maddr;
692         struct multicall_space mc;
693
694         if (desc_equal(shadow, &t->tls_array[i]))
695                 return;
696
697         *shadow = t->tls_array[i];
698
699         gdt = get_cpu_gdt_table(cpu);
700         maddr = arbitrary_virt_to_machine(&gdt[GDT_ENTRY_TLS_MIN+i]);
701         mc = __xen_mc_entry(0);
702
703         MULTI_update_descriptor(mc.mc, maddr.maddr, t->tls_array[i]);
704 }
705
706 static void xen_load_tls(struct thread_struct *t, unsigned int cpu)
707 {
708         /*
709          * XXX sleazy hack: If we're being called in a lazy-cpu zone
710          * and lazy gs handling is enabled, it means we're in a
711          * context switch, and %gs has just been saved.  This means we
712          * can zero it out to prevent faults on exit from the
713          * hypervisor if the next process has no %gs.  Either way, it
714          * has been saved, and the new value will get loaded properly.
715          * This will go away as soon as Xen has been modified to not
716          * save/restore %gs for normal hypercalls.
717          *
718          * On x86_64, this hack is not used for %gs, because gs points
719          * to KERNEL_GS_BASE (and uses it for PDA references), so we
720          * must not zero %gs on x86_64
721          *
722          * For x86_64, we need to zero %fs, otherwise we may get an
723          * exception between the new %fs descriptor being loaded and
724          * %fs being effectively cleared at __switch_to().
725          */
726         if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_CPU) {
727 #ifdef CONFIG_X86_32
728                 lazy_load_gs(0);
729 #else
730                 loadsegment(fs, 0);
731 #endif
732         }
733
734         xen_mc_batch();
735
736         load_TLS_descriptor(t, cpu, 0);
737         load_TLS_descriptor(t, cpu, 1);
738         load_TLS_descriptor(t, cpu, 2);
739
740         xen_mc_issue(PARAVIRT_LAZY_CPU);
741 }
742
743 #ifdef CONFIG_X86_64
744 static void xen_load_gs_index(unsigned int idx)
745 {
746         if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL, idx))
747                 BUG();
748 }
749 #endif
750
751 static void xen_write_ldt_entry(struct desc_struct *dt, int entrynum,
752                                 const void *ptr)
753 {
754         xmaddr_t mach_lp = arbitrary_virt_to_machine(&dt[entrynum]);
755         u64 entry = *(u64 *)ptr;
756
757         trace_xen_cpu_write_ldt_entry(dt, entrynum, entry);
758
759         preempt_disable();
760
761         xen_mc_flush();
762         if (HYPERVISOR_update_descriptor(mach_lp.maddr, entry))
763                 BUG();
764
765         preempt_enable();
766 }
767
768 static int cvt_gate_to_trap(int vector, const gate_desc *val,
769                             struct trap_info *info)
770 {
771         unsigned long addr;
772
773         if (val->type != GATE_TRAP && val->type != GATE_INTERRUPT)
774                 return 0;
775
776         info->vector = vector;
777
778         addr = gate_offset(*val);
779 #ifdef CONFIG_X86_64
780         /*
781          * Look for known traps using IST, and substitute them
782          * appropriately.  The debugger ones are the only ones we care
783          * about.  Xen will handle faults like double_fault,
784          * so we should never see them.  Warn if
785          * there's an unexpected IST-using fault handler.
786          */
787         if (addr == (unsigned long)debug)
788                 addr = (unsigned long)xen_debug;
789         else if (addr == (unsigned long)int3)
790                 addr = (unsigned long)xen_int3;
791         else if (addr == (unsigned long)stack_segment)
792                 addr = (unsigned long)xen_stack_segment;
793         else if (addr == (unsigned long)double_fault) {
794                 /* Don't need to handle these */
795                 return 0;
796 #ifdef CONFIG_X86_MCE
797         } else if (addr == (unsigned long)machine_check) {
798                 /*
799                  * when xen hypervisor inject vMCE to guest,
800                  * use native mce handler to handle it
801                  */
802                 ;
803 #endif
804         } else if (addr == (unsigned long)nmi)
805                 /*
806                  * Use the native version as well.
807                  */
808                 ;
809         else {
810                 /* Some other trap using IST? */
811                 if (WARN_ON(val->ist != 0))
812                         return 0;
813         }
814 #endif  /* CONFIG_X86_64 */
815         info->address = addr;
816
817         info->cs = gate_segment(*val);
818         info->flags = val->dpl;
819         /* interrupt gates clear IF */
820         if (val->type == GATE_INTERRUPT)
821                 info->flags |= 1 << 2;
822
823         return 1;
824 }
825
826 /* Locations of each CPU's IDT */
827 static DEFINE_PER_CPU(struct desc_ptr, idt_desc);
828
829 /* Set an IDT entry.  If the entry is part of the current IDT, then
830    also update Xen. */
831 static void xen_write_idt_entry(gate_desc *dt, int entrynum, const gate_desc *g)
832 {
833         unsigned long p = (unsigned long)&dt[entrynum];
834         unsigned long start, end;
835
836         trace_xen_cpu_write_idt_entry(dt, entrynum, g);
837
838         preempt_disable();
839
840         start = __this_cpu_read(idt_desc.address);
841         end = start + __this_cpu_read(idt_desc.size) + 1;
842
843         xen_mc_flush();
844
845         native_write_idt_entry(dt, entrynum, g);
846
847         if (p >= start && (p + 8) <= end) {
848                 struct trap_info info[2];
849
850                 info[1].address = 0;
851
852                 if (cvt_gate_to_trap(entrynum, g, &info[0]))
853                         if (HYPERVISOR_set_trap_table(info))
854                                 BUG();
855         }
856
857         preempt_enable();
858 }
859
860 static void xen_convert_trap_info(const struct desc_ptr *desc,
861                                   struct trap_info *traps)
862 {
863         unsigned in, out, count;
864
865         count = (desc->size+1) / sizeof(gate_desc);
866         BUG_ON(count > 256);
867
868         for (in = out = 0; in < count; in++) {
869                 gate_desc *entry = (gate_desc*)(desc->address) + in;
870
871                 if (cvt_gate_to_trap(in, entry, &traps[out]))
872                         out++;
873         }
874         traps[out].address = 0;
875 }
876
877 void xen_copy_trap_info(struct trap_info *traps)
878 {
879         const struct desc_ptr *desc = this_cpu_ptr(&idt_desc);
880
881         xen_convert_trap_info(desc, traps);
882 }
883
884 /* Load a new IDT into Xen.  In principle this can be per-CPU, so we
885    hold a spinlock to protect the static traps[] array (static because
886    it avoids allocation, and saves stack space). */
887 static void xen_load_idt(const struct desc_ptr *desc)
888 {
889         static DEFINE_SPINLOCK(lock);
890         static struct trap_info traps[257];
891
892         trace_xen_cpu_load_idt(desc);
893
894         spin_lock(&lock);
895
896         memcpy(this_cpu_ptr(&idt_desc), desc, sizeof(idt_desc));
897
898         xen_convert_trap_info(desc, traps);
899
900         xen_mc_flush();
901         if (HYPERVISOR_set_trap_table(traps))
902                 BUG();
903
904         spin_unlock(&lock);
905 }
906
907 /* Write a GDT descriptor entry.  Ignore LDT descriptors, since
908    they're handled differently. */
909 static void xen_write_gdt_entry(struct desc_struct *dt, int entry,
910                                 const void *desc, int type)
911 {
912         trace_xen_cpu_write_gdt_entry(dt, entry, desc, type);
913
914         preempt_disable();
915
916         switch (type) {
917         case DESC_LDT:
918         case DESC_TSS:
919                 /* ignore */
920                 break;
921
922         default: {
923                 xmaddr_t maddr = arbitrary_virt_to_machine(&dt[entry]);
924
925                 xen_mc_flush();
926                 if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc))
927                         BUG();
928         }
929
930         }
931
932         preempt_enable();
933 }
934
935 /*
936  * Version of write_gdt_entry for use at early boot-time needed to
937  * update an entry as simply as possible.
938  */
939 static void __init xen_write_gdt_entry_boot(struct desc_struct *dt, int entry,
940                                             const void *desc, int type)
941 {
942         trace_xen_cpu_write_gdt_entry(dt, entry, desc, type);
943
944         switch (type) {
945         case DESC_LDT:
946         case DESC_TSS:
947                 /* ignore */
948                 break;
949
950         default: {
951                 xmaddr_t maddr = virt_to_machine(&dt[entry]);
952
953                 if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc))
954                         dt[entry] = *(struct desc_struct *)desc;
955         }
956
957         }
958 }
959
960 static void xen_load_sp0(struct tss_struct *tss,
961                          struct thread_struct *thread)
962 {
963         struct multicall_space mcs;
964
965         mcs = xen_mc_entry(0);
966         MULTI_stack_switch(mcs.mc, __KERNEL_DS, thread->sp0);
967         xen_mc_issue(PARAVIRT_LAZY_CPU);
968         tss->x86_tss.sp0 = thread->sp0;
969 }
970
971 void xen_set_iopl_mask(unsigned mask)
972 {
973         struct physdev_set_iopl set_iopl;
974
975         /* Force the change at ring 0. */
976         set_iopl.iopl = (mask == 0) ? 1 : (mask >> 12) & 3;
977         HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);
978 }
979
980 static void xen_io_delay(void)
981 {
982 }
983
984 static void xen_clts(void)
985 {
986         struct multicall_space mcs;
987
988         mcs = xen_mc_entry(0);
989
990         MULTI_fpu_taskswitch(mcs.mc, 0);
991
992         xen_mc_issue(PARAVIRT_LAZY_CPU);
993 }
994
995 static DEFINE_PER_CPU(unsigned long, xen_cr0_value);
996
997 static unsigned long xen_read_cr0(void)
998 {
999         unsigned long cr0 = this_cpu_read(xen_cr0_value);
1000
1001         if (unlikely(cr0 == 0)) {
1002                 cr0 = native_read_cr0();
1003                 this_cpu_write(xen_cr0_value, cr0);
1004         }
1005
1006         return cr0;
1007 }
1008
1009 static void xen_write_cr0(unsigned long cr0)
1010 {
1011         struct multicall_space mcs;
1012
1013         this_cpu_write(xen_cr0_value, cr0);
1014
1015         /* Only pay attention to cr0.TS; everything else is
1016            ignored. */
1017         mcs = xen_mc_entry(0);
1018
1019         MULTI_fpu_taskswitch(mcs.mc, (cr0 & X86_CR0_TS) != 0);
1020
1021         xen_mc_issue(PARAVIRT_LAZY_CPU);
1022 }
1023
1024 static void xen_write_cr4(unsigned long cr4)
1025 {
1026         cr4 &= ~(X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PCE);
1027
1028         native_write_cr4(cr4);
1029 }
1030 #ifdef CONFIG_X86_64
1031 static inline unsigned long xen_read_cr8(void)
1032 {
1033         return 0;
1034 }
1035 static inline void xen_write_cr8(unsigned long val)
1036 {
1037         BUG_ON(val);
1038 }
1039 #endif
1040
1041 static u64 xen_read_msr_safe(unsigned int msr, int *err)
1042 {
1043         u64 val;
1044
1045         if (pmu_msr_read(msr, &val, err))
1046                 return val;
1047
1048         val = native_read_msr_safe(msr, err);
1049         switch (msr) {
1050         case MSR_IA32_APICBASE:
1051 #ifdef CONFIG_X86_X2APIC
1052                 if (!(cpuid_ecx(1) & (1 << (X86_FEATURE_X2APIC & 31))))
1053 #endif
1054                         val &= ~X2APIC_ENABLE;
1055                 break;
1056         }
1057         return val;
1058 }
1059
1060 static int xen_write_msr_safe(unsigned int msr, unsigned low, unsigned high)
1061 {
1062         int ret;
1063
1064         ret = 0;
1065
1066         switch (msr) {
1067 #ifdef CONFIG_X86_64
1068                 unsigned which;
1069                 u64 base;
1070
1071         case MSR_FS_BASE:               which = SEGBASE_FS; goto set;
1072         case MSR_KERNEL_GS_BASE:        which = SEGBASE_GS_USER; goto set;
1073         case MSR_GS_BASE:               which = SEGBASE_GS_KERNEL; goto set;
1074
1075         set:
1076                 base = ((u64)high << 32) | low;
1077                 if (HYPERVISOR_set_segment_base(which, base) != 0)
1078                         ret = -EIO;
1079                 break;
1080 #endif
1081
1082         case MSR_STAR:
1083         case MSR_CSTAR:
1084         case MSR_LSTAR:
1085         case MSR_SYSCALL_MASK:
1086         case MSR_IA32_SYSENTER_CS:
1087         case MSR_IA32_SYSENTER_ESP:
1088         case MSR_IA32_SYSENTER_EIP:
1089                 /* Fast syscall setup is all done in hypercalls, so
1090                    these are all ignored.  Stub them out here to stop
1091                    Xen console noise. */
1092                 break;
1093
1094         default:
1095                 if (!pmu_msr_write(msr, low, high, &ret))
1096                         ret = native_write_msr_safe(msr, low, high);
1097         }
1098
1099         return ret;
1100 }
1101
1102 static u64 xen_read_msr(unsigned int msr)
1103 {
1104         /*
1105          * This will silently swallow a #GP from RDMSR.  It may be worth
1106          * changing that.
1107          */
1108         int err;
1109
1110         return xen_read_msr_safe(msr, &err);
1111 }
1112
1113 static void xen_write_msr(unsigned int msr, unsigned low, unsigned high)
1114 {
1115         /*
1116          * This will silently swallow a #GP from WRMSR.  It may be worth
1117          * changing that.
1118          */
1119         xen_write_msr_safe(msr, low, high);
1120 }
1121
1122 void xen_setup_shared_info(void)
1123 {
1124         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1125                 set_fixmap(FIX_PARAVIRT_BOOTMAP,
1126                            xen_start_info->shared_info);
1127
1128                 HYPERVISOR_shared_info =
1129                         (struct shared_info *)fix_to_virt(FIX_PARAVIRT_BOOTMAP);
1130         } else
1131                 HYPERVISOR_shared_info =
1132                         (struct shared_info *)__va(xen_start_info->shared_info);
1133
1134 #ifndef CONFIG_SMP
1135         /* In UP this is as good a place as any to set up shared info */
1136         xen_setup_vcpu_info_placement();
1137 #endif
1138
1139         xen_setup_mfn_list_list();
1140 }
1141
1142 /* This is called once we have the cpu_possible_mask */
1143 void xen_setup_vcpu_info_placement(void)
1144 {
1145         int cpu;
1146
1147         for_each_possible_cpu(cpu) {
1148                 /* Set up direct vCPU id mapping for PV guests. */
1149                 per_cpu(xen_vcpu_id, cpu) = cpu;
1150                 xen_vcpu_setup(cpu);
1151         }
1152
1153         /* xen_vcpu_setup managed to place the vcpu_info within the
1154          * percpu area for all cpus, so make use of it. Note that for
1155          * PVH we want to use native IRQ mechanism. */
1156         if (have_vcpu_info_placement && !xen_pvh_domain()) {
1157                 pv_irq_ops.save_fl = __PV_IS_CALLEE_SAVE(xen_save_fl_direct);
1158                 pv_irq_ops.restore_fl = __PV_IS_CALLEE_SAVE(xen_restore_fl_direct);
1159                 pv_irq_ops.irq_disable = __PV_IS_CALLEE_SAVE(xen_irq_disable_direct);
1160                 pv_irq_ops.irq_enable = __PV_IS_CALLEE_SAVE(xen_irq_enable_direct);
1161                 pv_mmu_ops.read_cr2 = xen_read_cr2_direct;
1162         }
1163 }
1164
1165 static unsigned xen_patch(u8 type, u16 clobbers, void *insnbuf,
1166                           unsigned long addr, unsigned len)
1167 {
1168         char *start, *end, *reloc;
1169         unsigned ret;
1170
1171         start = end = reloc = NULL;
1172
1173 #define SITE(op, x)                                                     \
1174         case PARAVIRT_PATCH(op.x):                                      \
1175         if (have_vcpu_info_placement) {                                 \
1176                 start = (char *)xen_##x##_direct;                       \
1177                 end = xen_##x##_direct_end;                             \
1178                 reloc = xen_##x##_direct_reloc;                         \
1179         }                                                               \
1180         goto patch_site
1181
1182         switch (type) {
1183                 SITE(pv_irq_ops, irq_enable);
1184                 SITE(pv_irq_ops, irq_disable);
1185                 SITE(pv_irq_ops, save_fl);
1186                 SITE(pv_irq_ops, restore_fl);
1187 #undef SITE
1188
1189         patch_site:
1190                 if (start == NULL || (end-start) > len)
1191                         goto default_patch;
1192
1193                 ret = paravirt_patch_insns(insnbuf, len, start, end);
1194
1195                 /* Note: because reloc is assigned from something that
1196                    appears to be an array, gcc assumes it's non-null,
1197                    but doesn't know its relationship with start and
1198                    end. */
1199                 if (reloc > start && reloc < end) {
1200                         int reloc_off = reloc - start;
1201                         long *relocp = (long *)(insnbuf + reloc_off);
1202                         long delta = start - (char *)addr;
1203
1204                         *relocp += delta;
1205                 }
1206                 break;
1207
1208         default_patch:
1209         default:
1210                 ret = paravirt_patch_default(type, clobbers, insnbuf,
1211                                              addr, len);
1212                 break;
1213         }
1214
1215         return ret;
1216 }
1217
1218 static const struct pv_info xen_info __initconst = {
1219         .shared_kernel_pmd = 0,
1220
1221 #ifdef CONFIG_X86_64
1222         .extra_user_64bit_cs = FLAT_USER_CS64,
1223 #endif
1224         .name = "Xen",
1225 };
1226
1227 static const struct pv_init_ops xen_init_ops __initconst = {
1228         .patch = xen_patch,
1229 };
1230
1231 static const struct pv_cpu_ops xen_cpu_ops __initconst = {
1232         .cpuid = xen_cpuid,
1233
1234         .set_debugreg = xen_set_debugreg,
1235         .get_debugreg = xen_get_debugreg,
1236
1237         .clts = xen_clts,
1238
1239         .read_cr0 = xen_read_cr0,
1240         .write_cr0 = xen_write_cr0,
1241
1242         .read_cr4 = native_read_cr4,
1243         .read_cr4_safe = native_read_cr4_safe,
1244         .write_cr4 = xen_write_cr4,
1245
1246 #ifdef CONFIG_X86_64
1247         .read_cr8 = xen_read_cr8,
1248         .write_cr8 = xen_write_cr8,
1249 #endif
1250
1251         .wbinvd = native_wbinvd,
1252
1253         .read_msr = xen_read_msr,
1254         .write_msr = xen_write_msr,
1255
1256         .read_msr_safe = xen_read_msr_safe,
1257         .write_msr_safe = xen_write_msr_safe,
1258
1259         .read_pmc = xen_read_pmc,
1260
1261         .iret = xen_iret,
1262 #ifdef CONFIG_X86_64
1263         .usergs_sysret64 = xen_sysret64,
1264 #endif
1265
1266         .load_tr_desc = paravirt_nop,
1267         .set_ldt = xen_set_ldt,
1268         .load_gdt = xen_load_gdt,
1269         .load_idt = xen_load_idt,
1270         .load_tls = xen_load_tls,
1271 #ifdef CONFIG_X86_64
1272         .load_gs_index = xen_load_gs_index,
1273 #endif
1274
1275         .alloc_ldt = xen_alloc_ldt,
1276         .free_ldt = xen_free_ldt,
1277
1278         .store_idt = native_store_idt,
1279         .store_tr = xen_store_tr,
1280
1281         .write_ldt_entry = xen_write_ldt_entry,
1282         .write_gdt_entry = xen_write_gdt_entry,
1283         .write_idt_entry = xen_write_idt_entry,
1284         .load_sp0 = xen_load_sp0,
1285
1286         .set_iopl_mask = xen_set_iopl_mask,
1287         .io_delay = xen_io_delay,
1288
1289         /* Xen takes care of %gs when switching to usermode for us */
1290         .swapgs = paravirt_nop,
1291
1292         .start_context_switch = paravirt_start_context_switch,
1293         .end_context_switch = xen_end_context_switch,
1294 };
1295
1296 static void xen_reboot(int reason)
1297 {
1298         struct sched_shutdown r = { .reason = reason };
1299         int cpu;
1300
1301         for_each_online_cpu(cpu)
1302                 xen_pmu_finish(cpu);
1303
1304         if (HYPERVISOR_sched_op(SCHEDOP_shutdown, &r))
1305                 BUG();
1306 }
1307
1308 static void xen_restart(char *msg)
1309 {
1310         xen_reboot(SHUTDOWN_reboot);
1311 }
1312
1313 static void xen_emergency_restart(void)
1314 {
1315         xen_reboot(SHUTDOWN_reboot);
1316 }
1317
1318 static void xen_machine_halt(void)
1319 {
1320         xen_reboot(SHUTDOWN_poweroff);
1321 }
1322
1323 static void xen_machine_power_off(void)
1324 {
1325         if (pm_power_off)
1326                 pm_power_off();
1327         xen_reboot(SHUTDOWN_poweroff);
1328 }
1329
1330 static void xen_crash_shutdown(struct pt_regs *regs)
1331 {
1332         xen_reboot(SHUTDOWN_crash);
1333 }
1334
1335 static int
1336 xen_panic_event(struct notifier_block *this, unsigned long event, void *ptr)
1337 {
1338         xen_reboot(SHUTDOWN_crash);
1339         return NOTIFY_DONE;
1340 }
1341
1342 static struct notifier_block xen_panic_block = {
1343         .notifier_call= xen_panic_event,
1344         .priority = INT_MIN
1345 };
1346
1347 int xen_panic_handler_init(void)
1348 {
1349         atomic_notifier_chain_register(&panic_notifier_list, &xen_panic_block);
1350         return 0;
1351 }
1352
1353 static const struct machine_ops xen_machine_ops __initconst = {
1354         .restart = xen_restart,
1355         .halt = xen_machine_halt,
1356         .power_off = xen_machine_power_off,
1357         .shutdown = xen_machine_halt,
1358         .crash_shutdown = xen_crash_shutdown,
1359         .emergency_restart = xen_emergency_restart,
1360 };
1361
1362 static unsigned char xen_get_nmi_reason(void)
1363 {
1364         unsigned char reason = 0;
1365
1366         /* Construct a value which looks like it came from port 0x61. */
1367         if (test_bit(_XEN_NMIREASON_io_error,
1368                      &HYPERVISOR_shared_info->arch.nmi_reason))
1369                 reason |= NMI_REASON_IOCHK;
1370         if (test_bit(_XEN_NMIREASON_pci_serr,
1371                      &HYPERVISOR_shared_info->arch.nmi_reason))
1372                 reason |= NMI_REASON_SERR;
1373
1374         return reason;
1375 }
1376
1377 static void __init xen_boot_params_init_edd(void)
1378 {
1379 #if IS_ENABLED(CONFIG_EDD)
1380         struct xen_platform_op op;
1381         struct edd_info *edd_info;
1382         u32 *mbr_signature;
1383         unsigned nr;
1384         int ret;
1385
1386         edd_info = boot_params.eddbuf;
1387         mbr_signature = boot_params.edd_mbr_sig_buffer;
1388
1389         op.cmd = XENPF_firmware_info;
1390
1391         op.u.firmware_info.type = XEN_FW_DISK_INFO;
1392         for (nr = 0; nr < EDDMAXNR; nr++) {
1393                 struct edd_info *info = edd_info + nr;
1394
1395                 op.u.firmware_info.index = nr;
1396                 info->params.length = sizeof(info->params);
1397                 set_xen_guest_handle(op.u.firmware_info.u.disk_info.edd_params,
1398                                      &info->params);
1399                 ret = HYPERVISOR_platform_op(&op);
1400                 if (ret)
1401                         break;
1402
1403 #define C(x) info->x = op.u.firmware_info.u.disk_info.x
1404                 C(device);
1405                 C(version);
1406                 C(interface_support);
1407                 C(legacy_max_cylinder);
1408                 C(legacy_max_head);
1409                 C(legacy_sectors_per_track);
1410 #undef C
1411         }
1412         boot_params.eddbuf_entries = nr;
1413
1414         op.u.firmware_info.type = XEN_FW_DISK_MBR_SIGNATURE;
1415         for (nr = 0; nr < EDD_MBR_SIG_MAX; nr++) {
1416                 op.u.firmware_info.index = nr;
1417                 ret = HYPERVISOR_platform_op(&op);
1418                 if (ret)
1419                         break;
1420                 mbr_signature[nr] = op.u.firmware_info.u.disk_mbr_signature.mbr_signature;
1421         }
1422         boot_params.edd_mbr_sig_buf_entries = nr;
1423 #endif
1424 }
1425
1426 /*
1427  * Set up the GDT and segment registers for -fstack-protector.  Until
1428  * we do this, we have to be careful not to call any stack-protected
1429  * function, which is most of the kernel.
1430  *
1431  * Note, that it is __ref because the only caller of this after init
1432  * is PVH which is not going to use xen_load_gdt_boot or other
1433  * __init functions.
1434  */
1435 static void __ref xen_setup_gdt(int cpu)
1436 {
1437         if (xen_feature(XENFEAT_auto_translated_physmap)) {
1438 #ifdef CONFIG_X86_64
1439                 unsigned long dummy;
1440
1441                 load_percpu_segment(cpu); /* We need to access per-cpu area */
1442                 switch_to_new_gdt(cpu); /* GDT and GS set */
1443
1444                 /* We are switching of the Xen provided GDT to our HVM mode
1445                  * GDT. The new GDT has  __KERNEL_CS with CS.L = 1
1446                  * and we are jumping to reload it.
1447                  */
1448                 asm volatile ("pushq %0\n"
1449                               "leaq 1f(%%rip),%0\n"
1450                               "pushq %0\n"
1451                               "lretq\n"
1452                               "1:\n"
1453                               : "=&r" (dummy) : "0" (__KERNEL_CS));
1454
1455                 /*
1456                  * While not needed, we also set the %es, %ds, and %fs
1457                  * to zero. We don't care about %ss as it is NULL.
1458                  * Strictly speaking this is not needed as Xen zeros those
1459                  * out (and also MSR_FS_BASE, MSR_GS_BASE, MSR_KERNEL_GS_BASE)
1460                  *
1461                  * Linux zeros them in cpu_init() and in secondary_startup_64
1462                  * (for BSP).
1463                  */
1464                 loadsegment(es, 0);
1465                 loadsegment(ds, 0);
1466                 loadsegment(fs, 0);
1467 #else
1468                 /* PVH: TODO Implement. */
1469                 BUG();
1470 #endif
1471                 return; /* PVH does not need any PV GDT ops. */
1472         }
1473         pv_cpu_ops.write_gdt_entry = xen_write_gdt_entry_boot;
1474         pv_cpu_ops.load_gdt = xen_load_gdt_boot;
1475
1476         setup_stack_canary_segment(0);
1477         switch_to_new_gdt(0);
1478
1479         pv_cpu_ops.write_gdt_entry = xen_write_gdt_entry;
1480         pv_cpu_ops.load_gdt = xen_load_gdt;
1481 }
1482
1483 #ifdef CONFIG_XEN_PVH
1484 /*
1485  * A PV guest starts with default flags that are not set for PVH, set them
1486  * here asap.
1487  */
1488 static void xen_pvh_set_cr_flags(int cpu)
1489 {
1490
1491         /* Some of these are setup in 'secondary_startup_64'. The others:
1492          * X86_CR0_TS, X86_CR0_PE, X86_CR0_ET are set by Xen for HVM guests
1493          * (which PVH shared codepaths), while X86_CR0_PG is for PVH. */
1494         write_cr0(read_cr0() | X86_CR0_MP | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM);
1495
1496         if (!cpu)
1497                 return;
1498         /*
1499          * For BSP, PSE PGE are set in probe_page_size_mask(), for APs
1500          * set them here. For all, OSFXSR OSXMMEXCPT are set in fpu__init_cpu().
1501         */
1502         if (boot_cpu_has(X86_FEATURE_PSE))
1503                 cr4_set_bits_and_update_boot(X86_CR4_PSE);
1504
1505         if (boot_cpu_has(X86_FEATURE_PGE))
1506                 cr4_set_bits_and_update_boot(X86_CR4_PGE);
1507 }
1508
1509 /*
1510  * Note, that it is ref - because the only caller of this after init
1511  * is PVH which is not going to use xen_load_gdt_boot or other
1512  * __init functions.
1513  */
1514 void __ref xen_pvh_secondary_vcpu_init(int cpu)
1515 {
1516         xen_setup_gdt(cpu);
1517         xen_pvh_set_cr_flags(cpu);
1518 }
1519
1520 static void __init xen_pvh_early_guest_init(void)
1521 {
1522         if (!xen_feature(XENFEAT_auto_translated_physmap))
1523                 return;
1524
1525         if (!xen_feature(XENFEAT_hvm_callback_vector))
1526                 return;
1527
1528         xen_have_vector_callback = 1;
1529
1530         xen_pvh_early_cpu_init(0, false);
1531         xen_pvh_set_cr_flags(0);
1532
1533 #ifdef CONFIG_X86_32
1534         BUG(); /* PVH: Implement proper support. */
1535 #endif
1536 }
1537 #endif    /* CONFIG_XEN_PVH */
1538
1539 static void __init xen_dom0_set_legacy_features(void)
1540 {
1541         x86_platform.legacy.rtc = 1;
1542 }
1543
1544 /* First C function to be called on Xen boot */
1545 asmlinkage __visible void __init xen_start_kernel(void)
1546 {
1547         struct physdev_set_iopl set_iopl;
1548         unsigned long initrd_start = 0;
1549         int rc;
1550
1551         if (!xen_start_info)
1552                 return;
1553
1554         xen_domain_type = XEN_PV_DOMAIN;
1555
1556         xen_setup_features();
1557 #ifdef CONFIG_XEN_PVH
1558         xen_pvh_early_guest_init();
1559 #endif
1560         xen_setup_machphys_mapping();
1561
1562         /* Install Xen paravirt ops */
1563         pv_info = xen_info;
1564         pv_init_ops = xen_init_ops;
1565         if (!xen_pvh_domain()) {
1566                 pv_cpu_ops = xen_cpu_ops;
1567
1568                 x86_platform.get_nmi_reason = xen_get_nmi_reason;
1569         }
1570
1571         if (xen_feature(XENFEAT_auto_translated_physmap))
1572                 x86_init.resources.memory_setup = xen_auto_xlated_memory_setup;
1573         else
1574                 x86_init.resources.memory_setup = xen_memory_setup;
1575         x86_init.oem.arch_setup = xen_arch_setup;
1576         x86_init.oem.banner = xen_banner;
1577
1578         xen_init_time_ops();
1579
1580         /*
1581          * Set up some pagetable state before starting to set any ptes.
1582          */
1583
1584         xen_init_mmu_ops();
1585
1586         /* Prevent unwanted bits from being set in PTEs. */
1587         __supported_pte_mask &= ~_PAGE_GLOBAL;
1588
1589         /*
1590          * Prevent page tables from being allocated in highmem, even
1591          * if CONFIG_HIGHPTE is enabled.
1592          */
1593         __userpte_alloc_gfp &= ~__GFP_HIGHMEM;
1594
1595         /* Work out if we support NX */
1596         x86_configure_nx();
1597
1598         /* Get mfn list */
1599         xen_build_dynamic_phys_to_machine();
1600
1601         /*
1602          * Set up kernel GDT and segment registers, mainly so that
1603          * -fstack-protector code can be executed.
1604          */
1605         xen_setup_gdt(0);
1606
1607         xen_init_irq_ops();
1608         xen_init_cpuid_mask();
1609
1610 #ifdef CONFIG_X86_LOCAL_APIC
1611         /*
1612          * set up the basic apic ops.
1613          */
1614         xen_init_apic();
1615 #endif
1616
1617         if (xen_feature(XENFEAT_mmu_pt_update_preserve_ad)) {
1618                 pv_mmu_ops.ptep_modify_prot_start = xen_ptep_modify_prot_start;
1619                 pv_mmu_ops.ptep_modify_prot_commit = xen_ptep_modify_prot_commit;
1620         }
1621
1622         machine_ops = xen_machine_ops;
1623
1624         /*
1625          * The only reliable way to retain the initial address of the
1626          * percpu gdt_page is to remember it here, so we can go and
1627          * mark it RW later, when the initial percpu area is freed.
1628          */
1629         xen_initial_gdt = &per_cpu(gdt_page, 0);
1630
1631         xen_smp_init();
1632
1633 #ifdef CONFIG_ACPI_NUMA
1634         /*
1635          * The pages we from Xen are not related to machine pages, so
1636          * any NUMA information the kernel tries to get from ACPI will
1637          * be meaningless.  Prevent it from trying.
1638          */
1639         acpi_numa = -1;
1640 #endif
1641         /* Don't do the full vcpu_info placement stuff until we have a
1642            possible map and a non-dummy shared_info. */
1643         per_cpu(xen_vcpu, 0) = &HYPERVISOR_shared_info->vcpu_info[0];
1644
1645         local_irq_disable();
1646         early_boot_irqs_disabled = true;
1647
1648         xen_raw_console_write("mapping kernel into physical memory\n");
1649         xen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base,
1650                                    xen_start_info->nr_pages);
1651         xen_reserve_special_pages();
1652
1653         /* keep using Xen gdt for now; no urgent need to change it */
1654
1655 #ifdef CONFIG_X86_32
1656         pv_info.kernel_rpl = 1;
1657         if (xen_feature(XENFEAT_supervisor_mode_kernel))
1658                 pv_info.kernel_rpl = 0;
1659 #else
1660         pv_info.kernel_rpl = 0;
1661 #endif
1662         /* set the limit of our address space */
1663         xen_reserve_top();
1664
1665         /* PVH: runs at default kernel iopl of 0 */
1666         if (!xen_pvh_domain()) {
1667                 /*
1668                  * We used to do this in xen_arch_setup, but that is too late
1669                  * on AMD were early_cpu_init (run before ->arch_setup()) calls
1670                  * early_amd_init which pokes 0xcf8 port.
1671                  */
1672                 set_iopl.iopl = 1;
1673                 rc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);
1674                 if (rc != 0)
1675                         xen_raw_printk("physdev_op failed %d\n", rc);
1676         }
1677
1678 #ifdef CONFIG_X86_32
1679         /* set up basic CPUID stuff */
1680         cpu_detect(&new_cpu_data);
1681         set_cpu_cap(&new_cpu_data, X86_FEATURE_FPU);
1682         new_cpu_data.wp_works_ok = 1;
1683         new_cpu_data.x86_capability[CPUID_1_EDX] = cpuid_edx(1);
1684 #endif
1685
1686         if (xen_start_info->mod_start) {
1687             if (xen_start_info->flags & SIF_MOD_START_PFN)
1688                 initrd_start = PFN_PHYS(xen_start_info->mod_start);
1689             else
1690                 initrd_start = __pa(xen_start_info->mod_start);
1691         }
1692
1693         /* Poke various useful things into boot_params */
1694         boot_params.hdr.type_of_loader = (9 << 4) | 0;
1695         boot_params.hdr.ramdisk_image = initrd_start;
1696         boot_params.hdr.ramdisk_size = xen_start_info->mod_len;
1697         boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line);
1698         boot_params.hdr.hardware_subarch = X86_SUBARCH_XEN;
1699
1700         if (!xen_initial_domain()) {
1701                 add_preferred_console("xenboot", 0, NULL);
1702                 add_preferred_console("tty", 0, NULL);
1703                 add_preferred_console("hvc", 0, NULL);
1704                 if (pci_xen)
1705                         x86_init.pci.arch_init = pci_xen_init;
1706         } else {
1707                 const struct dom0_vga_console_info *info =
1708                         (void *)((char *)xen_start_info +
1709                                  xen_start_info->console.dom0.info_off);
1710                 struct xen_platform_op op = {
1711                         .cmd = XENPF_firmware_info,
1712                         .interface_version = XENPF_INTERFACE_VERSION,
1713                         .u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS,
1714                 };
1715
1716                 x86_platform.set_legacy_features =
1717                                 xen_dom0_set_legacy_features;
1718                 xen_init_vga(info, xen_start_info->console.dom0.info_size);
1719                 xen_start_info->console.domU.mfn = 0;
1720                 xen_start_info->console.domU.evtchn = 0;
1721
1722                 if (HYPERVISOR_platform_op(&op) == 0)
1723                         boot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags;
1724
1725                 /* Make sure ACS will be enabled */
1726                 pci_request_acs();
1727
1728                 xen_acpi_sleep_register();
1729
1730                 /* Avoid searching for BIOS MP tables */
1731                 x86_init.mpparse.find_smp_config = x86_init_noop;
1732                 x86_init.mpparse.get_smp_config = x86_init_uint_noop;
1733
1734                 xen_boot_params_init_edd();
1735         }
1736 #ifdef CONFIG_PCI
1737         /* PCI BIOS service won't work from a PV guest. */
1738         pci_probe &= ~PCI_PROBE_BIOS;
1739 #endif
1740         xen_raw_console_write("about to get started...\n");
1741
1742         /* Let's presume PV guests always boot on vCPU with id 0. */
1743         per_cpu(xen_vcpu_id, 0) = 0;
1744
1745         xen_setup_runstate_info(0);
1746
1747         xen_efi_init();
1748
1749         /* Start the world */
1750 #ifdef CONFIG_X86_32
1751         i386_start_kernel();
1752 #else
1753         cr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */
1754         x86_64_start_reservations((char *)__pa_symbol(&boot_params));
1755 #endif
1756 }
1757
1758 void __ref xen_hvm_init_shared_info(void)
1759 {
1760         int cpu;
1761         struct xen_add_to_physmap xatp;
1762         static struct shared_info *shared_info_page = 0;
1763
1764         if (!shared_info_page)
1765                 shared_info_page = (struct shared_info *)
1766                         extend_brk(PAGE_SIZE, PAGE_SIZE);
1767         xatp.domid = DOMID_SELF;
1768         xatp.idx = 0;
1769         xatp.space = XENMAPSPACE_shared_info;
1770         xatp.gpfn = __pa(shared_info_page) >> PAGE_SHIFT;
1771         if (HYPERVISOR_memory_op(XENMEM_add_to_physmap, &xatp))
1772                 BUG();
1773
1774         HYPERVISOR_shared_info = (struct shared_info *)shared_info_page;
1775
1776         /* xen_vcpu is a pointer to the vcpu_info struct in the shared_info
1777          * page, we use it in the event channel upcall and in some pvclock
1778          * related functions. We don't need the vcpu_info placement
1779          * optimizations because we don't use any pv_mmu or pv_irq op on
1780          * HVM.
1781          * When xen_hvm_init_shared_info is run at boot time only vcpu 0 is
1782          * online but xen_hvm_init_shared_info is run at resume time too and
1783          * in that case multiple vcpus might be online. */
1784         for_each_online_cpu(cpu) {
1785                 /* Leave it to be NULL. */
1786                 if (cpu >= MAX_VIRT_CPUS)
1787                         continue;
1788                 per_cpu(xen_vcpu, cpu) = &HYPERVISOR_shared_info->vcpu_info[cpu];
1789         }
1790 }
1791
1792 #ifdef CONFIG_XEN_PVHVM
1793 static void __init init_hvm_pv_info(void)
1794 {
1795         int major, minor;
1796         uint32_t eax, ebx, ecx, edx, pages, msr, base;
1797         u64 pfn;
1798
1799         base = xen_cpuid_base();
1800         cpuid(base + 1, &eax, &ebx, &ecx, &edx);
1801
1802         major = eax >> 16;
1803         minor = eax & 0xffff;
1804         printk(KERN_INFO "Xen version %d.%d.\n", major, minor);
1805
1806         cpuid(base + 2, &pages, &msr, &ecx, &edx);
1807
1808         pfn = __pa(hypercall_page);
1809         wrmsr_safe(msr, (u32)pfn, (u32)(pfn >> 32));
1810
1811         xen_setup_features();
1812
1813         cpuid(base + 4, &eax, &ebx, &ecx, &edx);
1814         if (eax & XEN_HVM_CPUID_VCPU_ID_PRESENT)
1815                 this_cpu_write(xen_vcpu_id, ebx);
1816         else
1817                 this_cpu_write(xen_vcpu_id, smp_processor_id());
1818
1819         pv_info.name = "Xen HVM";
1820
1821         xen_domain_type = XEN_HVM_DOMAIN;
1822 }
1823
1824 static int xen_hvm_cpu_notify(struct notifier_block *self, unsigned long action,
1825                               void *hcpu)
1826 {
1827         int cpu = (long)hcpu;
1828         switch (action) {
1829         case CPU_UP_PREPARE:
1830                 if (cpu_acpi_id(cpu) != U32_MAX)
1831                         per_cpu(xen_vcpu_id, cpu) = cpu_acpi_id(cpu);
1832                 else
1833                         per_cpu(xen_vcpu_id, cpu) = cpu;
1834                 xen_vcpu_setup(cpu);
1835                 if (xen_have_vector_callback) {
1836                         if (xen_feature(XENFEAT_hvm_safe_pvclock))
1837                                 xen_setup_timer(cpu);
1838                 }
1839                 break;
1840         default:
1841                 break;
1842         }
1843         return NOTIFY_OK;
1844 }
1845
1846 static struct notifier_block xen_hvm_cpu_notifier = {
1847         .notifier_call  = xen_hvm_cpu_notify,
1848 };
1849
1850 #ifdef CONFIG_KEXEC_CORE
1851 static void xen_hvm_shutdown(void)
1852 {
1853         native_machine_shutdown();
1854         if (kexec_in_progress)
1855                 xen_reboot(SHUTDOWN_soft_reset);
1856 }
1857
1858 static void xen_hvm_crash_shutdown(struct pt_regs *regs)
1859 {
1860         native_machine_crash_shutdown(regs);
1861         xen_reboot(SHUTDOWN_soft_reset);
1862 }
1863 #endif
1864
1865 static void __init xen_hvm_guest_init(void)
1866 {
1867         if (xen_pv_domain())
1868                 return;
1869
1870         init_hvm_pv_info();
1871
1872         xen_hvm_init_shared_info();
1873
1874         xen_panic_handler_init();
1875
1876         if (xen_feature(XENFEAT_hvm_callback_vector))
1877                 xen_have_vector_callback = 1;
1878         xen_hvm_smp_init();
1879         register_cpu_notifier(&xen_hvm_cpu_notifier);
1880         xen_unplug_emulated_devices();
1881         x86_init.irqs.intr_init = xen_init_IRQ;
1882         xen_hvm_init_time_ops();
1883         xen_hvm_init_mmu_ops();
1884 #ifdef CONFIG_KEXEC_CORE
1885         machine_ops.shutdown = xen_hvm_shutdown;
1886         machine_ops.crash_shutdown = xen_hvm_crash_shutdown;
1887 #endif
1888 }
1889 #endif
1890
1891 static bool xen_nopv = false;
1892 static __init int xen_parse_nopv(char *arg)
1893 {
1894        xen_nopv = true;
1895        return 0;
1896 }
1897 early_param("xen_nopv", xen_parse_nopv);
1898
1899 static uint32_t __init xen_platform(void)
1900 {
1901         if (xen_nopv)
1902                 return 0;
1903
1904         return xen_cpuid_base();
1905 }
1906
1907 bool xen_hvm_need_lapic(void)
1908 {
1909         if (xen_nopv)
1910                 return false;
1911         if (xen_pv_domain())
1912                 return false;
1913         if (!xen_hvm_domain())
1914                 return false;
1915         if (xen_feature(XENFEAT_hvm_pirqs) && xen_have_vector_callback)
1916                 return false;
1917         return true;
1918 }
1919 EXPORT_SYMBOL_GPL(xen_hvm_need_lapic);
1920
1921 static void xen_set_cpu_features(struct cpuinfo_x86 *c)
1922 {
1923         if (xen_pv_domain()) {
1924                 clear_cpu_bug(c, X86_BUG_SYSRET_SS_ATTRS);
1925                 set_cpu_cap(c, X86_FEATURE_XENPV);
1926         }
1927 }
1928
1929 const struct hypervisor_x86 x86_hyper_xen = {
1930         .name                   = "Xen",
1931         .detect                 = xen_platform,
1932 #ifdef CONFIG_XEN_PVHVM
1933         .init_platform          = xen_hvm_guest_init,
1934 #endif
1935         .x2apic_available       = xen_x2apic_para_available,
1936         .set_cpu_features       = xen_set_cpu_features,
1937 };
1938 EXPORT_SYMBOL(x86_hyper_xen);
1939
1940 #ifdef CONFIG_HOTPLUG_CPU
1941 void xen_arch_register_cpu(int num)
1942 {
1943         arch_register_cpu(num);
1944 }
1945 EXPORT_SYMBOL(xen_arch_register_cpu);
1946
1947 void xen_arch_unregister_cpu(int num)
1948 {
1949         arch_unregister_cpu(num);
1950 }
1951 EXPORT_SYMBOL(xen_arch_unregister_cpu);
1952 #endif