xref: /openbmc/qemu/hw/i386/x86.c (revision ff5b5739)
1 /*
2  * Copyright (c) 2003-2004 Fabrice Bellard
3  * Copyright (c) 2019 Red Hat, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE.
22  */
23 #include "qemu/osdep.h"
24 #include "qemu/error-report.h"
25 #include "qemu/option.h"
26 #include "qemu/cutils.h"
27 #include "qemu/units.h"
28 #include "qemu/datadir.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-common.h"
31 #include "qapi/clone-visitor.h"
32 #include "qapi/qapi-visit-machine.h"
33 #include "qapi/visitor.h"
34 #include "sysemu/qtest.h"
35 #include "sysemu/whpx.h"
36 #include "sysemu/numa.h"
37 #include "sysemu/replay.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/cpu-timers.h"
40 #include "sysemu/xen.h"
41 #include "trace.h"
42 
43 #include "hw/i386/x86.h"
44 #include "target/i386/cpu.h"
45 #include "hw/i386/topology.h"
46 #include "hw/i386/fw_cfg.h"
47 #include "hw/intc/i8259.h"
48 #include "hw/rtc/mc146818rtc.h"
49 #include "target/i386/sev.h"
50 
51 #include "hw/acpi/cpu_hotplug.h"
52 #include "hw/irq.h"
53 #include "hw/nmi.h"
54 #include "hw/loader.h"
55 #include "multiboot.h"
56 #include "elf.h"
57 #include "standard-headers/asm-x86/bootparam.h"
58 #include CONFIG_DEVICES
59 #include "kvm/kvm_i386.h"
60 
61 #ifdef CONFIG_XEN_EMU
62 #include "hw/xen/xen.h"
63 #include "hw/i386/kvm/xen_evtchn.h"
64 #endif
65 
66 /* Physical Address of PVH entry point read from kernel ELF NOTE */
67 static size_t pvh_start_addr;
68 
69 static void init_topo_info(X86CPUTopoInfo *topo_info,
70                            const X86MachineState *x86ms)
71 {
72     MachineState *ms = MACHINE(x86ms);
73 
74     topo_info->dies_per_pkg = ms->smp.dies;
75     topo_info->cores_per_die = ms->smp.cores;
76     topo_info->threads_per_core = ms->smp.threads;
77 }
78 
79 /*
80  * Calculates initial APIC ID for a specific CPU index
81  *
82  * Currently we need to be able to calculate the APIC ID from the CPU index
83  * alone (without requiring a CPU object), as the QEMU<->Seabios interfaces have
84  * no concept of "CPU index", and the NUMA tables on fw_cfg need the APIC ID of
85  * all CPUs up to max_cpus.
86  */
87 uint32_t x86_cpu_apic_id_from_index(X86MachineState *x86ms,
88                                     unsigned int cpu_index)
89 {
90     X86CPUTopoInfo topo_info;
91 
92     init_topo_info(&topo_info, x86ms);
93 
94     return x86_apicid_from_cpu_idx(&topo_info, cpu_index);
95 }
96 
97 
98 void x86_cpu_new(X86MachineState *x86ms, int64_t apic_id, Error **errp)
99 {
100     Object *cpu = object_new(MACHINE(x86ms)->cpu_type);
101 
102     if (!object_property_set_uint(cpu, "apic-id", apic_id, errp)) {
103         goto out;
104     }
105     qdev_realize(DEVICE(cpu), NULL, errp);
106 
107 out:
108     object_unref(cpu);
109 }
110 
111 void x86_cpus_init(X86MachineState *x86ms, int default_cpu_version)
112 {
113     int i;
114     const CPUArchIdList *possible_cpus;
115     MachineState *ms = MACHINE(x86ms);
116     MachineClass *mc = MACHINE_GET_CLASS(x86ms);
117 
118     x86_cpu_set_default_version(default_cpu_version);
119 
120     /*
121      * Calculates the limit to CPU APIC ID values
122      *
123      * Limit for the APIC ID value, so that all
124      * CPU APIC IDs are < x86ms->apic_id_limit.
125      *
126      * This is used for FW_CFG_MAX_CPUS. See comments on fw_cfg_arch_create().
127      */
128     x86ms->apic_id_limit = x86_cpu_apic_id_from_index(x86ms,
129                                                       ms->smp.max_cpus - 1) + 1;
130 
131     /*
132      * Can we support APIC ID 255 or higher?  With KVM, that requires
133      * both in-kernel lapic and X2APIC userspace API.
134      *
135      * kvm_enabled() must go first to ensure that kvm_* references are
136      * not emitted for the linker to consume (kvm_enabled() is
137      * a literal `0` in configurations where kvm_* aren't defined)
138      */
139     if (kvm_enabled() && x86ms->apic_id_limit > 255 &&
140         kvm_irqchip_in_kernel() && !kvm_enable_x2apic()) {
141         error_report("current -smp configuration requires kernel "
142                      "irqchip and X2APIC API support.");
143         exit(EXIT_FAILURE);
144     }
145 
146     if (kvm_enabled()) {
147         kvm_set_max_apic_id(x86ms->apic_id_limit);
148     }
149 
150     if (!kvm_irqchip_in_kernel()) {
151         apic_set_max_apic_id(x86ms->apic_id_limit);
152     }
153 
154     possible_cpus = mc->possible_cpu_arch_ids(ms);
155     for (i = 0; i < ms->smp.cpus; i++) {
156         x86_cpu_new(x86ms, possible_cpus->cpus[i].arch_id, &error_fatal);
157     }
158 }
159 
160 void x86_rtc_set_cpus_count(ISADevice *s, uint16_t cpus_count)
161 {
162     MC146818RtcState *rtc = MC146818_RTC(s);
163 
164     if (cpus_count > 0xff) {
165         /*
166          * If the number of CPUs can't be represented in 8 bits, the
167          * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
168          * to make old BIOSes fail more predictably.
169          */
170         mc146818rtc_set_cmos_data(rtc, 0x5f, 0);
171     } else {
172         mc146818rtc_set_cmos_data(rtc, 0x5f, cpus_count - 1);
173     }
174 }
175 
176 static int x86_apic_cmp(const void *a, const void *b)
177 {
178    CPUArchId *apic_a = (CPUArchId *)a;
179    CPUArchId *apic_b = (CPUArchId *)b;
180 
181    return apic_a->arch_id - apic_b->arch_id;
182 }
183 
184 /*
185  * returns pointer to CPUArchId descriptor that matches CPU's apic_id
186  * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
187  * entry corresponding to CPU's apic_id returns NULL.
188  */
189 CPUArchId *x86_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
190 {
191     CPUArchId apic_id, *found_cpu;
192 
193     apic_id.arch_id = id;
194     found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
195         ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
196         x86_apic_cmp);
197     if (found_cpu && idx) {
198         *idx = found_cpu - ms->possible_cpus->cpus;
199     }
200     return found_cpu;
201 }
202 
203 void x86_cpu_plug(HotplugHandler *hotplug_dev,
204                   DeviceState *dev, Error **errp)
205 {
206     CPUArchId *found_cpu;
207     Error *local_err = NULL;
208     X86CPU *cpu = X86_CPU(dev);
209     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
210 
211     if (x86ms->acpi_dev) {
212         hotplug_handler_plug(x86ms->acpi_dev, dev, &local_err);
213         if (local_err) {
214             goto out;
215         }
216     }
217 
218     /* increment the number of CPUs */
219     x86ms->boot_cpus++;
220     if (x86ms->rtc) {
221         x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
222     }
223     if (x86ms->fw_cfg) {
224         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
225     }
226 
227     found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
228     found_cpu->cpu = CPU(dev);
229 out:
230     error_propagate(errp, local_err);
231 }
232 
233 void x86_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
234                                DeviceState *dev, Error **errp)
235 {
236     int idx = -1;
237     X86CPU *cpu = X86_CPU(dev);
238     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
239 
240     if (!x86ms->acpi_dev) {
241         error_setg(errp, "CPU hot unplug not supported without ACPI");
242         return;
243     }
244 
245     x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
246     assert(idx != -1);
247     if (idx == 0) {
248         error_setg(errp, "Boot CPU is unpluggable");
249         return;
250     }
251 
252     hotplug_handler_unplug_request(x86ms->acpi_dev, dev,
253                                    errp);
254 }
255 
256 void x86_cpu_unplug_cb(HotplugHandler *hotplug_dev,
257                        DeviceState *dev, Error **errp)
258 {
259     CPUArchId *found_cpu;
260     Error *local_err = NULL;
261     X86CPU *cpu = X86_CPU(dev);
262     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
263 
264     hotplug_handler_unplug(x86ms->acpi_dev, dev, &local_err);
265     if (local_err) {
266         goto out;
267     }
268 
269     found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
270     found_cpu->cpu = NULL;
271     qdev_unrealize(dev);
272 
273     /* decrement the number of CPUs */
274     x86ms->boot_cpus--;
275     /* Update the number of CPUs in CMOS */
276     x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
277     fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
278  out:
279     error_propagate(errp, local_err);
280 }
281 
282 void x86_cpu_pre_plug(HotplugHandler *hotplug_dev,
283                       DeviceState *dev, Error **errp)
284 {
285     int idx;
286     CPUState *cs;
287     CPUArchId *cpu_slot;
288     X86CPUTopoIDs topo_ids;
289     X86CPU *cpu = X86_CPU(dev);
290     CPUX86State *env = &cpu->env;
291     MachineState *ms = MACHINE(hotplug_dev);
292     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
293     unsigned int smp_cores = ms->smp.cores;
294     unsigned int smp_threads = ms->smp.threads;
295     X86CPUTopoInfo topo_info;
296 
297     if (!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
298         error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
299                    ms->cpu_type);
300         return;
301     }
302 
303     if (x86ms->acpi_dev) {
304         Error *local_err = NULL;
305 
306         hotplug_handler_pre_plug(HOTPLUG_HANDLER(x86ms->acpi_dev), dev,
307                                  &local_err);
308         if (local_err) {
309             error_propagate(errp, local_err);
310             return;
311         }
312     }
313 
314     init_topo_info(&topo_info, x86ms);
315 
316     env->nr_dies = ms->smp.dies;
317 
318     /*
319      * If APIC ID is not set,
320      * set it based on socket/die/core/thread properties.
321      */
322     if (cpu->apic_id == UNASSIGNED_APIC_ID) {
323         int max_socket = (ms->smp.max_cpus - 1) /
324                                 smp_threads / smp_cores / ms->smp.dies;
325 
326         /*
327          * die-id was optional in QEMU 4.0 and older, so keep it optional
328          * if there's only one die per socket.
329          */
330         if (cpu->die_id < 0 && ms->smp.dies == 1) {
331             cpu->die_id = 0;
332         }
333 
334         if (cpu->socket_id < 0) {
335             error_setg(errp, "CPU socket-id is not set");
336             return;
337         } else if (cpu->socket_id > max_socket) {
338             error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
339                        cpu->socket_id, max_socket);
340             return;
341         }
342         if (cpu->die_id < 0) {
343             error_setg(errp, "CPU die-id is not set");
344             return;
345         } else if (cpu->die_id > ms->smp.dies - 1) {
346             error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
347                        cpu->die_id, ms->smp.dies - 1);
348             return;
349         }
350         if (cpu->core_id < 0) {
351             error_setg(errp, "CPU core-id is not set");
352             return;
353         } else if (cpu->core_id > (smp_cores - 1)) {
354             error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
355                        cpu->core_id, smp_cores - 1);
356             return;
357         }
358         if (cpu->thread_id < 0) {
359             error_setg(errp, "CPU thread-id is not set");
360             return;
361         } else if (cpu->thread_id > (smp_threads - 1)) {
362             error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
363                        cpu->thread_id, smp_threads - 1);
364             return;
365         }
366 
367         topo_ids.pkg_id = cpu->socket_id;
368         topo_ids.die_id = cpu->die_id;
369         topo_ids.core_id = cpu->core_id;
370         topo_ids.smt_id = cpu->thread_id;
371         cpu->apic_id = x86_apicid_from_topo_ids(&topo_info, &topo_ids);
372     }
373 
374     cpu_slot = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
375     if (!cpu_slot) {
376         x86_topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
377         error_setg(errp,
378             "Invalid CPU [socket: %u, die: %u, core: %u, thread: %u] with"
379             " APIC ID %" PRIu32 ", valid index range 0:%d",
380             topo_ids.pkg_id, topo_ids.die_id, topo_ids.core_id, topo_ids.smt_id,
381             cpu->apic_id, ms->possible_cpus->len - 1);
382         return;
383     }
384 
385     if (cpu_slot->cpu) {
386         error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
387                    idx, cpu->apic_id);
388         return;
389     }
390 
391     /* if 'address' properties socket-id/core-id/thread-id are not set, set them
392      * so that machine_query_hotpluggable_cpus would show correct values
393      */
394     /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
395      * once -smp refactoring is complete and there will be CPU private
396      * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
397     x86_topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
398     if (cpu->socket_id != -1 && cpu->socket_id != topo_ids.pkg_id) {
399         error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
400             " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id,
401             topo_ids.pkg_id);
402         return;
403     }
404     cpu->socket_id = topo_ids.pkg_id;
405 
406     if (cpu->die_id != -1 && cpu->die_id != topo_ids.die_id) {
407         error_setg(errp, "property die-id: %u doesn't match set apic-id:"
408             " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo_ids.die_id);
409         return;
410     }
411     cpu->die_id = topo_ids.die_id;
412 
413     if (cpu->core_id != -1 && cpu->core_id != topo_ids.core_id) {
414         error_setg(errp, "property core-id: %u doesn't match set apic-id:"
415             " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id,
416             topo_ids.core_id);
417         return;
418     }
419     cpu->core_id = topo_ids.core_id;
420 
421     if (cpu->thread_id != -1 && cpu->thread_id != topo_ids.smt_id) {
422         error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
423             " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id,
424             topo_ids.smt_id);
425         return;
426     }
427     cpu->thread_id = topo_ids.smt_id;
428 
429     /*
430     * kvm_enabled() must go first to ensure that kvm_* references are
431     * not emitted for the linker to consume (kvm_enabled() is
432     * a literal `0` in configurations where kvm_* aren't defined)
433     */
434     if (kvm_enabled() && hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
435         !kvm_hv_vpindex_settable()) {
436         error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
437         return;
438     }
439 
440     cs = CPU(cpu);
441     cs->cpu_index = idx;
442 
443     numa_cpu_pre_plug(cpu_slot, dev, errp);
444 }
445 
446 CpuInstanceProperties
447 x86_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
448 {
449     MachineClass *mc = MACHINE_GET_CLASS(ms);
450     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
451 
452     assert(cpu_index < possible_cpus->len);
453     return possible_cpus->cpus[cpu_index].props;
454 }
455 
456 int64_t x86_get_default_cpu_node_id(const MachineState *ms, int idx)
457 {
458    X86CPUTopoIDs topo_ids;
459    X86MachineState *x86ms = X86_MACHINE(ms);
460    X86CPUTopoInfo topo_info;
461 
462    init_topo_info(&topo_info, x86ms);
463 
464    assert(idx < ms->possible_cpus->len);
465    x86_topo_ids_from_apicid(ms->possible_cpus->cpus[idx].arch_id,
466                             &topo_info, &topo_ids);
467    return topo_ids.pkg_id % ms->numa_state->num_nodes;
468 }
469 
470 const CPUArchIdList *x86_possible_cpu_arch_ids(MachineState *ms)
471 {
472     X86MachineState *x86ms = X86_MACHINE(ms);
473     unsigned int max_cpus = ms->smp.max_cpus;
474     X86CPUTopoInfo topo_info;
475     int i;
476 
477     if (ms->possible_cpus) {
478         /*
479          * make sure that max_cpus hasn't changed since the first use, i.e.
480          * -smp hasn't been parsed after it
481          */
482         assert(ms->possible_cpus->len == max_cpus);
483         return ms->possible_cpus;
484     }
485 
486     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
487                                   sizeof(CPUArchId) * max_cpus);
488     ms->possible_cpus->len = max_cpus;
489 
490     init_topo_info(&topo_info, x86ms);
491 
492     for (i = 0; i < ms->possible_cpus->len; i++) {
493         X86CPUTopoIDs topo_ids;
494 
495         ms->possible_cpus->cpus[i].type = ms->cpu_type;
496         ms->possible_cpus->cpus[i].vcpus_count = 1;
497         ms->possible_cpus->cpus[i].arch_id =
498             x86_cpu_apic_id_from_index(x86ms, i);
499         x86_topo_ids_from_apicid(ms->possible_cpus->cpus[i].arch_id,
500                                  &topo_info, &topo_ids);
501         ms->possible_cpus->cpus[i].props.has_socket_id = true;
502         ms->possible_cpus->cpus[i].props.socket_id = topo_ids.pkg_id;
503         if (ms->smp.dies > 1) {
504             ms->possible_cpus->cpus[i].props.has_die_id = true;
505             ms->possible_cpus->cpus[i].props.die_id = topo_ids.die_id;
506         }
507         ms->possible_cpus->cpus[i].props.has_core_id = true;
508         ms->possible_cpus->cpus[i].props.core_id = topo_ids.core_id;
509         ms->possible_cpus->cpus[i].props.has_thread_id = true;
510         ms->possible_cpus->cpus[i].props.thread_id = topo_ids.smt_id;
511     }
512     return ms->possible_cpus;
513 }
514 
515 static void x86_nmi(NMIState *n, int cpu_index, Error **errp)
516 {
517     /* cpu index isn't used */
518     CPUState *cs;
519 
520     CPU_FOREACH(cs) {
521         X86CPU *cpu = X86_CPU(cs);
522 
523         if (cpu_is_apic_enabled(cpu->apic_state)) {
524             apic_deliver_nmi(cpu->apic_state);
525         } else {
526             cpu_interrupt(cs, CPU_INTERRUPT_NMI);
527         }
528     }
529 }
530 
531 static long get_file_size(FILE *f)
532 {
533     long where, size;
534 
535     /* XXX: on Unix systems, using fstat() probably makes more sense */
536 
537     where = ftell(f);
538     fseek(f, 0, SEEK_END);
539     size = ftell(f);
540     fseek(f, where, SEEK_SET);
541 
542     return size;
543 }
544 
545 /* TSC handling */
546 uint64_t cpu_get_tsc(CPUX86State *env)
547 {
548     return cpus_get_elapsed_ticks();
549 }
550 
551 /* IRQ handling */
552 static void pic_irq_request(void *opaque, int irq, int level)
553 {
554     CPUState *cs = first_cpu;
555     X86CPU *cpu = X86_CPU(cs);
556 
557     trace_x86_pic_interrupt(irq, level);
558     if (cpu_is_apic_enabled(cpu->apic_state) && !kvm_irqchip_in_kernel() &&
559         !whpx_apic_in_platform()) {
560         CPU_FOREACH(cs) {
561             cpu = X86_CPU(cs);
562             if (apic_accept_pic_intr(cpu->apic_state)) {
563                 apic_deliver_pic_intr(cpu->apic_state, level);
564             }
565         }
566     } else {
567         if (level) {
568             cpu_interrupt(cs, CPU_INTERRUPT_HARD);
569         } else {
570             cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
571         }
572     }
573 }
574 
575 qemu_irq x86_allocate_cpu_irq(void)
576 {
577     return qemu_allocate_irq(pic_irq_request, NULL, 0);
578 }
579 
580 int cpu_get_pic_interrupt(CPUX86State *env)
581 {
582     X86CPU *cpu = env_archcpu(env);
583     int intno;
584 
585     if (!kvm_irqchip_in_kernel() && !whpx_apic_in_platform()) {
586         intno = apic_get_interrupt(cpu->apic_state);
587         if (intno >= 0) {
588             return intno;
589         }
590         /* read the irq from the PIC */
591         if (!apic_accept_pic_intr(cpu->apic_state)) {
592             return -1;
593         }
594     }
595 
596     intno = pic_read_irq(isa_pic);
597     return intno;
598 }
599 
600 DeviceState *cpu_get_current_apic(void)
601 {
602     if (current_cpu) {
603         X86CPU *cpu = X86_CPU(current_cpu);
604         return cpu->apic_state;
605     } else {
606         return NULL;
607     }
608 }
609 
610 void gsi_handler(void *opaque, int n, int level)
611 {
612     GSIState *s = opaque;
613 
614     trace_x86_gsi_interrupt(n, level);
615     switch (n) {
616     case 0 ... ISA_NUM_IRQS - 1:
617         if (s->i8259_irq[n]) {
618             /* Under KVM, Kernel will forward to both PIC and IOAPIC */
619             qemu_set_irq(s->i8259_irq[n], level);
620         }
621         /* fall through */
622     case ISA_NUM_IRQS ... IOAPIC_NUM_PINS - 1:
623 #ifdef CONFIG_XEN_EMU
624         /*
625          * Xen delivers the GSI to the Legacy PIC (not that Legacy PIC
626          * routing actually works properly under Xen). And then to
627          * *either* the PIRQ handling or the I/OAPIC depending on
628          * whether the former wants it.
629          */
630         if (xen_mode == XEN_EMULATE && xen_evtchn_set_gsi(n, level)) {
631             break;
632         }
633 #endif
634         qemu_set_irq(s->ioapic_irq[n], level);
635         break;
636     case IO_APIC_SECONDARY_IRQBASE
637         ... IO_APIC_SECONDARY_IRQBASE + IOAPIC_NUM_PINS - 1:
638         qemu_set_irq(s->ioapic2_irq[n - IO_APIC_SECONDARY_IRQBASE], level);
639         break;
640     }
641 }
642 
643 void ioapic_init_gsi(GSIState *gsi_state, Object *parent)
644 {
645     DeviceState *dev;
646     SysBusDevice *d;
647     unsigned int i;
648 
649     assert(parent);
650     if (kvm_ioapic_in_kernel()) {
651         dev = qdev_new(TYPE_KVM_IOAPIC);
652     } else {
653         dev = qdev_new(TYPE_IOAPIC);
654     }
655     object_property_add_child(parent, "ioapic", OBJECT(dev));
656     d = SYS_BUS_DEVICE(dev);
657     sysbus_realize_and_unref(d, &error_fatal);
658     sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
659 
660     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
661         gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
662     }
663 }
664 
665 DeviceState *ioapic_init_secondary(GSIState *gsi_state)
666 {
667     DeviceState *dev;
668     SysBusDevice *d;
669     unsigned int i;
670 
671     dev = qdev_new(TYPE_IOAPIC);
672     d = SYS_BUS_DEVICE(dev);
673     sysbus_realize_and_unref(d, &error_fatal);
674     sysbus_mmio_map(d, 0, IO_APIC_SECONDARY_ADDRESS);
675 
676     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
677         gsi_state->ioapic2_irq[i] = qdev_get_gpio_in(dev, i);
678     }
679     return dev;
680 }
681 
682 /*
683  * The entry point into the kernel for PVH boot is different from
684  * the native entry point.  The PVH entry is defined by the x86/HVM
685  * direct boot ABI and is available in an ELFNOTE in the kernel binary.
686  *
687  * This function is passed to load_elf() when it is called from
688  * load_elfboot() which then additionally checks for an ELF Note of
689  * type XEN_ELFNOTE_PHYS32_ENTRY and passes it to this function to
690  * parse the PVH entry address from the ELF Note.
691  *
692  * Due to trickery in elf_opts.h, load_elf() is actually available as
693  * load_elf32() or load_elf64() and this routine needs to be able
694  * to deal with being called as 32 or 64 bit.
695  *
696  * The address of the PVH entry point is saved to the 'pvh_start_addr'
697  * global variable.  (although the entry point is 32-bit, the kernel
698  * binary can be either 32-bit or 64-bit).
699  */
700 static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64)
701 {
702     size_t *elf_note_data_addr;
703 
704     /* Check if ELF Note header passed in is valid */
705     if (arg1 == NULL) {
706         return 0;
707     }
708 
709     if (is64) {
710         struct elf64_note *nhdr64 = (struct elf64_note *)arg1;
711         uint64_t nhdr_size64 = sizeof(struct elf64_note);
712         uint64_t phdr_align = *(uint64_t *)arg2;
713         uint64_t nhdr_namesz = nhdr64->n_namesz;
714 
715         elf_note_data_addr =
716             ((void *)nhdr64) + nhdr_size64 +
717             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
718 
719         pvh_start_addr = *elf_note_data_addr;
720     } else {
721         struct elf32_note *nhdr32 = (struct elf32_note *)arg1;
722         uint32_t nhdr_size32 = sizeof(struct elf32_note);
723         uint32_t phdr_align = *(uint32_t *)arg2;
724         uint32_t nhdr_namesz = nhdr32->n_namesz;
725 
726         elf_note_data_addr =
727             ((void *)nhdr32) + nhdr_size32 +
728             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
729 
730         pvh_start_addr = *(uint32_t *)elf_note_data_addr;
731     }
732 
733     return pvh_start_addr;
734 }
735 
736 static bool load_elfboot(const char *kernel_filename,
737                          int kernel_file_size,
738                          uint8_t *header,
739                          size_t pvh_xen_start_addr,
740                          FWCfgState *fw_cfg)
741 {
742     uint32_t flags = 0;
743     uint32_t mh_load_addr = 0;
744     uint32_t elf_kernel_size = 0;
745     uint64_t elf_entry;
746     uint64_t elf_low, elf_high;
747     int kernel_size;
748 
749     if (ldl_p(header) != 0x464c457f) {
750         return false; /* no elfboot */
751     }
752 
753     bool elf_is64 = header[EI_CLASS] == ELFCLASS64;
754     flags = elf_is64 ?
755         ((Elf64_Ehdr *)header)->e_flags : ((Elf32_Ehdr *)header)->e_flags;
756 
757     if (flags & 0x00010004) { /* LOAD_ELF_HEADER_HAS_ADDR */
758         error_report("elfboot unsupported flags = %x", flags);
759         exit(1);
760     }
761 
762     uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY;
763     kernel_size = load_elf(kernel_filename, read_pvh_start_addr,
764                            NULL, &elf_note_type, &elf_entry,
765                            &elf_low, &elf_high, NULL, 0, I386_ELF_MACHINE,
766                            0, 0);
767 
768     if (kernel_size < 0) {
769         error_report("Error while loading elf kernel");
770         exit(1);
771     }
772     mh_load_addr = elf_low;
773     elf_kernel_size = elf_high - elf_low;
774 
775     if (pvh_start_addr == 0) {
776         error_report("Error loading uncompressed kernel without PVH ELF Note");
777         exit(1);
778     }
779     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr);
780     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
781     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size);
782 
783     return true;
784 }
785 
786 void x86_load_linux(X86MachineState *x86ms,
787                     FWCfgState *fw_cfg,
788                     int acpi_data_size,
789                     bool pvh_enabled)
790 {
791     bool linuxboot_dma_enabled = X86_MACHINE_GET_CLASS(x86ms)->fwcfg_dma_enabled;
792     uint16_t protocol;
793     int setup_size, kernel_size, cmdline_size;
794     int dtb_size, setup_data_offset;
795     uint32_t initrd_max;
796     uint8_t header[8192], *setup, *kernel;
797     hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
798     FILE *f;
799     char *vmode;
800     MachineState *machine = MACHINE(x86ms);
801     struct setup_data *setup_data;
802     const char *kernel_filename = machine->kernel_filename;
803     const char *initrd_filename = machine->initrd_filename;
804     const char *dtb_filename = machine->dtb;
805     const char *kernel_cmdline = machine->kernel_cmdline;
806     SevKernelLoaderContext sev_load_ctx = {};
807 
808     /* Align to 16 bytes as a paranoia measure */
809     cmdline_size = (strlen(kernel_cmdline) + 16) & ~15;
810 
811     /* load the kernel header */
812     f = fopen(kernel_filename, "rb");
813     if (!f) {
814         fprintf(stderr, "qemu: could not open kernel file '%s': %s\n",
815                 kernel_filename, strerror(errno));
816         exit(1);
817     }
818 
819     kernel_size = get_file_size(f);
820     if (!kernel_size ||
821         fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
822         MIN(ARRAY_SIZE(header), kernel_size)) {
823         fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
824                 kernel_filename, strerror(errno));
825         exit(1);
826     }
827 
828     /* kernel protocol version */
829     if (ldl_p(header + 0x202) == 0x53726448) {
830         protocol = lduw_p(header + 0x206);
831     } else {
832         /*
833          * This could be a multiboot kernel. If it is, let's stop treating it
834          * like a Linux kernel.
835          * Note: some multiboot images could be in the ELF format (the same of
836          * PVH), so we try multiboot first since we check the multiboot magic
837          * header before to load it.
838          */
839         if (load_multiboot(x86ms, fw_cfg, f, kernel_filename, initrd_filename,
840                            kernel_cmdline, kernel_size, header)) {
841             return;
842         }
843         /*
844          * Check if the file is an uncompressed kernel file (ELF) and load it,
845          * saving the PVH entry point used by the x86/HVM direct boot ABI.
846          * If load_elfboot() is successful, populate the fw_cfg info.
847          */
848         if (pvh_enabled &&
849             load_elfboot(kernel_filename, kernel_size,
850                          header, pvh_start_addr, fw_cfg)) {
851             fclose(f);
852 
853             fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
854                 strlen(kernel_cmdline) + 1);
855             fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
856 
857             fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, sizeof(header));
858             fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA,
859                              header, sizeof(header));
860 
861             /* load initrd */
862             if (initrd_filename) {
863                 GMappedFile *mapped_file;
864                 gsize initrd_size;
865                 gchar *initrd_data;
866                 GError *gerr = NULL;
867 
868                 mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
869                 if (!mapped_file) {
870                     fprintf(stderr, "qemu: error reading initrd %s: %s\n",
871                             initrd_filename, gerr->message);
872                     exit(1);
873                 }
874                 x86ms->initrd_mapped_file = mapped_file;
875 
876                 initrd_data = g_mapped_file_get_contents(mapped_file);
877                 initrd_size = g_mapped_file_get_length(mapped_file);
878                 initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
879                 if (initrd_size >= initrd_max) {
880                     fprintf(stderr, "qemu: initrd is too large, cannot support."
881                             "(max: %"PRIu32", need %"PRId64")\n",
882                             initrd_max, (uint64_t)initrd_size);
883                     exit(1);
884                 }
885 
886                 initrd_addr = (initrd_max - initrd_size) & ~4095;
887 
888                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
889                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
890                 fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data,
891                                  initrd_size);
892             }
893 
894             option_rom[nb_option_roms].bootindex = 0;
895             option_rom[nb_option_roms].name = "pvh.bin";
896             nb_option_roms++;
897 
898             return;
899         }
900         protocol = 0;
901     }
902 
903     if (protocol < 0x200 || !(header[0x211] & 0x01)) {
904         /* Low kernel */
905         real_addr    = 0x90000;
906         cmdline_addr = 0x9a000 - cmdline_size;
907         prot_addr    = 0x10000;
908     } else if (protocol < 0x202) {
909         /* High but ancient kernel */
910         real_addr    = 0x90000;
911         cmdline_addr = 0x9a000 - cmdline_size;
912         prot_addr    = 0x100000;
913     } else {
914         /* High and recent kernel */
915         real_addr    = 0x10000;
916         cmdline_addr = 0x20000;
917         prot_addr    = 0x100000;
918     }
919 
920     /* highest address for loading the initrd */
921     if (protocol >= 0x20c &&
922         lduw_p(header + 0x236) & XLF_CAN_BE_LOADED_ABOVE_4G) {
923         /*
924          * Linux has supported initrd up to 4 GB for a very long time (2007,
925          * long before XLF_CAN_BE_LOADED_ABOVE_4G which was added in 2013),
926          * though it only sets initrd_max to 2 GB to "work around bootloader
927          * bugs". Luckily, QEMU firmware(which does something like bootloader)
928          * has supported this.
929          *
930          * It's believed that if XLF_CAN_BE_LOADED_ABOVE_4G is set, initrd can
931          * be loaded into any address.
932          *
933          * In addition, initrd_max is uint32_t simply because QEMU doesn't
934          * support the 64-bit boot protocol (specifically the ext_ramdisk_image
935          * field).
936          *
937          * Therefore here just limit initrd_max to UINT32_MAX simply as well.
938          */
939         initrd_max = UINT32_MAX;
940     } else if (protocol >= 0x203) {
941         initrd_max = ldl_p(header + 0x22c);
942     } else {
943         initrd_max = 0x37ffffff;
944     }
945 
946     if (initrd_max >= x86ms->below_4g_mem_size - acpi_data_size) {
947         initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
948     }
949 
950     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
951     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline) + 1);
952     fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
953     sev_load_ctx.cmdline_data = (char *)kernel_cmdline;
954     sev_load_ctx.cmdline_size = strlen(kernel_cmdline) + 1;
955 
956     if (protocol >= 0x202) {
957         stl_p(header + 0x228, cmdline_addr);
958     } else {
959         stw_p(header + 0x20, 0xA33F);
960         stw_p(header + 0x22, cmdline_addr - real_addr);
961     }
962 
963     /* handle vga= parameter */
964     vmode = strstr(kernel_cmdline, "vga=");
965     if (vmode) {
966         unsigned int video_mode;
967         const char *end;
968         int ret;
969         /* skip "vga=" */
970         vmode += 4;
971         if (!strncmp(vmode, "normal", 6)) {
972             video_mode = 0xffff;
973         } else if (!strncmp(vmode, "ext", 3)) {
974             video_mode = 0xfffe;
975         } else if (!strncmp(vmode, "ask", 3)) {
976             video_mode = 0xfffd;
977         } else {
978             ret = qemu_strtoui(vmode, &end, 0, &video_mode);
979             if (ret != 0 || (*end && *end != ' ')) {
980                 fprintf(stderr, "qemu: invalid 'vga=' kernel parameter.\n");
981                 exit(1);
982             }
983         }
984         stw_p(header + 0x1fa, video_mode);
985     }
986 
987     /* loader type */
988     /*
989      * High nybble = B reserved for QEMU; low nybble is revision number.
990      * If this code is substantially changed, you may want to consider
991      * incrementing the revision.
992      */
993     if (protocol >= 0x200) {
994         header[0x210] = 0xB0;
995     }
996     /* heap */
997     if (protocol >= 0x201) {
998         header[0x211] |= 0x80; /* CAN_USE_HEAP */
999         stw_p(header + 0x224, cmdline_addr - real_addr - 0x200);
1000     }
1001 
1002     /* load initrd */
1003     if (initrd_filename) {
1004         GMappedFile *mapped_file;
1005         gsize initrd_size;
1006         gchar *initrd_data;
1007         GError *gerr = NULL;
1008 
1009         if (protocol < 0x200) {
1010             fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
1011             exit(1);
1012         }
1013 
1014         mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
1015         if (!mapped_file) {
1016             fprintf(stderr, "qemu: error reading initrd %s: %s\n",
1017                     initrd_filename, gerr->message);
1018             exit(1);
1019         }
1020         x86ms->initrd_mapped_file = mapped_file;
1021 
1022         initrd_data = g_mapped_file_get_contents(mapped_file);
1023         initrd_size = g_mapped_file_get_length(mapped_file);
1024         if (initrd_size >= initrd_max) {
1025             fprintf(stderr, "qemu: initrd is too large, cannot support."
1026                     "(max: %"PRIu32", need %"PRId64")\n",
1027                     initrd_max, (uint64_t)initrd_size);
1028             exit(1);
1029         }
1030 
1031         initrd_addr = (initrd_max - initrd_size) & ~4095;
1032 
1033         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
1034         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
1035         fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
1036         sev_load_ctx.initrd_data = initrd_data;
1037         sev_load_ctx.initrd_size = initrd_size;
1038 
1039         stl_p(header + 0x218, initrd_addr);
1040         stl_p(header + 0x21c, initrd_size);
1041     }
1042 
1043     /* load kernel and setup */
1044     setup_size = header[0x1f1];
1045     if (setup_size == 0) {
1046         setup_size = 4;
1047     }
1048     setup_size = (setup_size + 1) * 512;
1049     if (setup_size > kernel_size) {
1050         fprintf(stderr, "qemu: invalid kernel header\n");
1051         exit(1);
1052     }
1053     kernel_size -= setup_size;
1054 
1055     setup  = g_malloc(setup_size);
1056     kernel = g_malloc(kernel_size);
1057     fseek(f, 0, SEEK_SET);
1058     if (fread(setup, 1, setup_size, f) != setup_size) {
1059         fprintf(stderr, "fread() failed\n");
1060         exit(1);
1061     }
1062     if (fread(kernel, 1, kernel_size, f) != kernel_size) {
1063         fprintf(stderr, "fread() failed\n");
1064         exit(1);
1065     }
1066     fclose(f);
1067 
1068     /* append dtb to kernel */
1069     if (dtb_filename) {
1070         if (protocol < 0x209) {
1071             fprintf(stderr, "qemu: Linux kernel too old to load a dtb\n");
1072             exit(1);
1073         }
1074 
1075         dtb_size = get_image_size(dtb_filename);
1076         if (dtb_size <= 0) {
1077             fprintf(stderr, "qemu: error reading dtb %s: %s\n",
1078                     dtb_filename, strerror(errno));
1079             exit(1);
1080         }
1081 
1082         setup_data_offset = QEMU_ALIGN_UP(kernel_size, 16);
1083         kernel_size = setup_data_offset + sizeof(struct setup_data) + dtb_size;
1084         kernel = g_realloc(kernel, kernel_size);
1085 
1086         stq_p(header + 0x250, prot_addr + setup_data_offset);
1087 
1088         setup_data = (struct setup_data *)(kernel + setup_data_offset);
1089         setup_data->next = 0;
1090         setup_data->type = cpu_to_le32(SETUP_DTB);
1091         setup_data->len = cpu_to_le32(dtb_size);
1092 
1093         load_image_size(dtb_filename, setup_data->data, dtb_size);
1094     }
1095 
1096     /*
1097      * If we're starting an encrypted VM, it will be OVMF based, which uses the
1098      * efi stub for booting and doesn't require any values to be placed in the
1099      * kernel header.  We therefore don't update the header so the hash of the
1100      * kernel on the other side of the fw_cfg interface matches the hash of the
1101      * file the user passed in.
1102      */
1103     if (!sev_enabled()) {
1104         memcpy(setup, header, MIN(sizeof(header), setup_size));
1105     }
1106 
1107     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
1108     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
1109     fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);
1110     sev_load_ctx.kernel_data = (char *)kernel;
1111     sev_load_ctx.kernel_size = kernel_size;
1112 
1113     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
1114     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
1115     fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
1116     sev_load_ctx.setup_data = (char *)setup;
1117     sev_load_ctx.setup_size = setup_size;
1118 
1119     if (sev_enabled()) {
1120         sev_add_kernel_loader_hashes(&sev_load_ctx, &error_fatal);
1121     }
1122 
1123     option_rom[nb_option_roms].bootindex = 0;
1124     option_rom[nb_option_roms].name = "linuxboot.bin";
1125     if (linuxboot_dma_enabled && fw_cfg_dma_enabled(fw_cfg)) {
1126         option_rom[nb_option_roms].name = "linuxboot_dma.bin";
1127     }
1128     nb_option_roms++;
1129 }
1130 
1131 void x86_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *isa_memory,
1132                        MemoryRegion *bios, bool read_only)
1133 {
1134     uint64_t bios_size = memory_region_size(bios);
1135     uint64_t isa_bios_size = MIN(bios_size, 128 * KiB);
1136 
1137     memory_region_init_alias(isa_bios, NULL, "isa-bios", bios,
1138                              bios_size - isa_bios_size, isa_bios_size);
1139     memory_region_add_subregion_overlap(isa_memory, 1 * MiB - isa_bios_size,
1140                                         isa_bios, 1);
1141     memory_region_set_readonly(isa_bios, read_only);
1142 }
1143 
1144 void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
1145                        MemoryRegion *rom_memory, bool isapc_ram_fw)
1146 {
1147     const char *bios_name;
1148     char *filename;
1149     int bios_size;
1150     ssize_t ret;
1151 
1152     /* BIOS load */
1153     bios_name = MACHINE(x86ms)->firmware ?: default_firmware;
1154     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1155     if (filename) {
1156         bios_size = get_image_size(filename);
1157     } else {
1158         bios_size = -1;
1159     }
1160     if (bios_size <= 0 ||
1161         (bios_size % 65536) != 0) {
1162         goto bios_error;
1163     }
1164     memory_region_init_ram(&x86ms->bios, NULL, "pc.bios", bios_size,
1165                            &error_fatal);
1166     if (sev_enabled()) {
1167         /*
1168          * The concept of a "reset" simply doesn't exist for
1169          * confidential computing guests, we have to destroy and
1170          * re-launch them instead.  So there is no need to register
1171          * the firmware as rom to properly re-initialize on reset.
1172          * Just go for a straight file load instead.
1173          */
1174         void *ptr = memory_region_get_ram_ptr(&x86ms->bios);
1175         load_image_size(filename, ptr, bios_size);
1176         x86_firmware_configure(ptr, bios_size);
1177     } else {
1178         memory_region_set_readonly(&x86ms->bios, !isapc_ram_fw);
1179         ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);
1180         if (ret != 0) {
1181             goto bios_error;
1182         }
1183     }
1184     g_free(filename);
1185 
1186     /* map the last 128KB of the BIOS in ISA space */
1187     x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
1188                       !isapc_ram_fw);
1189 
1190     /* map all the bios at the top of memory */
1191     memory_region_add_subregion(rom_memory,
1192                                 (uint32_t)(-bios_size),
1193                                 &x86ms->bios);
1194     return;
1195 
1196 bios_error:
1197     fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);
1198     exit(1);
1199 }
1200 
1201 bool x86_machine_is_smm_enabled(const X86MachineState *x86ms)
1202 {
1203     bool smm_available = false;
1204 
1205     if (x86ms->smm == ON_OFF_AUTO_OFF) {
1206         return false;
1207     }
1208 
1209     if (tcg_enabled() || qtest_enabled()) {
1210         smm_available = true;
1211     } else if (kvm_enabled()) {
1212         smm_available = kvm_has_smm();
1213     }
1214 
1215     if (smm_available) {
1216         return true;
1217     }
1218 
1219     if (x86ms->smm == ON_OFF_AUTO_ON) {
1220         error_report("System Management Mode not supported by this hypervisor.");
1221         exit(1);
1222     }
1223     return false;
1224 }
1225 
1226 static void x86_machine_get_smm(Object *obj, Visitor *v, const char *name,
1227                                void *opaque, Error **errp)
1228 {
1229     X86MachineState *x86ms = X86_MACHINE(obj);
1230     OnOffAuto smm = x86ms->smm;
1231 
1232     visit_type_OnOffAuto(v, name, &smm, errp);
1233 }
1234 
1235 static void x86_machine_set_smm(Object *obj, Visitor *v, const char *name,
1236                                void *opaque, Error **errp)
1237 {
1238     X86MachineState *x86ms = X86_MACHINE(obj);
1239 
1240     visit_type_OnOffAuto(v, name, &x86ms->smm, errp);
1241 }
1242 
1243 bool x86_machine_is_acpi_enabled(const X86MachineState *x86ms)
1244 {
1245     if (x86ms->acpi == ON_OFF_AUTO_OFF) {
1246         return false;
1247     }
1248     return true;
1249 }
1250 
1251 static void x86_machine_get_acpi(Object *obj, Visitor *v, const char *name,
1252                                  void *opaque, Error **errp)
1253 {
1254     X86MachineState *x86ms = X86_MACHINE(obj);
1255     OnOffAuto acpi = x86ms->acpi;
1256 
1257     visit_type_OnOffAuto(v, name, &acpi, errp);
1258 }
1259 
1260 static void x86_machine_set_acpi(Object *obj, Visitor *v, const char *name,
1261                                  void *opaque, Error **errp)
1262 {
1263     X86MachineState *x86ms = X86_MACHINE(obj);
1264 
1265     visit_type_OnOffAuto(v, name, &x86ms->acpi, errp);
1266 }
1267 
1268 static void x86_machine_get_pit(Object *obj, Visitor *v, const char *name,
1269                                     void *opaque, Error **errp)
1270 {
1271     X86MachineState *x86ms = X86_MACHINE(obj);
1272     OnOffAuto pit = x86ms->pit;
1273 
1274     visit_type_OnOffAuto(v, name, &pit, errp);
1275 }
1276 
1277 static void x86_machine_set_pit(Object *obj, Visitor *v, const char *name,
1278                                     void *opaque, Error **errp)
1279 {
1280     X86MachineState *x86ms = X86_MACHINE(obj);;
1281 
1282     visit_type_OnOffAuto(v, name, &x86ms->pit, errp);
1283 }
1284 
1285 static void x86_machine_get_pic(Object *obj, Visitor *v, const char *name,
1286                                 void *opaque, Error **errp)
1287 {
1288     X86MachineState *x86ms = X86_MACHINE(obj);
1289     OnOffAuto pic = x86ms->pic;
1290 
1291     visit_type_OnOffAuto(v, name, &pic, errp);
1292 }
1293 
1294 static void x86_machine_set_pic(Object *obj, Visitor *v, const char *name,
1295                                 void *opaque, Error **errp)
1296 {
1297     X86MachineState *x86ms = X86_MACHINE(obj);
1298 
1299     visit_type_OnOffAuto(v, name, &x86ms->pic, errp);
1300 }
1301 
1302 static char *x86_machine_get_oem_id(Object *obj, Error **errp)
1303 {
1304     X86MachineState *x86ms = X86_MACHINE(obj);
1305 
1306     return g_strdup(x86ms->oem_id);
1307 }
1308 
1309 static void x86_machine_set_oem_id(Object *obj, const char *value, Error **errp)
1310 {
1311     X86MachineState *x86ms = X86_MACHINE(obj);
1312     size_t len = strlen(value);
1313 
1314     if (len > 6) {
1315         error_setg(errp,
1316                    "User specified "X86_MACHINE_OEM_ID" value is bigger than "
1317                    "6 bytes in size");
1318         return;
1319     }
1320 
1321     strncpy(x86ms->oem_id, value, 6);
1322 }
1323 
1324 static char *x86_machine_get_oem_table_id(Object *obj, Error **errp)
1325 {
1326     X86MachineState *x86ms = X86_MACHINE(obj);
1327 
1328     return g_strdup(x86ms->oem_table_id);
1329 }
1330 
1331 static void x86_machine_set_oem_table_id(Object *obj, const char *value,
1332                                          Error **errp)
1333 {
1334     X86MachineState *x86ms = X86_MACHINE(obj);
1335     size_t len = strlen(value);
1336 
1337     if (len > 8) {
1338         error_setg(errp,
1339                    "User specified "X86_MACHINE_OEM_TABLE_ID
1340                    " value is bigger than "
1341                    "8 bytes in size");
1342         return;
1343     }
1344     strncpy(x86ms->oem_table_id, value, 8);
1345 }
1346 
1347 static void x86_machine_get_bus_lock_ratelimit(Object *obj, Visitor *v,
1348                                 const char *name, void *opaque, Error **errp)
1349 {
1350     X86MachineState *x86ms = X86_MACHINE(obj);
1351     uint64_t bus_lock_ratelimit = x86ms->bus_lock_ratelimit;
1352 
1353     visit_type_uint64(v, name, &bus_lock_ratelimit, errp);
1354 }
1355 
1356 static void x86_machine_set_bus_lock_ratelimit(Object *obj, Visitor *v,
1357                                const char *name, void *opaque, Error **errp)
1358 {
1359     X86MachineState *x86ms = X86_MACHINE(obj);
1360 
1361     visit_type_uint64(v, name, &x86ms->bus_lock_ratelimit, errp);
1362 }
1363 
1364 static void machine_get_sgx_epc(Object *obj, Visitor *v, const char *name,
1365                                 void *opaque, Error **errp)
1366 {
1367     X86MachineState *x86ms = X86_MACHINE(obj);
1368     SgxEPCList *list = x86ms->sgx_epc_list;
1369 
1370     visit_type_SgxEPCList(v, name, &list, errp);
1371 }
1372 
1373 static void machine_set_sgx_epc(Object *obj, Visitor *v, const char *name,
1374                                 void *opaque, Error **errp)
1375 {
1376     X86MachineState *x86ms = X86_MACHINE(obj);
1377     SgxEPCList *list;
1378 
1379     list = x86ms->sgx_epc_list;
1380     visit_type_SgxEPCList(v, name, &x86ms->sgx_epc_list, errp);
1381 
1382     qapi_free_SgxEPCList(list);
1383 }
1384 
1385 static int x86_kvm_type(MachineState *ms, const char *vm_type)
1386 {
1387     /*
1388      * No x86 machine has a kvm-type property.  If one is added that has
1389      * it, it should call kvm_get_vm_type() directly or not use it at all.
1390      */
1391     assert(vm_type == NULL);
1392     return kvm_enabled() ? kvm_get_vm_type(ms) : 0;
1393 }
1394 
1395 static void x86_machine_initfn(Object *obj)
1396 {
1397     X86MachineState *x86ms = X86_MACHINE(obj);
1398 
1399     x86ms->smm = ON_OFF_AUTO_AUTO;
1400     x86ms->acpi = ON_OFF_AUTO_AUTO;
1401     x86ms->pit = ON_OFF_AUTO_AUTO;
1402     x86ms->pic = ON_OFF_AUTO_AUTO;
1403     x86ms->pci_irq_mask = ACPI_BUILD_PCI_IRQS;
1404     x86ms->oem_id = g_strndup(ACPI_BUILD_APPNAME6, 6);
1405     x86ms->oem_table_id = g_strndup(ACPI_BUILD_APPNAME8, 8);
1406     x86ms->bus_lock_ratelimit = 0;
1407     x86ms->above_4g_mem_start = 4 * GiB;
1408 }
1409 
1410 static void x86_machine_class_init(ObjectClass *oc, void *data)
1411 {
1412     MachineClass *mc = MACHINE_CLASS(oc);
1413     X86MachineClass *x86mc = X86_MACHINE_CLASS(oc);
1414     NMIClass *nc = NMI_CLASS(oc);
1415 
1416     mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
1417     mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
1418     mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
1419     mc->kvm_type = x86_kvm_type;
1420     x86mc->save_tsc_khz = true;
1421     x86mc->fwcfg_dma_enabled = true;
1422     nc->nmi_monitor_handler = x86_nmi;
1423 
1424     object_class_property_add(oc, X86_MACHINE_SMM, "OnOffAuto",
1425         x86_machine_get_smm, x86_machine_set_smm,
1426         NULL, NULL);
1427     object_class_property_set_description(oc, X86_MACHINE_SMM,
1428         "Enable SMM");
1429 
1430     object_class_property_add(oc, X86_MACHINE_ACPI, "OnOffAuto",
1431         x86_machine_get_acpi, x86_machine_set_acpi,
1432         NULL, NULL);
1433     object_class_property_set_description(oc, X86_MACHINE_ACPI,
1434         "Enable ACPI");
1435 
1436     object_class_property_add(oc, X86_MACHINE_PIT, "OnOffAuto",
1437                               x86_machine_get_pit,
1438                               x86_machine_set_pit,
1439                               NULL, NULL);
1440     object_class_property_set_description(oc, X86_MACHINE_PIT,
1441         "Enable i8254 PIT");
1442 
1443     object_class_property_add(oc, X86_MACHINE_PIC, "OnOffAuto",
1444                               x86_machine_get_pic,
1445                               x86_machine_set_pic,
1446                               NULL, NULL);
1447     object_class_property_set_description(oc, X86_MACHINE_PIC,
1448         "Enable i8259 PIC");
1449 
1450     object_class_property_add_str(oc, X86_MACHINE_OEM_ID,
1451                                   x86_machine_get_oem_id,
1452                                   x86_machine_set_oem_id);
1453     object_class_property_set_description(oc, X86_MACHINE_OEM_ID,
1454                                           "Override the default value of field OEMID "
1455                                           "in ACPI table header."
1456                                           "The string may be up to 6 bytes in size");
1457 
1458 
1459     object_class_property_add_str(oc, X86_MACHINE_OEM_TABLE_ID,
1460                                   x86_machine_get_oem_table_id,
1461                                   x86_machine_set_oem_table_id);
1462     object_class_property_set_description(oc, X86_MACHINE_OEM_TABLE_ID,
1463                                           "Override the default value of field OEM Table ID "
1464                                           "in ACPI table header."
1465                                           "The string may be up to 8 bytes in size");
1466 
1467     object_class_property_add(oc, X86_MACHINE_BUS_LOCK_RATELIMIT, "uint64_t",
1468                                 x86_machine_get_bus_lock_ratelimit,
1469                                 x86_machine_set_bus_lock_ratelimit, NULL, NULL);
1470     object_class_property_set_description(oc, X86_MACHINE_BUS_LOCK_RATELIMIT,
1471             "Set the ratelimit for the bus locks acquired in VMs");
1472 
1473     object_class_property_add(oc, "sgx-epc", "SgxEPC",
1474         machine_get_sgx_epc, machine_set_sgx_epc,
1475         NULL, NULL);
1476     object_class_property_set_description(oc, "sgx-epc",
1477         "SGX EPC device");
1478 }
1479 
1480 static const TypeInfo x86_machine_info = {
1481     .name = TYPE_X86_MACHINE,
1482     .parent = TYPE_MACHINE,
1483     .abstract = true,
1484     .instance_size = sizeof(X86MachineState),
1485     .instance_init = x86_machine_initfn,
1486     .class_size = sizeof(X86MachineClass),
1487     .class_init = x86_machine_class_init,
1488     .interfaces = (InterfaceInfo[]) {
1489          { TYPE_NMI },
1490          { }
1491     },
1492 };
1493 
1494 static void x86_machine_register_types(void)
1495 {
1496     type_register_static(&x86_machine_info);
1497 }
1498 
1499 type_init(x86_machine_register_types)
1500