xref: /qemu/hw/i386/x86-common.c (revision 09360a048bd7a133e47cb8dea617d44540bdebbd)
1 /*
2  * Copyright (c) 2003-2004 Fabrice Bellard
3  * Copyright (c) 2019, 2024 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/cutils.h"
26 #include "qemu/units.h"
27 #include "qemu/datadir.h"
28 #include "qapi/error.h"
29 #include "system/numa.h"
30 #include "system/system.h"
31 #include "system/xen.h"
32 #include "trace.h"
33 
34 #include "hw/i386/x86.h"
35 #include "target/i386/cpu.h"
36 #include "hw/rtc/mc146818rtc.h"
37 #include "target/i386/sev.h"
38 
39 #include "hw/acpi/cpu_hotplug.h"
40 #include "hw/irq.h"
41 #include "hw/loader.h"
42 #include "multiboot.h"
43 #include "elf.h"
44 #include "standard-headers/asm-x86/bootparam.h"
45 #include CONFIG_DEVICES
46 #include "kvm/kvm_i386.h"
47 
48 #ifdef CONFIG_XEN_EMU
49 #include "hw/xen/xen.h"
50 #include "hw/i386/kvm/xen_evtchn.h"
51 #endif
52 
53 /* Physical Address of PVH entry point read from kernel ELF NOTE */
54 static size_t pvh_start_addr;
55 
56 static void x86_cpu_new(X86MachineState *x86ms, int64_t apic_id, Error **errp)
57 {
58     Object *cpu = object_new(MACHINE(x86ms)->cpu_type);
59 
60     if (!object_property_set_uint(cpu, "apic-id", apic_id, errp)) {
61         goto out;
62     }
63     qdev_realize(DEVICE(cpu), NULL, errp);
64 
65 out:
66     object_unref(cpu);
67 }
68 
69 void x86_cpus_init(X86MachineState *x86ms, int default_cpu_version)
70 {
71     int i;
72     const CPUArchIdList *possible_cpus;
73     MachineState *ms = MACHINE(x86ms);
74     MachineClass *mc = MACHINE_GET_CLASS(x86ms);
75 
76     x86_cpu_set_default_version(default_cpu_version);
77 
78     /*
79      * Calculates the limit to CPU APIC ID values
80      *
81      * Limit for the APIC ID value, so that all
82      * CPU APIC IDs are < x86ms->apic_id_limit.
83      *
84      * This is used for FW_CFG_MAX_CPUS. See comments on fw_cfg_arch_create().
85      */
86     x86ms->apic_id_limit = x86_cpu_apic_id_from_index(x86ms,
87                                                       ms->smp.max_cpus - 1) + 1;
88 
89     /*
90      * Can we support APIC ID 255 or higher?  With KVM, that requires
91      * both in-kernel lapic and X2APIC userspace API.
92      *
93      * kvm_enabled() must go first to ensure that kvm_* references are
94      * not emitted for the linker to consume (kvm_enabled() is
95      * a literal `0` in configurations where kvm_* aren't defined)
96      */
97     if (kvm_enabled() && x86ms->apic_id_limit > 255 &&
98         kvm_irqchip_in_kernel() && !kvm_enable_x2apic()) {
99         error_report("current -smp configuration requires kernel "
100                      "irqchip and X2APIC API support.");
101         exit(EXIT_FAILURE);
102     }
103 
104     if (kvm_enabled()) {
105         kvm_set_max_apic_id(x86ms->apic_id_limit);
106     }
107 
108     if (!kvm_irqchip_in_kernel()) {
109         apic_set_max_apic_id(x86ms->apic_id_limit);
110     }
111 
112     possible_cpus = mc->possible_cpu_arch_ids(ms);
113     for (i = 0; i < ms->smp.cpus; i++) {
114         x86_cpu_new(x86ms, possible_cpus->cpus[i].arch_id, &error_fatal);
115     }
116 }
117 
118 void x86_rtc_set_cpus_count(ISADevice *s, uint16_t cpus_count)
119 {
120     MC146818RtcState *rtc = MC146818_RTC(s);
121 
122     if (cpus_count > 0xff) {
123         /*
124          * If the number of CPUs can't be represented in 8 bits, the
125          * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
126          * to make old BIOSes fail more predictably.
127          */
128         mc146818rtc_set_cmos_data(rtc, 0x5f, 0);
129     } else {
130         mc146818rtc_set_cmos_data(rtc, 0x5f, cpus_count - 1);
131     }
132 }
133 
134 static int x86_apic_cmp(const void *a, const void *b)
135 {
136    CPUArchId *apic_a = (CPUArchId *)a;
137    CPUArchId *apic_b = (CPUArchId *)b;
138 
139    return apic_a->arch_id - apic_b->arch_id;
140 }
141 
142 /*
143  * returns pointer to CPUArchId descriptor that matches CPU's apic_id
144  * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
145  * entry corresponding to CPU's apic_id returns NULL.
146  */
147 static CPUArchId *x86_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
148 {
149     CPUArchId apic_id, *found_cpu;
150 
151     apic_id.arch_id = id;
152     found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
153         ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
154         x86_apic_cmp);
155     if (found_cpu && idx) {
156         *idx = found_cpu - ms->possible_cpus->cpus;
157     }
158     return found_cpu;
159 }
160 
161 void x86_cpu_plug(HotplugHandler *hotplug_dev,
162                   DeviceState *dev, Error **errp)
163 {
164     CPUArchId *found_cpu;
165     Error *local_err = NULL;
166     X86CPU *cpu = X86_CPU(dev);
167     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
168 
169     if (x86ms->acpi_dev) {
170         hotplug_handler_plug(x86ms->acpi_dev, dev, &local_err);
171         if (local_err) {
172             goto out;
173         }
174     }
175 
176     /* increment the number of CPUs */
177     x86ms->boot_cpus++;
178     if (x86ms->rtc) {
179         x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
180     }
181     if (x86ms->fw_cfg) {
182         fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
183     }
184 
185     found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
186     found_cpu->cpu = CPU(dev);
187 out:
188     error_propagate(errp, local_err);
189 }
190 
191 void x86_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
192                                DeviceState *dev, Error **errp)
193 {
194     int idx = -1;
195     X86CPU *cpu = X86_CPU(dev);
196     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
197 
198     if (!x86ms->acpi_dev) {
199         error_setg(errp, "CPU hot unplug not supported without ACPI");
200         return;
201     }
202 
203     x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
204     assert(idx != -1);
205     if (idx == 0) {
206         error_setg(errp, "Boot CPU is unpluggable");
207         return;
208     }
209 
210     hotplug_handler_unplug_request(x86ms->acpi_dev, dev,
211                                    errp);
212 }
213 
214 void x86_cpu_unplug_cb(HotplugHandler *hotplug_dev,
215                        DeviceState *dev, Error **errp)
216 {
217     CPUArchId *found_cpu;
218     Error *local_err = NULL;
219     X86CPU *cpu = X86_CPU(dev);
220     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
221 
222     hotplug_handler_unplug(x86ms->acpi_dev, dev, &local_err);
223     if (local_err) {
224         goto out;
225     }
226 
227     found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
228     found_cpu->cpu = NULL;
229     qdev_unrealize(dev);
230 
231     /* decrement the number of CPUs */
232     x86ms->boot_cpus--;
233     /* Update the number of CPUs in CMOS */
234     x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
235     fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
236  out:
237     error_propagate(errp, local_err);
238 }
239 
240 void x86_cpu_pre_plug(HotplugHandler *hotplug_dev,
241                       DeviceState *dev, Error **errp)
242 {
243     int idx;
244     CPUState *cs;
245     CPUArchId *cpu_slot;
246     X86CPUTopoIDs topo_ids;
247     X86CPU *cpu = X86_CPU(dev);
248     CPUX86State *env = &cpu->env;
249     MachineState *ms = MACHINE(hotplug_dev);
250     X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
251     X86CPUTopoInfo *topo_info = &env->topo_info;
252 
253     if (!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
254         error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
255                    ms->cpu_type);
256         return;
257     }
258 
259     if (x86ms->acpi_dev) {
260         Error *local_err = NULL;
261 
262         hotplug_handler_pre_plug(HOTPLUG_HANDLER(x86ms->acpi_dev), dev,
263                                  &local_err);
264         if (local_err) {
265             error_propagate(errp, local_err);
266             return;
267         }
268     }
269 
270     init_topo_info(topo_info, x86ms);
271 
272     if (ms->smp.modules > 1) {
273         set_bit(CPU_TOPOLOGY_LEVEL_MODULE, env->avail_cpu_topo);
274     }
275 
276     if (ms->smp.dies > 1) {
277         set_bit(CPU_TOPOLOGY_LEVEL_DIE, env->avail_cpu_topo);
278     }
279 
280     /*
281      * If APIC ID is not set,
282      * set it based on socket/die/module/core/thread properties.
283      */
284     if (cpu->apic_id == UNASSIGNED_APIC_ID) {
285         /*
286          * die-id was optional in QEMU 4.0 and older, so keep it optional
287          * if there's only one die per socket.
288          */
289         if (cpu->die_id < 0 && ms->smp.dies == 1) {
290             cpu->die_id = 0;
291         }
292 
293         /*
294          * module-id was optional in QEMU 9.0 and older, so keep it optional
295          * if there's only one module per die.
296          */
297         if (cpu->module_id < 0 && ms->smp.modules == 1) {
298             cpu->module_id = 0;
299         }
300 
301         if (cpu->socket_id < 0) {
302             error_setg(errp, "CPU socket-id is not set");
303             return;
304         } else if (cpu->socket_id > ms->smp.sockets - 1) {
305             error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
306                        cpu->socket_id, ms->smp.sockets - 1);
307             return;
308         }
309         if (cpu->die_id < 0) {
310             error_setg(errp, "CPU die-id is not set");
311             return;
312         } else if (cpu->die_id > ms->smp.dies - 1) {
313             error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
314                        cpu->die_id, ms->smp.dies - 1);
315             return;
316         }
317         if (cpu->module_id < 0) {
318             error_setg(errp, "CPU module-id is not set");
319             return;
320         } else if (cpu->module_id > ms->smp.modules - 1) {
321             error_setg(errp, "Invalid CPU module-id: %u must be in range 0:%u",
322                        cpu->module_id, ms->smp.modules - 1);
323             return;
324         }
325         if (cpu->core_id < 0) {
326             error_setg(errp, "CPU core-id is not set");
327             return;
328         } else if (cpu->core_id > (ms->smp.cores - 1)) {
329             error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
330                        cpu->core_id, ms->smp.cores - 1);
331             return;
332         }
333         if (cpu->thread_id < 0) {
334             error_setg(errp, "CPU thread-id is not set");
335             return;
336         } else if (cpu->thread_id > (ms->smp.threads - 1)) {
337             error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
338                        cpu->thread_id, ms->smp.threads - 1);
339             return;
340         }
341 
342         topo_ids.pkg_id = cpu->socket_id;
343         topo_ids.die_id = cpu->die_id;
344         topo_ids.module_id = cpu->module_id;
345         topo_ids.core_id = cpu->core_id;
346         topo_ids.smt_id = cpu->thread_id;
347         cpu->apic_id = x86_apicid_from_topo_ids(topo_info, &topo_ids);
348     }
349 
350     cpu_slot = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
351     if (!cpu_slot) {
352         x86_topo_ids_from_apicid(cpu->apic_id, topo_info, &topo_ids);
353 
354         error_setg(errp,
355             "Invalid CPU [socket: %u, die: %u, module: %u, core: %u, thread: %u]"
356             " with APIC ID %" PRIu32 ", valid index range 0:%d",
357             topo_ids.pkg_id, topo_ids.die_id, topo_ids.module_id,
358             topo_ids.core_id, topo_ids.smt_id, cpu->apic_id,
359             ms->possible_cpus->len - 1);
360         return;
361     }
362 
363     if (cpu_slot->cpu) {
364         error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
365                    idx, cpu->apic_id);
366         return;
367     }
368 
369     /* if 'address' properties socket-id/core-id/thread-id are not set, set them
370      * so that machine_query_hotpluggable_cpus would show correct values
371      */
372     /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
373      * once -smp refactoring is complete and there will be CPU private
374      * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
375     x86_topo_ids_from_apicid(cpu->apic_id, topo_info, &topo_ids);
376     if (cpu->socket_id != -1 && cpu->socket_id != topo_ids.pkg_id) {
377         error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
378             " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id,
379             topo_ids.pkg_id);
380         return;
381     }
382     cpu->socket_id = topo_ids.pkg_id;
383 
384     if (cpu->die_id != -1 && cpu->die_id != topo_ids.die_id) {
385         error_setg(errp, "property die-id: %u doesn't match set apic-id:"
386             " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo_ids.die_id);
387         return;
388     }
389     cpu->die_id = topo_ids.die_id;
390 
391     if (cpu->module_id != -1 && cpu->module_id != topo_ids.module_id) {
392         error_setg(errp, "property module-id: %u doesn't match set apic-id:"
393             " 0x%x (module-id: %u)", cpu->module_id, cpu->apic_id,
394             topo_ids.module_id);
395         return;
396     }
397     cpu->module_id = topo_ids.module_id;
398 
399     if (cpu->core_id != -1 && cpu->core_id != topo_ids.core_id) {
400         error_setg(errp, "property core-id: %u doesn't match set apic-id:"
401             " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id,
402             topo_ids.core_id);
403         return;
404     }
405     cpu->core_id = topo_ids.core_id;
406 
407     if (cpu->thread_id != -1 && cpu->thread_id != topo_ids.smt_id) {
408         error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
409             " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id,
410             topo_ids.smt_id);
411         return;
412     }
413     cpu->thread_id = topo_ids.smt_id;
414 
415     /*
416     * kvm_enabled() must go first to ensure that kvm_* references are
417     * not emitted for the linker to consume (kvm_enabled() is
418     * a literal `0` in configurations where kvm_* aren't defined)
419     */
420     if (kvm_enabled() && hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
421         !kvm_hv_vpindex_settable()) {
422         error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
423         return;
424     }
425 
426     cs = CPU(cpu);
427     cs->cpu_index = idx;
428 
429     numa_cpu_pre_plug(cpu_slot, dev, errp);
430 }
431 
432 static long get_file_size(FILE *f)
433 {
434     long where, size;
435 
436     /* XXX: on Unix systems, using fstat() probably makes more sense */
437 
438     where = ftell(f);
439     fseek(f, 0, SEEK_END);
440     size = ftell(f);
441     fseek(f, where, SEEK_SET);
442 
443     return size;
444 }
445 
446 void gsi_handler(void *opaque, int n, int level)
447 {
448     GSIState *s = opaque;
449     bool bypass_ioapic = false;
450 
451     trace_x86_gsi_interrupt(n, level);
452 
453 #ifdef CONFIG_XEN_EMU
454     /*
455      * Xen delivers the GSI to the Legacy PIC (not that Legacy PIC
456      * routing actually works properly under Xen). And then to
457      * *either* the PIRQ handling or the I/OAPIC depending on whether
458      * the former wants it.
459      *
460      * Additionally, this hook allows the Xen event channel GSI to
461      * work around QEMU's lack of support for shared level interrupts,
462      * by keeping track of the externally driven state of the pin and
463      * implementing a logical OR with the state of the evtchn GSI.
464      */
465     if (xen_mode == XEN_EMULATE) {
466         bypass_ioapic = xen_evtchn_set_gsi(n, &level);
467     }
468 #endif
469 
470     switch (n) {
471     case 0 ... ISA_NUM_IRQS - 1:
472         if (s->i8259_irq[n]) {
473             /* Under KVM, Kernel will forward to both PIC and IOAPIC */
474             qemu_set_irq(s->i8259_irq[n], level);
475         }
476         /* fall through */
477     case ISA_NUM_IRQS ... IOAPIC_NUM_PINS - 1:
478         if (!bypass_ioapic) {
479             qemu_set_irq(s->ioapic_irq[n], level);
480         }
481         break;
482     case IO_APIC_SECONDARY_IRQBASE
483         ... IO_APIC_SECONDARY_IRQBASE + IOAPIC_NUM_PINS - 1:
484         qemu_set_irq(s->ioapic2_irq[n - IO_APIC_SECONDARY_IRQBASE], level);
485         break;
486     }
487 }
488 
489 void ioapic_init_gsi(GSIState *gsi_state, Object *parent)
490 {
491     DeviceState *dev;
492     SysBusDevice *d;
493     unsigned int i;
494 
495     assert(parent);
496     if (kvm_ioapic_in_kernel()) {
497         dev = qdev_new(TYPE_KVM_IOAPIC);
498     } else {
499         dev = qdev_new(TYPE_IOAPIC);
500     }
501     object_property_add_child(parent, "ioapic", OBJECT(dev));
502     d = SYS_BUS_DEVICE(dev);
503     sysbus_realize_and_unref(d, &error_fatal);
504     sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
505 
506     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
507         gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
508     }
509 }
510 
511 DeviceState *ioapic_init_secondary(GSIState *gsi_state)
512 {
513     DeviceState *dev;
514     SysBusDevice *d;
515     unsigned int i;
516 
517     dev = qdev_new(TYPE_IOAPIC);
518     d = SYS_BUS_DEVICE(dev);
519     sysbus_realize_and_unref(d, &error_fatal);
520     sysbus_mmio_map(d, 0, IO_APIC_SECONDARY_ADDRESS);
521 
522     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
523         gsi_state->ioapic2_irq[i] = qdev_get_gpio_in(dev, i);
524     }
525     return dev;
526 }
527 
528 /*
529  * The entry point into the kernel for PVH boot is different from
530  * the native entry point.  The PVH entry is defined by the x86/HVM
531  * direct boot ABI and is available in an ELFNOTE in the kernel binary.
532  *
533  * This function is passed to load_elf() when it is called from
534  * load_elfboot() which then additionally checks for an ELF Note of
535  * type XEN_ELFNOTE_PHYS32_ENTRY and passes it to this function to
536  * parse the PVH entry address from the ELF Note.
537  *
538  * Due to trickery in elf_opts.h, load_elf() is actually available as
539  * load_elf32() or load_elf64() and this routine needs to be able
540  * to deal with being called as 32 or 64 bit.
541  *
542  * The address of the PVH entry point is saved to the 'pvh_start_addr'
543  * global variable.  (although the entry point is 32-bit, the kernel
544  * binary can be either 32-bit or 64-bit).
545  */
546 static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64)
547 {
548     size_t *elf_note_data_addr;
549 
550     /* Check if ELF Note header passed in is valid */
551     if (arg1 == NULL) {
552         return 0;
553     }
554 
555     if (is64) {
556         struct elf64_note *nhdr64 = (struct elf64_note *)arg1;
557         uint64_t nhdr_size64 = sizeof(struct elf64_note);
558         uint64_t phdr_align = *(uint64_t *)arg2;
559         uint64_t nhdr_namesz = nhdr64->n_namesz;
560 
561         elf_note_data_addr =
562             ((void *)nhdr64) + nhdr_size64 +
563             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
564 
565         pvh_start_addr = *elf_note_data_addr;
566     } else {
567         struct elf32_note *nhdr32 = (struct elf32_note *)arg1;
568         uint32_t nhdr_size32 = sizeof(struct elf32_note);
569         uint32_t phdr_align = *(uint32_t *)arg2;
570         uint32_t nhdr_namesz = nhdr32->n_namesz;
571 
572         elf_note_data_addr =
573             ((void *)nhdr32) + nhdr_size32 +
574             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
575 
576         pvh_start_addr = *(uint32_t *)elf_note_data_addr;
577     }
578 
579     return pvh_start_addr;
580 }
581 
582 static bool load_elfboot(const char *kernel_filename,
583                          int kernel_file_size,
584                          uint8_t *header,
585                          size_t pvh_xen_start_addr,
586                          FWCfgState *fw_cfg)
587 {
588     uint32_t flags = 0;
589     uint32_t mh_load_addr = 0;
590     uint32_t elf_kernel_size = 0;
591     uint64_t elf_entry;
592     uint64_t elf_low, elf_high;
593     int kernel_size;
594 
595     if (ldl_le_p(header) != 0x464c457f) {
596         return false; /* no elfboot */
597     }
598 
599     bool elf_is64 = header[EI_CLASS] == ELFCLASS64;
600     flags = elf_is64 ?
601         ((Elf64_Ehdr *)header)->e_flags : ((Elf32_Ehdr *)header)->e_flags;
602 
603     if (flags & 0x00010004) { /* LOAD_ELF_HEADER_HAS_ADDR */
604         error_report("elfboot unsupported flags = %x", flags);
605         exit(1);
606     }
607 
608     uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY;
609     kernel_size = load_elf(kernel_filename, read_pvh_start_addr,
610                            NULL, &elf_note_type, &elf_entry,
611                            &elf_low, &elf_high, NULL, 0, I386_ELF_MACHINE,
612                            0, 0);
613 
614     if (kernel_size < 0) {
615         error_report("Error while loading elf kernel");
616         exit(1);
617     }
618     mh_load_addr = elf_low;
619     elf_kernel_size = elf_high - elf_low;
620 
621     if (pvh_start_addr == 0) {
622         error_report("Error loading uncompressed kernel without PVH ELF Note");
623         exit(1);
624     }
625     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr);
626     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
627     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size);
628 
629     return true;
630 }
631 
632 void x86_load_linux(X86MachineState *x86ms,
633                     FWCfgState *fw_cfg,
634                     int acpi_data_size,
635                     bool pvh_enabled)
636 {
637     bool linuxboot_dma_enabled = X86_MACHINE_GET_CLASS(x86ms)->fwcfg_dma_enabled;
638     uint16_t protocol;
639     int setup_size, kernel_size, cmdline_size;
640     int dtb_size, setup_data_offset;
641     uint32_t initrd_max;
642     uint8_t header[8192], *setup, *kernel;
643     hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
644     FILE *f;
645     char *vmode;
646     MachineState *machine = MACHINE(x86ms);
647     struct setup_data *setup_data;
648     const char *kernel_filename = machine->kernel_filename;
649     const char *initrd_filename = machine->initrd_filename;
650     const char *dtb_filename = machine->dtb;
651     const char *kernel_cmdline = machine->kernel_cmdline;
652     SevKernelLoaderContext sev_load_ctx = {};
653 
654     /* Align to 16 bytes as a paranoia measure */
655     cmdline_size = (strlen(kernel_cmdline) + 16) & ~15;
656 
657     /* load the kernel header */
658     f = fopen(kernel_filename, "rb");
659     if (!f) {
660         fprintf(stderr, "qemu: could not open kernel file '%s': %s\n",
661                 kernel_filename, strerror(errno));
662         exit(1);
663     }
664 
665     kernel_size = get_file_size(f);
666     if (!kernel_size ||
667         fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
668         MIN(ARRAY_SIZE(header), kernel_size)) {
669         fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
670                 kernel_filename, strerror(errno));
671         exit(1);
672     }
673 
674     /*
675      * kernel protocol version.
676      * Please see https://www.kernel.org/doc/Documentation/x86/boot.txt
677      */
678     if (ldl_le_p(header + 0x202) == 0x53726448) /* Magic signature "HdrS" */ {
679         protocol = lduw_le_p(header + 0x206);
680     } else {
681         /*
682          * This could be a multiboot kernel. If it is, let's stop treating it
683          * like a Linux kernel.
684          * Note: some multiboot images could be in the ELF format (the same of
685          * PVH), so we try multiboot first since we check the multiboot magic
686          * header before to load it.
687          */
688         if (load_multiboot(x86ms, fw_cfg, f, kernel_filename, initrd_filename,
689                            kernel_cmdline, kernel_size, header)) {
690             return;
691         }
692         /*
693          * Check if the file is an uncompressed kernel file (ELF) and load it,
694          * saving the PVH entry point used by the x86/HVM direct boot ABI.
695          * If load_elfboot() is successful, populate the fw_cfg info.
696          */
697         if (pvh_enabled &&
698             load_elfboot(kernel_filename, kernel_size,
699                          header, pvh_start_addr, fw_cfg)) {
700             fclose(f);
701 
702             fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
703                 strlen(kernel_cmdline) + 1);
704             fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
705 
706             setup = g_memdup2(header, sizeof(header));
707 
708             fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, sizeof(header));
709             fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA,
710                              setup, sizeof(header));
711 
712             /* load initrd */
713             if (initrd_filename) {
714                 GMappedFile *mapped_file;
715                 gsize initrd_size;
716                 gchar *initrd_data;
717                 GError *gerr = NULL;
718 
719                 mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
720                 if (!mapped_file) {
721                     fprintf(stderr, "qemu: error reading initrd %s: %s\n",
722                             initrd_filename, gerr->message);
723                     exit(1);
724                 }
725                 x86ms->initrd_mapped_file = mapped_file;
726 
727                 initrd_data = g_mapped_file_get_contents(mapped_file);
728                 initrd_size = g_mapped_file_get_length(mapped_file);
729                 initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
730                 if (initrd_size >= initrd_max) {
731                     fprintf(stderr, "qemu: initrd is too large, cannot support."
732                             "(max: %"PRIu32", need %"PRId64")\n",
733                             initrd_max, (uint64_t)initrd_size);
734                     exit(1);
735                 }
736 
737                 initrd_addr = (initrd_max - initrd_size) & ~4095;
738 
739                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
740                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
741                 fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data,
742                                  initrd_size);
743             }
744 
745             option_rom[nb_option_roms].bootindex = 0;
746             option_rom[nb_option_roms].name = "pvh.bin";
747             nb_option_roms++;
748 
749             return;
750         }
751         protocol = 0;
752     }
753 
754     if (protocol < 0x200 || !(header[0x211] & 0x01)) {
755         /* Low kernel */
756         real_addr    = 0x90000;
757         cmdline_addr = 0x9a000 - cmdline_size;
758         prot_addr    = 0x10000;
759     } else if (protocol < 0x202) {
760         /* High but ancient kernel */
761         real_addr    = 0x90000;
762         cmdline_addr = 0x9a000 - cmdline_size;
763         prot_addr    = 0x100000;
764     } else {
765         /* High and recent kernel */
766         real_addr    = 0x10000;
767         cmdline_addr = 0x20000;
768         prot_addr    = 0x100000;
769     }
770 
771     /* highest address for loading the initrd */
772     if (protocol >= 0x20c &&
773         lduw_le_p(header + 0x236) & XLF_CAN_BE_LOADED_ABOVE_4G) {
774         /*
775          * Linux has supported initrd up to 4 GB for a very long time (2007,
776          * long before XLF_CAN_BE_LOADED_ABOVE_4G which was added in 2013),
777          * though it only sets initrd_max to 2 GB to "work around bootloader
778          * bugs". Luckily, QEMU firmware(which does something like bootloader)
779          * has supported this.
780          *
781          * It's believed that if XLF_CAN_BE_LOADED_ABOVE_4G is set, initrd can
782          * be loaded into any address.
783          *
784          * In addition, initrd_max is uint32_t simply because QEMU doesn't
785          * support the 64-bit boot protocol (specifically the ext_ramdisk_image
786          * field).
787          *
788          * Therefore here just limit initrd_max to UINT32_MAX simply as well.
789          */
790         initrd_max = UINT32_MAX;
791     } else if (protocol >= 0x203) {
792         initrd_max = ldl_le_p(header + 0x22c);
793     } else {
794         initrd_max = 0x37ffffff;
795     }
796 
797     if (initrd_max >= x86ms->below_4g_mem_size - acpi_data_size) {
798         initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
799     }
800 
801     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
802     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline) + 1);
803     fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
804     sev_load_ctx.cmdline_data = (char *)kernel_cmdline;
805     sev_load_ctx.cmdline_size = strlen(kernel_cmdline) + 1;
806 
807     if (protocol >= 0x202) {
808         stl_le_p(header + 0x228, cmdline_addr);
809     } else {
810         stw_le_p(header + 0x20, 0xA33F);
811         stw_le_p(header + 0x22, cmdline_addr - real_addr);
812     }
813 
814     /* handle vga= parameter */
815     vmode = strstr(kernel_cmdline, "vga=");
816     if (vmode) {
817         unsigned int video_mode;
818         const char *end;
819         int ret;
820         /* skip "vga=" */
821         vmode += 4;
822         if (!strncmp(vmode, "normal", 6)) {
823             video_mode = 0xffff;
824         } else if (!strncmp(vmode, "ext", 3)) {
825             video_mode = 0xfffe;
826         } else if (!strncmp(vmode, "ask", 3)) {
827             video_mode = 0xfffd;
828         } else {
829             ret = qemu_strtoui(vmode, &end, 0, &video_mode);
830             if (ret != 0 || (*end && *end != ' ')) {
831                 fprintf(stderr, "qemu: invalid 'vga=' kernel parameter.\n");
832                 exit(1);
833             }
834         }
835         stw_le_p(header + 0x1fa, video_mode);
836     }
837 
838     /* loader type */
839     /*
840      * High nybble = B reserved for QEMU; low nybble is revision number.
841      * If this code is substantially changed, you may want to consider
842      * incrementing the revision.
843      */
844     if (protocol >= 0x200) {
845         header[0x210] = 0xB0;
846     }
847     /* heap */
848     if (protocol >= 0x201) {
849         header[0x211] |= 0x80; /* CAN_USE_HEAP */
850         stw_le_p(header + 0x224, cmdline_addr - real_addr - 0x200);
851     }
852 
853     /* load initrd */
854     if (initrd_filename) {
855         GMappedFile *mapped_file;
856         gsize initrd_size;
857         gchar *initrd_data;
858         GError *gerr = NULL;
859 
860         if (protocol < 0x200) {
861             fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
862             exit(1);
863         }
864 
865         mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
866         if (!mapped_file) {
867             fprintf(stderr, "qemu: error reading initrd %s: %s\n",
868                     initrd_filename, gerr->message);
869             exit(1);
870         }
871         x86ms->initrd_mapped_file = mapped_file;
872 
873         initrd_data = g_mapped_file_get_contents(mapped_file);
874         initrd_size = g_mapped_file_get_length(mapped_file);
875         if (initrd_size >= initrd_max) {
876             fprintf(stderr, "qemu: initrd is too large, cannot support."
877                     "(max: %"PRIu32", need %"PRId64")\n",
878                     initrd_max, (uint64_t)initrd_size);
879             exit(1);
880         }
881 
882         initrd_addr = (initrd_max - initrd_size) & ~4095;
883 
884         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
885         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
886         fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
887         sev_load_ctx.initrd_data = initrd_data;
888         sev_load_ctx.initrd_size = initrd_size;
889 
890         stl_le_p(header + 0x218, initrd_addr);
891         stl_le_p(header + 0x21c, initrd_size);
892     }
893 
894     /* load kernel and setup */
895     setup_size = header[0x1f1];
896     if (setup_size == 0) {
897         setup_size = 4;
898     }
899     setup_size = (setup_size + 1) * 512;
900     if (setup_size > kernel_size) {
901         fprintf(stderr, "qemu: invalid kernel header\n");
902         exit(1);
903     }
904 
905     setup  = g_malloc(setup_size);
906     kernel = g_malloc(kernel_size);
907     fseek(f, 0, SEEK_SET);
908     if (fread(setup, 1, setup_size, f) != setup_size) {
909         fprintf(stderr, "fread() failed\n");
910         exit(1);
911     }
912     fseek(f, 0, SEEK_SET);
913     if (fread(kernel, 1, kernel_size, f) != kernel_size) {
914         fprintf(stderr, "fread() failed\n");
915         exit(1);
916     }
917     fclose(f);
918 
919     /* append dtb to kernel */
920     if (dtb_filename) {
921         if (protocol < 0x209) {
922             fprintf(stderr, "qemu: Linux kernel too old to load a dtb\n");
923             exit(1);
924         }
925 
926         dtb_size = get_image_size(dtb_filename);
927         if (dtb_size <= 0) {
928             fprintf(stderr, "qemu: error reading dtb %s: %s\n",
929                     dtb_filename, strerror(errno));
930             exit(1);
931         }
932 
933         setup_data_offset = QEMU_ALIGN_UP(kernel_size, 16);
934         kernel_size = setup_data_offset + sizeof(struct setup_data) + dtb_size;
935         kernel = g_realloc(kernel, kernel_size);
936 
937         stq_le_p(header + 0x250, prot_addr + setup_data_offset);
938 
939         setup_data = (struct setup_data *)(kernel + setup_data_offset);
940         setup_data->next = 0;
941         setup_data->type = cpu_to_le32(SETUP_DTB);
942         setup_data->len = cpu_to_le32(dtb_size);
943 
944         load_image_size(dtb_filename, setup_data->data, dtb_size);
945     }
946 
947     /*
948      * If we're starting an encrypted VM, it will be OVMF based, which uses the
949      * efi stub for booting and doesn't require any values to be placed in the
950      * kernel header.  We therefore don't update the header so the hash of the
951      * kernel on the other side of the fw_cfg interface matches the hash of the
952      * file the user passed in.
953      */
954     if (!sev_enabled() && protocol > 0) {
955         memcpy(setup, header, MIN(sizeof(header), setup_size));
956     }
957 
958     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
959     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size - setup_size);
960     fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA,
961                      kernel + setup_size, kernel_size - setup_size);
962     sev_load_ctx.kernel_data = (char *)kernel + setup_size;
963     sev_load_ctx.kernel_size = kernel_size - setup_size;
964 
965     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
966     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
967     fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
968     sev_load_ctx.setup_data = (char *)setup;
969     sev_load_ctx.setup_size = setup_size;
970 
971     /* kernel without setup header patches */
972     fw_cfg_add_file(fw_cfg, "etc/boot/kernel", kernel, kernel_size);
973 
974     if (machine->shim_filename) {
975         GMappedFile *mapped_file;
976         GError *gerr = NULL;
977 
978         mapped_file = g_mapped_file_new(machine->shim_filename, false, &gerr);
979         if (!mapped_file) {
980             fprintf(stderr, "qemu: error reading shim %s: %s\n",
981                     machine->shim_filename, gerr->message);
982             exit(1);
983         }
984 
985         fw_cfg_add_file(fw_cfg, "etc/boot/shim",
986                         g_mapped_file_get_contents(mapped_file),
987                         g_mapped_file_get_length(mapped_file));
988     }
989 
990     if (sev_enabled()) {
991         sev_add_kernel_loader_hashes(&sev_load_ctx, &error_fatal);
992     }
993 
994     option_rom[nb_option_roms].bootindex = 0;
995     option_rom[nb_option_roms].name = "linuxboot.bin";
996     if (linuxboot_dma_enabled && fw_cfg_dma_enabled(fw_cfg)) {
997         option_rom[nb_option_roms].name = "linuxboot_dma.bin";
998     }
999     nb_option_roms++;
1000 }
1001 
1002 void x86_isa_bios_init(MemoryRegion *isa_bios, MemoryRegion *isa_memory,
1003                        MemoryRegion *bios, bool read_only)
1004 {
1005     uint64_t bios_size = memory_region_size(bios);
1006     uint64_t isa_bios_size = MIN(bios_size, 128 * KiB);
1007 
1008     memory_region_init_alias(isa_bios, NULL, "isa-bios", bios,
1009                              bios_size - isa_bios_size, isa_bios_size);
1010     memory_region_add_subregion_overlap(isa_memory, 1 * MiB - isa_bios_size,
1011                                         isa_bios, 1);
1012     memory_region_set_readonly(isa_bios, read_only);
1013 }
1014 
1015 void x86_bios_rom_init(X86MachineState *x86ms, const char *default_firmware,
1016                        MemoryRegion *rom_memory, bool isapc_ram_fw)
1017 {
1018     const char *bios_name;
1019     char *filename;
1020     int bios_size;
1021     ssize_t ret;
1022 
1023     /* BIOS load */
1024     bios_name = MACHINE(x86ms)->firmware ?: default_firmware;
1025     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1026     if (filename) {
1027         bios_size = get_image_size(filename);
1028     } else {
1029         bios_size = -1;
1030     }
1031     if (bios_size <= 0 ||
1032         (bios_size % 65536) != 0) {
1033         goto bios_error;
1034     }
1035     if (machine_require_guest_memfd(MACHINE(x86ms))) {
1036         memory_region_init_ram_guest_memfd(&x86ms->bios, NULL, "pc.bios",
1037                                            bios_size, &error_fatal);
1038     } else {
1039         memory_region_init_ram(&x86ms->bios, NULL, "pc.bios",
1040                                bios_size, &error_fatal);
1041     }
1042     if (sev_enabled()) {
1043         /*
1044          * The concept of a "reset" simply doesn't exist for
1045          * confidential computing guests, we have to destroy and
1046          * re-launch them instead.  So there is no need to register
1047          * the firmware as rom to properly re-initialize on reset.
1048          * Just go for a straight file load instead.
1049          */
1050         void *ptr = memory_region_get_ram_ptr(&x86ms->bios);
1051         load_image_size(filename, ptr, bios_size);
1052         x86_firmware_configure(0x100000000ULL - bios_size, ptr, bios_size);
1053     } else {
1054         memory_region_set_readonly(&x86ms->bios, !isapc_ram_fw);
1055         ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);
1056         if (ret != 0) {
1057             goto bios_error;
1058         }
1059     }
1060     g_free(filename);
1061 
1062     if (!machine_require_guest_memfd(MACHINE(x86ms))) {
1063         /* map the last 128KB of the BIOS in ISA space */
1064         x86_isa_bios_init(&x86ms->isa_bios, rom_memory, &x86ms->bios,
1065                           !isapc_ram_fw);
1066     }
1067 
1068     /* map all the bios at the top of memory */
1069     memory_region_add_subregion(rom_memory,
1070                                 (uint32_t)(-bios_size),
1071                                 &x86ms->bios);
1072     return;
1073 
1074 bios_error:
1075     fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);
1076     exit(1);
1077 }
1078