]> Git Repo - qemu.git/blob - hw/i386/pc.c
x86: move SMM property to X86MachineState
[qemu.git] / hw / i386 / pc.c
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/i386/x86.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 "hw/i386/fw_cfg.h"
34 #include "sysemu/cpus.h"
35 #include "hw/block/fdc.h"
36 #include "hw/ide.h"
37 #include "hw/pci/pci.h"
38 #include "hw/pci/pci_bus.h"
39 #include "hw/nvram/fw_cfg.h"
40 #include "hw/timer/hpet.h"
41 #include "hw/firmware/smbios.h"
42 #include "hw/loader.h"
43 #include "elf.h"
44 #include "migration/vmstate.h"
45 #include "multiboot.h"
46 #include "hw/rtc/mc146818rtc.h"
47 #include "hw/intc/i8259.h"
48 #include "hw/dma/i8257.h"
49 #include "hw/timer/i8254.h"
50 #include "hw/input/i8042.h"
51 #include "hw/irq.h"
52 #include "hw/audio/pcspk.h"
53 #include "hw/pci/msi.h"
54 #include "hw/sysbus.h"
55 #include "sysemu/sysemu.h"
56 #include "sysemu/tcg.h"
57 #include "sysemu/numa.h"
58 #include "sysemu/kvm.h"
59 #include "sysemu/qtest.h"
60 #include "sysemu/reset.h"
61 #include "sysemu/runstate.h"
62 #include "kvm_i386.h"
63 #include "hw/xen/xen.h"
64 #include "hw/xen/start_info.h"
65 #include "ui/qemu-spice.h"
66 #include "exec/memory.h"
67 #include "exec/address-spaces.h"
68 #include "sysemu/arch_init.h"
69 #include "qemu/bitmap.h"
70 #include "qemu/config-file.h"
71 #include "qemu/error-report.h"
72 #include "qemu/option.h"
73 #include "qemu/cutils.h"
74 #include "hw/acpi/acpi.h"
75 #include "hw/acpi/cpu_hotplug.h"
76 #include "hw/boards.h"
77 #include "acpi-build.h"
78 #include "hw/mem/pc-dimm.h"
79 #include "qapi/error.h"
80 #include "qapi/qapi-visit-common.h"
81 #include "qapi/visitor.h"
82 #include "hw/core/cpu.h"
83 #include "hw/usb.h"
84 #include "hw/i386/intel_iommu.h"
85 #include "hw/net/ne2000-isa.h"
86 #include "standard-headers/asm-x86/bootparam.h"
87 #include "hw/virtio/virtio-pmem-pci.h"
88 #include "hw/mem/memory-device.h"
89 #include "sysemu/replay.h"
90 #include "qapi/qmp/qerror.h"
91 #include "config-devices.h"
92 #include "e820_memory_layout.h"
93 #include "fw_cfg.h"
94
95 /* debug PC/ISA interrupts */
96 //#define DEBUG_IRQ
97
98 #ifdef DEBUG_IRQ
99 #define DPRINTF(fmt, ...)                                       \
100     do { printf("CPUIRQ: " fmt , ## __VA_ARGS__); } while (0)
101 #else
102 #define DPRINTF(fmt, ...)
103 #endif
104
105 GlobalProperty pc_compat_4_2[] = {};
106 const size_t pc_compat_4_2_len = G_N_ELEMENTS(pc_compat_4_2);
107
108 GlobalProperty pc_compat_4_1[] = {};
109 const size_t pc_compat_4_1_len = G_N_ELEMENTS(pc_compat_4_1);
110
111 GlobalProperty pc_compat_4_0[] = {};
112 const size_t pc_compat_4_0_len = G_N_ELEMENTS(pc_compat_4_0);
113
114 GlobalProperty pc_compat_3_1[] = {
115     { "intel-iommu", "dma-drain", "off" },
116     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "off" },
117     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "off" },
118     { "Opteron_G4" "-" TYPE_X86_CPU, "npt", "off" },
119     { "Opteron_G4" "-" TYPE_X86_CPU, "nrip-save", "off" },
120     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "off" },
121     { "Opteron_G5" "-" TYPE_X86_CPU, "npt", "off" },
122     { "Opteron_G5" "-" TYPE_X86_CPU, "nrip-save", "off" },
123     { "EPYC" "-" TYPE_X86_CPU, "npt", "off" },
124     { "EPYC" "-" TYPE_X86_CPU, "nrip-save", "off" },
125     { "EPYC-IBPB" "-" TYPE_X86_CPU, "npt", "off" },
126     { "EPYC-IBPB" "-" TYPE_X86_CPU, "nrip-save", "off" },
127     { "Skylake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
128     { "Skylake-Client-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
129     { "Skylake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
130     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
131     { "Cascadelake-Server" "-" TYPE_X86_CPU,  "mpx", "on" },
132     { "Icelake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
133     { "Icelake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
134     { "Cascadelake-Server" "-" TYPE_X86_CPU, "stepping", "5" },
135     { TYPE_X86_CPU, "x-intel-pt-auto-level", "off" },
136 };
137 const size_t pc_compat_3_1_len = G_N_ELEMENTS(pc_compat_3_1);
138
139 GlobalProperty pc_compat_3_0[] = {
140     { TYPE_X86_CPU, "x-hv-synic-kvm-only", "on" },
141     { "Skylake-Server" "-" TYPE_X86_CPU, "pku", "off" },
142     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "pku", "off" },
143 };
144 const size_t pc_compat_3_0_len = G_N_ELEMENTS(pc_compat_3_0);
145
146 GlobalProperty pc_compat_2_12[] = {
147     { TYPE_X86_CPU, "legacy-cache", "on" },
148     { TYPE_X86_CPU, "topoext", "off" },
149     { "EPYC-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
150     { "EPYC-IBPB-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
151 };
152 const size_t pc_compat_2_12_len = G_N_ELEMENTS(pc_compat_2_12);
153
154 GlobalProperty pc_compat_2_11[] = {
155     { TYPE_X86_CPU, "x-migrate-smi-count", "off" },
156     { "Skylake-Server" "-" TYPE_X86_CPU, "clflushopt", "off" },
157 };
158 const size_t pc_compat_2_11_len = G_N_ELEMENTS(pc_compat_2_11);
159
160 GlobalProperty pc_compat_2_10[] = {
161     { TYPE_X86_CPU, "x-hv-max-vps", "0x40" },
162     { "i440FX-pcihost", "x-pci-hole64-fix", "off" },
163     { "q35-pcihost", "x-pci-hole64-fix", "off" },
164 };
165 const size_t pc_compat_2_10_len = G_N_ELEMENTS(pc_compat_2_10);
166
167 GlobalProperty pc_compat_2_9[] = {
168     { "mch", "extended-tseg-mbytes", "0" },
169 };
170 const size_t pc_compat_2_9_len = G_N_ELEMENTS(pc_compat_2_9);
171
172 GlobalProperty pc_compat_2_8[] = {
173     { TYPE_X86_CPU, "tcg-cpuid", "off" },
174     { "kvmclock", "x-mach-use-reliable-get-clock", "off" },
175     { "ICH9-LPC", "x-smi-broadcast", "off" },
176     { TYPE_X86_CPU, "vmware-cpuid-freq", "off" },
177     { "Haswell-" TYPE_X86_CPU, "stepping", "1" },
178 };
179 const size_t pc_compat_2_8_len = G_N_ELEMENTS(pc_compat_2_8);
180
181 GlobalProperty pc_compat_2_7[] = {
182     { TYPE_X86_CPU, "l3-cache", "off" },
183     { TYPE_X86_CPU, "full-cpuid-auto-level", "off" },
184     { "Opteron_G3" "-" TYPE_X86_CPU, "family", "15" },
185     { "Opteron_G3" "-" TYPE_X86_CPU, "model", "6" },
186     { "Opteron_G3" "-" TYPE_X86_CPU, "stepping", "1" },
187     { "isa-pcspk", "migrate", "off" },
188 };
189 const size_t pc_compat_2_7_len = G_N_ELEMENTS(pc_compat_2_7);
190
191 GlobalProperty pc_compat_2_6[] = {
192     { TYPE_X86_CPU, "cpuid-0xb", "off" },
193     { "vmxnet3", "romfile", "" },
194     { TYPE_X86_CPU, "fill-mtrr-mask", "off" },
195     { "apic-common", "legacy-instance-id", "on", }
196 };
197 const size_t pc_compat_2_6_len = G_N_ELEMENTS(pc_compat_2_6);
198
199 GlobalProperty pc_compat_2_5[] = {};
200 const size_t pc_compat_2_5_len = G_N_ELEMENTS(pc_compat_2_5);
201
202 GlobalProperty pc_compat_2_4[] = {
203     PC_CPU_MODEL_IDS("2.4.0")
204     { "Haswell-" TYPE_X86_CPU, "abm", "off" },
205     { "Haswell-noTSX-" TYPE_X86_CPU, "abm", "off" },
206     { "Broadwell-" TYPE_X86_CPU, "abm", "off" },
207     { "Broadwell-noTSX-" TYPE_X86_CPU, "abm", "off" },
208     { "host" "-" TYPE_X86_CPU, "host-cache-info", "on" },
209     { TYPE_X86_CPU, "check", "off" },
210     { "qemu64" "-" TYPE_X86_CPU, "sse4a", "on" },
211     { "qemu64" "-" TYPE_X86_CPU, "abm", "on" },
212     { "qemu64" "-" TYPE_X86_CPU, "popcnt", "on" },
213     { "qemu32" "-" TYPE_X86_CPU, "popcnt", "on" },
214     { "Opteron_G2" "-" TYPE_X86_CPU, "rdtscp", "on" },
215     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "on" },
216     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "on" },
217     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "on", }
218 };
219 const size_t pc_compat_2_4_len = G_N_ELEMENTS(pc_compat_2_4);
220
221 GlobalProperty pc_compat_2_3[] = {
222     PC_CPU_MODEL_IDS("2.3.0")
223     { TYPE_X86_CPU, "arat", "off" },
224     { "qemu64" "-" TYPE_X86_CPU, "min-level", "4" },
225     { "kvm64" "-" TYPE_X86_CPU, "min-level", "5" },
226     { "pentium3" "-" TYPE_X86_CPU, "min-level", "2" },
227     { "n270" "-" TYPE_X86_CPU, "min-level", "5" },
228     { "Conroe" "-" TYPE_X86_CPU, "min-level", "4" },
229     { "Penryn" "-" TYPE_X86_CPU, "min-level", "4" },
230     { "Nehalem" "-" TYPE_X86_CPU, "min-level", "4" },
231     { "n270" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
232     { "Penryn" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
233     { "Conroe" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
234     { "Nehalem" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
235     { "Westmere" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
236     { "SandyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
237     { "IvyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
238     { "Haswell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
239     { "Haswell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
240     { "Broadwell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
241     { "Broadwell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
242     { TYPE_X86_CPU, "kvm-no-smi-migration", "on" },
243 };
244 const size_t pc_compat_2_3_len = G_N_ELEMENTS(pc_compat_2_3);
245
246 GlobalProperty pc_compat_2_2[] = {
247     PC_CPU_MODEL_IDS("2.2.0")
248     { "kvm64" "-" TYPE_X86_CPU, "vme", "off" },
249     { "kvm32" "-" TYPE_X86_CPU, "vme", "off" },
250     { "Conroe" "-" TYPE_X86_CPU, "vme", "off" },
251     { "Penryn" "-" TYPE_X86_CPU, "vme", "off" },
252     { "Nehalem" "-" TYPE_X86_CPU, "vme", "off" },
253     { "Westmere" "-" TYPE_X86_CPU, "vme", "off" },
254     { "SandyBridge" "-" TYPE_X86_CPU, "vme", "off" },
255     { "Haswell" "-" TYPE_X86_CPU, "vme", "off" },
256     { "Broadwell" "-" TYPE_X86_CPU, "vme", "off" },
257     { "Opteron_G1" "-" TYPE_X86_CPU, "vme", "off" },
258     { "Opteron_G2" "-" TYPE_X86_CPU, "vme", "off" },
259     { "Opteron_G3" "-" TYPE_X86_CPU, "vme", "off" },
260     { "Opteron_G4" "-" TYPE_X86_CPU, "vme", "off" },
261     { "Opteron_G5" "-" TYPE_X86_CPU, "vme", "off" },
262     { "Haswell" "-" TYPE_X86_CPU, "f16c", "off" },
263     { "Haswell" "-" TYPE_X86_CPU, "rdrand", "off" },
264     { "Broadwell" "-" TYPE_X86_CPU, "f16c", "off" },
265     { "Broadwell" "-" TYPE_X86_CPU, "rdrand", "off" },
266 };
267 const size_t pc_compat_2_2_len = G_N_ELEMENTS(pc_compat_2_2);
268
269 GlobalProperty pc_compat_2_1[] = {
270     PC_CPU_MODEL_IDS("2.1.0")
271     { "coreduo" "-" TYPE_X86_CPU, "vmx", "on" },
272     { "core2duo" "-" TYPE_X86_CPU, "vmx", "on" },
273 };
274 const size_t pc_compat_2_1_len = G_N_ELEMENTS(pc_compat_2_1);
275
276 GlobalProperty pc_compat_2_0[] = {
277     PC_CPU_MODEL_IDS("2.0.0")
278     { "virtio-scsi-pci", "any_layout", "off" },
279     { "PIIX4_PM", "memory-hotplug-support", "off" },
280     { "apic", "version", "0x11" },
281     { "nec-usb-xhci", "superspeed-ports-first", "off" },
282     { "nec-usb-xhci", "force-pcie-endcap", "on" },
283     { "pci-serial", "prog_if", "0" },
284     { "pci-serial-2x", "prog_if", "0" },
285     { "pci-serial-4x", "prog_if", "0" },
286     { "virtio-net-pci", "guest_announce", "off" },
287     { "ICH9-LPC", "memory-hotplug-support", "off" },
288     { "xio3130-downstream", COMPAT_PROP_PCP, "off" },
289     { "ioh3420", COMPAT_PROP_PCP, "off" },
290 };
291 const size_t pc_compat_2_0_len = G_N_ELEMENTS(pc_compat_2_0);
292
293 GlobalProperty pc_compat_1_7[] = {
294     PC_CPU_MODEL_IDS("1.7.0")
295     { TYPE_USB_DEVICE, "msos-desc", "no" },
296     { "PIIX4_PM", "acpi-pci-hotplug-with-bridge-support", "off" },
297     { "hpet", HPET_INTCAP, "4" },
298 };
299 const size_t pc_compat_1_7_len = G_N_ELEMENTS(pc_compat_1_7);
300
301 GlobalProperty pc_compat_1_6[] = {
302     PC_CPU_MODEL_IDS("1.6.0")
303     { "e1000", "mitigation", "off" },
304     { "qemu64-" TYPE_X86_CPU, "model", "2" },
305     { "qemu32-" TYPE_X86_CPU, "model", "3" },
306     { "i440FX-pcihost", "short_root_bus", "1" },
307     { "q35-pcihost", "short_root_bus", "1" },
308 };
309 const size_t pc_compat_1_6_len = G_N_ELEMENTS(pc_compat_1_6);
310
311 GlobalProperty pc_compat_1_5[] = {
312     PC_CPU_MODEL_IDS("1.5.0")
313     { "Conroe-" TYPE_X86_CPU, "model", "2" },
314     { "Conroe-" TYPE_X86_CPU, "min-level", "2" },
315     { "Penryn-" TYPE_X86_CPU, "model", "2" },
316     { "Penryn-" TYPE_X86_CPU, "min-level", "2" },
317     { "Nehalem-" TYPE_X86_CPU, "model", "2" },
318     { "Nehalem-" TYPE_X86_CPU, "min-level", "2" },
319     { "virtio-net-pci", "any_layout", "off" },
320     { TYPE_X86_CPU, "pmu", "on" },
321     { "i440FX-pcihost", "short_root_bus", "0" },
322     { "q35-pcihost", "short_root_bus", "0" },
323 };
324 const size_t pc_compat_1_5_len = G_N_ELEMENTS(pc_compat_1_5);
325
326 GlobalProperty pc_compat_1_4[] = {
327     PC_CPU_MODEL_IDS("1.4.0")
328     { "scsi-hd", "discard_granularity", "0" },
329     { "scsi-cd", "discard_granularity", "0" },
330     { "scsi-disk", "discard_granularity", "0" },
331     { "ide-hd", "discard_granularity", "0" },
332     { "ide-cd", "discard_granularity", "0" },
333     { "ide-drive", "discard_granularity", "0" },
334     { "virtio-blk-pci", "discard_granularity", "0" },
335     /* DEV_NVECTORS_UNSPECIFIED as a uint32_t string: */
336     { "virtio-serial-pci", "vectors", "0xFFFFFFFF" },
337     { "virtio-net-pci", "ctrl_guest_offloads", "off" },
338     { "e1000", "romfile", "pxe-e1000.rom" },
339     { "ne2k_pci", "romfile", "pxe-ne2k_pci.rom" },
340     { "pcnet", "romfile", "pxe-pcnet.rom" },
341     { "rtl8139", "romfile", "pxe-rtl8139.rom" },
342     { "virtio-net-pci", "romfile", "pxe-virtio.rom" },
343     { "486-" TYPE_X86_CPU, "model", "0" },
344     { "n270" "-" TYPE_X86_CPU, "movbe", "off" },
345     { "Westmere" "-" TYPE_X86_CPU, "pclmulqdq", "off" },
346 };
347 const size_t pc_compat_1_4_len = G_N_ELEMENTS(pc_compat_1_4);
348
349 void gsi_handler(void *opaque, int n, int level)
350 {
351     GSIState *s = opaque;
352
353     DPRINTF("pc: %s GSI %d\n", level ? "raising" : "lowering", n);
354     if (n < ISA_NUM_IRQS) {
355         qemu_set_irq(s->i8259_irq[n], level);
356     }
357     qemu_set_irq(s->ioapic_irq[n], level);
358 }
359
360 GSIState *pc_gsi_create(qemu_irq **irqs, bool pci_enabled)
361 {
362     GSIState *s;
363
364     s = g_new0(GSIState, 1);
365     if (kvm_ioapic_in_kernel()) {
366         kvm_pc_setup_irq_routing(pci_enabled);
367         *irqs = qemu_allocate_irqs(kvm_pc_gsi_handler, s, GSI_NUM_PINS);
368     } else {
369         *irqs = qemu_allocate_irqs(gsi_handler, s, GSI_NUM_PINS);
370     }
371
372     return s;
373 }
374
375 static void ioport80_write(void *opaque, hwaddr addr, uint64_t data,
376                            unsigned size)
377 {
378 }
379
380 static uint64_t ioport80_read(void *opaque, hwaddr addr, unsigned size)
381 {
382     return 0xffffffffffffffffULL;
383 }
384
385 /* MSDOS compatibility mode FPU exception support */
386 static void ioportF0_write(void *opaque, hwaddr addr, uint64_t data,
387                            unsigned size)
388 {
389     if (tcg_enabled()) {
390         cpu_set_ignne();
391     }
392 }
393
394 static uint64_t ioportF0_read(void *opaque, hwaddr addr, unsigned size)
395 {
396     return 0xffffffffffffffffULL;
397 }
398
399 /* TSC handling */
400 uint64_t cpu_get_tsc(CPUX86State *env)
401 {
402     return cpu_get_ticks();
403 }
404
405 /* IRQ handling */
406 int cpu_get_pic_interrupt(CPUX86State *env)
407 {
408     X86CPU *cpu = env_archcpu(env);
409     int intno;
410
411     if (!kvm_irqchip_in_kernel()) {
412         intno = apic_get_interrupt(cpu->apic_state);
413         if (intno >= 0) {
414             return intno;
415         }
416         /* read the irq from the PIC */
417         if (!apic_accept_pic_intr(cpu->apic_state)) {
418             return -1;
419         }
420     }
421
422     intno = pic_read_irq(isa_pic);
423     return intno;
424 }
425
426 static void pic_irq_request(void *opaque, int irq, int level)
427 {
428     CPUState *cs = first_cpu;
429     X86CPU *cpu = X86_CPU(cs);
430
431     DPRINTF("pic_irqs: %s irq %d\n", level? "raise" : "lower", irq);
432     if (cpu->apic_state && !kvm_irqchip_in_kernel()) {
433         CPU_FOREACH(cs) {
434             cpu = X86_CPU(cs);
435             if (apic_accept_pic_intr(cpu->apic_state)) {
436                 apic_deliver_pic_intr(cpu->apic_state, level);
437             }
438         }
439     } else {
440         if (level) {
441             cpu_interrupt(cs, CPU_INTERRUPT_HARD);
442         } else {
443             cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
444         }
445     }
446 }
447
448 /* PC cmos mappings */
449
450 #define REG_EQUIPMENT_BYTE          0x14
451
452 int cmos_get_fd_drive_type(FloppyDriveType fd0)
453 {
454     int val;
455
456     switch (fd0) {
457     case FLOPPY_DRIVE_TYPE_144:
458         /* 1.44 Mb 3"5 drive */
459         val = 4;
460         break;
461     case FLOPPY_DRIVE_TYPE_288:
462         /* 2.88 Mb 3"5 drive */
463         val = 5;
464         break;
465     case FLOPPY_DRIVE_TYPE_120:
466         /* 1.2 Mb 5"5 drive */
467         val = 2;
468         break;
469     case FLOPPY_DRIVE_TYPE_NONE:
470     default:
471         val = 0;
472         break;
473     }
474     return val;
475 }
476
477 static void cmos_init_hd(ISADevice *s, int type_ofs, int info_ofs,
478                          int16_t cylinders, int8_t heads, int8_t sectors)
479 {
480     rtc_set_memory(s, type_ofs, 47);
481     rtc_set_memory(s, info_ofs, cylinders);
482     rtc_set_memory(s, info_ofs + 1, cylinders >> 8);
483     rtc_set_memory(s, info_ofs + 2, heads);
484     rtc_set_memory(s, info_ofs + 3, 0xff);
485     rtc_set_memory(s, info_ofs + 4, 0xff);
486     rtc_set_memory(s, info_ofs + 5, 0xc0 | ((heads > 8) << 3));
487     rtc_set_memory(s, info_ofs + 6, cylinders);
488     rtc_set_memory(s, info_ofs + 7, cylinders >> 8);
489     rtc_set_memory(s, info_ofs + 8, sectors);
490 }
491
492 /* convert boot_device letter to something recognizable by the bios */
493 static int boot_device2nibble(char boot_device)
494 {
495     switch(boot_device) {
496     case 'a':
497     case 'b':
498         return 0x01; /* floppy boot */
499     case 'c':
500         return 0x02; /* hard drive boot */
501     case 'd':
502         return 0x03; /* CD-ROM boot */
503     case 'n':
504         return 0x04; /* Network boot */
505     }
506     return 0;
507 }
508
509 static void set_boot_dev(ISADevice *s, const char *boot_device, Error **errp)
510 {
511 #define PC_MAX_BOOT_DEVICES 3
512     int nbds, bds[3] = { 0, };
513     int i;
514
515     nbds = strlen(boot_device);
516     if (nbds > PC_MAX_BOOT_DEVICES) {
517         error_setg(errp, "Too many boot devices for PC");
518         return;
519     }
520     for (i = 0; i < nbds; i++) {
521         bds[i] = boot_device2nibble(boot_device[i]);
522         if (bds[i] == 0) {
523             error_setg(errp, "Invalid boot device for PC: '%c'",
524                        boot_device[i]);
525             return;
526         }
527     }
528     rtc_set_memory(s, 0x3d, (bds[1] << 4) | bds[0]);
529     rtc_set_memory(s, 0x38, (bds[2] << 4) | (fd_bootchk ? 0x0 : 0x1));
530 }
531
532 static void pc_boot_set(void *opaque, const char *boot_device, Error **errp)
533 {
534     set_boot_dev(opaque, boot_device, errp);
535 }
536
537 static void pc_cmos_init_floppy(ISADevice *rtc_state, ISADevice *floppy)
538 {
539     int val, nb, i;
540     FloppyDriveType fd_type[2] = { FLOPPY_DRIVE_TYPE_NONE,
541                                    FLOPPY_DRIVE_TYPE_NONE };
542
543     /* floppy type */
544     if (floppy) {
545         for (i = 0; i < 2; i++) {
546             fd_type[i] = isa_fdc_get_drive_type(floppy, i);
547         }
548     }
549     val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |
550         cmos_get_fd_drive_type(fd_type[1]);
551     rtc_set_memory(rtc_state, 0x10, val);
552
553     val = rtc_get_memory(rtc_state, REG_EQUIPMENT_BYTE);
554     nb = 0;
555     if (fd_type[0] != FLOPPY_DRIVE_TYPE_NONE) {
556         nb++;
557     }
558     if (fd_type[1] != FLOPPY_DRIVE_TYPE_NONE) {
559         nb++;
560     }
561     switch (nb) {
562     case 0:
563         break;
564     case 1:
565         val |= 0x01; /* 1 drive, ready for boot */
566         break;
567     case 2:
568         val |= 0x41; /* 2 drives, ready for boot */
569         break;
570     }
571     rtc_set_memory(rtc_state, REG_EQUIPMENT_BYTE, val);
572 }
573
574 typedef struct pc_cmos_init_late_arg {
575     ISADevice *rtc_state;
576     BusState *idebus[2];
577 } pc_cmos_init_late_arg;
578
579 typedef struct check_fdc_state {
580     ISADevice *floppy;
581     bool multiple;
582 } CheckFdcState;
583
584 static int check_fdc(Object *obj, void *opaque)
585 {
586     CheckFdcState *state = opaque;
587     Object *fdc;
588     uint32_t iobase;
589     Error *local_err = NULL;
590
591     fdc = object_dynamic_cast(obj, TYPE_ISA_FDC);
592     if (!fdc) {
593         return 0;
594     }
595
596     iobase = object_property_get_uint(obj, "iobase", &local_err);
597     if (local_err || iobase != 0x3f0) {
598         error_free(local_err);
599         return 0;
600     }
601
602     if (state->floppy) {
603         state->multiple = true;
604     } else {
605         state->floppy = ISA_DEVICE(obj);
606     }
607     return 0;
608 }
609
610 static const char * const fdc_container_path[] = {
611     "/unattached", "/peripheral", "/peripheral-anon"
612 };
613
614 /*
615  * Locate the FDC at IO address 0x3f0, in order to configure the CMOS registers
616  * and ACPI objects.
617  */
618 ISADevice *pc_find_fdc0(void)
619 {
620     int i;
621     Object *container;
622     CheckFdcState state = { 0 };
623
624     for (i = 0; i < ARRAY_SIZE(fdc_container_path); i++) {
625         container = container_get(qdev_get_machine(), fdc_container_path[i]);
626         object_child_foreach(container, check_fdc, &state);
627     }
628
629     if (state.multiple) {
630         warn_report("multiple floppy disk controllers with "
631                     "iobase=0x3f0 have been found");
632         error_printf("the one being picked for CMOS setup might not reflect "
633                      "your intent");
634     }
635
636     return state.floppy;
637 }
638
639 static void pc_cmos_init_late(void *opaque)
640 {
641     pc_cmos_init_late_arg *arg = opaque;
642     ISADevice *s = arg->rtc_state;
643     int16_t cylinders;
644     int8_t heads, sectors;
645     int val;
646     int i, trans;
647
648     val = 0;
649     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 0,
650                                            &cylinders, &heads, &sectors) >= 0) {
651         cmos_init_hd(s, 0x19, 0x1b, cylinders, heads, sectors);
652         val |= 0xf0;
653     }
654     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 1,
655                                            &cylinders, &heads, &sectors) >= 0) {
656         cmos_init_hd(s, 0x1a, 0x24, cylinders, heads, sectors);
657         val |= 0x0f;
658     }
659     rtc_set_memory(s, 0x12, val);
660
661     val = 0;
662     for (i = 0; i < 4; i++) {
663         /* NOTE: ide_get_geometry() returns the physical
664            geometry.  It is always such that: 1 <= sects <= 63, 1
665            <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
666            geometry can be different if a translation is done. */
667         if (arg->idebus[i / 2] &&
668             ide_get_geometry(arg->idebus[i / 2], i % 2,
669                              &cylinders, &heads, &sectors) >= 0) {
670             trans = ide_get_bios_chs_trans(arg->idebus[i / 2], i % 2) - 1;
671             assert((trans & ~3) == 0);
672             val |= trans << (i * 2);
673         }
674     }
675     rtc_set_memory(s, 0x39, val);
676
677     pc_cmos_init_floppy(s, pc_find_fdc0());
678
679     qemu_unregister_reset(pc_cmos_init_late, opaque);
680 }
681
682 void pc_cmos_init(PCMachineState *pcms,
683                   BusState *idebus0, BusState *idebus1,
684                   ISADevice *s)
685 {
686     int val;
687     static pc_cmos_init_late_arg arg;
688     X86MachineState *x86ms = X86_MACHINE(pcms);
689
690     /* various important CMOS locations needed by PC/Bochs bios */
691
692     /* memory size */
693     /* base memory (first MiB) */
694     val = MIN(x86ms->below_4g_mem_size / KiB, 640);
695     rtc_set_memory(s, 0x15, val);
696     rtc_set_memory(s, 0x16, val >> 8);
697     /* extended memory (next 64MiB) */
698     if (x86ms->below_4g_mem_size > 1 * MiB) {
699         val = (x86ms->below_4g_mem_size - 1 * MiB) / KiB;
700     } else {
701         val = 0;
702     }
703     if (val > 65535)
704         val = 65535;
705     rtc_set_memory(s, 0x17, val);
706     rtc_set_memory(s, 0x18, val >> 8);
707     rtc_set_memory(s, 0x30, val);
708     rtc_set_memory(s, 0x31, val >> 8);
709     /* memory between 16MiB and 4GiB */
710     if (x86ms->below_4g_mem_size > 16 * MiB) {
711         val = (x86ms->below_4g_mem_size - 16 * MiB) / (64 * KiB);
712     } else {
713         val = 0;
714     }
715     if (val > 65535)
716         val = 65535;
717     rtc_set_memory(s, 0x34, val);
718     rtc_set_memory(s, 0x35, val >> 8);
719     /* memory above 4GiB */
720     val = x86ms->above_4g_mem_size / 65536;
721     rtc_set_memory(s, 0x5b, val);
722     rtc_set_memory(s, 0x5c, val >> 8);
723     rtc_set_memory(s, 0x5d, val >> 16);
724
725     object_property_add_link(OBJECT(pcms), "rtc_state",
726                              TYPE_ISA_DEVICE,
727                              (Object **)&x86ms->rtc,
728                              object_property_allow_set_link,
729                              OBJ_PROP_LINK_STRONG, &error_abort);
730     object_property_set_link(OBJECT(pcms), OBJECT(s),
731                              "rtc_state", &error_abort);
732
733     set_boot_dev(s, MACHINE(pcms)->boot_order, &error_fatal);
734
735     val = 0;
736     val |= 0x02; /* FPU is there */
737     val |= 0x04; /* PS/2 mouse installed */
738     rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);
739
740     /* hard drives and FDC */
741     arg.rtc_state = s;
742     arg.idebus[0] = idebus0;
743     arg.idebus[1] = idebus1;
744     qemu_register_reset(pc_cmos_init_late, &arg);
745 }
746
747 #define TYPE_PORT92 "port92"
748 #define PORT92(obj) OBJECT_CHECK(Port92State, (obj), TYPE_PORT92)
749
750 /* port 92 stuff: could be split off */
751 typedef struct Port92State {
752     ISADevice parent_obj;
753
754     MemoryRegion io;
755     uint8_t outport;
756     qemu_irq a20_out;
757 } Port92State;
758
759 static void port92_write(void *opaque, hwaddr addr, uint64_t val,
760                          unsigned size)
761 {
762     Port92State *s = opaque;
763     int oldval = s->outport;
764
765     DPRINTF("port92: write 0x%02" PRIx64 "\n", val);
766     s->outport = val;
767     qemu_set_irq(s->a20_out, (val >> 1) & 1);
768     if ((val & 1) && !(oldval & 1)) {
769         qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
770     }
771 }
772
773 static uint64_t port92_read(void *opaque, hwaddr addr,
774                             unsigned size)
775 {
776     Port92State *s = opaque;
777     uint32_t ret;
778
779     ret = s->outport;
780     DPRINTF("port92: read 0x%02x\n", ret);
781     return ret;
782 }
783
784 static void port92_init(ISADevice *dev, qemu_irq a20_out)
785 {
786     qdev_connect_gpio_out_named(DEVICE(dev), PORT92_A20_LINE, 0, a20_out);
787 }
788
789 static const VMStateDescription vmstate_port92_isa = {
790     .name = "port92",
791     .version_id = 1,
792     .minimum_version_id = 1,
793     .fields = (VMStateField[]) {
794         VMSTATE_UINT8(outport, Port92State),
795         VMSTATE_END_OF_LIST()
796     }
797 };
798
799 static void port92_reset(DeviceState *d)
800 {
801     Port92State *s = PORT92(d);
802
803     s->outport &= ~1;
804 }
805
806 static const MemoryRegionOps port92_ops = {
807     .read = port92_read,
808     .write = port92_write,
809     .impl = {
810         .min_access_size = 1,
811         .max_access_size = 1,
812     },
813     .endianness = DEVICE_LITTLE_ENDIAN,
814 };
815
816 static void port92_initfn(Object *obj)
817 {
818     Port92State *s = PORT92(obj);
819
820     memory_region_init_io(&s->io, OBJECT(s), &port92_ops, s, "port92", 1);
821
822     s->outport = 0;
823
824     qdev_init_gpio_out_named(DEVICE(obj), &s->a20_out, PORT92_A20_LINE, 1);
825 }
826
827 static void port92_realizefn(DeviceState *dev, Error **errp)
828 {
829     ISADevice *isadev = ISA_DEVICE(dev);
830     Port92State *s = PORT92(dev);
831
832     isa_register_ioport(isadev, &s->io, 0x92);
833 }
834
835 static void port92_class_initfn(ObjectClass *klass, void *data)
836 {
837     DeviceClass *dc = DEVICE_CLASS(klass);
838
839     dc->realize = port92_realizefn;
840     dc->reset = port92_reset;
841     dc->vmsd = &vmstate_port92_isa;
842     /*
843      * Reason: unlike ordinary ISA devices, this one needs additional
844      * wiring: its A20 output line needs to be wired up by
845      * port92_init().
846      */
847     dc->user_creatable = false;
848 }
849
850 static const TypeInfo port92_info = {
851     .name          = TYPE_PORT92,
852     .parent        = TYPE_ISA_DEVICE,
853     .instance_size = sizeof(Port92State),
854     .instance_init = port92_initfn,
855     .class_init    = port92_class_initfn,
856 };
857
858 static void port92_register_types(void)
859 {
860     type_register_static(&port92_info);
861 }
862
863 type_init(port92_register_types)
864
865 static void handle_a20_line_change(void *opaque, int irq, int level)
866 {
867     X86CPU *cpu = opaque;
868
869     /* XXX: send to all CPUs ? */
870     /* XXX: add logic to handle multiple A20 line sources */
871     x86_cpu_set_a20(cpu, level);
872 }
873
874 #define NE2000_NB_MAX 6
875
876 static const int ne2000_io[NE2000_NB_MAX] = { 0x300, 0x320, 0x340, 0x360,
877                                               0x280, 0x380 };
878 static const int ne2000_irq[NE2000_NB_MAX] = { 9, 10, 11, 3, 4, 5 };
879
880 void pc_init_ne2k_isa(ISABus *bus, NICInfo *nd)
881 {
882     static int nb_ne2k = 0;
883
884     if (nb_ne2k == NE2000_NB_MAX)
885         return;
886     isa_ne2000_init(bus, ne2000_io[nb_ne2k],
887                     ne2000_irq[nb_ne2k], nd);
888     nb_ne2k++;
889 }
890
891 DeviceState *cpu_get_current_apic(void)
892 {
893     if (current_cpu) {
894         X86CPU *cpu = X86_CPU(current_cpu);
895         return cpu->apic_state;
896     } else {
897         return NULL;
898     }
899 }
900
901 void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
902 {
903     X86CPU *cpu = opaque;
904
905     if (level) {
906         cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
907     }
908 }
909
910 /*
911  * This function is very similar to smp_parse()
912  * in hw/core/machine.c but includes CPU die support.
913  */
914 void pc_smp_parse(MachineState *ms, QemuOpts *opts)
915 {
916     X86MachineState *x86ms = X86_MACHINE(ms);
917
918     if (opts) {
919         unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
920         unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
921         unsigned dies = qemu_opt_get_number(opts, "dies", 1);
922         unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
923         unsigned threads = qemu_opt_get_number(opts, "threads", 0);
924
925         /* compute missing values, prefer sockets over cores over threads */
926         if (cpus == 0 || sockets == 0) {
927             cores = cores > 0 ? cores : 1;
928             threads = threads > 0 ? threads : 1;
929             if (cpus == 0) {
930                 sockets = sockets > 0 ? sockets : 1;
931                 cpus = cores * threads * dies * sockets;
932             } else {
933                 ms->smp.max_cpus =
934                         qemu_opt_get_number(opts, "maxcpus", cpus);
935                 sockets = ms->smp.max_cpus / (cores * threads * dies);
936             }
937         } else if (cores == 0) {
938             threads = threads > 0 ? threads : 1;
939             cores = cpus / (sockets * dies * threads);
940             cores = cores > 0 ? cores : 1;
941         } else if (threads == 0) {
942             threads = cpus / (cores * dies * sockets);
943             threads = threads > 0 ? threads : 1;
944         } else if (sockets * dies * cores * threads < cpus) {
945             error_report("cpu topology: "
946                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) < "
947                          "smp_cpus (%u)",
948                          sockets, dies, cores, threads, cpus);
949             exit(1);
950         }
951
952         ms->smp.max_cpus =
953                 qemu_opt_get_number(opts, "maxcpus", cpus);
954
955         if (ms->smp.max_cpus < cpus) {
956             error_report("maxcpus must be equal to or greater than smp");
957             exit(1);
958         }
959
960         if (sockets * dies * cores * threads > ms->smp.max_cpus) {
961             error_report("cpu topology: "
962                          "sockets (%u) * dies (%u) * cores (%u) * threads (%u) > "
963                          "maxcpus (%u)",
964                          sockets, dies, cores, threads,
965                          ms->smp.max_cpus);
966             exit(1);
967         }
968
969         if (sockets * dies * cores * threads != ms->smp.max_cpus) {
970             warn_report("Invalid CPU topology deprecated: "
971                         "sockets (%u) * dies (%u) * cores (%u) * threads (%u) "
972                         "!= maxcpus (%u)",
973                         sockets, dies, cores, threads,
974                         ms->smp.max_cpus);
975         }
976
977         ms->smp.cpus = cpus;
978         ms->smp.cores = cores;
979         ms->smp.threads = threads;
980         x86ms->smp_dies = dies;
981     }
982
983     if (ms->smp.cpus > 1) {
984         Error *blocker = NULL;
985         error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");
986         replay_add_blocker(blocker);
987     }
988 }
989
990 void pc_hot_add_cpu(MachineState *ms, const int64_t id, Error **errp)
991 {
992     X86MachineState *x86ms = X86_MACHINE(ms);
993     int64_t apic_id = x86_cpu_apic_id_from_index(x86ms, id);
994     Error *local_err = NULL;
995
996     if (id < 0) {
997         error_setg(errp, "Invalid CPU id: %" PRIi64, id);
998         return;
999     }
1000
1001     if (apic_id >= ACPI_CPU_HOTPLUG_ID_LIMIT) {
1002         error_setg(errp, "Unable to add CPU: %" PRIi64
1003                    ", resulting APIC ID (%" PRIi64 ") is too large",
1004                    id, apic_id);
1005         return;
1006     }
1007
1008
1009     x86_cpu_new(X86_MACHINE(ms), apic_id, &local_err);
1010     if (local_err) {
1011         error_propagate(errp, local_err);
1012         return;
1013     }
1014 }
1015
1016 static void rtc_set_cpus_count(ISADevice *rtc, uint16_t cpus_count)
1017 {
1018     if (cpus_count > 0xff) {
1019         /* If the number of CPUs can't be represented in 8 bits, the
1020          * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
1021          * to make old BIOSes fail more predictably.
1022          */
1023         rtc_set_memory(rtc, 0x5f, 0);
1024     } else {
1025         rtc_set_memory(rtc, 0x5f, cpus_count - 1);
1026     }
1027 }
1028
1029 static
1030 void pc_machine_done(Notifier *notifier, void *data)
1031 {
1032     PCMachineState *pcms = container_of(notifier,
1033                                         PCMachineState, machine_done);
1034     X86MachineState *x86ms = X86_MACHINE(pcms);
1035     PCIBus *bus = pcms->bus;
1036
1037     /* set the number of CPUs */
1038     rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
1039
1040     if (bus) {
1041         int extra_hosts = 0;
1042
1043         QLIST_FOREACH(bus, &bus->child, sibling) {
1044             /* look for expander root buses */
1045             if (pci_bus_is_root(bus)) {
1046                 extra_hosts++;
1047             }
1048         }
1049         if (extra_hosts && x86ms->fw_cfg) {
1050             uint64_t *val = g_malloc(sizeof(*val));
1051             *val = cpu_to_le64(extra_hosts);
1052             fw_cfg_add_file(x86ms->fw_cfg,
1053                     "etc/extra-pci-roots", val, sizeof(*val));
1054         }
1055     }
1056
1057     acpi_setup();
1058     if (x86ms->fw_cfg) {
1059         fw_cfg_build_smbios(MACHINE(pcms), x86ms->fw_cfg);
1060         fw_cfg_build_feature_control(MACHINE(pcms), x86ms->fw_cfg);
1061         /* update FW_CFG_NB_CPUS to account for -device added CPUs */
1062         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1063     }
1064
1065     if (x86ms->apic_id_limit > 255 && !xen_enabled()) {
1066         IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
1067
1068         if (!iommu || !x86_iommu_ir_supported(X86_IOMMU_DEVICE(iommu)) ||
1069             iommu->intr_eim != ON_OFF_AUTO_ON) {
1070             error_report("current -smp configuration requires "
1071                          "Extended Interrupt Mode enabled. "
1072                          "You can add an IOMMU using: "
1073                          "-device intel-iommu,intremap=on,eim=on");
1074             exit(EXIT_FAILURE);
1075         }
1076     }
1077 }
1078
1079 void pc_guest_info_init(PCMachineState *pcms)
1080 {
1081     int i;
1082     MachineState *ms = MACHINE(pcms);
1083     X86MachineState *x86ms = X86_MACHINE(pcms);
1084
1085     x86ms->apic_xrupt_override = kvm_allows_irq0_override();
1086     pcms->numa_nodes = ms->numa_state->num_nodes;
1087     pcms->node_mem = g_malloc0(pcms->numa_nodes *
1088                                     sizeof *pcms->node_mem);
1089     for (i = 0; i < ms->numa_state->num_nodes; i++) {
1090         pcms->node_mem[i] = ms->numa_state->nodes[i].node_mem;
1091     }
1092
1093     pcms->machine_done.notify = pc_machine_done;
1094     qemu_add_machine_init_done_notifier(&pcms->machine_done);
1095 }
1096
1097 /* setup pci memory address space mapping into system address space */
1098 void pc_pci_as_mapping_init(Object *owner, MemoryRegion *system_memory,
1099                             MemoryRegion *pci_address_space)
1100 {
1101     /* Set to lower priority than RAM */
1102     memory_region_add_subregion_overlap(system_memory, 0x0,
1103                                         pci_address_space, -1);
1104 }
1105
1106 void xen_load_linux(PCMachineState *pcms)
1107 {
1108     int i;
1109     FWCfgState *fw_cfg;
1110     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1111     X86MachineState *x86ms = X86_MACHINE(pcms);
1112
1113     assert(MACHINE(pcms)->kernel_filename != NULL);
1114
1115     fw_cfg = fw_cfg_init_io(FW_CFG_IO_BASE);
1116     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1117     rom_set_fw(fw_cfg);
1118
1119     x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
1120                    pcmc->pvh_enabled, pcmc->linuxboot_dma_enabled);
1121     for (i = 0; i < nb_option_roms; i++) {
1122         assert(!strcmp(option_rom[i].name, "linuxboot.bin") ||
1123                !strcmp(option_rom[i].name, "linuxboot_dma.bin") ||
1124                !strcmp(option_rom[i].name, "pvh.bin") ||
1125                !strcmp(option_rom[i].name, "multiboot.bin"));
1126         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1127     }
1128     x86ms->fw_cfg = fw_cfg;
1129 }
1130
1131 void pc_memory_init(PCMachineState *pcms,
1132                     MemoryRegion *system_memory,
1133                     MemoryRegion *rom_memory,
1134                     MemoryRegion **ram_memory)
1135 {
1136     int linux_boot, i;
1137     MemoryRegion *ram, *option_rom_mr;
1138     MemoryRegion *ram_below_4g, *ram_above_4g;
1139     FWCfgState *fw_cfg;
1140     MachineState *machine = MACHINE(pcms);
1141     MachineClass *mc = MACHINE_GET_CLASS(machine);
1142     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1143     X86MachineState *x86ms = X86_MACHINE(pcms);
1144
1145     assert(machine->ram_size == x86ms->below_4g_mem_size +
1146                                 x86ms->above_4g_mem_size);
1147
1148     linux_boot = (machine->kernel_filename != NULL);
1149
1150     /* Allocate RAM.  We allocate it as a single memory region and use
1151      * aliases to address portions of it, mostly for backwards compatibility
1152      * with older qemus that used qemu_ram_alloc().
1153      */
1154     ram = g_malloc(sizeof(*ram));
1155     memory_region_allocate_system_memory(ram, NULL, "pc.ram",
1156                                          machine->ram_size);
1157     *ram_memory = ram;
1158     ram_below_4g = g_malloc(sizeof(*ram_below_4g));
1159     memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram,
1160                              0, x86ms->below_4g_mem_size);
1161     memory_region_add_subregion(system_memory, 0, ram_below_4g);
1162     e820_add_entry(0, x86ms->below_4g_mem_size, E820_RAM);
1163     if (x86ms->above_4g_mem_size > 0) {
1164         ram_above_4g = g_malloc(sizeof(*ram_above_4g));
1165         memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g", ram,
1166                                  x86ms->below_4g_mem_size,
1167                                  x86ms->above_4g_mem_size);
1168         memory_region_add_subregion(system_memory, 0x100000000ULL,
1169                                     ram_above_4g);
1170         e820_add_entry(0x100000000ULL, x86ms->above_4g_mem_size, E820_RAM);
1171     }
1172
1173     if (!pcmc->has_reserved_memory &&
1174         (machine->ram_slots ||
1175          (machine->maxram_size > machine->ram_size))) {
1176
1177         error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",
1178                      mc->name);
1179         exit(EXIT_FAILURE);
1180     }
1181
1182     /* always allocate the device memory information */
1183     machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
1184
1185     /* initialize device memory address space */
1186     if (pcmc->has_reserved_memory &&
1187         (machine->ram_size < machine->maxram_size)) {
1188         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
1189
1190         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
1191             error_report("unsupported amount of memory slots: %"PRIu64,
1192                          machine->ram_slots);
1193             exit(EXIT_FAILURE);
1194         }
1195
1196         if (QEMU_ALIGN_UP(machine->maxram_size,
1197                           TARGET_PAGE_SIZE) != machine->maxram_size) {
1198             error_report("maximum memory size must by aligned to multiple of "
1199                          "%d bytes", TARGET_PAGE_SIZE);
1200             exit(EXIT_FAILURE);
1201         }
1202
1203         machine->device_memory->base =
1204             ROUND_UP(0x100000000ULL + x86ms->above_4g_mem_size, 1 * GiB);
1205
1206         if (pcmc->enforce_aligned_dimm) {
1207             /* size device region assuming 1G page max alignment per slot */
1208             device_mem_size += (1 * GiB) * machine->ram_slots;
1209         }
1210
1211         if ((machine->device_memory->base + device_mem_size) <
1212             device_mem_size) {
1213             error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,
1214                          machine->maxram_size);
1215             exit(EXIT_FAILURE);
1216         }
1217
1218         memory_region_init(&machine->device_memory->mr, OBJECT(pcms),
1219                            "device-memory", device_mem_size);
1220         memory_region_add_subregion(system_memory, machine->device_memory->base,
1221                                     &machine->device_memory->mr);
1222     }
1223
1224     /* Initialize PC system firmware */
1225     pc_system_firmware_init(pcms, rom_memory);
1226
1227     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
1228     memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
1229                            &error_fatal);
1230     if (pcmc->pci_enabled) {
1231         memory_region_set_readonly(option_rom_mr, true);
1232     }
1233     memory_region_add_subregion_overlap(rom_memory,
1234                                         PC_ROM_MIN_VGA,
1235                                         option_rom_mr,
1236                                         1);
1237
1238     fw_cfg = fw_cfg_arch_create(machine,
1239                                 x86ms->boot_cpus, x86ms->apic_id_limit);
1240
1241     rom_set_fw(fw_cfg);
1242
1243     if (pcmc->has_reserved_memory && machine->device_memory->base) {
1244         uint64_t *val = g_malloc(sizeof(*val));
1245         PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1246         uint64_t res_mem_end = machine->device_memory->base;
1247
1248         if (!pcmc->broken_reserved_end) {
1249             res_mem_end += memory_region_size(&machine->device_memory->mr);
1250         }
1251         *val = cpu_to_le64(ROUND_UP(res_mem_end, 1 * GiB));
1252         fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));
1253     }
1254
1255     if (linux_boot) {
1256         x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
1257                        pcmc->pvh_enabled, pcmc->linuxboot_dma_enabled);
1258     }
1259
1260     for (i = 0; i < nb_option_roms; i++) {
1261         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1262     }
1263     x86ms->fw_cfg = fw_cfg;
1264
1265     /* Init default IOAPIC address space */
1266     x86ms->ioapic_as = &address_space_memory;
1267
1268     /* Init ACPI memory hotplug IO base address */
1269     pcms->memhp_io_base = ACPI_MEMORY_HOTPLUG_BASE;
1270 }
1271
1272 /*
1273  * The 64bit pci hole starts after "above 4G RAM" and
1274  * potentially the space reserved for memory hotplug.
1275  */
1276 uint64_t pc_pci_hole64_start(void)
1277 {
1278     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
1279     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1280     MachineState *ms = MACHINE(pcms);
1281     X86MachineState *x86ms = X86_MACHINE(pcms);
1282     uint64_t hole64_start = 0;
1283
1284     if (pcmc->has_reserved_memory && ms->device_memory->base) {
1285         hole64_start = ms->device_memory->base;
1286         if (!pcmc->broken_reserved_end) {
1287             hole64_start += memory_region_size(&ms->device_memory->mr);
1288         }
1289     } else {
1290         hole64_start = 0x100000000ULL + x86ms->above_4g_mem_size;
1291     }
1292
1293     return ROUND_UP(hole64_start, 1 * GiB);
1294 }
1295
1296 qemu_irq pc_allocate_cpu_irq(void)
1297 {
1298     return qemu_allocate_irq(pic_irq_request, NULL, 0);
1299 }
1300
1301 DeviceState *pc_vga_init(ISABus *isa_bus, PCIBus *pci_bus)
1302 {
1303     DeviceState *dev = NULL;
1304
1305     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_VGA);
1306     if (pci_bus) {
1307         PCIDevice *pcidev = pci_vga_init(pci_bus);
1308         dev = pcidev ? &pcidev->qdev : NULL;
1309     } else if (isa_bus) {
1310         ISADevice *isadev = isa_vga_init(isa_bus);
1311         dev = isadev ? DEVICE(isadev) : NULL;
1312     }
1313     rom_reset_order_override();
1314     return dev;
1315 }
1316
1317 static const MemoryRegionOps ioport80_io_ops = {
1318     .write = ioport80_write,
1319     .read = ioport80_read,
1320     .endianness = DEVICE_NATIVE_ENDIAN,
1321     .impl = {
1322         .min_access_size = 1,
1323         .max_access_size = 1,
1324     },
1325 };
1326
1327 static const MemoryRegionOps ioportF0_io_ops = {
1328     .write = ioportF0_write,
1329     .read = ioportF0_read,
1330     .endianness = DEVICE_NATIVE_ENDIAN,
1331     .impl = {
1332         .min_access_size = 1,
1333         .max_access_size = 1,
1334     },
1335 };
1336
1337 static void pc_superio_init(ISABus *isa_bus, bool create_fdctrl, bool no_vmport)
1338 {
1339     int i;
1340     DriveInfo *fd[MAX_FD];
1341     qemu_irq *a20_line;
1342     ISADevice *i8042, *port92, *vmmouse;
1343
1344     serial_hds_isa_init(isa_bus, 0, MAX_ISA_SERIAL_PORTS);
1345     parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);
1346
1347     for (i = 0; i < MAX_FD; i++) {
1348         fd[i] = drive_get(IF_FLOPPY, 0, i);
1349         create_fdctrl |= !!fd[i];
1350     }
1351     if (create_fdctrl) {
1352         fdctrl_init_isa(isa_bus, fd);
1353     }
1354
1355     i8042 = isa_create_simple(isa_bus, "i8042");
1356     if (!no_vmport) {
1357         vmport_init(isa_bus);
1358         vmmouse = isa_try_create(isa_bus, "vmmouse");
1359     } else {
1360         vmmouse = NULL;
1361     }
1362     if (vmmouse) {
1363         DeviceState *dev = DEVICE(vmmouse);
1364         qdev_prop_set_ptr(dev, "ps2_mouse", i8042);
1365         qdev_init_nofail(dev);
1366     }
1367     port92 = isa_create_simple(isa_bus, "port92");
1368
1369     a20_line = qemu_allocate_irqs(handle_a20_line_change, first_cpu, 2);
1370     i8042_setup_a20_line(i8042, a20_line[0]);
1371     port92_init(port92, a20_line[1]);
1372     g_free(a20_line);
1373 }
1374
1375 void pc_basic_device_init(ISABus *isa_bus, qemu_irq *gsi,
1376                           ISADevice **rtc_state,
1377                           bool create_fdctrl,
1378                           bool no_vmport,
1379                           bool has_pit,
1380                           uint32_t hpet_irqs)
1381 {
1382     int i;
1383     DeviceState *hpet = NULL;
1384     int pit_isa_irq = 0;
1385     qemu_irq pit_alt_irq = NULL;
1386     qemu_irq rtc_irq = NULL;
1387     ISADevice *pit = NULL;
1388     MemoryRegion *ioport80_io = g_new(MemoryRegion, 1);
1389     MemoryRegion *ioportF0_io = g_new(MemoryRegion, 1);
1390
1391     memory_region_init_io(ioport80_io, NULL, &ioport80_io_ops, NULL, "ioport80", 1);
1392     memory_region_add_subregion(isa_bus->address_space_io, 0x80, ioport80_io);
1393
1394     memory_region_init_io(ioportF0_io, NULL, &ioportF0_io_ops, NULL, "ioportF0", 1);
1395     memory_region_add_subregion(isa_bus->address_space_io, 0xf0, ioportF0_io);
1396
1397     /*
1398      * Check if an HPET shall be created.
1399      *
1400      * Without KVM_CAP_PIT_STATE2, we cannot switch off the in-kernel PIT
1401      * when the HPET wants to take over. Thus we have to disable the latter.
1402      */
1403     if (!no_hpet && (!kvm_irqchip_in_kernel() || kvm_has_pit_state2())) {
1404         /* In order to set property, here not using sysbus_try_create_simple */
1405         hpet = qdev_try_create(NULL, TYPE_HPET);
1406         if (hpet) {
1407             /* For pc-piix-*, hpet's intcap is always IRQ2. For pc-q35-1.7
1408              * and earlier, use IRQ2 for compat. Otherwise, use IRQ16~23,
1409              * IRQ8 and IRQ2.
1410              */
1411             uint8_t compat = object_property_get_uint(OBJECT(hpet),
1412                     HPET_INTCAP, NULL);
1413             if (!compat) {
1414                 qdev_prop_set_uint32(hpet, HPET_INTCAP, hpet_irqs);
1415             }
1416             qdev_init_nofail(hpet);
1417             sysbus_mmio_map(SYS_BUS_DEVICE(hpet), 0, HPET_BASE);
1418
1419             for (i = 0; i < GSI_NUM_PINS; i++) {
1420                 sysbus_connect_irq(SYS_BUS_DEVICE(hpet), i, gsi[i]);
1421             }
1422             pit_isa_irq = -1;
1423             pit_alt_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_PIT_INT);
1424             rtc_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_RTC_INT);
1425         }
1426     }
1427     *rtc_state = mc146818_rtc_init(isa_bus, 2000, rtc_irq);
1428
1429     qemu_register_boot_set(pc_boot_set, *rtc_state);
1430
1431     if (!xen_enabled() && has_pit) {
1432         if (kvm_pit_in_kernel()) {
1433             pit = kvm_pit_init(isa_bus, 0x40);
1434         } else {
1435             pit = i8254_pit_init(isa_bus, 0x40, pit_isa_irq, pit_alt_irq);
1436         }
1437         if (hpet) {
1438             /* connect PIT to output control line of the HPET */
1439             qdev_connect_gpio_out(hpet, 0, qdev_get_gpio_in(DEVICE(pit), 0));
1440         }
1441         pcspk_init(isa_bus, pit);
1442     }
1443
1444     i8257_dma_init(isa_bus, 0);
1445
1446     /* Super I/O */
1447     pc_superio_init(isa_bus, create_fdctrl, no_vmport);
1448 }
1449
1450 void pc_nic_init(PCMachineClass *pcmc, ISABus *isa_bus, PCIBus *pci_bus)
1451 {
1452     int i;
1453
1454     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_NIC);
1455     for (i = 0; i < nb_nics; i++) {
1456         NICInfo *nd = &nd_table[i];
1457         const char *model = nd->model ? nd->model : pcmc->default_nic_model;
1458
1459         if (g_str_equal(model, "ne2k_isa")) {
1460             pc_init_ne2k_isa(isa_bus, nd);
1461         } else {
1462             pci_nic_init_nofail(nd, pci_bus, model, NULL);
1463         }
1464     }
1465     rom_reset_order_override();
1466 }
1467
1468 void pc_i8259_create(ISABus *isa_bus, qemu_irq *i8259_irqs)
1469 {
1470     qemu_irq *i8259;
1471
1472     if (kvm_pic_in_kernel()) {
1473         i8259 = kvm_i8259_init(isa_bus);
1474     } else if (xen_enabled()) {
1475         i8259 = xen_interrupt_controller_init();
1476     } else {
1477         i8259 = i8259_init(isa_bus, pc_allocate_cpu_irq());
1478     }
1479
1480     for (size_t i = 0; i < ISA_NUM_IRQS; i++) {
1481         i8259_irqs[i] = i8259[i];
1482     }
1483
1484     g_free(i8259);
1485 }
1486
1487 void ioapic_init_gsi(GSIState *gsi_state, const char *parent_name)
1488 {
1489     DeviceState *dev;
1490     SysBusDevice *d;
1491     unsigned int i;
1492
1493     if (kvm_ioapic_in_kernel()) {
1494         dev = qdev_create(NULL, TYPE_KVM_IOAPIC);
1495     } else {
1496         dev = qdev_create(NULL, TYPE_IOAPIC);
1497     }
1498     if (parent_name) {
1499         object_property_add_child(object_resolve_path(parent_name, NULL),
1500                                   "ioapic", OBJECT(dev), NULL);
1501     }
1502     qdev_init_nofail(dev);
1503     d = SYS_BUS_DEVICE(dev);
1504     sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
1505
1506     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
1507         gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
1508     }
1509 }
1510
1511 static void pc_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
1512                                Error **errp)
1513 {
1514     const PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1515     const PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1516     const MachineState *ms = MACHINE(hotplug_dev);
1517     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1518     const uint64_t legacy_align = TARGET_PAGE_SIZE;
1519     Error *local_err = NULL;
1520
1521     /*
1522      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1523      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1524      * addition to cover this case.
1525      */
1526     if (!pcms->acpi_dev || !acpi_enabled) {
1527         error_setg(errp,
1528                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1529         return;
1530     }
1531
1532     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
1533         error_setg(errp, "nvdimm is not enabled: missing 'nvdimm' in '-M'");
1534         return;
1535     }
1536
1537     hotplug_handler_pre_plug(pcms->acpi_dev, dev, &local_err);
1538     if (local_err) {
1539         error_propagate(errp, local_err);
1540         return;
1541     }
1542
1543     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev),
1544                      pcmc->enforce_aligned_dimm ? NULL : &legacy_align, errp);
1545 }
1546
1547 static void pc_memory_plug(HotplugHandler *hotplug_dev,
1548                            DeviceState *dev, Error **errp)
1549 {
1550     Error *local_err = NULL;
1551     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1552     MachineState *ms = MACHINE(hotplug_dev);
1553     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1554
1555     pc_dimm_plug(PC_DIMM(dev), MACHINE(pcms), &local_err);
1556     if (local_err) {
1557         goto out;
1558     }
1559
1560     if (is_nvdimm) {
1561         nvdimm_plug(ms->nvdimms_state);
1562     }
1563
1564     hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &error_abort);
1565 out:
1566     error_propagate(errp, local_err);
1567 }
1568
1569 static void pc_memory_unplug_request(HotplugHandler *hotplug_dev,
1570                                      DeviceState *dev, Error **errp)
1571 {
1572     Error *local_err = NULL;
1573     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1574
1575     /*
1576      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1577      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1578      * addition to cover this case.
1579      */
1580     if (!pcms->acpi_dev || !acpi_enabled) {
1581         error_setg(&local_err,
1582                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1583         goto out;
1584     }
1585
1586     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
1587         error_setg(&local_err,
1588                    "nvdimm device hot unplug is not supported yet.");
1589         goto out;
1590     }
1591
1592     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
1593                                    &local_err);
1594 out:
1595     error_propagate(errp, local_err);
1596 }
1597
1598 static void pc_memory_unplug(HotplugHandler *hotplug_dev,
1599                              DeviceState *dev, Error **errp)
1600 {
1601     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1602     Error *local_err = NULL;
1603
1604     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1605     if (local_err) {
1606         goto out;
1607     }
1608
1609     pc_dimm_unplug(PC_DIMM(dev), MACHINE(pcms));
1610     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
1611  out:
1612     error_propagate(errp, local_err);
1613 }
1614
1615 static int pc_apic_cmp(const void *a, const void *b)
1616 {
1617    CPUArchId *apic_a = (CPUArchId *)a;
1618    CPUArchId *apic_b = (CPUArchId *)b;
1619
1620    return apic_a->arch_id - apic_b->arch_id;
1621 }
1622
1623 /* returns pointer to CPUArchId descriptor that matches CPU's apic_id
1624  * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
1625  * entry corresponding to CPU's apic_id returns NULL.
1626  */
1627 static CPUArchId *pc_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
1628 {
1629     CPUArchId apic_id, *found_cpu;
1630
1631     apic_id.arch_id = id;
1632     found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
1633         ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
1634         pc_apic_cmp);
1635     if (found_cpu && idx) {
1636         *idx = found_cpu - ms->possible_cpus->cpus;
1637     }
1638     return found_cpu;
1639 }
1640
1641 static void pc_cpu_plug(HotplugHandler *hotplug_dev,
1642                         DeviceState *dev, Error **errp)
1643 {
1644     CPUArchId *found_cpu;
1645     Error *local_err = NULL;
1646     X86CPU *cpu = X86_CPU(dev);
1647     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1648     X86MachineState *x86ms = X86_MACHINE(pcms);
1649
1650     if (pcms->acpi_dev) {
1651         hotplug_handler_plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1652         if (local_err) {
1653             goto out;
1654         }
1655     }
1656
1657     /* increment the number of CPUs */
1658     x86ms->boot_cpus++;
1659     if (x86ms->rtc) {
1660         rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
1661     }
1662     if (x86ms->fw_cfg) {
1663         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1664     }
1665
1666     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
1667     found_cpu->cpu = OBJECT(dev);
1668 out:
1669     error_propagate(errp, local_err);
1670 }
1671 static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
1672                                      DeviceState *dev, Error **errp)
1673 {
1674     int idx = -1;
1675     Error *local_err = NULL;
1676     X86CPU *cpu = X86_CPU(dev);
1677     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1678
1679     if (!pcms->acpi_dev) {
1680         error_setg(&local_err, "CPU hot unplug not supported without ACPI");
1681         goto out;
1682     }
1683
1684     pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
1685     assert(idx != -1);
1686     if (idx == 0) {
1687         error_setg(&local_err, "Boot CPU is unpluggable");
1688         goto out;
1689     }
1690
1691     hotplug_handler_unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev,
1692                                    &local_err);
1693     if (local_err) {
1694         goto out;
1695     }
1696
1697  out:
1698     error_propagate(errp, local_err);
1699
1700 }
1701
1702 static void pc_cpu_unplug_cb(HotplugHandler *hotplug_dev,
1703                              DeviceState *dev, Error **errp)
1704 {
1705     CPUArchId *found_cpu;
1706     Error *local_err = NULL;
1707     X86CPU *cpu = X86_CPU(dev);
1708     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1709     X86MachineState *x86ms = X86_MACHINE(pcms);
1710
1711     hotplug_handler_unplug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
1712     if (local_err) {
1713         goto out;
1714     }
1715
1716     found_cpu = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, NULL);
1717     found_cpu->cpu = NULL;
1718     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
1719
1720     /* decrement the number of CPUs */
1721     x86ms->boot_cpus--;
1722     /* Update the number of CPUs in CMOS */
1723     rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
1724     fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
1725  out:
1726     error_propagate(errp, local_err);
1727 }
1728
1729 static void pc_cpu_pre_plug(HotplugHandler *hotplug_dev,
1730                             DeviceState *dev, Error **errp)
1731 {
1732     int idx;
1733     CPUState *cs;
1734     CPUArchId *cpu_slot;
1735     X86CPUTopoInfo topo;
1736     X86CPU *cpu = X86_CPU(dev);
1737     CPUX86State *env = &cpu->env;
1738     MachineState *ms = MACHINE(hotplug_dev);
1739     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1740     X86MachineState *x86ms = X86_MACHINE(pcms);
1741     unsigned int smp_cores = ms->smp.cores;
1742     unsigned int smp_threads = ms->smp.threads;
1743
1744     if(!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
1745         error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
1746                    ms->cpu_type);
1747         return;
1748     }
1749
1750     env->nr_dies = x86ms->smp_dies;
1751
1752     /*
1753      * If APIC ID is not set,
1754      * set it based on socket/die/core/thread properties.
1755      */
1756     if (cpu->apic_id == UNASSIGNED_APIC_ID) {
1757         int max_socket = (ms->smp.max_cpus - 1) /
1758                                 smp_threads / smp_cores / x86ms->smp_dies;
1759
1760         /*
1761          * die-id was optional in QEMU 4.0 and older, so keep it optional
1762          * if there's only one die per socket.
1763          */
1764         if (cpu->die_id < 0 && x86ms->smp_dies == 1) {
1765             cpu->die_id = 0;
1766         }
1767
1768         if (cpu->socket_id < 0) {
1769             error_setg(errp, "CPU socket-id is not set");
1770             return;
1771         } else if (cpu->socket_id > max_socket) {
1772             error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
1773                        cpu->socket_id, max_socket);
1774             return;
1775         }
1776         if (cpu->die_id < 0) {
1777             error_setg(errp, "CPU die-id is not set");
1778             return;
1779         } else if (cpu->die_id > x86ms->smp_dies - 1) {
1780             error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
1781                        cpu->die_id, x86ms->smp_dies - 1);
1782             return;
1783         }
1784         if (cpu->core_id < 0) {
1785             error_setg(errp, "CPU core-id is not set");
1786             return;
1787         } else if (cpu->core_id > (smp_cores - 1)) {
1788             error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
1789                        cpu->core_id, smp_cores - 1);
1790             return;
1791         }
1792         if (cpu->thread_id < 0) {
1793             error_setg(errp, "CPU thread-id is not set");
1794             return;
1795         } else if (cpu->thread_id > (smp_threads - 1)) {
1796             error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
1797                        cpu->thread_id, smp_threads - 1);
1798             return;
1799         }
1800
1801         topo.pkg_id = cpu->socket_id;
1802         topo.die_id = cpu->die_id;
1803         topo.core_id = cpu->core_id;
1804         topo.smt_id = cpu->thread_id;
1805         cpu->apic_id = apicid_from_topo_ids(x86ms->smp_dies, smp_cores,
1806                                             smp_threads, &topo);
1807     }
1808
1809     cpu_slot = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
1810     if (!cpu_slot) {
1811         MachineState *ms = MACHINE(pcms);
1812
1813         x86_topo_ids_from_apicid(cpu->apic_id, x86ms->smp_dies,
1814                                  smp_cores, smp_threads, &topo);
1815         error_setg(errp,
1816             "Invalid CPU [socket: %u, die: %u, core: %u, thread: %u] with"
1817             " APIC ID %" PRIu32 ", valid index range 0:%d",
1818             topo.pkg_id, topo.die_id, topo.core_id, topo.smt_id,
1819             cpu->apic_id, ms->possible_cpus->len - 1);
1820         return;
1821     }
1822
1823     if (cpu_slot->cpu) {
1824         error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
1825                    idx, cpu->apic_id);
1826         return;
1827     }
1828
1829     /* if 'address' properties socket-id/core-id/thread-id are not set, set them
1830      * so that machine_query_hotpluggable_cpus would show correct values
1831      */
1832     /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
1833      * once -smp refactoring is complete and there will be CPU private
1834      * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
1835     x86_topo_ids_from_apicid(cpu->apic_id, x86ms->smp_dies,
1836                              smp_cores, smp_threads, &topo);
1837     if (cpu->socket_id != -1 && cpu->socket_id != topo.pkg_id) {
1838         error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
1839             " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id, topo.pkg_id);
1840         return;
1841     }
1842     cpu->socket_id = topo.pkg_id;
1843
1844     if (cpu->die_id != -1 && cpu->die_id != topo.die_id) {
1845         error_setg(errp, "property die-id: %u doesn't match set apic-id:"
1846             " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo.die_id);
1847         return;
1848     }
1849     cpu->die_id = topo.die_id;
1850
1851     if (cpu->core_id != -1 && cpu->core_id != topo.core_id) {
1852         error_setg(errp, "property core-id: %u doesn't match set apic-id:"
1853             " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id, topo.core_id);
1854         return;
1855     }
1856     cpu->core_id = topo.core_id;
1857
1858     if (cpu->thread_id != -1 && cpu->thread_id != topo.smt_id) {
1859         error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
1860             " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id, topo.smt_id);
1861         return;
1862     }
1863     cpu->thread_id = topo.smt_id;
1864
1865     if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
1866         !kvm_hv_vpindex_settable()) {
1867         error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
1868         return;
1869     }
1870
1871     cs = CPU(cpu);
1872     cs->cpu_index = idx;
1873
1874     numa_cpu_pre_plug(cpu_slot, dev, errp);
1875 }
1876
1877 static void pc_virtio_pmem_pci_pre_plug(HotplugHandler *hotplug_dev,
1878                                         DeviceState *dev, Error **errp)
1879 {
1880     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1881     Error *local_err = NULL;
1882
1883     if (!hotplug_dev2) {
1884         /*
1885          * Without a bus hotplug handler, we cannot control the plug/unplug
1886          * order. This should never be the case on x86, however better add
1887          * a safety net.
1888          */
1889         error_setg(errp, "virtio-pmem-pci not supported on this bus.");
1890         return;
1891     }
1892     /*
1893      * First, see if we can plug this memory device at all. If that
1894      * succeeds, branch of to the actual hotplug handler.
1895      */
1896     memory_device_pre_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev), NULL,
1897                            &local_err);
1898     if (!local_err) {
1899         hotplug_handler_pre_plug(hotplug_dev2, dev, &local_err);
1900     }
1901     error_propagate(errp, local_err);
1902 }
1903
1904 static void pc_virtio_pmem_pci_plug(HotplugHandler *hotplug_dev,
1905                                     DeviceState *dev, Error **errp)
1906 {
1907     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1908     Error *local_err = NULL;
1909
1910     /*
1911      * Plug the memory device first and then branch off to the actual
1912      * hotplug handler. If that one fails, we can easily undo the memory
1913      * device bits.
1914      */
1915     memory_device_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1916     hotplug_handler_plug(hotplug_dev2, dev, &local_err);
1917     if (local_err) {
1918         memory_device_unplug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1919     }
1920     error_propagate(errp, local_err);
1921 }
1922
1923 static void pc_virtio_pmem_pci_unplug_request(HotplugHandler *hotplug_dev,
1924                                               DeviceState *dev, Error **errp)
1925 {
1926     /* We don't support virtio pmem hot unplug */
1927     error_setg(errp, "virtio pmem device unplug not supported.");
1928 }
1929
1930 static void pc_virtio_pmem_pci_unplug(HotplugHandler *hotplug_dev,
1931                                       DeviceState *dev, Error **errp)
1932 {
1933     /* We don't support virtio pmem hot unplug */
1934 }
1935
1936 static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
1937                                           DeviceState *dev, Error **errp)
1938 {
1939     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1940         pc_memory_pre_plug(hotplug_dev, dev, errp);
1941     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1942         pc_cpu_pre_plug(hotplug_dev, dev, errp);
1943     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1944         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
1945     }
1946 }
1947
1948 static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
1949                                       DeviceState *dev, Error **errp)
1950 {
1951     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1952         pc_memory_plug(hotplug_dev, dev, errp);
1953     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1954         pc_cpu_plug(hotplug_dev, dev, errp);
1955     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1956         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
1957     }
1958 }
1959
1960 static void pc_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
1961                                                 DeviceState *dev, Error **errp)
1962 {
1963     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1964         pc_memory_unplug_request(hotplug_dev, dev, errp);
1965     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1966         pc_cpu_unplug_request_cb(hotplug_dev, dev, errp);
1967     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1968         pc_virtio_pmem_pci_unplug_request(hotplug_dev, dev, errp);
1969     } else {
1970         error_setg(errp, "acpi: device unplug request for not supported device"
1971                    " type: %s", object_get_typename(OBJECT(dev)));
1972     }
1973 }
1974
1975 static void pc_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
1976                                         DeviceState *dev, Error **errp)
1977 {
1978     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1979         pc_memory_unplug(hotplug_dev, dev, errp);
1980     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1981         pc_cpu_unplug_cb(hotplug_dev, dev, errp);
1982     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1983         pc_virtio_pmem_pci_unplug(hotplug_dev, dev, errp);
1984     } else {
1985         error_setg(errp, "acpi: device unplug for not supported device"
1986                    " type: %s", object_get_typename(OBJECT(dev)));
1987     }
1988 }
1989
1990 static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
1991                                              DeviceState *dev)
1992 {
1993     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
1994         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
1995         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
1996         return HOTPLUG_HANDLER(machine);
1997     }
1998
1999     return NULL;
2000 }
2001
2002 static void
2003 pc_machine_get_device_memory_region_size(Object *obj, Visitor *v,
2004                                          const char *name, void *opaque,
2005                                          Error **errp)
2006 {
2007     MachineState *ms = MACHINE(obj);
2008     int64_t value = 0;
2009
2010     if (ms->device_memory) {
2011         value = memory_region_size(&ms->device_memory->mr);
2012     }
2013
2014     visit_type_int(v, name, &value, errp);
2015 }
2016
2017 static void pc_machine_get_vmport(Object *obj, Visitor *v, const char *name,
2018                                   void *opaque, Error **errp)
2019 {
2020     PCMachineState *pcms = PC_MACHINE(obj);
2021     OnOffAuto vmport = pcms->vmport;
2022
2023     visit_type_OnOffAuto(v, name, &vmport, errp);
2024 }
2025
2026 static void pc_machine_set_vmport(Object *obj, Visitor *v, const char *name,
2027                                   void *opaque, Error **errp)
2028 {
2029     PCMachineState *pcms = PC_MACHINE(obj);
2030
2031     visit_type_OnOffAuto(v, name, &pcms->vmport, errp);
2032 }
2033
2034 static bool pc_machine_get_smbus(Object *obj, Error **errp)
2035 {
2036     PCMachineState *pcms = PC_MACHINE(obj);
2037
2038     return pcms->smbus_enabled;
2039 }
2040
2041 static void pc_machine_set_smbus(Object *obj, bool value, Error **errp)
2042 {
2043     PCMachineState *pcms = PC_MACHINE(obj);
2044
2045     pcms->smbus_enabled = value;
2046 }
2047
2048 static bool pc_machine_get_sata(Object *obj, Error **errp)
2049 {
2050     PCMachineState *pcms = PC_MACHINE(obj);
2051
2052     return pcms->sata_enabled;
2053 }
2054
2055 static void pc_machine_set_sata(Object *obj, bool value, Error **errp)
2056 {
2057     PCMachineState *pcms = PC_MACHINE(obj);
2058
2059     pcms->sata_enabled = value;
2060 }
2061
2062 static bool pc_machine_get_pit(Object *obj, Error **errp)
2063 {
2064     PCMachineState *pcms = PC_MACHINE(obj);
2065
2066     return pcms->pit_enabled;
2067 }
2068
2069 static void pc_machine_set_pit(Object *obj, bool value, Error **errp)
2070 {
2071     PCMachineState *pcms = PC_MACHINE(obj);
2072
2073     pcms->pit_enabled = value;
2074 }
2075
2076 static void pc_machine_initfn(Object *obj)
2077 {
2078     PCMachineState *pcms = PC_MACHINE(obj);
2079
2080 #ifdef CONFIG_VMPORT
2081     pcms->vmport = ON_OFF_AUTO_AUTO;
2082 #else
2083     pcms->vmport = ON_OFF_AUTO_OFF;
2084 #endif /* CONFIG_VMPORT */
2085     /* acpi build is enabled by default if machine supports it */
2086     pcms->acpi_build_enabled = PC_MACHINE_GET_CLASS(pcms)->has_acpi_build;
2087     pcms->smbus_enabled = true;
2088     pcms->sata_enabled = true;
2089     pcms->pit_enabled = true;
2090
2091     pc_system_flash_create(pcms);
2092 }
2093
2094 static void pc_machine_reset(MachineState *machine)
2095 {
2096     CPUState *cs;
2097     X86CPU *cpu;
2098
2099     qemu_devices_reset();
2100
2101     /* Reset APIC after devices have been reset to cancel
2102      * any changes that qemu_devices_reset() might have done.
2103      */
2104     CPU_FOREACH(cs) {
2105         cpu = X86_CPU(cs);
2106
2107         if (cpu->apic_state) {
2108             device_reset(cpu->apic_state);
2109         }
2110     }
2111 }
2112
2113 static void pc_machine_wakeup(MachineState *machine)
2114 {
2115     cpu_synchronize_all_states();
2116     pc_machine_reset(machine);
2117     cpu_synchronize_all_post_reset();
2118 }
2119
2120 static bool pc_hotplug_allowed(MachineState *ms, DeviceState *dev, Error **errp)
2121 {
2122     X86IOMMUState *iommu = x86_iommu_get_default();
2123     IntelIOMMUState *intel_iommu;
2124
2125     if (iommu &&
2126         object_dynamic_cast((Object *)iommu, TYPE_INTEL_IOMMU_DEVICE) &&
2127         object_dynamic_cast((Object *)dev, "vfio-pci")) {
2128         intel_iommu = INTEL_IOMMU_DEVICE(iommu);
2129         if (!intel_iommu->caching_mode) {
2130             error_setg(errp, "Device assignment is not allowed without "
2131                        "enabling caching-mode=on for Intel IOMMU.");
2132             return false;
2133         }
2134     }
2135
2136     return true;
2137 }
2138
2139 static void pc_machine_class_init(ObjectClass *oc, void *data)
2140 {
2141     MachineClass *mc = MACHINE_CLASS(oc);
2142     PCMachineClass *pcmc = PC_MACHINE_CLASS(oc);
2143     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
2144
2145     pcmc->pci_enabled = true;
2146     pcmc->has_acpi_build = true;
2147     pcmc->rsdp_in_ram = true;
2148     pcmc->smbios_defaults = true;
2149     pcmc->smbios_uuid_encoded = true;
2150     pcmc->gigabyte_align = true;
2151     pcmc->has_reserved_memory = true;
2152     pcmc->kvmclock_enabled = true;
2153     pcmc->enforce_aligned_dimm = true;
2154     /* BIOS ACPI tables: 128K. Other BIOS datastructures: less than 4K reported
2155      * to be used at the moment, 32K should be enough for a while.  */
2156     pcmc->acpi_data_size = 0x20000 + 0x8000;
2157     pcmc->linuxboot_dma_enabled = true;
2158     pcmc->pvh_enabled = true;
2159     assert(!mc->get_hotplug_handler);
2160     mc->get_hotplug_handler = pc_get_hotplug_handler;
2161     mc->hotplug_allowed = pc_hotplug_allowed;
2162     mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
2163     mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
2164     mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
2165     mc->auto_enable_numa_with_memhp = true;
2166     mc->has_hotpluggable_cpus = true;
2167     mc->default_boot_order = "cad";
2168     mc->hot_add_cpu = pc_hot_add_cpu;
2169     mc->smp_parse = pc_smp_parse;
2170     mc->block_default_type = IF_IDE;
2171     mc->max_cpus = 255;
2172     mc->reset = pc_machine_reset;
2173     mc->wakeup = pc_machine_wakeup;
2174     hc->pre_plug = pc_machine_device_pre_plug_cb;
2175     hc->plug = pc_machine_device_plug_cb;
2176     hc->unplug_request = pc_machine_device_unplug_request_cb;
2177     hc->unplug = pc_machine_device_unplug_cb;
2178     mc->default_cpu_type = TARGET_DEFAULT_CPU_TYPE;
2179     mc->nvdimm_supported = true;
2180     mc->numa_mem_supported = true;
2181
2182     object_class_property_add(oc, PC_MACHINE_DEVMEM_REGION_SIZE, "int",
2183         pc_machine_get_device_memory_region_size, NULL,
2184         NULL, NULL, &error_abort);
2185
2186     object_class_property_add(oc, PC_MACHINE_VMPORT, "OnOffAuto",
2187         pc_machine_get_vmport, pc_machine_set_vmport,
2188         NULL, NULL, &error_abort);
2189     object_class_property_set_description(oc, PC_MACHINE_VMPORT,
2190         "Enable vmport (pc & q35)", &error_abort);
2191
2192     object_class_property_add_bool(oc, PC_MACHINE_SMBUS,
2193         pc_machine_get_smbus, pc_machine_set_smbus, &error_abort);
2194
2195     object_class_property_add_bool(oc, PC_MACHINE_SATA,
2196         pc_machine_get_sata, pc_machine_set_sata, &error_abort);
2197
2198     object_class_property_add_bool(oc, PC_MACHINE_PIT,
2199         pc_machine_get_pit, pc_machine_set_pit, &error_abort);
2200 }
2201
2202 static const TypeInfo pc_machine_info = {
2203     .name = TYPE_PC_MACHINE,
2204     .parent = TYPE_X86_MACHINE,
2205     .abstract = true,
2206     .instance_size = sizeof(PCMachineState),
2207     .instance_init = pc_machine_initfn,
2208     .class_size = sizeof(PCMachineClass),
2209     .class_init = pc_machine_class_init,
2210     .interfaces = (InterfaceInfo[]) {
2211          { TYPE_HOTPLUG_HANDLER },
2212          { }
2213     },
2214 };
2215
2216 static void pc_machine_register_types(void)
2217 {
2218     type_register_static(&pc_machine_info);
2219 }
2220
2221 type_init(pc_machine_register_types)
This page took 0.141128 seconds and 4 git commands to generate.