xref: /openbmc/qemu/hw/i386/x86.c (revision ddda3748)
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-common.h"
29 #include "qapi/error.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qapi-visit-common.h"
32 #include "qapi/visitor.h"
33 #include "sysemu/qtest.h"
34 #include "sysemu/numa.h"
35 #include "sysemu/replay.h"
36 #include "sysemu/sysemu.h"
37 #include "trace.h"
38 
39 #include "hw/i386/x86.h"
40 #include "target/i386/cpu.h"
41 #include "hw/i386/topology.h"
42 #include "hw/i386/fw_cfg.h"
43 #include "hw/intc/i8259.h"
44 
45 #include "hw/acpi/cpu_hotplug.h"
46 #include "hw/irq.h"
47 #include "hw/nmi.h"
48 #include "hw/loader.h"
49 #include "multiboot.h"
50 #include "elf.h"
51 #include "standard-headers/asm-x86/bootparam.h"
52 #include "config-devices.h"
53 #include "kvm_i386.h"
54 
55 #define BIOS_FILENAME "bios.bin"
56 
57 /* Physical Address of PVH entry point read from kernel ELF NOTE */
58 static size_t pvh_start_addr;
59 
60 /*
61  * Calculates initial APIC ID for a specific CPU index
62  *
63  * Currently we need to be able to calculate the APIC ID from the CPU index
64  * alone (without requiring a CPU object), as the QEMU<->Seabios interfaces have
65  * no concept of "CPU index", and the NUMA tables on fw_cfg need the APIC ID of
66  * all CPUs up to max_cpus.
67  */
68 uint32_t x86_cpu_apic_id_from_index(X86MachineState *x86ms,
69                                     unsigned int cpu_index)
70 {
71     MachineState *ms = MACHINE(x86ms);
72     X86MachineClass *x86mc = X86_MACHINE_GET_CLASS(x86ms);
73     uint32_t correct_id;
74     static bool warned;
75 
76     correct_id = x86_apicid_from_cpu_idx(x86ms->smp_dies, ms->smp.cores,
77                                          ms->smp.threads, cpu_index);
78     if (x86mc->compat_apic_id_mode) {
79         if (cpu_index != correct_id && !warned && !qtest_enabled()) {
80             error_report("APIC IDs set in compatibility mode, "
81                          "CPU topology won't match the configuration");
82             warned = true;
83         }
84         return cpu_index;
85     } else {
86         return correct_id;
87     }
88 }
89 
90 
91 void x86_cpu_new(X86MachineState *x86ms, int64_t apic_id, Error **errp)
92 {
93     Object *cpu = NULL;
94     Error *local_err = NULL;
95     CPUX86State *env = NULL;
96 
97     cpu = object_new(MACHINE(x86ms)->cpu_type);
98 
99     env = &X86_CPU(cpu)->env;
100     env->nr_dies = x86ms->smp_dies;
101 
102     object_property_set_uint(cpu, apic_id, "apic-id", &local_err);
103     object_property_set_bool(cpu, true, "realized", &local_err);
104 
105     object_unref(cpu);
106     error_propagate(errp, local_err);
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     possible_cpus = mc->possible_cpu_arch_ids(ms);
129     for (i = 0; i < ms->smp.cpus; i++) {
130         x86_cpu_new(x86ms, possible_cpus->cpus[i].arch_id, &error_fatal);
131     }
132 }
133 
134 CpuInstanceProperties
135 x86_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
136 {
137     MachineClass *mc = MACHINE_GET_CLASS(ms);
138     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
139 
140     assert(cpu_index < possible_cpus->len);
141     return possible_cpus->cpus[cpu_index].props;
142 }
143 
144 int64_t x86_get_default_cpu_node_id(const MachineState *ms, int idx)
145 {
146    X86CPUTopoInfo topo;
147    X86MachineState *x86ms = X86_MACHINE(ms);
148 
149    assert(idx < ms->possible_cpus->len);
150    x86_topo_ids_from_apicid(ms->possible_cpus->cpus[idx].arch_id,
151                             x86ms->smp_dies, ms->smp.cores,
152                             ms->smp.threads, &topo);
153    return topo.pkg_id % ms->numa_state->num_nodes;
154 }
155 
156 const CPUArchIdList *x86_possible_cpu_arch_ids(MachineState *ms)
157 {
158     X86MachineState *x86ms = X86_MACHINE(ms);
159     int i;
160     unsigned int max_cpus = ms->smp.max_cpus;
161 
162     if (ms->possible_cpus) {
163         /*
164          * make sure that max_cpus hasn't changed since the first use, i.e.
165          * -smp hasn't been parsed after it
166          */
167         assert(ms->possible_cpus->len == max_cpus);
168         return ms->possible_cpus;
169     }
170 
171     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
172                                   sizeof(CPUArchId) * max_cpus);
173     ms->possible_cpus->len = max_cpus;
174     for (i = 0; i < ms->possible_cpus->len; i++) {
175         X86CPUTopoInfo topo;
176 
177         ms->possible_cpus->cpus[i].type = ms->cpu_type;
178         ms->possible_cpus->cpus[i].vcpus_count = 1;
179         ms->possible_cpus->cpus[i].arch_id =
180             x86_cpu_apic_id_from_index(x86ms, i);
181         x86_topo_ids_from_apicid(ms->possible_cpus->cpus[i].arch_id,
182                                  x86ms->smp_dies, ms->smp.cores,
183                                  ms->smp.threads, &topo);
184         ms->possible_cpus->cpus[i].props.has_socket_id = true;
185         ms->possible_cpus->cpus[i].props.socket_id = topo.pkg_id;
186         if (x86ms->smp_dies > 1) {
187             ms->possible_cpus->cpus[i].props.has_die_id = true;
188             ms->possible_cpus->cpus[i].props.die_id = topo.die_id;
189         }
190         ms->possible_cpus->cpus[i].props.has_core_id = true;
191         ms->possible_cpus->cpus[i].props.core_id = topo.core_id;
192         ms->possible_cpus->cpus[i].props.has_thread_id = true;
193         ms->possible_cpus->cpus[i].props.thread_id = topo.smt_id;
194     }
195     return ms->possible_cpus;
196 }
197 
198 static void x86_nmi(NMIState *n, int cpu_index, Error **errp)
199 {
200     /* cpu index isn't used */
201     CPUState *cs;
202 
203     CPU_FOREACH(cs) {
204         X86CPU *cpu = X86_CPU(cs);
205 
206         if (!cpu->apic_state) {
207             cpu_interrupt(cs, CPU_INTERRUPT_NMI);
208         } else {
209             apic_deliver_nmi(cpu->apic_state);
210         }
211     }
212 }
213 
214 static long get_file_size(FILE *f)
215 {
216     long where, size;
217 
218     /* XXX: on Unix systems, using fstat() probably makes more sense */
219 
220     where = ftell(f);
221     fseek(f, 0, SEEK_END);
222     size = ftell(f);
223     fseek(f, where, SEEK_SET);
224 
225     return size;
226 }
227 
228 /* TSC handling */
229 uint64_t cpu_get_tsc(CPUX86State *env)
230 {
231     return cpu_get_ticks();
232 }
233 
234 /* IRQ handling */
235 static void pic_irq_request(void *opaque, int irq, int level)
236 {
237     CPUState *cs = first_cpu;
238     X86CPU *cpu = X86_CPU(cs);
239 
240     trace_x86_pic_interrupt(irq, level);
241     if (cpu->apic_state && !kvm_irqchip_in_kernel()) {
242         CPU_FOREACH(cs) {
243             cpu = X86_CPU(cs);
244             if (apic_accept_pic_intr(cpu->apic_state)) {
245                 apic_deliver_pic_intr(cpu->apic_state, level);
246             }
247         }
248     } else {
249         if (level) {
250             cpu_interrupt(cs, CPU_INTERRUPT_HARD);
251         } else {
252             cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
253         }
254     }
255 }
256 
257 qemu_irq x86_allocate_cpu_irq(void)
258 {
259     return qemu_allocate_irq(pic_irq_request, NULL, 0);
260 }
261 
262 int cpu_get_pic_interrupt(CPUX86State *env)
263 {
264     X86CPU *cpu = env_archcpu(env);
265     int intno;
266 
267     if (!kvm_irqchip_in_kernel()) {
268         intno = apic_get_interrupt(cpu->apic_state);
269         if (intno >= 0) {
270             return intno;
271         }
272         /* read the irq from the PIC */
273         if (!apic_accept_pic_intr(cpu->apic_state)) {
274             return -1;
275         }
276     }
277 
278     intno = pic_read_irq(isa_pic);
279     return intno;
280 }
281 
282 DeviceState *cpu_get_current_apic(void)
283 {
284     if (current_cpu) {
285         X86CPU *cpu = X86_CPU(current_cpu);
286         return cpu->apic_state;
287     } else {
288         return NULL;
289     }
290 }
291 
292 void gsi_handler(void *opaque, int n, int level)
293 {
294     GSIState *s = opaque;
295 
296     trace_x86_gsi_interrupt(n, level);
297     if (n < ISA_NUM_IRQS) {
298         /* Under KVM, Kernel will forward to both PIC and IOAPIC */
299         qemu_set_irq(s->i8259_irq[n], level);
300     }
301     qemu_set_irq(s->ioapic_irq[n], level);
302 }
303 
304 void ioapic_init_gsi(GSIState *gsi_state, const char *parent_name)
305 {
306     DeviceState *dev;
307     SysBusDevice *d;
308     unsigned int i;
309 
310     assert(parent_name);
311     if (kvm_ioapic_in_kernel()) {
312         dev = qdev_create(NULL, TYPE_KVM_IOAPIC);
313     } else {
314         dev = qdev_create(NULL, TYPE_IOAPIC);
315     }
316     object_property_add_child(object_resolve_path(parent_name, NULL),
317                               "ioapic", OBJECT(dev), NULL);
318     qdev_init_nofail(dev);
319     d = SYS_BUS_DEVICE(dev);
320     sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
321 
322     for (i = 0; i < IOAPIC_NUM_PINS; i++) {
323         gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
324     }
325 }
326 
327 struct setup_data {
328     uint64_t next;
329     uint32_t type;
330     uint32_t len;
331     uint8_t data[0];
332 } __attribute__((packed));
333 
334 
335 /*
336  * The entry point into the kernel for PVH boot is different from
337  * the native entry point.  The PVH entry is defined by the x86/HVM
338  * direct boot ABI and is available in an ELFNOTE in the kernel binary.
339  *
340  * This function is passed to load_elf() when it is called from
341  * load_elfboot() which then additionally checks for an ELF Note of
342  * type XEN_ELFNOTE_PHYS32_ENTRY and passes it to this function to
343  * parse the PVH entry address from the ELF Note.
344  *
345  * Due to trickery in elf_opts.h, load_elf() is actually available as
346  * load_elf32() or load_elf64() and this routine needs to be able
347  * to deal with being called as 32 or 64 bit.
348  *
349  * The address of the PVH entry point is saved to the 'pvh_start_addr'
350  * global variable.  (although the entry point is 32-bit, the kernel
351  * binary can be either 32-bit or 64-bit).
352  */
353 static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64)
354 {
355     size_t *elf_note_data_addr;
356 
357     /* Check if ELF Note header passed in is valid */
358     if (arg1 == NULL) {
359         return 0;
360     }
361 
362     if (is64) {
363         struct elf64_note *nhdr64 = (struct elf64_note *)arg1;
364         uint64_t nhdr_size64 = sizeof(struct elf64_note);
365         uint64_t phdr_align = *(uint64_t *)arg2;
366         uint64_t nhdr_namesz = nhdr64->n_namesz;
367 
368         elf_note_data_addr =
369             ((void *)nhdr64) + nhdr_size64 +
370             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
371     } else {
372         struct elf32_note *nhdr32 = (struct elf32_note *)arg1;
373         uint32_t nhdr_size32 = sizeof(struct elf32_note);
374         uint32_t phdr_align = *(uint32_t *)arg2;
375         uint32_t nhdr_namesz = nhdr32->n_namesz;
376 
377         elf_note_data_addr =
378             ((void *)nhdr32) + nhdr_size32 +
379             QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
380     }
381 
382     pvh_start_addr = *elf_note_data_addr;
383 
384     return pvh_start_addr;
385 }
386 
387 static bool load_elfboot(const char *kernel_filename,
388                          int kernel_file_size,
389                          uint8_t *header,
390                          size_t pvh_xen_start_addr,
391                          FWCfgState *fw_cfg)
392 {
393     uint32_t flags = 0;
394     uint32_t mh_load_addr = 0;
395     uint32_t elf_kernel_size = 0;
396     uint64_t elf_entry;
397     uint64_t elf_low, elf_high;
398     int kernel_size;
399 
400     if (ldl_p(header) != 0x464c457f) {
401         return false; /* no elfboot */
402     }
403 
404     bool elf_is64 = header[EI_CLASS] == ELFCLASS64;
405     flags = elf_is64 ?
406         ((Elf64_Ehdr *)header)->e_flags : ((Elf32_Ehdr *)header)->e_flags;
407 
408     if (flags & 0x00010004) { /* LOAD_ELF_HEADER_HAS_ADDR */
409         error_report("elfboot unsupported flags = %x", flags);
410         exit(1);
411     }
412 
413     uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY;
414     kernel_size = load_elf(kernel_filename, read_pvh_start_addr,
415                            NULL, &elf_note_type, &elf_entry,
416                            &elf_low, &elf_high, NULL, 0, I386_ELF_MACHINE,
417                            0, 0);
418 
419     if (kernel_size < 0) {
420         error_report("Error while loading elf kernel");
421         exit(1);
422     }
423     mh_load_addr = elf_low;
424     elf_kernel_size = elf_high - elf_low;
425 
426     if (pvh_start_addr == 0) {
427         error_report("Error loading uncompressed kernel without PVH ELF Note");
428         exit(1);
429     }
430     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr);
431     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
432     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size);
433 
434     return true;
435 }
436 
437 void x86_load_linux(X86MachineState *x86ms,
438                     FWCfgState *fw_cfg,
439                     int acpi_data_size,
440                     bool pvh_enabled,
441                     bool linuxboot_dma_enabled)
442 {
443     uint16_t protocol;
444     int setup_size, kernel_size, cmdline_size;
445     int dtb_size, setup_data_offset;
446     uint32_t initrd_max;
447     uint8_t header[8192], *setup, *kernel;
448     hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
449     FILE *f;
450     char *vmode;
451     MachineState *machine = MACHINE(x86ms);
452     struct setup_data *setup_data;
453     const char *kernel_filename = machine->kernel_filename;
454     const char *initrd_filename = machine->initrd_filename;
455     const char *dtb_filename = machine->dtb;
456     const char *kernel_cmdline = machine->kernel_cmdline;
457 
458     /* Align to 16 bytes as a paranoia measure */
459     cmdline_size = (strlen(kernel_cmdline) + 16) & ~15;
460 
461     /* load the kernel header */
462     f = fopen(kernel_filename, "rb");
463     if (!f) {
464         fprintf(stderr, "qemu: could not open kernel file '%s': %s\n",
465                 kernel_filename, strerror(errno));
466         exit(1);
467     }
468 
469     kernel_size = get_file_size(f);
470     if (!kernel_size ||
471         fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
472         MIN(ARRAY_SIZE(header), kernel_size)) {
473         fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
474                 kernel_filename, strerror(errno));
475         exit(1);
476     }
477 
478     /* kernel protocol version */
479     if (ldl_p(header + 0x202) == 0x53726448) {
480         protocol = lduw_p(header + 0x206);
481     } else {
482         /*
483          * This could be a multiboot kernel. If it is, let's stop treating it
484          * like a Linux kernel.
485          * Note: some multiboot images could be in the ELF format (the same of
486          * PVH), so we try multiboot first since we check the multiboot magic
487          * header before to load it.
488          */
489         if (load_multiboot(fw_cfg, f, kernel_filename, initrd_filename,
490                            kernel_cmdline, kernel_size, header)) {
491             return;
492         }
493         /*
494          * Check if the file is an uncompressed kernel file (ELF) and load it,
495          * saving the PVH entry point used by the x86/HVM direct boot ABI.
496          * If load_elfboot() is successful, populate the fw_cfg info.
497          */
498         if (pvh_enabled &&
499             load_elfboot(kernel_filename, kernel_size,
500                          header, pvh_start_addr, fw_cfg)) {
501             fclose(f);
502 
503             fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
504                 strlen(kernel_cmdline) + 1);
505             fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
506 
507             fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, sizeof(header));
508             fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA,
509                              header, sizeof(header));
510 
511             /* load initrd */
512             if (initrd_filename) {
513                 GMappedFile *mapped_file;
514                 gsize initrd_size;
515                 gchar *initrd_data;
516                 GError *gerr = NULL;
517 
518                 mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
519                 if (!mapped_file) {
520                     fprintf(stderr, "qemu: error reading initrd %s: %s\n",
521                             initrd_filename, gerr->message);
522                     exit(1);
523                 }
524                 x86ms->initrd_mapped_file = mapped_file;
525 
526                 initrd_data = g_mapped_file_get_contents(mapped_file);
527                 initrd_size = g_mapped_file_get_length(mapped_file);
528                 initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
529                 if (initrd_size >= initrd_max) {
530                     fprintf(stderr, "qemu: initrd is too large, cannot support."
531                             "(max: %"PRIu32", need %"PRId64")\n",
532                             initrd_max, (uint64_t)initrd_size);
533                     exit(1);
534                 }
535 
536                 initrd_addr = (initrd_max - initrd_size) & ~4095;
537 
538                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
539                 fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
540                 fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data,
541                                  initrd_size);
542             }
543 
544             option_rom[nb_option_roms].bootindex = 0;
545             option_rom[nb_option_roms].name = "pvh.bin";
546             nb_option_roms++;
547 
548             return;
549         }
550         protocol = 0;
551     }
552 
553     if (protocol < 0x200 || !(header[0x211] & 0x01)) {
554         /* Low kernel */
555         real_addr    = 0x90000;
556         cmdline_addr = 0x9a000 - cmdline_size;
557         prot_addr    = 0x10000;
558     } else if (protocol < 0x202) {
559         /* High but ancient kernel */
560         real_addr    = 0x90000;
561         cmdline_addr = 0x9a000 - cmdline_size;
562         prot_addr    = 0x100000;
563     } else {
564         /* High and recent kernel */
565         real_addr    = 0x10000;
566         cmdline_addr = 0x20000;
567         prot_addr    = 0x100000;
568     }
569 
570     /* highest address for loading the initrd */
571     if (protocol >= 0x20c &&
572         lduw_p(header + 0x236) & XLF_CAN_BE_LOADED_ABOVE_4G) {
573         /*
574          * Linux has supported initrd up to 4 GB for a very long time (2007,
575          * long before XLF_CAN_BE_LOADED_ABOVE_4G which was added in 2013),
576          * though it only sets initrd_max to 2 GB to "work around bootloader
577          * bugs". Luckily, QEMU firmware(which does something like bootloader)
578          * has supported this.
579          *
580          * It's believed that if XLF_CAN_BE_LOADED_ABOVE_4G is set, initrd can
581          * be loaded into any address.
582          *
583          * In addition, initrd_max is uint32_t simply because QEMU doesn't
584          * support the 64-bit boot protocol (specifically the ext_ramdisk_image
585          * field).
586          *
587          * Therefore here just limit initrd_max to UINT32_MAX simply as well.
588          */
589         initrd_max = UINT32_MAX;
590     } else if (protocol >= 0x203) {
591         initrd_max = ldl_p(header + 0x22c);
592     } else {
593         initrd_max = 0x37ffffff;
594     }
595 
596     if (initrd_max >= x86ms->below_4g_mem_size - acpi_data_size) {
597         initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
598     }
599 
600     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
601     fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline) + 1);
602     fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
603 
604     if (protocol >= 0x202) {
605         stl_p(header + 0x228, cmdline_addr);
606     } else {
607         stw_p(header + 0x20, 0xA33F);
608         stw_p(header + 0x22, cmdline_addr - real_addr);
609     }
610 
611     /* handle vga= parameter */
612     vmode = strstr(kernel_cmdline, "vga=");
613     if (vmode) {
614         unsigned int video_mode;
615         const char *end;
616         int ret;
617         /* skip "vga=" */
618         vmode += 4;
619         if (!strncmp(vmode, "normal", 6)) {
620             video_mode = 0xffff;
621         } else if (!strncmp(vmode, "ext", 3)) {
622             video_mode = 0xfffe;
623         } else if (!strncmp(vmode, "ask", 3)) {
624             video_mode = 0xfffd;
625         } else {
626             ret = qemu_strtoui(vmode, &end, 0, &video_mode);
627             if (ret != 0 || (*end && *end != ' ')) {
628                 fprintf(stderr, "qemu: invalid 'vga=' kernel parameter.\n");
629                 exit(1);
630             }
631         }
632         stw_p(header + 0x1fa, video_mode);
633     }
634 
635     /* loader type */
636     /*
637      * High nybble = B reserved for QEMU; low nybble is revision number.
638      * If this code is substantially changed, you may want to consider
639      * incrementing the revision.
640      */
641     if (protocol >= 0x200) {
642         header[0x210] = 0xB0;
643     }
644     /* heap */
645     if (protocol >= 0x201) {
646         header[0x211] |= 0x80; /* CAN_USE_HEAP */
647         stw_p(header + 0x224, cmdline_addr - real_addr - 0x200);
648     }
649 
650     /* load initrd */
651     if (initrd_filename) {
652         GMappedFile *mapped_file;
653         gsize initrd_size;
654         gchar *initrd_data;
655         GError *gerr = NULL;
656 
657         if (protocol < 0x200) {
658             fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
659             exit(1);
660         }
661 
662         mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
663         if (!mapped_file) {
664             fprintf(stderr, "qemu: error reading initrd %s: %s\n",
665                     initrd_filename, gerr->message);
666             exit(1);
667         }
668         x86ms->initrd_mapped_file = mapped_file;
669 
670         initrd_data = g_mapped_file_get_contents(mapped_file);
671         initrd_size = g_mapped_file_get_length(mapped_file);
672         if (initrd_size >= initrd_max) {
673             fprintf(stderr, "qemu: initrd is too large, cannot support."
674                     "(max: %"PRIu32", need %"PRId64")\n",
675                     initrd_max, (uint64_t)initrd_size);
676             exit(1);
677         }
678 
679         initrd_addr = (initrd_max - initrd_size) & ~4095;
680 
681         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
682         fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
683         fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
684 
685         stl_p(header + 0x218, initrd_addr);
686         stl_p(header + 0x21c, initrd_size);
687     }
688 
689     /* load kernel and setup */
690     setup_size = header[0x1f1];
691     if (setup_size == 0) {
692         setup_size = 4;
693     }
694     setup_size = (setup_size + 1) * 512;
695     if (setup_size > kernel_size) {
696         fprintf(stderr, "qemu: invalid kernel header\n");
697         exit(1);
698     }
699     kernel_size -= setup_size;
700 
701     setup  = g_malloc(setup_size);
702     kernel = g_malloc(kernel_size);
703     fseek(f, 0, SEEK_SET);
704     if (fread(setup, 1, setup_size, f) != setup_size) {
705         fprintf(stderr, "fread() failed\n");
706         exit(1);
707     }
708     if (fread(kernel, 1, kernel_size, f) != kernel_size) {
709         fprintf(stderr, "fread() failed\n");
710         exit(1);
711     }
712     fclose(f);
713 
714     /* append dtb to kernel */
715     if (dtb_filename) {
716         if (protocol < 0x209) {
717             fprintf(stderr, "qemu: Linux kernel too old to load a dtb\n");
718             exit(1);
719         }
720 
721         dtb_size = get_image_size(dtb_filename);
722         if (dtb_size <= 0) {
723             fprintf(stderr, "qemu: error reading dtb %s: %s\n",
724                     dtb_filename, strerror(errno));
725             exit(1);
726         }
727 
728         setup_data_offset = QEMU_ALIGN_UP(kernel_size, 16);
729         kernel_size = setup_data_offset + sizeof(struct setup_data) + dtb_size;
730         kernel = g_realloc(kernel, kernel_size);
731 
732         stq_p(header + 0x250, prot_addr + setup_data_offset);
733 
734         setup_data = (struct setup_data *)(kernel + setup_data_offset);
735         setup_data->next = 0;
736         setup_data->type = cpu_to_le32(SETUP_DTB);
737         setup_data->len = cpu_to_le32(dtb_size);
738 
739         load_image_size(dtb_filename, setup_data->data, dtb_size);
740     }
741 
742     memcpy(setup, header, MIN(sizeof(header), setup_size));
743 
744     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
745     fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
746     fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);
747 
748     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
749     fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
750     fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
751 
752     option_rom[nb_option_roms].bootindex = 0;
753     option_rom[nb_option_roms].name = "linuxboot.bin";
754     if (linuxboot_dma_enabled && fw_cfg_dma_enabled(fw_cfg)) {
755         option_rom[nb_option_roms].name = "linuxboot_dma.bin";
756     }
757     nb_option_roms++;
758 }
759 
760 void x86_bios_rom_init(MemoryRegion *rom_memory, bool isapc_ram_fw)
761 {
762     char *filename;
763     MemoryRegion *bios, *isa_bios;
764     int bios_size, isa_bios_size;
765     int ret;
766 
767     /* BIOS load */
768     if (bios_name == NULL) {
769         bios_name = BIOS_FILENAME;
770     }
771     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
772     if (filename) {
773         bios_size = get_image_size(filename);
774     } else {
775         bios_size = -1;
776     }
777     if (bios_size <= 0 ||
778         (bios_size % 65536) != 0) {
779         goto bios_error;
780     }
781     bios = g_malloc(sizeof(*bios));
782     memory_region_init_ram(bios, NULL, "pc.bios", bios_size, &error_fatal);
783     if (!isapc_ram_fw) {
784         memory_region_set_readonly(bios, true);
785     }
786     ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);
787     if (ret != 0) {
788     bios_error:
789         fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);
790         exit(1);
791     }
792     g_free(filename);
793 
794     /* map the last 128KB of the BIOS in ISA space */
795     isa_bios_size = MIN(bios_size, 128 * KiB);
796     isa_bios = g_malloc(sizeof(*isa_bios));
797     memory_region_init_alias(isa_bios, NULL, "isa-bios", bios,
798                              bios_size - isa_bios_size, isa_bios_size);
799     memory_region_add_subregion_overlap(rom_memory,
800                                         0x100000 - isa_bios_size,
801                                         isa_bios,
802                                         1);
803     if (!isapc_ram_fw) {
804         memory_region_set_readonly(isa_bios, true);
805     }
806 
807     /* map all the bios at the top of memory */
808     memory_region_add_subregion(rom_memory,
809                                 (uint32_t)(-bios_size),
810                                 bios);
811 }
812 
813 static void x86_machine_get_max_ram_below_4g(Object *obj, Visitor *v,
814                                              const char *name, void *opaque,
815                                              Error **errp)
816 {
817     X86MachineState *x86ms = X86_MACHINE(obj);
818     uint64_t value = x86ms->max_ram_below_4g;
819 
820     visit_type_size(v, name, &value, errp);
821 }
822 
823 static void x86_machine_set_max_ram_below_4g(Object *obj, Visitor *v,
824                                              const char *name, void *opaque,
825                                              Error **errp)
826 {
827     X86MachineState *x86ms = X86_MACHINE(obj);
828     Error *error = NULL;
829     uint64_t value;
830 
831     visit_type_size(v, name, &value, &error);
832     if (error) {
833         error_propagate(errp, error);
834         return;
835     }
836     if (value > 4 * GiB) {
837         error_setg(&error,
838                    "Machine option 'max-ram-below-4g=%"PRIu64
839                    "' expects size less than or equal to 4G", value);
840         error_propagate(errp, error);
841         return;
842     }
843 
844     if (value < 1 * MiB) {
845         warn_report("Only %" PRIu64 " bytes of RAM below the 4GiB boundary,"
846                     "BIOS may not work with less than 1MiB", value);
847     }
848 
849     x86ms->max_ram_below_4g = value;
850 }
851 
852 bool x86_machine_is_smm_enabled(X86MachineState *x86ms)
853 {
854     bool smm_available = false;
855 
856     if (x86ms->smm == ON_OFF_AUTO_OFF) {
857         return false;
858     }
859 
860     if (tcg_enabled() || qtest_enabled()) {
861         smm_available = true;
862     } else if (kvm_enabled()) {
863         smm_available = kvm_has_smm();
864     }
865 
866     if (smm_available) {
867         return true;
868     }
869 
870     if (x86ms->smm == ON_OFF_AUTO_ON) {
871         error_report("System Management Mode not supported by this hypervisor.");
872         exit(1);
873     }
874     return false;
875 }
876 
877 static void x86_machine_get_smm(Object *obj, Visitor *v, const char *name,
878                                void *opaque, Error **errp)
879 {
880     X86MachineState *x86ms = X86_MACHINE(obj);
881     OnOffAuto smm = x86ms->smm;
882 
883     visit_type_OnOffAuto(v, name, &smm, errp);
884 }
885 
886 static void x86_machine_set_smm(Object *obj, Visitor *v, const char *name,
887                                void *opaque, Error **errp)
888 {
889     X86MachineState *x86ms = X86_MACHINE(obj);
890 
891     visit_type_OnOffAuto(v, name, &x86ms->smm, errp);
892 }
893 
894 static void x86_machine_initfn(Object *obj)
895 {
896     X86MachineState *x86ms = X86_MACHINE(obj);
897 
898     x86ms->smm = ON_OFF_AUTO_AUTO;
899     x86ms->max_ram_below_4g = 0; /* use default */
900     x86ms->smp_dies = 1;
901 }
902 
903 static void x86_machine_class_init(ObjectClass *oc, void *data)
904 {
905     MachineClass *mc = MACHINE_CLASS(oc);
906     X86MachineClass *x86mc = X86_MACHINE_CLASS(oc);
907     NMIClass *nc = NMI_CLASS(oc);
908 
909     mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
910     mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
911     mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
912     x86mc->compat_apic_id_mode = false;
913     x86mc->save_tsc_khz = true;
914     nc->nmi_monitor_handler = x86_nmi;
915 
916     object_class_property_add(oc, X86_MACHINE_MAX_RAM_BELOW_4G, "size",
917         x86_machine_get_max_ram_below_4g, x86_machine_set_max_ram_below_4g,
918         NULL, NULL, &error_abort);
919     object_class_property_set_description(oc, X86_MACHINE_MAX_RAM_BELOW_4G,
920         "Maximum ram below the 4G boundary (32bit boundary)", &error_abort);
921 
922     object_class_property_add(oc, X86_MACHINE_SMM, "OnOffAuto",
923         x86_machine_get_smm, x86_machine_set_smm,
924         NULL, NULL, &error_abort);
925     object_class_property_set_description(oc, X86_MACHINE_SMM,
926         "Enable SMM", &error_abort);
927 }
928 
929 static const TypeInfo x86_machine_info = {
930     .name = TYPE_X86_MACHINE,
931     .parent = TYPE_MACHINE,
932     .abstract = true,
933     .instance_size = sizeof(X86MachineState),
934     .instance_init = x86_machine_initfn,
935     .class_size = sizeof(X86MachineClass),
936     .class_init = x86_machine_class_init,
937     .interfaces = (InterfaceInfo[]) {
938          { TYPE_NMI },
939          { }
940     },
941 };
942 
943 static void x86_machine_register_types(void)
944 {
945     type_register_static(&x86_machine_info);
946 }
947 
948 type_init(x86_machine_register_types)
949