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