xref: /openbmc/qemu/hw/i386/pc.c (revision a976ed3f)
1 /*
2  * QEMU PC System Emulator
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include "hw/i386/x86.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 "migration/vmstate.h"
45 #include "multiboot.h"
46 #include "hw/rtc/mc146818rtc.h"
47 #include "hw/intc/i8259.h"
48 #include "hw/dma/i8257.h"
49 #include "hw/timer/i8254.h"
50 #include "hw/input/i8042.h"
51 #include "hw/irq.h"
52 #include "hw/audio/pcspk.h"
53 #include "hw/pci/msi.h"
54 #include "hw/sysbus.h"
55 #include "sysemu/sysemu.h"
56 #include "sysemu/tcg.h"
57 #include "sysemu/numa.h"
58 #include "sysemu/kvm.h"
59 #include "sysemu/qtest.h"
60 #include "sysemu/reset.h"
61 #include "sysemu/runstate.h"
62 #include "kvm_i386.h"
63 #include "hw/xen/xen.h"
64 #include "hw/xen/start_info.h"
65 #include "ui/qemu-spice.h"
66 #include "exec/memory.h"
67 #include "exec/address-spaces.h"
68 #include "sysemu/arch_init.h"
69 #include "qemu/bitmap.h"
70 #include "qemu/config-file.h"
71 #include "qemu/error-report.h"
72 #include "qemu/option.h"
73 #include "qemu/cutils.h"
74 #include "hw/acpi/acpi.h"
75 #include "hw/acpi/cpu_hotplug.h"
76 #include "hw/boards.h"
77 #include "acpi-build.h"
78 #include "hw/mem/pc-dimm.h"
79 #include "hw/mem/nvdimm.h"
80 #include "qapi/error.h"
81 #include "qapi/qapi-visit-common.h"
82 #include "qapi/visitor.h"
83 #include "hw/core/cpu.h"
84 #include "hw/usb.h"
85 #include "hw/i386/intel_iommu.h"
86 #include "hw/net/ne2000-isa.h"
87 #include "standard-headers/asm-x86/bootparam.h"
88 #include "hw/virtio/virtio-pmem-pci.h"
89 #include "hw/mem/memory-device.h"
90 #include "sysemu/replay.h"
91 #include "qapi/qmp/qerror.h"
92 #include "config-devices.h"
93 #include "e820_memory_layout.h"
94 #include "vmport.h"
95 #include "fw_cfg.h"
96 #include "trace.h"
97 
98 GlobalProperty pc_compat_4_2[] = {
99     { "mch", "smbase-smram", "off" },
100 };
101 const size_t pc_compat_4_2_len = G_N_ELEMENTS(pc_compat_4_2);
102 
103 GlobalProperty pc_compat_4_1[] = {};
104 const size_t pc_compat_4_1_len = G_N_ELEMENTS(pc_compat_4_1);
105 
106 GlobalProperty pc_compat_4_0[] = {};
107 const size_t pc_compat_4_0_len = G_N_ELEMENTS(pc_compat_4_0);
108 
109 GlobalProperty pc_compat_3_1[] = {
110     { "intel-iommu", "dma-drain", "off" },
111     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "off" },
112     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "off" },
113     { "Opteron_G4" "-" TYPE_X86_CPU, "npt", "off" },
114     { "Opteron_G4" "-" TYPE_X86_CPU, "nrip-save", "off" },
115     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "off" },
116     { "Opteron_G5" "-" TYPE_X86_CPU, "npt", "off" },
117     { "Opteron_G5" "-" TYPE_X86_CPU, "nrip-save", "off" },
118     { "EPYC" "-" TYPE_X86_CPU, "npt", "off" },
119     { "EPYC" "-" TYPE_X86_CPU, "nrip-save", "off" },
120     { "EPYC-IBPB" "-" TYPE_X86_CPU, "npt", "off" },
121     { "EPYC-IBPB" "-" TYPE_X86_CPU, "nrip-save", "off" },
122     { "Skylake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
123     { "Skylake-Client-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
124     { "Skylake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
125     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
126     { "Cascadelake-Server" "-" TYPE_X86_CPU,  "mpx", "on" },
127     { "Icelake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
128     { "Icelake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
129     { "Cascadelake-Server" "-" TYPE_X86_CPU, "stepping", "5" },
130     { TYPE_X86_CPU, "x-intel-pt-auto-level", "off" },
131 };
132 const size_t pc_compat_3_1_len = G_N_ELEMENTS(pc_compat_3_1);
133 
134 GlobalProperty pc_compat_3_0[] = {
135     { TYPE_X86_CPU, "x-hv-synic-kvm-only", "on" },
136     { "Skylake-Server" "-" TYPE_X86_CPU, "pku", "off" },
137     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "pku", "off" },
138 };
139 const size_t pc_compat_3_0_len = G_N_ELEMENTS(pc_compat_3_0);
140 
141 GlobalProperty pc_compat_2_12[] = {
142     { TYPE_X86_CPU, "legacy-cache", "on" },
143     { TYPE_X86_CPU, "topoext", "off" },
144     { "EPYC-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
145     { "EPYC-IBPB-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
146 };
147 const size_t pc_compat_2_12_len = G_N_ELEMENTS(pc_compat_2_12);
148 
149 GlobalProperty pc_compat_2_11[] = {
150     { TYPE_X86_CPU, "x-migrate-smi-count", "off" },
151     { "Skylake-Server" "-" TYPE_X86_CPU, "clflushopt", "off" },
152 };
153 const size_t pc_compat_2_11_len = G_N_ELEMENTS(pc_compat_2_11);
154 
155 GlobalProperty pc_compat_2_10[] = {
156     { TYPE_X86_CPU, "x-hv-max-vps", "0x40" },
157     { "i440FX-pcihost", "x-pci-hole64-fix", "off" },
158     { "q35-pcihost", "x-pci-hole64-fix", "off" },
159 };
160 const size_t pc_compat_2_10_len = G_N_ELEMENTS(pc_compat_2_10);
161 
162 GlobalProperty pc_compat_2_9[] = {
163     { "mch", "extended-tseg-mbytes", "0" },
164 };
165 const size_t pc_compat_2_9_len = G_N_ELEMENTS(pc_compat_2_9);
166 
167 GlobalProperty pc_compat_2_8[] = {
168     { TYPE_X86_CPU, "tcg-cpuid", "off" },
169     { "kvmclock", "x-mach-use-reliable-get-clock", "off" },
170     { "ICH9-LPC", "x-smi-broadcast", "off" },
171     { TYPE_X86_CPU, "vmware-cpuid-freq", "off" },
172     { "Haswell-" TYPE_X86_CPU, "stepping", "1" },
173 };
174 const size_t pc_compat_2_8_len = G_N_ELEMENTS(pc_compat_2_8);
175 
176 GlobalProperty pc_compat_2_7[] = {
177     { TYPE_X86_CPU, "l3-cache", "off" },
178     { TYPE_X86_CPU, "full-cpuid-auto-level", "off" },
179     { "Opteron_G3" "-" TYPE_X86_CPU, "family", "15" },
180     { "Opteron_G3" "-" TYPE_X86_CPU, "model", "6" },
181     { "Opteron_G3" "-" TYPE_X86_CPU, "stepping", "1" },
182     { "isa-pcspk", "migrate", "off" },
183 };
184 const size_t pc_compat_2_7_len = G_N_ELEMENTS(pc_compat_2_7);
185 
186 GlobalProperty pc_compat_2_6[] = {
187     { TYPE_X86_CPU, "cpuid-0xb", "off" },
188     { "vmxnet3", "romfile", "" },
189     { TYPE_X86_CPU, "fill-mtrr-mask", "off" },
190     { "apic-common", "legacy-instance-id", "on", }
191 };
192 const size_t pc_compat_2_6_len = G_N_ELEMENTS(pc_compat_2_6);
193 
194 GlobalProperty pc_compat_2_5[] = {};
195 const size_t pc_compat_2_5_len = G_N_ELEMENTS(pc_compat_2_5);
196 
197 GlobalProperty pc_compat_2_4[] = {
198     PC_CPU_MODEL_IDS("2.4.0")
199     { "Haswell-" TYPE_X86_CPU, "abm", "off" },
200     { "Haswell-noTSX-" TYPE_X86_CPU, "abm", "off" },
201     { "Broadwell-" TYPE_X86_CPU, "abm", "off" },
202     { "Broadwell-noTSX-" TYPE_X86_CPU, "abm", "off" },
203     { "host" "-" TYPE_X86_CPU, "host-cache-info", "on" },
204     { TYPE_X86_CPU, "check", "off" },
205     { "qemu64" "-" TYPE_X86_CPU, "sse4a", "on" },
206     { "qemu64" "-" TYPE_X86_CPU, "abm", "on" },
207     { "qemu64" "-" TYPE_X86_CPU, "popcnt", "on" },
208     { "qemu32" "-" TYPE_X86_CPU, "popcnt", "on" },
209     { "Opteron_G2" "-" TYPE_X86_CPU, "rdtscp", "on" },
210     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "on" },
211     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "on" },
212     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "on", }
213 };
214 const size_t pc_compat_2_4_len = G_N_ELEMENTS(pc_compat_2_4);
215 
216 GlobalProperty pc_compat_2_3[] = {
217     PC_CPU_MODEL_IDS("2.3.0")
218     { TYPE_X86_CPU, "arat", "off" },
219     { "qemu64" "-" TYPE_X86_CPU, "min-level", "4" },
220     { "kvm64" "-" TYPE_X86_CPU, "min-level", "5" },
221     { "pentium3" "-" TYPE_X86_CPU, "min-level", "2" },
222     { "n270" "-" TYPE_X86_CPU, "min-level", "5" },
223     { "Conroe" "-" TYPE_X86_CPU, "min-level", "4" },
224     { "Penryn" "-" TYPE_X86_CPU, "min-level", "4" },
225     { "Nehalem" "-" TYPE_X86_CPU, "min-level", "4" },
226     { "n270" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
227     { "Penryn" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
228     { "Conroe" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
229     { "Nehalem" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
230     { "Westmere" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
231     { "SandyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
232     { "IvyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
233     { "Haswell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
234     { "Haswell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
235     { "Broadwell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
236     { "Broadwell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
237     { TYPE_X86_CPU, "kvm-no-smi-migration", "on" },
238 };
239 const size_t pc_compat_2_3_len = G_N_ELEMENTS(pc_compat_2_3);
240 
241 GlobalProperty pc_compat_2_2[] = {
242     PC_CPU_MODEL_IDS("2.2.0")
243     { "kvm64" "-" TYPE_X86_CPU, "vme", "off" },
244     { "kvm32" "-" TYPE_X86_CPU, "vme", "off" },
245     { "Conroe" "-" TYPE_X86_CPU, "vme", "off" },
246     { "Penryn" "-" TYPE_X86_CPU, "vme", "off" },
247     { "Nehalem" "-" TYPE_X86_CPU, "vme", "off" },
248     { "Westmere" "-" TYPE_X86_CPU, "vme", "off" },
249     { "SandyBridge" "-" TYPE_X86_CPU, "vme", "off" },
250     { "Haswell" "-" TYPE_X86_CPU, "vme", "off" },
251     { "Broadwell" "-" TYPE_X86_CPU, "vme", "off" },
252     { "Opteron_G1" "-" TYPE_X86_CPU, "vme", "off" },
253     { "Opteron_G2" "-" TYPE_X86_CPU, "vme", "off" },
254     { "Opteron_G3" "-" TYPE_X86_CPU, "vme", "off" },
255     { "Opteron_G4" "-" TYPE_X86_CPU, "vme", "off" },
256     { "Opteron_G5" "-" TYPE_X86_CPU, "vme", "off" },
257     { "Haswell" "-" TYPE_X86_CPU, "f16c", "off" },
258     { "Haswell" "-" TYPE_X86_CPU, "rdrand", "off" },
259     { "Broadwell" "-" TYPE_X86_CPU, "f16c", "off" },
260     { "Broadwell" "-" TYPE_X86_CPU, "rdrand", "off" },
261 };
262 const size_t pc_compat_2_2_len = G_N_ELEMENTS(pc_compat_2_2);
263 
264 GlobalProperty pc_compat_2_1[] = {
265     PC_CPU_MODEL_IDS("2.1.0")
266     { "coreduo" "-" TYPE_X86_CPU, "vmx", "on" },
267     { "core2duo" "-" TYPE_X86_CPU, "vmx", "on" },
268 };
269 const size_t pc_compat_2_1_len = G_N_ELEMENTS(pc_compat_2_1);
270 
271 GlobalProperty pc_compat_2_0[] = {
272     PC_CPU_MODEL_IDS("2.0.0")
273     { "virtio-scsi-pci", "any_layout", "off" },
274     { "PIIX4_PM", "memory-hotplug-support", "off" },
275     { "apic", "version", "0x11" },
276     { "nec-usb-xhci", "superspeed-ports-first", "off" },
277     { "nec-usb-xhci", "force-pcie-endcap", "on" },
278     { "pci-serial", "prog_if", "0" },
279     { "pci-serial-2x", "prog_if", "0" },
280     { "pci-serial-4x", "prog_if", "0" },
281     { "virtio-net-pci", "guest_announce", "off" },
282     { "ICH9-LPC", "memory-hotplug-support", "off" },
283     { "xio3130-downstream", COMPAT_PROP_PCP, "off" },
284     { "ioh3420", COMPAT_PROP_PCP, "off" },
285 };
286 const size_t pc_compat_2_0_len = G_N_ELEMENTS(pc_compat_2_0);
287 
288 GlobalProperty pc_compat_1_7[] = {
289     PC_CPU_MODEL_IDS("1.7.0")
290     { TYPE_USB_DEVICE, "msos-desc", "no" },
291     { "PIIX4_PM", "acpi-pci-hotplug-with-bridge-support", "off" },
292     { "hpet", HPET_INTCAP, "4" },
293 };
294 const size_t pc_compat_1_7_len = G_N_ELEMENTS(pc_compat_1_7);
295 
296 GlobalProperty pc_compat_1_6[] = {
297     PC_CPU_MODEL_IDS("1.6.0")
298     { "e1000", "mitigation", "off" },
299     { "qemu64-" TYPE_X86_CPU, "model", "2" },
300     { "qemu32-" TYPE_X86_CPU, "model", "3" },
301     { "i440FX-pcihost", "short_root_bus", "1" },
302     { "q35-pcihost", "short_root_bus", "1" },
303 };
304 const size_t pc_compat_1_6_len = G_N_ELEMENTS(pc_compat_1_6);
305 
306 GlobalProperty pc_compat_1_5[] = {
307     PC_CPU_MODEL_IDS("1.5.0")
308     { "Conroe-" TYPE_X86_CPU, "model", "2" },
309     { "Conroe-" TYPE_X86_CPU, "min-level", "2" },
310     { "Penryn-" TYPE_X86_CPU, "model", "2" },
311     { "Penryn-" TYPE_X86_CPU, "min-level", "2" },
312     { "Nehalem-" TYPE_X86_CPU, "model", "2" },
313     { "Nehalem-" TYPE_X86_CPU, "min-level", "2" },
314     { "virtio-net-pci", "any_layout", "off" },
315     { TYPE_X86_CPU, "pmu", "on" },
316     { "i440FX-pcihost", "short_root_bus", "0" },
317     { "q35-pcihost", "short_root_bus", "0" },
318 };
319 const size_t pc_compat_1_5_len = G_N_ELEMENTS(pc_compat_1_5);
320 
321 GlobalProperty pc_compat_1_4[] = {
322     PC_CPU_MODEL_IDS("1.4.0")
323     { "scsi-hd", "discard_granularity", "0" },
324     { "scsi-cd", "discard_granularity", "0" },
325     { "scsi-disk", "discard_granularity", "0" },
326     { "ide-hd", "discard_granularity", "0" },
327     { "ide-cd", "discard_granularity", "0" },
328     { "ide-drive", "discard_granularity", "0" },
329     { "virtio-blk-pci", "discard_granularity", "0" },
330     /* DEV_NVECTORS_UNSPECIFIED as a uint32_t string: */
331     { "virtio-serial-pci", "vectors", "0xFFFFFFFF" },
332     { "virtio-net-pci", "ctrl_guest_offloads", "off" },
333     { "e1000", "romfile", "pxe-e1000.rom" },
334     { "ne2k_pci", "romfile", "pxe-ne2k_pci.rom" },
335     { "pcnet", "romfile", "pxe-pcnet.rom" },
336     { "rtl8139", "romfile", "pxe-rtl8139.rom" },
337     { "virtio-net-pci", "romfile", "pxe-virtio.rom" },
338     { "486-" TYPE_X86_CPU, "model", "0" },
339     { "n270" "-" TYPE_X86_CPU, "movbe", "off" },
340     { "Westmere" "-" TYPE_X86_CPU, "pclmulqdq", "off" },
341 };
342 const size_t pc_compat_1_4_len = G_N_ELEMENTS(pc_compat_1_4);
343 
344 GSIState *pc_gsi_create(qemu_irq **irqs, bool pci_enabled)
345 {
346     GSIState *s;
347 
348     s = g_new0(GSIState, 1);
349     if (kvm_ioapic_in_kernel()) {
350         kvm_pc_setup_irq_routing(pci_enabled);
351     }
352     *irqs = qemu_allocate_irqs(gsi_handler, s, GSI_NUM_PINS);
353 
354     return s;
355 }
356 
357 static void ioport80_write(void *opaque, hwaddr addr, uint64_t data,
358                            unsigned size)
359 {
360 }
361 
362 static uint64_t ioport80_read(void *opaque, hwaddr addr, unsigned size)
363 {
364     return 0xffffffffffffffffULL;
365 }
366 
367 /* MSDOS compatibility mode FPU exception support */
368 static void ioportF0_write(void *opaque, hwaddr addr, uint64_t data,
369                            unsigned size)
370 {
371     if (tcg_enabled()) {
372         cpu_set_ignne();
373     }
374 }
375 
376 static uint64_t ioportF0_read(void *opaque, hwaddr addr, unsigned size)
377 {
378     return 0xffffffffffffffffULL;
379 }
380 
381 /* PC cmos mappings */
382 
383 #define REG_EQUIPMENT_BYTE          0x14
384 
385 int cmos_get_fd_drive_type(FloppyDriveType fd0)
386 {
387     int val;
388 
389     switch (fd0) {
390     case FLOPPY_DRIVE_TYPE_144:
391         /* 1.44 Mb 3"5 drive */
392         val = 4;
393         break;
394     case FLOPPY_DRIVE_TYPE_288:
395         /* 2.88 Mb 3"5 drive */
396         val = 5;
397         break;
398     case FLOPPY_DRIVE_TYPE_120:
399         /* 1.2 Mb 5"5 drive */
400         val = 2;
401         break;
402     case FLOPPY_DRIVE_TYPE_NONE:
403     default:
404         val = 0;
405         break;
406     }
407     return val;
408 }
409 
410 static void cmos_init_hd(ISADevice *s, int type_ofs, int info_ofs,
411                          int16_t cylinders, int8_t heads, int8_t sectors)
412 {
413     rtc_set_memory(s, type_ofs, 47);
414     rtc_set_memory(s, info_ofs, cylinders);
415     rtc_set_memory(s, info_ofs + 1, cylinders >> 8);
416     rtc_set_memory(s, info_ofs + 2, heads);
417     rtc_set_memory(s, info_ofs + 3, 0xff);
418     rtc_set_memory(s, info_ofs + 4, 0xff);
419     rtc_set_memory(s, info_ofs + 5, 0xc0 | ((heads > 8) << 3));
420     rtc_set_memory(s, info_ofs + 6, cylinders);
421     rtc_set_memory(s, info_ofs + 7, cylinders >> 8);
422     rtc_set_memory(s, info_ofs + 8, sectors);
423 }
424 
425 /* convert boot_device letter to something recognizable by the bios */
426 static int boot_device2nibble(char boot_device)
427 {
428     switch(boot_device) {
429     case 'a':
430     case 'b':
431         return 0x01; /* floppy boot */
432     case 'c':
433         return 0x02; /* hard drive boot */
434     case 'd':
435         return 0x03; /* CD-ROM boot */
436     case 'n':
437         return 0x04; /* Network boot */
438     }
439     return 0;
440 }
441 
442 static void set_boot_dev(ISADevice *s, const char *boot_device, Error **errp)
443 {
444 #define PC_MAX_BOOT_DEVICES 3
445     int nbds, bds[3] = { 0, };
446     int i;
447 
448     nbds = strlen(boot_device);
449     if (nbds > PC_MAX_BOOT_DEVICES) {
450         error_setg(errp, "Too many boot devices for PC");
451         return;
452     }
453     for (i = 0; i < nbds; i++) {
454         bds[i] = boot_device2nibble(boot_device[i]);
455         if (bds[i] == 0) {
456             error_setg(errp, "Invalid boot device for PC: '%c'",
457                        boot_device[i]);
458             return;
459         }
460     }
461     rtc_set_memory(s, 0x3d, (bds[1] << 4) | bds[0]);
462     rtc_set_memory(s, 0x38, (bds[2] << 4) | (fd_bootchk ? 0x0 : 0x1));
463 }
464 
465 static void pc_boot_set(void *opaque, const char *boot_device, Error **errp)
466 {
467     set_boot_dev(opaque, boot_device, errp);
468 }
469 
470 static void pc_cmos_init_floppy(ISADevice *rtc_state, ISADevice *floppy)
471 {
472     int val, nb, i;
473     FloppyDriveType fd_type[2] = { FLOPPY_DRIVE_TYPE_NONE,
474                                    FLOPPY_DRIVE_TYPE_NONE };
475 
476     /* floppy type */
477     if (floppy) {
478         for (i = 0; i < 2; i++) {
479             fd_type[i] = isa_fdc_get_drive_type(floppy, i);
480         }
481     }
482     val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |
483         cmos_get_fd_drive_type(fd_type[1]);
484     rtc_set_memory(rtc_state, 0x10, val);
485 
486     val = rtc_get_memory(rtc_state, REG_EQUIPMENT_BYTE);
487     nb = 0;
488     if (fd_type[0] != FLOPPY_DRIVE_TYPE_NONE) {
489         nb++;
490     }
491     if (fd_type[1] != FLOPPY_DRIVE_TYPE_NONE) {
492         nb++;
493     }
494     switch (nb) {
495     case 0:
496         break;
497     case 1:
498         val |= 0x01; /* 1 drive, ready for boot */
499         break;
500     case 2:
501         val |= 0x41; /* 2 drives, ready for boot */
502         break;
503     }
504     rtc_set_memory(rtc_state, REG_EQUIPMENT_BYTE, val);
505 }
506 
507 typedef struct pc_cmos_init_late_arg {
508     ISADevice *rtc_state;
509     BusState *idebus[2];
510 } pc_cmos_init_late_arg;
511 
512 typedef struct check_fdc_state {
513     ISADevice *floppy;
514     bool multiple;
515 } CheckFdcState;
516 
517 static int check_fdc(Object *obj, void *opaque)
518 {
519     CheckFdcState *state = opaque;
520     Object *fdc;
521     uint32_t iobase;
522     Error *local_err = NULL;
523 
524     fdc = object_dynamic_cast(obj, TYPE_ISA_FDC);
525     if (!fdc) {
526         return 0;
527     }
528 
529     iobase = object_property_get_uint(obj, "iobase", &local_err);
530     if (local_err || iobase != 0x3f0) {
531         error_free(local_err);
532         return 0;
533     }
534 
535     if (state->floppy) {
536         state->multiple = true;
537     } else {
538         state->floppy = ISA_DEVICE(obj);
539     }
540     return 0;
541 }
542 
543 static const char * const fdc_container_path[] = {
544     "/unattached", "/peripheral", "/peripheral-anon"
545 };
546 
547 /*
548  * Locate the FDC at IO address 0x3f0, in order to configure the CMOS registers
549  * and ACPI objects.
550  */
551 ISADevice *pc_find_fdc0(void)
552 {
553     int i;
554     Object *container;
555     CheckFdcState state = { 0 };
556 
557     for (i = 0; i < ARRAY_SIZE(fdc_container_path); i++) {
558         container = container_get(qdev_get_machine(), fdc_container_path[i]);
559         object_child_foreach(container, check_fdc, &state);
560     }
561 
562     if (state.multiple) {
563         warn_report("multiple floppy disk controllers with "
564                     "iobase=0x3f0 have been found");
565         error_printf("the one being picked for CMOS setup might not reflect "
566                      "your intent");
567     }
568 
569     return state.floppy;
570 }
571 
572 static void pc_cmos_init_late(void *opaque)
573 {
574     pc_cmos_init_late_arg *arg = opaque;
575     ISADevice *s = arg->rtc_state;
576     int16_t cylinders;
577     int8_t heads, sectors;
578     int val;
579     int i, trans;
580 
581     val = 0;
582     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 0,
583                                            &cylinders, &heads, &sectors) >= 0) {
584         cmos_init_hd(s, 0x19, 0x1b, cylinders, heads, sectors);
585         val |= 0xf0;
586     }
587     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 1,
588                                            &cylinders, &heads, &sectors) >= 0) {
589         cmos_init_hd(s, 0x1a, 0x24, cylinders, heads, sectors);
590         val |= 0x0f;
591     }
592     rtc_set_memory(s, 0x12, val);
593 
594     val = 0;
595     for (i = 0; i < 4; i++) {
596         /* NOTE: ide_get_geometry() returns the physical
597            geometry.  It is always such that: 1 <= sects <= 63, 1
598            <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
599            geometry can be different if a translation is done. */
600         if (arg->idebus[i / 2] &&
601             ide_get_geometry(arg->idebus[i / 2], i % 2,
602                              &cylinders, &heads, &sectors) >= 0) {
603             trans = ide_get_bios_chs_trans(arg->idebus[i / 2], i % 2) - 1;
604             assert((trans & ~3) == 0);
605             val |= trans << (i * 2);
606         }
607     }
608     rtc_set_memory(s, 0x39, val);
609 
610     pc_cmos_init_floppy(s, pc_find_fdc0());
611 
612     qemu_unregister_reset(pc_cmos_init_late, opaque);
613 }
614 
615 void pc_cmos_init(PCMachineState *pcms,
616                   BusState *idebus0, BusState *idebus1,
617                   ISADevice *s)
618 {
619     int val;
620     static pc_cmos_init_late_arg arg;
621     X86MachineState *x86ms = X86_MACHINE(pcms);
622 
623     /* various important CMOS locations needed by PC/Bochs bios */
624 
625     /* memory size */
626     /* base memory (first MiB) */
627     val = MIN(x86ms->below_4g_mem_size / KiB, 640);
628     rtc_set_memory(s, 0x15, val);
629     rtc_set_memory(s, 0x16, val >> 8);
630     /* extended memory (next 64MiB) */
631     if (x86ms->below_4g_mem_size > 1 * MiB) {
632         val = (x86ms->below_4g_mem_size - 1 * MiB) / KiB;
633     } else {
634         val = 0;
635     }
636     if (val > 65535)
637         val = 65535;
638     rtc_set_memory(s, 0x17, val);
639     rtc_set_memory(s, 0x18, val >> 8);
640     rtc_set_memory(s, 0x30, val);
641     rtc_set_memory(s, 0x31, val >> 8);
642     /* memory between 16MiB and 4GiB */
643     if (x86ms->below_4g_mem_size > 16 * MiB) {
644         val = (x86ms->below_4g_mem_size - 16 * MiB) / (64 * KiB);
645     } else {
646         val = 0;
647     }
648     if (val > 65535)
649         val = 65535;
650     rtc_set_memory(s, 0x34, val);
651     rtc_set_memory(s, 0x35, val >> 8);
652     /* memory above 4GiB */
653     val = x86ms->above_4g_mem_size / 65536;
654     rtc_set_memory(s, 0x5b, val);
655     rtc_set_memory(s, 0x5c, val >> 8);
656     rtc_set_memory(s, 0x5d, val >> 16);
657 
658     object_property_add_link(OBJECT(pcms), "rtc_state",
659                              TYPE_ISA_DEVICE,
660                              (Object **)&x86ms->rtc,
661                              object_property_allow_set_link,
662                              OBJ_PROP_LINK_STRONG, &error_abort);
663     object_property_set_link(OBJECT(pcms), OBJECT(s),
664                              "rtc_state", &error_abort);
665 
666     set_boot_dev(s, MACHINE(pcms)->boot_order, &error_fatal);
667 
668     val = 0;
669     val |= 0x02; /* FPU is there */
670     val |= 0x04; /* PS/2 mouse installed */
671     rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);
672 
673     /* hard drives and FDC */
674     arg.rtc_state = s;
675     arg.idebus[0] = idebus0;
676     arg.idebus[1] = idebus1;
677     qemu_register_reset(pc_cmos_init_late, &arg);
678 }
679 
680 static void handle_a20_line_change(void *opaque, int irq, int level)
681 {
682     X86CPU *cpu = opaque;
683 
684     /* XXX: send to all CPUs ? */
685     /* XXX: add logic to handle multiple A20 line sources */
686     x86_cpu_set_a20(cpu, level);
687 }
688 
689 #define NE2000_NB_MAX 6
690 
691 static const int ne2000_io[NE2000_NB_MAX] = { 0x300, 0x320, 0x340, 0x360,
692                                               0x280, 0x380 };
693 static const int ne2000_irq[NE2000_NB_MAX] = { 9, 10, 11, 3, 4, 5 };
694 
695 void pc_init_ne2k_isa(ISABus *bus, NICInfo *nd)
696 {
697     static int nb_ne2k = 0;
698 
699     if (nb_ne2k == NE2000_NB_MAX)
700         return;
701     isa_ne2000_init(bus, ne2000_io[nb_ne2k],
702                     ne2000_irq[nb_ne2k], nd);
703     nb_ne2k++;
704 }
705 
706 void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
707 {
708     X86CPU *cpu = opaque;
709 
710     if (level) {
711         cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
712     }
713 }
714 
715 /*
716  * This function is very similar to smp_parse()
717  * in hw/core/machine.c but includes CPU die support.
718  */
719 void pc_smp_parse(MachineState *ms, QemuOpts *opts)
720 {
721     X86MachineState *x86ms = X86_MACHINE(ms);
722 
723     if (opts) {
724         unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
725         unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
726         unsigned dies = qemu_opt_get_number(opts, "dies", 1);
727         unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
728         unsigned threads = qemu_opt_get_number(opts, "threads", 0);
729 
730         /* compute missing values, prefer sockets over cores over threads */
731         if (cpus == 0 || sockets == 0) {
732             cores = cores > 0 ? cores : 1;
733             threads = threads > 0 ? threads : 1;
734             if (cpus == 0) {
735                 sockets = sockets > 0 ? sockets : 1;
736                 cpus = cores * threads * dies * sockets;
737             } else {
738                 ms->smp.max_cpus =
739                         qemu_opt_get_number(opts, "maxcpus", cpus);
740                 sockets = ms->smp.max_cpus / (cores * threads * dies);
741             }
742         } else if (cores == 0) {
743             threads = threads > 0 ? threads : 1;
744             cores = cpus / (sockets * dies * threads);
745             cores = cores > 0 ? cores : 1;
746         } else if (threads == 0) {
747             threads = cpus / (cores * dies * sockets);
748             threads = threads > 0 ? threads : 1;
749         } else if (sockets * dies * cores * threads < cpus) {
750             error_report("cpu topology: "
751                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) < "
752                          "smp_cpus (%u)",
753                          sockets, dies, cores, threads, cpus);
754             exit(1);
755         }
756 
757         ms->smp.max_cpus =
758                 qemu_opt_get_number(opts, "maxcpus", cpus);
759 
760         if (ms->smp.max_cpus < cpus) {
761             error_report("maxcpus must be equal to or greater than smp");
762             exit(1);
763         }
764 
765         if (sockets * dies * cores * threads > ms->smp.max_cpus) {
766             error_report("cpu topology: "
767                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) > "
768                          "maxcpus (%u)",
769                          sockets, dies, cores, threads,
770                          ms->smp.max_cpus);
771             exit(1);
772         }
773 
774         if (sockets * dies * cores * threads != ms->smp.max_cpus) {
775             warn_report("Invalid CPU topology deprecated: "
776                         "sockets (%u) * dies (%u) * cores (%u) * threads (%u) "
777                         "!= maxcpus (%u)",
778                         sockets, dies, cores, threads,
779                         ms->smp.max_cpus);
780         }
781 
782         ms->smp.cpus = cpus;
783         ms->smp.cores = cores;
784         ms->smp.threads = threads;
785         ms->smp.sockets = sockets;
786         x86ms->smp_dies = dies;
787     }
788 
789     if (ms->smp.cpus > 1) {
790         Error *blocker = NULL;
791         error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");
792         replay_add_blocker(blocker);
793     }
794 }
795 
796 void pc_hot_add_cpu(MachineState *ms, const int64_t id, Error **errp)
797 {
798     X86MachineState *x86ms = X86_MACHINE(ms);
799     int64_t apic_id = x86_cpu_apic_id_from_index(x86ms, id);
800     Error *local_err = NULL;
801 
802     if (id < 0) {
803         error_setg(errp, "Invalid CPU id: %" PRIi64, id);
804         return;
805     }
806 
807     if (apic_id >= ACPI_CPU_HOTPLUG_ID_LIMIT) {
808         error_setg(errp, "Unable to add CPU: %" PRIi64
809                    ", resulting APIC ID (%" PRIi64 ") is too large",
810                    id, apic_id);
811         return;
812     }
813 
814 
815     x86_cpu_new(X86_MACHINE(ms), apic_id, &local_err);
816     if (local_err) {
817         error_propagate(errp, local_err);
818         return;
819     }
820 }
821 
822 static void rtc_set_cpus_count(ISADevice *rtc, uint16_t cpus_count)
823 {
824     if (cpus_count > 0xff) {
825         /* If the number of CPUs can't be represented in 8 bits, the
826          * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
827          * to make old BIOSes fail more predictably.
828          */
829         rtc_set_memory(rtc, 0x5f, 0);
830     } else {
831         rtc_set_memory(rtc, 0x5f, cpus_count - 1);
832     }
833 }
834 
835 static
836 void pc_machine_done(Notifier *notifier, void *data)
837 {
838     PCMachineState *pcms = container_of(notifier,
839                                         PCMachineState, machine_done);
840     X86MachineState *x86ms = X86_MACHINE(pcms);
841     PCIBus *bus = pcms->bus;
842 
843     /* set the number of CPUs */
844     rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
845 
846     if (bus) {
847         int extra_hosts = 0;
848 
849         QLIST_FOREACH(bus, &bus->child, sibling) {
850             /* look for expander root buses */
851             if (pci_bus_is_root(bus)) {
852                 extra_hosts++;
853             }
854         }
855         if (extra_hosts && x86ms->fw_cfg) {
856             uint64_t *val = g_malloc(sizeof(*val));
857             *val = cpu_to_le64(extra_hosts);
858             fw_cfg_add_file(x86ms->fw_cfg,
859                     "etc/extra-pci-roots", val, sizeof(*val));
860         }
861     }
862 
863     acpi_setup();
864     if (x86ms->fw_cfg) {
865         fw_cfg_build_smbios(MACHINE(pcms), x86ms->fw_cfg);
866         fw_cfg_build_feature_control(MACHINE(pcms), x86ms->fw_cfg);
867         /* update FW_CFG_NB_CPUS to account for -device added CPUs */
868         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
869     }
870 
871     if (x86ms->apic_id_limit > 255 && !xen_enabled()) {
872         IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
873 
874         if (!iommu || !x86_iommu_ir_supported(X86_IOMMU_DEVICE(iommu)) ||
875             iommu->intr_eim != ON_OFF_AUTO_ON) {
876             error_report("current -smp configuration requires "
877                          "Extended Interrupt Mode enabled. "
878                          "You can add an IOMMU using: "
879                          "-device intel-iommu,intremap=on,eim=on");
880             exit(EXIT_FAILURE);
881         }
882     }
883 }
884 
885 void pc_guest_info_init(PCMachineState *pcms)
886 {
887     int i;
888     MachineState *ms = MACHINE(pcms);
889     X86MachineState *x86ms = X86_MACHINE(pcms);
890 
891     x86ms->apic_xrupt_override = kvm_allows_irq0_override();
892     pcms->numa_nodes = ms->numa_state->num_nodes;
893     pcms->node_mem = g_malloc0(pcms->numa_nodes *
894                                     sizeof *pcms->node_mem);
895     for (i = 0; i < ms->numa_state->num_nodes; i++) {
896         pcms->node_mem[i] = ms->numa_state->nodes[i].node_mem;
897     }
898 
899     pcms->machine_done.notify = pc_machine_done;
900     qemu_add_machine_init_done_notifier(&pcms->machine_done);
901 }
902 
903 /* setup pci memory address space mapping into system address space */
904 void pc_pci_as_mapping_init(Object *owner, MemoryRegion *system_memory,
905                             MemoryRegion *pci_address_space)
906 {
907     /* Set to lower priority than RAM */
908     memory_region_add_subregion_overlap(system_memory, 0x0,
909                                         pci_address_space, -1);
910 }
911 
912 void xen_load_linux(PCMachineState *pcms)
913 {
914     int i;
915     FWCfgState *fw_cfg;
916     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
917     X86MachineState *x86ms = X86_MACHINE(pcms);
918 
919     assert(MACHINE(pcms)->kernel_filename != NULL);
920 
921     fw_cfg = fw_cfg_init_io(FW_CFG_IO_BASE);
922     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
923     rom_set_fw(fw_cfg);
924 
925     x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
926                    pcmc->pvh_enabled, pcmc->linuxboot_dma_enabled);
927     for (i = 0; i < nb_option_roms; i++) {
928         assert(!strcmp(option_rom[i].name, "linuxboot.bin") ||
929                !strcmp(option_rom[i].name, "linuxboot_dma.bin") ||
930                !strcmp(option_rom[i].name, "pvh.bin") ||
931                !strcmp(option_rom[i].name, "multiboot.bin"));
932         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
933     }
934     x86ms->fw_cfg = fw_cfg;
935 }
936 
937 void pc_memory_init(PCMachineState *pcms,
938                     MemoryRegion *system_memory,
939                     MemoryRegion *rom_memory,
940                     MemoryRegion **ram_memory)
941 {
942     int linux_boot, i;
943     MemoryRegion *option_rom_mr;
944     MemoryRegion *ram_below_4g, *ram_above_4g;
945     FWCfgState *fw_cfg;
946     MachineState *machine = MACHINE(pcms);
947     MachineClass *mc = MACHINE_GET_CLASS(machine);
948     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
949     X86MachineState *x86ms = X86_MACHINE(pcms);
950 
951     assert(machine->ram_size == x86ms->below_4g_mem_size +
952                                 x86ms->above_4g_mem_size);
953 
954     linux_boot = (machine->kernel_filename != NULL);
955 
956     /*
957      * Split single memory region and use aliases to address portions of it,
958      * done for backwards compatibility with older qemus.
959      */
960     *ram_memory = machine->ram;
961     ram_below_4g = g_malloc(sizeof(*ram_below_4g));
962     memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", machine->ram,
963                              0, x86ms->below_4g_mem_size);
964     memory_region_add_subregion(system_memory, 0, ram_below_4g);
965     e820_add_entry(0, x86ms->below_4g_mem_size, E820_RAM);
966     if (x86ms->above_4g_mem_size > 0) {
967         ram_above_4g = g_malloc(sizeof(*ram_above_4g));
968         memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g",
969                                  machine->ram,
970                                  x86ms->below_4g_mem_size,
971                                  x86ms->above_4g_mem_size);
972         memory_region_add_subregion(system_memory, 0x100000000ULL,
973                                     ram_above_4g);
974         e820_add_entry(0x100000000ULL, x86ms->above_4g_mem_size, E820_RAM);
975     }
976 
977     if (!pcmc->has_reserved_memory &&
978         (machine->ram_slots ||
979          (machine->maxram_size > machine->ram_size))) {
980 
981         error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",
982                      mc->name);
983         exit(EXIT_FAILURE);
984     }
985 
986     /* always allocate the device memory information */
987     machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
988 
989     /* initialize device memory address space */
990     if (pcmc->has_reserved_memory &&
991         (machine->ram_size < machine->maxram_size)) {
992         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
993 
994         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
995             error_report("unsupported amount of memory slots: %"PRIu64,
996                          machine->ram_slots);
997             exit(EXIT_FAILURE);
998         }
999 
1000         if (QEMU_ALIGN_UP(machine->maxram_size,
1001                           TARGET_PAGE_SIZE) != machine->maxram_size) {
1002             error_report("maximum memory size must by aligned to multiple of "
1003                          "%d bytes", TARGET_PAGE_SIZE);
1004             exit(EXIT_FAILURE);
1005         }
1006 
1007         machine->device_memory->base =
1008             ROUND_UP(0x100000000ULL + x86ms->above_4g_mem_size, 1 * GiB);
1009 
1010         if (pcmc->enforce_aligned_dimm) {
1011             /* size device region assuming 1G page max alignment per slot */
1012             device_mem_size += (1 * GiB) * machine->ram_slots;
1013         }
1014 
1015         if ((machine->device_memory->base + device_mem_size) <
1016             device_mem_size) {
1017             error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,
1018                          machine->maxram_size);
1019             exit(EXIT_FAILURE);
1020         }
1021 
1022         memory_region_init(&machine->device_memory->mr, OBJECT(pcms),
1023                            "device-memory", device_mem_size);
1024         memory_region_add_subregion(system_memory, machine->device_memory->base,
1025                                     &machine->device_memory->mr);
1026     }
1027 
1028     /* Initialize PC system firmware */
1029     pc_system_firmware_init(pcms, rom_memory);
1030 
1031     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
1032     memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
1033                            &error_fatal);
1034     if (pcmc->pci_enabled) {
1035         memory_region_set_readonly(option_rom_mr, true);
1036     }
1037     memory_region_add_subregion_overlap(rom_memory,
1038                                         PC_ROM_MIN_VGA,
1039                                         option_rom_mr,
1040                                         1);
1041 
1042     fw_cfg = fw_cfg_arch_create(machine,
1043                                 x86ms->boot_cpus, x86ms->apic_id_limit);
1044 
1045     rom_set_fw(fw_cfg);
1046 
1047     if (pcmc->has_reserved_memory && machine->device_memory->base) {
1048         uint64_t *val = g_malloc(sizeof(*val));
1049         PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1050         uint64_t res_mem_end = machine->device_memory->base;
1051 
1052         if (!pcmc->broken_reserved_end) {
1053             res_mem_end += memory_region_size(&machine->device_memory->mr);
1054         }
1055         *val = cpu_to_le64(ROUND_UP(res_mem_end, 1 * GiB));
1056         fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));
1057     }
1058 
1059     if (linux_boot) {
1060         x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
1061                        pcmc->pvh_enabled, pcmc->linuxboot_dma_enabled);
1062     }
1063 
1064     for (i = 0; i < nb_option_roms; i++) {
1065         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1066     }
1067     x86ms->fw_cfg = fw_cfg;
1068 
1069     /* Init default IOAPIC address space */
1070     x86ms->ioapic_as = &address_space_memory;
1071 
1072     /* Init ACPI memory hotplug IO base address */
1073     pcms->memhp_io_base = ACPI_MEMORY_HOTPLUG_BASE;
1074 }
1075 
1076 /*
1077  * The 64bit pci hole starts after "above 4G RAM" and
1078  * potentially the space reserved for memory hotplug.
1079  */
1080 uint64_t pc_pci_hole64_start(void)
1081 {
1082     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
1083     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1084     MachineState *ms = MACHINE(pcms);
1085     X86MachineState *x86ms = X86_MACHINE(pcms);
1086     uint64_t hole64_start = 0;
1087 
1088     if (pcmc->has_reserved_memory && ms->device_memory->base) {
1089         hole64_start = ms->device_memory->base;
1090         if (!pcmc->broken_reserved_end) {
1091             hole64_start += memory_region_size(&ms->device_memory->mr);
1092         }
1093     } else {
1094         hole64_start = 0x100000000ULL + x86ms->above_4g_mem_size;
1095     }
1096 
1097     return ROUND_UP(hole64_start, 1 * GiB);
1098 }
1099 
1100 DeviceState *pc_vga_init(ISABus *isa_bus, PCIBus *pci_bus)
1101 {
1102     DeviceState *dev = NULL;
1103 
1104     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_VGA);
1105     if (pci_bus) {
1106         PCIDevice *pcidev = pci_vga_init(pci_bus);
1107         dev = pcidev ? &pcidev->qdev : NULL;
1108     } else if (isa_bus) {
1109         ISADevice *isadev = isa_vga_init(isa_bus);
1110         dev = isadev ? DEVICE(isadev) : NULL;
1111     }
1112     rom_reset_order_override();
1113     return dev;
1114 }
1115 
1116 static const MemoryRegionOps ioport80_io_ops = {
1117     .write = ioport80_write,
1118     .read = ioport80_read,
1119     .endianness = DEVICE_NATIVE_ENDIAN,
1120     .impl = {
1121         .min_access_size = 1,
1122         .max_access_size = 1,
1123     },
1124 };
1125 
1126 static const MemoryRegionOps ioportF0_io_ops = {
1127     .write = ioportF0_write,
1128     .read = ioportF0_read,
1129     .endianness = DEVICE_NATIVE_ENDIAN,
1130     .impl = {
1131         .min_access_size = 1,
1132         .max_access_size = 1,
1133     },
1134 };
1135 
1136 static void pc_superio_init(ISABus *isa_bus, bool create_fdctrl, bool no_vmport)
1137 {
1138     int i;
1139     DriveInfo *fd[MAX_FD];
1140     qemu_irq *a20_line;
1141     ISADevice *i8042, *port92, *vmmouse;
1142 
1143     serial_hds_isa_init(isa_bus, 0, MAX_ISA_SERIAL_PORTS);
1144     parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);
1145 
1146     for (i = 0; i < MAX_FD; i++) {
1147         fd[i] = drive_get(IF_FLOPPY, 0, i);
1148         create_fdctrl |= !!fd[i];
1149     }
1150     if (create_fdctrl) {
1151         fdctrl_init_isa(isa_bus, fd);
1152     }
1153 
1154     i8042 = isa_create_simple(isa_bus, "i8042");
1155     if (!no_vmport) {
1156         isa_create_simple(isa_bus, TYPE_VMPORT);
1157         vmmouse = isa_try_create(isa_bus, "vmmouse");
1158     } else {
1159         vmmouse = NULL;
1160     }
1161     if (vmmouse) {
1162         object_property_set_link(OBJECT(vmmouse), OBJECT(i8042),
1163                                  "i8042", &error_abort);
1164         qdev_init_nofail(DEVICE(vmmouse));
1165     }
1166     port92 = isa_create_simple(isa_bus, TYPE_PORT92);
1167 
1168     a20_line = qemu_allocate_irqs(handle_a20_line_change, first_cpu, 2);
1169     i8042_setup_a20_line(i8042, a20_line[0]);
1170     qdev_connect_gpio_out_named(DEVICE(port92),
1171                                 PORT92_A20_LINE, 0, a20_line[1]);
1172     g_free(a20_line);
1173 }
1174 
1175 void pc_basic_device_init(ISABus *isa_bus, qemu_irq *gsi,
1176                           ISADevice **rtc_state,
1177                           bool create_fdctrl,
1178                           bool no_vmport,
1179                           bool has_pit,
1180                           uint32_t hpet_irqs)
1181 {
1182     int i;
1183     DeviceState *hpet = NULL;
1184     int pit_isa_irq = 0;
1185     qemu_irq pit_alt_irq = NULL;
1186     qemu_irq rtc_irq = NULL;
1187     ISADevice *pit = NULL;
1188     MemoryRegion *ioport80_io = g_new(MemoryRegion, 1);
1189     MemoryRegion *ioportF0_io = g_new(MemoryRegion, 1);
1190 
1191     memory_region_init_io(ioport80_io, NULL, &ioport80_io_ops, NULL, "ioport80", 1);
1192     memory_region_add_subregion(isa_bus->address_space_io, 0x80, ioport80_io);
1193 
1194     memory_region_init_io(ioportF0_io, NULL, &ioportF0_io_ops, NULL, "ioportF0", 1);
1195     memory_region_add_subregion(isa_bus->address_space_io, 0xf0, ioportF0_io);
1196 
1197     /*
1198      * Check if an HPET shall be created.
1199      *
1200      * Without KVM_CAP_PIT_STATE2, we cannot switch off the in-kernel PIT
1201      * when the HPET wants to take over. Thus we have to disable the latter.
1202      */
1203     if (!no_hpet && (!kvm_irqchip_in_kernel() || kvm_has_pit_state2())) {
1204         hpet = qdev_try_create(NULL, TYPE_HPET);
1205         if (hpet) {
1206             /* For pc-piix-*, hpet's intcap is always IRQ2. For pc-q35-1.7
1207              * and earlier, use IRQ2 for compat. Otherwise, use IRQ16~23,
1208              * IRQ8 and IRQ2.
1209              */
1210             uint8_t compat = object_property_get_uint(OBJECT(hpet),
1211                     HPET_INTCAP, NULL);
1212             if (!compat) {
1213                 qdev_prop_set_uint32(hpet, HPET_INTCAP, hpet_irqs);
1214             }
1215             qdev_init_nofail(hpet);
1216             sysbus_mmio_map(SYS_BUS_DEVICE(hpet), 0, HPET_BASE);
1217 
1218             for (i = 0; i < GSI_NUM_PINS; i++) {
1219                 sysbus_connect_irq(SYS_BUS_DEVICE(hpet), i, gsi[i]);
1220             }
1221             pit_isa_irq = -1;
1222             pit_alt_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_PIT_INT);
1223             rtc_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_RTC_INT);
1224         }
1225     }
1226     *rtc_state = mc146818_rtc_init(isa_bus, 2000, rtc_irq);
1227 
1228     qemu_register_boot_set(pc_boot_set, *rtc_state);
1229 
1230     if (!xen_enabled() && has_pit) {
1231         if (kvm_pit_in_kernel()) {
1232             pit = kvm_pit_init(isa_bus, 0x40);
1233         } else {
1234             pit = i8254_pit_init(isa_bus, 0x40, pit_isa_irq, pit_alt_irq);
1235         }
1236         if (hpet) {
1237             /* connect PIT to output control line of the HPET */
1238             qdev_connect_gpio_out(hpet, 0, qdev_get_gpio_in(DEVICE(pit), 0));
1239         }
1240         pcspk_init(isa_bus, pit);
1241     }
1242 
1243     i8257_dma_init(isa_bus, 0);
1244 
1245     /* Super I/O */
1246     pc_superio_init(isa_bus, create_fdctrl, no_vmport);
1247 }
1248 
1249 void pc_nic_init(PCMachineClass *pcmc, ISABus *isa_bus, PCIBus *pci_bus)
1250 {
1251     int i;
1252 
1253     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_NIC);
1254     for (i = 0; i < nb_nics; i++) {
1255         NICInfo *nd = &nd_table[i];
1256         const char *model = nd->model ? nd->model : pcmc->default_nic_model;
1257 
1258         if (g_str_equal(model, "ne2k_isa")) {
1259             pc_init_ne2k_isa(isa_bus, nd);
1260         } else {
1261             pci_nic_init_nofail(nd, pci_bus, model, NULL);
1262         }
1263     }
1264     rom_reset_order_override();
1265 }
1266 
1267 void pc_i8259_create(ISABus *isa_bus, qemu_irq *i8259_irqs)
1268 {
1269     qemu_irq *i8259;
1270 
1271     if (kvm_pic_in_kernel()) {
1272         i8259 = kvm_i8259_init(isa_bus);
1273     } else if (xen_enabled()) {
1274         i8259 = xen_interrupt_controller_init();
1275     } else {
1276         i8259 = i8259_init(isa_bus, x86_allocate_cpu_irq());
1277     }
1278 
1279     for (size_t i = 0; i < ISA_NUM_IRQS; i++) {
1280         i8259_irqs[i] = i8259[i];
1281     }
1282 
1283     g_free(i8259);
1284 }
1285 
1286 static void pc_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
1287                                Error **errp)
1288 {
1289     const PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1290     const PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1291     const MachineState *ms = MACHINE(hotplug_dev);
1292     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1293     const uint64_t legacy_align = TARGET_PAGE_SIZE;
1294     Error *local_err = NULL;
1295 
1296     /*
1297      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1298      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1299      * addition to cover this case.
1300      */
1301     if (!pcms->acpi_dev || !x86_machine_is_acpi_enabled(X86_MACHINE(pcms))) {
1302         error_setg(errp,
1303                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1304         return;
1305     }
1306 
1307     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
1308         error_setg(errp, "nvdimm is not enabled: missing 'nvdimm' in '-M'");
1309         return;
1310     }
1311 
1312     hotplug_handler_pre_plug(pcms->acpi_dev, dev, &local_err);
1313     if (local_err) {
1314         error_propagate(errp, local_err);
1315         return;
1316     }
1317 
1318     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev),
1319                      pcmc->enforce_aligned_dimm ? NULL : &legacy_align, errp);
1320 }
1321 
1322 static void pc_memory_plug(HotplugHandler *hotplug_dev,
1323                            DeviceState *dev, Error **errp)
1324 {
1325     Error *local_err = NULL;
1326     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1327     MachineState *ms = MACHINE(hotplug_dev);
1328     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1329 
1330     pc_dimm_plug(PC_DIMM(dev), MACHINE(pcms), &local_err);
1331     if (local_err) {
1332         goto out;
1333     }
1334 
1335     if (is_nvdimm) {
1336         nvdimm_plug(ms->nvdimms_state);
1337     }
1338 
1339     hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &error_abort);
1340 out:
1341     error_propagate(errp, local_err);
1342 }
1343 
1344 static void pc_memory_unplug_request(HotplugHandler *hotplug_dev,
1345                                      DeviceState *dev, Error **errp)
1346 {
1347     Error *local_err = NULL;
1348     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1349 
1350     /*
1351      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1352      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1353      * addition to cover this case.
1354      */
1355     if (!pcms->acpi_dev || !x86_machine_is_acpi_enabled(X86_MACHINE(pcms))) {
1356         error_setg(&local_err,
1357                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1358         goto out;
1359     }
1360 
1361     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
1362         error_setg(&local_err,
1363                    "nvdimm device hot unplug is not supported yet.");
1364         goto out;
1365     }
1366 
1367     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
1368                                    &local_err);
1369 out:
1370     error_propagate(errp, local_err);
1371 }
1372 
1373 static void pc_memory_unplug(HotplugHandler *hotplug_dev,
1374                              DeviceState *dev, Error **errp)
1375 {
1376     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1377     Error *local_err = NULL;
1378 
1379     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1380     if (local_err) {
1381         goto out;
1382     }
1383 
1384     pc_dimm_unplug(PC_DIMM(dev), MACHINE(pcms));
1385     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
1386  out:
1387     error_propagate(errp, local_err);
1388 }
1389 
1390 static int pc_apic_cmp(const void *a, const void *b)
1391 {
1392    CPUArchId *apic_a = (CPUArchId *)a;
1393    CPUArchId *apic_b = (CPUArchId *)b;
1394 
1395    return apic_a->arch_id - apic_b->arch_id;
1396 }
1397 
1398 /* returns pointer to CPUArchId descriptor that matches CPU's apic_id
1399  * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
1400  * entry corresponding to CPU's apic_id returns NULL.
1401  */
1402 static CPUArchId *pc_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
1403 {
1404     CPUArchId apic_id, *found_cpu;
1405 
1406     apic_id.arch_id = id;
1407     found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
1408         ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
1409         pc_apic_cmp);
1410     if (found_cpu && idx) {
1411         *idx = found_cpu - ms->possible_cpus->cpus;
1412     }
1413     return found_cpu;
1414 }
1415 
1416 static void pc_cpu_plug(HotplugHandler *hotplug_dev,
1417                         DeviceState *dev, Error **errp)
1418 {
1419     CPUArchId *found_cpu;
1420     Error *local_err = NULL;
1421     X86CPU *cpu = X86_CPU(dev);
1422     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1423     X86MachineState *x86ms = X86_MACHINE(pcms);
1424 
1425     if (pcms->acpi_dev) {
1426         hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1427         if (local_err) {
1428             goto out;
1429         }
1430     }
1431 
1432     /* increment the number of CPUs */
1433     x86ms->boot_cpus++;
1434     if (x86ms->rtc) {
1435         rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
1436     }
1437     if (x86ms->fw_cfg) {
1438         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1439     }
1440 
1441     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
1442     found_cpu->cpu = OBJECT(dev);
1443 out:
1444     error_propagate(errp, local_err);
1445 }
1446 static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
1447                                      DeviceState *dev, Error **errp)
1448 {
1449     int idx = -1;
1450     Error *local_err = NULL;
1451     X86CPU *cpu = X86_CPU(dev);
1452     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1453 
1454     if (!pcms->acpi_dev) {
1455         error_setg(&local_err, "CPU hot unplug not supported without ACPI");
1456         goto out;
1457     }
1458 
1459     pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
1460     assert(idx != -1);
1461     if (idx == 0) {
1462         error_setg(&local_err, "Boot CPU is unpluggable");
1463         goto out;
1464     }
1465 
1466     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
1467                                    &local_err);
1468     if (local_err) {
1469         goto out;
1470     }
1471 
1472  out:
1473     error_propagate(errp, local_err);
1474 
1475 }
1476 
1477 static void pc_cpu_unplug_cb(HotplugHandler *hotplug_dev,
1478                              DeviceState *dev, Error **errp)
1479 {
1480     CPUArchId *found_cpu;
1481     Error *local_err = NULL;
1482     X86CPU *cpu = X86_CPU(dev);
1483     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1484     X86MachineState *x86ms = X86_MACHINE(pcms);
1485 
1486     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1487     if (local_err) {
1488         goto out;
1489     }
1490 
1491     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
1492     found_cpu->cpu = NULL;
1493     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
1494 
1495     /* decrement the number of CPUs */
1496     x86ms->boot_cpus--;
1497     /* Update the number of CPUs in CMOS */
1498     rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
1499     fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1500  out:
1501     error_propagate(errp, local_err);
1502 }
1503 
1504 static void pc_cpu_pre_plug(HotplugHandler *hotplug_dev,
1505                             DeviceState *dev, Error **errp)
1506 {
1507     int idx;
1508     CPUState *cs;
1509     CPUArchId *cpu_slot;
1510     X86CPUTopoIDs topo_ids;
1511     X86CPU *cpu = X86_CPU(dev);
1512     CPUX86State *env = &cpu->env;
1513     MachineState *ms = MACHINE(hotplug_dev);
1514     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1515     X86MachineState *x86ms = X86_MACHINE(pcms);
1516     unsigned int smp_cores = ms->smp.cores;
1517     unsigned int smp_threads = ms->smp.threads;
1518     X86CPUTopoInfo topo_info;
1519 
1520     if(!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
1521         error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
1522                    ms->cpu_type);
1523         return;
1524     }
1525 
1526     init_topo_info(&topo_info, x86ms);
1527 
1528     env->nr_dies = x86ms->smp_dies;
1529     env->nr_nodes = topo_info.nodes_per_pkg;
1530     env->pkg_offset = x86ms->apicid_pkg_offset(&topo_info);
1531 
1532     /*
1533      * If APIC ID is not set,
1534      * set it based on socket/die/core/thread properties.
1535      */
1536     if (cpu->apic_id == UNASSIGNED_APIC_ID) {
1537         int max_socket = (ms->smp.max_cpus - 1) /
1538                                 smp_threads / smp_cores / x86ms->smp_dies;
1539 
1540         /*
1541          * die-id was optional in QEMU 4.0 and older, so keep it optional
1542          * if there's only one die per socket.
1543          */
1544         if (cpu->die_id < 0 && x86ms->smp_dies == 1) {
1545             cpu->die_id = 0;
1546         }
1547 
1548         if (cpu->socket_id < 0) {
1549             error_setg(errp, "CPU socket-id is not set");
1550             return;
1551         } else if (cpu->socket_id > max_socket) {
1552             error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
1553                        cpu->socket_id, max_socket);
1554             return;
1555         }
1556         if (cpu->die_id < 0) {
1557             error_setg(errp, "CPU die-id is not set");
1558             return;
1559         } else if (cpu->die_id > x86ms->smp_dies - 1) {
1560             error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
1561                        cpu->die_id, x86ms->smp_dies - 1);
1562             return;
1563         }
1564         if (cpu->core_id < 0) {
1565             error_setg(errp, "CPU core-id is not set");
1566             return;
1567         } else if (cpu->core_id > (smp_cores - 1)) {
1568             error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
1569                        cpu->core_id, smp_cores - 1);
1570             return;
1571         }
1572         if (cpu->thread_id < 0) {
1573             error_setg(errp, "CPU thread-id is not set");
1574             return;
1575         } else if (cpu->thread_id > (smp_threads - 1)) {
1576             error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
1577                        cpu->thread_id, smp_threads - 1);
1578             return;
1579         }
1580 
1581         topo_ids.pkg_id = cpu->socket_id;
1582         topo_ids.die_id = cpu->die_id;
1583         topo_ids.core_id = cpu->core_id;
1584         topo_ids.smt_id = cpu->thread_id;
1585         cpu->apic_id = x86ms->apicid_from_topo_ids(&topo_info, &topo_ids);
1586     }
1587 
1588     cpu_slot = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
1589     if (!cpu_slot) {
1590         MachineState *ms = MACHINE(pcms);
1591 
1592         x86ms->topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
1593         error_setg(errp,
1594             "Invalid CPU [socket: %u, die: %u, core: %u, thread: %u] with"
1595             " APIC ID %" PRIu32 ", valid index range 0:%d",
1596             topo_ids.pkg_id, topo_ids.die_id, topo_ids.core_id, topo_ids.smt_id,
1597             cpu->apic_id, ms->possible_cpus->len - 1);
1598         return;
1599     }
1600 
1601     if (cpu_slot->cpu) {
1602         error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
1603                    idx, cpu->apic_id);
1604         return;
1605     }
1606 
1607     /* if 'address' properties socket-id/core-id/thread-id are not set, set them
1608      * so that machine_query_hotpluggable_cpus would show correct values
1609      */
1610     /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
1611      * once -smp refactoring is complete and there will be CPU private
1612      * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
1613     x86ms->topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
1614     if (cpu->socket_id != -1 && cpu->socket_id != topo_ids.pkg_id) {
1615         error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
1616             " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id,
1617             topo_ids.pkg_id);
1618         return;
1619     }
1620     cpu->socket_id = topo_ids.pkg_id;
1621 
1622     if (cpu->die_id != -1 && cpu->die_id != topo_ids.die_id) {
1623         error_setg(errp, "property die-id: %u doesn't match set apic-id:"
1624             " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo_ids.die_id);
1625         return;
1626     }
1627     cpu->die_id = topo_ids.die_id;
1628 
1629     if (cpu->core_id != -1 && cpu->core_id != topo_ids.core_id) {
1630         error_setg(errp, "property core-id: %u doesn't match set apic-id:"
1631             " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id,
1632             topo_ids.core_id);
1633         return;
1634     }
1635     cpu->core_id = topo_ids.core_id;
1636 
1637     if (cpu->thread_id != -1 && cpu->thread_id != topo_ids.smt_id) {
1638         error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
1639             " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id,
1640             topo_ids.smt_id);
1641         return;
1642     }
1643     cpu->thread_id = topo_ids.smt_id;
1644 
1645     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
1646         !kvm_hv_vpindex_settable()) {
1647         error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
1648         return;
1649     }
1650 
1651     cs = CPU(cpu);
1652     cs->cpu_index = idx;
1653 
1654     numa_cpu_pre_plug(cpu_slot, dev, errp);
1655 }
1656 
1657 static void pc_virtio_pmem_pci_pre_plug(HotplugHandler *hotplug_dev,
1658                                         DeviceState *dev, Error **errp)
1659 {
1660     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1661     Error *local_err = NULL;
1662 
1663     if (!hotplug_dev2) {
1664         /*
1665          * Without a bus hotplug handler, we cannot control the plug/unplug
1666          * order. This should never be the case on x86, however better add
1667          * a safety net.
1668          */
1669         error_setg(errp, "virtio-pmem-pci not supported on this bus.");
1670         return;
1671     }
1672     /*
1673      * First, see if we can plug this memory device at all. If that
1674      * succeeds, branch of to the actual hotplug handler.
1675      */
1676     memory_device_pre_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev), NULL,
1677                            &local_err);
1678     if (!local_err) {
1679         hotplug_handler_pre_plug(hotplug_dev2, dev, &local_err);
1680     }
1681     error_propagate(errp, local_err);
1682 }
1683 
1684 static void pc_virtio_pmem_pci_plug(HotplugHandler *hotplug_dev,
1685                                     DeviceState *dev, Error **errp)
1686 {
1687     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1688     Error *local_err = NULL;
1689 
1690     /*
1691      * Plug the memory device first and then branch off to the actual
1692      * hotplug handler. If that one fails, we can easily undo the memory
1693      * device bits.
1694      */
1695     memory_device_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1696     hotplug_handler_plug(hotplug_dev2, dev, &local_err);
1697     if (local_err) {
1698         memory_device_unplug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1699     }
1700     error_propagate(errp, local_err);
1701 }
1702 
1703 static void pc_virtio_pmem_pci_unplug_request(HotplugHandler *hotplug_dev,
1704                                               DeviceState *dev, Error **errp)
1705 {
1706     /* We don't support virtio pmem hot unplug */
1707     error_setg(errp, "virtio pmem device unplug not supported.");
1708 }
1709 
1710 static void pc_virtio_pmem_pci_unplug(HotplugHandler *hotplug_dev,
1711                                       DeviceState *dev, Error **errp)
1712 {
1713     /* We don't support virtio pmem hot unplug */
1714 }
1715 
1716 static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
1717                                           DeviceState *dev, Error **errp)
1718 {
1719     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1720         pc_memory_pre_plug(hotplug_dev, dev, errp);
1721     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1722         pc_cpu_pre_plug(hotplug_dev, dev, errp);
1723     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1724         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
1725     }
1726 }
1727 
1728 static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
1729                                       DeviceState *dev, Error **errp)
1730 {
1731     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1732         pc_memory_plug(hotplug_dev, dev, errp);
1733     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1734         pc_cpu_plug(hotplug_dev, dev, errp);
1735     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1736         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
1737     }
1738 }
1739 
1740 static void pc_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
1741                                                 DeviceState *dev, Error **errp)
1742 {
1743     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1744         pc_memory_unplug_request(hotplug_dev, dev, errp);
1745     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1746         pc_cpu_unplug_request_cb(hotplug_dev, dev, errp);
1747     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1748         pc_virtio_pmem_pci_unplug_request(hotplug_dev, dev, errp);
1749     } else {
1750         error_setg(errp, "acpi: device unplug request for not supported device"
1751                    " type: %s", object_get_typename(OBJECT(dev)));
1752     }
1753 }
1754 
1755 static void pc_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
1756                                         DeviceState *dev, Error **errp)
1757 {
1758     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1759         pc_memory_unplug(hotplug_dev, dev, errp);
1760     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1761         pc_cpu_unplug_cb(hotplug_dev, dev, errp);
1762     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1763         pc_virtio_pmem_pci_unplug(hotplug_dev, dev, errp);
1764     } else {
1765         error_setg(errp, "acpi: device unplug for not supported device"
1766                    " type: %s", object_get_typename(OBJECT(dev)));
1767     }
1768 }
1769 
1770 static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
1771                                              DeviceState *dev)
1772 {
1773     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
1774         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
1775         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1776         return HOTPLUG_HANDLER(machine);
1777     }
1778 
1779     return NULL;
1780 }
1781 
1782 static void
1783 pc_machine_get_device_memory_region_size(Object *obj, Visitor *v,
1784                                          const char *name, void *opaque,
1785                                          Error **errp)
1786 {
1787     MachineState *ms = MACHINE(obj);
1788     int64_t value = 0;
1789 
1790     if (ms->device_memory) {
1791         value = memory_region_size(&ms->device_memory->mr);
1792     }
1793 
1794     visit_type_int(v, name, &value, errp);
1795 }
1796 
1797 static void pc_machine_get_vmport(Object *obj, Visitor *v, const char *name,
1798                                   void *opaque, Error **errp)
1799 {
1800     PCMachineState *pcms = PC_MACHINE(obj);
1801     OnOffAuto vmport = pcms->vmport;
1802 
1803     visit_type_OnOffAuto(v, name, &vmport, errp);
1804 }
1805 
1806 static void pc_machine_set_vmport(Object *obj, Visitor *v, const char *name,
1807                                   void *opaque, Error **errp)
1808 {
1809     PCMachineState *pcms = PC_MACHINE(obj);
1810 
1811     visit_type_OnOffAuto(v, name, &pcms->vmport, errp);
1812 }
1813 
1814 static bool pc_machine_get_smbus(Object *obj, Error **errp)
1815 {
1816     PCMachineState *pcms = PC_MACHINE(obj);
1817 
1818     return pcms->smbus_enabled;
1819 }
1820 
1821 static void pc_machine_set_smbus(Object *obj, bool value, Error **errp)
1822 {
1823     PCMachineState *pcms = PC_MACHINE(obj);
1824 
1825     pcms->smbus_enabled = value;
1826 }
1827 
1828 static bool pc_machine_get_sata(Object *obj, Error **errp)
1829 {
1830     PCMachineState *pcms = PC_MACHINE(obj);
1831 
1832     return pcms->sata_enabled;
1833 }
1834 
1835 static void pc_machine_set_sata(Object *obj, bool value, Error **errp)
1836 {
1837     PCMachineState *pcms = PC_MACHINE(obj);
1838 
1839     pcms->sata_enabled = value;
1840 }
1841 
1842 static bool pc_machine_get_pit(Object *obj, Error **errp)
1843 {
1844     PCMachineState *pcms = PC_MACHINE(obj);
1845 
1846     return pcms->pit_enabled;
1847 }
1848 
1849 static void pc_machine_set_pit(Object *obj, bool value, Error **errp)
1850 {
1851     PCMachineState *pcms = PC_MACHINE(obj);
1852 
1853     pcms->pit_enabled = value;
1854 }
1855 
1856 static void pc_machine_initfn(Object *obj)
1857 {
1858     PCMachineState *pcms = PC_MACHINE(obj);
1859 
1860 #ifdef CONFIG_VMPORT
1861     pcms->vmport = ON_OFF_AUTO_AUTO;
1862 #else
1863     pcms->vmport = ON_OFF_AUTO_OFF;
1864 #endif /* CONFIG_VMPORT */
1865     /* acpi build is enabled by default if machine supports it */
1866     pcms->acpi_build_enabled = PC_MACHINE_GET_CLASS(pcms)->has_acpi_build;
1867     pcms->smbus_enabled = true;
1868     pcms->sata_enabled = true;
1869     pcms->pit_enabled = true;
1870 
1871     pc_system_flash_create(pcms);
1872 }
1873 
1874 static void pc_machine_reset(MachineState *machine)
1875 {
1876     CPUState *cs;
1877     X86CPU *cpu;
1878 
1879     qemu_devices_reset();
1880 
1881     /* Reset APIC after devices have been reset to cancel
1882      * any changes that qemu_devices_reset() might have done.
1883      */
1884     CPU_FOREACH(cs) {
1885         cpu = X86_CPU(cs);
1886 
1887         if (cpu->apic_state) {
1888             device_legacy_reset(cpu->apic_state);
1889         }
1890     }
1891 }
1892 
1893 static void pc_machine_wakeup(MachineState *machine)
1894 {
1895     cpu_synchronize_all_states();
1896     pc_machine_reset(machine);
1897     cpu_synchronize_all_post_reset();
1898 }
1899 
1900 static bool pc_hotplug_allowed(MachineState *ms, DeviceState *dev, Error **errp)
1901 {
1902     X86IOMMUState *iommu = x86_iommu_get_default();
1903     IntelIOMMUState *intel_iommu;
1904 
1905     if (iommu &&
1906         object_dynamic_cast((Object *)iommu, TYPE_INTEL_IOMMU_DEVICE) &&
1907         object_dynamic_cast((Object *)dev, "vfio-pci")) {
1908         intel_iommu = INTEL_IOMMU_DEVICE(iommu);
1909         if (!intel_iommu->caching_mode) {
1910             error_setg(errp, "Device assignment is not allowed without "
1911                        "enabling caching-mode=on for Intel IOMMU.");
1912             return false;
1913         }
1914     }
1915 
1916     return true;
1917 }
1918 
1919 static void pc_machine_class_init(ObjectClass *oc, void *data)
1920 {
1921     MachineClass *mc = MACHINE_CLASS(oc);
1922     PCMachineClass *pcmc = PC_MACHINE_CLASS(oc);
1923     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
1924 
1925     pcmc->pci_enabled = true;
1926     pcmc->has_acpi_build = true;
1927     pcmc->rsdp_in_ram = true;
1928     pcmc->smbios_defaults = true;
1929     pcmc->smbios_uuid_encoded = true;
1930     pcmc->gigabyte_align = true;
1931     pcmc->has_reserved_memory = true;
1932     pcmc->kvmclock_enabled = true;
1933     pcmc->enforce_aligned_dimm = true;
1934     /* BIOS ACPI tables: 128K. Other BIOS datastructures: less than 4K reported
1935      * to be used at the moment, 32K should be enough for a while.  */
1936     pcmc->acpi_data_size = 0x20000 + 0x8000;
1937     pcmc->linuxboot_dma_enabled = true;
1938     pcmc->pvh_enabled = true;
1939     assert(!mc->get_hotplug_handler);
1940     mc->get_hotplug_handler = pc_get_hotplug_handler;
1941     mc->hotplug_allowed = pc_hotplug_allowed;
1942     mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
1943     mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
1944     mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
1945     mc->auto_enable_numa_with_memhp = true;
1946     mc->has_hotpluggable_cpus = true;
1947     mc->default_boot_order = "cad";
1948     mc->hot_add_cpu = pc_hot_add_cpu;
1949     mc->smp_parse = pc_smp_parse;
1950     mc->block_default_type = IF_IDE;
1951     mc->max_cpus = 255;
1952     mc->reset = pc_machine_reset;
1953     mc->wakeup = pc_machine_wakeup;
1954     hc->pre_plug = pc_machine_device_pre_plug_cb;
1955     hc->plug = pc_machine_device_plug_cb;
1956     hc->unplug_request = pc_machine_device_unplug_request_cb;
1957     hc->unplug = pc_machine_device_unplug_cb;
1958     mc->default_cpu_type = TARGET_DEFAULT_CPU_TYPE;
1959     mc->nvdimm_supported = true;
1960     mc->numa_mem_supported = true;
1961     mc->default_ram_id = "pc.ram";
1962 
1963     object_class_property_add(oc, PC_MACHINE_DEVMEM_REGION_SIZE, "int",
1964         pc_machine_get_device_memory_region_size, NULL,
1965         NULL, NULL, &error_abort);
1966 
1967     object_class_property_add(oc, PC_MACHINE_VMPORT, "OnOffAuto",
1968         pc_machine_get_vmport, pc_machine_set_vmport,
1969         NULL, NULL, &error_abort);
1970     object_class_property_set_description(oc, PC_MACHINE_VMPORT,
1971         "Enable vmport (pc & q35)", &error_abort);
1972 
1973     object_class_property_add_bool(oc, PC_MACHINE_SMBUS,
1974         pc_machine_get_smbus, pc_machine_set_smbus, &error_abort);
1975 
1976     object_class_property_add_bool(oc, PC_MACHINE_SATA,
1977         pc_machine_get_sata, pc_machine_set_sata, &error_abort);
1978 
1979     object_class_property_add_bool(oc, PC_MACHINE_PIT,
1980         pc_machine_get_pit, pc_machine_set_pit, &error_abort);
1981 }
1982 
1983 static const TypeInfo pc_machine_info = {
1984     .name = TYPE_PC_MACHINE,
1985     .parent = TYPE_X86_MACHINE,
1986     .abstract = true,
1987     .instance_size = sizeof(PCMachineState),
1988     .instance_init = pc_machine_initfn,
1989     .class_size = sizeof(PCMachineClass),
1990     .class_init = pc_machine_class_init,
1991     .interfaces = (InterfaceInfo[]) {
1992          { TYPE_HOTPLUG_HANDLER },
1993          { }
1994     },
1995 };
1996 
1997 static void pc_machine_register_types(void)
1998 {
1999     type_register_static(&pc_machine_info);
2000 }
2001 
2002 type_init(pc_machine_register_types)
2003