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