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