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