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