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