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