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