Merge tag 'tpm-next-27102023' of https://source.denx.de/u-boot/custodians/u-boot-tpm
[pandora-u-boot.git] / boot / bootm.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2000-2009
4  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5  */
6
7 #ifndef USE_HOSTCC
8 #include <common.h>
9 #include <bootstage.h>
10 #include <cli.h>
11 #include <command.h>
12 #include <cpu_func.h>
13 #include <env.h>
14 #include <errno.h>
15 #include <fdt_support.h>
16 #include <irq_func.h>
17 #include <lmb.h>
18 #include <log.h>
19 #include <malloc.h>
20 #include <mapmem.h>
21 #include <net.h>
22 #include <asm/cache.h>
23 #include <asm/global_data.h>
24 #include <asm/io.h>
25 #include <linux/sizes.h>
26 #include <tpm-v2.h>
27 #if defined(CONFIG_CMD_USB)
28 #include <usb.h>
29 #endif
30 #else
31 #include "mkimage.h"
32 #endif
33
34 #include <bootm.h>
35 #include <image.h>
36
37 #define MAX_CMDLINE_SIZE        SZ_4K
38
39 #define IH_INITRD_ARCH IH_ARCH_DEFAULT
40
41 #ifndef USE_HOSTCC
42
43 DECLARE_GLOBAL_DATA_PTR;
44
45 struct bootm_headers images;            /* pointers to os/initrd/fdt images */
46
47 static const void *boot_get_kernel(struct cmd_tbl *cmdtp, int flag, int argc,
48                                    char *const argv[], struct bootm_headers *images,
49                                    ulong *os_data, ulong *os_len);
50
51 __weak void board_quiesce_devices(void)
52 {
53 }
54
55 #ifdef CONFIG_LMB
56 static void boot_start_lmb(struct bootm_headers *images)
57 {
58         ulong           mem_start;
59         phys_size_t     mem_size;
60
61         mem_start = env_get_bootm_low();
62         mem_size = env_get_bootm_size();
63
64         lmb_init_and_reserve_range(&images->lmb, (phys_addr_t)mem_start,
65                                    mem_size, NULL);
66 }
67 #else
68 #define lmb_reserve(lmb, base, size)
69 static inline void boot_start_lmb(struct bootm_headers *images) { }
70 #endif
71
72 static int bootm_start(struct cmd_tbl *cmdtp, int flag, int argc,
73                        char *const argv[])
74 {
75         memset((void *)&images, 0, sizeof(images));
76         images.verify = env_get_yesno("verify");
77
78         boot_start_lmb(&images);
79
80         bootstage_mark_name(BOOTSTAGE_ID_BOOTM_START, "bootm_start");
81         images.state = BOOTM_STATE_START;
82
83         return 0;
84 }
85
86 static ulong bootm_data_addr(int argc, char *const argv[])
87 {
88         ulong addr;
89
90         if (argc > 0)
91                 addr = simple_strtoul(argv[0], NULL, 16);
92         else
93                 addr = image_load_addr;
94
95         return addr;
96 }
97
98 static int bootm_pre_load(struct cmd_tbl *cmdtp, int flag, int argc,
99                           char *const argv[])
100 {
101         ulong data_addr = bootm_data_addr(argc, argv);
102         int ret = 0;
103
104         if (IS_ENABLED(CONFIG_CMD_BOOTM_PRE_LOAD))
105                 ret = image_pre_load(data_addr);
106
107         if (ret)
108                 ret = CMD_RET_FAILURE;
109
110         return ret;
111 }
112
113 static int bootm_find_os(struct cmd_tbl *cmdtp, int flag, int argc,
114                          char *const argv[])
115 {
116         const void *os_hdr;
117 #ifdef CONFIG_ANDROID_BOOT_IMAGE
118         const void *vendor_boot_img;
119         const void *boot_img;
120 #endif
121         bool ep_found = false;
122         int ret;
123
124         /* get kernel image header, start address and length */
125         os_hdr = boot_get_kernel(cmdtp, flag, argc, argv,
126                         &images, &images.os.image_start, &images.os.image_len);
127         if (images.os.image_len == 0) {
128                 puts("ERROR: can't get kernel image!\n");
129                 return 1;
130         }
131
132         /* get image parameters */
133         switch (genimg_get_format(os_hdr)) {
134 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
135         case IMAGE_FORMAT_LEGACY:
136                 images.os.type = image_get_type(os_hdr);
137                 images.os.comp = image_get_comp(os_hdr);
138                 images.os.os = image_get_os(os_hdr);
139
140                 images.os.end = image_get_image_end(os_hdr);
141                 images.os.load = image_get_load(os_hdr);
142                 images.os.arch = image_get_arch(os_hdr);
143                 break;
144 #endif
145 #if CONFIG_IS_ENABLED(FIT)
146         case IMAGE_FORMAT_FIT:
147                 if (fit_image_get_type(images.fit_hdr_os,
148                                        images.fit_noffset_os,
149                                        &images.os.type)) {
150                         puts("Can't get image type!\n");
151                         bootstage_error(BOOTSTAGE_ID_FIT_TYPE);
152                         return 1;
153                 }
154
155                 if (fit_image_get_comp(images.fit_hdr_os,
156                                        images.fit_noffset_os,
157                                        &images.os.comp)) {
158                         puts("Can't get image compression!\n");
159                         bootstage_error(BOOTSTAGE_ID_FIT_COMPRESSION);
160                         return 1;
161                 }
162
163                 if (fit_image_get_os(images.fit_hdr_os, images.fit_noffset_os,
164                                      &images.os.os)) {
165                         puts("Can't get image OS!\n");
166                         bootstage_error(BOOTSTAGE_ID_FIT_OS);
167                         return 1;
168                 }
169
170                 if (fit_image_get_arch(images.fit_hdr_os,
171                                        images.fit_noffset_os,
172                                        &images.os.arch)) {
173                         puts("Can't get image ARCH!\n");
174                         return 1;
175                 }
176
177                 images.os.end = fit_get_end(images.fit_hdr_os);
178
179                 if (fit_image_get_load(images.fit_hdr_os, images.fit_noffset_os,
180                                        &images.os.load)) {
181                         puts("Can't get image load address!\n");
182                         bootstage_error(BOOTSTAGE_ID_FIT_LOADADDR);
183                         return 1;
184                 }
185                 break;
186 #endif
187 #ifdef CONFIG_ANDROID_BOOT_IMAGE
188         case IMAGE_FORMAT_ANDROID:
189                 boot_img = os_hdr;
190                 vendor_boot_img = NULL;
191                 if (IS_ENABLED(CONFIG_CMD_ABOOTIMG)) {
192                         boot_img = map_sysmem(get_abootimg_addr(), 0);
193                         vendor_boot_img = map_sysmem(get_avendor_bootimg_addr(), 0);
194                 }
195                 images.os.type = IH_TYPE_KERNEL;
196                 images.os.comp = android_image_get_kcomp(boot_img, vendor_boot_img);
197                 images.os.os = IH_OS_LINUX;
198                 images.os.end = android_image_get_end(boot_img, vendor_boot_img);
199                 images.os.load = android_image_get_kload(boot_img, vendor_boot_img);
200                 images.ep = images.os.load;
201                 ep_found = true;
202                 if (IS_ENABLED(CONFIG_CMD_ABOOTIMG)) {
203                         unmap_sysmem(vendor_boot_img);
204                         unmap_sysmem(boot_img);
205                 }
206                 break;
207 #endif
208         default:
209                 puts("ERROR: unknown image format type!\n");
210                 return 1;
211         }
212
213         /* If we have a valid setup.bin, we will use that for entry (x86) */
214         if (images.os.arch == IH_ARCH_I386 ||
215             images.os.arch == IH_ARCH_X86_64) {
216                 ulong len;
217
218                 ret = boot_get_setup(&images, IH_ARCH_I386, &images.ep, &len);
219                 if (ret < 0 && ret != -ENOENT) {
220                         puts("Could not find a valid setup.bin for x86\n");
221                         return 1;
222                 }
223                 /* Kernel entry point is the setup.bin */
224         } else if (images.legacy_hdr_valid) {
225                 images.ep = image_get_ep(&images.legacy_hdr_os_copy);
226 #if CONFIG_IS_ENABLED(FIT)
227         } else if (images.fit_uname_os) {
228                 int ret;
229
230                 ret = fit_image_get_entry(images.fit_hdr_os,
231                                           images.fit_noffset_os, &images.ep);
232                 if (ret) {
233                         puts("Can't get entry point property!\n");
234                         return 1;
235                 }
236 #endif
237         } else if (!ep_found) {
238                 puts("Could not find kernel entry point!\n");
239                 return 1;
240         }
241
242         if (images.os.type == IH_TYPE_KERNEL_NOLOAD) {
243                 if (IS_ENABLED(CONFIG_CMD_BOOTI) &&
244                     images.os.arch == IH_ARCH_ARM64 &&
245                     images.os.os == IH_OS_LINUX) {
246                         ulong image_addr;
247                         ulong image_size;
248
249                         ret = booti_setup(images.os.image_start, &image_addr,
250                                           &image_size, true);
251                         if (ret != 0)
252                                 return 1;
253
254                         images.os.type = IH_TYPE_KERNEL;
255                         images.os.load = image_addr;
256                         images.ep = image_addr;
257                 } else {
258                         images.os.load = images.os.image_start;
259                         images.ep += images.os.image_start;
260                 }
261         }
262
263         images.os.start = map_to_sysmem(os_hdr);
264
265         return 0;
266 }
267
268 /**
269  * bootm_find_images - wrapper to find and locate various images
270  * @flag: Ignored Argument
271  * @argc: command argument count
272  * @argv: command argument list
273  * @start: OS image start address
274  * @size: OS image size
275  *
276  * boot_find_images() will attempt to load an available ramdisk,
277  * flattened device tree, as well as specifically marked
278  * "loadable" images (loadables are FIT only)
279  *
280  * Note: bootm_find_images will skip an image if it is not found
281  *
282  * @return:
283  *     0, if all existing images were loaded correctly
284  *     1, if an image is found but corrupted, or invalid
285  */
286 int bootm_find_images(int flag, int argc, char *const argv[], ulong start,
287                       ulong size)
288 {
289         int ret;
290
291         /* find ramdisk */
292         ret = boot_get_ramdisk(argc, argv, &images, IH_INITRD_ARCH,
293                                &images.rd_start, &images.rd_end);
294         if (ret) {
295                 puts("Ramdisk image is corrupt or invalid\n");
296                 return 1;
297         }
298
299         /* check if ramdisk overlaps OS image */
300         if (images.rd_start && (((ulong)images.rd_start >= start &&
301                                  (ulong)images.rd_start < start + size) ||
302                                 ((ulong)images.rd_end > start &&
303                                  (ulong)images.rd_end <= start + size) ||
304                                 ((ulong)images.rd_start < start &&
305                                  (ulong)images.rd_end >= start + size))) {
306                 printf("ERROR: RD image overlaps OS image (OS=0x%lx..0x%lx)\n",
307                        start, start + size);
308                 return 1;
309         }
310
311 #if CONFIG_IS_ENABLED(OF_LIBFDT)
312         /* find flattened device tree */
313         ret = boot_get_fdt(flag, argc, argv, IH_ARCH_DEFAULT, &images,
314                            &images.ft_addr, &images.ft_len);
315         if (ret) {
316                 puts("Could not find a valid device tree\n");
317                 return 1;
318         }
319
320         /* check if FDT overlaps OS image */
321         if (images.ft_addr &&
322             (((ulong)images.ft_addr >= start &&
323               (ulong)images.ft_addr < start + size) ||
324              ((ulong)images.ft_addr + images.ft_len >= start &&
325               (ulong)images.ft_addr + images.ft_len < start + size))) {
326                 printf("ERROR: FDT image overlaps OS image (OS=0x%lx..0x%lx)\n",
327                        start, start + size);
328                 return 1;
329         }
330
331         if (IS_ENABLED(CONFIG_CMD_FDT))
332                 set_working_fdt_addr(map_to_sysmem(images.ft_addr));
333 #endif
334
335 #if CONFIG_IS_ENABLED(FIT)
336         if (IS_ENABLED(CONFIG_FPGA)) {
337                 /* find bitstreams */
338                 ret = boot_get_fpga(argc, argv, &images, IH_ARCH_DEFAULT,
339                                     NULL, NULL);
340                 if (ret) {
341                         printf("FPGA image is corrupted or invalid\n");
342                         return 1;
343                 }
344         }
345
346         /* find all of the loadables */
347         ret = boot_get_loadable(argc, argv, &images, IH_ARCH_DEFAULT,
348                                NULL, NULL);
349         if (ret) {
350                 printf("Loadable(s) is corrupt or invalid\n");
351                 return 1;
352         }
353 #endif
354
355         return 0;
356 }
357
358 static int bootm_find_other(struct cmd_tbl *cmdtp, int flag, int argc,
359                             char *const argv[])
360 {
361         if (((images.os.type == IH_TYPE_KERNEL) ||
362              (images.os.type == IH_TYPE_KERNEL_NOLOAD) ||
363              (images.os.type == IH_TYPE_MULTI)) &&
364             (images.os.os == IH_OS_LINUX ||
365                  images.os.os == IH_OS_VXWORKS))
366                 return bootm_find_images(flag, argc, argv, 0, 0);
367
368         return 0;
369 }
370 #endif /* USE_HOSTC */
371
372 #if !defined(USE_HOSTCC) || defined(CONFIG_FIT_SIGNATURE)
373 /**
374  * handle_decomp_error() - display a decompression error
375  *
376  * This function tries to produce a useful message. In the case where the
377  * uncompressed size is the same as the available space, we can assume that
378  * the image is too large for the buffer.
379  *
380  * @comp_type:          Compression type being used (IH_COMP_...)
381  * @uncomp_size:        Number of bytes uncompressed
382  * @buf_size:           Number of bytes the decompresion buffer was
383  * @ret:                errno error code received from compression library
384  * Return: Appropriate BOOTM_ERR_ error code
385  */
386 static int handle_decomp_error(int comp_type, size_t uncomp_size,
387                                size_t buf_size, int ret)
388 {
389         const char *name = genimg_get_comp_name(comp_type);
390
391         /* ENOSYS means unimplemented compression type, don't reset. */
392         if (ret == -ENOSYS)
393                 return BOOTM_ERR_UNIMPLEMENTED;
394
395         if (uncomp_size >= buf_size)
396                 printf("Image too large: increase CONFIG_SYS_BOOTM_LEN\n");
397         else
398                 printf("%s: uncompress error %d\n", name, ret);
399
400         /*
401          * The decompression routines are now safe, so will not write beyond
402          * their bounds. Probably it is not necessary to reset, but maintain
403          * the current behaviour for now.
404          */
405         printf("Must RESET board to recover\n");
406 #ifndef USE_HOSTCC
407         bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE);
408 #endif
409
410         return BOOTM_ERR_RESET;
411 }
412 #endif
413
414 #ifndef USE_HOSTCC
415 static int bootm_load_os(struct bootm_headers *images, int boot_progress)
416 {
417         struct image_info os = images->os;
418         ulong load = os.load;
419         ulong load_end;
420         ulong blob_start = os.start;
421         ulong blob_end = os.end;
422         ulong image_start = os.image_start;
423         ulong image_len = os.image_len;
424         ulong flush_start = ALIGN_DOWN(load, ARCH_DMA_MINALIGN);
425         bool no_overlap;
426         void *load_buf, *image_buf;
427         int err;
428
429         load_buf = map_sysmem(load, 0);
430         image_buf = map_sysmem(os.image_start, image_len);
431         err = image_decomp(os.comp, load, os.image_start, os.type,
432                            load_buf, image_buf, image_len,
433                            CONFIG_SYS_BOOTM_LEN, &load_end);
434         if (err) {
435                 err = handle_decomp_error(os.comp, load_end - load,
436                                           CONFIG_SYS_BOOTM_LEN, err);
437                 bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE);
438                 return err;
439         }
440         /* We need the decompressed image size in the next steps */
441         images->os.image_len = load_end - load;
442
443         flush_cache(flush_start, ALIGN(load_end, ARCH_DMA_MINALIGN) - flush_start);
444
445         debug("   kernel loaded at 0x%08lx, end = 0x%08lx\n", load, load_end);
446         bootstage_mark(BOOTSTAGE_ID_KERNEL_LOADED);
447
448         no_overlap = (os.comp == IH_COMP_NONE && load == image_start);
449
450         if (!no_overlap && load < blob_end && load_end > blob_start) {
451                 debug("images.os.start = 0x%lX, images.os.end = 0x%lx\n",
452                       blob_start, blob_end);
453                 debug("images.os.load = 0x%lx, load_end = 0x%lx\n", load,
454                       load_end);
455
456                 /* Check what type of image this is. */
457                 if (images->legacy_hdr_valid) {
458                         if (image_get_type(&images->legacy_hdr_os_copy)
459                                         == IH_TYPE_MULTI)
460                                 puts("WARNING: legacy format multi component image overwritten\n");
461                         return BOOTM_ERR_OVERLAP;
462                 } else {
463                         puts("ERROR: new format image overwritten - must RESET the board to recover\n");
464                         bootstage_error(BOOTSTAGE_ID_OVERWRITTEN);
465                         return BOOTM_ERR_RESET;
466                 }
467         }
468
469         lmb_reserve(&images->lmb, images->os.load, (load_end -
470                                                     images->os.load));
471         return 0;
472 }
473
474 /**
475  * bootm_disable_interrupts() - Disable interrupts in preparation for load/boot
476  *
477  * Return: interrupt flag (0 if interrupts were disabled, non-zero if they were
478  *      enabled)
479  */
480 ulong bootm_disable_interrupts(void)
481 {
482         ulong iflag;
483
484         /*
485          * We have reached the point of no return: we are going to
486          * overwrite all exception vector code, so we cannot easily
487          * recover from any failures any more...
488          */
489         iflag = disable_interrupts();
490 #ifdef CONFIG_NETCONSOLE
491         /* Stop the ethernet stack if NetConsole could have left it up */
492         eth_halt();
493 #endif
494
495 #if defined(CONFIG_CMD_USB)
496         /*
497          * turn off USB to prevent the host controller from writing to the
498          * SDRAM while Linux is booting. This could happen (at least for OHCI
499          * controller), because the HCCA (Host Controller Communication Area)
500          * lies within the SDRAM and the host controller writes continously to
501          * this area (as busmaster!). The HccaFrameNumber is for example
502          * updated every 1 ms within the HCCA structure in SDRAM! For more
503          * details see the OpenHCI specification.
504          */
505         usb_stop();
506 #endif
507         return iflag;
508 }
509
510 #define CONSOLE_ARG             "console="
511 #define NULL_CONSOLE            (CONSOLE_ARG "ttynull")
512 #define CONSOLE_ARG_SIZE        sizeof(NULL_CONSOLE)
513
514 /**
515  * fixup_silent_linux() - Handle silencing the linux boot if required
516  *
517  * This uses the silent_linux envvar to control whether to add/set a "console="
518  * parameter to the command line
519  *
520  * @buf: Buffer containing the string to process
521  * @maxlen: Maximum length of buffer
522  * Return: 0 if OK, -ENOSPC if @maxlen is too small
523  */
524 static int fixup_silent_linux(char *buf, int maxlen)
525 {
526         int want_silent;
527         char *cmdline;
528         int size;
529
530         /*
531          * Move the input string to the end of buffer. The output string will be
532          * built up at the start.
533          */
534         size = strlen(buf) + 1;
535         if (size * 2 > maxlen)
536                 return -ENOSPC;
537         cmdline = buf + maxlen - size;
538         memmove(cmdline, buf, size);
539         /*
540          * Only fix cmdline when requested. The environment variable can be:
541          *
542          *      no - we never fixup
543          *      yes - we always fixup
544          *      unset - we rely on the console silent flag
545          */
546         want_silent = env_get_yesno("silent_linux");
547         if (want_silent == 0)
548                 return 0;
549         else if (want_silent == -1 && !(gd->flags & GD_FLG_SILENT))
550                 return 0;
551
552         debug("before silent fix-up: %s\n", cmdline);
553         if (*cmdline) {
554                 char *start = strstr(cmdline, CONSOLE_ARG);
555
556                 /* Check space for maximum possible new command line */
557                 if (size + CONSOLE_ARG_SIZE > maxlen)
558                         return -ENOSPC;
559
560                 if (start) {
561                         char *end = strchr(start, ' ');
562                         int start_bytes;
563
564                         start_bytes = start - cmdline;
565                         strncpy(buf, cmdline, start_bytes);
566                         strncpy(buf + start_bytes, NULL_CONSOLE, CONSOLE_ARG_SIZE);
567                         if (end)
568                                 strcpy(buf + start_bytes + CONSOLE_ARG_SIZE - 1, end);
569                         else
570                                 buf[start_bytes + CONSOLE_ARG_SIZE] = '\0';
571                 } else {
572                         sprintf(buf, "%s %s", cmdline, NULL_CONSOLE);
573                 }
574                 if (buf + strlen(buf) >= cmdline)
575                         return -ENOSPC;
576         } else {
577                 if (maxlen < CONSOLE_ARG_SIZE)
578                         return -ENOSPC;
579                 strcpy(buf, NULL_CONSOLE);
580         }
581         debug("after silent fix-up: %s\n", buf);
582
583         return 0;
584 }
585
586 /**
587  * process_subst() - Handle substitution of ${...} fields in the environment
588  *
589  * Handle variable substitution in the provided buffer
590  *
591  * @buf: Buffer containing the string to process
592  * @maxlen: Maximum length of buffer
593  * Return: 0 if OK, -ENOSPC if @maxlen is too small
594  */
595 static int process_subst(char *buf, int maxlen)
596 {
597         char *cmdline;
598         int size;
599         int ret;
600
601         /* Move to end of buffer */
602         size = strlen(buf) + 1;
603         cmdline = buf + maxlen - size;
604         if (buf + size > cmdline)
605                 return -ENOSPC;
606         memmove(cmdline, buf, size);
607
608         ret = cli_simple_process_macros(cmdline, buf, cmdline - buf);
609
610         return ret;
611 }
612
613 int bootm_process_cmdline(char *buf, int maxlen, int flags)
614 {
615         int ret;
616
617         /* Check config first to enable compiler to eliminate code */
618         if (IS_ENABLED(CONFIG_SILENT_CONSOLE) &&
619             !IS_ENABLED(CONFIG_SILENT_U_BOOT_ONLY) &&
620             (flags & BOOTM_CL_SILENT)) {
621                 ret = fixup_silent_linux(buf, maxlen);
622                 if (ret)
623                         return log_msg_ret("silent", ret);
624         }
625         if (IS_ENABLED(CONFIG_BOOTARGS_SUBST) && IS_ENABLED(CONFIG_CMDLINE) &&
626             (flags & BOOTM_CL_SUBST)) {
627                 ret = process_subst(buf, maxlen);
628                 if (ret)
629                         return log_msg_ret("subst", ret);
630         }
631
632         return 0;
633 }
634
635 int bootm_process_cmdline_env(int flags)
636 {
637         const int maxlen = MAX_CMDLINE_SIZE;
638         bool do_silent;
639         const char *env;
640         char *buf;
641         int ret;
642
643         /* First check if any action is needed */
644         do_silent = IS_ENABLED(CONFIG_SILENT_CONSOLE) &&
645             !IS_ENABLED(CONFIG_SILENT_U_BOOT_ONLY) && (flags & BOOTM_CL_SILENT);
646         if (!do_silent && !IS_ENABLED(CONFIG_BOOTARGS_SUBST))
647                 return 0;
648
649         env = env_get("bootargs");
650         if (env && strlen(env) >= maxlen)
651                 return -E2BIG;
652         buf = malloc(maxlen);
653         if (!buf)
654                 return -ENOMEM;
655         if (env)
656                 strcpy(buf, env);
657         else
658                 *buf = '\0';
659         ret = bootm_process_cmdline(buf, maxlen, flags);
660         if (!ret) {
661                 ret = env_set("bootargs", buf);
662
663                 /*
664                  * If buf is "" and bootargs does not exist, this will produce
665                  * an error trying to delete bootargs. Ignore it
666                  */
667                 if (ret == -ENOENT)
668                         ret = 0;
669         }
670         free(buf);
671         if (ret)
672                 return log_msg_ret("env", ret);
673
674         return 0;
675 }
676
677 int bootm_measure(struct bootm_headers *images)
678 {
679         int ret = 0;
680
681         /* Skip measurement if EFI is going to do it */
682         if (images->os.os == IH_OS_EFI &&
683             IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL) &&
684             IS_ENABLED(CONFIG_BOOTM_EFI))
685                 return ret;
686
687         if (IS_ENABLED(CONFIG_MEASURED_BOOT)) {
688                 struct tcg2_event_log elog;
689                 struct udevice *dev;
690                 void *initrd_buf;
691                 void *image_buf;
692                 const char *s;
693                 u32 rd_len;
694                 bool ign;
695
696                 elog.log_size = 0;
697                 ign = IS_ENABLED(CONFIG_MEASURE_IGNORE_LOG);
698                 ret = tcg2_measurement_init(&dev, &elog, ign);
699                 if (ret)
700                         return ret;
701
702                 image_buf = map_sysmem(images->os.image_start,
703                                        images->os.image_len);
704                 ret = tcg2_measure_data(dev, &elog, 8, images->os.image_len,
705                                         image_buf, EV_COMPACT_HASH,
706                                         strlen("linux") + 1, (u8 *)"linux");
707                 if (ret)
708                         goto unmap_image;
709
710                 rd_len = images->rd_end - images->rd_start;
711                 initrd_buf = map_sysmem(images->rd_start, rd_len);
712                 ret = tcg2_measure_data(dev, &elog, 9, rd_len, initrd_buf,
713                                         EV_COMPACT_HASH, strlen("initrd") + 1,
714                                         (u8 *)"initrd");
715                 if (ret)
716                         goto unmap_initrd;
717
718                 if (IS_ENABLED(CONFIG_MEASURE_DEVICETREE)) {
719                         ret = tcg2_measure_data(dev, &elog, 0, images->ft_len,
720                                                 (u8 *)images->ft_addr,
721                                                 EV_TABLE_OF_DEVICES,
722                                                 strlen("dts") + 1,
723                                                 (u8 *)"dts");
724                         if (ret)
725                                 goto unmap_initrd;
726                 }
727
728                 s = env_get("bootargs");
729                 if (!s)
730                         s = "";
731                 ret = tcg2_measure_data(dev, &elog, 1, strlen(s) + 1, (u8 *)s,
732                                         EV_PLATFORM_CONFIG_FLAGS,
733                                         strlen(s) + 1, (u8 *)s);
734
735 unmap_initrd:
736                 unmap_sysmem(initrd_buf);
737
738 unmap_image:
739                 unmap_sysmem(image_buf);
740                 tcg2_measurement_term(dev, &elog, ret != 0);
741         }
742
743         return ret;
744 }
745
746 /**
747  * Execute selected states of the bootm command.
748  *
749  * Note the arguments to this state must be the first argument, Any 'bootm'
750  * or sub-command arguments must have already been taken.
751  *
752  * Note that if states contains more than one flag it MUST contain
753  * BOOTM_STATE_START, since this handles and consumes the command line args.
754  *
755  * Also note that aside from boot_os_fn functions and bootm_load_os no other
756  * functions we store the return value of in 'ret' may use a negative return
757  * value, without special handling.
758  *
759  * @param cmdtp         Pointer to bootm command table entry
760  * @param flag          Command flags (CMD_FLAG_...)
761  * @param argc          Number of subcommand arguments (0 = no arguments)
762  * @param argv          Arguments
763  * @param states        Mask containing states to run (BOOTM_STATE_...)
764  * @param images        Image header information
765  * @param boot_progress 1 to show boot progress, 0 to not do this
766  * Return: 0 if ok, something else on error. Some errors will cause this
767  *      function to perform a reboot! If states contains BOOTM_STATE_OS_GO
768  *      then the intent is to boot an OS, so this function will not return
769  *      unless the image type is standalone.
770  */
771 int do_bootm_states(struct cmd_tbl *cmdtp, int flag, int argc,
772                     char *const argv[], int states, struct bootm_headers *images,
773                     int boot_progress)
774 {
775         boot_os_fn *boot_fn;
776         ulong iflag = 0;
777         int ret = 0, need_boot_fn;
778
779         images->state |= states;
780
781         /*
782          * Work through the states and see how far we get. We stop on
783          * any error.
784          */
785         if (states & BOOTM_STATE_START)
786                 ret = bootm_start(cmdtp, flag, argc, argv);
787
788         if (!ret && (states & BOOTM_STATE_PRE_LOAD))
789                 ret = bootm_pre_load(cmdtp, flag, argc, argv);
790
791         if (!ret && (states & BOOTM_STATE_FINDOS))
792                 ret = bootm_find_os(cmdtp, flag, argc, argv);
793
794         if (!ret && (states & BOOTM_STATE_FINDOTHER))
795                 ret = bootm_find_other(cmdtp, flag, argc, argv);
796
797         if (IS_ENABLED(CONFIG_MEASURED_BOOT) && !ret &&
798             (states & BOOTM_STATE_MEASURE))
799                 bootm_measure(images);
800
801         /* Load the OS */
802         if (!ret && (states & BOOTM_STATE_LOADOS)) {
803                 iflag = bootm_disable_interrupts();
804                 ret = bootm_load_os(images, 0);
805                 if (ret && ret != BOOTM_ERR_OVERLAP)
806                         goto err;
807                 else if (ret == BOOTM_ERR_OVERLAP)
808                         ret = 0;
809         }
810
811         /* Relocate the ramdisk */
812 #ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
813         if (!ret && (states & BOOTM_STATE_RAMDISK)) {
814                 ulong rd_len = images->rd_end - images->rd_start;
815
816                 ret = boot_ramdisk_high(&images->lmb, images->rd_start,
817                         rd_len, &images->initrd_start, &images->initrd_end);
818                 if (!ret) {
819                         env_set_hex("initrd_start", images->initrd_start);
820                         env_set_hex("initrd_end", images->initrd_end);
821                 }
822         }
823 #endif
824 #if CONFIG_IS_ENABLED(OF_LIBFDT) && defined(CONFIG_LMB)
825         if (!ret && (states & BOOTM_STATE_FDT)) {
826                 boot_fdt_add_mem_rsv_regions(&images->lmb, images->ft_addr);
827                 ret = boot_relocate_fdt(&images->lmb, &images->ft_addr,
828                                         &images->ft_len);
829         }
830 #endif
831
832         /* From now on, we need the OS boot function */
833         if (ret)
834                 return ret;
835         boot_fn = bootm_os_get_boot_func(images->os.os);
836         need_boot_fn = states & (BOOTM_STATE_OS_CMDLINE |
837                         BOOTM_STATE_OS_BD_T | BOOTM_STATE_OS_PREP |
838                         BOOTM_STATE_OS_FAKE_GO | BOOTM_STATE_OS_GO);
839         if (boot_fn == NULL && need_boot_fn) {
840                 if (iflag)
841                         enable_interrupts();
842                 printf("ERROR: booting os '%s' (%d) is not supported\n",
843                        genimg_get_os_name(images->os.os), images->os.os);
844                 bootstage_error(BOOTSTAGE_ID_CHECK_BOOT_OS);
845                 return 1;
846         }
847
848
849         /* Call various other states that are not generally used */
850         if (!ret && (states & BOOTM_STATE_OS_CMDLINE))
851                 ret = boot_fn(BOOTM_STATE_OS_CMDLINE, argc, argv, images);
852         if (!ret && (states & BOOTM_STATE_OS_BD_T))
853                 ret = boot_fn(BOOTM_STATE_OS_BD_T, argc, argv, images);
854         if (!ret && (states & BOOTM_STATE_OS_PREP)) {
855                 ret = bootm_process_cmdline_env(images->os.os == IH_OS_LINUX);
856                 if (ret) {
857                         printf("Cmdline setup failed (err=%d)\n", ret);
858                         ret = CMD_RET_FAILURE;
859                         goto err;
860                 }
861                 ret = boot_fn(BOOTM_STATE_OS_PREP, argc, argv, images);
862         }
863
864 #ifdef CONFIG_TRACE
865         /* Pretend to run the OS, then run a user command */
866         if (!ret && (states & BOOTM_STATE_OS_FAKE_GO)) {
867                 char *cmd_list = env_get("fakegocmd");
868
869                 ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_FAKE_GO,
870                                 images, boot_fn);
871                 if (!ret && cmd_list)
872                         ret = run_command_list(cmd_list, -1, flag);
873         }
874 #endif
875
876         /* Check for unsupported subcommand. */
877         if (ret) {
878                 printf("subcommand failed (err=%d)\n", ret);
879                 return ret;
880         }
881
882         /* Now run the OS! We hope this doesn't return */
883         if (!ret && (states & BOOTM_STATE_OS_GO))
884                 ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_GO,
885                                 images, boot_fn);
886
887         /* Deal with any fallout */
888 err:
889         if (iflag)
890                 enable_interrupts();
891
892         if (ret == BOOTM_ERR_UNIMPLEMENTED)
893                 bootstage_error(BOOTSTAGE_ID_DECOMP_UNIMPL);
894         else if (ret == BOOTM_ERR_RESET)
895                 do_reset(cmdtp, flag, argc, argv);
896
897         return ret;
898 }
899
900 int bootm_boot_start(ulong addr, const char *cmdline)
901 {
902         static struct cmd_tbl cmd = {"bootm"};
903         char addr_str[30];
904         char *argv[] = {addr_str, NULL};
905         int states;
906         int ret;
907
908         /*
909          * TODO(sjg@chromium.org): This uses the command-line interface, but
910          * should not. To clean this up, the various bootm states need to be
911          * passed an info structure instead of cmdline flags. Then this can
912          * set up the required info and move through the states without needing
913          * the command line.
914          */
915         states = BOOTM_STATE_START | BOOTM_STATE_FINDOS | BOOTM_STATE_PRE_LOAD |
916                 BOOTM_STATE_FINDOTHER | BOOTM_STATE_LOADOS |
917                 BOOTM_STATE_OS_PREP | BOOTM_STATE_OS_FAKE_GO |
918                 BOOTM_STATE_OS_GO;
919         if (IS_ENABLED(CONFIG_SYS_BOOT_RAMDISK_HIGH))
920                 states |= BOOTM_STATE_RAMDISK;
921         if (IS_ENABLED(CONFIG_PPC) || IS_ENABLED(CONFIG_MIPS))
922                 states |= BOOTM_STATE_OS_CMDLINE;
923         images.state |= states;
924
925         snprintf(addr_str, sizeof(addr_str), "%lx", addr);
926
927         ret = env_set("bootargs", cmdline);
928         if (ret) {
929                 printf("Failed to set cmdline\n");
930                 return ret;
931         }
932         ret = do_bootm_states(&cmd, 0, 1, argv, states, &images, 1);
933
934         return ret;
935 }
936
937 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
938 /**
939  * image_get_kernel - verify legacy format kernel image
940  * @img_addr: in RAM address of the legacy format image to be verified
941  * @verify: data CRC verification flag
942  *
943  * image_get_kernel() verifies legacy image integrity and returns pointer to
944  * legacy image header if image verification was completed successfully.
945  *
946  * returns:
947  *     pointer to a legacy image header if valid image was found
948  *     otherwise return NULL
949  */
950 static struct legacy_img_hdr *image_get_kernel(ulong img_addr, int verify)
951 {
952         struct legacy_img_hdr *hdr = (struct legacy_img_hdr *)img_addr;
953
954         if (!image_check_magic(hdr)) {
955                 puts("Bad Magic Number\n");
956                 bootstage_error(BOOTSTAGE_ID_CHECK_MAGIC);
957                 return NULL;
958         }
959         bootstage_mark(BOOTSTAGE_ID_CHECK_HEADER);
960
961         if (!image_check_hcrc(hdr)) {
962                 puts("Bad Header Checksum\n");
963                 bootstage_error(BOOTSTAGE_ID_CHECK_HEADER);
964                 return NULL;
965         }
966
967         bootstage_mark(BOOTSTAGE_ID_CHECK_CHECKSUM);
968         image_print_contents(hdr);
969
970         if (verify) {
971                 puts("   Verifying Checksum ... ");
972                 if (!image_check_dcrc(hdr)) {
973                         printf("Bad Data CRC\n");
974                         bootstage_error(BOOTSTAGE_ID_CHECK_CHECKSUM);
975                         return NULL;
976                 }
977                 puts("OK\n");
978         }
979         bootstage_mark(BOOTSTAGE_ID_CHECK_ARCH);
980
981         if (!image_check_target_arch(hdr)) {
982                 printf("Unsupported Architecture 0x%x\n", image_get_arch(hdr));
983                 bootstage_error(BOOTSTAGE_ID_CHECK_ARCH);
984                 return NULL;
985         }
986         return hdr;
987 }
988 #endif
989
990 /**
991  * boot_get_kernel - find kernel image
992  * @os_data: pointer to a ulong variable, will hold os data start address
993  * @os_len: pointer to a ulong variable, will hold os data length
994  *
995  * boot_get_kernel() tries to find a kernel image, verifies its integrity
996  * and locates kernel data.
997  *
998  * returns:
999  *     pointer to image header if valid image was found, plus kernel start
1000  *     address and length, otherwise NULL
1001  */
1002 static const void *boot_get_kernel(struct cmd_tbl *cmdtp, int flag, int argc,
1003                                    char *const argv[], struct bootm_headers *images,
1004                                    ulong *os_data, ulong *os_len)
1005 {
1006 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
1007         struct legacy_img_hdr   *hdr;
1008 #endif
1009         ulong           img_addr;
1010         const void *buf;
1011         const char      *fit_uname_config = NULL;
1012         const char      *fit_uname_kernel = NULL;
1013 #if CONFIG_IS_ENABLED(FIT)
1014         int             os_noffset;
1015 #endif
1016
1017 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1018         const void *boot_img;
1019         const void *vendor_boot_img;
1020 #endif
1021         img_addr = genimg_get_kernel_addr_fit(argc < 1 ? NULL : argv[0],
1022                                               &fit_uname_config,
1023                                               &fit_uname_kernel);
1024
1025         if (IS_ENABLED(CONFIG_CMD_BOOTM_PRE_LOAD))
1026                 img_addr += image_load_offset;
1027
1028         bootstage_mark(BOOTSTAGE_ID_CHECK_MAGIC);
1029
1030         /* check image type, for FIT images get FIT kernel node */
1031         *os_data = *os_len = 0;
1032         buf = map_sysmem(img_addr, 0);
1033         switch (genimg_get_format(buf)) {
1034 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
1035         case IMAGE_FORMAT_LEGACY:
1036                 printf("## Booting kernel from Legacy Image at %08lx ...\n",
1037                        img_addr);
1038                 hdr = image_get_kernel(img_addr, images->verify);
1039                 if (!hdr)
1040                         return NULL;
1041                 bootstage_mark(BOOTSTAGE_ID_CHECK_IMAGETYPE);
1042
1043                 /* get os_data and os_len */
1044                 switch (image_get_type(hdr)) {
1045                 case IH_TYPE_KERNEL:
1046                 case IH_TYPE_KERNEL_NOLOAD:
1047                         *os_data = image_get_data(hdr);
1048                         *os_len = image_get_data_size(hdr);
1049                         break;
1050                 case IH_TYPE_MULTI:
1051                         image_multi_getimg(hdr, 0, os_data, os_len);
1052                         break;
1053                 case IH_TYPE_STANDALONE:
1054                         *os_data = image_get_data(hdr);
1055                         *os_len = image_get_data_size(hdr);
1056                         break;
1057                 default:
1058                         printf("Wrong Image Type for %s command\n",
1059                                cmdtp->name);
1060                         bootstage_error(BOOTSTAGE_ID_CHECK_IMAGETYPE);
1061                         return NULL;
1062                 }
1063
1064                 /*
1065                  * copy image header to allow for image overwrites during
1066                  * kernel decompression.
1067                  */
1068                 memmove(&images->legacy_hdr_os_copy, hdr,
1069                         sizeof(struct legacy_img_hdr));
1070
1071                 /* save pointer to image header */
1072                 images->legacy_hdr_os = hdr;
1073
1074                 images->legacy_hdr_valid = 1;
1075                 bootstage_mark(BOOTSTAGE_ID_DECOMP_IMAGE);
1076                 break;
1077 #endif
1078 #if CONFIG_IS_ENABLED(FIT)
1079         case IMAGE_FORMAT_FIT:
1080                 os_noffset = fit_image_load(images, img_addr,
1081                                 &fit_uname_kernel, &fit_uname_config,
1082                                 IH_ARCH_DEFAULT, IH_TYPE_KERNEL,
1083                                 BOOTSTAGE_ID_FIT_KERNEL_START,
1084                                 FIT_LOAD_IGNORED, os_data, os_len);
1085                 if (os_noffset < 0)
1086                         return NULL;
1087
1088                 images->fit_hdr_os = map_sysmem(img_addr, 0);
1089                 images->fit_uname_os = fit_uname_kernel;
1090                 images->fit_uname_cfg = fit_uname_config;
1091                 images->fit_noffset_os = os_noffset;
1092                 break;
1093 #endif
1094 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1095         case IMAGE_FORMAT_ANDROID:
1096                 boot_img = buf;
1097                 vendor_boot_img = NULL;
1098                 if (IS_ENABLED(CONFIG_CMD_ABOOTIMG)) {
1099                         boot_img = map_sysmem(get_abootimg_addr(), 0);
1100                         vendor_boot_img = map_sysmem(get_avendor_bootimg_addr(), 0);
1101                 }
1102                 printf("## Booting Android Image at 0x%08lx ...\n", img_addr);
1103                 if (android_image_get_kernel(boot_img, vendor_boot_img, images->verify,
1104                                              os_data, os_len))
1105                         return NULL;
1106                 if (IS_ENABLED(CONFIG_CMD_ABOOTIMG)) {
1107                         unmap_sysmem(vendor_boot_img);
1108                         unmap_sysmem(boot_img);
1109                 }
1110                 break;
1111 #endif
1112         default:
1113                 printf("Wrong Image Format for %s command\n", cmdtp->name);
1114                 bootstage_error(BOOTSTAGE_ID_FIT_KERNEL_INFO);
1115                 return NULL;
1116         }
1117
1118         debug("   kernel data at 0x%08lx, len = 0x%08lx (%ld)\n",
1119               *os_data, *os_len, *os_len);
1120
1121         return buf;
1122 }
1123
1124 /**
1125  * switch_to_non_secure_mode() - switch to non-secure mode
1126  *
1127  * This routine is overridden by architectures requiring this feature.
1128  */
1129 void __weak switch_to_non_secure_mode(void)
1130 {
1131 }
1132
1133 #else /* USE_HOSTCC */
1134
1135 #if defined(CONFIG_FIT_SIGNATURE)
1136 static int bootm_host_load_image(const void *fit, int req_image_type,
1137                                  int cfg_noffset)
1138 {
1139         const char *fit_uname_config = NULL;
1140         ulong data, len;
1141         struct bootm_headers images;
1142         int noffset;
1143         ulong load_end, buf_size;
1144         uint8_t image_type;
1145         uint8_t image_comp;
1146         void *load_buf;
1147         int ret;
1148
1149         fit_uname_config = fdt_get_name(fit, cfg_noffset, NULL);
1150         memset(&images, '\0', sizeof(images));
1151         images.verify = 1;
1152         noffset = fit_image_load(&images, (ulong)fit,
1153                 NULL, &fit_uname_config,
1154                 IH_ARCH_DEFAULT, req_image_type, -1,
1155                 FIT_LOAD_IGNORED, &data, &len);
1156         if (noffset < 0)
1157                 return noffset;
1158         if (fit_image_get_type(fit, noffset, &image_type)) {
1159                 puts("Can't get image type!\n");
1160                 return -EINVAL;
1161         }
1162
1163         if (fit_image_get_comp(fit, noffset, &image_comp))
1164                 image_comp = IH_COMP_NONE;
1165
1166         /* Allow the image to expand by a factor of 4, should be safe */
1167         buf_size = (1 << 20) + len * 4;
1168         load_buf = malloc(buf_size);
1169         ret = image_decomp(image_comp, 0, data, image_type, load_buf,
1170                            (void *)data, len, buf_size, &load_end);
1171         free(load_buf);
1172
1173         if (ret) {
1174                 ret = handle_decomp_error(image_comp, load_end - 0, buf_size, ret);
1175                 if (ret != BOOTM_ERR_UNIMPLEMENTED)
1176                         return ret;
1177         }
1178
1179         return 0;
1180 }
1181
1182 int bootm_host_load_images(const void *fit, int cfg_noffset)
1183 {
1184         static uint8_t image_types[] = {
1185                 IH_TYPE_KERNEL,
1186                 IH_TYPE_FLATDT,
1187                 IH_TYPE_RAMDISK,
1188         };
1189         int err = 0;
1190         int i;
1191
1192         for (i = 0; i < ARRAY_SIZE(image_types); i++) {
1193                 int ret;
1194
1195                 ret = bootm_host_load_image(fit, image_types[i], cfg_noffset);
1196                 if (!err && ret && ret != -ENOENT)
1197                         err = ret;
1198         }
1199
1200         /* Return the first error we found */
1201         return err;
1202 }
1203 #endif
1204
1205 #endif /* ndef USE_HOSTCC */