xref: /openbmc/qemu/hw/arm/boot.c (revision 2aef8c91)
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     scells = qemu_fdt_getprop_cell(fdt, "/", "#size-cells");
442     if (acells == 0 || scells == 0) {
443         fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n");
444         goto fail;
445     }
446 
447     if (scells < 2 && binfo->ram_size >= (1ULL << 32)) {
448         /* This is user error so deserves a friendlier error message
449          * than the failure of setprop_sized_cells would provide
450          */
451         fprintf(stderr, "qemu: dtb file not compatible with "
452                 "RAM size > 4GB\n");
453         goto fail;
454     }
455 
456     rc = qemu_fdt_setprop_sized_cells(fdt, "/memory", "reg",
457                                       acells, binfo->loader_start,
458                                       scells, binfo->ram_size);
459     if (rc < 0) {
460         fprintf(stderr, "couldn't set /memory/reg\n");
461         goto fail;
462     }
463 
464     if (binfo->kernel_cmdline && *binfo->kernel_cmdline) {
465         rc = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs",
466                                      binfo->kernel_cmdline);
467         if (rc < 0) {
468             fprintf(stderr, "couldn't set /chosen/bootargs\n");
469             goto fail;
470         }
471     }
472 
473     if (binfo->initrd_size) {
474         rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-start",
475                                    binfo->initrd_start);
476         if (rc < 0) {
477             fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");
478             goto fail;
479         }
480 
481         rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-end",
482                                    binfo->initrd_start + binfo->initrd_size);
483         if (rc < 0) {
484             fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");
485             goto fail;
486         }
487     }
488 
489     if (binfo->modify_dtb) {
490         binfo->modify_dtb(binfo, fdt);
491     }
492 
493     qemu_fdt_dumpdtb(fdt, size);
494 
495     /* Put the DTB into the memory map as a ROM image: this will ensure
496      * the DTB is copied again upon reset, even if addr points into RAM.
497      */
498     rom_add_blob_fixed("dtb", fdt, size, addr);
499 
500     g_free(fdt);
501 
502     return size;
503 
504 fail:
505     g_free(fdt);
506     return -1;
507 }
508 
509 static void do_cpu_reset(void *opaque)
510 {
511     ARMCPU *cpu = opaque;
512     CPUState *cs = CPU(cpu);
513     CPUARMState *env = &cpu->env;
514     const struct arm_boot_info *info = env->boot_info;
515 
516     cpu_reset(cs);
517     if (info) {
518         if (!info->is_linux) {
519             /* Jump to the entry point.  */
520             uint64_t entry = info->entry;
521 
522             if (!env->aarch64) {
523                 env->thumb = info->entry & 1;
524                 entry &= 0xfffffffe;
525             }
526             cpu_set_pc(cs, entry);
527         } else {
528             /* If we are booting Linux then we need to check whether we are
529              * booting into secure or non-secure state and adjust the state
530              * accordingly.  Out of reset, ARM is defined to be in secure state
531              * (SCR.NS = 0), we change that here if non-secure boot has been
532              * requested.
533              */
534             if (arm_feature(env, ARM_FEATURE_EL3)) {
535                 /* AArch64 is defined to come out of reset into EL3 if enabled.
536                  * If we are booting Linux then we need to adjust our EL as
537                  * Linux expects us to be in EL2 or EL1.  AArch32 resets into
538                  * SVC, which Linux expects, so no privilege/exception level to
539                  * adjust.
540                  */
541                 if (env->aarch64) {
542                     env->cp15.scr_el3 |= SCR_RW;
543                     if (arm_feature(env, ARM_FEATURE_EL2)) {
544                         env->cp15.hcr_el2 |= HCR_RW;
545                         env->pstate = PSTATE_MODE_EL2h;
546                     } else {
547                         env->pstate = PSTATE_MODE_EL1h;
548                     }
549                 }
550 
551                 /* Set to non-secure if not a secure boot */
552                 if (!info->secure_boot &&
553                     (cs != first_cpu || !info->secure_board_setup)) {
554                     /* Linux expects non-secure state */
555                     env->cp15.scr_el3 |= SCR_NS;
556                 }
557             }
558 
559             if (cs == first_cpu) {
560                 cpu_set_pc(cs, info->loader_start);
561 
562                 if (!have_dtb(info)) {
563                     if (old_param) {
564                         set_kernel_args_old(info);
565                     } else {
566                         set_kernel_args(info);
567                     }
568                 }
569             } else {
570                 info->secondary_cpu_reset_hook(cpu, info);
571             }
572         }
573     }
574 }
575 
576 /**
577  * load_image_to_fw_cfg() - Load an image file into an fw_cfg entry identified
578  *                          by key.
579  * @fw_cfg:         The firmware config instance to store the data in.
580  * @size_key:       The firmware config key to store the size of the loaded
581  *                  data under, with fw_cfg_add_i32().
582  * @data_key:       The firmware config key to store the loaded data under,
583  *                  with fw_cfg_add_bytes().
584  * @image_name:     The name of the image file to load. If it is NULL, the
585  *                  function returns without doing anything.
586  * @try_decompress: Whether the image should be decompressed (gunzipped) before
587  *                  adding it to fw_cfg. If decompression fails, the image is
588  *                  loaded as-is.
589  *
590  * In case of failure, the function prints an error message to stderr and the
591  * process exits with status 1.
592  */
593 static void load_image_to_fw_cfg(FWCfgState *fw_cfg, uint16_t size_key,
594                                  uint16_t data_key, const char *image_name,
595                                  bool try_decompress)
596 {
597     size_t size = -1;
598     uint8_t *data;
599 
600     if (image_name == NULL) {
601         return;
602     }
603 
604     if (try_decompress) {
605         size = load_image_gzipped_buffer(image_name,
606                                          LOAD_IMAGE_MAX_GUNZIP_BYTES, &data);
607     }
608 
609     if (size == (size_t)-1) {
610         gchar *contents;
611         gsize length;
612 
613         if (!g_file_get_contents(image_name, &contents, &length, NULL)) {
614             fprintf(stderr, "failed to load \"%s\"\n", image_name);
615             exit(1);
616         }
617         size = length;
618         data = (uint8_t *)contents;
619     }
620 
621     fw_cfg_add_i32(fw_cfg, size_key, size);
622     fw_cfg_add_bytes(fw_cfg, data_key, data, size);
623 }
624 
625 static int do_arm_linux_init(Object *obj, void *opaque)
626 {
627     if (object_dynamic_cast(obj, TYPE_ARM_LINUX_BOOT_IF)) {
628         ARMLinuxBootIf *albif = ARM_LINUX_BOOT_IF(obj);
629         ARMLinuxBootIfClass *albifc = ARM_LINUX_BOOT_IF_GET_CLASS(obj);
630         struct arm_boot_info *info = opaque;
631 
632         if (albifc->arm_linux_init) {
633             albifc->arm_linux_init(albif, info->secure_boot);
634         }
635     }
636     return 0;
637 }
638 
639 static void arm_load_kernel_notify(Notifier *notifier, void *data)
640 {
641     CPUState *cs;
642     int kernel_size;
643     int initrd_size;
644     int is_linux = 0;
645     uint64_t elf_entry, elf_low_addr, elf_high_addr;
646     int elf_machine;
647     hwaddr entry, kernel_load_offset;
648     int big_endian;
649     static const ARMInsnFixup *primary_loader;
650     ArmLoadKernelNotifier *n = DO_UPCAST(ArmLoadKernelNotifier,
651                                          notifier, notifier);
652     ARMCPU *cpu = n->cpu;
653     struct arm_boot_info *info =
654         container_of(n, struct arm_boot_info, load_kernel_notifier);
655 
656     /* The board code is not supposed to set secure_board_setup unless
657      * running its code in secure mode is actually possible, and KVM
658      * doesn't support secure.
659      */
660     assert(!(info->secure_board_setup && kvm_enabled()));
661 
662     /* Load the kernel.  */
663     if (!info->kernel_filename || info->firmware_loaded) {
664 
665         if (have_dtb(info)) {
666             /* If we have a device tree blob, but no kernel to supply it to (or
667              * the kernel is supposed to be loaded by the bootloader), copy the
668              * DTB to the base of RAM for the bootloader to pick up.
669              */
670             if (load_dtb(info->loader_start, info, 0) < 0) {
671                 exit(1);
672             }
673         }
674 
675         if (info->kernel_filename) {
676             FWCfgState *fw_cfg;
677             bool try_decompressing_kernel;
678 
679             fw_cfg = fw_cfg_find();
680             try_decompressing_kernel = arm_feature(&cpu->env,
681                                                    ARM_FEATURE_AARCH64);
682 
683             /* Expose the kernel, the command line, and the initrd in fw_cfg.
684              * We don't process them here at all, it's all left to the
685              * firmware.
686              */
687             load_image_to_fw_cfg(fw_cfg,
688                                  FW_CFG_KERNEL_SIZE, FW_CFG_KERNEL_DATA,
689                                  info->kernel_filename,
690                                  try_decompressing_kernel);
691             load_image_to_fw_cfg(fw_cfg,
692                                  FW_CFG_INITRD_SIZE, FW_CFG_INITRD_DATA,
693                                  info->initrd_filename, false);
694 
695             if (info->kernel_cmdline) {
696                 fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
697                                strlen(info->kernel_cmdline) + 1);
698                 fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA,
699                                   info->kernel_cmdline);
700             }
701         }
702 
703         /* We will start from address 0 (typically a boot ROM image) in the
704          * same way as hardware.
705          */
706         return;
707     }
708 
709     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
710         primary_loader = bootloader_aarch64;
711         kernel_load_offset = KERNEL64_LOAD_ADDR;
712         elf_machine = EM_AARCH64;
713     } else {
714         primary_loader = bootloader;
715         if (!info->write_board_setup) {
716             primary_loader += BOOTLOADER_NO_BOARD_SETUP_OFFSET;
717         }
718         kernel_load_offset = KERNEL_LOAD_ADDR;
719         elf_machine = EM_ARM;
720     }
721 
722     info->dtb_filename = qemu_opt_get(qemu_get_machine_opts(), "dtb");
723 
724     if (!info->secondary_cpu_reset_hook) {
725         info->secondary_cpu_reset_hook = default_reset_secondary;
726     }
727     if (!info->write_secondary_boot) {
728         info->write_secondary_boot = default_write_secondary;
729     }
730 
731     if (info->nb_cpus == 0)
732         info->nb_cpus = 1;
733 
734 #ifdef TARGET_WORDS_BIGENDIAN
735     big_endian = 1;
736 #else
737     big_endian = 0;
738 #endif
739 
740     /* We want to put the initrd far enough into RAM that when the
741      * kernel is uncompressed it will not clobber the initrd. However
742      * on boards without much RAM we must ensure that we still leave
743      * enough room for a decent sized initrd, and on boards with large
744      * amounts of RAM we must avoid the initrd being so far up in RAM
745      * that it is outside lowmem and inaccessible to the kernel.
746      * So for boards with less  than 256MB of RAM we put the initrd
747      * halfway into RAM, and for boards with 256MB of RAM or more we put
748      * the initrd at 128MB.
749      */
750     info->initrd_start = info->loader_start +
751         MIN(info->ram_size / 2, 128 * 1024 * 1024);
752 
753     /* Assume that raw images are linux kernels, and ELF images are not.  */
754     kernel_size = load_elf(info->kernel_filename, NULL, NULL, &elf_entry,
755                            &elf_low_addr, &elf_high_addr, big_endian,
756                            elf_machine, 1);
757     if (kernel_size > 0 && have_dtb(info)) {
758         /* If there is still some room left at the base of RAM, try and put
759          * the DTB there like we do for images loaded with -bios or -pflash.
760          */
761         if (elf_low_addr > info->loader_start
762             || elf_high_addr < info->loader_start) {
763             /* Pass elf_low_addr as address limit to load_dtb if it may be
764              * pointing into RAM, otherwise pass '0' (no limit)
765              */
766             if (elf_low_addr < info->loader_start) {
767                 elf_low_addr = 0;
768             }
769             if (load_dtb(info->loader_start, info, elf_low_addr) < 0) {
770                 exit(1);
771             }
772         }
773     }
774     entry = elf_entry;
775     if (kernel_size < 0) {
776         kernel_size = load_uimage(info->kernel_filename, &entry, NULL,
777                                   &is_linux, NULL, NULL);
778     }
779     /* On aarch64, it's the bootloader's job to uncompress the kernel. */
780     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64) && kernel_size < 0) {
781         entry = info->loader_start + kernel_load_offset;
782         kernel_size = load_image_gzipped(info->kernel_filename, entry,
783                                          info->ram_size - kernel_load_offset);
784         is_linux = 1;
785     }
786     if (kernel_size < 0) {
787         entry = info->loader_start + kernel_load_offset;
788         kernel_size = load_image_targphys(info->kernel_filename, entry,
789                                           info->ram_size - kernel_load_offset);
790         is_linux = 1;
791     }
792     if (kernel_size < 0) {
793         fprintf(stderr, "qemu: could not load kernel '%s'\n",
794                 info->kernel_filename);
795         exit(1);
796     }
797     info->entry = entry;
798     if (is_linux) {
799         uint32_t fixupcontext[FIXUP_MAX];
800 
801         if (info->initrd_filename) {
802             initrd_size = load_ramdisk(info->initrd_filename,
803                                        info->initrd_start,
804                                        info->ram_size -
805                                        info->initrd_start);
806             if (initrd_size < 0) {
807                 initrd_size = load_image_targphys(info->initrd_filename,
808                                                   info->initrd_start,
809                                                   info->ram_size -
810                                                   info->initrd_start);
811             }
812             if (initrd_size < 0) {
813                 fprintf(stderr, "qemu: could not load initrd '%s'\n",
814                         info->initrd_filename);
815                 exit(1);
816             }
817         } else {
818             initrd_size = 0;
819         }
820         info->initrd_size = initrd_size;
821 
822         fixupcontext[FIXUP_BOARDID] = info->board_id;
823         fixupcontext[FIXUP_BOARD_SETUP] = info->board_setup_addr;
824 
825         /* for device tree boot, we pass the DTB directly in r2. Otherwise
826          * we point to the kernel args.
827          */
828         if (have_dtb(info)) {
829             hwaddr align;
830             hwaddr dtb_start;
831 
832             if (elf_machine == EM_AARCH64) {
833                 /*
834                  * Some AArch64 kernels on early bootup map the fdt region as
835                  *
836                  *   [ ALIGN_DOWN(fdt, 2MB) ... ALIGN_DOWN(fdt, 2MB) + 2MB ]
837                  *
838                  * Let's play safe and prealign it to 2MB to give us some space.
839                  */
840                 align = 2 * 1024 * 1024;
841             } else {
842                 /*
843                  * Some 32bit kernels will trash anything in the 4K page the
844                  * initrd ends in, so make sure the DTB isn't caught up in that.
845                  */
846                 align = 4096;
847             }
848 
849             /* Place the DTB after the initrd in memory with alignment. */
850             dtb_start = QEMU_ALIGN_UP(info->initrd_start + initrd_size, align);
851             if (load_dtb(dtb_start, info, 0) < 0) {
852                 exit(1);
853             }
854             fixupcontext[FIXUP_ARGPTR] = dtb_start;
855         } else {
856             fixupcontext[FIXUP_ARGPTR] = info->loader_start + KERNEL_ARGS_ADDR;
857             if (info->ram_size >= (1ULL << 32)) {
858                 fprintf(stderr, "qemu: RAM size must be less than 4GB to boot"
859                         " Linux kernel using ATAGS (try passing a device tree"
860                         " using -dtb)\n");
861                 exit(1);
862             }
863         }
864         fixupcontext[FIXUP_ENTRYPOINT] = entry;
865 
866         write_bootloader("bootloader", info->loader_start,
867                          primary_loader, fixupcontext);
868 
869         if (info->nb_cpus > 1) {
870             info->write_secondary_boot(cpu, info);
871         }
872         if (info->write_board_setup) {
873             info->write_board_setup(cpu, info);
874         }
875 
876         /* Notify devices which need to fake up firmware initialization
877          * that we're doing a direct kernel boot.
878          */
879         object_child_foreach_recursive(object_get_root(),
880                                        do_arm_linux_init, info);
881     }
882     info->is_linux = is_linux;
883 
884     for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) {
885         ARM_CPU(cs)->env.boot_info = info;
886     }
887 }
888 
889 void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info)
890 {
891     CPUState *cs;
892 
893     info->load_kernel_notifier.cpu = cpu;
894     info->load_kernel_notifier.notifier.notify = arm_load_kernel_notify;
895     qemu_add_machine_init_done_notifier(&info->load_kernel_notifier.notifier);
896 
897     /* CPU objects (unlike devices) are not automatically reset on system
898      * reset, so we must always register a handler to do so. If we're
899      * actually loading a kernel, the handler is also responsible for
900      * arranging that we start it correctly.
901      */
902     for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) {
903         qemu_register_reset(do_cpu_reset, ARM_CPU(cs));
904     }
905 }
906 
907 static const TypeInfo arm_linux_boot_if_info = {
908     .name = TYPE_ARM_LINUX_BOOT_IF,
909     .parent = TYPE_INTERFACE,
910     .class_size = sizeof(ARMLinuxBootIfClass),
911 };
912 
913 static void arm_linux_boot_register_types(void)
914 {
915     type_register_static(&arm_linux_boot_if_info);
916 }
917 
918 type_init(arm_linux_boot_register_types)
919