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