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