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