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