x86-common.c 36 KB

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