xref: /openbmc/qemu/hw/i386/pc.c (revision 64552b6b)
1 /*
2  * QEMU PC System Emulator
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include "hw/hw.h"
28 #include "hw/i386/pc.h"
29 #include "hw/char/serial.h"
30 #include "hw/char/parallel.h"
31 #include "hw/i386/apic.h"
32 #include "hw/i386/topology.h"
33 #include "hw/i386/fw_cfg.h"
34 #include "sysemu/cpus.h"
35 #include "hw/block/fdc.h"
36 #include "hw/ide.h"
37 #include "hw/pci/pci.h"
38 #include "hw/pci/pci_bus.h"
39 #include "hw/nvram/fw_cfg.h"
40 #include "hw/timer/hpet.h"
41 #include "hw/firmware/smbios.h"
42 #include "hw/loader.h"
43 #include "elf.h"
44 #include "multiboot.h"
45 #include "hw/timer/mc146818rtc.h"
46 #include "hw/dma/i8257.h"
47 #include "hw/timer/i8254.h"
48 #include "hw/input/i8042.h"
49 #include "hw/irq.h"
50 #include "hw/audio/pcspk.h"
51 #include "hw/pci/msi.h"
52 #include "hw/sysbus.h"
53 #include "sysemu/sysemu.h"
54 #include "sysemu/tcg.h"
55 #include "sysemu/numa.h"
56 #include "sysemu/kvm.h"
57 #include "sysemu/qtest.h"
58 #include "sysemu/reset.h"
59 #include "kvm_i386.h"
60 #include "hw/xen/xen.h"
61 #include "hw/xen/start_info.h"
62 #include "ui/qemu-spice.h"
63 #include "exec/memory.h"
64 #include "exec/address-spaces.h"
65 #include "sysemu/arch_init.h"
66 #include "qemu/bitmap.h"
67 #include "qemu/config-file.h"
68 #include "qemu/error-report.h"
69 #include "qemu/option.h"
70 #include "hw/acpi/acpi.h"
71 #include "hw/acpi/cpu_hotplug.h"
72 #include "hw/boards.h"
73 #include "acpi-build.h"
74 #include "hw/mem/pc-dimm.h"
75 #include "qapi/error.h"
76 #include "qapi/qapi-visit-common.h"
77 #include "qapi/visitor.h"
78 #include "qom/cpu.h"
79 #include "hw/nmi.h"
80 #include "hw/usb.h"
81 #include "hw/i386/intel_iommu.h"
82 #include "hw/net/ne2000-isa.h"
83 #include "standard-headers/asm-x86/bootparam.h"
84 #include "hw/virtio/virtio-pmem-pci.h"
85 #include "hw/mem/memory-device.h"
86 #include "sysemu/replay.h"
87 #include "qapi/qmp/qerror.h"
88 #include "config-devices.h"
89 
90 /* debug PC/ISA interrupts */
91 //#define DEBUG_IRQ
92 
93 #ifdef DEBUG_IRQ
94 #define DPRINTF(fmt, ...)                                       \
95     do { printf("CPUIRQ: " fmt , ## __VA_ARGS__); } while (0)
96 #else
97 #define DPRINTF(fmt, ...)
98 #endif
99 
100 #define E820_NR_ENTRIES		16
101 
102 struct e820_entry {
103     uint64_t address;
104     uint64_t length;
105     uint32_t type;
106 } QEMU_PACKED __attribute((__aligned__(4)));
107 
108 struct e820_table {
109     uint32_t count;
110     struct e820_entry entry[E820_NR_ENTRIES];
111 } QEMU_PACKED __attribute((__aligned__(4)));
112 
113 static struct e820_table e820_reserve;
114 static struct e820_entry *e820_table;
115 static unsigned e820_entries;
116 struct hpet_fw_config hpet_cfg = {.count = UINT8_MAX};
117 
118 /* Physical Address of PVH entry point read from kernel ELF NOTE */
119 static size_t pvh_start_addr;
120 
121 GlobalProperty pc_compat_4_0[] = {};
122 const size_t pc_compat_4_0_len = G_N_ELEMENTS(pc_compat_4_0);
123 
124 GlobalProperty pc_compat_3_1[] = {
125     { "intel-iommu", "dma-drain", "off" },
126     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "off" },
127     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "off" },
128     { "Opteron_G4" "-" TYPE_X86_CPU, "npt", "off" },
129     { "Opteron_G4" "-" TYPE_X86_CPU, "nrip-save", "off" },
130     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "off" },
131     { "Opteron_G5" "-" TYPE_X86_CPU, "npt", "off" },
132     { "Opteron_G5" "-" TYPE_X86_CPU, "nrip-save", "off" },
133     { "EPYC" "-" TYPE_X86_CPU, "npt", "off" },
134     { "EPYC" "-" TYPE_X86_CPU, "nrip-save", "off" },
135     { "EPYC-IBPB" "-" TYPE_X86_CPU, "npt", "off" },
136     { "EPYC-IBPB" "-" TYPE_X86_CPU, "nrip-save", "off" },
137     { "Skylake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
138     { "Skylake-Client-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
139     { "Skylake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
140     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
141     { "Cascadelake-Server" "-" TYPE_X86_CPU,  "mpx", "on" },
142     { "Icelake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
143     { "Icelake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
144     { "Cascadelake-Server" "-" TYPE_X86_CPU, "stepping", "5" },
145     { TYPE_X86_CPU, "x-intel-pt-auto-level", "off" },
146 };
147 const size_t pc_compat_3_1_len = G_N_ELEMENTS(pc_compat_3_1);
148 
149 GlobalProperty pc_compat_3_0[] = {
150     { TYPE_X86_CPU, "x-hv-synic-kvm-only", "on" },
151     { "Skylake-Server" "-" TYPE_X86_CPU, "pku", "off" },
152     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "pku", "off" },
153 };
154 const size_t pc_compat_3_0_len = G_N_ELEMENTS(pc_compat_3_0);
155 
156 GlobalProperty pc_compat_2_12[] = {
157     { TYPE_X86_CPU, "legacy-cache", "on" },
158     { TYPE_X86_CPU, "topoext", "off" },
159     { "EPYC-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
160     { "EPYC-IBPB-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
161 };
162 const size_t pc_compat_2_12_len = G_N_ELEMENTS(pc_compat_2_12);
163 
164 GlobalProperty pc_compat_2_11[] = {
165     { TYPE_X86_CPU, "x-migrate-smi-count", "off" },
166     { "Skylake-Server" "-" TYPE_X86_CPU, "clflushopt", "off" },
167 };
168 const size_t pc_compat_2_11_len = G_N_ELEMENTS(pc_compat_2_11);
169 
170 GlobalProperty pc_compat_2_10[] = {
171     { TYPE_X86_CPU, "x-hv-max-vps", "0x40" },
172     { "i440FX-pcihost", "x-pci-hole64-fix", "off" },
173     { "q35-pcihost", "x-pci-hole64-fix", "off" },
174 };
175 const size_t pc_compat_2_10_len = G_N_ELEMENTS(pc_compat_2_10);
176 
177 GlobalProperty pc_compat_2_9[] = {
178     { "mch", "extended-tseg-mbytes", "0" },
179 };
180 const size_t pc_compat_2_9_len = G_N_ELEMENTS(pc_compat_2_9);
181 
182 GlobalProperty pc_compat_2_8[] = {
183     { TYPE_X86_CPU, "tcg-cpuid", "off" },
184     { "kvmclock", "x-mach-use-reliable-get-clock", "off" },
185     { "ICH9-LPC", "x-smi-broadcast", "off" },
186     { TYPE_X86_CPU, "vmware-cpuid-freq", "off" },
187     { "Haswell-" TYPE_X86_CPU, "stepping", "1" },
188 };
189 const size_t pc_compat_2_8_len = G_N_ELEMENTS(pc_compat_2_8);
190 
191 GlobalProperty pc_compat_2_7[] = {
192     { TYPE_X86_CPU, "l3-cache", "off" },
193     { TYPE_X86_CPU, "full-cpuid-auto-level", "off" },
194     { "Opteron_G3" "-" TYPE_X86_CPU, "family", "15" },
195     { "Opteron_G3" "-" TYPE_X86_CPU, "model", "6" },
196     { "Opteron_G3" "-" TYPE_X86_CPU, "stepping", "1" },
197     { "isa-pcspk", "migrate", "off" },
198 };
199 const size_t pc_compat_2_7_len = G_N_ELEMENTS(pc_compat_2_7);
200 
201 GlobalProperty pc_compat_2_6[] = {
202     { TYPE_X86_CPU, "cpuid-0xb", "off" },
203     { "vmxnet3", "romfile", "" },
204     { TYPE_X86_CPU, "fill-mtrr-mask", "off" },
205     { "apic-common", "legacy-instance-id", "on", }
206 };
207 const size_t pc_compat_2_6_len = G_N_ELEMENTS(pc_compat_2_6);
208 
209 GlobalProperty pc_compat_2_5[] = {};
210 const size_t pc_compat_2_5_len = G_N_ELEMENTS(pc_compat_2_5);
211 
212 GlobalProperty pc_compat_2_4[] = {
213     PC_CPU_MODEL_IDS("2.4.0")
214     { "Haswell-" TYPE_X86_CPU, "abm", "off" },
215     { "Haswell-noTSX-" TYPE_X86_CPU, "abm", "off" },
216     { "Broadwell-" TYPE_X86_CPU, "abm", "off" },
217     { "Broadwell-noTSX-" TYPE_X86_CPU, "abm", "off" },
218     { "host" "-" TYPE_X86_CPU, "host-cache-info", "on" },
219     { TYPE_X86_CPU, "check", "off" },
220     { "qemu64" "-" TYPE_X86_CPU, "sse4a", "on" },
221     { "qemu64" "-" TYPE_X86_CPU, "abm", "on" },
222     { "qemu64" "-" TYPE_X86_CPU, "popcnt", "on" },
223     { "qemu32" "-" TYPE_X86_CPU, "popcnt", "on" },
224     { "Opteron_G2" "-" TYPE_X86_CPU, "rdtscp", "on" },
225     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "on" },
226     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "on" },
227     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "on", }
228 };
229 const size_t pc_compat_2_4_len = G_N_ELEMENTS(pc_compat_2_4);
230 
231 GlobalProperty pc_compat_2_3[] = {
232     PC_CPU_MODEL_IDS("2.3.0")
233     { TYPE_X86_CPU, "arat", "off" },
234     { "qemu64" "-" TYPE_X86_CPU, "min-level", "4" },
235     { "kvm64" "-" TYPE_X86_CPU, "min-level", "5" },
236     { "pentium3" "-" TYPE_X86_CPU, "min-level", "2" },
237     { "n270" "-" TYPE_X86_CPU, "min-level", "5" },
238     { "Conroe" "-" TYPE_X86_CPU, "min-level", "4" },
239     { "Penryn" "-" TYPE_X86_CPU, "min-level", "4" },
240     { "Nehalem" "-" TYPE_X86_CPU, "min-level", "4" },
241     { "n270" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
242     { "Penryn" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
243     { "Conroe" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
244     { "Nehalem" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
245     { "Westmere" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
246     { "SandyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
247     { "IvyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
248     { "Haswell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
249     { "Haswell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
250     { "Broadwell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
251     { "Broadwell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
252     { TYPE_X86_CPU, "kvm-no-smi-migration", "on" },
253 };
254 const size_t pc_compat_2_3_len = G_N_ELEMENTS(pc_compat_2_3);
255 
256 GlobalProperty pc_compat_2_2[] = {
257     PC_CPU_MODEL_IDS("2.2.0")
258     { "kvm64" "-" TYPE_X86_CPU, "vme", "off" },
259     { "kvm32" "-" TYPE_X86_CPU, "vme", "off" },
260     { "Conroe" "-" TYPE_X86_CPU, "vme", "off" },
261     { "Penryn" "-" TYPE_X86_CPU, "vme", "off" },
262     { "Nehalem" "-" TYPE_X86_CPU, "vme", "off" },
263     { "Westmere" "-" TYPE_X86_CPU, "vme", "off" },
264     { "SandyBridge" "-" TYPE_X86_CPU, "vme", "off" },
265     { "Haswell" "-" TYPE_X86_CPU, "vme", "off" },
266     { "Broadwell" "-" TYPE_X86_CPU, "vme", "off" },
267     { "Opteron_G1" "-" TYPE_X86_CPU, "vme", "off" },
268     { "Opteron_G2" "-" TYPE_X86_CPU, "vme", "off" },
269     { "Opteron_G3" "-" TYPE_X86_CPU, "vme", "off" },
270     { "Opteron_G4" "-" TYPE_X86_CPU, "vme", "off" },
271     { "Opteron_G5" "-" TYPE_X86_CPU, "vme", "off" },
272     { "Haswell" "-" TYPE_X86_CPU, "f16c", "off" },
273     { "Haswell" "-" TYPE_X86_CPU, "rdrand", "off" },
274     { "Broadwell" "-" TYPE_X86_CPU, "f16c", "off" },
275     { "Broadwell" "-" TYPE_X86_CPU, "rdrand", "off" },
276 };
277 const size_t pc_compat_2_2_len = G_N_ELEMENTS(pc_compat_2_2);
278 
279 GlobalProperty pc_compat_2_1[] = {
280     PC_CPU_MODEL_IDS("2.1.0")
281     { "coreduo" "-" TYPE_X86_CPU, "vmx", "on" },
282     { "core2duo" "-" TYPE_X86_CPU, "vmx", "on" },
283 };
284 const size_t pc_compat_2_1_len = G_N_ELEMENTS(pc_compat_2_1);
285 
286 GlobalProperty pc_compat_2_0[] = {
287     PC_CPU_MODEL_IDS("2.0.0")
288     { "virtio-scsi-pci", "any_layout", "off" },
289     { "PIIX4_PM", "memory-hotplug-support", "off" },
290     { "apic", "version", "0x11" },
291     { "nec-usb-xhci", "superspeed-ports-first", "off" },
292     { "nec-usb-xhci", "force-pcie-endcap", "on" },
293     { "pci-serial", "prog_if", "0" },
294     { "pci-serial-2x", "prog_if", "0" },
295     { "pci-serial-4x", "prog_if", "0" },
296     { "virtio-net-pci", "guest_announce", "off" },
297     { "ICH9-LPC", "memory-hotplug-support", "off" },
298     { "xio3130-downstream", COMPAT_PROP_PCP, "off" },
299     { "ioh3420", COMPAT_PROP_PCP, "off" },
300 };
301 const size_t pc_compat_2_0_len = G_N_ELEMENTS(pc_compat_2_0);
302 
303 GlobalProperty pc_compat_1_7[] = {
304     PC_CPU_MODEL_IDS("1.7.0")
305     { TYPE_USB_DEVICE, "msos-desc", "no" },
306     { "PIIX4_PM", "acpi-pci-hotplug-with-bridge-support", "off" },
307     { "hpet", HPET_INTCAP, "4" },
308 };
309 const size_t pc_compat_1_7_len = G_N_ELEMENTS(pc_compat_1_7);
310 
311 GlobalProperty pc_compat_1_6[] = {
312     PC_CPU_MODEL_IDS("1.6.0")
313     { "e1000", "mitigation", "off" },
314     { "qemu64-" TYPE_X86_CPU, "model", "2" },
315     { "qemu32-" TYPE_X86_CPU, "model", "3" },
316     { "i440FX-pcihost", "short_root_bus", "1" },
317     { "q35-pcihost", "short_root_bus", "1" },
318 };
319 const size_t pc_compat_1_6_len = G_N_ELEMENTS(pc_compat_1_6);
320 
321 GlobalProperty pc_compat_1_5[] = {
322     PC_CPU_MODEL_IDS("1.5.0")
323     { "Conroe-" TYPE_X86_CPU, "model", "2" },
324     { "Conroe-" TYPE_X86_CPU, "min-level", "2" },
325     { "Penryn-" TYPE_X86_CPU, "model", "2" },
326     { "Penryn-" TYPE_X86_CPU, "min-level", "2" },
327     { "Nehalem-" TYPE_X86_CPU, "model", "2" },
328     { "Nehalem-" TYPE_X86_CPU, "min-level", "2" },
329     { "virtio-net-pci", "any_layout", "off" },
330     { TYPE_X86_CPU, "pmu", "on" },
331     { "i440FX-pcihost", "short_root_bus", "0" },
332     { "q35-pcihost", "short_root_bus", "0" },
333 };
334 const size_t pc_compat_1_5_len = G_N_ELEMENTS(pc_compat_1_5);
335 
336 GlobalProperty pc_compat_1_4[] = {
337     PC_CPU_MODEL_IDS("1.4.0")
338     { "scsi-hd", "discard_granularity", "0" },
339     { "scsi-cd", "discard_granularity", "0" },
340     { "scsi-disk", "discard_granularity", "0" },
341     { "ide-hd", "discard_granularity", "0" },
342     { "ide-cd", "discard_granularity", "0" },
343     { "ide-drive", "discard_granularity", "0" },
344     { "virtio-blk-pci", "discard_granularity", "0" },
345     /* DEV_NVECTORS_UNSPECIFIED as a uint32_t string: */
346     { "virtio-serial-pci", "vectors", "0xFFFFFFFF" },
347     { "virtio-net-pci", "ctrl_guest_offloads", "off" },
348     { "e1000", "romfile", "pxe-e1000.rom" },
349     { "ne2k_pci", "romfile", "pxe-ne2k_pci.rom" },
350     { "pcnet", "romfile", "pxe-pcnet.rom" },
351     { "rtl8139", "romfile", "pxe-rtl8139.rom" },
352     { "virtio-net-pci", "romfile", "pxe-virtio.rom" },
353     { "486-" TYPE_X86_CPU, "model", "0" },
354     { "n270" "-" TYPE_X86_CPU, "movbe", "off" },
355     { "Westmere" "-" TYPE_X86_CPU, "pclmulqdq", "off" },
356 };
357 const size_t pc_compat_1_4_len = G_N_ELEMENTS(pc_compat_1_4);
358 
359 void gsi_handler(void *opaque, int n, int level)
360 {
361     GSIState *s = opaque;
362 
363     DPRINTF("pc: %s GSI %d\n", level ? "raising" : "lowering", n);
364     if (n < ISA_NUM_IRQS) {
365         qemu_set_irq(s->i8259_irq[n], level);
366     }
367     qemu_set_irq(s->ioapic_irq[n], level);
368 }
369 
370 static void ioport80_write(void *opaque, hwaddr addr, uint64_t data,
371                            unsigned size)
372 {
373 }
374 
375 static uint64_t ioport80_read(void *opaque, hwaddr addr, unsigned size)
376 {
377     return 0xffffffffffffffffULL;
378 }
379 
380 /* MSDOS compatibility mode FPU exception support */
381 static qemu_irq ferr_irq;
382 
383 void pc_register_ferr_irq(qemu_irq irq)
384 {
385     ferr_irq = irq;
386 }
387 
388 /* XXX: add IGNNE support */
389 void cpu_set_ferr(CPUX86State *s)
390 {
391     qemu_irq_raise(ferr_irq);
392 }
393 
394 static void ioportF0_write(void *opaque, hwaddr addr, uint64_t data,
395                            unsigned size)
396 {
397     qemu_irq_lower(ferr_irq);
398 }
399 
400 static uint64_t ioportF0_read(void *opaque, hwaddr addr, unsigned size)
401 {
402     return 0xffffffffffffffffULL;
403 }
404 
405 /* TSC handling */
406 uint64_t cpu_get_tsc(CPUX86State *env)
407 {
408     return cpu_get_ticks();
409 }
410 
411 /* IRQ handling */
412 int cpu_get_pic_interrupt(CPUX86State *env)
413 {
414     X86CPU *cpu = env_archcpu(env);
415     int intno;
416 
417     if (!kvm_irqchip_in_kernel()) {
418         intno = apic_get_interrupt(cpu->apic_state);
419         if (intno >= 0) {
420             return intno;
421         }
422         /* read the irq from the PIC */
423         if (!apic_accept_pic_intr(cpu->apic_state)) {
424             return -1;
425         }
426     }
427 
428     intno = pic_read_irq(isa_pic);
429     return intno;
430 }
431 
432 static void pic_irq_request(void *opaque, int irq, int level)
433 {
434     CPUState *cs = first_cpu;
435     X86CPU *cpu = X86_CPU(cs);
436 
437     DPRINTF("pic_irqs: %s irq %d\n", level? "raise" : "lower", irq);
438     if (cpu->apic_state && !kvm_irqchip_in_kernel()) {
439         CPU_FOREACH(cs) {
440             cpu = X86_CPU(cs);
441             if (apic_accept_pic_intr(cpu->apic_state)) {
442                 apic_deliver_pic_intr(cpu->apic_state, level);
443             }
444         }
445     } else {
446         if (level) {
447             cpu_interrupt(cs, CPU_INTERRUPT_HARD);
448         } else {
449             cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
450         }
451     }
452 }
453 
454 /* PC cmos mappings */
455 
456 #define REG_EQUIPMENT_BYTE          0x14
457 
458 int cmos_get_fd_drive_type(FloppyDriveType fd0)
459 {
460     int val;
461 
462     switch (fd0) {
463     case FLOPPY_DRIVE_TYPE_144:
464         /* 1.44 Mb 3"5 drive */
465         val = 4;
466         break;
467     case FLOPPY_DRIVE_TYPE_288:
468         /* 2.88 Mb 3"5 drive */
469         val = 5;
470         break;
471     case FLOPPY_DRIVE_TYPE_120:
472         /* 1.2 Mb 5"5 drive */
473         val = 2;
474         break;
475     case FLOPPY_DRIVE_TYPE_NONE:
476     default:
477         val = 0;
478         break;
479     }
480     return val;
481 }
482 
483 static void cmos_init_hd(ISADevice *s, int type_ofs, int info_ofs,
484                          int16_t cylinders, int8_t heads, int8_t sectors)
485 {
486     rtc_set_memory(s, type_ofs, 47);
487     rtc_set_memory(s, info_ofs, cylinders);
488     rtc_set_memory(s, info_ofs + 1, cylinders >> 8);
489     rtc_set_memory(s, info_ofs + 2, heads);
490     rtc_set_memory(s, info_ofs + 3, 0xff);
491     rtc_set_memory(s, info_ofs + 4, 0xff);
492     rtc_set_memory(s, info_ofs + 5, 0xc0 | ((heads > 8) << 3));
493     rtc_set_memory(s, info_ofs + 6, cylinders);
494     rtc_set_memory(s, info_ofs + 7, cylinders >> 8);
495     rtc_set_memory(s, info_ofs + 8, sectors);
496 }
497 
498 /* convert boot_device letter to something recognizable by the bios */
499 static int boot_device2nibble(char boot_device)
500 {
501     switch(boot_device) {
502     case 'a':
503     case 'b':
504         return 0x01; /* floppy boot */
505     case 'c':
506         return 0x02; /* hard drive boot */
507     case 'd':
508         return 0x03; /* CD-ROM boot */
509     case 'n':
510         return 0x04; /* Network boot */
511     }
512     return 0;
513 }
514 
515 static void set_boot_dev(ISADevice *s, const char *boot_device, Error **errp)
516 {
517 #define PC_MAX_BOOT_DEVICES 3
518     int nbds, bds[3] = { 0, };
519     int i;
520 
521     nbds = strlen(boot_device);
522     if (nbds > PC_MAX_BOOT_DEVICES) {
523         error_setg(errp, "Too many boot devices for PC");
524         return;
525     }
526     for (i = 0; i < nbds; i++) {
527         bds[i] = boot_device2nibble(boot_device[i]);
528         if (bds[i] == 0) {
529             error_setg(errp, "Invalid boot device for PC: '%c'",
530                        boot_device[i]);
531             return;
532         }
533     }
534     rtc_set_memory(s, 0x3d, (bds[1] << 4) | bds[0]);
535     rtc_set_memory(s, 0x38, (bds[2] << 4) | (fd_bootchk ? 0x0 : 0x1));
536 }
537 
538 static void pc_boot_set(void *opaque, const char *boot_device, Error **errp)
539 {
540     set_boot_dev(opaque, boot_device, errp);
541 }
542 
543 static void pc_cmos_init_floppy(ISADevice *rtc_state, ISADevice *floppy)
544 {
545     int val, nb, i;
546     FloppyDriveType fd_type[2] = { FLOPPY_DRIVE_TYPE_NONE,
547                                    FLOPPY_DRIVE_TYPE_NONE };
548 
549     /* floppy type */
550     if (floppy) {
551         for (i = 0; i < 2; i++) {
552             fd_type[i] = isa_fdc_get_drive_type(floppy, i);
553         }
554     }
555     val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |
556         cmos_get_fd_drive_type(fd_type[1]);
557     rtc_set_memory(rtc_state, 0x10, val);
558 
559     val = rtc_get_memory(rtc_state, REG_EQUIPMENT_BYTE);
560     nb = 0;
561     if (fd_type[0] != FLOPPY_DRIVE_TYPE_NONE) {
562         nb++;
563     }
564     if (fd_type[1] != FLOPPY_DRIVE_TYPE_NONE) {
565         nb++;
566     }
567     switch (nb) {
568     case 0:
569         break;
570     case 1:
571         val |= 0x01; /* 1 drive, ready for boot */
572         break;
573     case 2:
574         val |= 0x41; /* 2 drives, ready for boot */
575         break;
576     }
577     rtc_set_memory(rtc_state, REG_EQUIPMENT_BYTE, val);
578 }
579 
580 typedef struct pc_cmos_init_late_arg {
581     ISADevice *rtc_state;
582     BusState *idebus[2];
583 } pc_cmos_init_late_arg;
584 
585 typedef struct check_fdc_state {
586     ISADevice *floppy;
587     bool multiple;
588 } CheckFdcState;
589 
590 static int check_fdc(Object *obj, void *opaque)
591 {
592     CheckFdcState *state = opaque;
593     Object *fdc;
594     uint32_t iobase;
595     Error *local_err = NULL;
596 
597     fdc = object_dynamic_cast(obj, TYPE_ISA_FDC);
598     if (!fdc) {
599         return 0;
600     }
601 
602     iobase = object_property_get_uint(obj, "iobase", &local_err);
603     if (local_err || iobase != 0x3f0) {
604         error_free(local_err);
605         return 0;
606     }
607 
608     if (state->floppy) {
609         state->multiple = true;
610     } else {
611         state->floppy = ISA_DEVICE(obj);
612     }
613     return 0;
614 }
615 
616 static const char * const fdc_container_path[] = {
617     "/unattached", "/peripheral", "/peripheral-anon"
618 };
619 
620 /*
621  * Locate the FDC at IO address 0x3f0, in order to configure the CMOS registers
622  * and ACPI objects.
623  */
624 ISADevice *pc_find_fdc0(void)
625 {
626     int i;
627     Object *container;
628     CheckFdcState state = { 0 };
629 
630     for (i = 0; i < ARRAY_SIZE(fdc_container_path); i++) {
631         container = container_get(qdev_get_machine(), fdc_container_path[i]);
632         object_child_foreach(container, check_fdc, &state);
633     }
634 
635     if (state.multiple) {
636         warn_report("multiple floppy disk controllers with "
637                     "iobase=0x3f0 have been found");
638         error_printf("the one being picked for CMOS setup might not reflect "
639                      "your intent");
640     }
641 
642     return state.floppy;
643 }
644 
645 static void pc_cmos_init_late(void *opaque)
646 {
647     pc_cmos_init_late_arg *arg = opaque;
648     ISADevice *s = arg->rtc_state;
649     int16_t cylinders;
650     int8_t heads, sectors;
651     int val;
652     int i, trans;
653 
654     val = 0;
655     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 0,
656                                            &cylinders, &heads, &sectors) >= 0) {
657         cmos_init_hd(s, 0x19, 0x1b, cylinders, heads, sectors);
658         val |= 0xf0;
659     }
660     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 1,
661                                            &cylinders, &heads, &sectors) >= 0) {
662         cmos_init_hd(s, 0x1a, 0x24, cylinders, heads, sectors);
663         val |= 0x0f;
664     }
665     rtc_set_memory(s, 0x12, val);
666 
667     val = 0;
668     for (i = 0; i < 4; i++) {
669         /* NOTE: ide_get_geometry() returns the physical
670            geometry.  It is always such that: 1 <= sects <= 63, 1
671            <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
672            geometry can be different if a translation is done. */
673         if (arg->idebus[i / 2] &&
674             ide_get_geometry(arg->idebus[i / 2], i % 2,
675                              &cylinders, &heads, &sectors) >= 0) {
676             trans = ide_get_bios_chs_trans(arg->idebus[i / 2], i % 2) - 1;
677             assert((trans & ~3) == 0);
678             val |= trans << (i * 2);
679         }
680     }
681     rtc_set_memory(s, 0x39, val);
682 
683     pc_cmos_init_floppy(s, pc_find_fdc0());
684 
685     qemu_unregister_reset(pc_cmos_init_late, opaque);
686 }
687 
688 void pc_cmos_init(PCMachineState *pcms,
689                   BusState *idebus0, BusState *idebus1,
690                   ISADevice *s)
691 {
692     int val;
693     static pc_cmos_init_late_arg arg;
694 
695     /* various important CMOS locations needed by PC/Bochs bios */
696 
697     /* memory size */
698     /* base memory (first MiB) */
699     val = MIN(pcms->below_4g_mem_size / KiB, 640);
700     rtc_set_memory(s, 0x15, val);
701     rtc_set_memory(s, 0x16, val >> 8);
702     /* extended memory (next 64MiB) */
703     if (pcms->below_4g_mem_size > 1 * MiB) {
704         val = (pcms->below_4g_mem_size - 1 * MiB) / KiB;
705     } else {
706         val = 0;
707     }
708     if (val > 65535)
709         val = 65535;
710     rtc_set_memory(s, 0x17, val);
711     rtc_set_memory(s, 0x18, val >> 8);
712     rtc_set_memory(s, 0x30, val);
713     rtc_set_memory(s, 0x31, val >> 8);
714     /* memory between 16MiB and 4GiB */
715     if (pcms->below_4g_mem_size > 16 * MiB) {
716         val = (pcms->below_4g_mem_size - 16 * MiB) / (64 * KiB);
717     } else {
718         val = 0;
719     }
720     if (val > 65535)
721         val = 65535;
722     rtc_set_memory(s, 0x34, val);
723     rtc_set_memory(s, 0x35, val >> 8);
724     /* memory above 4GiB */
725     val = pcms->above_4g_mem_size / 65536;
726     rtc_set_memory(s, 0x5b, val);
727     rtc_set_memory(s, 0x5c, val >> 8);
728     rtc_set_memory(s, 0x5d, val >> 16);
729 
730     object_property_add_link(OBJECT(pcms), "rtc_state",
731                              TYPE_ISA_DEVICE,
732                              (Object **)&pcms->rtc,
733                              object_property_allow_set_link,
734                              OBJ_PROP_LINK_STRONG, &error_abort);
735     object_property_set_link(OBJECT(pcms), OBJECT(s),
736                              "rtc_state", &error_abort);
737 
738     set_boot_dev(s, MACHINE(pcms)->boot_order, &error_fatal);
739 
740     val = 0;
741     val |= 0x02; /* FPU is there */
742     val |= 0x04; /* PS/2 mouse installed */
743     rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);
744 
745     /* hard drives and FDC */
746     arg.rtc_state = s;
747     arg.idebus[0] = idebus0;
748     arg.idebus[1] = idebus1;
749     qemu_register_reset(pc_cmos_init_late, &arg);
750 }
751 
752 #define TYPE_PORT92 "port92"
753 #define PORT92(obj) OBJECT_CHECK(Port92State, (obj), TYPE_PORT92)
754 
755 /* port 92 stuff: could be split off */
756 typedef struct Port92State {
757     ISADevice parent_obj;
758 
759     MemoryRegion io;
760     uint8_t outport;
761     qemu_irq a20_out;
762 } Port92State;
763 
764 static void port92_write(void *opaque, hwaddr addr, uint64_t val,
765                          unsigned size)
766 {
767     Port92State *s = opaque;
768     int oldval = s->outport;
769 
770     DPRINTF("port92: write 0x%02" PRIx64 "\n", val);
771     s->outport = val;
772     qemu_set_irq(s->a20_out, (val >> 1) & 1);
773     if ((val & 1) && !(oldval & 1)) {
774         qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
775     }
776 }
777 
778 static uint64_t port92_read(void *opaque, hwaddr addr,
779                             unsigned size)
780 {
781     Port92State *s = opaque;
782     uint32_t ret;
783 
784     ret = s->outport;
785     DPRINTF("port92: read 0x%02x\n", ret);
786     return ret;
787 }
788 
789 static void port92_init(ISADevice *dev, qemu_irq a20_out)
790 {
791     qdev_connect_gpio_out_named(DEVICE(dev), PORT92_A20_LINE, 0, a20_out);
792 }
793 
794 static const VMStateDescription vmstate_port92_isa = {
795     .name = "port92",
796     .version_id = 1,
797     .minimum_version_id = 1,
798     .fields = (VMStateField[]) {
799         VMSTATE_UINT8(outport, Port92State),
800         VMSTATE_END_OF_LIST()
801     }
802 };
803 
804 static void port92_reset(DeviceState *d)
805 {
806     Port92State *s = PORT92(d);
807 
808     s->outport &= ~1;
809 }
810 
811 static const MemoryRegionOps port92_ops = {
812     .read = port92_read,
813     .write = port92_write,
814     .impl = {
815         .min_access_size = 1,
816         .max_access_size = 1,
817     },
818     .endianness = DEVICE_LITTLE_ENDIAN,
819 };
820 
821 static void port92_initfn(Object *obj)
822 {
823     Port92State *s = PORT92(obj);
824 
825     memory_region_init_io(&s->io, OBJECT(s), &port92_ops, s, "port92", 1);
826 
827     s->outport = 0;
828 
829     qdev_init_gpio_out_named(DEVICE(obj), &s->a20_out, PORT92_A20_LINE, 1);
830 }
831 
832 static void port92_realizefn(DeviceState *dev, Error **errp)
833 {
834     ISADevice *isadev = ISA_DEVICE(dev);
835     Port92State *s = PORT92(dev);
836 
837     isa_register_ioport(isadev, &s->io, 0x92);
838 }
839 
840 static void port92_class_initfn(ObjectClass *klass, void *data)
841 {
842     DeviceClass *dc = DEVICE_CLASS(klass);
843 
844     dc->realize = port92_realizefn;
845     dc->reset = port92_reset;
846     dc->vmsd = &vmstate_port92_isa;
847     /*
848      * Reason: unlike ordinary ISA devices, this one needs additional
849      * wiring: its A20 output line needs to be wired up by
850      * port92_init().
851      */
852     dc->user_creatable = false;
853 }
854 
855 static const TypeInfo port92_info = {
856     .name          = TYPE_PORT92,
857     .parent        = TYPE_ISA_DEVICE,
858     .instance_size = sizeof(Port92State),
859     .instance_init = port92_initfn,
860     .class_init    = port92_class_initfn,
861 };
862 
863 static void port92_register_types(void)
864 {
865     type_register_static(&port92_info);
866 }
867 
868 type_init(port92_register_types)
869 
870 static void handle_a20_line_change(void *opaque, int irq, int level)
871 {
872     X86CPU *cpu = opaque;
873 
874     /* XXX: send to all CPUs ? */
875     /* XXX: add logic to handle multiple A20 line sources */
876     x86_cpu_set_a20(cpu, level);
877 }
878 
879 int e820_add_entry(uint64_t address, uint64_t length, uint32_t type)
880 {
881     int index = le32_to_cpu(e820_reserve.count);
882     struct e820_entry *entry;
883 
884     if (type != E820_RAM) {
885         /* old FW_CFG_E820_TABLE entry -- reservations only */
886         if (index >= E820_NR_ENTRIES) {
887             return -EBUSY;
888         }
889         entry = &e820_reserve.entry[index++];
890 
891         entry->address = cpu_to_le64(address);
892         entry->length = cpu_to_le64(length);
893         entry->type = cpu_to_le32(type);
894 
895         e820_reserve.count = cpu_to_le32(index);
896     }
897 
898     /* new "etc/e820" file -- include ram too */
899     e820_table = g_renew(struct e820_entry, e820_table, e820_entries + 1);
900     e820_table[e820_entries].address = cpu_to_le64(address);
901     e820_table[e820_entries].length = cpu_to_le64(length);
902     e820_table[e820_entries].type = cpu_to_le32(type);
903     e820_entries++;
904 
905     return e820_entries;
906 }
907 
908 int e820_get_num_entries(void)
909 {
910     return e820_entries;
911 }
912 
913 bool e820_get_entry(int idx, uint32_t type, uint64_t *address, uint64_t *length)
914 {
915     if (idx < e820_entries && e820_table[idx].type == cpu_to_le32(type)) {
916         *address = le64_to_cpu(e820_table[idx].address);
917         *length = le64_to_cpu(e820_table[idx].length);
918         return true;
919     }
920     return false;
921 }
922 
923 /* Calculates initial APIC ID for a specific CPU index
924  *
925  * Currently we need to be able to calculate the APIC ID from the CPU index
926  * alone (without requiring a CPU object), as the QEMU<->Seabios interfaces have
927  * no concept of "CPU index", and the NUMA tables on fw_cfg need the APIC ID of
928  * all CPUs up to max_cpus.
929  */
930 static uint32_t x86_cpu_apic_id_from_index(PCMachineState *pcms,
931                                            unsigned int cpu_index)
932 {
933     MachineState *ms = MACHINE(pcms);
934     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
935     uint32_t correct_id;
936     static bool warned;
937 
938     correct_id = x86_apicid_from_cpu_idx(pcms->smp_dies, ms->smp.cores,
939                                          ms->smp.threads, cpu_index);
940     if (pcmc->compat_apic_id_mode) {
941         if (cpu_index != correct_id && !warned && !qtest_enabled()) {
942             error_report("APIC IDs set in compatibility mode, "
943                          "CPU topology won't match the configuration");
944             warned = true;
945         }
946         return cpu_index;
947     } else {
948         return correct_id;
949     }
950 }
951 
952 static void pc_build_smbios(PCMachineState *pcms)
953 {
954     uint8_t *smbios_tables, *smbios_anchor;
955     size_t smbios_tables_len, smbios_anchor_len;
956     struct smbios_phys_mem_area *mem_array;
957     unsigned i, array_count;
958     MachineState *ms = MACHINE(pcms);
959     X86CPU *cpu = X86_CPU(ms->possible_cpus->cpus[0].cpu);
960 
961     /* tell smbios about cpuid version and features */
962     smbios_set_cpuid(cpu->env.cpuid_version, cpu->env.features[FEAT_1_EDX]);
963 
964     smbios_tables = smbios_get_table_legacy(ms, &smbios_tables_len);
965     if (smbios_tables) {
966         fw_cfg_add_bytes(pcms->fw_cfg, FW_CFG_SMBIOS_ENTRIES,
967                          smbios_tables, smbios_tables_len);
968     }
969 
970     /* build the array of physical mem area from e820 table */
971     mem_array = g_malloc0(sizeof(*mem_array) * e820_get_num_entries());
972     for (i = 0, array_count = 0; i < e820_get_num_entries(); i++) {
973         uint64_t addr, len;
974 
975         if (e820_get_entry(i, E820_RAM, &addr, &len)) {
976             mem_array[array_count].address = addr;
977             mem_array[array_count].length = len;
978             array_count++;
979         }
980     }
981     smbios_get_tables(ms, mem_array, array_count,
982                       &smbios_tables, &smbios_tables_len,
983                       &smbios_anchor, &smbios_anchor_len);
984     g_free(mem_array);
985 
986     if (smbios_anchor) {
987         fw_cfg_add_file(pcms->fw_cfg, "etc/smbios/smbios-tables",
988                         smbios_tables, smbios_tables_len);
989         fw_cfg_add_file(pcms->fw_cfg, "etc/smbios/smbios-anchor",
990                         smbios_anchor, smbios_anchor_len);
991     }
992 }
993 
994 static FWCfgState *bochs_bios_init(AddressSpace *as, PCMachineState *pcms)
995 {
996     FWCfgState *fw_cfg;
997     uint64_t *numa_fw_cfg;
998     int i;
999     const CPUArchIdList *cpus;
1000     MachineClass *mc = MACHINE_GET_CLASS(pcms);
1001 
1002     fw_cfg = fw_cfg_init_io_dma(FW_CFG_IO_BASE, FW_CFG_IO_BASE + 4, as);
1003     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);
1004 
1005     /* FW_CFG_MAX_CPUS is a bit confusing/problematic on x86:
1006      *
1007      * For machine types prior to 1.8, SeaBIOS needs FW_CFG_MAX_CPUS for
1008      * building MPTable, ACPI MADT, ACPI CPU hotplug and ACPI SRAT table,
1009      * that tables are based on xAPIC ID and QEMU<->SeaBIOS interface
1010      * for CPU hotplug also uses APIC ID and not "CPU index".
1011      * This means that FW_CFG_MAX_CPUS is not the "maximum number of CPUs",
1012      * but the "limit to the APIC ID values SeaBIOS may see".
1013      *
1014      * So for compatibility reasons with old BIOSes we are stuck with
1015      * "etc/max-cpus" actually being apic_id_limit
1016      */
1017     fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)pcms->apic_id_limit);
1018     fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);
1019     fw_cfg_add_bytes(fw_cfg, FW_CFG_ACPI_TABLES,
1020                      acpi_tables, acpi_tables_len);
1021     fw_cfg_add_i32(fw_cfg, FW_CFG_IRQ0_OVERRIDE, kvm_allows_irq0_override());
1022 
1023     fw_cfg_add_bytes(fw_cfg, FW_CFG_E820_TABLE,
1024                      &e820_reserve, sizeof(e820_reserve));
1025     fw_cfg_add_file(fw_cfg, "etc/e820", e820_table,
1026                     sizeof(struct e820_entry) * e820_entries);
1027 
1028     fw_cfg_add_bytes(fw_cfg, FW_CFG_HPET, &hpet_cfg, sizeof(hpet_cfg));
1029     /* allocate memory for the NUMA channel: one (64bit) word for the number
1030      * of nodes, one word for each VCPU->node and one word for each node to
1031      * hold the amount of memory.
1032      */
1033     numa_fw_cfg = g_new0(uint64_t, 1 + pcms->apic_id_limit + nb_numa_nodes);
1034     numa_fw_cfg[0] = cpu_to_le64(nb_numa_nodes);
1035     cpus = mc->possible_cpu_arch_ids(MACHINE(pcms));
1036     for (i = 0; i < cpus->len; i++) {
1037         unsigned int apic_id = cpus->cpus[i].arch_id;
1038         assert(apic_id < pcms->apic_id_limit);
1039         numa_fw_cfg[apic_id + 1] = cpu_to_le64(cpus->cpus[i].props.node_id);
1040     }
1041     for (i = 0; i < nb_numa_nodes; i++) {
1042         numa_fw_cfg[pcms->apic_id_limit + 1 + i] =
1043             cpu_to_le64(numa_info[i].node_mem);
1044     }
1045     fw_cfg_add_bytes(fw_cfg, FW_CFG_NUMA, numa_fw_cfg,
1046                      (1 + pcms->apic_id_limit + nb_numa_nodes) *
1047                      sizeof(*numa_fw_cfg));
1048 
1049     return fw_cfg;
1050 }
1051 
1052 static long get_file_size(FILE *f)
1053 {
1054     long where, size;
1055 
1056     /* XXX: on Unix systems, using fstat() probably makes more sense */
1057 
1058     where = ftell(f);
1059     fseek(f, 0, SEEK_END);
1060     size = ftell(f);
1061     fseek(f, where, SEEK_SET);
1062 
1063     return size;
1064 }
1065 
1066 struct setup_data {
1067     uint64_t next;
1068     uint32_t type;
1069     uint32_t len;
1070     uint8_t data[0];
1071 } __attribute__((packed));
1072 
1073 
1074 /*
1075  * The entry point into the kernel for PVH boot is different from
1076  * the native entry point.  The PVH entry is defined by the x86/HVM
1077  * direct boot ABI and is available in an ELFNOTE in the kernel binary.
1078  *
1079  * This function is passed to load_elf() when it is called from
1080  * load_elfboot() which then additionally checks for an ELF Note of
1081  * type XEN_ELFNOTE_PHYS32_ENTRY and passes it to this function to
1082  * parse the PVH entry address from the ELF Note.
1083  *
1084  * Due to trickery in elf_opts.h, load_elf() is actually available as
1085  * load_elf32() or load_elf64() and this routine needs to be able
1086  * to deal with being called as 32 or 64 bit.
1087  *
1088  * The address of the PVH entry point is saved to the 'pvh_start_addr'
1089  * global variable.  (although the entry point is 32-bit, the kernel
1090  * binary can be either 32-bit or 64-bit).
1091  */
1092 static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64)
1093 {
1094     size_t *elf_note_data_addr;
1095 
1096     /* Check if ELF Note header passed in is valid */
1097     if (arg1 == NULL) {
1098         return 0;
1099     }
1100 
1101     if (is64) {
1102         struct elf64_note *nhdr64 = (struct elf64_note *)arg1;
1103         uint64_t nhdr_size64 = sizeof(struct elf64_note);
1104         uint64_t phdr_align = *(uint64_t *)arg2;
1105         uint64_t nhdr_namesz = nhdr64->n_namesz;
1106 
1107         elf_note_data_addr =
1108             ((void *)nhdr64) + nhdr_size64 +
1109             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
1110     } else {
1111         struct elf32_note *nhdr32 = (struct elf32_note *)arg1;
1112         uint32_t nhdr_size32 = sizeof(struct elf32_note);
1113         uint32_t phdr_align = *(uint32_t *)arg2;
1114         uint32_t nhdr_namesz = nhdr32->n_namesz;
1115 
1116         elf_note_data_addr =
1117             ((void *)nhdr32) + nhdr_size32 +
1118             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
1119     }
1120 
1121     pvh_start_addr = *elf_note_data_addr;
1122 
1123     return pvh_start_addr;
1124 }
1125 
1126 static bool load_elfboot(const char *kernel_filename,
1127                    int kernel_file_size,
1128                    uint8_t *header,
1129                    size_t pvh_xen_start_addr,
1130                    FWCfgState *fw_cfg)
1131 {
1132     uint32_t flags = 0;
1133     uint32_t mh_load_addr = 0;
1134     uint32_t elf_kernel_size = 0;
1135     uint64_t elf_entry;
1136     uint64_t elf_low, elf_high;
1137     int kernel_size;
1138 
1139     if (ldl_p(header) != 0x464c457f) {
1140         return false; /* no elfboot */
1141     }
1142 
1143     bool elf_is64 = header[EI_CLASS] == ELFCLASS64;
1144     flags = elf_is64 ?
1145         ((Elf64_Ehdr *)header)->e_flags : ((Elf32_Ehdr *)header)->e_flags;
1146 
1147     if (flags & 0x00010004) { /* LOAD_ELF_HEADER_HAS_ADDR */
1148         error_report("elfboot unsupported flags = %x", flags);
1149         exit(1);
1150     }
1151 
1152     uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY;
1153     kernel_size = load_elf(kernel_filename, read_pvh_start_addr,
1154                            NULL, &elf_note_type, &elf_entry,
1155                            &elf_low, &elf_high, 0, I386_ELF_MACHINE,
1156                            0, 0);
1157 
1158     if (kernel_size < 0) {
1159         error_report("Error while loading elf kernel");
1160         exit(1);
1161     }
1162     mh_load_addr = elf_low;
1163     elf_kernel_size = elf_high - elf_low;
1164 
1165     if (pvh_start_addr == 0) {
1166         error_report("Error loading uncompressed kernel without PVH ELF Note");
1167         exit(1);
1168     }
1169     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr);
1170     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
1171     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size);
1172 
1173     return true;
1174 }
1175 
1176 static void load_linux(PCMachineState *pcms,
1177                        FWCfgState *fw_cfg)
1178 {
1179     uint16_t protocol;
1180     int setup_size, kernel_size, cmdline_size;
1181     int dtb_size, setup_data_offset;
1182     uint32_t initrd_max;
1183     uint8_t header[8192], *setup, *kernel;
1184     hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
1185     FILE *f;
1186     char *vmode;
1187     MachineState *machine = MACHINE(pcms);
1188     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1189     struct setup_data *setup_data;
1190     const char *kernel_filename = machine->kernel_filename;
1191     const char *initrd_filename = machine->initrd_filename;
1192     const char *dtb_filename = machine->dtb;
1193     const char *kernel_cmdline = machine->kernel_cmdline;
1194 
1195     /* Align to 16 bytes as a paranoia measure */
1196     cmdline_size = (strlen(kernel_cmdline)+16) & ~15;
1197 
1198     /* load the kernel header */
1199     f = fopen(kernel_filename, "rb");
1200     if (!f || !(kernel_size = get_file_size(f)) ||
1201         fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
1202         MIN(ARRAY_SIZE(header), kernel_size)) {
1203         fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
1204                 kernel_filename, strerror(errno));
1205         exit(1);
1206     }
1207 
1208     /* kernel protocol version */
1209 #if 0
1210     fprintf(stderr, "header magic: %#x\n", ldl_p(header+0x202));
1211 #endif
1212     if (ldl_p(header+0x202) == 0x53726448) {
1213         protocol = lduw_p(header+0x206);
1214     } else {
1215         /*
1216          * This could be a multiboot kernel. If it is, let's stop treating it
1217          * like a Linux kernel.
1218          * Note: some multiboot images could be in the ELF format (the same of
1219          * PVH), so we try multiboot first since we check the multiboot magic
1220          * header before to load it.
1221          */
1222         if (load_multiboot(fw_cfg, f, kernel_filename, initrd_filename,
1223                            kernel_cmdline, kernel_size, header)) {
1224             return;
1225         }
1226         /*
1227          * Check if the file is an uncompressed kernel file (ELF) and load it,
1228          * saving the PVH entry point used by the x86/HVM direct boot ABI.
1229          * If load_elfboot() is successful, populate the fw_cfg info.
1230          */
1231         if (pcmc->pvh_enabled &&
1232             load_elfboot(kernel_filename, kernel_size,
1233                          header, pvh_start_addr, fw_cfg)) {
1234             fclose(f);
1235 
1236             fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
1237                 strlen(kernel_cmdline) + 1);
1238             fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
1239 
1240             fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, sizeof(header));
1241             fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA,
1242                              header, sizeof(header));
1243 
1244             /* load initrd */
1245             if (initrd_filename) {
1246                 gsize initrd_size;
1247                 gchar *initrd_data;
1248                 GError *gerr = NULL;
1249 
1250                 if (!g_file_get_contents(initrd_filename, &initrd_data,
1251                             &initrd_size, &gerr)) {
1252                     fprintf(stderr, "qemu: error reading initrd %s: %s\n",
1253                             initrd_filename, gerr->message);
1254                     exit(1);
1255                 }
1256 
1257                 initrd_max = pcms->below_4g_mem_size - pcmc->acpi_data_size - 1;
1258                 if (initrd_size >= initrd_max) {
1259                     fprintf(stderr, "qemu: initrd is too large, cannot support."
1260                             "(max: %"PRIu32", need %"PRId64")\n",
1261                             initrd_max, (uint64_t)initrd_size);
1262                     exit(1);
1263                 }
1264 
1265                 initrd_addr = (initrd_max - initrd_size) & ~4095;
1266 
1267                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
1268                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
1269                 fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data,
1270                                  initrd_size);
1271             }
1272 
1273             option_rom[nb_option_roms].bootindex = 0;
1274             option_rom[nb_option_roms].name = "pvh.bin";
1275             nb_option_roms++;
1276 
1277             return;
1278         }
1279         protocol = 0;
1280     }
1281 
1282     if (protocol < 0x200 || !(header[0x211] & 0x01)) {
1283         /* Low kernel */
1284         real_addr    = 0x90000;
1285         cmdline_addr = 0x9a000 - cmdline_size;
1286         prot_addr    = 0x10000;
1287     } else if (protocol < 0x202) {
1288         /* High but ancient kernel */
1289         real_addr    = 0x90000;
1290         cmdline_addr = 0x9a000 - cmdline_size;
1291         prot_addr    = 0x100000;
1292     } else {
1293         /* High and recent kernel */
1294         real_addr    = 0x10000;
1295         cmdline_addr = 0x20000;
1296         prot_addr    = 0x100000;
1297     }
1298 
1299 #if 0
1300     fprintf(stderr,
1301             "qemu: real_addr     = 0x" TARGET_FMT_plx "\n"
1302             "qemu: cmdline_addr  = 0x" TARGET_FMT_plx "\n"
1303             "qemu: prot_addr     = 0x" TARGET_FMT_plx "\n",
1304             real_addr,
1305             cmdline_addr,
1306             prot_addr);
1307 #endif
1308 
1309     /* highest address for loading the initrd */
1310     if (protocol >= 0x20c &&
1311         lduw_p(header+0x236) & XLF_CAN_BE_LOADED_ABOVE_4G) {
1312         /*
1313          * Linux has supported initrd up to 4 GB for a very long time (2007,
1314          * long before XLF_CAN_BE_LOADED_ABOVE_4G which was added in 2013),
1315          * though it only sets initrd_max to 2 GB to "work around bootloader
1316          * bugs". Luckily, QEMU firmware(which does something like bootloader)
1317          * has supported this.
1318          *
1319          * It's believed that if XLF_CAN_BE_LOADED_ABOVE_4G is set, initrd can
1320          * be loaded into any address.
1321          *
1322          * In addition, initrd_max is uint32_t simply because QEMU doesn't
1323          * support the 64-bit boot protocol (specifically the ext_ramdisk_image
1324          * field).
1325          *
1326          * Therefore here just limit initrd_max to UINT32_MAX simply as well.
1327          */
1328         initrd_max = UINT32_MAX;
1329     } else if (protocol >= 0x203) {
1330         initrd_max = ldl_p(header+0x22c);
1331     } else {
1332         initrd_max = 0x37ffffff;
1333     }
1334 
1335     if (initrd_max >= pcms->below_4g_mem_size - pcmc->acpi_data_size) {
1336         initrd_max = pcms->below_4g_mem_size - pcmc->acpi_data_size - 1;
1337     }
1338 
1339     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
1340     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline)+1);
1341     fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
1342 
1343     if (protocol >= 0x202) {
1344         stl_p(header+0x228, cmdline_addr);
1345     } else {
1346         stw_p(header+0x20, 0xA33F);
1347         stw_p(header+0x22, cmdline_addr-real_addr);
1348     }
1349 
1350     /* handle vga= parameter */
1351     vmode = strstr(kernel_cmdline, "vga=");
1352     if (vmode) {
1353         unsigned int video_mode;
1354         /* skip "vga=" */
1355         vmode += 4;
1356         if (!strncmp(vmode, "normal", 6)) {
1357             video_mode = 0xffff;
1358         } else if (!strncmp(vmode, "ext", 3)) {
1359             video_mode = 0xfffe;
1360         } else if (!strncmp(vmode, "ask", 3)) {
1361             video_mode = 0xfffd;
1362         } else {
1363             video_mode = strtol(vmode, NULL, 0);
1364         }
1365         stw_p(header+0x1fa, video_mode);
1366     }
1367 
1368     /* loader type */
1369     /* High nybble = B reserved for QEMU; low nybble is revision number.
1370        If this code is substantially changed, you may want to consider
1371        incrementing the revision. */
1372     if (protocol >= 0x200) {
1373         header[0x210] = 0xB0;
1374     }
1375     /* heap */
1376     if (protocol >= 0x201) {
1377         header[0x211] |= 0x80;	/* CAN_USE_HEAP */
1378         stw_p(header+0x224, cmdline_addr-real_addr-0x200);
1379     }
1380 
1381     /* load initrd */
1382     if (initrd_filename) {
1383         gsize initrd_size;
1384         gchar *initrd_data;
1385         GError *gerr = NULL;
1386 
1387         if (protocol < 0x200) {
1388             fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
1389             exit(1);
1390         }
1391 
1392         if (!g_file_get_contents(initrd_filename, &initrd_data,
1393                                  &initrd_size, &gerr)) {
1394             fprintf(stderr, "qemu: error reading initrd %s: %s\n",
1395                     initrd_filename, gerr->message);
1396             exit(1);
1397         }
1398         if (initrd_size >= initrd_max) {
1399             fprintf(stderr, "qemu: initrd is too large, cannot support."
1400                     "(max: %"PRIu32", need %"PRId64")\n",
1401                     initrd_max, (uint64_t)initrd_size);
1402             exit(1);
1403         }
1404 
1405         initrd_addr = (initrd_max-initrd_size) & ~4095;
1406 
1407         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
1408         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
1409         fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
1410 
1411         stl_p(header+0x218, initrd_addr);
1412         stl_p(header+0x21c, initrd_size);
1413     }
1414 
1415     /* load kernel and setup */
1416     setup_size = header[0x1f1];
1417     if (setup_size == 0) {
1418         setup_size = 4;
1419     }
1420     setup_size = (setup_size+1)*512;
1421     if (setup_size > kernel_size) {
1422         fprintf(stderr, "qemu: invalid kernel header\n");
1423         exit(1);
1424     }
1425     kernel_size -= setup_size;
1426 
1427     setup  = g_malloc(setup_size);
1428     kernel = g_malloc(kernel_size);
1429     fseek(f, 0, SEEK_SET);
1430     if (fread(setup, 1, setup_size, f) != setup_size) {
1431         fprintf(stderr, "fread() failed\n");
1432         exit(1);
1433     }
1434     if (fread(kernel, 1, kernel_size, f) != kernel_size) {
1435         fprintf(stderr, "fread() failed\n");
1436         exit(1);
1437     }
1438     fclose(f);
1439 
1440     /* append dtb to kernel */
1441     if (dtb_filename) {
1442         if (protocol < 0x209) {
1443             fprintf(stderr, "qemu: Linux kernel too old to load a dtb\n");
1444             exit(1);
1445         }
1446 
1447         dtb_size = get_image_size(dtb_filename);
1448         if (dtb_size <= 0) {
1449             fprintf(stderr, "qemu: error reading dtb %s: %s\n",
1450                     dtb_filename, strerror(errno));
1451             exit(1);
1452         }
1453 
1454         setup_data_offset = QEMU_ALIGN_UP(kernel_size, 16);
1455         kernel_size = setup_data_offset + sizeof(struct setup_data) + dtb_size;
1456         kernel = g_realloc(kernel, kernel_size);
1457 
1458         stq_p(header+0x250, prot_addr + setup_data_offset);
1459 
1460         setup_data = (struct setup_data *)(kernel + setup_data_offset);
1461         setup_data->next = 0;
1462         setup_data->type = cpu_to_le32(SETUP_DTB);
1463         setup_data->len = cpu_to_le32(dtb_size);
1464 
1465         load_image_size(dtb_filename, setup_data->data, dtb_size);
1466     }
1467 
1468     memcpy(setup, header, MIN(sizeof(header), setup_size));
1469 
1470     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
1471     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
1472     fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);
1473 
1474     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
1475     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
1476     fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
1477 
1478     option_rom[nb_option_roms].bootindex = 0;
1479     option_rom[nb_option_roms].name = "linuxboot.bin";
1480     if (pcmc->linuxboot_dma_enabled && fw_cfg_dma_enabled(fw_cfg)) {
1481         option_rom[nb_option_roms].name = "linuxboot_dma.bin";
1482     }
1483     nb_option_roms++;
1484 }
1485 
1486 #define NE2000_NB_MAX 6
1487 
1488 static const int ne2000_io[NE2000_NB_MAX] = { 0x300, 0x320, 0x340, 0x360,
1489                                               0x280, 0x380 };
1490 static const int ne2000_irq[NE2000_NB_MAX] = { 9, 10, 11, 3, 4, 5 };
1491 
1492 void pc_init_ne2k_isa(ISABus *bus, NICInfo *nd)
1493 {
1494     static int nb_ne2k = 0;
1495 
1496     if (nb_ne2k == NE2000_NB_MAX)
1497         return;
1498     isa_ne2000_init(bus, ne2000_io[nb_ne2k],
1499                     ne2000_irq[nb_ne2k], nd);
1500     nb_ne2k++;
1501 }
1502 
1503 DeviceState *cpu_get_current_apic(void)
1504 {
1505     if (current_cpu) {
1506         X86CPU *cpu = X86_CPU(current_cpu);
1507         return cpu->apic_state;
1508     } else {
1509         return NULL;
1510     }
1511 }
1512 
1513 void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
1514 {
1515     X86CPU *cpu = opaque;
1516 
1517     if (level) {
1518         cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
1519     }
1520 }
1521 
1522 static void pc_new_cpu(PCMachineState *pcms, int64_t apic_id, Error **errp)
1523 {
1524     Object *cpu = NULL;
1525     Error *local_err = NULL;
1526     CPUX86State *env = NULL;
1527 
1528     cpu = object_new(MACHINE(pcms)->cpu_type);
1529 
1530     env = &X86_CPU(cpu)->env;
1531     env->nr_dies = pcms->smp_dies;
1532 
1533     object_property_set_uint(cpu, apic_id, "apic-id", &local_err);
1534     object_property_set_bool(cpu, true, "realized", &local_err);
1535 
1536     object_unref(cpu);
1537     error_propagate(errp, local_err);
1538 }
1539 
1540 /*
1541  * This function is very similar to smp_parse()
1542  * in hw/core/machine.c but includes CPU die support.
1543  */
1544 void pc_smp_parse(MachineState *ms, QemuOpts *opts)
1545 {
1546     PCMachineState *pcms = PC_MACHINE(ms);
1547 
1548     if (opts) {
1549         unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
1550         unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
1551         unsigned dies = qemu_opt_get_number(opts, "dies", 1);
1552         unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
1553         unsigned threads = qemu_opt_get_number(opts, "threads", 0);
1554 
1555         /* compute missing values, prefer sockets over cores over threads */
1556         if (cpus == 0 || sockets == 0) {
1557             cores = cores > 0 ? cores : 1;
1558             threads = threads > 0 ? threads : 1;
1559             if (cpus == 0) {
1560                 sockets = sockets > 0 ? sockets : 1;
1561                 cpus = cores * threads * dies * sockets;
1562             } else {
1563                 ms->smp.max_cpus =
1564                         qemu_opt_get_number(opts, "maxcpus", cpus);
1565                 sockets = ms->smp.max_cpus / (cores * threads * dies);
1566             }
1567         } else if (cores == 0) {
1568             threads = threads > 0 ? threads : 1;
1569             cores = cpus / (sockets * dies * threads);
1570             cores = cores > 0 ? cores : 1;
1571         } else if (threads == 0) {
1572             threads = cpus / (cores * dies * sockets);
1573             threads = threads > 0 ? threads : 1;
1574         } else if (sockets * dies * cores * threads < cpus) {
1575             error_report("cpu topology: "
1576                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) < "
1577                          "smp_cpus (%u)",
1578                          sockets, dies, cores, threads, cpus);
1579             exit(1);
1580         }
1581 
1582         ms->smp.max_cpus =
1583                 qemu_opt_get_number(opts, "maxcpus", cpus);
1584 
1585         if (ms->smp.max_cpus < cpus) {
1586             error_report("maxcpus must be equal to or greater than smp");
1587             exit(1);
1588         }
1589 
1590         if (sockets * dies * cores * threads > ms->smp.max_cpus) {
1591             error_report("cpu topology: "
1592                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) > "
1593                          "maxcpus (%u)",
1594                          sockets, dies, cores, threads,
1595                          ms->smp.max_cpus);
1596             exit(1);
1597         }
1598 
1599         if (sockets * dies * cores * threads != ms->smp.max_cpus) {
1600             warn_report("Invalid CPU topology deprecated: "
1601                         "sockets (%u) * dies (%u) * cores (%u) * threads (%u) "
1602                         "!= maxcpus (%u)",
1603                         sockets, dies, cores, threads,
1604                         ms->smp.max_cpus);
1605         }
1606 
1607         ms->smp.cpus = cpus;
1608         ms->smp.cores = cores;
1609         ms->smp.threads = threads;
1610         pcms->smp_dies = dies;
1611     }
1612 
1613     if (ms->smp.cpus > 1) {
1614         Error *blocker = NULL;
1615         error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");
1616         replay_add_blocker(blocker);
1617     }
1618 }
1619 
1620 void pc_hot_add_cpu(MachineState *ms, const int64_t id, Error **errp)
1621 {
1622     PCMachineState *pcms = PC_MACHINE(ms);
1623     int64_t apic_id = x86_cpu_apic_id_from_index(pcms, id);
1624     Error *local_err = NULL;
1625 
1626     if (id < 0) {
1627         error_setg(errp, "Invalid CPU id: %" PRIi64, id);
1628         return;
1629     }
1630 
1631     if (apic_id >= ACPI_CPU_HOTPLUG_ID_LIMIT) {
1632         error_setg(errp, "Unable to add CPU: %" PRIi64
1633                    ", resulting APIC ID (%" PRIi64 ") is too large",
1634                    id, apic_id);
1635         return;
1636     }
1637 
1638     pc_new_cpu(PC_MACHINE(ms), apic_id, &local_err);
1639     if (local_err) {
1640         error_propagate(errp, local_err);
1641         return;
1642     }
1643 }
1644 
1645 void pc_cpus_init(PCMachineState *pcms)
1646 {
1647     int i;
1648     const CPUArchIdList *possible_cpus;
1649     MachineState *ms = MACHINE(pcms);
1650     MachineClass *mc = MACHINE_GET_CLASS(pcms);
1651     PCMachineClass *pcmc = PC_MACHINE_CLASS(mc);
1652 
1653     x86_cpu_set_default_version(pcmc->default_cpu_version);
1654 
1655     /* Calculates the limit to CPU APIC ID values
1656      *
1657      * Limit for the APIC ID value, so that all
1658      * CPU APIC IDs are < pcms->apic_id_limit.
1659      *
1660      * This is used for FW_CFG_MAX_CPUS. See comments on bochs_bios_init().
1661      */
1662     pcms->apic_id_limit = x86_cpu_apic_id_from_index(pcms,
1663                                                      ms->smp.max_cpus - 1) + 1;
1664     possible_cpus = mc->possible_cpu_arch_ids(ms);
1665     for (i = 0; i < ms->smp.cpus; i++) {
1666         pc_new_cpu(pcms, possible_cpus->cpus[i].arch_id, &error_fatal);
1667     }
1668 }
1669 
1670 static void pc_build_feature_control_file(PCMachineState *pcms)
1671 {
1672     MachineState *ms = MACHINE(pcms);
1673     X86CPU *cpu = X86_CPU(ms->possible_cpus->cpus[0].cpu);
1674     CPUX86State *env = &cpu->env;
1675     uint32_t unused, ecx, edx;
1676     uint64_t feature_control_bits = 0;
1677     uint64_t *val;
1678 
1679     cpu_x86_cpuid(env, 1, 0, &unused, &unused, &ecx, &edx);
1680     if (ecx & CPUID_EXT_VMX) {
1681         feature_control_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1682     }
1683 
1684     if ((edx & (CPUID_EXT2_MCE | CPUID_EXT2_MCA)) ==
1685         (CPUID_EXT2_MCE | CPUID_EXT2_MCA) &&
1686         (env->mcg_cap & MCG_LMCE_P)) {
1687         feature_control_bits |= FEATURE_CONTROL_LMCE;
1688     }
1689 
1690     if (!feature_control_bits) {
1691         return;
1692     }
1693 
1694     val = g_malloc(sizeof(*val));
1695     *val = cpu_to_le64(feature_control_bits | FEATURE_CONTROL_LOCKED);
1696     fw_cfg_add_file(pcms->fw_cfg, "etc/msr_feature_control", val, sizeof(*val));
1697 }
1698 
1699 static void rtc_set_cpus_count(ISADevice *rtc, uint16_t cpus_count)
1700 {
1701     if (cpus_count > 0xff) {
1702         /* If the number of CPUs can't be represented in 8 bits, the
1703          * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
1704          * to make old BIOSes fail more predictably.
1705          */
1706         rtc_set_memory(rtc, 0x5f, 0);
1707     } else {
1708         rtc_set_memory(rtc, 0x5f, cpus_count - 1);
1709     }
1710 }
1711 
1712 static
1713 void pc_machine_done(Notifier *notifier, void *data)
1714 {
1715     PCMachineState *pcms = container_of(notifier,
1716                                         PCMachineState, machine_done);
1717     PCIBus *bus = pcms->bus;
1718 
1719     /* set the number of CPUs */
1720     rtc_set_cpus_count(pcms->rtc, pcms->boot_cpus);
1721 
1722     if (bus) {
1723         int extra_hosts = 0;
1724 
1725         QLIST_FOREACH(bus, &bus->child, sibling) {
1726             /* look for expander root buses */
1727             if (pci_bus_is_root(bus)) {
1728                 extra_hosts++;
1729             }
1730         }
1731         if (extra_hosts && pcms->fw_cfg) {
1732             uint64_t *val = g_malloc(sizeof(*val));
1733             *val = cpu_to_le64(extra_hosts);
1734             fw_cfg_add_file(pcms->fw_cfg,
1735                     "etc/extra-pci-roots", val, sizeof(*val));
1736         }
1737     }
1738 
1739     acpi_setup();
1740     if (pcms->fw_cfg) {
1741         pc_build_smbios(pcms);
1742         pc_build_feature_control_file(pcms);
1743         /* update FW_CFG_NB_CPUS to account for -device added CPUs */
1744         fw_cfg_modify_i16(pcms->fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);
1745     }
1746 
1747     if (pcms->apic_id_limit > 255 && !xen_enabled()) {
1748         IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
1749 
1750         if (!iommu || !x86_iommu_ir_supported(X86_IOMMU_DEVICE(iommu)) ||
1751             iommu->intr_eim != ON_OFF_AUTO_ON) {
1752             error_report("current -smp configuration requires "
1753                          "Extended Interrupt Mode enabled. "
1754                          "You can add an IOMMU using: "
1755                          "-device intel-iommu,intremap=on,eim=on");
1756             exit(EXIT_FAILURE);
1757         }
1758     }
1759 }
1760 
1761 void pc_guest_info_init(PCMachineState *pcms)
1762 {
1763     int i;
1764 
1765     pcms->apic_xrupt_override = kvm_allows_irq0_override();
1766     pcms->numa_nodes = nb_numa_nodes;
1767     pcms->node_mem = g_malloc0(pcms->numa_nodes *
1768                                     sizeof *pcms->node_mem);
1769     for (i = 0; i < nb_numa_nodes; i++) {
1770         pcms->node_mem[i] = numa_info[i].node_mem;
1771     }
1772 
1773     pcms->machine_done.notify = pc_machine_done;
1774     qemu_add_machine_init_done_notifier(&pcms->machine_done);
1775 }
1776 
1777 /* setup pci memory address space mapping into system address space */
1778 void pc_pci_as_mapping_init(Object *owner, MemoryRegion *system_memory,
1779                             MemoryRegion *pci_address_space)
1780 {
1781     /* Set to lower priority than RAM */
1782     memory_region_add_subregion_overlap(system_memory, 0x0,
1783                                         pci_address_space, -1);
1784 }
1785 
1786 void xen_load_linux(PCMachineState *pcms)
1787 {
1788     int i;
1789     FWCfgState *fw_cfg;
1790 
1791     assert(MACHINE(pcms)->kernel_filename != NULL);
1792 
1793     fw_cfg = fw_cfg_init_io(FW_CFG_IO_BASE);
1794     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);
1795     rom_set_fw(fw_cfg);
1796 
1797     load_linux(pcms, fw_cfg);
1798     for (i = 0; i < nb_option_roms; i++) {
1799         assert(!strcmp(option_rom[i].name, "linuxboot.bin") ||
1800                !strcmp(option_rom[i].name, "linuxboot_dma.bin") ||
1801                !strcmp(option_rom[i].name, "pvh.bin") ||
1802                !strcmp(option_rom[i].name, "multiboot.bin"));
1803         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1804     }
1805     pcms->fw_cfg = fw_cfg;
1806 }
1807 
1808 void pc_memory_init(PCMachineState *pcms,
1809                     MemoryRegion *system_memory,
1810                     MemoryRegion *rom_memory,
1811                     MemoryRegion **ram_memory)
1812 {
1813     int linux_boot, i;
1814     MemoryRegion *ram, *option_rom_mr;
1815     MemoryRegion *ram_below_4g, *ram_above_4g;
1816     FWCfgState *fw_cfg;
1817     MachineState *machine = MACHINE(pcms);
1818     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1819 
1820     assert(machine->ram_size == pcms->below_4g_mem_size +
1821                                 pcms->above_4g_mem_size);
1822 
1823     linux_boot = (machine->kernel_filename != NULL);
1824 
1825     /* Allocate RAM.  We allocate it as a single memory region and use
1826      * aliases to address portions of it, mostly for backwards compatibility
1827      * with older qemus that used qemu_ram_alloc().
1828      */
1829     ram = g_malloc(sizeof(*ram));
1830     memory_region_allocate_system_memory(ram, NULL, "pc.ram",
1831                                          machine->ram_size);
1832     *ram_memory = ram;
1833     ram_below_4g = g_malloc(sizeof(*ram_below_4g));
1834     memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram,
1835                              0, pcms->below_4g_mem_size);
1836     memory_region_add_subregion(system_memory, 0, ram_below_4g);
1837     e820_add_entry(0, pcms->below_4g_mem_size, E820_RAM);
1838     if (pcms->above_4g_mem_size > 0) {
1839         ram_above_4g = g_malloc(sizeof(*ram_above_4g));
1840         memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g", ram,
1841                                  pcms->below_4g_mem_size,
1842                                  pcms->above_4g_mem_size);
1843         memory_region_add_subregion(system_memory, 0x100000000ULL,
1844                                     ram_above_4g);
1845         e820_add_entry(0x100000000ULL, pcms->above_4g_mem_size, E820_RAM);
1846     }
1847 
1848     if (!pcmc->has_reserved_memory &&
1849         (machine->ram_slots ||
1850          (machine->maxram_size > machine->ram_size))) {
1851         MachineClass *mc = MACHINE_GET_CLASS(machine);
1852 
1853         error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",
1854                      mc->name);
1855         exit(EXIT_FAILURE);
1856     }
1857 
1858     /* always allocate the device memory information */
1859     machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
1860 
1861     /* initialize device memory address space */
1862     if (pcmc->has_reserved_memory &&
1863         (machine->ram_size < machine->maxram_size)) {
1864         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
1865 
1866         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
1867             error_report("unsupported amount of memory slots: %"PRIu64,
1868                          machine->ram_slots);
1869             exit(EXIT_FAILURE);
1870         }
1871 
1872         if (QEMU_ALIGN_UP(machine->maxram_size,
1873                           TARGET_PAGE_SIZE) != machine->maxram_size) {
1874             error_report("maximum memory size must by aligned to multiple of "
1875                          "%d bytes", TARGET_PAGE_SIZE);
1876             exit(EXIT_FAILURE);
1877         }
1878 
1879         machine->device_memory->base =
1880             ROUND_UP(0x100000000ULL + pcms->above_4g_mem_size, 1 * GiB);
1881 
1882         if (pcmc->enforce_aligned_dimm) {
1883             /* size device region assuming 1G page max alignment per slot */
1884             device_mem_size += (1 * GiB) * machine->ram_slots;
1885         }
1886 
1887         if ((machine->device_memory->base + device_mem_size) <
1888             device_mem_size) {
1889             error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,
1890                          machine->maxram_size);
1891             exit(EXIT_FAILURE);
1892         }
1893 
1894         memory_region_init(&machine->device_memory->mr, OBJECT(pcms),
1895                            "device-memory", device_mem_size);
1896         memory_region_add_subregion(system_memory, machine->device_memory->base,
1897                                     &machine->device_memory->mr);
1898     }
1899 
1900     /* Initialize PC system firmware */
1901     pc_system_firmware_init(pcms, rom_memory);
1902 
1903     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
1904     memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
1905                            &error_fatal);
1906     if (pcmc->pci_enabled) {
1907         memory_region_set_readonly(option_rom_mr, true);
1908     }
1909     memory_region_add_subregion_overlap(rom_memory,
1910                                         PC_ROM_MIN_VGA,
1911                                         option_rom_mr,
1912                                         1);
1913 
1914     fw_cfg = bochs_bios_init(&address_space_memory, pcms);
1915 
1916     rom_set_fw(fw_cfg);
1917 
1918     if (pcmc->has_reserved_memory && machine->device_memory->base) {
1919         uint64_t *val = g_malloc(sizeof(*val));
1920         PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1921         uint64_t res_mem_end = machine->device_memory->base;
1922 
1923         if (!pcmc->broken_reserved_end) {
1924             res_mem_end += memory_region_size(&machine->device_memory->mr);
1925         }
1926         *val = cpu_to_le64(ROUND_UP(res_mem_end, 1 * GiB));
1927         fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));
1928     }
1929 
1930     if (linux_boot) {
1931         load_linux(pcms, fw_cfg);
1932     }
1933 
1934     for (i = 0; i < nb_option_roms; i++) {
1935         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1936     }
1937     pcms->fw_cfg = fw_cfg;
1938 
1939     /* Init default IOAPIC address space */
1940     pcms->ioapic_as = &address_space_memory;
1941 }
1942 
1943 /*
1944  * The 64bit pci hole starts after "above 4G RAM" and
1945  * potentially the space reserved for memory hotplug.
1946  */
1947 uint64_t pc_pci_hole64_start(void)
1948 {
1949     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
1950     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1951     MachineState *ms = MACHINE(pcms);
1952     uint64_t hole64_start = 0;
1953 
1954     if (pcmc->has_reserved_memory && ms->device_memory->base) {
1955         hole64_start = ms->device_memory->base;
1956         if (!pcmc->broken_reserved_end) {
1957             hole64_start += memory_region_size(&ms->device_memory->mr);
1958         }
1959     } else {
1960         hole64_start = 0x100000000ULL + pcms->above_4g_mem_size;
1961     }
1962 
1963     return ROUND_UP(hole64_start, 1 * GiB);
1964 }
1965 
1966 qemu_irq pc_allocate_cpu_irq(void)
1967 {
1968     return qemu_allocate_irq(pic_irq_request, NULL, 0);
1969 }
1970 
1971 DeviceState *pc_vga_init(ISABus *isa_bus, PCIBus *pci_bus)
1972 {
1973     DeviceState *dev = NULL;
1974 
1975     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_VGA);
1976     if (pci_bus) {
1977         PCIDevice *pcidev = pci_vga_init(pci_bus);
1978         dev = pcidev ? &pcidev->qdev : NULL;
1979     } else if (isa_bus) {
1980         ISADevice *isadev = isa_vga_init(isa_bus);
1981         dev = isadev ? DEVICE(isadev) : NULL;
1982     }
1983     rom_reset_order_override();
1984     return dev;
1985 }
1986 
1987 static const MemoryRegionOps ioport80_io_ops = {
1988     .write = ioport80_write,
1989     .read = ioport80_read,
1990     .endianness = DEVICE_NATIVE_ENDIAN,
1991     .impl = {
1992         .min_access_size = 1,
1993         .max_access_size = 1,
1994     },
1995 };
1996 
1997 static const MemoryRegionOps ioportF0_io_ops = {
1998     .write = ioportF0_write,
1999     .read = ioportF0_read,
2000     .endianness = DEVICE_NATIVE_ENDIAN,
2001     .impl = {
2002         .min_access_size = 1,
2003         .max_access_size = 1,
2004     },
2005 };
2006 
2007 static void pc_superio_init(ISABus *isa_bus, bool create_fdctrl, bool no_vmport)
2008 {
2009     int i;
2010     DriveInfo *fd[MAX_FD];
2011     qemu_irq *a20_line;
2012     ISADevice *i8042, *port92, *vmmouse;
2013 
2014     serial_hds_isa_init(isa_bus, 0, MAX_ISA_SERIAL_PORTS);
2015     parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);
2016 
2017     for (i = 0; i < MAX_FD; i++) {
2018         fd[i] = drive_get(IF_FLOPPY, 0, i);
2019         create_fdctrl |= !!fd[i];
2020     }
2021     if (create_fdctrl) {
2022         fdctrl_init_isa(isa_bus, fd);
2023     }
2024 
2025     i8042 = isa_create_simple(isa_bus, "i8042");
2026     if (!no_vmport) {
2027         vmport_init(isa_bus);
2028         vmmouse = isa_try_create(isa_bus, "vmmouse");
2029     } else {
2030         vmmouse = NULL;
2031     }
2032     if (vmmouse) {
2033         DeviceState *dev = DEVICE(vmmouse);
2034         qdev_prop_set_ptr(dev, "ps2_mouse", i8042);
2035         qdev_init_nofail(dev);
2036     }
2037     port92 = isa_create_simple(isa_bus, "port92");
2038 
2039     a20_line = qemu_allocate_irqs(handle_a20_line_change, first_cpu, 2);
2040     i8042_setup_a20_line(i8042, a20_line[0]);
2041     port92_init(port92, a20_line[1]);
2042     g_free(a20_line);
2043 }
2044 
2045 void pc_basic_device_init(ISABus *isa_bus, qemu_irq *gsi,
2046                           ISADevice **rtc_state,
2047                           bool create_fdctrl,
2048                           bool no_vmport,
2049                           bool has_pit,
2050                           uint32_t hpet_irqs)
2051 {
2052     int i;
2053     DeviceState *hpet = NULL;
2054     int pit_isa_irq = 0;
2055     qemu_irq pit_alt_irq = NULL;
2056     qemu_irq rtc_irq = NULL;
2057     ISADevice *pit = NULL;
2058     MemoryRegion *ioport80_io = g_new(MemoryRegion, 1);
2059     MemoryRegion *ioportF0_io = g_new(MemoryRegion, 1);
2060 
2061     memory_region_init_io(ioport80_io, NULL, &ioport80_io_ops, NULL, "ioport80", 1);
2062     memory_region_add_subregion(isa_bus->address_space_io, 0x80, ioport80_io);
2063 
2064     memory_region_init_io(ioportF0_io, NULL, &ioportF0_io_ops, NULL, "ioportF0", 1);
2065     memory_region_add_subregion(isa_bus->address_space_io, 0xf0, ioportF0_io);
2066 
2067     /*
2068      * Check if an HPET shall be created.
2069      *
2070      * Without KVM_CAP_PIT_STATE2, we cannot switch off the in-kernel PIT
2071      * when the HPET wants to take over. Thus we have to disable the latter.
2072      */
2073     if (!no_hpet && (!kvm_irqchip_in_kernel() || kvm_has_pit_state2())) {
2074         /* In order to set property, here not using sysbus_try_create_simple */
2075         hpet = qdev_try_create(NULL, TYPE_HPET);
2076         if (hpet) {
2077             /* For pc-piix-*, hpet's intcap is always IRQ2. For pc-q35-1.7
2078              * and earlier, use IRQ2 for compat. Otherwise, use IRQ16~23,
2079              * IRQ8 and IRQ2.
2080              */
2081             uint8_t compat = object_property_get_uint(OBJECT(hpet),
2082                     HPET_INTCAP, NULL);
2083             if (!compat) {
2084                 qdev_prop_set_uint32(hpet, HPET_INTCAP, hpet_irqs);
2085             }
2086             qdev_init_nofail(hpet);
2087             sysbus_mmio_map(SYS_BUS_DEVICE(hpet), 0, HPET_BASE);
2088 
2089             for (i = 0; i < GSI_NUM_PINS; i++) {
2090                 sysbus_connect_irq(SYS_BUS_DEVICE(hpet), i, gsi[i]);
2091             }
2092             pit_isa_irq = -1;
2093             pit_alt_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_PIT_INT);
2094             rtc_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_RTC_INT);
2095         }
2096     }
2097     *rtc_state = mc146818_rtc_init(isa_bus, 2000, rtc_irq);
2098 
2099     qemu_register_boot_set(pc_boot_set, *rtc_state);
2100 
2101     if (!xen_enabled() && has_pit) {
2102         if (kvm_pit_in_kernel()) {
2103             pit = kvm_pit_init(isa_bus, 0x40);
2104         } else {
2105             pit = i8254_pit_init(isa_bus, 0x40, pit_isa_irq, pit_alt_irq);
2106         }
2107         if (hpet) {
2108             /* connect PIT to output control line of the HPET */
2109             qdev_connect_gpio_out(hpet, 0, qdev_get_gpio_in(DEVICE(pit), 0));
2110         }
2111         pcspk_init(isa_bus, pit);
2112     }
2113 
2114     i8257_dma_init(isa_bus, 0);
2115 
2116     /* Super I/O */
2117     pc_superio_init(isa_bus, create_fdctrl, no_vmport);
2118 }
2119 
2120 void pc_nic_init(PCMachineClass *pcmc, ISABus *isa_bus, PCIBus *pci_bus)
2121 {
2122     int i;
2123 
2124     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_NIC);
2125     for (i = 0; i < nb_nics; i++) {
2126         NICInfo *nd = &nd_table[i];
2127         const char *model = nd->model ? nd->model : pcmc->default_nic_model;
2128 
2129         if (g_str_equal(model, "ne2k_isa")) {
2130             pc_init_ne2k_isa(isa_bus, nd);
2131         } else {
2132             pci_nic_init_nofail(nd, pci_bus, model, NULL);
2133         }
2134     }
2135     rom_reset_order_override();
2136 }
2137 
2138 void ioapic_init_gsi(GSIState *gsi_state, const char *parent_name)
2139 {
2140     DeviceState *dev;
2141     SysBusDevice *d;
2142     unsigned int i;
2143 
2144     if (kvm_ioapic_in_kernel()) {
2145         dev = qdev_create(NULL, TYPE_KVM_IOAPIC);
2146     } else {
2147         dev = qdev_create(NULL, TYPE_IOAPIC);
2148     }
2149     if (parent_name) {
2150         object_property_add_child(object_resolve_path(parent_name, NULL),
2151                                   "ioapic", OBJECT(dev), NULL);
2152     }
2153     qdev_init_nofail(dev);
2154     d = SYS_BUS_DEVICE(dev);
2155     sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
2156 
2157     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
2158         gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
2159     }
2160 }
2161 
2162 static void pc_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
2163                                Error **errp)
2164 {
2165     const PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2166     const PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
2167     const MachineState *ms = MACHINE(hotplug_dev);
2168     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2169     const uint64_t legacy_align = TARGET_PAGE_SIZE;
2170     Error *local_err = NULL;
2171 
2172     /*
2173      * When -no-acpi is used with Q35 machine type, no ACPI is built,
2174      * but pcms->acpi_dev is still created. Check !acpi_enabled in
2175      * addition to cover this case.
2176      */
2177     if (!pcms->acpi_dev || !acpi_enabled) {
2178         error_setg(errp,
2179                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
2180         return;
2181     }
2182 
2183     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
2184         error_setg(errp, "nvdimm is not enabled: missing 'nvdimm' in '-M'");
2185         return;
2186     }
2187 
2188     hotplug_handler_pre_plug(pcms->acpi_dev, dev, &local_err);
2189     if (local_err) {
2190         error_propagate(errp, local_err);
2191         return;
2192     }
2193 
2194     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev),
2195                      pcmc->enforce_aligned_dimm ? NULL : &legacy_align, errp);
2196 }
2197 
2198 static void pc_memory_plug(HotplugHandler *hotplug_dev,
2199                            DeviceState *dev, Error **errp)
2200 {
2201     Error *local_err = NULL;
2202     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2203     MachineState *ms = MACHINE(hotplug_dev);
2204     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2205 
2206     pc_dimm_plug(PC_DIMM(dev), MACHINE(pcms), &local_err);
2207     if (local_err) {
2208         goto out;
2209     }
2210 
2211     if (is_nvdimm) {
2212         nvdimm_plug(ms->nvdimms_state);
2213     }
2214 
2215     hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &error_abort);
2216 out:
2217     error_propagate(errp, local_err);
2218 }
2219 
2220 static void pc_memory_unplug_request(HotplugHandler *hotplug_dev,
2221                                      DeviceState *dev, Error **errp)
2222 {
2223     Error *local_err = NULL;
2224     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2225 
2226     /*
2227      * When -no-acpi is used with Q35 machine type, no ACPI is built,
2228      * but pcms->acpi_dev is still created. Check !acpi_enabled in
2229      * addition to cover this case.
2230      */
2231     if (!pcms->acpi_dev || !acpi_enabled) {
2232         error_setg(&local_err,
2233                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
2234         goto out;
2235     }
2236 
2237     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
2238         error_setg(&local_err,
2239                    "nvdimm device hot unplug is not supported yet.");
2240         goto out;
2241     }
2242 
2243     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
2244                                    &local_err);
2245 out:
2246     error_propagate(errp, local_err);
2247 }
2248 
2249 static void pc_memory_unplug(HotplugHandler *hotplug_dev,
2250                              DeviceState *dev, Error **errp)
2251 {
2252     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2253     Error *local_err = NULL;
2254 
2255     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
2256     if (local_err) {
2257         goto out;
2258     }
2259 
2260     pc_dimm_unplug(PC_DIMM(dev), MACHINE(pcms));
2261     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
2262  out:
2263     error_propagate(errp, local_err);
2264 }
2265 
2266 static int pc_apic_cmp(const void *a, const void *b)
2267 {
2268    CPUArchId *apic_a = (CPUArchId *)a;
2269    CPUArchId *apic_b = (CPUArchId *)b;
2270 
2271    return apic_a->arch_id - apic_b->arch_id;
2272 }
2273 
2274 /* returns pointer to CPUArchId descriptor that matches CPU's apic_id
2275  * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
2276  * entry corresponding to CPU's apic_id returns NULL.
2277  */
2278 static CPUArchId *pc_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
2279 {
2280     CPUArchId apic_id, *found_cpu;
2281 
2282     apic_id.arch_id = id;
2283     found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
2284         ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
2285         pc_apic_cmp);
2286     if (found_cpu && idx) {
2287         *idx = found_cpu - ms->possible_cpus->cpus;
2288     }
2289     return found_cpu;
2290 }
2291 
2292 static void pc_cpu_plug(HotplugHandler *hotplug_dev,
2293                         DeviceState *dev, Error **errp)
2294 {
2295     CPUArchId *found_cpu;
2296     Error *local_err = NULL;
2297     X86CPU *cpu = X86_CPU(dev);
2298     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2299 
2300     if (pcms->acpi_dev) {
2301         hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
2302         if (local_err) {
2303             goto out;
2304         }
2305     }
2306 
2307     /* increment the number of CPUs */
2308     pcms->boot_cpus++;
2309     if (pcms->rtc) {
2310         rtc_set_cpus_count(pcms->rtc, pcms->boot_cpus);
2311     }
2312     if (pcms->fw_cfg) {
2313         fw_cfg_modify_i16(pcms->fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);
2314     }
2315 
2316     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
2317     found_cpu->cpu = OBJECT(dev);
2318 out:
2319     error_propagate(errp, local_err);
2320 }
2321 static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
2322                                      DeviceState *dev, Error **errp)
2323 {
2324     int idx = -1;
2325     Error *local_err = NULL;
2326     X86CPU *cpu = X86_CPU(dev);
2327     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2328 
2329     if (!pcms->acpi_dev) {
2330         error_setg(&local_err, "CPU hot unplug not supported without ACPI");
2331         goto out;
2332     }
2333 
2334     pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
2335     assert(idx != -1);
2336     if (idx == 0) {
2337         error_setg(&local_err, "Boot CPU is unpluggable");
2338         goto out;
2339     }
2340 
2341     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
2342                                    &local_err);
2343     if (local_err) {
2344         goto out;
2345     }
2346 
2347  out:
2348     error_propagate(errp, local_err);
2349 
2350 }
2351 
2352 static void pc_cpu_unplug_cb(HotplugHandler *hotplug_dev,
2353                              DeviceState *dev, Error **errp)
2354 {
2355     CPUArchId *found_cpu;
2356     Error *local_err = NULL;
2357     X86CPU *cpu = X86_CPU(dev);
2358     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2359 
2360     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
2361     if (local_err) {
2362         goto out;
2363     }
2364 
2365     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
2366     found_cpu->cpu = NULL;
2367     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
2368 
2369     /* decrement the number of CPUs */
2370     pcms->boot_cpus--;
2371     /* Update the number of CPUs in CMOS */
2372     rtc_set_cpus_count(pcms->rtc, pcms->boot_cpus);
2373     fw_cfg_modify_i16(pcms->fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);
2374  out:
2375     error_propagate(errp, local_err);
2376 }
2377 
2378 static void pc_cpu_pre_plug(HotplugHandler *hotplug_dev,
2379                             DeviceState *dev, Error **errp)
2380 {
2381     int idx;
2382     CPUState *cs;
2383     CPUArchId *cpu_slot;
2384     X86CPUTopoInfo topo;
2385     X86CPU *cpu = X86_CPU(dev);
2386     CPUX86State *env = &cpu->env;
2387     MachineState *ms = MACHINE(hotplug_dev);
2388     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
2389     unsigned int smp_cores = ms->smp.cores;
2390     unsigned int smp_threads = ms->smp.threads;
2391 
2392     if(!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
2393         error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
2394                    ms->cpu_type);
2395         return;
2396     }
2397 
2398     env->nr_dies = pcms->smp_dies;
2399 
2400     /*
2401      * If APIC ID is not set,
2402      * set it based on socket/die/core/thread properties.
2403      */
2404     if (cpu->apic_id == UNASSIGNED_APIC_ID) {
2405         int max_socket = (ms->smp.max_cpus - 1) /
2406                                 smp_threads / smp_cores / pcms->smp_dies;
2407 
2408         if (cpu->socket_id < 0) {
2409             error_setg(errp, "CPU socket-id is not set");
2410             return;
2411         } else if (cpu->socket_id > max_socket) {
2412             error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
2413                        cpu->socket_id, max_socket);
2414             return;
2415         } else if (cpu->die_id > pcms->smp_dies - 1) {
2416             error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
2417                        cpu->die_id, max_socket);
2418             return;
2419         }
2420         if (cpu->core_id < 0) {
2421             error_setg(errp, "CPU core-id is not set");
2422             return;
2423         } else if (cpu->core_id > (smp_cores - 1)) {
2424             error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
2425                        cpu->core_id, smp_cores - 1);
2426             return;
2427         }
2428         if (cpu->thread_id < 0) {
2429             error_setg(errp, "CPU thread-id is not set");
2430             return;
2431         } else if (cpu->thread_id > (smp_threads - 1)) {
2432             error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
2433                        cpu->thread_id, smp_threads - 1);
2434             return;
2435         }
2436 
2437         topo.pkg_id = cpu->socket_id;
2438         topo.die_id = cpu->die_id;
2439         topo.core_id = cpu->core_id;
2440         topo.smt_id = cpu->thread_id;
2441         cpu->apic_id = apicid_from_topo_ids(pcms->smp_dies, smp_cores,
2442                                             smp_threads, &topo);
2443     }
2444 
2445     cpu_slot = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
2446     if (!cpu_slot) {
2447         MachineState *ms = MACHINE(pcms);
2448 
2449         x86_topo_ids_from_apicid(cpu->apic_id, pcms->smp_dies,
2450                                  smp_cores, smp_threads, &topo);
2451         error_setg(errp,
2452             "Invalid CPU [socket: %u, die: %u, core: %u, thread: %u] with"
2453             " APIC ID %" PRIu32 ", valid index range 0:%d",
2454             topo.pkg_id, topo.die_id, topo.core_id, topo.smt_id,
2455             cpu->apic_id, ms->possible_cpus->len - 1);
2456         return;
2457     }
2458 
2459     if (cpu_slot->cpu) {
2460         error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
2461                    idx, cpu->apic_id);
2462         return;
2463     }
2464 
2465     /* if 'address' properties socket-id/core-id/thread-id are not set, set them
2466      * so that machine_query_hotpluggable_cpus would show correct values
2467      */
2468     /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
2469      * once -smp refactoring is complete and there will be CPU private
2470      * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
2471     x86_topo_ids_from_apicid(cpu->apic_id, pcms->smp_dies,
2472                              smp_cores, smp_threads, &topo);
2473     if (cpu->socket_id != -1 && cpu->socket_id != topo.pkg_id) {
2474         error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
2475             " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id, topo.pkg_id);
2476         return;
2477     }
2478     cpu->socket_id = topo.pkg_id;
2479 
2480     if (cpu->die_id != -1 && cpu->die_id != topo.die_id) {
2481         error_setg(errp, "property die-id: %u doesn't match set apic-id:"
2482             " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo.die_id);
2483         return;
2484     }
2485     cpu->die_id = topo.die_id;
2486 
2487     if (cpu->core_id != -1 && cpu->core_id != topo.core_id) {
2488         error_setg(errp, "property core-id: %u doesn't match set apic-id:"
2489             " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id, topo.core_id);
2490         return;
2491     }
2492     cpu->core_id = topo.core_id;
2493 
2494     if (cpu->thread_id != -1 && cpu->thread_id != topo.smt_id) {
2495         error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
2496             " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id, topo.smt_id);
2497         return;
2498     }
2499     cpu->thread_id = topo.smt_id;
2500 
2501     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
2502         !kvm_hv_vpindex_settable()) {
2503         error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
2504         return;
2505     }
2506 
2507     cs = CPU(cpu);
2508     cs->cpu_index = idx;
2509 
2510     numa_cpu_pre_plug(cpu_slot, dev, errp);
2511 }
2512 
2513 static void pc_virtio_pmem_pci_pre_plug(HotplugHandler *hotplug_dev,
2514                                         DeviceState *dev, Error **errp)
2515 {
2516     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
2517     Error *local_err = NULL;
2518 
2519     if (!hotplug_dev2) {
2520         /*
2521          * Without a bus hotplug handler, we cannot control the plug/unplug
2522          * order. This should never be the case on x86, however better add
2523          * a safety net.
2524          */
2525         error_setg(errp, "virtio-pmem-pci not supported on this bus.");
2526         return;
2527     }
2528     /*
2529      * First, see if we can plug this memory device at all. If that
2530      * succeeds, branch of to the actual hotplug handler.
2531      */
2532     memory_device_pre_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev), NULL,
2533                            &local_err);
2534     if (!local_err) {
2535         hotplug_handler_pre_plug(hotplug_dev2, dev, &local_err);
2536     }
2537     error_propagate(errp, local_err);
2538 }
2539 
2540 static void pc_virtio_pmem_pci_plug(HotplugHandler *hotplug_dev,
2541                                     DeviceState *dev, Error **errp)
2542 {
2543     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
2544     Error *local_err = NULL;
2545 
2546     /*
2547      * Plug the memory device first and then branch off to the actual
2548      * hotplug handler. If that one fails, we can easily undo the memory
2549      * device bits.
2550      */
2551     memory_device_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
2552     hotplug_handler_plug(hotplug_dev2, dev, &local_err);
2553     if (local_err) {
2554         memory_device_unplug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
2555     }
2556     error_propagate(errp, local_err);
2557 }
2558 
2559 static void pc_virtio_pmem_pci_unplug_request(HotplugHandler *hotplug_dev,
2560                                               DeviceState *dev, Error **errp)
2561 {
2562     /* We don't support virtio pmem hot unplug */
2563     error_setg(errp, "virtio pmem device unplug not supported.");
2564 }
2565 
2566 static void pc_virtio_pmem_pci_unplug(HotplugHandler *hotplug_dev,
2567                                       DeviceState *dev, Error **errp)
2568 {
2569     /* We don't support virtio pmem hot unplug */
2570 }
2571 
2572 static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
2573                                           DeviceState *dev, Error **errp)
2574 {
2575     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2576         pc_memory_pre_plug(hotplug_dev, dev, errp);
2577     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
2578         pc_cpu_pre_plug(hotplug_dev, dev, errp);
2579     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
2580         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
2581     }
2582 }
2583 
2584 static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
2585                                       DeviceState *dev, Error **errp)
2586 {
2587     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2588         pc_memory_plug(hotplug_dev, dev, errp);
2589     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
2590         pc_cpu_plug(hotplug_dev, dev, errp);
2591     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
2592         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
2593     }
2594 }
2595 
2596 static void pc_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
2597                                                 DeviceState *dev, Error **errp)
2598 {
2599     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2600         pc_memory_unplug_request(hotplug_dev, dev, errp);
2601     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
2602         pc_cpu_unplug_request_cb(hotplug_dev, dev, errp);
2603     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
2604         pc_virtio_pmem_pci_unplug_request(hotplug_dev, dev, errp);
2605     } else {
2606         error_setg(errp, "acpi: device unplug request for not supported device"
2607                    " type: %s", object_get_typename(OBJECT(dev)));
2608     }
2609 }
2610 
2611 static void pc_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
2612                                         DeviceState *dev, Error **errp)
2613 {
2614     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2615         pc_memory_unplug(hotplug_dev, dev, errp);
2616     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
2617         pc_cpu_unplug_cb(hotplug_dev, dev, errp);
2618     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
2619         pc_virtio_pmem_pci_unplug(hotplug_dev, dev, errp);
2620     } else {
2621         error_setg(errp, "acpi: device unplug for not supported device"
2622                    " type: %s", object_get_typename(OBJECT(dev)));
2623     }
2624 }
2625 
2626 static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
2627                                              DeviceState *dev)
2628 {
2629     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
2630         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
2631         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
2632         return HOTPLUG_HANDLER(machine);
2633     }
2634 
2635     return NULL;
2636 }
2637 
2638 static void
2639 pc_machine_get_device_memory_region_size(Object *obj, Visitor *v,
2640                                          const char *name, void *opaque,
2641                                          Error **errp)
2642 {
2643     MachineState *ms = MACHINE(obj);
2644     int64_t value = 0;
2645 
2646     if (ms->device_memory) {
2647         value = memory_region_size(&ms->device_memory->mr);
2648     }
2649 
2650     visit_type_int(v, name, &value, errp);
2651 }
2652 
2653 static void pc_machine_get_max_ram_below_4g(Object *obj, Visitor *v,
2654                                             const char *name, void *opaque,
2655                                             Error **errp)
2656 {
2657     PCMachineState *pcms = PC_MACHINE(obj);
2658     uint64_t value = pcms->max_ram_below_4g;
2659 
2660     visit_type_size(v, name, &value, errp);
2661 }
2662 
2663 static void pc_machine_set_max_ram_below_4g(Object *obj, Visitor *v,
2664                                             const char *name, void *opaque,
2665                                             Error **errp)
2666 {
2667     PCMachineState *pcms = PC_MACHINE(obj);
2668     Error *error = NULL;
2669     uint64_t value;
2670 
2671     visit_type_size(v, name, &value, &error);
2672     if (error) {
2673         error_propagate(errp, error);
2674         return;
2675     }
2676     if (value > 4 * GiB) {
2677         error_setg(&error,
2678                    "Machine option 'max-ram-below-4g=%"PRIu64
2679                    "' expects size less than or equal to 4G", value);
2680         error_propagate(errp, error);
2681         return;
2682     }
2683 
2684     if (value < 1 * MiB) {
2685         warn_report("Only %" PRIu64 " bytes of RAM below the 4GiB boundary,"
2686                     "BIOS may not work with less than 1MiB", value);
2687     }
2688 
2689     pcms->max_ram_below_4g = value;
2690 }
2691 
2692 static void pc_machine_get_vmport(Object *obj, Visitor *v, const char *name,
2693                                   void *opaque, Error **errp)
2694 {
2695     PCMachineState *pcms = PC_MACHINE(obj);
2696     OnOffAuto vmport = pcms->vmport;
2697 
2698     visit_type_OnOffAuto(v, name, &vmport, errp);
2699 }
2700 
2701 static void pc_machine_set_vmport(Object *obj, Visitor *v, const char *name,
2702                                   void *opaque, Error **errp)
2703 {
2704     PCMachineState *pcms = PC_MACHINE(obj);
2705 
2706     visit_type_OnOffAuto(v, name, &pcms->vmport, errp);
2707 }
2708 
2709 bool pc_machine_is_smm_enabled(PCMachineState *pcms)
2710 {
2711     bool smm_available = false;
2712 
2713     if (pcms->smm == ON_OFF_AUTO_OFF) {
2714         return false;
2715     }
2716 
2717     if (tcg_enabled() || qtest_enabled()) {
2718         smm_available = true;
2719     } else if (kvm_enabled()) {
2720         smm_available = kvm_has_smm();
2721     }
2722 
2723     if (smm_available) {
2724         return true;
2725     }
2726 
2727     if (pcms->smm == ON_OFF_AUTO_ON) {
2728         error_report("System Management Mode not supported by this hypervisor.");
2729         exit(1);
2730     }
2731     return false;
2732 }
2733 
2734 static void pc_machine_get_smm(Object *obj, Visitor *v, const char *name,
2735                                void *opaque, Error **errp)
2736 {
2737     PCMachineState *pcms = PC_MACHINE(obj);
2738     OnOffAuto smm = pcms->smm;
2739 
2740     visit_type_OnOffAuto(v, name, &smm, errp);
2741 }
2742 
2743 static void pc_machine_set_smm(Object *obj, Visitor *v, const char *name,
2744                                void *opaque, Error **errp)
2745 {
2746     PCMachineState *pcms = PC_MACHINE(obj);
2747 
2748     visit_type_OnOffAuto(v, name, &pcms->smm, errp);
2749 }
2750 
2751 static bool pc_machine_get_smbus(Object *obj, Error **errp)
2752 {
2753     PCMachineState *pcms = PC_MACHINE(obj);
2754 
2755     return pcms->smbus_enabled;
2756 }
2757 
2758 static void pc_machine_set_smbus(Object *obj, bool value, Error **errp)
2759 {
2760     PCMachineState *pcms = PC_MACHINE(obj);
2761 
2762     pcms->smbus_enabled = value;
2763 }
2764 
2765 static bool pc_machine_get_sata(Object *obj, Error **errp)
2766 {
2767     PCMachineState *pcms = PC_MACHINE(obj);
2768 
2769     return pcms->sata_enabled;
2770 }
2771 
2772 static void pc_machine_set_sata(Object *obj, bool value, Error **errp)
2773 {
2774     PCMachineState *pcms = PC_MACHINE(obj);
2775 
2776     pcms->sata_enabled = value;
2777 }
2778 
2779 static bool pc_machine_get_pit(Object *obj, Error **errp)
2780 {
2781     PCMachineState *pcms = PC_MACHINE(obj);
2782 
2783     return pcms->pit_enabled;
2784 }
2785 
2786 static void pc_machine_set_pit(Object *obj, bool value, Error **errp)
2787 {
2788     PCMachineState *pcms = PC_MACHINE(obj);
2789 
2790     pcms->pit_enabled = value;
2791 }
2792 
2793 static void pc_machine_initfn(Object *obj)
2794 {
2795     PCMachineState *pcms = PC_MACHINE(obj);
2796 
2797     pcms->max_ram_below_4g = 0; /* use default */
2798     pcms->smm = ON_OFF_AUTO_AUTO;
2799 #ifdef CONFIG_VMPORT
2800     pcms->vmport = ON_OFF_AUTO_AUTO;
2801 #else
2802     pcms->vmport = ON_OFF_AUTO_OFF;
2803 #endif /* CONFIG_VMPORT */
2804     /* acpi build is enabled by default if machine supports it */
2805     pcms->acpi_build_enabled = PC_MACHINE_GET_CLASS(pcms)->has_acpi_build;
2806     pcms->smbus_enabled = true;
2807     pcms->sata_enabled = true;
2808     pcms->pit_enabled = true;
2809     pcms->smp_dies = 1;
2810 
2811     pc_system_flash_create(pcms);
2812 }
2813 
2814 static void pc_machine_reset(MachineState *machine)
2815 {
2816     CPUState *cs;
2817     X86CPU *cpu;
2818 
2819     qemu_devices_reset();
2820 
2821     /* Reset APIC after devices have been reset to cancel
2822      * any changes that qemu_devices_reset() might have done.
2823      */
2824     CPU_FOREACH(cs) {
2825         cpu = X86_CPU(cs);
2826 
2827         if (cpu->apic_state) {
2828             device_reset(cpu->apic_state);
2829         }
2830     }
2831 }
2832 
2833 static CpuInstanceProperties
2834 pc_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
2835 {
2836     MachineClass *mc = MACHINE_GET_CLASS(ms);
2837     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
2838 
2839     assert(cpu_index < possible_cpus->len);
2840     return possible_cpus->cpus[cpu_index].props;
2841 }
2842 
2843 static int64_t pc_get_default_cpu_node_id(const MachineState *ms, int idx)
2844 {
2845    X86CPUTopoInfo topo;
2846    PCMachineState *pcms = PC_MACHINE(ms);
2847 
2848    assert(idx < ms->possible_cpus->len);
2849    x86_topo_ids_from_apicid(ms->possible_cpus->cpus[idx].arch_id,
2850                             pcms->smp_dies, ms->smp.cores,
2851                             ms->smp.threads, &topo);
2852    return topo.pkg_id % nb_numa_nodes;
2853 }
2854 
2855 static const CPUArchIdList *pc_possible_cpu_arch_ids(MachineState *ms)
2856 {
2857     PCMachineState *pcms = PC_MACHINE(ms);
2858     int i;
2859     unsigned int max_cpus = ms->smp.max_cpus;
2860 
2861     if (ms->possible_cpus) {
2862         /*
2863          * make sure that max_cpus hasn't changed since the first use, i.e.
2864          * -smp hasn't been parsed after it
2865         */
2866         assert(ms->possible_cpus->len == max_cpus);
2867         return ms->possible_cpus;
2868     }
2869 
2870     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
2871                                   sizeof(CPUArchId) * max_cpus);
2872     ms->possible_cpus->len = max_cpus;
2873     for (i = 0; i < ms->possible_cpus->len; i++) {
2874         X86CPUTopoInfo topo;
2875 
2876         ms->possible_cpus->cpus[i].type = ms->cpu_type;
2877         ms->possible_cpus->cpus[i].vcpus_count = 1;
2878         ms->possible_cpus->cpus[i].arch_id = x86_cpu_apic_id_from_index(pcms, i);
2879         x86_topo_ids_from_apicid(ms->possible_cpus->cpus[i].arch_id,
2880                                  pcms->smp_dies, ms->smp.cores,
2881                                  ms->smp.threads, &topo);
2882         ms->possible_cpus->cpus[i].props.has_socket_id = true;
2883         ms->possible_cpus->cpus[i].props.socket_id = topo.pkg_id;
2884         ms->possible_cpus->cpus[i].props.has_die_id = true;
2885         ms->possible_cpus->cpus[i].props.die_id = topo.die_id;
2886         ms->possible_cpus->cpus[i].props.has_core_id = true;
2887         ms->possible_cpus->cpus[i].props.core_id = topo.core_id;
2888         ms->possible_cpus->cpus[i].props.has_thread_id = true;
2889         ms->possible_cpus->cpus[i].props.thread_id = topo.smt_id;
2890     }
2891     return ms->possible_cpus;
2892 }
2893 
2894 static void x86_nmi(NMIState *n, int cpu_index, Error **errp)
2895 {
2896     /* cpu index isn't used */
2897     CPUState *cs;
2898 
2899     CPU_FOREACH(cs) {
2900         X86CPU *cpu = X86_CPU(cs);
2901 
2902         if (!cpu->apic_state) {
2903             cpu_interrupt(cs, CPU_INTERRUPT_NMI);
2904         } else {
2905             apic_deliver_nmi(cpu->apic_state);
2906         }
2907     }
2908 }
2909 
2910 static void pc_machine_class_init(ObjectClass *oc, void *data)
2911 {
2912     MachineClass *mc = MACHINE_CLASS(oc);
2913     PCMachineClass *pcmc = PC_MACHINE_CLASS(oc);
2914     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
2915     NMIClass *nc = NMI_CLASS(oc);
2916 
2917     pcmc->pci_enabled = true;
2918     pcmc->has_acpi_build = true;
2919     pcmc->rsdp_in_ram = true;
2920     pcmc->smbios_defaults = true;
2921     pcmc->smbios_uuid_encoded = true;
2922     pcmc->gigabyte_align = true;
2923     pcmc->has_reserved_memory = true;
2924     pcmc->kvmclock_enabled = true;
2925     pcmc->enforce_aligned_dimm = true;
2926     /* BIOS ACPI tables: 128K. Other BIOS datastructures: less than 4K reported
2927      * to be used at the moment, 32K should be enough for a while.  */
2928     pcmc->acpi_data_size = 0x20000 + 0x8000;
2929     pcmc->save_tsc_khz = true;
2930     pcmc->linuxboot_dma_enabled = true;
2931     pcmc->pvh_enabled = true;
2932     assert(!mc->get_hotplug_handler);
2933     mc->get_hotplug_handler = pc_get_hotplug_handler;
2934     mc->cpu_index_to_instance_props = pc_cpu_index_to_props;
2935     mc->get_default_cpu_node_id = pc_get_default_cpu_node_id;
2936     mc->possible_cpu_arch_ids = pc_possible_cpu_arch_ids;
2937     mc->auto_enable_numa_with_memhp = true;
2938     mc->has_hotpluggable_cpus = true;
2939     mc->default_boot_order = "cad";
2940     mc->hot_add_cpu = pc_hot_add_cpu;
2941     mc->smp_parse = pc_smp_parse;
2942     mc->block_default_type = IF_IDE;
2943     mc->max_cpus = 255;
2944     mc->reset = pc_machine_reset;
2945     hc->pre_plug = pc_machine_device_pre_plug_cb;
2946     hc->plug = pc_machine_device_plug_cb;
2947     hc->unplug_request = pc_machine_device_unplug_request_cb;
2948     hc->unplug = pc_machine_device_unplug_cb;
2949     nc->nmi_monitor_handler = x86_nmi;
2950     mc->default_cpu_type = TARGET_DEFAULT_CPU_TYPE;
2951     mc->nvdimm_supported = true;
2952     mc->numa_mem_supported = true;
2953 
2954     object_class_property_add(oc, PC_MACHINE_DEVMEM_REGION_SIZE, "int",
2955         pc_machine_get_device_memory_region_size, NULL,
2956         NULL, NULL, &error_abort);
2957 
2958     object_class_property_add(oc, PC_MACHINE_MAX_RAM_BELOW_4G, "size",
2959         pc_machine_get_max_ram_below_4g, pc_machine_set_max_ram_below_4g,
2960         NULL, NULL, &error_abort);
2961 
2962     object_class_property_set_description(oc, PC_MACHINE_MAX_RAM_BELOW_4G,
2963         "Maximum ram below the 4G boundary (32bit boundary)", &error_abort);
2964 
2965     object_class_property_add(oc, PC_MACHINE_SMM, "OnOffAuto",
2966         pc_machine_get_smm, pc_machine_set_smm,
2967         NULL, NULL, &error_abort);
2968     object_class_property_set_description(oc, PC_MACHINE_SMM,
2969         "Enable SMM (pc & q35)", &error_abort);
2970 
2971     object_class_property_add(oc, PC_MACHINE_VMPORT, "OnOffAuto",
2972         pc_machine_get_vmport, pc_machine_set_vmport,
2973         NULL, NULL, &error_abort);
2974     object_class_property_set_description(oc, PC_MACHINE_VMPORT,
2975         "Enable vmport (pc & q35)", &error_abort);
2976 
2977     object_class_property_add_bool(oc, PC_MACHINE_SMBUS,
2978         pc_machine_get_smbus, pc_machine_set_smbus, &error_abort);
2979 
2980     object_class_property_add_bool(oc, PC_MACHINE_SATA,
2981         pc_machine_get_sata, pc_machine_set_sata, &error_abort);
2982 
2983     object_class_property_add_bool(oc, PC_MACHINE_PIT,
2984         pc_machine_get_pit, pc_machine_set_pit, &error_abort);
2985 }
2986 
2987 static const TypeInfo pc_machine_info = {
2988     .name = TYPE_PC_MACHINE,
2989     .parent = TYPE_MACHINE,
2990     .abstract = true,
2991     .instance_size = sizeof(PCMachineState),
2992     .instance_init = pc_machine_initfn,
2993     .class_size = sizeof(PCMachineClass),
2994     .class_init = pc_machine_class_init,
2995     .interfaces = (InterfaceInfo[]) {
2996          { TYPE_HOTPLUG_HANDLER },
2997          { TYPE_NMI },
2998          { }
2999     },
3000 };
3001 
3002 static void pc_machine_register_types(void)
3003 {
3004     type_register_static(&pc_machine_info);
3005 }
3006 
3007 type_init(pc_machine_register_types)
3008