OSDN Git Service

hw/xen: Add xen_gnttab device for grant table emulation
[qmiga/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/topology.h"
32 #include "hw/i386/fw_cfg.h"
33 #include "hw/i386/vmport.h"
34 #include "sysemu/cpus.h"
35 #include "hw/block/fdc.h"
36 #include "hw/ide/internal.h"
37 #include "hw/ide/isa.h"
38 #include "hw/pci/pci.h"
39 #include "hw/pci/pci_bus.h"
40 #include "hw/pci-bridge/pci_expander_bridge.h"
41 #include "hw/nvram/fw_cfg.h"
42 #include "hw/timer/hpet.h"
43 #include "hw/firmware/smbios.h"
44 #include "hw/loader.h"
45 #include "elf.h"
46 #include "migration/vmstate.h"
47 #include "multiboot.h"
48 #include "hw/rtc/mc146818rtc.h"
49 #include "hw/intc/i8259.h"
50 #include "hw/intc/ioapic.h"
51 #include "hw/timer/i8254.h"
52 #include "hw/input/i8042.h"
53 #include "hw/irq.h"
54 #include "hw/audio/pcspk.h"
55 #include "hw/pci/msi.h"
56 #include "hw/sysbus.h"
57 #include "sysemu/sysemu.h"
58 #include "sysemu/tcg.h"
59 #include "sysemu/numa.h"
60 #include "sysemu/kvm.h"
61 #include "sysemu/xen.h"
62 #include "sysemu/reset.h"
63 #include "sysemu/runstate.h"
64 #include "kvm/kvm_i386.h"
65 #include "hw/xen/xen.h"
66 #include "hw/xen/start_info.h"
67 #include "ui/qemu-spice.h"
68 #include "exec/memory.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 "acpi-build.h"
77 #include "hw/mem/pc-dimm.h"
78 #include "hw/mem/nvdimm.h"
79 #include "hw/cxl/cxl.h"
80 #include "hw/cxl/cxl_host.h"
81 #include "qapi/error.h"
82 #include "qapi/qapi-visit-common.h"
83 #include "qapi/qapi-visit-machine.h"
84 #include "qapi/visitor.h"
85 #include "hw/core/cpu.h"
86 #include "hw/usb.h"
87 #include "hw/i386/intel_iommu.h"
88 #include "hw/net/ne2000-isa.h"
89 #include "standard-headers/asm-x86/bootparam.h"
90 #include "hw/virtio/virtio-iommu.h"
91 #include "hw/virtio/virtio-pmem-pci.h"
92 #include "hw/virtio/virtio-mem-pci.h"
93 #include "hw/i386/kvm/xen_overlay.h"
94 #include "hw/i386/kvm/xen_evtchn.h"
95 #include "hw/i386/kvm/xen_gnttab.h"
96 #include "hw/mem/memory-device.h"
97 #include "sysemu/replay.h"
98 #include "target/i386/cpu.h"
99 #include "e820_memory_layout.h"
100 #include "fw_cfg.h"
101 #include "trace.h"
102 #include CONFIG_DEVICES
103
104 /*
105  * Helper for setting model-id for CPU models that changed model-id
106  * depending on QEMU versions up to QEMU 2.4.
107  */
108 #define PC_CPU_MODEL_IDS(v) \
109     { "qemu32-" TYPE_X86_CPU, "model-id", "QEMU Virtual CPU version " v, },\
110     { "qemu64-" TYPE_X86_CPU, "model-id", "QEMU Virtual CPU version " v, },\
111     { "athlon-" TYPE_X86_CPU, "model-id", "QEMU Virtual CPU version " v, },
112
113 GlobalProperty pc_compat_7_2[] = {
114     { "ICH9-LPC", "noreboot", "true" },
115 };
116 const size_t pc_compat_7_2_len = G_N_ELEMENTS(pc_compat_7_2);
117
118 GlobalProperty pc_compat_7_1[] = {};
119 const size_t pc_compat_7_1_len = G_N_ELEMENTS(pc_compat_7_1);
120
121 GlobalProperty pc_compat_7_0[] = {};
122 const size_t pc_compat_7_0_len = G_N_ELEMENTS(pc_compat_7_0);
123
124 GlobalProperty pc_compat_6_2[] = {
125     { "virtio-mem", "unplugged-inaccessible", "off" },
126 };
127 const size_t pc_compat_6_2_len = G_N_ELEMENTS(pc_compat_6_2);
128
129 GlobalProperty pc_compat_6_1[] = {
130     { TYPE_X86_CPU, "hv-version-id-build", "0x1bbc" },
131     { TYPE_X86_CPU, "hv-version-id-major", "0x0006" },
132     { TYPE_X86_CPU, "hv-version-id-minor", "0x0001" },
133     { "ICH9-LPC", "x-keep-pci-slot-hpc", "false" },
134 };
135 const size_t pc_compat_6_1_len = G_N_ELEMENTS(pc_compat_6_1);
136
137 GlobalProperty pc_compat_6_0[] = {
138     { "qemu64" "-" TYPE_X86_CPU, "family", "6" },
139     { "qemu64" "-" TYPE_X86_CPU, "model", "6" },
140     { "qemu64" "-" TYPE_X86_CPU, "stepping", "3" },
141     { TYPE_X86_CPU, "x-vendor-cpuid-only", "off" },
142     { "ICH9-LPC", ACPI_PM_PROP_ACPI_PCIHP_BRIDGE, "off" },
143     { "ICH9-LPC", "x-keep-pci-slot-hpc", "true" },
144 };
145 const size_t pc_compat_6_0_len = G_N_ELEMENTS(pc_compat_6_0);
146
147 GlobalProperty pc_compat_5_2[] = {
148     { "ICH9-LPC", "x-smi-cpu-hotunplug", "off" },
149 };
150 const size_t pc_compat_5_2_len = G_N_ELEMENTS(pc_compat_5_2);
151
152 GlobalProperty pc_compat_5_1[] = {
153     { "ICH9-LPC", "x-smi-cpu-hotplug", "off" },
154     { TYPE_X86_CPU, "kvm-msi-ext-dest-id", "off" },
155 };
156 const size_t pc_compat_5_1_len = G_N_ELEMENTS(pc_compat_5_1);
157
158 GlobalProperty pc_compat_5_0[] = {
159 };
160 const size_t pc_compat_5_0_len = G_N_ELEMENTS(pc_compat_5_0);
161
162 GlobalProperty pc_compat_4_2[] = {
163     { "mch", "smbase-smram", "off" },
164 };
165 const size_t pc_compat_4_2_len = G_N_ELEMENTS(pc_compat_4_2);
166
167 GlobalProperty pc_compat_4_1[] = {};
168 const size_t pc_compat_4_1_len = G_N_ELEMENTS(pc_compat_4_1);
169
170 GlobalProperty pc_compat_4_0[] = {};
171 const size_t pc_compat_4_0_len = G_N_ELEMENTS(pc_compat_4_0);
172
173 GlobalProperty pc_compat_3_1[] = {
174     { "intel-iommu", "dma-drain", "off" },
175     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "off" },
176     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "off" },
177     { "Opteron_G4" "-" TYPE_X86_CPU, "npt", "off" },
178     { "Opteron_G4" "-" TYPE_X86_CPU, "nrip-save", "off" },
179     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "off" },
180     { "Opteron_G5" "-" TYPE_X86_CPU, "npt", "off" },
181     { "Opteron_G5" "-" TYPE_X86_CPU, "nrip-save", "off" },
182     { "EPYC" "-" TYPE_X86_CPU, "npt", "off" },
183     { "EPYC" "-" TYPE_X86_CPU, "nrip-save", "off" },
184     { "EPYC-IBPB" "-" TYPE_X86_CPU, "npt", "off" },
185     { "EPYC-IBPB" "-" TYPE_X86_CPU, "nrip-save", "off" },
186     { "Skylake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
187     { "Skylake-Client-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
188     { "Skylake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
189     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "mpx", "on" },
190     { "Cascadelake-Server" "-" TYPE_X86_CPU,  "mpx", "on" },
191     { "Icelake-Client" "-" TYPE_X86_CPU,      "mpx", "on" },
192     { "Icelake-Server" "-" TYPE_X86_CPU,      "mpx", "on" },
193     { "Cascadelake-Server" "-" TYPE_X86_CPU, "stepping", "5" },
194     { TYPE_X86_CPU, "x-intel-pt-auto-level", "off" },
195 };
196 const size_t pc_compat_3_1_len = G_N_ELEMENTS(pc_compat_3_1);
197
198 GlobalProperty pc_compat_3_0[] = {
199     { TYPE_X86_CPU, "x-hv-synic-kvm-only", "on" },
200     { "Skylake-Server" "-" TYPE_X86_CPU, "pku", "off" },
201     { "Skylake-Server-IBRS" "-" TYPE_X86_CPU, "pku", "off" },
202 };
203 const size_t pc_compat_3_0_len = G_N_ELEMENTS(pc_compat_3_0);
204
205 GlobalProperty pc_compat_2_12[] = {
206     { TYPE_X86_CPU, "legacy-cache", "on" },
207     { TYPE_X86_CPU, "topoext", "off" },
208     { "EPYC-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
209     { "EPYC-IBPB-" TYPE_X86_CPU, "xlevel", "0x8000000a" },
210 };
211 const size_t pc_compat_2_12_len = G_N_ELEMENTS(pc_compat_2_12);
212
213 GlobalProperty pc_compat_2_11[] = {
214     { TYPE_X86_CPU, "x-migrate-smi-count", "off" },
215     { "Skylake-Server" "-" TYPE_X86_CPU, "clflushopt", "off" },
216 };
217 const size_t pc_compat_2_11_len = G_N_ELEMENTS(pc_compat_2_11);
218
219 GlobalProperty pc_compat_2_10[] = {
220     { TYPE_X86_CPU, "x-hv-max-vps", "0x40" },
221     { "i440FX-pcihost", "x-pci-hole64-fix", "off" },
222     { "q35-pcihost", "x-pci-hole64-fix", "off" },
223 };
224 const size_t pc_compat_2_10_len = G_N_ELEMENTS(pc_compat_2_10);
225
226 GlobalProperty pc_compat_2_9[] = {
227     { "mch", "extended-tseg-mbytes", "0" },
228 };
229 const size_t pc_compat_2_9_len = G_N_ELEMENTS(pc_compat_2_9);
230
231 GlobalProperty pc_compat_2_8[] = {
232     { TYPE_X86_CPU, "tcg-cpuid", "off" },
233     { "kvmclock", "x-mach-use-reliable-get-clock", "off" },
234     { "ICH9-LPC", "x-smi-broadcast", "off" },
235     { TYPE_X86_CPU, "vmware-cpuid-freq", "off" },
236     { "Haswell-" TYPE_X86_CPU, "stepping", "1" },
237 };
238 const size_t pc_compat_2_8_len = G_N_ELEMENTS(pc_compat_2_8);
239
240 GlobalProperty pc_compat_2_7[] = {
241     { TYPE_X86_CPU, "l3-cache", "off" },
242     { TYPE_X86_CPU, "full-cpuid-auto-level", "off" },
243     { "Opteron_G3" "-" TYPE_X86_CPU, "family", "15" },
244     { "Opteron_G3" "-" TYPE_X86_CPU, "model", "6" },
245     { "Opteron_G3" "-" TYPE_X86_CPU, "stepping", "1" },
246     { "isa-pcspk", "migrate", "off" },
247 };
248 const size_t pc_compat_2_7_len = G_N_ELEMENTS(pc_compat_2_7);
249
250 GlobalProperty pc_compat_2_6[] = {
251     { TYPE_X86_CPU, "cpuid-0xb", "off" },
252     { "vmxnet3", "romfile", "" },
253     { TYPE_X86_CPU, "fill-mtrr-mask", "off" },
254     { "apic-common", "legacy-instance-id", "on", }
255 };
256 const size_t pc_compat_2_6_len = G_N_ELEMENTS(pc_compat_2_6);
257
258 GlobalProperty pc_compat_2_5[] = {};
259 const size_t pc_compat_2_5_len = G_N_ELEMENTS(pc_compat_2_5);
260
261 GlobalProperty pc_compat_2_4[] = {
262     PC_CPU_MODEL_IDS("2.4.0")
263     { "Haswell-" TYPE_X86_CPU, "abm", "off" },
264     { "Haswell-noTSX-" TYPE_X86_CPU, "abm", "off" },
265     { "Broadwell-" TYPE_X86_CPU, "abm", "off" },
266     { "Broadwell-noTSX-" TYPE_X86_CPU, "abm", "off" },
267     { "host" "-" TYPE_X86_CPU, "host-cache-info", "on" },
268     { TYPE_X86_CPU, "check", "off" },
269     { "qemu64" "-" TYPE_X86_CPU, "sse4a", "on" },
270     { "qemu64" "-" TYPE_X86_CPU, "abm", "on" },
271     { "qemu64" "-" TYPE_X86_CPU, "popcnt", "on" },
272     { "qemu32" "-" TYPE_X86_CPU, "popcnt", "on" },
273     { "Opteron_G2" "-" TYPE_X86_CPU, "rdtscp", "on" },
274     { "Opteron_G3" "-" TYPE_X86_CPU, "rdtscp", "on" },
275     { "Opteron_G4" "-" TYPE_X86_CPU, "rdtscp", "on" },
276     { "Opteron_G5" "-" TYPE_X86_CPU, "rdtscp", "on", }
277 };
278 const size_t pc_compat_2_4_len = G_N_ELEMENTS(pc_compat_2_4);
279
280 GlobalProperty pc_compat_2_3[] = {
281     PC_CPU_MODEL_IDS("2.3.0")
282     { TYPE_X86_CPU, "arat", "off" },
283     { "qemu64" "-" TYPE_X86_CPU, "min-level", "4" },
284     { "kvm64" "-" TYPE_X86_CPU, "min-level", "5" },
285     { "pentium3" "-" TYPE_X86_CPU, "min-level", "2" },
286     { "n270" "-" TYPE_X86_CPU, "min-level", "5" },
287     { "Conroe" "-" TYPE_X86_CPU, "min-level", "4" },
288     { "Penryn" "-" TYPE_X86_CPU, "min-level", "4" },
289     { "Nehalem" "-" TYPE_X86_CPU, "min-level", "4" },
290     { "n270" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
291     { "Penryn" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
292     { "Conroe" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
293     { "Nehalem" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
294     { "Westmere" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
295     { "SandyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
296     { "IvyBridge" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
297     { "Haswell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
298     { "Haswell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
299     { "Broadwell" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
300     { "Broadwell-noTSX" "-" TYPE_X86_CPU, "min-xlevel", "0x8000000a" },
301     { TYPE_X86_CPU, "kvm-no-smi-migration", "on" },
302 };
303 const size_t pc_compat_2_3_len = G_N_ELEMENTS(pc_compat_2_3);
304
305 GlobalProperty pc_compat_2_2[] = {
306     PC_CPU_MODEL_IDS("2.2.0")
307     { "kvm64" "-" TYPE_X86_CPU, "vme", "off" },
308     { "kvm32" "-" TYPE_X86_CPU, "vme", "off" },
309     { "Conroe" "-" TYPE_X86_CPU, "vme", "off" },
310     { "Penryn" "-" TYPE_X86_CPU, "vme", "off" },
311     { "Nehalem" "-" TYPE_X86_CPU, "vme", "off" },
312     { "Westmere" "-" TYPE_X86_CPU, "vme", "off" },
313     { "SandyBridge" "-" TYPE_X86_CPU, "vme", "off" },
314     { "Haswell" "-" TYPE_X86_CPU, "vme", "off" },
315     { "Broadwell" "-" TYPE_X86_CPU, "vme", "off" },
316     { "Opteron_G1" "-" TYPE_X86_CPU, "vme", "off" },
317     { "Opteron_G2" "-" TYPE_X86_CPU, "vme", "off" },
318     { "Opteron_G3" "-" TYPE_X86_CPU, "vme", "off" },
319     { "Opteron_G4" "-" TYPE_X86_CPU, "vme", "off" },
320     { "Opteron_G5" "-" TYPE_X86_CPU, "vme", "off" },
321     { "Haswell" "-" TYPE_X86_CPU, "f16c", "off" },
322     { "Haswell" "-" TYPE_X86_CPU, "rdrand", "off" },
323     { "Broadwell" "-" TYPE_X86_CPU, "f16c", "off" },
324     { "Broadwell" "-" TYPE_X86_CPU, "rdrand", "off" },
325 };
326 const size_t pc_compat_2_2_len = G_N_ELEMENTS(pc_compat_2_2);
327
328 GlobalProperty pc_compat_2_1[] = {
329     PC_CPU_MODEL_IDS("2.1.0")
330     { "coreduo" "-" TYPE_X86_CPU, "vmx", "on" },
331     { "core2duo" "-" TYPE_X86_CPU, "vmx", "on" },
332 };
333 const size_t pc_compat_2_1_len = G_N_ELEMENTS(pc_compat_2_1);
334
335 GlobalProperty pc_compat_2_0[] = {
336     PC_CPU_MODEL_IDS("2.0.0")
337     { "virtio-scsi-pci", "any_layout", "off" },
338     { "PIIX4_PM", "memory-hotplug-support", "off" },
339     { "apic", "version", "0x11" },
340     { "nec-usb-xhci", "superspeed-ports-first", "off" },
341     { "nec-usb-xhci", "force-pcie-endcap", "on" },
342     { "pci-serial", "prog_if", "0" },
343     { "pci-serial-2x", "prog_if", "0" },
344     { "pci-serial-4x", "prog_if", "0" },
345     { "virtio-net-pci", "guest_announce", "off" },
346     { "ICH9-LPC", "memory-hotplug-support", "off" },
347 };
348 const size_t pc_compat_2_0_len = G_N_ELEMENTS(pc_compat_2_0);
349
350 GlobalProperty pc_compat_1_7[] = {
351     PC_CPU_MODEL_IDS("1.7.0")
352     { TYPE_USB_DEVICE, "msos-desc", "no" },
353     { "PIIX4_PM", ACPI_PM_PROP_ACPI_PCIHP_BRIDGE, "off" },
354     { "hpet", HPET_INTCAP, "4" },
355 };
356 const size_t pc_compat_1_7_len = G_N_ELEMENTS(pc_compat_1_7);
357
358 GlobalProperty pc_compat_1_6[] = {
359     PC_CPU_MODEL_IDS("1.6.0")
360     { "e1000", "mitigation", "off" },
361     { "qemu64-" TYPE_X86_CPU, "model", "2" },
362     { "qemu32-" TYPE_X86_CPU, "model", "3" },
363     { "i440FX-pcihost", "short_root_bus", "1" },
364     { "q35-pcihost", "short_root_bus", "1" },
365 };
366 const size_t pc_compat_1_6_len = G_N_ELEMENTS(pc_compat_1_6);
367
368 GlobalProperty pc_compat_1_5[] = {
369     PC_CPU_MODEL_IDS("1.5.0")
370     { "Conroe-" TYPE_X86_CPU, "model", "2" },
371     { "Conroe-" TYPE_X86_CPU, "min-level", "2" },
372     { "Penryn-" TYPE_X86_CPU, "model", "2" },
373     { "Penryn-" TYPE_X86_CPU, "min-level", "2" },
374     { "Nehalem-" TYPE_X86_CPU, "model", "2" },
375     { "Nehalem-" TYPE_X86_CPU, "min-level", "2" },
376     { "virtio-net-pci", "any_layout", "off" },
377     { TYPE_X86_CPU, "pmu", "on" },
378     { "i440FX-pcihost", "short_root_bus", "0" },
379     { "q35-pcihost", "short_root_bus", "0" },
380 };
381 const size_t pc_compat_1_5_len = G_N_ELEMENTS(pc_compat_1_5);
382
383 GlobalProperty pc_compat_1_4[] = {
384     PC_CPU_MODEL_IDS("1.4.0")
385     { "scsi-hd", "discard_granularity", "0" },
386     { "scsi-cd", "discard_granularity", "0" },
387     { "ide-hd", "discard_granularity", "0" },
388     { "ide-cd", "discard_granularity", "0" },
389     { "virtio-blk-pci", "discard_granularity", "0" },
390     /* DEV_NVECTORS_UNSPECIFIED as a uint32_t string: */
391     { "virtio-serial-pci", "vectors", "0xFFFFFFFF" },
392     { "virtio-net-pci", "ctrl_guest_offloads", "off" },
393     { "e1000", "romfile", "pxe-e1000.rom" },
394     { "ne2k_pci", "romfile", "pxe-ne2k_pci.rom" },
395     { "pcnet", "romfile", "pxe-pcnet.rom" },
396     { "rtl8139", "romfile", "pxe-rtl8139.rom" },
397     { "virtio-net-pci", "romfile", "pxe-virtio.rom" },
398     { "486-" TYPE_X86_CPU, "model", "0" },
399     { "n270" "-" TYPE_X86_CPU, "movbe", "off" },
400     { "Westmere" "-" TYPE_X86_CPU, "pclmulqdq", "off" },
401 };
402 const size_t pc_compat_1_4_len = G_N_ELEMENTS(pc_compat_1_4);
403
404 GSIState *pc_gsi_create(qemu_irq **irqs, bool pci_enabled)
405 {
406     GSIState *s;
407
408     s = g_new0(GSIState, 1);
409     if (kvm_ioapic_in_kernel()) {
410         kvm_pc_setup_irq_routing(pci_enabled);
411     }
412     *irqs = qemu_allocate_irqs(gsi_handler, s, IOAPIC_NUM_PINS);
413
414     return s;
415 }
416
417 static void ioport80_write(void *opaque, hwaddr addr, uint64_t data,
418                            unsigned size)
419 {
420 }
421
422 static uint64_t ioport80_read(void *opaque, hwaddr addr, unsigned size)
423 {
424     return 0xffffffffffffffffULL;
425 }
426
427 /* MSDOS compatibility mode FPU exception support */
428 static void ioportF0_write(void *opaque, hwaddr addr, uint64_t data,
429                            unsigned size)
430 {
431     if (tcg_enabled()) {
432         cpu_set_ignne();
433     }
434 }
435
436 static uint64_t ioportF0_read(void *opaque, hwaddr addr, unsigned size)
437 {
438     return 0xffffffffffffffffULL;
439 }
440
441 /* PC cmos mappings */
442
443 #define REG_EQUIPMENT_BYTE          0x14
444
445 static void cmos_init_hd(MC146818RtcState *s, int type_ofs, int info_ofs,
446                          int16_t cylinders, int8_t heads, int8_t sectors)
447 {
448     mc146818rtc_set_cmos_data(s, type_ofs, 47);
449     mc146818rtc_set_cmos_data(s, info_ofs, cylinders);
450     mc146818rtc_set_cmos_data(s, info_ofs + 1, cylinders >> 8);
451     mc146818rtc_set_cmos_data(s, info_ofs + 2, heads);
452     mc146818rtc_set_cmos_data(s, info_ofs + 3, 0xff);
453     mc146818rtc_set_cmos_data(s, info_ofs + 4, 0xff);
454     mc146818rtc_set_cmos_data(s, info_ofs + 5, 0xc0 | ((heads > 8) << 3));
455     mc146818rtc_set_cmos_data(s, info_ofs + 6, cylinders);
456     mc146818rtc_set_cmos_data(s, info_ofs + 7, cylinders >> 8);
457     mc146818rtc_set_cmos_data(s, info_ofs + 8, sectors);
458 }
459
460 /* convert boot_device letter to something recognizable by the bios */
461 static int boot_device2nibble(char boot_device)
462 {
463     switch(boot_device) {
464     case 'a':
465     case 'b':
466         return 0x01; /* floppy boot */
467     case 'c':
468         return 0x02; /* hard drive boot */
469     case 'd':
470         return 0x03; /* CD-ROM boot */
471     case 'n':
472         return 0x04; /* Network boot */
473     }
474     return 0;
475 }
476
477 static void set_boot_dev(MC146818RtcState *s, const char *boot_device,
478                          Error **errp)
479 {
480 #define PC_MAX_BOOT_DEVICES 3
481     int nbds, bds[3] = { 0, };
482     int i;
483
484     nbds = strlen(boot_device);
485     if (nbds > PC_MAX_BOOT_DEVICES) {
486         error_setg(errp, "Too many boot devices for PC");
487         return;
488     }
489     for (i = 0; i < nbds; i++) {
490         bds[i] = boot_device2nibble(boot_device[i]);
491         if (bds[i] == 0) {
492             error_setg(errp, "Invalid boot device for PC: '%c'",
493                        boot_device[i]);
494             return;
495         }
496     }
497     mc146818rtc_set_cmos_data(s, 0x3d, (bds[1] << 4) | bds[0]);
498     mc146818rtc_set_cmos_data(s, 0x38, (bds[2] << 4) | (fd_bootchk ? 0x0 : 0x1));
499 }
500
501 static void pc_boot_set(void *opaque, const char *boot_device, Error **errp)
502 {
503     set_boot_dev(opaque, boot_device, errp);
504 }
505
506 static void pc_cmos_init_floppy(MC146818RtcState *rtc_state, ISADevice *floppy)
507 {
508     int val, nb, i;
509     FloppyDriveType fd_type[2] = { FLOPPY_DRIVE_TYPE_NONE,
510                                    FLOPPY_DRIVE_TYPE_NONE };
511
512     /* floppy type */
513     if (floppy) {
514         for (i = 0; i < 2; i++) {
515             fd_type[i] = isa_fdc_get_drive_type(floppy, i);
516         }
517     }
518     val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |
519         cmos_get_fd_drive_type(fd_type[1]);
520     mc146818rtc_set_cmos_data(rtc_state, 0x10, val);
521
522     val = mc146818rtc_get_cmos_data(rtc_state, REG_EQUIPMENT_BYTE);
523     nb = 0;
524     if (fd_type[0] != FLOPPY_DRIVE_TYPE_NONE) {
525         nb++;
526     }
527     if (fd_type[1] != FLOPPY_DRIVE_TYPE_NONE) {
528         nb++;
529     }
530     switch (nb) {
531     case 0:
532         break;
533     case 1:
534         val |= 0x01; /* 1 drive, ready for boot */
535         break;
536     case 2:
537         val |= 0x41; /* 2 drives, ready for boot */
538         break;
539     }
540     mc146818rtc_set_cmos_data(rtc_state, REG_EQUIPMENT_BYTE, val);
541 }
542
543 typedef struct pc_cmos_init_late_arg {
544     MC146818RtcState *rtc_state;
545     BusState *idebus[2];
546 } pc_cmos_init_late_arg;
547
548 typedef struct check_fdc_state {
549     ISADevice *floppy;
550     bool multiple;
551 } CheckFdcState;
552
553 static int check_fdc(Object *obj, void *opaque)
554 {
555     CheckFdcState *state = opaque;
556     Object *fdc;
557     uint32_t iobase;
558     Error *local_err = NULL;
559
560     fdc = object_dynamic_cast(obj, TYPE_ISA_FDC);
561     if (!fdc) {
562         return 0;
563     }
564
565     iobase = object_property_get_uint(obj, "iobase", &local_err);
566     if (local_err || iobase != 0x3f0) {
567         error_free(local_err);
568         return 0;
569     }
570
571     if (state->floppy) {
572         state->multiple = true;
573     } else {
574         state->floppy = ISA_DEVICE(obj);
575     }
576     return 0;
577 }
578
579 static const char * const fdc_container_path[] = {
580     "/unattached", "/peripheral", "/peripheral-anon"
581 };
582
583 /*
584  * Locate the FDC at IO address 0x3f0, in order to configure the CMOS registers
585  * and ACPI objects.
586  */
587 static ISADevice *pc_find_fdc0(void)
588 {
589     int i;
590     Object *container;
591     CheckFdcState state = { 0 };
592
593     for (i = 0; i < ARRAY_SIZE(fdc_container_path); i++) {
594         container = container_get(qdev_get_machine(), fdc_container_path[i]);
595         object_child_foreach(container, check_fdc, &state);
596     }
597
598     if (state.multiple) {
599         warn_report("multiple floppy disk controllers with "
600                     "iobase=0x3f0 have been found");
601         error_printf("the one being picked for CMOS setup might not reflect "
602                      "your intent");
603     }
604
605     return state.floppy;
606 }
607
608 static void pc_cmos_init_late(void *opaque)
609 {
610     pc_cmos_init_late_arg *arg = opaque;
611     MC146818RtcState *s = arg->rtc_state;
612     int16_t cylinders;
613     int8_t heads, sectors;
614     int val;
615     int i, trans;
616
617     val = 0;
618     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 0,
619                                            &cylinders, &heads, &sectors) >= 0) {
620         cmos_init_hd(s, 0x19, 0x1b, cylinders, heads, sectors);
621         val |= 0xf0;
622     }
623     if (arg->idebus[0] && ide_get_geometry(arg->idebus[0], 1,
624                                            &cylinders, &heads, &sectors) >= 0) {
625         cmos_init_hd(s, 0x1a, 0x24, cylinders, heads, sectors);
626         val |= 0x0f;
627     }
628     mc146818rtc_set_cmos_data(s, 0x12, val);
629
630     val = 0;
631     for (i = 0; i < 4; i++) {
632         /* NOTE: ide_get_geometry() returns the physical
633            geometry.  It is always such that: 1 <= sects <= 63, 1
634            <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
635            geometry can be different if a translation is done. */
636         if (arg->idebus[i / 2] &&
637             ide_get_geometry(arg->idebus[i / 2], i % 2,
638                              &cylinders, &heads, &sectors) >= 0) {
639             trans = ide_get_bios_chs_trans(arg->idebus[i / 2], i % 2) - 1;
640             assert((trans & ~3) == 0);
641             val |= trans << (i * 2);
642         }
643     }
644     mc146818rtc_set_cmos_data(s, 0x39, val);
645
646     pc_cmos_init_floppy(s, pc_find_fdc0());
647
648     qemu_unregister_reset(pc_cmos_init_late, opaque);
649 }
650
651 void pc_cmos_init(PCMachineState *pcms,
652                   BusState *idebus0, BusState *idebus1,
653                   ISADevice *rtc)
654 {
655     int val;
656     static pc_cmos_init_late_arg arg;
657     X86MachineState *x86ms = X86_MACHINE(pcms);
658     MC146818RtcState *s = MC146818_RTC(rtc);
659
660     /* various important CMOS locations needed by PC/Bochs bios */
661
662     /* memory size */
663     /* base memory (first MiB) */
664     val = MIN(x86ms->below_4g_mem_size / KiB, 640);
665     mc146818rtc_set_cmos_data(s, 0x15, val);
666     mc146818rtc_set_cmos_data(s, 0x16, val >> 8);
667     /* extended memory (next 64MiB) */
668     if (x86ms->below_4g_mem_size > 1 * MiB) {
669         val = (x86ms->below_4g_mem_size - 1 * MiB) / KiB;
670     } else {
671         val = 0;
672     }
673     if (val > 65535)
674         val = 65535;
675     mc146818rtc_set_cmos_data(s, 0x17, val);
676     mc146818rtc_set_cmos_data(s, 0x18, val >> 8);
677     mc146818rtc_set_cmos_data(s, 0x30, val);
678     mc146818rtc_set_cmos_data(s, 0x31, val >> 8);
679     /* memory between 16MiB and 4GiB */
680     if (x86ms->below_4g_mem_size > 16 * MiB) {
681         val = (x86ms->below_4g_mem_size - 16 * MiB) / (64 * KiB);
682     } else {
683         val = 0;
684     }
685     if (val > 65535)
686         val = 65535;
687     mc146818rtc_set_cmos_data(s, 0x34, val);
688     mc146818rtc_set_cmos_data(s, 0x35, val >> 8);
689     /* memory above 4GiB */
690     val = x86ms->above_4g_mem_size / 65536;
691     mc146818rtc_set_cmos_data(s, 0x5b, val);
692     mc146818rtc_set_cmos_data(s, 0x5c, val >> 8);
693     mc146818rtc_set_cmos_data(s, 0x5d, val >> 16);
694
695     object_property_add_link(OBJECT(pcms), "rtc_state",
696                              TYPE_ISA_DEVICE,
697                              (Object **)&x86ms->rtc,
698                              object_property_allow_set_link,
699                              OBJ_PROP_LINK_STRONG);
700     object_property_set_link(OBJECT(pcms), "rtc_state", OBJECT(s),
701                              &error_abort);
702
703     set_boot_dev(s, MACHINE(pcms)->boot_config.order, &error_fatal);
704
705     val = 0;
706     val |= 0x02; /* FPU is there */
707     val |= 0x04; /* PS/2 mouse installed */
708     mc146818rtc_set_cmos_data(s, REG_EQUIPMENT_BYTE, val);
709
710     /* hard drives and FDC */
711     arg.rtc_state = s;
712     arg.idebus[0] = idebus0;
713     arg.idebus[1] = idebus1;
714     qemu_register_reset(pc_cmos_init_late, &arg);
715 }
716
717 static void handle_a20_line_change(void *opaque, int irq, int level)
718 {
719     X86CPU *cpu = opaque;
720
721     /* XXX: send to all CPUs ? */
722     /* XXX: add logic to handle multiple A20 line sources */
723     x86_cpu_set_a20(cpu, level);
724 }
725
726 #define NE2000_NB_MAX 6
727
728 static const int ne2000_io[NE2000_NB_MAX] = { 0x300, 0x320, 0x340, 0x360,
729                                               0x280, 0x380 };
730 static const int ne2000_irq[NE2000_NB_MAX] = { 9, 10, 11, 3, 4, 5 };
731
732 static void pc_init_ne2k_isa(ISABus *bus, NICInfo *nd)
733 {
734     static int nb_ne2k = 0;
735
736     if (nb_ne2k == NE2000_NB_MAX)
737         return;
738     isa_ne2000_init(bus, ne2000_io[nb_ne2k],
739                     ne2000_irq[nb_ne2k], nd);
740     nb_ne2k++;
741 }
742
743 void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
744 {
745     X86CPU *cpu = opaque;
746
747     if (level) {
748         cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
749     }
750 }
751
752 static
753 void pc_machine_done(Notifier *notifier, void *data)
754 {
755     PCMachineState *pcms = container_of(notifier,
756                                         PCMachineState, machine_done);
757     X86MachineState *x86ms = X86_MACHINE(pcms);
758
759     cxl_hook_up_pxb_registers(pcms->bus, &pcms->cxl_devices_state,
760                               &error_fatal);
761
762     if (pcms->cxl_devices_state.is_enabled) {
763         cxl_fmws_link_targets(&pcms->cxl_devices_state, &error_fatal);
764     }
765
766     /* set the number of CPUs */
767     x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
768
769     fw_cfg_add_extra_pci_roots(pcms->bus, x86ms->fw_cfg);
770
771     acpi_setup();
772     if (x86ms->fw_cfg) {
773         fw_cfg_build_smbios(MACHINE(pcms), x86ms->fw_cfg);
774         fw_cfg_build_feature_control(MACHINE(pcms), x86ms->fw_cfg);
775         /* update FW_CFG_NB_CPUS to account for -device added CPUs */
776         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
777     }
778 }
779
780 void pc_guest_info_init(PCMachineState *pcms)
781 {
782     X86MachineState *x86ms = X86_MACHINE(pcms);
783
784     x86ms->apic_xrupt_override = true;
785     pcms->machine_done.notify = pc_machine_done;
786     qemu_add_machine_init_done_notifier(&pcms->machine_done);
787 }
788
789 /* setup pci memory address space mapping into system address space */
790 void pc_pci_as_mapping_init(MemoryRegion *system_memory,
791                             MemoryRegion *pci_address_space)
792 {
793     /* Set to lower priority than RAM */
794     memory_region_add_subregion_overlap(system_memory, 0x0,
795                                         pci_address_space, -1);
796 }
797
798 void xen_load_linux(PCMachineState *pcms)
799 {
800     int i;
801     FWCfgState *fw_cfg;
802     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
803     X86MachineState *x86ms = X86_MACHINE(pcms);
804
805     assert(MACHINE(pcms)->kernel_filename != NULL);
806
807     fw_cfg = fw_cfg_init_io(FW_CFG_IO_BASE);
808     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
809     rom_set_fw(fw_cfg);
810
811     x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
812                    pcmc->pvh_enabled, pcmc->legacy_no_rng_seed);
813     for (i = 0; i < nb_option_roms; i++) {
814         assert(!strcmp(option_rom[i].name, "linuxboot.bin") ||
815                !strcmp(option_rom[i].name, "linuxboot_dma.bin") ||
816                !strcmp(option_rom[i].name, "pvh.bin") ||
817                !strcmp(option_rom[i].name, "multiboot.bin") ||
818                !strcmp(option_rom[i].name, "multiboot_dma.bin"));
819         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
820     }
821     x86ms->fw_cfg = fw_cfg;
822 }
823
824 #define PC_ROM_MIN_VGA     0xc0000
825 #define PC_ROM_MIN_OPTION  0xc8000
826 #define PC_ROM_MAX         0xe0000
827 #define PC_ROM_ALIGN       0x800
828 #define PC_ROM_SIZE        (PC_ROM_MAX - PC_ROM_MIN_VGA)
829
830 static hwaddr pc_above_4g_end(PCMachineState *pcms)
831 {
832     X86MachineState *x86ms = X86_MACHINE(pcms);
833
834     if (pcms->sgx_epc.size != 0) {
835         return sgx_epc_above_4g_end(&pcms->sgx_epc);
836     }
837
838     return x86ms->above_4g_mem_start + x86ms->above_4g_mem_size;
839 }
840
841 static void pc_get_device_memory_range(PCMachineState *pcms,
842                                        hwaddr *base,
843                                        ram_addr_t *device_mem_size)
844 {
845     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
846     MachineState *machine = MACHINE(pcms);
847     ram_addr_t size;
848     hwaddr addr;
849
850     size = machine->maxram_size - machine->ram_size;
851     addr = ROUND_UP(pc_above_4g_end(pcms), 1 * GiB);
852
853     if (pcmc->enforce_aligned_dimm) {
854         /* size device region assuming 1G page max alignment per slot */
855         size += (1 * GiB) * machine->ram_slots;
856     }
857
858     *base = addr;
859     *device_mem_size = size;
860 }
861
862 static uint64_t pc_get_cxl_range_start(PCMachineState *pcms)
863 {
864     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
865     hwaddr cxl_base;
866     ram_addr_t size;
867
868     if (pcmc->has_reserved_memory) {
869         pc_get_device_memory_range(pcms, &cxl_base, &size);
870         cxl_base += size;
871     } else {
872         cxl_base = pc_above_4g_end(pcms);
873     }
874
875     return cxl_base;
876 }
877
878 static uint64_t pc_get_cxl_range_end(PCMachineState *pcms)
879 {
880     uint64_t start = pc_get_cxl_range_start(pcms) + MiB;
881
882     if (pcms->cxl_devices_state.fixed_windows) {
883         GList *it;
884
885         start = ROUND_UP(start, 256 * MiB);
886         for (it = pcms->cxl_devices_state.fixed_windows; it; it = it->next) {
887             CXLFixedWindow *fw = it->data;
888             start += fw->size;
889         }
890     }
891
892     return start;
893 }
894
895 static hwaddr pc_max_used_gpa(PCMachineState *pcms, uint64_t pci_hole64_size)
896 {
897     X86CPU *cpu = X86_CPU(first_cpu);
898
899     /* 32-bit systems don't have hole64 thus return max CPU address */
900     if (cpu->phys_bits <= 32) {
901         return ((hwaddr)1 << cpu->phys_bits) - 1;
902     }
903
904     return pc_pci_hole64_start() + pci_hole64_size - 1;
905 }
906
907 /*
908  * AMD systems with an IOMMU have an additional hole close to the
909  * 1Tb, which are special GPAs that cannot be DMA mapped. Depending
910  * on kernel version, VFIO may or may not let you DMA map those ranges.
911  * Starting Linux v5.4 we validate it, and can't create guests on AMD machines
912  * with certain memory sizes. It's also wrong to use those IOVA ranges
913  * in detriment of leading to IOMMU INVALID_DEVICE_REQUEST or worse.
914  * The ranges reserved for Hyper-Transport are:
915  *
916  * FD_0000_0000h - FF_FFFF_FFFFh
917  *
918  * The ranges represent the following:
919  *
920  * Base Address   Top Address  Use
921  *
922  * FD_0000_0000h FD_F7FF_FFFFh Reserved interrupt address space
923  * FD_F800_0000h FD_F8FF_FFFFh Interrupt/EOI IntCtl
924  * FD_F900_0000h FD_F90F_FFFFh Legacy PIC IACK
925  * FD_F910_0000h FD_F91F_FFFFh System Management
926  * FD_F920_0000h FD_FAFF_FFFFh Reserved Page Tables
927  * FD_FB00_0000h FD_FBFF_FFFFh Address Translation
928  * FD_FC00_0000h FD_FDFF_FFFFh I/O Space
929  * FD_FE00_0000h FD_FFFF_FFFFh Configuration
930  * FE_0000_0000h FE_1FFF_FFFFh Extended Configuration/Device Messages
931  * FE_2000_0000h FF_FFFF_FFFFh Reserved
932  *
933  * See AMD IOMMU spec, section 2.1.2 "IOMMU Logical Topology",
934  * Table 3: Special Address Controls (GPA) for more information.
935  */
936 #define AMD_HT_START         0xfd00000000UL
937 #define AMD_HT_END           0xffffffffffUL
938 #define AMD_ABOVE_1TB_START  (AMD_HT_END + 1)
939 #define AMD_HT_SIZE          (AMD_ABOVE_1TB_START - AMD_HT_START)
940
941 void pc_memory_init(PCMachineState *pcms,
942                     MemoryRegion *system_memory,
943                     MemoryRegion *rom_memory,
944                     MemoryRegion **ram_memory,
945                     uint64_t pci_hole64_size)
946 {
947     int linux_boot, i;
948     MemoryRegion *option_rom_mr;
949     MemoryRegion *ram_below_4g, *ram_above_4g;
950     FWCfgState *fw_cfg;
951     MachineState *machine = MACHINE(pcms);
952     MachineClass *mc = MACHINE_GET_CLASS(machine);
953     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
954     X86MachineState *x86ms = X86_MACHINE(pcms);
955     hwaddr maxphysaddr, maxusedaddr;
956     hwaddr cxl_base, cxl_resv_end = 0;
957     X86CPU *cpu = X86_CPU(first_cpu);
958
959     assert(machine->ram_size == x86ms->below_4g_mem_size +
960                                 x86ms->above_4g_mem_size);
961
962     linux_boot = (machine->kernel_filename != NULL);
963
964     /*
965      * The HyperTransport range close to the 1T boundary is unique to AMD
966      * hosts with IOMMUs enabled. Restrict the ram-above-4g relocation
967      * to above 1T to AMD vCPUs only. @enforce_amd_1tb_hole is only false in
968      * older machine types (<= 7.0) for compatibility purposes.
969      */
970     if (IS_AMD_CPU(&cpu->env) && pcmc->enforce_amd_1tb_hole) {
971         /* Bail out if max possible address does not cross HT range */
972         if (pc_max_used_gpa(pcms, pci_hole64_size) >= AMD_HT_START) {
973             x86ms->above_4g_mem_start = AMD_ABOVE_1TB_START;
974         }
975
976         /*
977          * Advertise the HT region if address space covers the reserved
978          * region or if we relocate.
979          */
980         if (cpu->phys_bits >= 40) {
981             e820_add_entry(AMD_HT_START, AMD_HT_SIZE, E820_RESERVED);
982         }
983     }
984
985     /*
986      * phys-bits is required to be appropriately configured
987      * to make sure max used GPA is reachable.
988      */
989     maxusedaddr = pc_max_used_gpa(pcms, pci_hole64_size);
990     maxphysaddr = ((hwaddr)1 << cpu->phys_bits) - 1;
991     if (maxphysaddr < maxusedaddr) {
992         error_report("Address space limit 0x%"PRIx64" < 0x%"PRIx64
993                      " phys-bits too low (%u)",
994                      maxphysaddr, maxusedaddr, cpu->phys_bits);
995         exit(EXIT_FAILURE);
996     }
997
998     /*
999      * Split single memory region and use aliases to address portions of it,
1000      * done for backwards compatibility with older qemus.
1001      */
1002     *ram_memory = machine->ram;
1003     ram_below_4g = g_malloc(sizeof(*ram_below_4g));
1004     memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", machine->ram,
1005                              0, x86ms->below_4g_mem_size);
1006     memory_region_add_subregion(system_memory, 0, ram_below_4g);
1007     e820_add_entry(0, x86ms->below_4g_mem_size, E820_RAM);
1008     if (x86ms->above_4g_mem_size > 0) {
1009         ram_above_4g = g_malloc(sizeof(*ram_above_4g));
1010         memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g",
1011                                  machine->ram,
1012                                  x86ms->below_4g_mem_size,
1013                                  x86ms->above_4g_mem_size);
1014         memory_region_add_subregion(system_memory, x86ms->above_4g_mem_start,
1015                                     ram_above_4g);
1016         e820_add_entry(x86ms->above_4g_mem_start, x86ms->above_4g_mem_size,
1017                        E820_RAM);
1018     }
1019
1020     if (pcms->sgx_epc.size != 0) {
1021         e820_add_entry(pcms->sgx_epc.base, pcms->sgx_epc.size, E820_RESERVED);
1022     }
1023
1024     if (!pcmc->has_reserved_memory &&
1025         (machine->ram_slots ||
1026          (machine->maxram_size > machine->ram_size))) {
1027
1028         error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",
1029                      mc->name);
1030         exit(EXIT_FAILURE);
1031     }
1032
1033     /* always allocate the device memory information */
1034     machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
1035
1036     /* initialize device memory address space */
1037     if (pcmc->has_reserved_memory &&
1038         (machine->ram_size < machine->maxram_size)) {
1039         ram_addr_t device_mem_size;
1040
1041         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
1042             error_report("unsupported amount of memory slots: %"PRIu64,
1043                          machine->ram_slots);
1044             exit(EXIT_FAILURE);
1045         }
1046
1047         if (QEMU_ALIGN_UP(machine->maxram_size,
1048                           TARGET_PAGE_SIZE) != machine->maxram_size) {
1049             error_report("maximum memory size must by aligned to multiple of "
1050                          "%d bytes", TARGET_PAGE_SIZE);
1051             exit(EXIT_FAILURE);
1052         }
1053
1054         pc_get_device_memory_range(pcms, &machine->device_memory->base, &device_mem_size);
1055
1056         if ((machine->device_memory->base + device_mem_size) <
1057             device_mem_size) {
1058             error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,
1059                          machine->maxram_size);
1060             exit(EXIT_FAILURE);
1061         }
1062
1063         memory_region_init(&machine->device_memory->mr, OBJECT(pcms),
1064                            "device-memory", device_mem_size);
1065         memory_region_add_subregion(system_memory, machine->device_memory->base,
1066                                     &machine->device_memory->mr);
1067     }
1068
1069     if (pcms->cxl_devices_state.is_enabled) {
1070         MemoryRegion *mr = &pcms->cxl_devices_state.host_mr;
1071         hwaddr cxl_size = MiB;
1072
1073         cxl_base = pc_get_cxl_range_start(pcms);
1074         memory_region_init(mr, OBJECT(machine), "cxl_host_reg", cxl_size);
1075         memory_region_add_subregion(system_memory, cxl_base, mr);
1076         cxl_resv_end = cxl_base + cxl_size;
1077         if (pcms->cxl_devices_state.fixed_windows) {
1078             hwaddr cxl_fmw_base;
1079             GList *it;
1080
1081             cxl_fmw_base = ROUND_UP(cxl_base + cxl_size, 256 * MiB);
1082             for (it = pcms->cxl_devices_state.fixed_windows; it; it = it->next) {
1083                 CXLFixedWindow *fw = it->data;
1084
1085                 fw->base = cxl_fmw_base;
1086                 memory_region_init_io(&fw->mr, OBJECT(machine), &cfmws_ops, fw,
1087                                       "cxl-fixed-memory-region", fw->size);
1088                 memory_region_add_subregion(system_memory, fw->base, &fw->mr);
1089                 cxl_fmw_base += fw->size;
1090                 cxl_resv_end = cxl_fmw_base;
1091             }
1092         }
1093     }
1094
1095     /* Initialize PC system firmware */
1096     pc_system_firmware_init(pcms, rom_memory);
1097
1098     option_rom_mr = g_malloc(sizeof(*option_rom_mr));
1099     memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,
1100                            &error_fatal);
1101     if (pcmc->pci_enabled) {
1102         memory_region_set_readonly(option_rom_mr, true);
1103     }
1104     memory_region_add_subregion_overlap(rom_memory,
1105                                         PC_ROM_MIN_VGA,
1106                                         option_rom_mr,
1107                                         1);
1108
1109     fw_cfg = fw_cfg_arch_create(machine,
1110                                 x86ms->boot_cpus, x86ms->apic_id_limit);
1111
1112     rom_set_fw(fw_cfg);
1113
1114     if (pcmc->has_reserved_memory && machine->device_memory->base) {
1115         uint64_t *val = g_malloc(sizeof(*val));
1116         PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1117         uint64_t res_mem_end = machine->device_memory->base;
1118
1119         if (!pcmc->broken_reserved_end) {
1120             res_mem_end += memory_region_size(&machine->device_memory->mr);
1121         }
1122
1123         if (pcms->cxl_devices_state.is_enabled) {
1124             res_mem_end = cxl_resv_end;
1125         }
1126         *val = cpu_to_le64(ROUND_UP(res_mem_end, 1 * GiB));
1127         fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));
1128     }
1129
1130     if (linux_boot) {
1131         x86_load_linux(x86ms, fw_cfg, pcmc->acpi_data_size,
1132                        pcmc->pvh_enabled, pcmc->legacy_no_rng_seed);
1133     }
1134
1135     for (i = 0; i < nb_option_roms; i++) {
1136         rom_add_option(option_rom[i].name, option_rom[i].bootindex);
1137     }
1138     x86ms->fw_cfg = fw_cfg;
1139
1140     /* Init default IOAPIC address space */
1141     x86ms->ioapic_as = &address_space_memory;
1142
1143     /* Init ACPI memory hotplug IO base address */
1144     pcms->memhp_io_base = ACPI_MEMORY_HOTPLUG_BASE;
1145 }
1146
1147 /*
1148  * The 64bit pci hole starts after "above 4G RAM" and
1149  * potentially the space reserved for memory hotplug.
1150  */
1151 uint64_t pc_pci_hole64_start(void)
1152 {
1153     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
1154     PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1155     MachineState *ms = MACHINE(pcms);
1156     uint64_t hole64_start = 0;
1157     ram_addr_t size = 0;
1158
1159     if (pcms->cxl_devices_state.is_enabled) {
1160         hole64_start = pc_get_cxl_range_end(pcms);
1161     } else if (pcmc->has_reserved_memory && (ms->ram_size < ms->maxram_size)) {
1162         pc_get_device_memory_range(pcms, &hole64_start, &size);
1163         if (!pcmc->broken_reserved_end) {
1164             hole64_start += size;
1165         }
1166     } else {
1167         hole64_start = pc_above_4g_end(pcms);
1168     }
1169
1170     return ROUND_UP(hole64_start, 1 * GiB);
1171 }
1172
1173 DeviceState *pc_vga_init(ISABus *isa_bus, PCIBus *pci_bus)
1174 {
1175     DeviceState *dev = NULL;
1176
1177     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_VGA);
1178     if (pci_bus) {
1179         PCIDevice *pcidev = pci_vga_init(pci_bus);
1180         dev = pcidev ? &pcidev->qdev : NULL;
1181     } else if (isa_bus) {
1182         ISADevice *isadev = isa_vga_init(isa_bus);
1183         dev = isadev ? DEVICE(isadev) : NULL;
1184     }
1185     rom_reset_order_override();
1186     return dev;
1187 }
1188
1189 static const MemoryRegionOps ioport80_io_ops = {
1190     .write = ioport80_write,
1191     .read = ioport80_read,
1192     .endianness = DEVICE_NATIVE_ENDIAN,
1193     .impl = {
1194         .min_access_size = 1,
1195         .max_access_size = 1,
1196     },
1197 };
1198
1199 static const MemoryRegionOps ioportF0_io_ops = {
1200     .write = ioportF0_write,
1201     .read = ioportF0_read,
1202     .endianness = DEVICE_NATIVE_ENDIAN,
1203     .impl = {
1204         .min_access_size = 1,
1205         .max_access_size = 1,
1206     },
1207 };
1208
1209 static void pc_superio_init(ISABus *isa_bus, bool create_fdctrl,
1210                             bool create_i8042, bool no_vmport)
1211 {
1212     int i;
1213     DriveInfo *fd[MAX_FD];
1214     qemu_irq *a20_line;
1215     ISADevice *fdc, *i8042, *port92, *vmmouse;
1216
1217     serial_hds_isa_init(isa_bus, 0, MAX_ISA_SERIAL_PORTS);
1218     parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);
1219
1220     for (i = 0; i < MAX_FD; i++) {
1221         fd[i] = drive_get(IF_FLOPPY, 0, i);
1222         create_fdctrl |= !!fd[i];
1223     }
1224     if (create_fdctrl) {
1225         fdc = isa_new(TYPE_ISA_FDC);
1226         if (fdc) {
1227             isa_realize_and_unref(fdc, isa_bus, &error_fatal);
1228             isa_fdc_init_drives(fdc, fd);
1229         }
1230     }
1231
1232     if (!create_i8042) {
1233         return;
1234     }
1235
1236     i8042 = isa_create_simple(isa_bus, TYPE_I8042);
1237     if (!no_vmport) {
1238         isa_create_simple(isa_bus, TYPE_VMPORT);
1239         vmmouse = isa_try_new("vmmouse");
1240     } else {
1241         vmmouse = NULL;
1242     }
1243     if (vmmouse) {
1244         object_property_set_link(OBJECT(vmmouse), TYPE_I8042, OBJECT(i8042),
1245                                  &error_abort);
1246         isa_realize_and_unref(vmmouse, isa_bus, &error_fatal);
1247     }
1248     port92 = isa_create_simple(isa_bus, TYPE_PORT92);
1249
1250     a20_line = qemu_allocate_irqs(handle_a20_line_change, first_cpu, 2);
1251     i8042_setup_a20_line(i8042, a20_line[0]);
1252     qdev_connect_gpio_out_named(DEVICE(port92),
1253                                 PORT92_A20_LINE, 0, a20_line[1]);
1254     g_free(a20_line);
1255 }
1256
1257 void pc_basic_device_init(struct PCMachineState *pcms,
1258                           ISABus *isa_bus, qemu_irq *gsi,
1259                           ISADevice **rtc_state,
1260                           bool create_fdctrl,
1261                           uint32_t hpet_irqs)
1262 {
1263     int i;
1264     DeviceState *hpet = NULL;
1265     int pit_isa_irq = 0;
1266     qemu_irq pit_alt_irq = NULL;
1267     qemu_irq rtc_irq = NULL;
1268     ISADevice *pit = NULL;
1269     MemoryRegion *ioport80_io = g_new(MemoryRegion, 1);
1270     MemoryRegion *ioportF0_io = g_new(MemoryRegion, 1);
1271     X86MachineState *x86ms = X86_MACHINE(pcms);
1272
1273     memory_region_init_io(ioport80_io, NULL, &ioport80_io_ops, NULL, "ioport80", 1);
1274     memory_region_add_subregion(isa_bus->address_space_io, 0x80, ioport80_io);
1275
1276     memory_region_init_io(ioportF0_io, NULL, &ioportF0_io_ops, NULL, "ioportF0", 1);
1277     memory_region_add_subregion(isa_bus->address_space_io, 0xf0, ioportF0_io);
1278
1279     /*
1280      * Check if an HPET shall be created.
1281      *
1282      * Without KVM_CAP_PIT_STATE2, we cannot switch off the in-kernel PIT
1283      * when the HPET wants to take over. Thus we have to disable the latter.
1284      */
1285     if (pcms->hpet_enabled && (!kvm_irqchip_in_kernel() ||
1286                                kvm_has_pit_state2())) {
1287         hpet = qdev_try_new(TYPE_HPET);
1288         if (!hpet) {
1289             error_report("couldn't create HPET device");
1290             exit(1);
1291         }
1292         /*
1293          * For pc-piix-*, hpet's intcap is always IRQ2. For pc-q35-1.7 and
1294          * earlier, use IRQ2 for compat. Otherwise, use IRQ16~23, IRQ8 and
1295          * IRQ2.
1296          */
1297         uint8_t compat = object_property_get_uint(OBJECT(hpet),
1298                 HPET_INTCAP, NULL);
1299         if (!compat) {
1300             qdev_prop_set_uint32(hpet, HPET_INTCAP, hpet_irqs);
1301         }
1302         sysbus_realize_and_unref(SYS_BUS_DEVICE(hpet), &error_fatal);
1303         sysbus_mmio_map(SYS_BUS_DEVICE(hpet), 0, HPET_BASE);
1304
1305         for (i = 0; i < IOAPIC_NUM_PINS; i++) {
1306             sysbus_connect_irq(SYS_BUS_DEVICE(hpet), i, gsi[i]);
1307         }
1308         pit_isa_irq = -1;
1309         pit_alt_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_PIT_INT);
1310         rtc_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_RTC_INT);
1311     }
1312     *rtc_state = ISA_DEVICE(mc146818_rtc_init(isa_bus, 2000, rtc_irq));
1313
1314 #ifdef CONFIG_XEN_EMU
1315     if (xen_mode == XEN_EMULATE) {
1316         xen_evtchn_connect_gsis(gsi);
1317     }
1318 #endif
1319
1320     qemu_register_boot_set(pc_boot_set, *rtc_state);
1321
1322     if (!xen_enabled() &&
1323         (x86ms->pit == ON_OFF_AUTO_AUTO || x86ms->pit == ON_OFF_AUTO_ON)) {
1324         if (kvm_pit_in_kernel()) {
1325             pit = kvm_pit_init(isa_bus, 0x40);
1326         } else {
1327             pit = i8254_pit_init(isa_bus, 0x40, pit_isa_irq, pit_alt_irq);
1328         }
1329         if (hpet) {
1330             /* connect PIT to output control line of the HPET */
1331             qdev_connect_gpio_out(hpet, 0, qdev_get_gpio_in(DEVICE(pit), 0));
1332         }
1333         pcspk_init(pcms->pcspk, isa_bus, pit);
1334     }
1335
1336     /* Super I/O */
1337     pc_superio_init(isa_bus, create_fdctrl, pcms->i8042_enabled,
1338                     pcms->vmport != ON_OFF_AUTO_ON);
1339 }
1340
1341 void pc_nic_init(PCMachineClass *pcmc, ISABus *isa_bus, PCIBus *pci_bus)
1342 {
1343     int i;
1344
1345     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_NIC);
1346     for (i = 0; i < nb_nics; i++) {
1347         NICInfo *nd = &nd_table[i];
1348         const char *model = nd->model ? nd->model : pcmc->default_nic_model;
1349
1350         if (g_str_equal(model, "ne2k_isa")) {
1351             pc_init_ne2k_isa(isa_bus, nd);
1352         } else {
1353             pci_nic_init_nofail(nd, pci_bus, model, NULL);
1354         }
1355     }
1356     rom_reset_order_override();
1357 }
1358
1359 void pc_i8259_create(ISABus *isa_bus, qemu_irq *i8259_irqs)
1360 {
1361     qemu_irq *i8259;
1362
1363     if (kvm_pic_in_kernel()) {
1364         i8259 = kvm_i8259_init(isa_bus);
1365     } else if (xen_enabled()) {
1366         i8259 = xen_interrupt_controller_init();
1367     } else {
1368         i8259 = i8259_init(isa_bus, x86_allocate_cpu_irq());
1369     }
1370
1371     for (size_t i = 0; i < ISA_NUM_IRQS; i++) {
1372         i8259_irqs[i] = i8259[i];
1373     }
1374
1375     g_free(i8259);
1376 }
1377
1378 static void pc_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
1379                                Error **errp)
1380 {
1381     const PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1382     const X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
1383     const PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
1384     const MachineState *ms = MACHINE(hotplug_dev);
1385     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1386     const uint64_t legacy_align = TARGET_PAGE_SIZE;
1387     Error *local_err = NULL;
1388
1389     /*
1390      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1391      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1392      * addition to cover this case.
1393      */
1394     if (!x86ms->acpi_dev || !x86_machine_is_acpi_enabled(x86ms)) {
1395         error_setg(errp,
1396                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1397         return;
1398     }
1399
1400     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
1401         error_setg(errp, "nvdimm is not enabled: missing 'nvdimm' in '-M'");
1402         return;
1403     }
1404
1405     hotplug_handler_pre_plug(x86ms->acpi_dev, dev, &local_err);
1406     if (local_err) {
1407         error_propagate(errp, local_err);
1408         return;
1409     }
1410
1411     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev),
1412                      pcmc->enforce_aligned_dimm ? NULL : &legacy_align, errp);
1413 }
1414
1415 static void pc_memory_plug(HotplugHandler *hotplug_dev,
1416                            DeviceState *dev, Error **errp)
1417 {
1418     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1419     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
1420     MachineState *ms = MACHINE(hotplug_dev);
1421     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1422
1423     pc_dimm_plug(PC_DIMM(dev), MACHINE(pcms));
1424
1425     if (is_nvdimm) {
1426         nvdimm_plug(ms->nvdimms_state);
1427     }
1428
1429     hotplug_handler_plug(x86ms->acpi_dev, dev, &error_abort);
1430 }
1431
1432 static void pc_memory_unplug_request(HotplugHandler *hotplug_dev,
1433                                      DeviceState *dev, Error **errp)
1434 {
1435     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
1436
1437     /*
1438      * When -no-acpi is used with Q35 machine type, no ACPI is built,
1439      * but pcms->acpi_dev is still created. Check !acpi_enabled in
1440      * addition to cover this case.
1441      */
1442     if (!x86ms->acpi_dev || !x86_machine_is_acpi_enabled(x86ms)) {
1443         error_setg(errp,
1444                    "memory hotplug is not enabled: missing acpi device or acpi disabled");
1445         return;
1446     }
1447
1448     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
1449         error_setg(errp, "nvdimm device hot unplug is not supported yet.");
1450         return;
1451     }
1452
1453     hotplug_handler_unplug_request(x86ms->acpi_dev, dev,
1454                                    errp);
1455 }
1456
1457 static void pc_memory_unplug(HotplugHandler *hotplug_dev,
1458                              DeviceState *dev, Error **errp)
1459 {
1460     PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1461     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
1462     Error *local_err = NULL;
1463
1464     hotplug_handler_unplug(x86ms->acpi_dev, dev, &local_err);
1465     if (local_err) {
1466         goto out;
1467     }
1468
1469     pc_dimm_unplug(PC_DIMM(dev), MACHINE(pcms));
1470     qdev_unrealize(dev);
1471  out:
1472     error_propagate(errp, local_err);
1473 }
1474
1475 static void pc_virtio_md_pci_pre_plug(HotplugHandler *hotplug_dev,
1476                                       DeviceState *dev, Error **errp)
1477 {
1478     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1479     Error *local_err = NULL;
1480
1481     if (!hotplug_dev2 && dev->hotplugged) {
1482         /*
1483          * Without a bus hotplug handler, we cannot control the plug/unplug
1484          * order. We should never reach this point when hotplugging on x86,
1485          * however, better add a safety net.
1486          */
1487         error_setg(errp, "hotplug of virtio based memory devices not supported"
1488                    " on this bus.");
1489         return;
1490     }
1491     /*
1492      * First, see if we can plug this memory device at all. If that
1493      * succeeds, branch of to the actual hotplug handler.
1494      */
1495     memory_device_pre_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev), NULL,
1496                            &local_err);
1497     if (!local_err && hotplug_dev2) {
1498         hotplug_handler_pre_plug(hotplug_dev2, dev, &local_err);
1499     }
1500     error_propagate(errp, local_err);
1501 }
1502
1503 static void pc_virtio_md_pci_plug(HotplugHandler *hotplug_dev,
1504                                   DeviceState *dev, Error **errp)
1505 {
1506     HotplugHandler *hotplug_dev2 = qdev_get_bus_hotplug_handler(dev);
1507     Error *local_err = NULL;
1508
1509     /*
1510      * Plug the memory device first and then branch off to the actual
1511      * hotplug handler. If that one fails, we can easily undo the memory
1512      * device bits.
1513      */
1514     memory_device_plug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1515     if (hotplug_dev2) {
1516         hotplug_handler_plug(hotplug_dev2, dev, &local_err);
1517         if (local_err) {
1518             memory_device_unplug(MEMORY_DEVICE(dev), MACHINE(hotplug_dev));
1519         }
1520     }
1521     error_propagate(errp, local_err);
1522 }
1523
1524 static void pc_virtio_md_pci_unplug_request(HotplugHandler *hotplug_dev,
1525                                             DeviceState *dev, Error **errp)
1526 {
1527     /* We don't support hot unplug of virtio based memory devices */
1528     error_setg(errp, "virtio based memory devices cannot be unplugged.");
1529 }
1530
1531 static void pc_virtio_md_pci_unplug(HotplugHandler *hotplug_dev,
1532                                     DeviceState *dev, Error **errp)
1533 {
1534     /* We don't support hot unplug of virtio based memory devices */
1535 }
1536
1537 static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
1538                                           DeviceState *dev, Error **errp)
1539 {
1540     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1541         pc_memory_pre_plug(hotplug_dev, dev, errp);
1542     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1543         x86_cpu_pre_plug(hotplug_dev, dev, errp);
1544     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
1545                object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MEM_PCI)) {
1546         pc_virtio_md_pci_pre_plug(hotplug_dev, dev, errp);
1547     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
1548         /* Declare the APIC range as the reserved MSI region */
1549         char *resv_prop_str = g_strdup_printf("0xfee00000:0xfeefffff:%d",
1550                                               VIRTIO_IOMMU_RESV_MEM_T_MSI);
1551
1552         object_property_set_uint(OBJECT(dev), "len-reserved-regions", 1, errp);
1553         object_property_set_str(OBJECT(dev), "reserved-regions[0]",
1554                                 resv_prop_str, errp);
1555         g_free(resv_prop_str);
1556     }
1557
1558     if (object_dynamic_cast(OBJECT(dev), TYPE_X86_IOMMU_DEVICE) ||
1559         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
1560         PCMachineState *pcms = PC_MACHINE(hotplug_dev);
1561
1562         if (pcms->iommu) {
1563             error_setg(errp, "QEMU does not support multiple vIOMMUs "
1564                        "for x86 yet.");
1565             return;
1566         }
1567         pcms->iommu = dev;
1568     }
1569 }
1570
1571 static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
1572                                       DeviceState *dev, Error **errp)
1573 {
1574     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1575         pc_memory_plug(hotplug_dev, dev, errp);
1576     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1577         x86_cpu_plug(hotplug_dev, dev, errp);
1578     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
1579                object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MEM_PCI)) {
1580         pc_virtio_md_pci_plug(hotplug_dev, dev, errp);
1581     }
1582 }
1583
1584 static void pc_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
1585                                                 DeviceState *dev, Error **errp)
1586 {
1587     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1588         pc_memory_unplug_request(hotplug_dev, dev, errp);
1589     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1590         x86_cpu_unplug_request_cb(hotplug_dev, dev, errp);
1591     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
1592                object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MEM_PCI)) {
1593         pc_virtio_md_pci_unplug_request(hotplug_dev, dev, errp);
1594     } else {
1595         error_setg(errp, "acpi: device unplug request for not supported device"
1596                    " type: %s", object_get_typename(OBJECT(dev)));
1597     }
1598 }
1599
1600 static void pc_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
1601                                         DeviceState *dev, Error **errp)
1602 {
1603     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
1604         pc_memory_unplug(hotplug_dev, dev, errp);
1605     } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {
1606         x86_cpu_unplug_cb(hotplug_dev, dev, errp);
1607     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
1608                object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MEM_PCI)) {
1609         pc_virtio_md_pci_unplug(hotplug_dev, dev, errp);
1610     } else {
1611         error_setg(errp, "acpi: device unplug for not supported device"
1612                    " type: %s", object_get_typename(OBJECT(dev)));
1613     }
1614 }
1615
1616 static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
1617                                              DeviceState *dev)
1618 {
1619     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
1620         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
1621         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
1622         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MEM_PCI) ||
1623         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI) ||
1624         object_dynamic_cast(OBJECT(dev), TYPE_X86_IOMMU_DEVICE)) {
1625         return HOTPLUG_HANDLER(machine);
1626     }
1627
1628     return NULL;
1629 }
1630
1631 static void
1632 pc_machine_get_device_memory_region_size(Object *obj, Visitor *v,
1633                                          const char *name, void *opaque,
1634                                          Error **errp)
1635 {
1636     MachineState *ms = MACHINE(obj);
1637     int64_t value = 0;
1638
1639     if (ms->device_memory) {
1640         value = memory_region_size(&ms->device_memory->mr);
1641     }
1642
1643     visit_type_int(v, name, &value, errp);
1644 }
1645
1646 static void pc_machine_get_vmport(Object *obj, Visitor *v, const char *name,
1647                                   void *opaque, Error **errp)
1648 {
1649     PCMachineState *pcms = PC_MACHINE(obj);
1650     OnOffAuto vmport = pcms->vmport;
1651
1652     visit_type_OnOffAuto(v, name, &vmport, errp);
1653 }
1654
1655 static void pc_machine_set_vmport(Object *obj, Visitor *v, const char *name,
1656                                   void *opaque, Error **errp)
1657 {
1658     PCMachineState *pcms = PC_MACHINE(obj);
1659
1660     visit_type_OnOffAuto(v, name, &pcms->vmport, errp);
1661 }
1662
1663 static bool pc_machine_get_smbus(Object *obj, Error **errp)
1664 {
1665     PCMachineState *pcms = PC_MACHINE(obj);
1666
1667     return pcms->smbus_enabled;
1668 }
1669
1670 static void pc_machine_set_smbus(Object *obj, bool value, Error **errp)
1671 {
1672     PCMachineState *pcms = PC_MACHINE(obj);
1673
1674     pcms->smbus_enabled = value;
1675 }
1676
1677 static bool pc_machine_get_sata(Object *obj, Error **errp)
1678 {
1679     PCMachineState *pcms = PC_MACHINE(obj);
1680
1681     return pcms->sata_enabled;
1682 }
1683
1684 static void pc_machine_set_sata(Object *obj, bool value, Error **errp)
1685 {
1686     PCMachineState *pcms = PC_MACHINE(obj);
1687
1688     pcms->sata_enabled = value;
1689 }
1690
1691 static bool pc_machine_get_hpet(Object *obj, Error **errp)
1692 {
1693     PCMachineState *pcms = PC_MACHINE(obj);
1694
1695     return pcms->hpet_enabled;
1696 }
1697
1698 static void pc_machine_set_hpet(Object *obj, bool value, Error **errp)
1699 {
1700     PCMachineState *pcms = PC_MACHINE(obj);
1701
1702     pcms->hpet_enabled = value;
1703 }
1704
1705 static bool pc_machine_get_i8042(Object *obj, Error **errp)
1706 {
1707     PCMachineState *pcms = PC_MACHINE(obj);
1708
1709     return pcms->i8042_enabled;
1710 }
1711
1712 static void pc_machine_set_i8042(Object *obj, bool value, Error **errp)
1713 {
1714     PCMachineState *pcms = PC_MACHINE(obj);
1715
1716     pcms->i8042_enabled = value;
1717 }
1718
1719 static bool pc_machine_get_default_bus_bypass_iommu(Object *obj, Error **errp)
1720 {
1721     PCMachineState *pcms = PC_MACHINE(obj);
1722
1723     return pcms->default_bus_bypass_iommu;
1724 }
1725
1726 static void pc_machine_set_default_bus_bypass_iommu(Object *obj, bool value,
1727                                                     Error **errp)
1728 {
1729     PCMachineState *pcms = PC_MACHINE(obj);
1730
1731     pcms->default_bus_bypass_iommu = value;
1732 }
1733
1734 static void pc_machine_get_smbios_ep(Object *obj, Visitor *v, const char *name,
1735                                      void *opaque, Error **errp)
1736 {
1737     PCMachineState *pcms = PC_MACHINE(obj);
1738     SmbiosEntryPointType smbios_entry_point_type = pcms->smbios_entry_point_type;
1739
1740     visit_type_SmbiosEntryPointType(v, name, &smbios_entry_point_type, errp);
1741 }
1742
1743 static void pc_machine_set_smbios_ep(Object *obj, Visitor *v, const char *name,
1744                                      void *opaque, Error **errp)
1745 {
1746     PCMachineState *pcms = PC_MACHINE(obj);
1747
1748     visit_type_SmbiosEntryPointType(v, name, &pcms->smbios_entry_point_type, errp);
1749 }
1750
1751 static void pc_machine_get_max_ram_below_4g(Object *obj, Visitor *v,
1752                                             const char *name, void *opaque,
1753                                             Error **errp)
1754 {
1755     PCMachineState *pcms = PC_MACHINE(obj);
1756     uint64_t value = pcms->max_ram_below_4g;
1757
1758     visit_type_size(v, name, &value, errp);
1759 }
1760
1761 static void pc_machine_set_max_ram_below_4g(Object *obj, Visitor *v,
1762                                             const char *name, void *opaque,
1763                                             Error **errp)
1764 {
1765     PCMachineState *pcms = PC_MACHINE(obj);
1766     uint64_t value;
1767
1768     if (!visit_type_size(v, name, &value, errp)) {
1769         return;
1770     }
1771     if (value > 4 * GiB) {
1772         error_setg(errp,
1773                    "Machine option 'max-ram-below-4g=%"PRIu64
1774                    "' expects size less than or equal to 4G", value);
1775         return;
1776     }
1777
1778     if (value < 1 * MiB) {
1779         warn_report("Only %" PRIu64 " bytes of RAM below the 4GiB boundary,"
1780                     "BIOS may not work with less than 1MiB", value);
1781     }
1782
1783     pcms->max_ram_below_4g = value;
1784 }
1785
1786 static void pc_machine_get_max_fw_size(Object *obj, Visitor *v,
1787                                        const char *name, void *opaque,
1788                                        Error **errp)
1789 {
1790     PCMachineState *pcms = PC_MACHINE(obj);
1791     uint64_t value = pcms->max_fw_size;
1792
1793     visit_type_size(v, name, &value, errp);
1794 }
1795
1796 static void pc_machine_set_max_fw_size(Object *obj, Visitor *v,
1797                                        const char *name, void *opaque,
1798                                        Error **errp)
1799 {
1800     PCMachineState *pcms = PC_MACHINE(obj);
1801     uint64_t value;
1802
1803     if (!visit_type_size(v, name, &value, errp)) {
1804         return;
1805     }
1806
1807     /*
1808     * We don't have a theoretically justifiable exact lower bound on the base
1809     * address of any flash mapping. In practice, the IO-APIC MMIO range is
1810     * [0xFEE00000..0xFEE01000] -- see IO_APIC_DEFAULT_ADDRESS --, leaving free
1811     * only 18MB-4KB below 4G. For now, restrict the cumulative mapping to 8MB in
1812     * size.
1813     */
1814     if (value > 16 * MiB) {
1815         error_setg(errp,
1816                    "User specified max allowed firmware size %" PRIu64 " is "
1817                    "greater than 16MiB. If combined firwmare size exceeds "
1818                    "16MiB the system may not boot, or experience intermittent"
1819                    "stability issues.",
1820                    value);
1821         return;
1822     }
1823
1824     pcms->max_fw_size = value;
1825 }
1826
1827
1828 static void pc_machine_initfn(Object *obj)
1829 {
1830     PCMachineState *pcms = PC_MACHINE(obj);
1831
1832 #ifdef CONFIG_VMPORT
1833     pcms->vmport = ON_OFF_AUTO_AUTO;
1834 #else
1835     pcms->vmport = ON_OFF_AUTO_OFF;
1836 #endif /* CONFIG_VMPORT */
1837     pcms->max_ram_below_4g = 0; /* use default */
1838     pcms->smbios_entry_point_type = SMBIOS_ENTRY_POINT_TYPE_32;
1839
1840     /* acpi build is enabled by default if machine supports it */
1841     pcms->acpi_build_enabled = PC_MACHINE_GET_CLASS(pcms)->has_acpi_build;
1842     pcms->smbus_enabled = true;
1843     pcms->sata_enabled = true;
1844     pcms->i8042_enabled = true;
1845     pcms->max_fw_size = 8 * MiB;
1846 #ifdef CONFIG_HPET
1847     pcms->hpet_enabled = true;
1848 #endif
1849     pcms->default_bus_bypass_iommu = false;
1850
1851     pc_system_flash_create(pcms);
1852     pcms->pcspk = isa_new(TYPE_PC_SPEAKER);
1853     object_property_add_alias(OBJECT(pcms), "pcspk-audiodev",
1854                               OBJECT(pcms->pcspk), "audiodev");
1855     cxl_machine_init(obj, &pcms->cxl_devices_state);
1856 }
1857
1858 int pc_machine_kvm_type(MachineState *machine, const char *kvm_type)
1859 {
1860 #ifdef CONFIG_XEN_EMU
1861     if (xen_mode == XEN_EMULATE) {
1862         xen_overlay_create();
1863         xen_evtchn_create();
1864         xen_gnttab_create();
1865     }
1866 #endif
1867     return 0;
1868 }
1869
1870 static void pc_machine_reset(MachineState *machine, ShutdownCause reason)
1871 {
1872     CPUState *cs;
1873     X86CPU *cpu;
1874
1875     qemu_devices_reset(reason);
1876
1877     /* Reset APIC after devices have been reset to cancel
1878      * any changes that qemu_devices_reset() might have done.
1879      */
1880     CPU_FOREACH(cs) {
1881         cpu = X86_CPU(cs);
1882
1883         x86_cpu_after_reset(cpu);
1884     }
1885 }
1886
1887 static void pc_machine_wakeup(MachineState *machine)
1888 {
1889     cpu_synchronize_all_states();
1890     pc_machine_reset(machine, SHUTDOWN_CAUSE_NONE);
1891     cpu_synchronize_all_post_reset();
1892 }
1893
1894 static bool pc_hotplug_allowed(MachineState *ms, DeviceState *dev, Error **errp)
1895 {
1896     X86IOMMUState *iommu = x86_iommu_get_default();
1897     IntelIOMMUState *intel_iommu;
1898
1899     if (iommu &&
1900         object_dynamic_cast((Object *)iommu, TYPE_INTEL_IOMMU_DEVICE) &&
1901         object_dynamic_cast((Object *)dev, "vfio-pci")) {
1902         intel_iommu = INTEL_IOMMU_DEVICE(iommu);
1903         if (!intel_iommu->caching_mode) {
1904             error_setg(errp, "Device assignment is not allowed without "
1905                        "enabling caching-mode=on for Intel IOMMU.");
1906             return false;
1907         }
1908     }
1909
1910     return true;
1911 }
1912
1913 static void pc_machine_class_init(ObjectClass *oc, void *data)
1914 {
1915     MachineClass *mc = MACHINE_CLASS(oc);
1916     PCMachineClass *pcmc = PC_MACHINE_CLASS(oc);
1917     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
1918
1919     pcmc->pci_enabled = true;
1920     pcmc->has_acpi_build = true;
1921     pcmc->rsdp_in_ram = true;
1922     pcmc->smbios_defaults = true;
1923     pcmc->smbios_uuid_encoded = true;
1924     pcmc->gigabyte_align = true;
1925     pcmc->has_reserved_memory = true;
1926     pcmc->kvmclock_enabled = true;
1927     pcmc->enforce_aligned_dimm = true;
1928     pcmc->enforce_amd_1tb_hole = true;
1929     /* BIOS ACPI tables: 128K. Other BIOS datastructures: less than 4K reported
1930      * to be used at the moment, 32K should be enough for a while.  */
1931     pcmc->acpi_data_size = 0x20000 + 0x8000;
1932     pcmc->pvh_enabled = true;
1933     pcmc->kvmclock_create_always = true;
1934     assert(!mc->get_hotplug_handler);
1935     mc->get_hotplug_handler = pc_get_hotplug_handler;
1936     mc->hotplug_allowed = pc_hotplug_allowed;
1937     mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
1938     mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
1939     mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
1940     mc->auto_enable_numa_with_memhp = true;
1941     mc->auto_enable_numa_with_memdev = true;
1942     mc->has_hotpluggable_cpus = true;
1943     mc->default_boot_order = "cad";
1944     mc->block_default_type = IF_IDE;
1945     mc->max_cpus = 255;
1946     mc->reset = pc_machine_reset;
1947     mc->wakeup = pc_machine_wakeup;
1948     hc->pre_plug = pc_machine_device_pre_plug_cb;
1949     hc->plug = pc_machine_device_plug_cb;
1950     hc->unplug_request = pc_machine_device_unplug_request_cb;
1951     hc->unplug = pc_machine_device_unplug_cb;
1952     mc->default_cpu_type = TARGET_DEFAULT_CPU_TYPE;
1953     mc->nvdimm_supported = true;
1954     mc->smp_props.dies_supported = true;
1955     mc->default_ram_id = "pc.ram";
1956
1957     object_class_property_add(oc, PC_MACHINE_MAX_RAM_BELOW_4G, "size",
1958         pc_machine_get_max_ram_below_4g, pc_machine_set_max_ram_below_4g,
1959         NULL, NULL);
1960     object_class_property_set_description(oc, PC_MACHINE_MAX_RAM_BELOW_4G,
1961         "Maximum ram below the 4G boundary (32bit boundary)");
1962
1963     object_class_property_add(oc, PC_MACHINE_DEVMEM_REGION_SIZE, "int",
1964         pc_machine_get_device_memory_region_size, NULL,
1965         NULL, NULL);
1966
1967     object_class_property_add(oc, PC_MACHINE_VMPORT, "OnOffAuto",
1968         pc_machine_get_vmport, pc_machine_set_vmport,
1969         NULL, NULL);
1970     object_class_property_set_description(oc, PC_MACHINE_VMPORT,
1971         "Enable vmport (pc & q35)");
1972
1973     object_class_property_add_bool(oc, PC_MACHINE_SMBUS,
1974         pc_machine_get_smbus, pc_machine_set_smbus);
1975     object_class_property_set_description(oc, PC_MACHINE_SMBUS,
1976         "Enable/disable system management bus");
1977
1978     object_class_property_add_bool(oc, PC_MACHINE_SATA,
1979         pc_machine_get_sata, pc_machine_set_sata);
1980     object_class_property_set_description(oc, PC_MACHINE_SATA,
1981         "Enable/disable Serial ATA bus");
1982
1983     object_class_property_add_bool(oc, "hpet",
1984         pc_machine_get_hpet, pc_machine_set_hpet);
1985     object_class_property_set_description(oc, "hpet",
1986         "Enable/disable high precision event timer emulation");
1987
1988     object_class_property_add_bool(oc, PC_MACHINE_I8042,
1989         pc_machine_get_i8042, pc_machine_set_i8042);
1990
1991     object_class_property_add_bool(oc, "default-bus-bypass-iommu",
1992         pc_machine_get_default_bus_bypass_iommu,
1993         pc_machine_set_default_bus_bypass_iommu);
1994
1995     object_class_property_add(oc, PC_MACHINE_MAX_FW_SIZE, "size",
1996         pc_machine_get_max_fw_size, pc_machine_set_max_fw_size,
1997         NULL, NULL);
1998     object_class_property_set_description(oc, PC_MACHINE_MAX_FW_SIZE,
1999         "Maximum combined firmware size");
2000
2001     object_class_property_add(oc, PC_MACHINE_SMBIOS_EP, "str",
2002         pc_machine_get_smbios_ep, pc_machine_set_smbios_ep,
2003         NULL, NULL);
2004     object_class_property_set_description(oc, PC_MACHINE_SMBIOS_EP,
2005         "SMBIOS Entry Point type [32, 64]");
2006 }
2007
2008 static const TypeInfo pc_machine_info = {
2009     .name = TYPE_PC_MACHINE,
2010     .parent = TYPE_X86_MACHINE,
2011     .abstract = true,
2012     .instance_size = sizeof(PCMachineState),
2013     .instance_init = pc_machine_initfn,
2014     .class_size = sizeof(PCMachineClass),
2015     .class_init = pc_machine_class_init,
2016     .interfaces = (InterfaceInfo[]) {
2017          { TYPE_HOTPLUG_HANDLER },
2018          { }
2019     },
2020 };
2021
2022 static void pc_machine_register_types(void)
2023 {
2024     type_register_static(&pc_machine_info);
2025 }
2026
2027 type_init(pc_machine_register_types)