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