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