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