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