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