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