xref: /openbmc/qemu/hw/arm/boot.c (revision 3174c64b)
1 /*
2  * ARM kernel loader.
3  *
4  * Copyright (c) 2006-2007 CodeSourcery.
5  * Written by Paul Brook
6  *
7  * This code is licensed under the GPL.
8  */
9 
10 #include "qemu/osdep.h"
11 #include "hw/hw.h"
12 #include "hw/arm/arm.h"
13 #include "hw/arm/linux-boot-if.h"
14 #include "sysemu/kvm.h"
15 #include "sysemu/sysemu.h"
16 #include "hw/boards.h"
17 #include "hw/loader.h"
18 #include "elf.h"
19 #include "sysemu/device_tree.h"
20 #include "qemu/config-file.h"
21 #include "exec/address-spaces.h"
22 
23 /* Kernel boot protocol is specified in the kernel docs
24  * Documentation/arm/Booting and Documentation/arm64/booting.txt
25  * They have different preferred image load offsets from system RAM base.
26  */
27 #define KERNEL_ARGS_ADDR 0x100
28 #define KERNEL_LOAD_ADDR 0x00010000
29 #define KERNEL64_LOAD_ADDR 0x00080000
30 
31 typedef enum {
32     FIXUP_NONE = 0,     /* do nothing */
33     FIXUP_TERMINATOR,   /* end of insns */
34     FIXUP_BOARDID,      /* overwrite with board ID number */
35     FIXUP_BOARD_SETUP,  /* overwrite with board specific setup code address */
36     FIXUP_ARGPTR,       /* overwrite with pointer to kernel args */
37     FIXUP_ENTRYPOINT,   /* overwrite with kernel entry point */
38     FIXUP_GIC_CPU_IF,   /* overwrite with GIC CPU interface address */
39     FIXUP_BOOTREG,      /* overwrite with boot register address */
40     FIXUP_DSB,          /* overwrite with correct DSB insn for cpu */
41     FIXUP_MAX,
42 } FixupType;
43 
44 typedef struct ARMInsnFixup {
45     uint32_t insn;
46     FixupType fixup;
47 } ARMInsnFixup;
48 
49 static const ARMInsnFixup bootloader_aarch64[] = {
50     { 0x580000c0 }, /* ldr x0, arg ; Load the lower 32-bits of DTB */
51     { 0xaa1f03e1 }, /* mov x1, xzr */
52     { 0xaa1f03e2 }, /* mov x2, xzr */
53     { 0xaa1f03e3 }, /* mov x3, xzr */
54     { 0x58000084 }, /* ldr x4, entry ; Load the lower 32-bits of kernel entry */
55     { 0xd61f0080 }, /* br x4      ; Jump to the kernel entry point */
56     { 0, FIXUP_ARGPTR }, /* arg: .word @DTB Lower 32-bits */
57     { 0 }, /* .word @DTB Higher 32-bits */
58     { 0, FIXUP_ENTRYPOINT }, /* entry: .word @Kernel Entry Lower 32-bits */
59     { 0 }, /* .word @Kernel Entry Higher 32-bits */
60     { 0, FIXUP_TERMINATOR }
61 };
62 
63 /* A very small bootloader: call the board-setup code (if needed),
64  * set r0-r2, then jump to the kernel.
65  * If we're not calling boot setup code then we don't copy across
66  * the first BOOTLOADER_NO_BOARD_SETUP_OFFSET insns in this array.
67  */
68 
69 static const ARMInsnFixup bootloader[] = {
70     { 0xe28fe008 }, /* add     lr, pc, #8 */
71     { 0xe51ff004 }, /* ldr     pc, [pc, #-4] */
72     { 0, FIXUP_BOARD_SETUP },
73 #define BOOTLOADER_NO_BOARD_SETUP_OFFSET 3
74     { 0xe3a00000 }, /* mov     r0, #0 */
75     { 0xe59f1004 }, /* ldr     r1, [pc, #4] */
76     { 0xe59f2004 }, /* ldr     r2, [pc, #4] */
77     { 0xe59ff004 }, /* ldr     pc, [pc, #4] */
78     { 0, FIXUP_BOARDID },
79     { 0, FIXUP_ARGPTR },
80     { 0, FIXUP_ENTRYPOINT },
81     { 0, FIXUP_TERMINATOR }
82 };
83 
84 /* Handling for secondary CPU boot in a multicore system.
85  * Unlike the uniprocessor/primary CPU boot, this is platform
86  * dependent. The default code here is based on the secondary
87  * CPU boot protocol used on realview/vexpress boards, with
88  * some parameterisation to increase its flexibility.
89  * QEMU platform models for which this code is not appropriate
90  * should override write_secondary_boot and secondary_cpu_reset_hook
91  * instead.
92  *
93  * This code enables the interrupt controllers for the secondary
94  * CPUs and then puts all the secondary CPUs into a loop waiting
95  * for an interprocessor interrupt and polling a configurable
96  * location for the kernel secondary CPU entry point.
97  */
98 #define DSB_INSN 0xf57ff04f
99 #define CP15_DSB_INSN 0xee070f9a /* mcr cp15, 0, r0, c7, c10, 4 */
100 
101 static const ARMInsnFixup smpboot[] = {
102     { 0xe59f2028 }, /* ldr r2, gic_cpu_if */
103     { 0xe59f0028 }, /* ldr r0, bootreg_addr */
104     { 0xe3a01001 }, /* mov r1, #1 */
105     { 0xe5821000 }, /* str r1, [r2] - set GICC_CTLR.Enable */
106     { 0xe3a010ff }, /* mov r1, #0xff */
107     { 0xe5821004 }, /* str r1, [r2, 4] - set GIC_PMR.Priority to 0xff */
108     { 0, FIXUP_DSB },   /* dsb */
109     { 0xe320f003 }, /* wfi */
110     { 0xe5901000 }, /* ldr     r1, [r0] */
111     { 0xe1110001 }, /* tst     r1, r1 */
112     { 0x0afffffb }, /* beq     <wfi> */
113     { 0xe12fff11 }, /* bx      r1 */
114     { 0, FIXUP_GIC_CPU_IF }, /* gic_cpu_if: .word 0x.... */
115     { 0, FIXUP_BOOTREG }, /* bootreg_addr: .word 0x.... */
116     { 0, FIXUP_TERMINATOR }
117 };
118 
119 static void write_bootloader(const char *name, hwaddr addr,
120                              const ARMInsnFixup *insns, uint32_t *fixupcontext)
121 {
122     /* Fix up the specified bootloader fragment and write it into
123      * guest memory using rom_add_blob_fixed(). fixupcontext is
124      * an array giving the values to write in for the fixup types
125      * which write a value into the code array.
126      */
127     int i, len;
128     uint32_t *code;
129 
130     len = 0;
131     while (insns[len].fixup != FIXUP_TERMINATOR) {
132         len++;
133     }
134 
135     code = g_new0(uint32_t, len);
136 
137     for (i = 0; i < len; i++) {
138         uint32_t insn = insns[i].insn;
139         FixupType fixup = insns[i].fixup;
140 
141         switch (fixup) {
142         case FIXUP_NONE:
143             break;
144         case FIXUP_BOARDID:
145         case FIXUP_BOARD_SETUP:
146         case FIXUP_ARGPTR:
147         case FIXUP_ENTRYPOINT:
148         case FIXUP_GIC_CPU_IF:
149         case FIXUP_BOOTREG:
150         case FIXUP_DSB:
151             insn = fixupcontext[fixup];
152             break;
153         default:
154             abort();
155         }
156         code[i] = tswap32(insn);
157     }
158 
159     rom_add_blob_fixed(name, code, len * sizeof(uint32_t), addr);
160 
161     g_free(code);
162 }
163 
164 static void default_write_secondary(ARMCPU *cpu,
165                                     const struct arm_boot_info *info)
166 {
167     uint32_t fixupcontext[FIXUP_MAX];
168 
169     fixupcontext[FIXUP_GIC_CPU_IF] = info->gic_cpu_if_addr;
170     fixupcontext[FIXUP_BOOTREG] = info->smp_bootreg_addr;
171     if (arm_feature(&cpu->env, ARM_FEATURE_V7)) {
172         fixupcontext[FIXUP_DSB] = DSB_INSN;
173     } else {
174         fixupcontext[FIXUP_DSB] = CP15_DSB_INSN;
175     }
176 
177     write_bootloader("smpboot", info->smp_loader_start,
178                      smpboot, fixupcontext);
179 }
180 
181 void arm_write_secure_board_setup_dummy_smc(ARMCPU *cpu,
182                                             const struct arm_boot_info *info,
183                                             hwaddr mvbar_addr)
184 {
185     int n;
186     uint32_t mvbar_blob[] = {
187         /* mvbar_addr: secure monitor vectors
188          * Default unimplemented and unused vectors to spin. Makes it
189          * easier to debug (as opposed to the CPU running away).
190          */
191         0xeafffffe, /* (spin) */
192         0xeafffffe, /* (spin) */
193         0xe1b0f00e, /* movs pc, lr ;SMC exception return */
194         0xeafffffe, /* (spin) */
195         0xeafffffe, /* (spin) */
196         0xeafffffe, /* (spin) */
197         0xeafffffe, /* (spin) */
198         0xeafffffe, /* (spin) */
199     };
200     uint32_t board_setup_blob[] = {
201         /* board setup addr */
202         0xe3a00e00 + (mvbar_addr >> 4), /* mov r0, #mvbar_addr */
203         0xee0c0f30, /* mcr     p15, 0, r0, c12, c0, 1 ;set MVBAR */
204         0xee110f11, /* mrc     p15, 0, r0, c1 , c1, 0 ;read SCR */
205         0xe3800031, /* orr     r0, #0x31              ;enable AW, FW, NS */
206         0xee010f11, /* mcr     p15, 0, r0, c1, c1, 0  ;write SCR */
207         0xe1a0100e, /* mov     r1, lr                 ;save LR across SMC */
208         0xe1600070, /* smc     #0                     ;call monitor to flush SCR */
209         0xe1a0f001, /* mov     pc, r1                 ;return */
210     };
211 
212     /* check that mvbar_addr is correctly aligned and relocatable (using MOV) */
213     assert((mvbar_addr & 0x1f) == 0 && (mvbar_addr >> 4) < 0x100);
214 
215     /* check that these blobs don't overlap */
216     assert((mvbar_addr + sizeof(mvbar_blob) <= info->board_setup_addr)
217           || (info->board_setup_addr + sizeof(board_setup_blob) <= mvbar_addr));
218 
219     for (n = 0; n < ARRAY_SIZE(mvbar_blob); n++) {
220         mvbar_blob[n] = tswap32(mvbar_blob[n]);
221     }
222     rom_add_blob_fixed("board-setup-mvbar", mvbar_blob, sizeof(mvbar_blob),
223                        mvbar_addr);
224 
225     for (n = 0; n < ARRAY_SIZE(board_setup_blob); n++) {
226         board_setup_blob[n] = tswap32(board_setup_blob[n]);
227     }
228     rom_add_blob_fixed("board-setup", board_setup_blob,
229                        sizeof(board_setup_blob), info->board_setup_addr);
230 }
231 
232 static void default_reset_secondary(ARMCPU *cpu,
233                                     const struct arm_boot_info *info)
234 {
235     CPUState *cs = CPU(cpu);
236 
237     address_space_stl_notdirty(&address_space_memory, info->smp_bootreg_addr,
238                                0, MEMTXATTRS_UNSPECIFIED, NULL);
239     cpu_set_pc(cs, info->smp_loader_start);
240 }
241 
242 static inline bool have_dtb(const struct arm_boot_info *info)
243 {
244     return info->dtb_filename || info->get_dtb;
245 }
246 
247 #define WRITE_WORD(p, value) do { \
248     address_space_stl_notdirty(&address_space_memory, p, value, \
249                                MEMTXATTRS_UNSPECIFIED, NULL);  \
250     p += 4;                       \
251 } while (0)
252 
253 static void set_kernel_args(const struct arm_boot_info *info)
254 {
255     int initrd_size = info->initrd_size;
256     hwaddr base = info->loader_start;
257     hwaddr p;
258 
259     p = base + KERNEL_ARGS_ADDR;
260     /* ATAG_CORE */
261     WRITE_WORD(p, 5);
262     WRITE_WORD(p, 0x54410001);
263     WRITE_WORD(p, 1);
264     WRITE_WORD(p, 0x1000);
265     WRITE_WORD(p, 0);
266     /* ATAG_MEM */
267     /* TODO: handle multiple chips on one ATAG list */
268     WRITE_WORD(p, 4);
269     WRITE_WORD(p, 0x54410002);
270     WRITE_WORD(p, info->ram_size);
271     WRITE_WORD(p, info->loader_start);
272     if (initrd_size) {
273         /* ATAG_INITRD2 */
274         WRITE_WORD(p, 4);
275         WRITE_WORD(p, 0x54420005);
276         WRITE_WORD(p, info->initrd_start);
277         WRITE_WORD(p, initrd_size);
278     }
279     if (info->kernel_cmdline && *info->kernel_cmdline) {
280         /* ATAG_CMDLINE */
281         int cmdline_size;
282 
283         cmdline_size = strlen(info->kernel_cmdline);
284         cpu_physical_memory_write(p + 8, info->kernel_cmdline,
285                                   cmdline_size + 1);
286         cmdline_size = (cmdline_size >> 2) + 1;
287         WRITE_WORD(p, cmdline_size + 2);
288         WRITE_WORD(p, 0x54410009);
289         p += cmdline_size * 4;
290     }
291     if (info->atag_board) {
292         /* ATAG_BOARD */
293         int atag_board_len;
294         uint8_t atag_board_buf[0x1000];
295 
296         atag_board_len = (info->atag_board(info, atag_board_buf) + 3) & ~3;
297         WRITE_WORD(p, (atag_board_len + 8) >> 2);
298         WRITE_WORD(p, 0x414f4d50);
299         cpu_physical_memory_write(p, atag_board_buf, atag_board_len);
300         p += atag_board_len;
301     }
302     /* ATAG_END */
303     WRITE_WORD(p, 0);
304     WRITE_WORD(p, 0);
305 }
306 
307 static void set_kernel_args_old(const struct arm_boot_info *info)
308 {
309     hwaddr p;
310     const char *s;
311     int initrd_size = info->initrd_size;
312     hwaddr base = info->loader_start;
313 
314     /* see linux/include/asm-arm/setup.h */
315     p = base + KERNEL_ARGS_ADDR;
316     /* page_size */
317     WRITE_WORD(p, 4096);
318     /* nr_pages */
319     WRITE_WORD(p, info->ram_size / 4096);
320     /* ramdisk_size */
321     WRITE_WORD(p, 0);
322 #define FLAG_READONLY	1
323 #define FLAG_RDLOAD	4
324 #define FLAG_RDPROMPT	8
325     /* flags */
326     WRITE_WORD(p, FLAG_READONLY | FLAG_RDLOAD | FLAG_RDPROMPT);
327     /* rootdev */
328     WRITE_WORD(p, (31 << 8) | 0);	/* /dev/mtdblock0 */
329     /* video_num_cols */
330     WRITE_WORD(p, 0);
331     /* video_num_rows */
332     WRITE_WORD(p, 0);
333     /* video_x */
334     WRITE_WORD(p, 0);
335     /* video_y */
336     WRITE_WORD(p, 0);
337     /* memc_control_reg */
338     WRITE_WORD(p, 0);
339     /* unsigned char sounddefault */
340     /* unsigned char adfsdrives */
341     /* unsigned char bytes_per_char_h */
342     /* unsigned char bytes_per_char_v */
343     WRITE_WORD(p, 0);
344     /* pages_in_bank[4] */
345     WRITE_WORD(p, 0);
346     WRITE_WORD(p, 0);
347     WRITE_WORD(p, 0);
348     WRITE_WORD(p, 0);
349     /* pages_in_vram */
350     WRITE_WORD(p, 0);
351     /* initrd_start */
352     if (initrd_size) {
353         WRITE_WORD(p, info->initrd_start);
354     } else {
355         WRITE_WORD(p, 0);
356     }
357     /* initrd_size */
358     WRITE_WORD(p, initrd_size);
359     /* rd_start */
360     WRITE_WORD(p, 0);
361     /* system_rev */
362     WRITE_WORD(p, 0);
363     /* system_serial_low */
364     WRITE_WORD(p, 0);
365     /* system_serial_high */
366     WRITE_WORD(p, 0);
367     /* mem_fclk_21285 */
368     WRITE_WORD(p, 0);
369     /* zero unused fields */
370     while (p < base + KERNEL_ARGS_ADDR + 256 + 1024) {
371         WRITE_WORD(p, 0);
372     }
373     s = info->kernel_cmdline;
374     if (s) {
375         cpu_physical_memory_write(p, s, strlen(s) + 1);
376     } else {
377         WRITE_WORD(p, 0);
378     }
379 }
380 
381 /**
382  * load_dtb() - load a device tree binary image into memory
383  * @addr:       the address to load the image at
384  * @binfo:      struct describing the boot environment
385  * @addr_limit: upper limit of the available memory area at @addr
386  *
387  * Load a device tree supplied by the machine or by the user  with the
388  * '-dtb' command line option, and put it at offset @addr in target
389  * memory.
390  *
391  * If @addr_limit contains a meaningful value (i.e., it is strictly greater
392  * than @addr), the device tree is only loaded if its size does not exceed
393  * the limit.
394  *
395  * Returns: the size of the device tree image on success,
396  *          0 if the image size exceeds the limit,
397  *          -1 on errors.
398  *
399  * Note: Must not be called unless have_dtb(binfo) is true.
400  */
401 static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo,
402                     hwaddr addr_limit)
403 {
404     void *fdt = NULL;
405     int size, rc;
406     uint32_t acells, scells;
407 
408     if (binfo->dtb_filename) {
409         char *filename;
410         filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, binfo->dtb_filename);
411         if (!filename) {
412             fprintf(stderr, "Couldn't open dtb file %s\n", binfo->dtb_filename);
413             goto fail;
414         }
415 
416         fdt = load_device_tree(filename, &size);
417         if (!fdt) {
418             fprintf(stderr, "Couldn't open dtb file %s\n", filename);
419             g_free(filename);
420             goto fail;
421         }
422         g_free(filename);
423     } else {
424         fdt = binfo->get_dtb(binfo, &size);
425         if (!fdt) {
426             fprintf(stderr, "Board was unable to create a dtb blob\n");
427             goto fail;
428         }
429     }
430 
431     if (addr_limit > addr && size > (addr_limit - addr)) {
432         /* Installing the device tree blob at addr would exceed addr_limit.
433          * Whether this constitutes failure is up to the caller to decide,
434          * so just return 0 as size, i.e., no error.
435          */
436         g_free(fdt);
437         return 0;
438     }
439 
440     acells = qemu_fdt_getprop_cell(fdt, "/", "#address-cells",
441                                    NULL, &error_fatal);
442     scells = qemu_fdt_getprop_cell(fdt, "/", "#size-cells",
443                                    NULL, &error_fatal);
444     if (acells == 0 || scells == 0) {
445         fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n");
446         goto fail;
447     }
448 
449     if (scells < 2 && binfo->ram_size >= (1ULL << 32)) {
450         /* This is user error so deserves a friendlier error message
451          * than the failure of setprop_sized_cells would provide
452          */
453         fprintf(stderr, "qemu: dtb file not compatible with "
454                 "RAM size > 4GB\n");
455         goto fail;
456     }
457 
458     rc = qemu_fdt_setprop_sized_cells(fdt, "/memory", "reg",
459                                       acells, binfo->loader_start,
460                                       scells, binfo->ram_size);
461     if (rc < 0) {
462         fprintf(stderr, "couldn't set /memory/reg\n");
463         goto fail;
464     }
465 
466     if (binfo->kernel_cmdline && *binfo->kernel_cmdline) {
467         rc = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs",
468                                      binfo->kernel_cmdline);
469         if (rc < 0) {
470             fprintf(stderr, "couldn't set /chosen/bootargs\n");
471             goto fail;
472         }
473     }
474 
475     if (binfo->initrd_size) {
476         rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-start",
477                                    binfo->initrd_start);
478         if (rc < 0) {
479             fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");
480             goto fail;
481         }
482 
483         rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-end",
484                                    binfo->initrd_start + binfo->initrd_size);
485         if (rc < 0) {
486             fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");
487             goto fail;
488         }
489     }
490 
491     if (binfo->modify_dtb) {
492         binfo->modify_dtb(binfo, fdt);
493     }
494 
495     qemu_fdt_dumpdtb(fdt, size);
496 
497     /* Put the DTB into the memory map as a ROM image: this will ensure
498      * the DTB is copied again upon reset, even if addr points into RAM.
499      */
500     rom_add_blob_fixed("dtb", fdt, size, addr);
501 
502     g_free(fdt);
503 
504     return size;
505 
506 fail:
507     g_free(fdt);
508     return -1;
509 }
510 
511 static void do_cpu_reset(void *opaque)
512 {
513     ARMCPU *cpu = opaque;
514     CPUState *cs = CPU(cpu);
515     CPUARMState *env = &cpu->env;
516     const struct arm_boot_info *info = env->boot_info;
517 
518     cpu_reset(cs);
519     if (info) {
520         if (!info->is_linux) {
521             /* Jump to the entry point.  */
522             uint64_t entry = info->entry;
523 
524             if (!env->aarch64) {
525                 env->thumb = info->entry & 1;
526                 entry &= 0xfffffffe;
527             }
528             cpu_set_pc(cs, entry);
529         } else {
530             /* If we are booting Linux then we need to check whether we are
531              * booting into secure or non-secure state and adjust the state
532              * accordingly.  Out of reset, ARM is defined to be in secure state
533              * (SCR.NS = 0), we change that here if non-secure boot has been
534              * requested.
535              */
536             if (arm_feature(env, ARM_FEATURE_EL3)) {
537                 /* AArch64 is defined to come out of reset into EL3 if enabled.
538                  * If we are booting Linux then we need to adjust our EL as
539                  * Linux expects us to be in EL2 or EL1.  AArch32 resets into
540                  * SVC, which Linux expects, so no privilege/exception level to
541                  * adjust.
542                  */
543                 if (env->aarch64) {
544                     env->cp15.scr_el3 |= SCR_RW;
545                     if (arm_feature(env, ARM_FEATURE_EL2)) {
546                         env->cp15.hcr_el2 |= HCR_RW;
547                         env->pstate = PSTATE_MODE_EL2h;
548                     } else {
549                         env->pstate = PSTATE_MODE_EL1h;
550                     }
551                 }
552 
553                 /* Set to non-secure if not a secure boot */
554                 if (!info->secure_boot &&
555                     (cs != first_cpu || !info->secure_board_setup)) {
556                     /* Linux expects non-secure state */
557                     env->cp15.scr_el3 |= SCR_NS;
558                 }
559             }
560 
561             if (cs == first_cpu) {
562                 cpu_set_pc(cs, info->loader_start);
563 
564                 if (!have_dtb(info)) {
565                     if (old_param) {
566                         set_kernel_args_old(info);
567                     } else {
568                         set_kernel_args(info);
569                     }
570                 }
571             } else {
572                 info->secondary_cpu_reset_hook(cpu, info);
573             }
574         }
575     }
576 }
577 
578 /**
579  * load_image_to_fw_cfg() - Load an image file into an fw_cfg entry identified
580  *                          by key.
581  * @fw_cfg:         The firmware config instance to store the data in.
582  * @size_key:       The firmware config key to store the size of the loaded
583  *                  data under, with fw_cfg_add_i32().
584  * @data_key:       The firmware config key to store the loaded data under,
585  *                  with fw_cfg_add_bytes().
586  * @image_name:     The name of the image file to load. If it is NULL, the
587  *                  function returns without doing anything.
588  * @try_decompress: Whether the image should be decompressed (gunzipped) before
589  *                  adding it to fw_cfg. If decompression fails, the image is
590  *                  loaded as-is.
591  *
592  * In case of failure, the function prints an error message to stderr and the
593  * process exits with status 1.
594  */
595 static void load_image_to_fw_cfg(FWCfgState *fw_cfg, uint16_t size_key,
596                                  uint16_t data_key, const char *image_name,
597                                  bool try_decompress)
598 {
599     size_t size = -1;
600     uint8_t *data;
601 
602     if (image_name == NULL) {
603         return;
604     }
605 
606     if (try_decompress) {
607         size = load_image_gzipped_buffer(image_name,
608                                          LOAD_IMAGE_MAX_GUNZIP_BYTES, &data);
609     }
610 
611     if (size == (size_t)-1) {
612         gchar *contents;
613         gsize length;
614 
615         if (!g_file_get_contents(image_name, &contents, &length, NULL)) {
616             fprintf(stderr, "failed to load \"%s\"\n", image_name);
617             exit(1);
618         }
619         size = length;
620         data = (uint8_t *)contents;
621     }
622 
623     fw_cfg_add_i32(fw_cfg, size_key, size);
624     fw_cfg_add_bytes(fw_cfg, data_key, data, size);
625 }
626 
627 static int do_arm_linux_init(Object *obj, void *opaque)
628 {
629     if (object_dynamic_cast(obj, TYPE_ARM_LINUX_BOOT_IF)) {
630         ARMLinuxBootIf *albif = ARM_LINUX_BOOT_IF(obj);
631         ARMLinuxBootIfClass *albifc = ARM_LINUX_BOOT_IF_GET_CLASS(obj);
632         struct arm_boot_info *info = opaque;
633 
634         if (albifc->arm_linux_init) {
635             albifc->arm_linux_init(albif, info->secure_boot);
636         }
637     }
638     return 0;
639 }
640 
641 static void arm_load_kernel_notify(Notifier *notifier, void *data)
642 {
643     CPUState *cs;
644     int kernel_size;
645     int initrd_size;
646     int is_linux = 0;
647     uint64_t elf_entry, elf_low_addr, elf_high_addr;
648     int elf_machine;
649     hwaddr entry, kernel_load_offset;
650     int big_endian;
651     static const ARMInsnFixup *primary_loader;
652     ArmLoadKernelNotifier *n = DO_UPCAST(ArmLoadKernelNotifier,
653                                          notifier, notifier);
654     ARMCPU *cpu = n->cpu;
655     struct arm_boot_info *info =
656         container_of(n, struct arm_boot_info, load_kernel_notifier);
657 
658     /* The board code is not supposed to set secure_board_setup unless
659      * running its code in secure mode is actually possible, and KVM
660      * doesn't support secure.
661      */
662     assert(!(info->secure_board_setup && kvm_enabled()));
663 
664     /* Load the kernel.  */
665     if (!info->kernel_filename || info->firmware_loaded) {
666 
667         if (have_dtb(info)) {
668             /* If we have a device tree blob, but no kernel to supply it to (or
669              * the kernel is supposed to be loaded by the bootloader), copy the
670              * DTB to the base of RAM for the bootloader to pick up.
671              */
672             if (load_dtb(info->loader_start, info, 0) < 0) {
673                 exit(1);
674             }
675         }
676 
677         if (info->kernel_filename) {
678             FWCfgState *fw_cfg;
679             bool try_decompressing_kernel;
680 
681             fw_cfg = fw_cfg_find();
682             try_decompressing_kernel = arm_feature(&cpu->env,
683                                                    ARM_FEATURE_AARCH64);
684 
685             /* Expose the kernel, the command line, and the initrd in fw_cfg.
686              * We don't process them here at all, it's all left to the
687              * firmware.
688              */
689             load_image_to_fw_cfg(fw_cfg,
690                                  FW_CFG_KERNEL_SIZE, FW_CFG_KERNEL_DATA,
691                                  info->kernel_filename,
692                                  try_decompressing_kernel);
693             load_image_to_fw_cfg(fw_cfg,
694                                  FW_CFG_INITRD_SIZE, FW_CFG_INITRD_DATA,
695                                  info->initrd_filename, false);
696 
697             if (info->kernel_cmdline) {
698                 fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
699                                strlen(info->kernel_cmdline) + 1);
700                 fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA,
701                                   info->kernel_cmdline);
702             }
703         }
704 
705         /* We will start from address 0 (typically a boot ROM image) in the
706          * same way as hardware.
707          */
708         return;
709     }
710 
711     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
712         primary_loader = bootloader_aarch64;
713         kernel_load_offset = KERNEL64_LOAD_ADDR;
714         elf_machine = EM_AARCH64;
715     } else {
716         primary_loader = bootloader;
717         if (!info->write_board_setup) {
718             primary_loader += BOOTLOADER_NO_BOARD_SETUP_OFFSET;
719         }
720         kernel_load_offset = KERNEL_LOAD_ADDR;
721         elf_machine = EM_ARM;
722     }
723 
724     info->dtb_filename = qemu_opt_get(qemu_get_machine_opts(), "dtb");
725 
726     if (!info->secondary_cpu_reset_hook) {
727         info->secondary_cpu_reset_hook = default_reset_secondary;
728     }
729     if (!info->write_secondary_boot) {
730         info->write_secondary_boot = default_write_secondary;
731     }
732 
733     if (info->nb_cpus == 0)
734         info->nb_cpus = 1;
735 
736 #ifdef TARGET_WORDS_BIGENDIAN
737     big_endian = 1;
738 #else
739     big_endian = 0;
740 #endif
741 
742     /* We want to put the initrd far enough into RAM that when the
743      * kernel is uncompressed it will not clobber the initrd. However
744      * on boards without much RAM we must ensure that we still leave
745      * enough room for a decent sized initrd, and on boards with large
746      * amounts of RAM we must avoid the initrd being so far up in RAM
747      * that it is outside lowmem and inaccessible to the kernel.
748      * So for boards with less  than 256MB of RAM we put the initrd
749      * halfway into RAM, and for boards with 256MB of RAM or more we put
750      * the initrd at 128MB.
751      */
752     info->initrd_start = info->loader_start +
753         MIN(info->ram_size / 2, 128 * 1024 * 1024);
754 
755     /* Assume that raw images are linux kernels, and ELF images are not.  */
756     kernel_size = load_elf(info->kernel_filename, NULL, NULL, &elf_entry,
757                            &elf_low_addr, &elf_high_addr, big_endian,
758                            elf_machine, 1);
759     if (kernel_size > 0 && have_dtb(info)) {
760         /* If there is still some room left at the base of RAM, try and put
761          * the DTB there like we do for images loaded with -bios or -pflash.
762          */
763         if (elf_low_addr > info->loader_start
764             || elf_high_addr < info->loader_start) {
765             /* Pass elf_low_addr as address limit to load_dtb if it may be
766              * pointing into RAM, otherwise pass '0' (no limit)
767              */
768             if (elf_low_addr < info->loader_start) {
769                 elf_low_addr = 0;
770             }
771             if (load_dtb(info->loader_start, info, elf_low_addr) < 0) {
772                 exit(1);
773             }
774         }
775     }
776     entry = elf_entry;
777     if (kernel_size < 0) {
778         kernel_size = load_uimage(info->kernel_filename, &entry, NULL,
779                                   &is_linux, NULL, NULL);
780     }
781     /* On aarch64, it's the bootloader's job to uncompress the kernel. */
782     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64) && kernel_size < 0) {
783         entry = info->loader_start + kernel_load_offset;
784         kernel_size = load_image_gzipped(info->kernel_filename, entry,
785                                          info->ram_size - kernel_load_offset);
786         is_linux = 1;
787     }
788     if (kernel_size < 0) {
789         entry = info->loader_start + kernel_load_offset;
790         kernel_size = load_image_targphys(info->kernel_filename, entry,
791                                           info->ram_size - kernel_load_offset);
792         is_linux = 1;
793     }
794     if (kernel_size < 0) {
795         fprintf(stderr, "qemu: could not load kernel '%s'\n",
796                 info->kernel_filename);
797         exit(1);
798     }
799     info->entry = entry;
800     if (is_linux) {
801         uint32_t fixupcontext[FIXUP_MAX];
802 
803         if (info->initrd_filename) {
804             initrd_size = load_ramdisk(info->initrd_filename,
805                                        info->initrd_start,
806                                        info->ram_size -
807                                        info->initrd_start);
808             if (initrd_size < 0) {
809                 initrd_size = load_image_targphys(info->initrd_filename,
810                                                   info->initrd_start,
811                                                   info->ram_size -
812                                                   info->initrd_start);
813             }
814             if (initrd_size < 0) {
815                 fprintf(stderr, "qemu: could not load initrd '%s'\n",
816                         info->initrd_filename);
817                 exit(1);
818             }
819         } else {
820             initrd_size = 0;
821         }
822         info->initrd_size = initrd_size;
823 
824         fixupcontext[FIXUP_BOARDID] = info->board_id;
825         fixupcontext[FIXUP_BOARD_SETUP] = info->board_setup_addr;
826 
827         /* for device tree boot, we pass the DTB directly in r2. Otherwise
828          * we point to the kernel args.
829          */
830         if (have_dtb(info)) {
831             hwaddr align;
832             hwaddr dtb_start;
833 
834             if (elf_machine == EM_AARCH64) {
835                 /*
836                  * Some AArch64 kernels on early bootup map the fdt region as
837                  *
838                  *   [ ALIGN_DOWN(fdt, 2MB) ... ALIGN_DOWN(fdt, 2MB) + 2MB ]
839                  *
840                  * Let's play safe and prealign it to 2MB to give us some space.
841                  */
842                 align = 2 * 1024 * 1024;
843             } else {
844                 /*
845                  * Some 32bit kernels will trash anything in the 4K page the
846                  * initrd ends in, so make sure the DTB isn't caught up in that.
847                  */
848                 align = 4096;
849             }
850 
851             /* Place the DTB after the initrd in memory with alignment. */
852             dtb_start = QEMU_ALIGN_UP(info->initrd_start + initrd_size, align);
853             if (load_dtb(dtb_start, info, 0) < 0) {
854                 exit(1);
855             }
856             fixupcontext[FIXUP_ARGPTR] = dtb_start;
857         } else {
858             fixupcontext[FIXUP_ARGPTR] = info->loader_start + KERNEL_ARGS_ADDR;
859             if (info->ram_size >= (1ULL << 32)) {
860                 fprintf(stderr, "qemu: RAM size must be less than 4GB to boot"
861                         " Linux kernel using ATAGS (try passing a device tree"
862                         " using -dtb)\n");
863                 exit(1);
864             }
865         }
866         fixupcontext[FIXUP_ENTRYPOINT] = entry;
867 
868         write_bootloader("bootloader", info->loader_start,
869                          primary_loader, fixupcontext);
870 
871         if (info->nb_cpus > 1) {
872             info->write_secondary_boot(cpu, info);
873         }
874         if (info->write_board_setup) {
875             info->write_board_setup(cpu, info);
876         }
877 
878         /* Notify devices which need to fake up firmware initialization
879          * that we're doing a direct kernel boot.
880          */
881         object_child_foreach_recursive(object_get_root(),
882                                        do_arm_linux_init, info);
883     }
884     info->is_linux = is_linux;
885 
886     for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) {
887         ARM_CPU(cs)->env.boot_info = info;
888     }
889 }
890 
891 void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info)
892 {
893     CPUState *cs;
894 
895     info->load_kernel_notifier.cpu = cpu;
896     info->load_kernel_notifier.notifier.notify = arm_load_kernel_notify;
897     qemu_add_machine_init_done_notifier(&info->load_kernel_notifier.notifier);
898 
899     /* CPU objects (unlike devices) are not automatically reset on system
900      * reset, so we must always register a handler to do so. If we're
901      * actually loading a kernel, the handler is also responsible for
902      * arranging that we start it correctly.
903      */
904     for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) {
905         qemu_register_reset(do_cpu_reset, ARM_CPU(cs));
906     }
907 }
908 
909 static const TypeInfo arm_linux_boot_if_info = {
910     .name = TYPE_ARM_LINUX_BOOT_IF,
911     .parent = TYPE_INTERFACE,
912     .class_size = sizeof(ARMLinuxBootIfClass),
913 };
914 
915 static void arm_linux_boot_register_types(void)
916 {
917     type_register_static(&arm_linux_boot_if_info);
918 }
919 
920 type_init(arm_linux_boot_register_types)
921