e16d433b91df15e98cd9407c7938c50685d538f5
[platform/kernel/u-boot.git] / common / image.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2008 Semihalf
4  *
5  * (C) Copyright 2000-2006
6  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
7  */
8
9 #ifndef USE_HOSTCC
10 #include <common.h>
11 #include <bootstage.h>
12 #include <cpu_func.h>
13 #include <env.h>
14 #include <lmb.h>
15 #include <log.h>
16 #include <malloc.h>
17 #include <asm/cache.h>
18 #include <u-boot/crc.h>
19 #include <watchdog.h>
20
21 #ifdef CONFIG_SHOW_BOOT_PROGRESS
22 #include <status_led.h>
23 #endif
24
25 #include <rtc.h>
26
27 #include <image.h>
28 #include <mapmem.h>
29
30 #if IMAGE_ENABLE_FIT || IMAGE_ENABLE_OF_LIBFDT
31 #include <linux/libfdt.h>
32 #include <fdt_support.h>
33 #include <fpga.h>
34 #include <xilinx.h>
35 #endif
36
37 #include <asm/global_data.h>
38 #include <u-boot/md5.h>
39 #include <u-boot/sha1.h>
40 #include <linux/errno.h>
41 #include <asm/io.h>
42
43 #ifdef CONFIG_CMD_BDI
44 extern int do_bdinfo(struct cmd_tbl *cmdtp, int flag, int argc,
45                      char *const argv[]);
46 #endif
47
48 DECLARE_GLOBAL_DATA_PTR;
49
50 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
51 static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch,
52                                                 int verify);
53 #endif
54
55 /* Set this if we have less than 4 MB of malloc() space */
56 #if CONFIG_SYS_MALLOC_LEN < (4096 * 1024)
57 #define CONSERVE_MEMORY         true
58 #else
59 #define CONSERVE_MEMORY         false
60 #endif
61
62 #else /* USE_HOSTCC */
63 #include "mkimage.h"
64 #include <u-boot/md5.h>
65 #include <time.h>
66 #include <image.h>
67
68 #ifndef __maybe_unused
69 # define __maybe_unused         /* unimplemented */
70 #endif
71
72 #define CONSERVE_MEMORY         false
73
74 #endif /* !USE_HOSTCC*/
75
76 #include <abuf.h>
77 #include <bzlib.h>
78 #include <gzip.h>
79 #include <lz4.h>
80 #include <imximage.h>
81 #include <linux/lzo.h>
82 #include <linux/zstd.h>
83 #include <linux/kconfig.h>
84 #include <lzma/LzmaTypes.h>
85 #include <lzma/LzmaDec.h>
86 #include <lzma/LzmaTools.h>
87 #include <u-boot/crc.h>
88
89 #ifndef CONFIG_SYS_BARGSIZE
90 #define CONFIG_SYS_BARGSIZE 512
91 #endif
92
93 static const table_entry_t uimage_arch[] = {
94         {       IH_ARCH_INVALID,        "invalid",      "Invalid ARCH", },
95         {       IH_ARCH_ALPHA,          "alpha",        "Alpha",        },
96         {       IH_ARCH_ARM,            "arm",          "ARM",          },
97         {       IH_ARCH_I386,           "x86",          "Intel x86",    },
98         {       IH_ARCH_IA64,           "ia64",         "IA64",         },
99         {       IH_ARCH_M68K,           "m68k",         "M68K",         },
100         {       IH_ARCH_MICROBLAZE,     "microblaze",   "MicroBlaze",   },
101         {       IH_ARCH_MIPS,           "mips",         "MIPS",         },
102         {       IH_ARCH_MIPS64,         "mips64",       "MIPS 64 Bit",  },
103         {       IH_ARCH_NIOS2,          "nios2",        "NIOS II",      },
104         {       IH_ARCH_PPC,            "powerpc",      "PowerPC",      },
105         {       IH_ARCH_PPC,            "ppc",          "PowerPC",      },
106         {       IH_ARCH_S390,           "s390",         "IBM S390",     },
107         {       IH_ARCH_SH,             "sh",           "SuperH",       },
108         {       IH_ARCH_SPARC,          "sparc",        "SPARC",        },
109         {       IH_ARCH_SPARC64,        "sparc64",      "SPARC 64 Bit", },
110         {       IH_ARCH_BLACKFIN,       "blackfin",     "Blackfin",     },
111         {       IH_ARCH_AVR32,          "avr32",        "AVR32",        },
112         {       IH_ARCH_NDS32,          "nds32",        "NDS32",        },
113         {       IH_ARCH_OPENRISC,       "or1k",         "OpenRISC 1000",},
114         {       IH_ARCH_SANDBOX,        "sandbox",      "Sandbox",      },
115         {       IH_ARCH_ARM64,          "arm64",        "AArch64",      },
116         {       IH_ARCH_ARC,            "arc",          "ARC",          },
117         {       IH_ARCH_X86_64,         "x86_64",       "AMD x86_64",   },
118         {       IH_ARCH_XTENSA,         "xtensa",       "Xtensa",       },
119         {       IH_ARCH_RISCV,          "riscv",        "RISC-V",       },
120         {       -1,                     "",             "",             },
121 };
122
123 static const table_entry_t uimage_os[] = {
124         {       IH_OS_INVALID,  "invalid",      "Invalid OS",           },
125         {       IH_OS_ARM_TRUSTED_FIRMWARE, "arm-trusted-firmware", "ARM Trusted Firmware"  },
126         {       IH_OS_LINUX,    "linux",        "Linux",                },
127 #if defined(CONFIG_LYNXKDI) || defined(USE_HOSTCC)
128         {       IH_OS_LYNXOS,   "lynxos",       "LynxOS",               },
129 #endif
130         {       IH_OS_NETBSD,   "netbsd",       "NetBSD",               },
131         {       IH_OS_OSE,      "ose",          "Enea OSE",             },
132         {       IH_OS_PLAN9,    "plan9",        "Plan 9",               },
133         {       IH_OS_RTEMS,    "rtems",        "RTEMS",                },
134         {       IH_OS_TEE,      "tee",          "Trusted Execution Environment" },
135         {       IH_OS_U_BOOT,   "u-boot",       "U-Boot",               },
136         {       IH_OS_VXWORKS,  "vxworks",      "VxWorks",              },
137 #if defined(CONFIG_CMD_ELF) || defined(USE_HOSTCC)
138         {       IH_OS_QNX,      "qnx",          "QNX",                  },
139 #endif
140 #if defined(CONFIG_INTEGRITY) || defined(USE_HOSTCC)
141         {       IH_OS_INTEGRITY,"integrity",    "INTEGRITY",            },
142 #endif
143 #ifdef USE_HOSTCC
144         {       IH_OS_4_4BSD,   "4_4bsd",       "4_4BSD",               },
145         {       IH_OS_DELL,     "dell",         "Dell",                 },
146         {       IH_OS_ESIX,     "esix",         "Esix",                 },
147         {       IH_OS_FREEBSD,  "freebsd",      "FreeBSD",              },
148         {       IH_OS_IRIX,     "irix",         "Irix",                 },
149         {       IH_OS_NCR,      "ncr",          "NCR",                  },
150         {       IH_OS_OPENBSD,  "openbsd",      "OpenBSD",              },
151         {       IH_OS_PSOS,     "psos",         "pSOS",                 },
152         {       IH_OS_SCO,      "sco",          "SCO",                  },
153         {       IH_OS_SOLARIS,  "solaris",      "Solaris",              },
154         {       IH_OS_SVR4,     "svr4",         "SVR4",                 },
155 #endif
156 #if defined(CONFIG_BOOTM_OPENRTOS) || defined(USE_HOSTCC)
157         {       IH_OS_OPENRTOS, "openrtos",     "OpenRTOS",             },
158 #endif
159         {       IH_OS_OPENSBI,  "opensbi",      "RISC-V OpenSBI",       },
160         {       IH_OS_EFI,      "efi",          "EFI Firmware" },
161
162         {       -1,             "",             "",                     },
163 };
164
165 static const table_entry_t uimage_type[] = {
166         {       IH_TYPE_AISIMAGE,   "aisimage",   "Davinci AIS image",},
167         {       IH_TYPE_FILESYSTEM, "filesystem", "Filesystem Image",   },
168         {       IH_TYPE_FIRMWARE,   "firmware",   "Firmware",           },
169         {       IH_TYPE_FLATDT,     "flat_dt",    "Flat Device Tree",   },
170         {       IH_TYPE_GPIMAGE,    "gpimage",    "TI Keystone SPL Image",},
171         {       IH_TYPE_KERNEL,     "kernel",     "Kernel Image",       },
172         {       IH_TYPE_KERNEL_NOLOAD, "kernel_noload",  "Kernel Image (no loading done)", },
173         {       IH_TYPE_KWBIMAGE,   "kwbimage",   "Kirkwood Boot Image",},
174         {       IH_TYPE_IMXIMAGE,   "imximage",   "Freescale i.MX Boot Image",},
175         {       IH_TYPE_IMX8IMAGE,  "imx8image",  "NXP i.MX8 Boot Image",},
176         {       IH_TYPE_IMX8MIMAGE, "imx8mimage", "NXP i.MX8M Boot Image",},
177         {       IH_TYPE_INVALID,    "invalid",    "Invalid Image",      },
178         {       IH_TYPE_MULTI,      "multi",      "Multi-File Image",   },
179         {       IH_TYPE_OMAPIMAGE,  "omapimage",  "TI OMAP SPL With GP CH",},
180         {       IH_TYPE_PBLIMAGE,   "pblimage",   "Freescale PBL Boot Image",},
181         {       IH_TYPE_RAMDISK,    "ramdisk",    "RAMDisk Image",      },
182         {       IH_TYPE_SCRIPT,     "script",     "Script",             },
183         {       IH_TYPE_SOCFPGAIMAGE, "socfpgaimage", "Altera SoCFPGA CV/AV preloader",},
184         {       IH_TYPE_SOCFPGAIMAGE_V1, "socfpgaimage_v1", "Altera SoCFPGA A10 preloader",},
185         {       IH_TYPE_STANDALONE, "standalone", "Standalone Program", },
186         {       IH_TYPE_UBLIMAGE,   "ublimage",   "Davinci UBL image",},
187         {       IH_TYPE_MXSIMAGE,   "mxsimage",   "Freescale MXS Boot Image",},
188         {       IH_TYPE_ATMELIMAGE, "atmelimage", "ATMEL ROM-Boot Image",},
189         {       IH_TYPE_X86_SETUP,  "x86_setup",  "x86 setup.bin",    },
190         {       IH_TYPE_LPC32XXIMAGE, "lpc32xximage",  "LPC32XX Boot Image", },
191         {       IH_TYPE_RKIMAGE,    "rkimage",    "Rockchip Boot Image" },
192         {       IH_TYPE_RKSD,       "rksd",       "Rockchip SD Boot Image" },
193         {       IH_TYPE_RKSPI,      "rkspi",      "Rockchip SPI Boot Image" },
194         {       IH_TYPE_VYBRIDIMAGE, "vybridimage",  "Vybrid Boot Image", },
195         {       IH_TYPE_ZYNQIMAGE,  "zynqimage",  "Xilinx Zynq Boot Image" },
196         {       IH_TYPE_ZYNQMPIMAGE, "zynqmpimage", "Xilinx ZynqMP Boot Image" },
197         {       IH_TYPE_ZYNQMPBIF,  "zynqmpbif",  "Xilinx ZynqMP Boot Image (bif)" },
198         {       IH_TYPE_FPGA,       "fpga",       "FPGA Image" },
199         {       IH_TYPE_TEE,        "tee",        "Trusted Execution Environment Image",},
200         {       IH_TYPE_FIRMWARE_IVT, "firmware_ivt", "Firmware with HABv4 IVT" },
201         {       IH_TYPE_PMMC,        "pmmc",        "TI Power Management Micro-Controller Firmware",},
202         {       IH_TYPE_STM32IMAGE, "stm32image", "STMicroelectronics STM32 Image" },
203         {       IH_TYPE_MTKIMAGE,   "mtk_image",   "MediaTek BootROM loadable Image" },
204         {       IH_TYPE_COPRO, "copro", "Coprocessor Image"},
205         {       IH_TYPE_SUNXI_EGON, "sunxi_egon",  "Allwinner eGON Boot Image" },
206         {       -1,                 "",           "",                   },
207 };
208
209 static const table_entry_t uimage_comp[] = {
210         {       IH_COMP_NONE,   "none",         "uncompressed",         },
211         {       IH_COMP_BZIP2,  "bzip2",        "bzip2 compressed",     },
212         {       IH_COMP_GZIP,   "gzip",         "gzip compressed",      },
213         {       IH_COMP_LZMA,   "lzma",         "lzma compressed",      },
214         {       IH_COMP_LZO,    "lzo",          "lzo compressed",       },
215         {       IH_COMP_LZ4,    "lz4",          "lz4 compressed",       },
216         {       IH_COMP_ZSTD,   "zstd",         "zstd compressed",      },
217         {       -1,             "",             "",                     },
218 };
219
220 struct table_info {
221         const char *desc;
222         int count;
223         const table_entry_t *table;
224 };
225
226 static const struct comp_magic_map image_comp[] = {
227         {       IH_COMP_BZIP2,  "bzip2",        {0x42, 0x5a},},
228         {       IH_COMP_GZIP,   "gzip",         {0x1f, 0x8b},},
229         {       IH_COMP_LZMA,   "lzma",         {0x5d, 0x00},},
230         {       IH_COMP_LZO,    "lzo",          {0x89, 0x4c},},
231         {       IH_COMP_LZ4,    "lz4",          {0x04, 0x22},},
232         {       IH_COMP_ZSTD,   "zstd",         {0x28, 0xb5},},
233         {       IH_COMP_NONE,   "none",         {},     },
234 };
235
236 static const struct table_info table_info[IH_COUNT] = {
237         { "architecture", IH_ARCH_COUNT, uimage_arch },
238         { "compression", IH_COMP_COUNT, uimage_comp },
239         { "operating system", IH_OS_COUNT, uimage_os },
240         { "image type", IH_TYPE_COUNT, uimage_type },
241 };
242
243 /*****************************************************************************/
244 /* Legacy format routines */
245 /*****************************************************************************/
246 int image_check_hcrc(const image_header_t *hdr)
247 {
248         ulong hcrc;
249         ulong len = image_get_header_size();
250         image_header_t header;
251
252         /* Copy header so we can blank CRC field for re-calculation */
253         memmove(&header, (char *)hdr, image_get_header_size());
254         image_set_hcrc(&header, 0);
255
256         hcrc = crc32(0, (unsigned char *)&header, len);
257
258         return (hcrc == image_get_hcrc(hdr));
259 }
260
261 int image_check_dcrc(const image_header_t *hdr)
262 {
263         ulong data = image_get_data(hdr);
264         ulong len = image_get_data_size(hdr);
265         ulong dcrc = crc32_wd(0, (unsigned char *)data, len, CHUNKSZ_CRC32);
266
267         return (dcrc == image_get_dcrc(hdr));
268 }
269
270 /**
271  * image_multi_count - get component (sub-image) count
272  * @hdr: pointer to the header of the multi component image
273  *
274  * image_multi_count() returns number of components in a multi
275  * component image.
276  *
277  * Note: no checking of the image type is done, caller must pass
278  * a valid multi component image.
279  *
280  * returns:
281  *     number of components
282  */
283 ulong image_multi_count(const image_header_t *hdr)
284 {
285         ulong i, count = 0;
286         uint32_t *size;
287
288         /* get start of the image payload, which in case of multi
289          * component images that points to a table of component sizes */
290         size = (uint32_t *)image_get_data(hdr);
291
292         /* count non empty slots */
293         for (i = 0; size[i]; ++i)
294                 count++;
295
296         return count;
297 }
298
299 /**
300  * image_multi_getimg - get component data address and size
301  * @hdr: pointer to the header of the multi component image
302  * @idx: index of the requested component
303  * @data: pointer to a ulong variable, will hold component data address
304  * @len: pointer to a ulong variable, will hold component size
305  *
306  * image_multi_getimg() returns size and data address for the requested
307  * component in a multi component image.
308  *
309  * Note: no checking of the image type is done, caller must pass
310  * a valid multi component image.
311  *
312  * returns:
313  *     data address and size of the component, if idx is valid
314  *     0 in data and len, if idx is out of range
315  */
316 void image_multi_getimg(const image_header_t *hdr, ulong idx,
317                         ulong *data, ulong *len)
318 {
319         int i;
320         uint32_t *size;
321         ulong offset, count, img_data;
322
323         /* get number of component */
324         count = image_multi_count(hdr);
325
326         /* get start of the image payload, which in case of multi
327          * component images that points to a table of component sizes */
328         size = (uint32_t *)image_get_data(hdr);
329
330         /* get address of the proper component data start, which means
331          * skipping sizes table (add 1 for last, null entry) */
332         img_data = image_get_data(hdr) + (count + 1) * sizeof(uint32_t);
333
334         if (idx < count) {
335                 *len = uimage_to_cpu(size[idx]);
336                 offset = 0;
337
338                 /* go over all indices preceding requested component idx */
339                 for (i = 0; i < idx; i++) {
340                         /* add up i-th component size, rounding up to 4 bytes */
341                         offset += (uimage_to_cpu(size[i]) + 3) & ~3 ;
342                 }
343
344                 /* calculate idx-th component data address */
345                 *data = img_data + offset;
346         } else {
347                 *len = 0;
348                 *data = 0;
349         }
350 }
351
352 static void image_print_type(const image_header_t *hdr)
353 {
354         const char __maybe_unused *os, *arch, *type, *comp;
355
356         os = genimg_get_os_name(image_get_os(hdr));
357         arch = genimg_get_arch_name(image_get_arch(hdr));
358         type = genimg_get_type_name(image_get_type(hdr));
359         comp = genimg_get_comp_name(image_get_comp(hdr));
360
361         printf("%s %s %s (%s)\n", arch, os, type, comp);
362 }
363
364 /**
365  * image_print_contents - prints out the contents of the legacy format image
366  * @ptr: pointer to the legacy format image header
367  * @p: pointer to prefix string
368  *
369  * image_print_contents() formats a multi line legacy image contents description.
370  * The routine prints out all header fields followed by the size/offset data
371  * for MULTI/SCRIPT images.
372  *
373  * returns:
374  *     no returned results
375  */
376 void image_print_contents(const void *ptr)
377 {
378         const image_header_t *hdr = (const image_header_t *)ptr;
379         const char __maybe_unused *p;
380
381         p = IMAGE_INDENT_STRING;
382         printf("%sImage Name:   %.*s\n", p, IH_NMLEN, image_get_name(hdr));
383         if (IMAGE_ENABLE_TIMESTAMP) {
384                 printf("%sCreated:      ", p);
385                 genimg_print_time((time_t)image_get_time(hdr));
386         }
387         printf("%sImage Type:   ", p);
388         image_print_type(hdr);
389         printf("%sData Size:    ", p);
390         genimg_print_size(image_get_data_size(hdr));
391         printf("%sLoad Address: %08x\n", p, image_get_load(hdr));
392         printf("%sEntry Point:  %08x\n", p, image_get_ep(hdr));
393
394         if (image_check_type(hdr, IH_TYPE_MULTI) ||
395                         image_check_type(hdr, IH_TYPE_SCRIPT)) {
396                 int i;
397                 ulong data, len;
398                 ulong count = image_multi_count(hdr);
399
400                 printf("%sContents:\n", p);
401                 for (i = 0; i < count; i++) {
402                         image_multi_getimg(hdr, i, &data, &len);
403
404                         printf("%s   Image %d: ", p, i);
405                         genimg_print_size(len);
406
407                         if (image_check_type(hdr, IH_TYPE_SCRIPT) && i > 0) {
408                                 /*
409                                  * the user may need to know offsets
410                                  * if planning to do something with
411                                  * multiple files
412                                  */
413                                 printf("%s    Offset = 0x%08lx\n", p, data);
414                         }
415                 }
416         } else if (image_check_type(hdr, IH_TYPE_FIRMWARE_IVT)) {
417                 printf("HAB Blocks:   0x%08x   0x0000   0x%08x\n",
418                         image_get_load(hdr) - image_get_header_size(),
419                         (int)(image_get_size(hdr) + image_get_header_size()
420                         + sizeof(flash_header_v2_t) - 0x2060));
421         }
422 }
423
424 /**
425  * print_decomp_msg() - Print a suitable decompression/loading message
426  *
427  * @type:       OS type (IH_OS_...)
428  * @comp_type:  Compression type being used (IH_COMP_...)
429  * @is_xip:     true if the load address matches the image start
430  */
431 static void print_decomp_msg(int comp_type, int type, bool is_xip)
432 {
433         const char *name = genimg_get_type_name(type);
434
435         if (comp_type == IH_COMP_NONE)
436                 printf("   %s %s\n", is_xip ? "XIP" : "Loading", name);
437         else
438                 printf("   Uncompressing %s\n", name);
439 }
440
441 int image_decomp_type(const unsigned char *buf, ulong len)
442 {
443         const struct comp_magic_map *cmagic = image_comp;
444
445         if (len < 2)
446                 return -EINVAL;
447
448         for (; cmagic->comp_id > 0; cmagic++) {
449                 if (!memcmp(buf, cmagic->magic, 2))
450                         break;
451         }
452
453         return cmagic->comp_id;
454 }
455
456 int image_decomp(int comp, ulong load, ulong image_start, int type,
457                  void *load_buf, void *image_buf, ulong image_len,
458                  uint unc_len, ulong *load_end)
459 {
460         int ret = -ENOSYS;
461
462         *load_end = load;
463         print_decomp_msg(comp, type, load == image_start);
464
465         /*
466          * Load the image to the right place, decompressing if needed. After
467          * this, image_len will be set to the number of uncompressed bytes
468          * loaded, ret will be non-zero on error.
469          */
470         switch (comp) {
471         case IH_COMP_NONE:
472                 ret = 0;
473                 if (load == image_start)
474                         break;
475                 if (image_len <= unc_len)
476                         memmove_wd(load_buf, image_buf, image_len, CHUNKSZ);
477                 else
478                         ret = -ENOSPC;
479                 break;
480         case IH_COMP_GZIP:
481                 if (!host_build() && CONFIG_IS_ENABLED(GZIP))
482                         ret = gunzip(load_buf, unc_len, image_buf, &image_len);
483                 break;
484         case IH_COMP_BZIP2:
485                 if (!host_build() && CONFIG_IS_ENABLED(BZIP2)) {
486                         uint size = unc_len;
487
488                         /*
489                          * If we've got less than 4 MB of malloc() space,
490                          * use slower decompression algorithm which requires
491                          * at most 2300 KB of memory.
492                          */
493                         ret = BZ2_bzBuffToBuffDecompress(load_buf, &size,
494                                 image_buf, image_len, CONSERVE_MEMORY, 0);
495                         image_len = size;
496                 }
497                 break;
498         case IH_COMP_LZMA:
499                 if (!host_build() && CONFIG_IS_ENABLED(LZMA)) {
500                         SizeT lzma_len = unc_len;
501
502                         ret = lzmaBuffToBuffDecompress(load_buf, &lzma_len,
503                                                        image_buf, image_len);
504                         image_len = lzma_len;
505                 }
506                 break;
507         case IH_COMP_LZO:
508                 if (!host_build() && CONFIG_IS_ENABLED(LZO)) {
509                         size_t size = unc_len;
510
511                         ret = lzop_decompress(image_buf, image_len, load_buf, &size);
512                         image_len = size;
513                 }
514                 break;
515         case IH_COMP_LZ4:
516                 if (!host_build() && CONFIG_IS_ENABLED(LZ4)) {
517                         size_t size = unc_len;
518
519                         ret = ulz4fn(image_buf, image_len, load_buf, &size);
520                         image_len = size;
521                 }
522                 break;
523         case IH_COMP_ZSTD:
524                 if (!host_build() && CONFIG_IS_ENABLED(ZSTD)) {
525                         struct abuf in, out;
526
527                         abuf_init_set(&in, image_buf, image_len);
528                         abuf_init_set(&in, load_buf, unc_len);
529                         ret = zstd_decompress(&in, &out);
530                         if (ret >= 0) {
531                                 image_len = ret;
532                                 ret = 0;
533                         }
534                 }
535                 break;
536         }
537         if (ret == -ENOSYS) {
538                 printf("Unimplemented compression type %d\n", comp);
539                 return ret;
540         }
541         if (ret)
542                 return ret;
543
544         *load_end = load + image_len;
545
546         return 0;
547 }
548
549 #ifndef USE_HOSTCC
550 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
551 /**
552  * image_get_ramdisk - get and verify ramdisk image
553  * @rd_addr: ramdisk image start address
554  * @arch: expected ramdisk architecture
555  * @verify: checksum verification flag
556  *
557  * image_get_ramdisk() returns a pointer to the verified ramdisk image
558  * header. Routine receives image start address and expected architecture
559  * flag. Verification done covers data and header integrity and os/type/arch
560  * fields checking.
561  *
562  * returns:
563  *     pointer to a ramdisk image header, if image was found and valid
564  *     otherwise, return NULL
565  */
566 static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch,
567                                                 int verify)
568 {
569         const image_header_t *rd_hdr = (const image_header_t *)rd_addr;
570
571         if (!image_check_magic(rd_hdr)) {
572                 puts("Bad Magic Number\n");
573                 bootstage_error(BOOTSTAGE_ID_RD_MAGIC);
574                 return NULL;
575         }
576
577         if (!image_check_hcrc(rd_hdr)) {
578                 puts("Bad Header Checksum\n");
579                 bootstage_error(BOOTSTAGE_ID_RD_HDR_CHECKSUM);
580                 return NULL;
581         }
582
583         bootstage_mark(BOOTSTAGE_ID_RD_MAGIC);
584         image_print_contents(rd_hdr);
585
586         if (verify) {
587                 puts("   Verifying Checksum ... ");
588                 if (!image_check_dcrc(rd_hdr)) {
589                         puts("Bad Data CRC\n");
590                         bootstage_error(BOOTSTAGE_ID_RD_CHECKSUM);
591                         return NULL;
592                 }
593                 puts("OK\n");
594         }
595
596         bootstage_mark(BOOTSTAGE_ID_RD_HDR_CHECKSUM);
597
598         if (!image_check_os(rd_hdr, IH_OS_LINUX) ||
599             !image_check_arch(rd_hdr, arch) ||
600             !image_check_type(rd_hdr, IH_TYPE_RAMDISK)) {
601                 printf("No Linux %s Ramdisk Image\n",
602                                 genimg_get_arch_name(arch));
603                 bootstage_error(BOOTSTAGE_ID_RAMDISK);
604                 return NULL;
605         }
606
607         return rd_hdr;
608 }
609 #endif
610 #endif /* !USE_HOSTCC */
611
612 /*****************************************************************************/
613 /* Shared dual-format routines */
614 /*****************************************************************************/
615 #ifndef USE_HOSTCC
616 ulong image_load_addr = CONFIG_SYS_LOAD_ADDR;   /* Default Load Address */
617 ulong image_save_addr;                  /* Default Save Address */
618 ulong image_save_size;                  /* Default Save Size (in bytes) */
619
620 static int on_loadaddr(const char *name, const char *value, enum env_op op,
621         int flags)
622 {
623         switch (op) {
624         case env_op_create:
625         case env_op_overwrite:
626                 image_load_addr = hextoul(value, NULL);
627                 break;
628         default:
629                 break;
630         }
631
632         return 0;
633 }
634 U_BOOT_ENV_CALLBACK(loadaddr, on_loadaddr);
635
636 ulong env_get_bootm_low(void)
637 {
638         char *s = env_get("bootm_low");
639         if (s) {
640                 ulong tmp = hextoul(s, NULL);
641                 return tmp;
642         }
643
644 #if defined(CONFIG_SYS_SDRAM_BASE)
645         return CONFIG_SYS_SDRAM_BASE;
646 #elif defined(CONFIG_ARM) || defined(CONFIG_MICROBLAZE) || defined(CONFIG_RISCV)
647         return gd->bd->bi_dram[0].start;
648 #else
649         return 0;
650 #endif
651 }
652
653 phys_size_t env_get_bootm_size(void)
654 {
655         phys_size_t tmp, size;
656         phys_addr_t start;
657         char *s = env_get("bootm_size");
658         if (s) {
659                 tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
660                 return tmp;
661         }
662
663         start = gd->ram_base;
664         size = gd->ram_size;
665
666         if (start + size > gd->ram_top)
667                 size = gd->ram_top - start;
668
669         s = env_get("bootm_low");
670         if (s)
671                 tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
672         else
673                 tmp = start;
674
675         return size - (tmp - start);
676 }
677
678 phys_size_t env_get_bootm_mapsize(void)
679 {
680         phys_size_t tmp;
681         char *s = env_get("bootm_mapsize");
682         if (s) {
683                 tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
684                 return tmp;
685         }
686
687 #if defined(CONFIG_SYS_BOOTMAPSZ)
688         return CONFIG_SYS_BOOTMAPSZ;
689 #else
690         return env_get_bootm_size();
691 #endif
692 }
693
694 void memmove_wd(void *to, void *from, size_t len, ulong chunksz)
695 {
696         if (to == from)
697                 return;
698
699 #if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
700         if (to > from) {
701                 from += len;
702                 to += len;
703         }
704         while (len > 0) {
705                 size_t tail = (len > chunksz) ? chunksz : len;
706                 WATCHDOG_RESET();
707                 if (to > from) {
708                         to -= tail;
709                         from -= tail;
710                 }
711                 memmove(to, from, tail);
712                 if (to < from) {
713                         to += tail;
714                         from += tail;
715                 }
716                 len -= tail;
717         }
718 #else   /* !(CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG) */
719         memmove(to, from, len);
720 #endif  /* CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG */
721 }
722 #else   /* USE_HOSTCC */
723 void memmove_wd(void *to, void *from, size_t len, ulong chunksz)
724 {
725         memmove(to, from, len);
726 }
727 #endif /* !USE_HOSTCC */
728
729 void genimg_print_size(uint32_t size)
730 {
731 #ifndef USE_HOSTCC
732         printf("%d Bytes = ", size);
733         print_size(size, "\n");
734 #else
735         printf("%d Bytes = %.2f KiB = %.2f MiB\n",
736                         size, (double)size / 1.024e3,
737                         (double)size / 1.048576e6);
738 #endif
739 }
740
741 #if IMAGE_ENABLE_TIMESTAMP
742 void genimg_print_time(time_t timestamp)
743 {
744 #ifndef USE_HOSTCC
745         struct rtc_time tm;
746
747         rtc_to_tm(timestamp, &tm);
748         printf("%4d-%02d-%02d  %2d:%02d:%02d UTC\n",
749                         tm.tm_year, tm.tm_mon, tm.tm_mday,
750                         tm.tm_hour, tm.tm_min, tm.tm_sec);
751 #else
752         printf("%s", ctime(&timestamp));
753 #endif
754 }
755 #endif
756
757 const table_entry_t *get_table_entry(const table_entry_t *table, int id)
758 {
759         for (; table->id >= 0; ++table) {
760                 if (table->id == id)
761                         return table;
762         }
763         return NULL;
764 }
765
766 static const char *unknown_msg(enum ih_category category)
767 {
768         static const char unknown_str[] = "Unknown ";
769         static char msg[30];
770
771         strcpy(msg, unknown_str);
772         strncat(msg, table_info[category].desc,
773                 sizeof(msg) - sizeof(unknown_str));
774
775         return msg;
776 }
777
778 /**
779  * genimg_get_cat_name - translate entry id to long name
780  * @category: category to look up (enum ih_category)
781  * @id: entry id to be translated
782  *
783  * This will scan the translation table trying to find the entry that matches
784  * the given id.
785  *
786  * @return long entry name if translation succeeds; error string on failure
787  */
788 const char *genimg_get_cat_name(enum ih_category category, uint id)
789 {
790         const table_entry_t *entry;
791
792         entry = get_table_entry(table_info[category].table, id);
793         if (!entry)
794                 return unknown_msg(category);
795 #if defined(USE_HOSTCC) || !defined(CONFIG_NEEDS_MANUAL_RELOC)
796         return entry->lname;
797 #else
798         return entry->lname + gd->reloc_off;
799 #endif
800 }
801
802 /**
803  * genimg_get_cat_short_name - translate entry id to short name
804  * @category: category to look up (enum ih_category)
805  * @id: entry id to be translated
806  *
807  * This will scan the translation table trying to find the entry that matches
808  * the given id.
809  *
810  * @return short entry name if translation succeeds; error string on failure
811  */
812 const char *genimg_get_cat_short_name(enum ih_category category, uint id)
813 {
814         const table_entry_t *entry;
815
816         entry = get_table_entry(table_info[category].table, id);
817         if (!entry)
818                 return unknown_msg(category);
819 #if defined(USE_HOSTCC) || !defined(CONFIG_NEEDS_MANUAL_RELOC)
820         return entry->sname;
821 #else
822         return entry->sname + gd->reloc_off;
823 #endif
824 }
825
826 int genimg_get_cat_count(enum ih_category category)
827 {
828         return table_info[category].count;
829 }
830
831 const char *genimg_get_cat_desc(enum ih_category category)
832 {
833         return table_info[category].desc;
834 }
835
836 /**
837  * genimg_cat_has_id - check whether category has entry id
838  * @category: category to look up (enum ih_category)
839  * @id: entry id to be checked
840  *
841  * This will scan the translation table trying to find the entry that matches
842  * the given id.
843  *
844  * @return true if category has entry id; false if not
845  */
846 bool genimg_cat_has_id(enum ih_category category, uint id)
847 {
848         if (get_table_entry(table_info[category].table, id))
849                 return true;
850
851         return false;
852 }
853
854 /**
855  * get_table_entry_name - translate entry id to long name
856  * @table: pointer to a translation table for entries of a specific type
857  * @msg: message to be returned when translation fails
858  * @id: entry id to be translated
859  *
860  * get_table_entry_name() will go over translation table trying to find
861  * entry that matches given id. If matching entry is found, its long
862  * name is returned to the caller.
863  *
864  * returns:
865  *     long entry name if translation succeeds
866  *     msg otherwise
867  */
868 char *get_table_entry_name(const table_entry_t *table, char *msg, int id)
869 {
870         table = get_table_entry(table, id);
871         if (!table)
872                 return msg;
873 #if defined(USE_HOSTCC) || !defined(CONFIG_NEEDS_MANUAL_RELOC)
874         return table->lname;
875 #else
876         return table->lname + gd->reloc_off;
877 #endif
878 }
879
880 const char *genimg_get_os_name(uint8_t os)
881 {
882         return (get_table_entry_name(uimage_os, "Unknown OS", os));
883 }
884
885 const char *genimg_get_arch_name(uint8_t arch)
886 {
887         return (get_table_entry_name(uimage_arch, "Unknown Architecture",
888                                         arch));
889 }
890
891 const char *genimg_get_type_name(uint8_t type)
892 {
893         return (get_table_entry_name(uimage_type, "Unknown Image", type));
894 }
895
896 const char *genimg_get_comp_name(uint8_t comp)
897 {
898         return (get_table_entry_name(uimage_comp, "Unknown Compression",
899                                         comp));
900 }
901
902 static const char *genimg_get_short_name(const table_entry_t *table, int val)
903 {
904         table = get_table_entry(table, val);
905         if (!table)
906                 return "unknown";
907 #if defined(USE_HOSTCC) || !defined(CONFIG_NEEDS_MANUAL_RELOC)
908         return table->sname;
909 #else
910         return table->sname + gd->reloc_off;
911 #endif
912 }
913
914 const char *genimg_get_type_short_name(uint8_t type)
915 {
916         return genimg_get_short_name(uimage_type, type);
917 }
918
919 const char *genimg_get_comp_short_name(uint8_t comp)
920 {
921         return genimg_get_short_name(uimage_comp, comp);
922 }
923
924 const char *genimg_get_os_short_name(uint8_t os)
925 {
926         return genimg_get_short_name(uimage_os, os);
927 }
928
929 const char *genimg_get_arch_short_name(uint8_t arch)
930 {
931         return genimg_get_short_name(uimage_arch, arch);
932 }
933
934 /**
935  * get_table_entry_id - translate short entry name to id
936  * @table: pointer to a translation table for entries of a specific type
937  * @table_name: to be used in case of error
938  * @name: entry short name to be translated
939  *
940  * get_table_entry_id() will go over translation table trying to find
941  * entry that matches given short name. If matching entry is found,
942  * its id returned to the caller.
943  *
944  * returns:
945  *     entry id if translation succeeds
946  *     -1 otherwise
947  */
948 int get_table_entry_id(const table_entry_t *table,
949                 const char *table_name, const char *name)
950 {
951         const table_entry_t *t;
952
953         for (t = table; t->id >= 0; ++t) {
954 #if !defined(USE_HOSTCC) && defined(CONFIG_NEEDS_MANUAL_RELOC)
955                 if (t->sname && strcasecmp(t->sname + gd->reloc_off, name) == 0)
956 #else
957                 if (t->sname && strcasecmp(t->sname, name) == 0)
958 #endif
959                         return (t->id);
960         }
961         debug("Invalid %s Type: %s\n", table_name, name);
962
963         return -1;
964 }
965
966 int genimg_get_os_id(const char *name)
967 {
968         return (get_table_entry_id(uimage_os, "OS", name));
969 }
970
971 int genimg_get_arch_id(const char *name)
972 {
973         return (get_table_entry_id(uimage_arch, "CPU", name));
974 }
975
976 int genimg_get_type_id(const char *name)
977 {
978         return (get_table_entry_id(uimage_type, "Image", name));
979 }
980
981 int genimg_get_comp_id(const char *name)
982 {
983         return (get_table_entry_id(uimage_comp, "Compression", name));
984 }
985
986 #ifndef USE_HOSTCC
987 /**
988  * genimg_get_kernel_addr_fit - get the real kernel address and return 2
989  *                              FIT strings
990  * @img_addr: a string might contain real image address
991  * @fit_uname_config: double pointer to a char, will hold pointer to a
992  *                    configuration unit name
993  * @fit_uname_kernel: double pointer to a char, will hold pointer to a subimage
994  *                    name
995  *
996  * genimg_get_kernel_addr_fit get the real kernel start address from a string
997  * which is normally the first argv of bootm/bootz
998  *
999  * returns:
1000  *     kernel start address
1001  */
1002 ulong genimg_get_kernel_addr_fit(char * const img_addr,
1003                              const char **fit_uname_config,
1004                              const char **fit_uname_kernel)
1005 {
1006         ulong kernel_addr;
1007
1008         /* find out kernel image address */
1009         if (!img_addr) {
1010                 kernel_addr = image_load_addr;
1011                 debug("*  kernel: default image load address = 0x%08lx\n",
1012                       image_load_addr);
1013 #if CONFIG_IS_ENABLED(FIT)
1014         } else if (fit_parse_conf(img_addr, image_load_addr, &kernel_addr,
1015                                   fit_uname_config)) {
1016                 debug("*  kernel: config '%s' from image at 0x%08lx\n",
1017                       *fit_uname_config, kernel_addr);
1018         } else if (fit_parse_subimage(img_addr, image_load_addr, &kernel_addr,
1019                                      fit_uname_kernel)) {
1020                 debug("*  kernel: subimage '%s' from image at 0x%08lx\n",
1021                       *fit_uname_kernel, kernel_addr);
1022 #endif
1023         } else {
1024                 kernel_addr = hextoul(img_addr, NULL);
1025                 debug("*  kernel: cmdline image address = 0x%08lx\n",
1026                       kernel_addr);
1027         }
1028
1029         return kernel_addr;
1030 }
1031
1032 /**
1033  * genimg_get_kernel_addr() is the simple version of
1034  * genimg_get_kernel_addr_fit(). It ignores those return FIT strings
1035  */
1036 ulong genimg_get_kernel_addr(char * const img_addr)
1037 {
1038         const char *fit_uname_config = NULL;
1039         const char *fit_uname_kernel = NULL;
1040
1041         return genimg_get_kernel_addr_fit(img_addr, &fit_uname_config,
1042                                           &fit_uname_kernel);
1043 }
1044
1045 /**
1046  * genimg_get_format - get image format type
1047  * @img_addr: image start address
1048  *
1049  * genimg_get_format() checks whether provided address points to a valid
1050  * legacy or FIT image.
1051  *
1052  * New uImage format and FDT blob are based on a libfdt. FDT blob
1053  * may be passed directly or embedded in a FIT image. In both situations
1054  * genimg_get_format() must be able to dectect libfdt header.
1055  *
1056  * returns:
1057  *     image format type or IMAGE_FORMAT_INVALID if no image is present
1058  */
1059 int genimg_get_format(const void *img_addr)
1060 {
1061 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
1062         const image_header_t *hdr;
1063
1064         hdr = (const image_header_t *)img_addr;
1065         if (image_check_magic(hdr))
1066                 return IMAGE_FORMAT_LEGACY;
1067 #endif
1068 #if IMAGE_ENABLE_FIT || IMAGE_ENABLE_OF_LIBFDT
1069         if (fdt_check_header(img_addr) == 0)
1070                 return IMAGE_FORMAT_FIT;
1071 #endif
1072 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1073         if (android_image_check_header(img_addr) == 0)
1074                 return IMAGE_FORMAT_ANDROID;
1075 #endif
1076
1077         return IMAGE_FORMAT_INVALID;
1078 }
1079
1080 /**
1081  * fit_has_config - check if there is a valid FIT configuration
1082  * @images: pointer to the bootm command headers structure
1083  *
1084  * fit_has_config() checks if there is a FIT configuration in use
1085  * (if FTI support is present).
1086  *
1087  * returns:
1088  *     0, no FIT support or no configuration found
1089  *     1, configuration found
1090  */
1091 int genimg_has_config(bootm_headers_t *images)
1092 {
1093 #if IMAGE_ENABLE_FIT
1094         if (images->fit_uname_cfg)
1095                 return 1;
1096 #endif
1097         return 0;
1098 }
1099
1100 /**
1101  * boot_get_ramdisk - main ramdisk handling routine
1102  * @argc: command argument count
1103  * @argv: command argument list
1104  * @images: pointer to the bootm images structure
1105  * @arch: expected ramdisk architecture
1106  * @rd_start: pointer to a ulong variable, will hold ramdisk start address
1107  * @rd_end: pointer to a ulong variable, will hold ramdisk end
1108  *
1109  * boot_get_ramdisk() is responsible for finding a valid ramdisk image.
1110  * Curently supported are the following ramdisk sources:
1111  *      - multicomponent kernel/ramdisk image,
1112  *      - commandline provided address of decicated ramdisk image.
1113  *
1114  * returns:
1115  *     0, if ramdisk image was found and valid, or skiped
1116  *     rd_start and rd_end are set to ramdisk start/end addresses if
1117  *     ramdisk image is found and valid
1118  *
1119  *     1, if ramdisk image is found but corrupted, or invalid
1120  *     rd_start and rd_end are set to 0 if no ramdisk exists
1121  */
1122 int boot_get_ramdisk(int argc, char *const argv[], bootm_headers_t *images,
1123                      uint8_t arch, ulong *rd_start, ulong *rd_end)
1124 {
1125         ulong rd_addr, rd_load;
1126         ulong rd_data, rd_len;
1127 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
1128         const image_header_t *rd_hdr;
1129 #endif
1130         void *buf;
1131 #ifdef CONFIG_SUPPORT_RAW_INITRD
1132         char *end;
1133 #endif
1134 #if IMAGE_ENABLE_FIT
1135         const char      *fit_uname_config = images->fit_uname_cfg;
1136         const char      *fit_uname_ramdisk = NULL;
1137         ulong           default_addr;
1138         int             rd_noffset;
1139 #endif
1140         const char *select = NULL;
1141
1142         *rd_start = 0;
1143         *rd_end = 0;
1144
1145 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1146         /*
1147          * Look for an Android boot image.
1148          */
1149         buf = map_sysmem(images->os.start, 0);
1150         if (buf && genimg_get_format(buf) == IMAGE_FORMAT_ANDROID)
1151                 select = (argc == 0) ? env_get("loadaddr") : argv[0];
1152 #endif
1153
1154         if (argc >= 2)
1155                 select = argv[1];
1156
1157         /*
1158          * Look for a '-' which indicates to ignore the
1159          * ramdisk argument
1160          */
1161         if (select && strcmp(select, "-") ==  0) {
1162                 debug("## Skipping init Ramdisk\n");
1163                 rd_len = rd_data = 0;
1164         } else if (select || genimg_has_config(images)) {
1165 #if IMAGE_ENABLE_FIT
1166                 if (select) {
1167                         /*
1168                          * If the init ramdisk comes from the FIT image and
1169                          * the FIT image address is omitted in the command
1170                          * line argument, try to use os FIT image address or
1171                          * default load address.
1172                          */
1173                         if (images->fit_uname_os)
1174                                 default_addr = (ulong)images->fit_hdr_os;
1175                         else
1176                                 default_addr = image_load_addr;
1177
1178                         if (fit_parse_conf(select, default_addr,
1179                                            &rd_addr, &fit_uname_config)) {
1180                                 debug("*  ramdisk: config '%s' from image at "
1181                                                 "0x%08lx\n",
1182                                                 fit_uname_config, rd_addr);
1183                         } else if (fit_parse_subimage(select, default_addr,
1184                                                 &rd_addr, &fit_uname_ramdisk)) {
1185                                 debug("*  ramdisk: subimage '%s' from image at "
1186                                                 "0x%08lx\n",
1187                                                 fit_uname_ramdisk, rd_addr);
1188                         } else
1189 #endif
1190                         {
1191                                 rd_addr = hextoul(select, NULL);
1192                                 debug("*  ramdisk: cmdline image address = "
1193                                                 "0x%08lx\n",
1194                                                 rd_addr);
1195                         }
1196 #if IMAGE_ENABLE_FIT
1197                 } else {
1198                         /* use FIT configuration provided in first bootm
1199                          * command argument. If the property is not defined,
1200                          * quit silently.
1201                          */
1202                         rd_addr = map_to_sysmem(images->fit_hdr_os);
1203                         rd_noffset = fit_get_node_from_config(images,
1204                                         FIT_RAMDISK_PROP, rd_addr);
1205                         if (rd_noffset == -ENOENT)
1206                                 return 0;
1207                         else if (rd_noffset < 0)
1208                                 return 1;
1209                 }
1210 #endif
1211
1212                 /*
1213                  * Check if there is an initrd image at the
1214                  * address provided in the second bootm argument
1215                  * check image type, for FIT images get FIT node.
1216                  */
1217                 buf = map_sysmem(rd_addr, 0);
1218                 switch (genimg_get_format(buf)) {
1219 #if CONFIG_IS_ENABLED(LEGACY_IMAGE_FORMAT)
1220                 case IMAGE_FORMAT_LEGACY:
1221                         printf("## Loading init Ramdisk from Legacy "
1222                                         "Image at %08lx ...\n", rd_addr);
1223
1224                         bootstage_mark(BOOTSTAGE_ID_CHECK_RAMDISK);
1225                         rd_hdr = image_get_ramdisk(rd_addr, arch,
1226                                                         images->verify);
1227
1228                         if (rd_hdr == NULL)
1229                                 return 1;
1230
1231                         rd_data = image_get_data(rd_hdr);
1232                         rd_len = image_get_data_size(rd_hdr);
1233                         rd_load = image_get_load(rd_hdr);
1234                         break;
1235 #endif
1236 #if IMAGE_ENABLE_FIT
1237                 case IMAGE_FORMAT_FIT:
1238                         rd_noffset = fit_image_load(images,
1239                                         rd_addr, &fit_uname_ramdisk,
1240                                         &fit_uname_config, arch,
1241                                         IH_TYPE_RAMDISK,
1242                                         BOOTSTAGE_ID_FIT_RD_START,
1243                                         FIT_LOAD_OPTIONAL_NON_ZERO,
1244                                         &rd_data, &rd_len);
1245                         if (rd_noffset < 0)
1246                                 return 1;
1247
1248                         images->fit_hdr_rd = map_sysmem(rd_addr, 0);
1249                         images->fit_uname_rd = fit_uname_ramdisk;
1250                         images->fit_noffset_rd = rd_noffset;
1251                         break;
1252 #endif
1253 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1254                 case IMAGE_FORMAT_ANDROID:
1255                         android_image_get_ramdisk((void *)images->os.start,
1256                                 &rd_data, &rd_len);
1257                         break;
1258 #endif
1259                 default:
1260 #ifdef CONFIG_SUPPORT_RAW_INITRD
1261                         end = NULL;
1262                         if (select)
1263                                 end = strchr(select, ':');
1264                         if (end) {
1265                                 rd_len = hextoul(++end, NULL);
1266                                 rd_data = rd_addr;
1267                         } else
1268 #endif
1269                         {
1270                                 puts("Wrong Ramdisk Image Format\n");
1271                                 rd_data = rd_len = rd_load = 0;
1272                                 return 1;
1273                         }
1274                 }
1275         } else if (images->legacy_hdr_valid &&
1276                         image_check_type(&images->legacy_hdr_os_copy,
1277                                                 IH_TYPE_MULTI)) {
1278
1279                 /*
1280                  * Now check if we have a legacy mult-component image,
1281                  * get second entry data start address and len.
1282                  */
1283                 bootstage_mark(BOOTSTAGE_ID_RAMDISK);
1284                 printf("## Loading init Ramdisk from multi component "
1285                                 "Legacy Image at %08lx ...\n",
1286                                 (ulong)images->legacy_hdr_os);
1287
1288                 image_multi_getimg(images->legacy_hdr_os, 1, &rd_data, &rd_len);
1289         } else {
1290                 /*
1291                  * no initrd image
1292                  */
1293                 bootstage_mark(BOOTSTAGE_ID_NO_RAMDISK);
1294                 rd_len = rd_data = 0;
1295         }
1296
1297         if (!rd_data) {
1298                 debug("## No init Ramdisk\n");
1299         } else {
1300                 *rd_start = rd_data;
1301                 *rd_end = rd_data + rd_len;
1302         }
1303         debug("   ramdisk start = 0x%08lx, ramdisk end = 0x%08lx\n",
1304                         *rd_start, *rd_end);
1305
1306         return 0;
1307 }
1308
1309 #ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
1310 /**
1311  * boot_ramdisk_high - relocate init ramdisk
1312  * @lmb: pointer to lmb handle, will be used for memory mgmt
1313  * @rd_data: ramdisk data start address
1314  * @rd_len: ramdisk data length
1315  * @initrd_start: pointer to a ulong variable, will hold final init ramdisk
1316  *      start address (after possible relocation)
1317  * @initrd_end: pointer to a ulong variable, will hold final init ramdisk
1318  *      end address (after possible relocation)
1319  *
1320  * boot_ramdisk_high() takes a relocation hint from "initrd_high" environment
1321  * variable and if requested ramdisk data is moved to a specified location.
1322  *
1323  * Initrd_start and initrd_end are set to final (after relocation) ramdisk
1324  * start/end addresses if ramdisk image start and len were provided,
1325  * otherwise set initrd_start and initrd_end set to zeros.
1326  *
1327  * returns:
1328  *      0 - success
1329  *     -1 - failure
1330  */
1331 int boot_ramdisk_high(struct lmb *lmb, ulong rd_data, ulong rd_len,
1332                   ulong *initrd_start, ulong *initrd_end)
1333 {
1334         char    *s;
1335         ulong   initrd_high;
1336         int     initrd_copy_to_ram = 1;
1337
1338         s = env_get("initrd_high");
1339         if (s) {
1340                 /* a value of "no" or a similar string will act like 0,
1341                  * turning the "load high" feature off. This is intentional.
1342                  */
1343                 initrd_high = hextoul(s, NULL);
1344                 if (initrd_high == ~0)
1345                         initrd_copy_to_ram = 0;
1346         } else {
1347                 initrd_high = env_get_bootm_mapsize() + env_get_bootm_low();
1348         }
1349
1350
1351         debug("## initrd_high = 0x%08lx, copy_to_ram = %d\n",
1352                         initrd_high, initrd_copy_to_ram);
1353
1354         if (rd_data) {
1355                 if (!initrd_copy_to_ram) {      /* zero-copy ramdisk support */
1356                         debug("   in-place initrd\n");
1357                         *initrd_start = rd_data;
1358                         *initrd_end = rd_data + rd_len;
1359                         lmb_reserve(lmb, rd_data, rd_len);
1360                 } else {
1361                         if (initrd_high)
1362                                 *initrd_start = (ulong)lmb_alloc_base(lmb,
1363                                                 rd_len, 0x1000, initrd_high);
1364                         else
1365                                 *initrd_start = (ulong)lmb_alloc(lmb, rd_len,
1366                                                                  0x1000);
1367
1368                         if (*initrd_start == 0) {
1369                                 puts("ramdisk - allocation error\n");
1370                                 goto error;
1371                         }
1372                         bootstage_mark(BOOTSTAGE_ID_COPY_RAMDISK);
1373
1374                         *initrd_end = *initrd_start + rd_len;
1375                         printf("   Loading Ramdisk to %08lx, end %08lx ... ",
1376                                         *initrd_start, *initrd_end);
1377
1378                         memmove_wd((void *)*initrd_start,
1379                                         (void *)rd_data, rd_len, CHUNKSZ);
1380
1381 #ifdef CONFIG_MP
1382                         /*
1383                          * Ensure the image is flushed to memory to handle
1384                          * AMP boot scenarios in which we might not be
1385                          * HW cache coherent
1386                          */
1387                         flush_cache((unsigned long)*initrd_start,
1388                                     ALIGN(rd_len, ARCH_DMA_MINALIGN));
1389 #endif
1390                         puts("OK\n");
1391                 }
1392         } else {
1393                 *initrd_start = 0;
1394                 *initrd_end = 0;
1395         }
1396         debug("   ramdisk load start = 0x%08lx, ramdisk load end = 0x%08lx\n",
1397                         *initrd_start, *initrd_end);
1398
1399         return 0;
1400
1401 error:
1402         return -1;
1403 }
1404 #endif /* CONFIG_SYS_BOOT_RAMDISK_HIGH */
1405
1406 int boot_get_setup(bootm_headers_t *images, uint8_t arch,
1407                    ulong *setup_start, ulong *setup_len)
1408 {
1409 #if IMAGE_ENABLE_FIT
1410         return boot_get_setup_fit(images, arch, setup_start, setup_len);
1411 #else
1412         return -ENOENT;
1413 #endif
1414 }
1415
1416 #if IMAGE_ENABLE_FIT
1417 #if defined(CONFIG_FPGA)
1418 int boot_get_fpga(int argc, char *const argv[], bootm_headers_t *images,
1419                   uint8_t arch, const ulong *ld_start, ulong * const ld_len)
1420 {
1421         ulong tmp_img_addr, img_data, img_len;
1422         void *buf;
1423         int conf_noffset;
1424         int fit_img_result;
1425         const char *uname, *name;
1426         int err;
1427         int devnum = 0; /* TODO support multi fpga platforms */
1428
1429         /* Check to see if the images struct has a FIT configuration */
1430         if (!genimg_has_config(images)) {
1431                 debug("## FIT configuration was not specified\n");
1432                 return 0;
1433         }
1434
1435         /*
1436          * Obtain the os FIT header from the images struct
1437          */
1438         tmp_img_addr = map_to_sysmem(images->fit_hdr_os);
1439         buf = map_sysmem(tmp_img_addr, 0);
1440         /*
1441          * Check image type. For FIT images get FIT node
1442          * and attempt to locate a generic binary.
1443          */
1444         switch (genimg_get_format(buf)) {
1445         case IMAGE_FORMAT_FIT:
1446                 conf_noffset = fit_conf_get_node(buf, images->fit_uname_cfg);
1447
1448                 uname = fdt_stringlist_get(buf, conf_noffset, FIT_FPGA_PROP, 0,
1449                                            NULL);
1450                 if (!uname) {
1451                         debug("## FPGA image is not specified\n");
1452                         return 0;
1453                 }
1454                 fit_img_result = fit_image_load(images,
1455                                                 tmp_img_addr,
1456                                                 (const char **)&uname,
1457                                                 &(images->fit_uname_cfg),
1458                                                 arch,
1459                                                 IH_TYPE_FPGA,
1460                                                 BOOTSTAGE_ID_FPGA_INIT,
1461                                                 FIT_LOAD_OPTIONAL_NON_ZERO,
1462                                                 &img_data, &img_len);
1463
1464                 debug("FPGA image (%s) loaded to 0x%lx/size 0x%lx\n",
1465                       uname, img_data, img_len);
1466
1467                 if (fit_img_result < 0) {
1468                         /* Something went wrong! */
1469                         return fit_img_result;
1470                 }
1471
1472                 if (!fpga_is_partial_data(devnum, img_len)) {
1473                         name = "full";
1474                         err = fpga_loadbitstream(devnum, (char *)img_data,
1475                                                  img_len, BIT_FULL);
1476                         if (err)
1477                                 err = fpga_load(devnum, (const void *)img_data,
1478                                                 img_len, BIT_FULL);
1479                 } else {
1480                         name = "partial";
1481                         err = fpga_loadbitstream(devnum, (char *)img_data,
1482                                                  img_len, BIT_PARTIAL);
1483                         if (err)
1484                                 err = fpga_load(devnum, (const void *)img_data,
1485                                                 img_len, BIT_PARTIAL);
1486                 }
1487
1488                 if (err)
1489                         return err;
1490
1491                 printf("   Programming %s bitstream... OK\n", name);
1492                 break;
1493         default:
1494                 printf("The given image format is not supported (corrupt?)\n");
1495                 return 1;
1496         }
1497
1498         return 0;
1499 }
1500 #endif
1501
1502 static void fit_loadable_process(uint8_t img_type,
1503                                  ulong img_data,
1504                                  ulong img_len)
1505 {
1506         int i;
1507         const unsigned int count =
1508                         ll_entry_count(struct fit_loadable_tbl, fit_loadable);
1509         struct fit_loadable_tbl *fit_loadable_handler =
1510                         ll_entry_start(struct fit_loadable_tbl, fit_loadable);
1511         /* For each loadable handler */
1512         for (i = 0; i < count; i++, fit_loadable_handler++)
1513                 /* matching this type */
1514                 if (fit_loadable_handler->type == img_type)
1515                         /* call that handler with this image data */
1516                         fit_loadable_handler->handler(img_data, img_len);
1517 }
1518
1519 int boot_get_loadable(int argc, char *const argv[], bootm_headers_t *images,
1520                       uint8_t arch, const ulong *ld_start, ulong * const ld_len)
1521 {
1522         /*
1523          * These variables are used to hold the current image location
1524          * in system memory.
1525          */
1526         ulong tmp_img_addr;
1527         /*
1528          * These two variables are requirements for fit_image_load, but
1529          * their values are not used
1530          */
1531         ulong img_data, img_len;
1532         void *buf;
1533         int loadables_index;
1534         int conf_noffset;
1535         int fit_img_result;
1536         const char *uname;
1537         uint8_t img_type;
1538
1539         /* Check to see if the images struct has a FIT configuration */
1540         if (!genimg_has_config(images)) {
1541                 debug("## FIT configuration was not specified\n");
1542                 return 0;
1543         }
1544
1545         /*
1546          * Obtain the os FIT header from the images struct
1547          */
1548         tmp_img_addr = map_to_sysmem(images->fit_hdr_os);
1549         buf = map_sysmem(tmp_img_addr, 0);
1550         /*
1551          * Check image type. For FIT images get FIT node
1552          * and attempt to locate a generic binary.
1553          */
1554         switch (genimg_get_format(buf)) {
1555         case IMAGE_FORMAT_FIT:
1556                 conf_noffset = fit_conf_get_node(buf, images->fit_uname_cfg);
1557
1558                 for (loadables_index = 0;
1559                      uname = fdt_stringlist_get(buf, conf_noffset,
1560                                         FIT_LOADABLE_PROP, loadables_index,
1561                                         NULL), uname;
1562                      loadables_index++)
1563                 {
1564                         fit_img_result = fit_image_load(images,
1565                                 tmp_img_addr,
1566                                 &uname,
1567                                 &(images->fit_uname_cfg), arch,
1568                                 IH_TYPE_LOADABLE,
1569                                 BOOTSTAGE_ID_FIT_LOADABLE_START,
1570                                 FIT_LOAD_OPTIONAL_NON_ZERO,
1571                                 &img_data, &img_len);
1572                         if (fit_img_result < 0) {
1573                                 /* Something went wrong! */
1574                                 return fit_img_result;
1575                         }
1576
1577                         fit_img_result = fit_image_get_node(buf, uname);
1578                         if (fit_img_result < 0) {
1579                                 /* Something went wrong! */
1580                                 return fit_img_result;
1581                         }
1582                         fit_img_result = fit_image_get_type(buf,
1583                                                             fit_img_result,
1584                                                             &img_type);
1585                         if (fit_img_result < 0) {
1586                                 /* Something went wrong! */
1587                                 return fit_img_result;
1588                         }
1589
1590                         fit_loadable_process(img_type, img_data, img_len);
1591                 }
1592                 break;
1593         default:
1594                 printf("The given image format is not supported (corrupt?)\n");
1595                 return 1;
1596         }
1597
1598         return 0;
1599 }
1600 #endif
1601
1602 #ifdef CONFIG_SYS_BOOT_GET_CMDLINE
1603 /**
1604  * boot_get_cmdline - allocate and initialize kernel cmdline
1605  * @lmb: pointer to lmb handle, will be used for memory mgmt
1606  * @cmd_start: pointer to a ulong variable, will hold cmdline start
1607  * @cmd_end: pointer to a ulong variable, will hold cmdline end
1608  *
1609  * boot_get_cmdline() allocates space for kernel command line below
1610  * BOOTMAPSZ + env_get_bootm_low() address. If "bootargs" U-Boot environment
1611  * variable is present its contents is copied to allocated kernel
1612  * command line.
1613  *
1614  * returns:
1615  *      0 - success
1616  *     -1 - failure
1617  */
1618 int boot_get_cmdline(struct lmb *lmb, ulong *cmd_start, ulong *cmd_end)
1619 {
1620         char *cmdline;
1621         char *s;
1622
1623         cmdline = (char *)(ulong)lmb_alloc_base(lmb, CONFIG_SYS_BARGSIZE, 0xf,
1624                                 env_get_bootm_mapsize() + env_get_bootm_low());
1625
1626         if (cmdline == NULL)
1627                 return -1;
1628
1629         s = env_get("bootargs");
1630         if (!s)
1631                 s = "";
1632
1633         strcpy(cmdline, s);
1634
1635         *cmd_start = (ulong) & cmdline[0];
1636         *cmd_end = *cmd_start + strlen(cmdline);
1637
1638         debug("## cmdline at 0x%08lx ... 0x%08lx\n", *cmd_start, *cmd_end);
1639
1640         return 0;
1641 }
1642 #endif /* CONFIG_SYS_BOOT_GET_CMDLINE */
1643
1644 #ifdef CONFIG_SYS_BOOT_GET_KBD
1645 /**
1646  * boot_get_kbd - allocate and initialize kernel copy of board info
1647  * @lmb: pointer to lmb handle, will be used for memory mgmt
1648  * @kbd: double pointer to board info data
1649  *
1650  * boot_get_kbd() allocates space for kernel copy of board info data below
1651  * BOOTMAPSZ + env_get_bootm_low() address and kernel board info is initialized
1652  * with the current u-boot board info data.
1653  *
1654  * returns:
1655  *      0 - success
1656  *     -1 - failure
1657  */
1658 int boot_get_kbd(struct lmb *lmb, struct bd_info **kbd)
1659 {
1660         *kbd = (struct bd_info *)(ulong)lmb_alloc_base(lmb,
1661                                                        sizeof(struct bd_info),
1662                                                        0xf,
1663                                                        env_get_bootm_mapsize() + env_get_bootm_low());
1664         if (*kbd == NULL)
1665                 return -1;
1666
1667         **kbd = *(gd->bd);
1668
1669         debug("## kernel board info at 0x%08lx\n", (ulong)*kbd);
1670
1671 #if defined(DEBUG) && defined(CONFIG_CMD_BDI)
1672         do_bdinfo(NULL, 0, 0, NULL);
1673 #endif
1674
1675         return 0;
1676 }
1677 #endif /* CONFIG_SYS_BOOT_GET_KBD */
1678
1679 #ifdef CONFIG_LMB
1680 int image_setup_linux(bootm_headers_t *images)
1681 {
1682         ulong of_size = images->ft_len;
1683         char **of_flat_tree = &images->ft_addr;
1684         struct lmb *lmb = &images->lmb;
1685         int ret;
1686
1687         if (IMAGE_ENABLE_OF_LIBFDT)
1688                 boot_fdt_add_mem_rsv_regions(lmb, *of_flat_tree);
1689
1690         if (IMAGE_BOOT_GET_CMDLINE) {
1691                 ret = boot_get_cmdline(lmb, &images->cmdline_start,
1692                                 &images->cmdline_end);
1693                 if (ret) {
1694                         puts("ERROR with allocation of cmdline\n");
1695                         return ret;
1696                 }
1697         }
1698
1699         if (IMAGE_ENABLE_OF_LIBFDT) {
1700                 ret = boot_relocate_fdt(lmb, of_flat_tree, &of_size);
1701                 if (ret)
1702                         return ret;
1703         }
1704
1705         if (IMAGE_ENABLE_OF_LIBFDT && of_size) {
1706                 ret = image_setup_libfdt(images, *of_flat_tree, of_size, lmb);
1707                 if (ret)
1708                         return ret;
1709         }
1710
1711         return 0;
1712 }
1713 #endif /* CONFIG_LMB */
1714 #endif /* !USE_HOSTCC */