e1e4148e4c8e036cb73dcf5daf33ad70980a260a
[platform/kernel/u-boot.git] / include / image.h
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 /*
3  * (C) Copyright 2008 Semihalf
4  *
5  * (C) Copyright 2000-2005
6  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
7  ********************************************************************
8  * NOTE: This header file defines an interface to U-Boot. Including
9  * this (unmodified) header file in another file is considered normal
10  * use of U-Boot, and does *not* fall under the heading of "derived
11  * work".
12  ********************************************************************
13  */
14
15 #ifndef __IMAGE_H__
16 #define __IMAGE_H__
17
18 #include "compiler.h"
19 #include <asm/byteorder.h>
20 #include <stdbool.h>
21
22 /* Define this to avoid #ifdefs later on */
23 struct lmb;
24 struct fdt_region;
25
26 #ifdef USE_HOSTCC
27 #include <sys/types.h>
28 #include <linux/kconfig.h>
29
30 #define IMAGE_ENABLE_IGNORE     0
31 #define IMAGE_INDENT_STRING     ""
32
33 #else
34
35 #include <lmb.h>
36 #include <asm/u-boot.h>
37 #include <command.h>
38 #include <linker_lists.h>
39
40 /* Take notice of the 'ignore' property for hashes */
41 #define IMAGE_ENABLE_IGNORE     1
42 #define IMAGE_INDENT_STRING     "   "
43
44 #endif /* USE_HOSTCC */
45
46 #if CONFIG_IS_ENABLED(FIT)
47 #include <hash.h>
48 #include <linux/libfdt.h>
49 #include <fdt_support.h>
50 #endif /* FIT */
51
52 #ifdef CONFIG_OF_SYSTEM_SETUP
53 # define IMAGE_OF_SYSTEM_SETUP  1
54 #else
55 # define IMAGE_OF_SYSTEM_SETUP  0
56 #endif
57
58 extern ulong image_load_addr;           /* Default Load Address */
59 extern ulong image_save_addr;           /* Default Save Address */
60 extern ulong image_save_size;           /* Default Save Size */
61
62 /* An invalid size, meaning that the image size is not known */
63 #define IMAGE_SIZE_INVAL        (-1UL)
64
65 enum ih_category {
66         IH_ARCH,
67         IH_COMP,
68         IH_OS,
69         IH_TYPE,
70
71         IH_COUNT,
72 };
73
74 /*
75  * Operating System Codes
76  *
77  * The following are exposed to uImage header.
78  * New IDs *MUST* be appended at the end of the list and *NEVER*
79  * inserted for backward compatibility.
80  */
81 enum {
82         IH_OS_INVALID           = 0,    /* Invalid OS   */
83         IH_OS_OPENBSD,                  /* OpenBSD      */
84         IH_OS_NETBSD,                   /* NetBSD       */
85         IH_OS_FREEBSD,                  /* FreeBSD      */
86         IH_OS_4_4BSD,                   /* 4.4BSD       */
87         IH_OS_LINUX,                    /* Linux        */
88         IH_OS_SVR4,                     /* SVR4         */
89         IH_OS_ESIX,                     /* Esix         */
90         IH_OS_SOLARIS,                  /* Solaris      */
91         IH_OS_IRIX,                     /* Irix         */
92         IH_OS_SCO,                      /* SCO          */
93         IH_OS_DELL,                     /* Dell         */
94         IH_OS_NCR,                      /* NCR          */
95         IH_OS_LYNXOS,                   /* LynxOS       */
96         IH_OS_VXWORKS,                  /* VxWorks      */
97         IH_OS_PSOS,                     /* pSOS         */
98         IH_OS_QNX,                      /* QNX          */
99         IH_OS_U_BOOT,                   /* Firmware     */
100         IH_OS_RTEMS,                    /* RTEMS        */
101         IH_OS_ARTOS,                    /* ARTOS        */
102         IH_OS_UNITY,                    /* Unity OS     */
103         IH_OS_INTEGRITY,                /* INTEGRITY    */
104         IH_OS_OSE,                      /* OSE          */
105         IH_OS_PLAN9,                    /* Plan 9       */
106         IH_OS_OPENRTOS,         /* OpenRTOS     */
107         IH_OS_ARM_TRUSTED_FIRMWARE,     /* ARM Trusted Firmware */
108         IH_OS_TEE,                      /* Trusted Execution Environment */
109         IH_OS_OPENSBI,                  /* RISC-V OpenSBI */
110         IH_OS_EFI,                      /* EFI Firmware (e.g. GRUB2) */
111
112         IH_OS_COUNT,
113 };
114
115 /*
116  * CPU Architecture Codes (supported by Linux)
117  *
118  * The following are exposed to uImage header.
119  * New IDs *MUST* be appended at the end of the list and *NEVER*
120  * inserted for backward compatibility.
121  */
122 enum {
123         IH_ARCH_INVALID         = 0,    /* Invalid CPU  */
124         IH_ARCH_ALPHA,                  /* Alpha        */
125         IH_ARCH_ARM,                    /* ARM          */
126         IH_ARCH_I386,                   /* Intel x86    */
127         IH_ARCH_IA64,                   /* IA64         */
128         IH_ARCH_MIPS,                   /* MIPS         */
129         IH_ARCH_MIPS64,                 /* MIPS  64 Bit */
130         IH_ARCH_PPC,                    /* PowerPC      */
131         IH_ARCH_S390,                   /* IBM S390     */
132         IH_ARCH_SH,                     /* SuperH       */
133         IH_ARCH_SPARC,                  /* Sparc        */
134         IH_ARCH_SPARC64,                /* Sparc 64 Bit */
135         IH_ARCH_M68K,                   /* M68K         */
136         IH_ARCH_NIOS,                   /* Nios-32      */
137         IH_ARCH_MICROBLAZE,             /* MicroBlaze   */
138         IH_ARCH_NIOS2,                  /* Nios-II      */
139         IH_ARCH_BLACKFIN,               /* Blackfin     */
140         IH_ARCH_AVR32,                  /* AVR32        */
141         IH_ARCH_ST200,                  /* STMicroelectronics ST200  */
142         IH_ARCH_SANDBOX,                /* Sandbox architecture (test only) */
143         IH_ARCH_NDS32,                  /* ANDES Technology - NDS32  */
144         IH_ARCH_OPENRISC,               /* OpenRISC 1000  */
145         IH_ARCH_ARM64,                  /* ARM64        */
146         IH_ARCH_ARC,                    /* Synopsys DesignWare ARC */
147         IH_ARCH_X86_64,                 /* AMD x86_64, Intel and Via */
148         IH_ARCH_XTENSA,                 /* Xtensa       */
149         IH_ARCH_RISCV,                  /* RISC-V */
150
151         IH_ARCH_COUNT,
152 };
153
154 /*
155  * Image Types
156  *
157  * "Standalone Programs" are directly runnable in the environment
158  *      provided by U-Boot; it is expected that (if they behave
159  *      well) you can continue to work in U-Boot after return from
160  *      the Standalone Program.
161  * "OS Kernel Images" are usually images of some Embedded OS which
162  *      will take over control completely. Usually these programs
163  *      will install their own set of exception handlers, device
164  *      drivers, set up the MMU, etc. - this means, that you cannot
165  *      expect to re-enter U-Boot except by resetting the CPU.
166  * "RAMDisk Images" are more or less just data blocks, and their
167  *      parameters (address, size) are passed to an OS kernel that is
168  *      being started.
169  * "Multi-File Images" contain several images, typically an OS
170  *      (Linux) kernel image and one or more data images like
171  *      RAMDisks. This construct is useful for instance when you want
172  *      to boot over the network using BOOTP etc., where the boot
173  *      server provides just a single image file, but you want to get
174  *      for instance an OS kernel and a RAMDisk image.
175  *
176  *      "Multi-File Images" start with a list of image sizes, each
177  *      image size (in bytes) specified by an "uint32_t" in network
178  *      byte order. This list is terminated by an "(uint32_t)0".
179  *      Immediately after the terminating 0 follow the images, one by
180  *      one, all aligned on "uint32_t" boundaries (size rounded up to
181  *      a multiple of 4 bytes - except for the last file).
182  *
183  * "Firmware Images" are binary images containing firmware (like
184  *      U-Boot or FPGA images) which usually will be programmed to
185  *      flash memory.
186  *
187  * "Script files" are command sequences that will be executed by
188  *      U-Boot's command interpreter; this feature is especially
189  *      useful when you configure U-Boot to use a real shell (hush)
190  *      as command interpreter (=> Shell Scripts).
191  *
192  * The following are exposed to uImage header.
193  * New IDs *MUST* be appended at the end of the list and *NEVER*
194  * inserted for backward compatibility.
195  */
196
197 enum {
198         IH_TYPE_INVALID         = 0,    /* Invalid Image                */
199         IH_TYPE_STANDALONE,             /* Standalone Program           */
200         IH_TYPE_KERNEL,                 /* OS Kernel Image              */
201         IH_TYPE_RAMDISK,                /* RAMDisk Image                */
202         IH_TYPE_MULTI,                  /* Multi-File Image             */
203         IH_TYPE_FIRMWARE,               /* Firmware Image               */
204         IH_TYPE_SCRIPT,                 /* Script file                  */
205         IH_TYPE_FILESYSTEM,             /* Filesystem Image (any type)  */
206         IH_TYPE_FLATDT,                 /* Binary Flat Device Tree Blob */
207         IH_TYPE_KWBIMAGE,               /* Kirkwood Boot Image          */
208         IH_TYPE_IMXIMAGE,               /* Freescale IMXBoot Image      */
209         IH_TYPE_UBLIMAGE,               /* Davinci UBL Image            */
210         IH_TYPE_OMAPIMAGE,              /* TI OMAP Config Header Image  */
211         IH_TYPE_AISIMAGE,               /* TI Davinci AIS Image         */
212         /* OS Kernel Image, can run from any load address */
213         IH_TYPE_KERNEL_NOLOAD,
214         IH_TYPE_PBLIMAGE,               /* Freescale PBL Boot Image     */
215         IH_TYPE_MXSIMAGE,               /* Freescale MXSBoot Image      */
216         IH_TYPE_GPIMAGE,                /* TI Keystone GPHeader Image   */
217         IH_TYPE_ATMELIMAGE,             /* ATMEL ROM bootable Image     */
218         IH_TYPE_SOCFPGAIMAGE,           /* Altera SOCFPGA CV/AV Preloader */
219         IH_TYPE_X86_SETUP,              /* x86 setup.bin Image          */
220         IH_TYPE_LPC32XXIMAGE,           /* x86 setup.bin Image          */
221         IH_TYPE_LOADABLE,               /* A list of typeless images    */
222         IH_TYPE_RKIMAGE,                /* Rockchip Boot Image          */
223         IH_TYPE_RKSD,                   /* Rockchip SD card             */
224         IH_TYPE_RKSPI,                  /* Rockchip SPI image           */
225         IH_TYPE_ZYNQIMAGE,              /* Xilinx Zynq Boot Image */
226         IH_TYPE_ZYNQMPIMAGE,            /* Xilinx ZynqMP Boot Image */
227         IH_TYPE_ZYNQMPBIF,              /* Xilinx ZynqMP Boot Image (bif) */
228         IH_TYPE_FPGA,                   /* FPGA Image */
229         IH_TYPE_VYBRIDIMAGE,    /* VYBRID .vyb Image */
230         IH_TYPE_TEE,            /* Trusted Execution Environment OS Image */
231         IH_TYPE_FIRMWARE_IVT,           /* Firmware Image with HABv4 IVT */
232         IH_TYPE_PMMC,            /* TI Power Management Micro-Controller Firmware */
233         IH_TYPE_STM32IMAGE,             /* STMicroelectronics STM32 Image */
234         IH_TYPE_SOCFPGAIMAGE_V1,        /* Altera SOCFPGA A10 Preloader */
235         IH_TYPE_MTKIMAGE,               /* MediaTek BootROM loadable Image */
236         IH_TYPE_IMX8MIMAGE,             /* Freescale IMX8MBoot Image    */
237         IH_TYPE_IMX8IMAGE,              /* Freescale IMX8Boot Image     */
238         IH_TYPE_COPRO,                  /* Coprocessor Image for remoteproc*/
239         IH_TYPE_SUNXI_EGON,             /* Allwinner eGON Boot Image */
240
241         IH_TYPE_COUNT,                  /* Number of image types */
242 };
243
244 /*
245  * Compression Types
246  *
247  * The following are exposed to uImage header.
248  * New IDs *MUST* be appended at the end of the list and *NEVER*
249  * inserted for backward compatibility.
250  */
251 enum {
252         IH_COMP_NONE            = 0,    /*  No   Compression Used       */
253         IH_COMP_GZIP,                   /* gzip  Compression Used       */
254         IH_COMP_BZIP2,                  /* bzip2 Compression Used       */
255         IH_COMP_LZMA,                   /* lzma  Compression Used       */
256         IH_COMP_LZO,                    /* lzo   Compression Used       */
257         IH_COMP_LZ4,                    /* lz4   Compression Used       */
258         IH_COMP_ZSTD,                   /* zstd   Compression Used      */
259
260         IH_COMP_COUNT,
261 };
262
263 #define LZ4F_MAGIC      0x184D2204      /* LZ4 Magic Number             */
264 #define IH_MAGIC        0x27051956      /* Image Magic Number           */
265 #define IH_NMLEN                32      /* Image Name Length            */
266
267 /* Reused from common.h */
268 #define ROUND(a, b)             (((a) + (b) - 1) & ~((b) - 1))
269
270 /*
271  * Legacy format image header,
272  * all data in network byte order (aka natural aka bigendian).
273  */
274 typedef struct image_header {
275         uint32_t        ih_magic;       /* Image Header Magic Number    */
276         uint32_t        ih_hcrc;        /* Image Header CRC Checksum    */
277         uint32_t        ih_time;        /* Image Creation Timestamp     */
278         uint32_t        ih_size;        /* Image Data Size              */
279         uint32_t        ih_load;        /* Data  Load  Address          */
280         uint32_t        ih_ep;          /* Entry Point Address          */
281         uint32_t        ih_dcrc;        /* Image Data CRC Checksum      */
282         uint8_t         ih_os;          /* Operating System             */
283         uint8_t         ih_arch;        /* CPU architecture             */
284         uint8_t         ih_type;        /* Image Type                   */
285         uint8_t         ih_comp;        /* Compression Type             */
286         uint8_t         ih_name[IH_NMLEN];      /* Image Name           */
287 } image_header_t;
288
289 typedef struct image_info {
290         ulong           start, end;             /* start/end of blob */
291         ulong           image_start, image_len; /* start of image within blob, len of image */
292         ulong           load;                   /* load addr for the image */
293         uint8_t         comp, type, os;         /* compression, type of image, os type */
294         uint8_t         arch;                   /* CPU architecture */
295 } image_info_t;
296
297 /*
298  * Legacy and FIT format headers used by do_bootm() and do_bootm_<os>()
299  * routines.
300  */
301 typedef struct bootm_headers {
302         /*
303          * Legacy os image header, if it is a multi component image
304          * then boot_get_ramdisk() and get_fdt() will attempt to get
305          * data from second and third component accordingly.
306          */
307         image_header_t  *legacy_hdr_os;         /* image header pointer */
308         image_header_t  legacy_hdr_os_copy;     /* header copy */
309         ulong           legacy_hdr_valid;
310
311 #if CONFIG_IS_ENABLED(FIT)
312         const char      *fit_uname_cfg; /* configuration node unit name */
313
314         void            *fit_hdr_os;    /* os FIT image header */
315         const char      *fit_uname_os;  /* os subimage node unit name */
316         int             fit_noffset_os; /* os subimage node offset */
317
318         void            *fit_hdr_rd;    /* init ramdisk FIT image header */
319         const char      *fit_uname_rd;  /* init ramdisk subimage node unit name */
320         int             fit_noffset_rd; /* init ramdisk subimage node offset */
321
322         void            *fit_hdr_fdt;   /* FDT blob FIT image header */
323         const char      *fit_uname_fdt; /* FDT blob subimage node unit name */
324         int             fit_noffset_fdt;/* FDT blob subimage node offset */
325
326         void            *fit_hdr_setup; /* x86 setup FIT image header */
327         const char      *fit_uname_setup; /* x86 setup subimage node name */
328         int             fit_noffset_setup;/* x86 setup subimage node offset */
329 #endif
330
331 #ifndef USE_HOSTCC
332         image_info_t    os;             /* os image info */
333         ulong           ep;             /* entry point of OS */
334
335         ulong           rd_start, rd_end;/* ramdisk start/end */
336
337         char            *ft_addr;       /* flat dev tree address */
338         ulong           ft_len;         /* length of flat device tree */
339
340         ulong           initrd_start;
341         ulong           initrd_end;
342         ulong           cmdline_start;
343         ulong           cmdline_end;
344         struct bd_info          *kbd;
345 #endif
346
347         int             verify;         /* env_get("verify")[0] != 'n' */
348
349 #define BOOTM_STATE_START       (0x00000001)
350 #define BOOTM_STATE_FINDOS      (0x00000002)
351 #define BOOTM_STATE_FINDOTHER   (0x00000004)
352 #define BOOTM_STATE_LOADOS      (0x00000008)
353 #define BOOTM_STATE_RAMDISK     (0x00000010)
354 #define BOOTM_STATE_FDT         (0x00000020)
355 #define BOOTM_STATE_OS_CMDLINE  (0x00000040)
356 #define BOOTM_STATE_OS_BD_T     (0x00000080)
357 #define BOOTM_STATE_OS_PREP     (0x00000100)
358 #define BOOTM_STATE_OS_FAKE_GO  (0x00000200)    /* 'Almost' run the OS */
359 #define BOOTM_STATE_OS_GO       (0x00000400)
360         int             state;
361
362 #if defined(CONFIG_LMB) && !defined(USE_HOSTCC)
363         struct lmb      lmb;            /* for memory mgmt */
364 #endif
365 } bootm_headers_t;
366
367 extern bootm_headers_t images;
368
369 /*
370  * Some systems (for example LWMON) have very short watchdog periods;
371  * we must make sure to split long operations like memmove() or
372  * checksum calculations into reasonable chunks.
373  */
374 #ifndef CHUNKSZ
375 #define CHUNKSZ (64 * 1024)
376 #endif
377
378 #ifndef CHUNKSZ_CRC32
379 #define CHUNKSZ_CRC32 (64 * 1024)
380 #endif
381
382 #ifndef CHUNKSZ_MD5
383 #define CHUNKSZ_MD5 (64 * 1024)
384 #endif
385
386 #ifndef CHUNKSZ_SHA1
387 #define CHUNKSZ_SHA1 (64 * 1024)
388 #endif
389
390 #define uimage_to_cpu(x)                be32_to_cpu(x)
391 #define cpu_to_uimage(x)                cpu_to_be32(x)
392
393 /*
394  * Translation table for entries of a specific type; used by
395  * get_table_entry_id() and get_table_entry_name().
396  */
397 typedef struct table_entry {
398         int     id;
399         char    *sname;         /* short (input) name to find table entry */
400         char    *lname;         /* long (output) name to print for messages */
401 } table_entry_t;
402
403 /*
404  * Compression type and magic number mapping table.
405  */
406 struct comp_magic_map {
407         int             comp_id;
408         const char      *name;
409         unsigned char   magic[2];
410 };
411
412 /*
413  * get_table_entry_id() scans the translation table trying to find an
414  * entry that matches the given short name. If a matching entry is
415  * found, it's id is returned to the caller.
416  */
417 int get_table_entry_id(const table_entry_t *table,
418                 const char *table_name, const char *name);
419 /*
420  * get_table_entry_name() scans the translation table trying to find
421  * an entry that matches the given id. If a matching entry is found,
422  * its long name is returned to the caller.
423  */
424 char *get_table_entry_name(const table_entry_t *table, char *msg, int id);
425
426 const char *genimg_get_os_name(uint8_t os);
427
428 /**
429  * genimg_get_os_short_name() - get the short name for an OS
430  *
431  * @param os    OS (IH_OS_...)
432  * @return OS short name, or "unknown" if unknown
433  */
434 const char *genimg_get_os_short_name(uint8_t comp);
435
436 const char *genimg_get_arch_name(uint8_t arch);
437
438 /**
439  * genimg_get_arch_short_name() - get the short name for an architecture
440  *
441  * @param arch  Architecture type (IH_ARCH_...)
442  * @return architecture short name, or "unknown" if unknown
443  */
444 const char *genimg_get_arch_short_name(uint8_t arch);
445
446 const char *genimg_get_type_name(uint8_t type);
447
448 /**
449  * genimg_get_type_short_name() - get the short name for an image type
450  *
451  * @param type  Image type (IH_TYPE_...)
452  * @return image short name, or "unknown" if unknown
453  */
454 const char *genimg_get_type_short_name(uint8_t type);
455
456 const char *genimg_get_comp_name(uint8_t comp);
457
458 /**
459  * genimg_get_comp_short_name() - get the short name for a compression method
460  *
461  * @param comp  compression method (IH_COMP_...)
462  * @return compression method short name, or "unknown" if unknown
463  */
464 const char *genimg_get_comp_short_name(uint8_t comp);
465
466 /**
467  * genimg_get_cat_name() - Get the name of an item in a category
468  *
469  * @category:   Category of item
470  * @id:         Item ID
471  * @return name of item, or "Unknown ..." if unknown
472  */
473 const char *genimg_get_cat_name(enum ih_category category, uint id);
474
475 /**
476  * genimg_get_cat_short_name() - Get the short name of an item in a category
477  *
478  * @category:   Category of item
479  * @id:         Item ID
480  * @return short name of item, or "Unknown ..." if unknown
481  */
482 const char *genimg_get_cat_short_name(enum ih_category category, uint id);
483
484 /**
485  * genimg_get_cat_count() - Get the number of items in a category
486  *
487  * @category:   Category to check
488  * @return the number of items in the category (IH_xxx_COUNT)
489  */
490 int genimg_get_cat_count(enum ih_category category);
491
492 /**
493  * genimg_get_cat_desc() - Get the description of a category
494  *
495  * @category:   Category to check
496  * @return the description of a category, e.g. "architecture". This
497  * effectively converts the enum to a string.
498  */
499 const char *genimg_get_cat_desc(enum ih_category category);
500
501 /**
502  * genimg_cat_has_id() - Check whether a category has an item
503  *
504  * @category:   Category to check
505  * @id:         Item ID
506  * @return true or false as to whether a category has an item
507  */
508 bool genimg_cat_has_id(enum ih_category category, uint id);
509
510 int genimg_get_os_id(const char *name);
511 int genimg_get_arch_id(const char *name);
512 int genimg_get_type_id(const char *name);
513 int genimg_get_comp_id(const char *name);
514 void genimg_print_size(uint32_t size);
515
516 #if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || \
517         defined(USE_HOSTCC)
518 #define IMAGE_ENABLE_TIMESTAMP 1
519 #else
520 #define IMAGE_ENABLE_TIMESTAMP 0
521 #endif
522 void genimg_print_time(time_t timestamp);
523
524 /* What to do with a image load address ('load = <> 'in the FIT) */
525 enum fit_load_op {
526         FIT_LOAD_IGNORED,       /* Ignore load address */
527         FIT_LOAD_OPTIONAL,      /* Can be provided, but optional */
528         FIT_LOAD_OPTIONAL_NON_ZERO,     /* Optional, a value of 0 is ignored */
529         FIT_LOAD_REQUIRED,      /* Must be provided */
530 };
531
532 int boot_get_setup(bootm_headers_t *images, uint8_t arch, ulong *setup_start,
533                    ulong *setup_len);
534
535 #ifndef USE_HOSTCC
536 /* Image format types, returned by _get_format() routine */
537 #define IMAGE_FORMAT_INVALID    0x00
538 #if defined(CONFIG_LEGACY_IMAGE_FORMAT)
539 #define IMAGE_FORMAT_LEGACY     0x01    /* legacy image_header based format */
540 #endif
541 #define IMAGE_FORMAT_FIT        0x02    /* new, libfdt based format */
542 #define IMAGE_FORMAT_ANDROID    0x03    /* Android boot image */
543
544 ulong genimg_get_kernel_addr_fit(char * const img_addr,
545                                  const char **fit_uname_config,
546                                  const char **fit_uname_kernel);
547 ulong genimg_get_kernel_addr(char * const img_addr);
548 int genimg_get_format(const void *img_addr);
549 int genimg_has_config(bootm_headers_t *images);
550
551 int boot_get_fpga(int argc, char *const argv[], bootm_headers_t *images,
552                   uint8_t arch, const ulong *ld_start, ulong * const ld_len);
553 int boot_get_ramdisk(int argc, char *const argv[], bootm_headers_t *images,
554                      uint8_t arch, ulong *rd_start, ulong *rd_end);
555
556 /**
557  * boot_get_loadable - routine to load a list of binaries to memory
558  * @argc: Ignored Argument
559  * @argv: Ignored Argument
560  * @images: pointer to the bootm images structure
561  * @arch: expected architecture for the image
562  * @ld_start: Ignored Argument
563  * @ld_len: Ignored Argument
564  *
565  * boot_get_loadable() will take the given FIT configuration, and look
566  * for a field named "loadables".  Loadables, is a list of elements in
567  * the FIT given as strings.  exe:
568  *   loadables = "linux_kernel", "fdt-2";
569  * this function will attempt to parse each string, and load the
570  * corresponding element from the FIT into memory.  Once placed,
571  * no aditional actions are taken.
572  *
573  * @return:
574  *     0, if only valid images or no images are found
575  *     error code, if an error occurs during fit_image_load
576  */
577 int boot_get_loadable(int argc, char *const argv[], bootm_headers_t *images,
578                       uint8_t arch, const ulong *ld_start, ulong *const ld_len);
579 #endif /* !USE_HOSTCC */
580
581 int boot_get_setup_fit(bootm_headers_t *images, uint8_t arch,
582                        ulong *setup_start, ulong *setup_len);
583
584 /**
585  * boot_get_fdt_fit() - load a DTB from a FIT file (applying overlays)
586  *
587  * This deals with all aspects of loading an DTB from a FIT.
588  * The correct base image based on configuration will be selected, and
589  * then any overlays specified will be applied (as present in fit_uname_configp).
590  *
591  * @param images        Boot images structure
592  * @param addr          Address of FIT in memory
593  * @param fit_unamep    On entry this is the requested image name
594  *                      (e.g. "kernel") or NULL to use the default. On exit
595  *                      points to the selected image name
596  * @param fit_uname_configp     On entry this is the requested configuration
597  *                      name (e.g. "conf-1") or NULL to use the default. On
598  *                      exit points to the selected configuration name.
599  * @param arch          Expected architecture (IH_ARCH_...)
600  * @param datap         Returns address of loaded image
601  * @param lenp          Returns length of loaded image
602  *
603  * @return node offset of base image, or -ve error code on error
604  */
605 int boot_get_fdt_fit(bootm_headers_t *images, ulong addr,
606                    const char **fit_unamep, const char **fit_uname_configp,
607                    int arch, ulong *datap, ulong *lenp);
608
609 /**
610  * fit_image_load() - load an image from a FIT
611  *
612  * This deals with all aspects of loading an image from a FIT, including
613  * selecting the right image based on configuration, verifying it, printing
614  * out progress messages, checking the type/arch/os and optionally copying it
615  * to the right load address.
616  *
617  * The property to look up is defined by image_type.
618  *
619  * @param images        Boot images structure
620  * @param addr          Address of FIT in memory
621  * @param fit_unamep    On entry this is the requested image name
622  *                      (e.g. "kernel") or NULL to use the default. On exit
623  *                      points to the selected image name
624  * @param fit_uname_configp     On entry this is the requested configuration
625  *                      name (e.g. "conf-1") or NULL to use the default. On
626  *                      exit points to the selected configuration name.
627  * @param arch          Expected architecture (IH_ARCH_...)
628  * @param image_type    Required image type (IH_TYPE_...). If this is
629  *                      IH_TYPE_KERNEL then we allow IH_TYPE_KERNEL_NOLOAD
630  *                      also.
631  * @param bootstage_id  ID of starting bootstage to use for progress updates.
632  *                      This will be added to the BOOTSTAGE_SUB values when
633  *                      calling bootstage_mark()
634  * @param load_op       Decribes what to do with the load address
635  * @param datap         Returns address of loaded image
636  * @param lenp          Returns length of loaded image
637  * @return node offset of image, or -ve error code on error
638  */
639 int fit_image_load(bootm_headers_t *images, ulong addr,
640                    const char **fit_unamep, const char **fit_uname_configp,
641                    int arch, int image_type, int bootstage_id,
642                    enum fit_load_op load_op, ulong *datap, ulong *lenp);
643
644 /**
645  * image_source_script() - Execute a script
646  *
647  * Executes a U-Boot script at a particular address in memory. The script should
648  * have a header (FIT or legacy) with the script type (IH_TYPE_SCRIPT).
649  *
650  * @addr: Address of script
651  * @fit_uname: FIT subimage name
652  * @return result code (enum command_ret_t)
653  */
654 int image_source_script(ulong addr, const char *fit_uname);
655
656 #ifndef USE_HOSTCC
657 /**
658  * fit_get_node_from_config() - Look up an image a FIT by type
659  *
660  * This looks in the selected conf- node (images->fit_uname_cfg) for a
661  * particular image type (e.g. "kernel") and then finds the image that is
662  * referred to.
663  *
664  * For example, for something like:
665  *
666  * images {
667  *      kernel {
668  *              ...
669  *      };
670  * };
671  * configurations {
672  *      conf-1 {
673  *              kernel = "kernel";
674  *      };
675  * };
676  *
677  * the function will return the node offset of the kernel@1 node, assuming
678  * that conf-1 is the chosen configuration.
679  *
680  * @param images        Boot images structure
681  * @param prop_name     Property name to look up (FIT_..._PROP)
682  * @param addr          Address of FIT in memory
683  */
684 int fit_get_node_from_config(bootm_headers_t *images, const char *prop_name,
685                         ulong addr);
686
687 int boot_get_fdt(int flag, int argc, char *const argv[], uint8_t arch,
688                  bootm_headers_t *images,
689                  char **of_flat_tree, ulong *of_size);
690 void boot_fdt_add_mem_rsv_regions(struct lmb *lmb, void *fdt_blob);
691 int boot_relocate_fdt(struct lmb *lmb, char **of_flat_tree, ulong *of_size);
692
693 int boot_ramdisk_high(struct lmb *lmb, ulong rd_data, ulong rd_len,
694                   ulong *initrd_start, ulong *initrd_end);
695 int boot_get_cmdline(struct lmb *lmb, ulong *cmd_start, ulong *cmd_end);
696 #ifdef CONFIG_SYS_BOOT_GET_KBD
697 int boot_get_kbd(struct lmb *lmb, struct bd_info **kbd);
698 #endif /* CONFIG_SYS_BOOT_GET_KBD */
699 #endif /* !USE_HOSTCC */
700
701 /*******************************************************************/
702 /* Legacy format specific code (prefixed with image_) */
703 /*******************************************************************/
704 static inline uint32_t image_get_header_size(void)
705 {
706         return (sizeof(image_header_t));
707 }
708
709 #define image_get_hdr_l(f) \
710         static inline uint32_t image_get_##f(const image_header_t *hdr) \
711         { \
712                 return uimage_to_cpu(hdr->ih_##f); \
713         }
714 image_get_hdr_l(magic)          /* image_get_magic */
715 image_get_hdr_l(hcrc)           /* image_get_hcrc */
716 image_get_hdr_l(time)           /* image_get_time */
717 image_get_hdr_l(size)           /* image_get_size */
718 image_get_hdr_l(load)           /* image_get_load */
719 image_get_hdr_l(ep)             /* image_get_ep */
720 image_get_hdr_l(dcrc)           /* image_get_dcrc */
721
722 #define image_get_hdr_b(f) \
723         static inline uint8_t image_get_##f(const image_header_t *hdr) \
724         { \
725                 return hdr->ih_##f; \
726         }
727 image_get_hdr_b(os)             /* image_get_os */
728 image_get_hdr_b(arch)           /* image_get_arch */
729 image_get_hdr_b(type)           /* image_get_type */
730 image_get_hdr_b(comp)           /* image_get_comp */
731
732 static inline char *image_get_name(const image_header_t *hdr)
733 {
734         return (char *)hdr->ih_name;
735 }
736
737 static inline uint32_t image_get_data_size(const image_header_t *hdr)
738 {
739         return image_get_size(hdr);
740 }
741
742 /**
743  * image_get_data - get image payload start address
744  * @hdr: image header
745  *
746  * image_get_data() returns address of the image payload. For single
747  * component images it is image data start. For multi component
748  * images it points to the null terminated table of sub-images sizes.
749  *
750  * returns:
751  *     image payload data start address
752  */
753 static inline ulong image_get_data(const image_header_t *hdr)
754 {
755         return ((ulong)hdr + image_get_header_size());
756 }
757
758 static inline uint32_t image_get_image_size(const image_header_t *hdr)
759 {
760         return (image_get_size(hdr) + image_get_header_size());
761 }
762 static inline ulong image_get_image_end(const image_header_t *hdr)
763 {
764         return ((ulong)hdr + image_get_image_size(hdr));
765 }
766
767 #define image_set_hdr_l(f) \
768         static inline void image_set_##f(image_header_t *hdr, uint32_t val) \
769         { \
770                 hdr->ih_##f = cpu_to_uimage(val); \
771         }
772 image_set_hdr_l(magic)          /* image_set_magic */
773 image_set_hdr_l(hcrc)           /* image_set_hcrc */
774 image_set_hdr_l(time)           /* image_set_time */
775 image_set_hdr_l(size)           /* image_set_size */
776 image_set_hdr_l(load)           /* image_set_load */
777 image_set_hdr_l(ep)             /* image_set_ep */
778 image_set_hdr_l(dcrc)           /* image_set_dcrc */
779
780 #define image_set_hdr_b(f) \
781         static inline void image_set_##f(image_header_t *hdr, uint8_t val) \
782         { \
783                 hdr->ih_##f = val; \
784         }
785 image_set_hdr_b(os)             /* image_set_os */
786 image_set_hdr_b(arch)           /* image_set_arch */
787 image_set_hdr_b(type)           /* image_set_type */
788 image_set_hdr_b(comp)           /* image_set_comp */
789
790 static inline void image_set_name(image_header_t *hdr, const char *name)
791 {
792         strncpy(image_get_name(hdr), name, IH_NMLEN);
793 }
794
795 int image_check_hcrc(const image_header_t *hdr);
796 int image_check_dcrc(const image_header_t *hdr);
797 #ifndef USE_HOSTCC
798 ulong env_get_bootm_low(void);
799 phys_size_t env_get_bootm_size(void);
800 phys_size_t env_get_bootm_mapsize(void);
801 #endif
802 void memmove_wd(void *to, void *from, size_t len, ulong chunksz);
803
804 static inline int image_check_magic(const image_header_t *hdr)
805 {
806         return (image_get_magic(hdr) == IH_MAGIC);
807 }
808 static inline int image_check_type(const image_header_t *hdr, uint8_t type)
809 {
810         return (image_get_type(hdr) == type);
811 }
812 static inline int image_check_arch(const image_header_t *hdr, uint8_t arch)
813 {
814 #ifndef USE_HOSTCC
815         /* Let's assume that sandbox can load any architecture */
816         if (IS_ENABLED(CONFIG_SANDBOX))
817                 return true;
818 #endif
819         return (image_get_arch(hdr) == arch) ||
820                 (image_get_arch(hdr) == IH_ARCH_ARM && arch == IH_ARCH_ARM64);
821 }
822 static inline int image_check_os(const image_header_t *hdr, uint8_t os)
823 {
824         return (image_get_os(hdr) == os);
825 }
826
827 ulong image_multi_count(const image_header_t *hdr);
828 void image_multi_getimg(const image_header_t *hdr, ulong idx,
829                         ulong *data, ulong *len);
830
831 void image_print_contents(const void *hdr);
832
833 #ifndef USE_HOSTCC
834 static inline int image_check_target_arch(const image_header_t *hdr)
835 {
836 #ifndef IH_ARCH_DEFAULT
837 # error "please define IH_ARCH_DEFAULT in your arch asm/u-boot.h"
838 #endif
839         return image_check_arch(hdr, IH_ARCH_DEFAULT);
840 }
841 #endif /* USE_HOSTCC */
842
843 /**
844  * image_decomp_type() - Find out compression type of an image
845  *
846  * @buf:        Address in U-Boot memory where image is loaded.
847  * @len:        Length of the compressed image.
848  * @return      compression type or IH_COMP_NONE if not compressed.
849  *
850  * Note: Only following compression types are supported now.
851  * lzo, lzma, gzip, bzip2
852  */
853 int image_decomp_type(const unsigned char *buf, ulong len);
854
855 /**
856  * image_decomp() - decompress an image
857  *
858  * @comp:       Compression algorithm that is used (IH_COMP_...)
859  * @load:       Destination load address in U-Boot memory
860  * @image_start Image start address (where we are decompressing from)
861  * @type:       OS type (IH_OS_...)
862  * @load_bug:   Place to decompress to
863  * @image_buf:  Address to decompress from
864  * @image_len:  Number of bytes in @image_buf to decompress
865  * @unc_len:    Available space for decompression
866  * @return 0 if OK, -ve on error (BOOTM_ERR_...)
867  */
868 int image_decomp(int comp, ulong load, ulong image_start, int type,
869                  void *load_buf, void *image_buf, ulong image_len,
870                  uint unc_len, ulong *load_end);
871
872 /**
873  * Set up properties in the FDT
874  *
875  * This sets up properties in the FDT that is to be passed to linux.
876  *
877  * @images:     Images information
878  * @blob:       FDT to update
879  * @of_size:    Size of the FDT
880  * @lmb:        Points to logical memory block structure
881  * @return 0 if ok, <0 on failure
882  */
883 int image_setup_libfdt(bootm_headers_t *images, void *blob,
884                        int of_size, struct lmb *lmb);
885
886 /**
887  * Set up the FDT to use for booting a kernel
888  *
889  * This performs ramdisk setup, sets up the FDT if required, and adds
890  * paramters to the FDT if libfdt is available.
891  *
892  * @param images        Images information
893  * @return 0 if ok, <0 on failure
894  */
895 int image_setup_linux(bootm_headers_t *images);
896
897 /**
898  * bootz_setup() - Extract stat and size of a Linux xImage
899  *
900  * @image: Address of image
901  * @start: Returns start address of image
902  * @end : Returns end address of image
903  * @return 0 if OK, 1 if the image was not recognised
904  */
905 int bootz_setup(ulong image, ulong *start, ulong *end);
906
907 /**
908  * Return the correct start address and size of a Linux aarch64 Image.
909  *
910  * @image: Address of image
911  * @start: Returns start address of image
912  * @size : Returns size image
913  * @force_reloc: Ignore image->ep field, always place image to RAM start
914  * @return 0 if OK, 1 if the image was not recognised
915  */
916 int booti_setup(ulong image, ulong *relocated_addr, ulong *size,
917                 bool force_reloc);
918
919 /*******************************************************************/
920 /* New uImage format specific code (prefixed with fit_) */
921 /*******************************************************************/
922
923 #define FIT_IMAGES_PATH         "/images"
924 #define FIT_CONFS_PATH          "/configurations"
925
926 /* hash/signature/key node */
927 #define FIT_HASH_NODENAME       "hash"
928 #define FIT_ALGO_PROP           "algo"
929 #define FIT_VALUE_PROP          "value"
930 #define FIT_IGNORE_PROP         "uboot-ignore"
931 #define FIT_SIG_NODENAME        "signature"
932 #define FIT_KEY_REQUIRED        "required"
933 #define FIT_KEY_HINT            "key-name-hint"
934
935 /* cipher node */
936 #define FIT_CIPHER_NODENAME     "cipher"
937 #define FIT_ALGO_PROP           "algo"
938
939 /* image node */
940 #define FIT_DATA_PROP           "data"
941 #define FIT_DATA_POSITION_PROP  "data-position"
942 #define FIT_DATA_OFFSET_PROP    "data-offset"
943 #define FIT_DATA_SIZE_PROP      "data-size"
944 #define FIT_TIMESTAMP_PROP      "timestamp"
945 #define FIT_DESC_PROP           "description"
946 #define FIT_ARCH_PROP           "arch"
947 #define FIT_TYPE_PROP           "type"
948 #define FIT_OS_PROP             "os"
949 #define FIT_COMP_PROP           "compression"
950 #define FIT_ENTRY_PROP          "entry"
951 #define FIT_LOAD_PROP           "load"
952
953 /* configuration node */
954 #define FIT_KERNEL_PROP         "kernel"
955 #define FIT_RAMDISK_PROP        "ramdisk"
956 #define FIT_FDT_PROP            "fdt"
957 #define FIT_LOADABLE_PROP       "loadables"
958 #define FIT_DEFAULT_PROP        "default"
959 #define FIT_SETUP_PROP          "setup"
960 #define FIT_FPGA_PROP           "fpga"
961 #define FIT_FIRMWARE_PROP       "firmware"
962 #define FIT_STANDALONE_PROP     "standalone"
963
964 #define FIT_MAX_HASH_LEN        HASH_MAX_DIGEST_SIZE
965
966 #if CONFIG_IS_ENABLED(FIT)
967 /* cmdline argument format parsing */
968 int fit_parse_conf(const char *spec, ulong addr_curr,
969                 ulong *addr, const char **conf_name);
970 int fit_parse_subimage(const char *spec, ulong addr_curr,
971                 ulong *addr, const char **image_name);
972
973 int fit_get_subimage_count(const void *fit, int images_noffset);
974 void fit_print_contents(const void *fit);
975 void fit_image_print(const void *fit, int noffset, const char *p);
976
977 /**
978  * fit_get_end - get FIT image size
979  * @fit: pointer to the FIT format image header
980  *
981  * returns:
982  *     size of the FIT image (blob) in memory
983  */
984 static inline ulong fit_get_size(const void *fit)
985 {
986         return fdt_totalsize(fit);
987 }
988
989 /**
990  * fit_get_end - get FIT image end
991  * @fit: pointer to the FIT format image header
992  *
993  * returns:
994  *     end address of the FIT image (blob) in memory
995  */
996 ulong fit_get_end(const void *fit);
997
998 /**
999  * fit_get_name - get FIT node name
1000  * @fit: pointer to the FIT format image header
1001  *
1002  * returns:
1003  *     NULL, on error
1004  *     pointer to node name, on success
1005  */
1006 static inline const char *fit_get_name(const void *fit_hdr,
1007                 int noffset, int *len)
1008 {
1009         return fdt_get_name(fit_hdr, noffset, len);
1010 }
1011
1012 int fit_get_desc(const void *fit, int noffset, char **desc);
1013 int fit_get_timestamp(const void *fit, int noffset, time_t *timestamp);
1014
1015 int fit_image_get_node(const void *fit, const char *image_uname);
1016 int fit_image_get_os(const void *fit, int noffset, uint8_t *os);
1017 int fit_image_get_arch(const void *fit, int noffset, uint8_t *arch);
1018 int fit_image_get_type(const void *fit, int noffset, uint8_t *type);
1019 int fit_image_get_comp(const void *fit, int noffset, uint8_t *comp);
1020 int fit_image_get_load(const void *fit, int noffset, ulong *load);
1021 int fit_image_get_entry(const void *fit, int noffset, ulong *entry);
1022 int fit_image_get_data(const void *fit, int noffset,
1023                                 const void **data, size_t *size);
1024 int fit_image_get_data_offset(const void *fit, int noffset, int *data_offset);
1025 int fit_image_get_data_position(const void *fit, int noffset,
1026                                 int *data_position);
1027 int fit_image_get_data_size(const void *fit, int noffset, int *data_size);
1028 int fit_image_get_data_size_unciphered(const void *fit, int noffset,
1029                                        size_t *data_size);
1030 int fit_image_get_data_and_size(const void *fit, int noffset,
1031                                 const void **data, size_t *size);
1032
1033 int fit_image_hash_get_algo(const void *fit, int noffset, char **algo);
1034 int fit_image_hash_get_value(const void *fit, int noffset, uint8_t **value,
1035                                 int *value_len);
1036
1037 int fit_set_timestamp(void *fit, int noffset, time_t timestamp);
1038
1039 int fit_cipher_data(const char *keydir, void *keydest, void *fit,
1040                     const char *comment, int require_keys,
1041                     const char *engine_id, const char *cmdname);
1042
1043 /**
1044  * fit_add_verification_data() - add verification data to FIT image nodes
1045  *
1046  * @keydir:     Directory containing keys
1047  * @kwydest:    FDT blob to write public key information to
1048  * @fit:        Pointer to the FIT format image header
1049  * @comment:    Comment to add to signature nodes
1050  * @require_keys: Mark all keys as 'required'
1051  * @engine_id:  Engine to use for signing
1052  * @cmdname:    Command name used when reporting errors
1053  *
1054  * Adds hash values for all component images in the FIT blob.
1055  * Hashes are calculated for all component images which have hash subnodes
1056  * with algorithm property set to one of the supported hash algorithms.
1057  *
1058  * Also add signatures if signature nodes are present.
1059  *
1060  * returns
1061  *     0, on success
1062  *     libfdt error code, on failure
1063  */
1064 int fit_add_verification_data(const char *keydir, const char *keyfile,
1065                               void *keydest, void *fit, const char *comment,
1066                               int require_keys, const char *engine_id,
1067                               const char *cmdname);
1068
1069 int fit_image_verify_with_data(const void *fit, int image_noffset,
1070                                const void *data, size_t size);
1071 int fit_image_verify(const void *fit, int noffset);
1072 int fit_config_verify(const void *fit, int conf_noffset);
1073 int fit_all_image_verify(const void *fit);
1074 int fit_config_decrypt(const void *fit, int conf_noffset);
1075 int fit_image_check_os(const void *fit, int noffset, uint8_t os);
1076 int fit_image_check_arch(const void *fit, int noffset, uint8_t arch);
1077 int fit_image_check_type(const void *fit, int noffset, uint8_t type);
1078 int fit_image_check_comp(const void *fit, int noffset, uint8_t comp);
1079
1080 /**
1081  * fit_check_format() - Check that the FIT is valid
1082  *
1083  * This performs various checks on the FIT to make sure it is suitable for
1084  * use, looking for mandatory properties, nodes, etc.
1085  *
1086  * If FIT_FULL_CHECK is enabled, it also runs it through libfdt to make
1087  * sure that there are no strange tags or broken nodes in the FIT.
1088  *
1089  * @fit: pointer to the FIT format image header
1090  * @return 0 if OK, -ENOEXEC if not an FDT file, -EINVAL if the full FDT check
1091  *      failed (e.g. due to bad structure), -ENOMSG if the description is
1092  *      missing, -EBADMSG if the timestamp is missing, -ENOENT if the /images
1093  *      path is missing
1094  */
1095 int fit_check_format(const void *fit, ulong size);
1096
1097 int fit_conf_find_compat(const void *fit, const void *fdt);
1098
1099 /**
1100  * fit_conf_get_node - get node offset for configuration of a given unit name
1101  * @fit: pointer to the FIT format image header
1102  * @conf_uname: configuration node unit name (NULL to use default)
1103  *
1104  * fit_conf_get_node() finds a configuration (within the '/configurations'
1105  * parent node) of a provided unit name. If configuration is found its node
1106  * offset is returned to the caller.
1107  *
1108  * When NULL is provided in second argument fit_conf_get_node() will search
1109  * for a default configuration node instead. Default configuration node unit
1110  * name is retrieved from FIT_DEFAULT_PROP property of the '/configurations'
1111  * node.
1112  *
1113  * returns:
1114  *     configuration node offset when found (>=0)
1115  *     negative number on failure (FDT_ERR_* code)
1116  */
1117 int fit_conf_get_node(const void *fit, const char *conf_uname);
1118
1119 int fit_conf_get_prop_node_count(const void *fit, int noffset,
1120                 const char *prop_name);
1121 int fit_conf_get_prop_node_index(const void *fit, int noffset,
1122                 const char *prop_name, int index);
1123
1124 /**
1125  * fit_conf_get_prop_node() - Get node refered to by a configuration
1126  * @fit:        FIT to check
1127  * @noffset:    Offset of conf@xxx node to check
1128  * @prop_name:  Property to read from the conf node
1129  *
1130  * The conf- nodes contain references to other nodes, using properties
1131  * like 'kernel = "kernel"'. Given such a property name (e.g. "kernel"),
1132  * return the offset of the node referred to (e.g. offset of node
1133  * "/images/kernel".
1134  */
1135 int fit_conf_get_prop_node(const void *fit, int noffset,
1136                 const char *prop_name);
1137
1138 int fit_check_ramdisk(const void *fit, int os_noffset,
1139                 uint8_t arch, int verify);
1140 #endif /* FIT */
1141
1142 int calculate_hash(const void *data, int data_len, const char *algo,
1143                         uint8_t *value, int *value_len);
1144
1145 /*
1146  * At present we only support signing on the host, and verification on the
1147  * device
1148  */
1149 #if defined(USE_HOSTCC)
1150 # if defined(CONFIG_FIT_SIGNATURE)
1151 #  define IMAGE_ENABLE_SIGN     1
1152 #  define FIT_IMAGE_ENABLE_VERIFY       1
1153 #  include <openssl/evp.h>
1154 # else
1155 #  define IMAGE_ENABLE_SIGN     0
1156 #  define FIT_IMAGE_ENABLE_VERIFY       0
1157 # endif
1158 #else
1159 # define IMAGE_ENABLE_SIGN      0
1160 # define FIT_IMAGE_ENABLE_VERIFY        CONFIG_IS_ENABLED(FIT_SIGNATURE)
1161 #endif
1162
1163 #if CONFIG_IS_ENABLED(FIT)
1164 #ifdef USE_HOSTCC
1165 void *image_get_host_blob(void);
1166 void image_set_host_blob(void *host_blob);
1167 # define gd_fdt_blob()          image_get_host_blob()
1168 #else
1169 # define gd_fdt_blob()          (gd->fdt_blob)
1170 #endif
1171
1172 #endif /* IMAGE_ENABLE_FIT */
1173
1174 /*
1175  * Information passed to the signing routines
1176  *
1177  * Either 'keydir',  'keyname', or 'keyfile' can be NULL. However, either
1178  * 'keyfile', or both 'keydir' and 'keyname' should have valid values. If
1179  * neither are valid, some operations might fail with EINVAL.
1180  */
1181 struct image_sign_info {
1182         const char *keydir;             /* Directory conaining keys */
1183         const char *keyname;            /* Name of key to use */
1184         const char *keyfile;            /* Filename of private or public key */
1185         void *fit;                      /* Pointer to FIT blob */
1186         int node_offset;                /* Offset of signature node */
1187         const char *name;               /* Algorithm name */
1188         struct checksum_algo *checksum; /* Checksum algorithm information */
1189         struct padding_algo *padding;   /* Padding algorithm information */
1190         struct crypto_algo *crypto;     /* Crypto algorithm information */
1191         const void *fdt_blob;           /* FDT containing public keys */
1192         int required_keynode;           /* Node offset of key to use: -1=any */
1193         const char *require_keys;       /* Value for 'required' property */
1194         const char *engine_id;          /* Engine to use for signing */
1195         /*
1196          * Note: the following two fields are always valid even w/o
1197          * RSA_VERIFY_WITH_PKEY in order to make sure this structure is
1198          * the same on target and host. Otherwise, vboot test may fail.
1199          */
1200         const void *key;                /* Pointer to public key in DER */
1201         int keylen;                     /* Length of public key */
1202 };
1203
1204 /* A part of an image, used for hashing */
1205 struct image_region {
1206         const void *data;
1207         int size;
1208 };
1209
1210 #if FIT_IMAGE_ENABLE_VERIFY
1211 # include <u-boot/hash-checksum.h>
1212 #endif
1213 struct checksum_algo {
1214         const char *name;
1215         const int checksum_len;
1216         const int der_len;
1217         const uint8_t *der_prefix;
1218 #if IMAGE_ENABLE_SIGN
1219         const EVP_MD *(*calculate_sign)(void);
1220 #endif
1221         int (*calculate)(const char *name,
1222                          const struct image_region region[],
1223                          int region_count, uint8_t *checksum);
1224 };
1225
1226 struct crypto_algo {
1227         const char *name;               /* Name of algorithm */
1228         const int key_len;
1229
1230         /**
1231          * sign() - calculate and return signature for given input data
1232          *
1233          * @info:       Specifies key and FIT information
1234          * @data:       Pointer to the input data
1235          * @data_len:   Data length
1236          * @sigp:       Set to an allocated buffer holding the signature
1237          * @sig_len:    Set to length of the calculated hash
1238          *
1239          * This computes input data signature according to selected algorithm.
1240          * Resulting signature value is placed in an allocated buffer, the
1241          * pointer is returned as *sigp. The length of the calculated
1242          * signature is returned via the sig_len pointer argument. The caller
1243          * should free *sigp.
1244          *
1245          * @return: 0, on success, -ve on error
1246          */
1247         int (*sign)(struct image_sign_info *info,
1248                     const struct image_region region[],
1249                     int region_count, uint8_t **sigp, uint *sig_len);
1250
1251         /**
1252          * add_verify_data() - Add verification information to FDT
1253          *
1254          * Add public key information to the FDT node, suitable for
1255          * verification at run-time. The information added depends on the
1256          * algorithm being used.
1257          *
1258          * @info:       Specifies key and FIT information
1259          * @keydest:    Destination FDT blob for public key data
1260          * @return: 0, on success, -ve on error
1261          */
1262         int (*add_verify_data)(struct image_sign_info *info, void *keydest);
1263
1264         /**
1265          * verify() - Verify a signature against some data
1266          *
1267          * @info:       Specifies key and FIT information
1268          * @data:       Pointer to the input data
1269          * @data_len:   Data length
1270          * @sig:        Signature
1271          * @sig_len:    Number of bytes in signature
1272          * @return 0 if verified, -ve on error
1273          */
1274         int (*verify)(struct image_sign_info *info,
1275                       const struct image_region region[], int region_count,
1276                       uint8_t *sig, uint sig_len);
1277 };
1278
1279 /* Declare a new U-Boot crypto algorithm handler */
1280 #define U_BOOT_CRYPTO_ALGO(__name)                                              \
1281 ll_entry_declare(struct crypto_algo, __name, cryptos)
1282
1283 struct padding_algo {
1284         const char *name;
1285         int (*verify)(struct image_sign_info *info,
1286                       uint8_t *pad, int pad_len,
1287                       const uint8_t *hash, int hash_len);
1288 };
1289
1290 /* Declare a new U-Boot padding algorithm handler */
1291 #define U_BOOT_PADDING_ALGO(__name)                                             \
1292 ll_entry_declare(struct padding_algo, __name, paddings)
1293
1294 /**
1295  * image_get_checksum_algo() - Look up a checksum algorithm
1296  *
1297  * @param full_name     Name of algorithm in the form "checksum,crypto"
1298  * @return pointer to algorithm information, or NULL if not found
1299  */
1300 struct checksum_algo *image_get_checksum_algo(const char *full_name);
1301
1302 /**
1303  * image_get_crypto_algo() - Look up a cryptosystem algorithm
1304  *
1305  * @param full_name     Name of algorithm in the form "checksum,crypto"
1306  * @return pointer to algorithm information, or NULL if not found
1307  */
1308 struct crypto_algo *image_get_crypto_algo(const char *full_name);
1309
1310 /**
1311  * image_get_padding_algo() - Look up a padding algorithm
1312  *
1313  * @param name          Name of padding algorithm
1314  * @return pointer to algorithm information, or NULL if not found
1315  */
1316 struct padding_algo *image_get_padding_algo(const char *name);
1317
1318 #if CONFIG_IS_ENABLED(FIT)
1319
1320 /**
1321  * fit_image_verify_required_sigs() - Verify signatures marked as 'required'
1322  *
1323  * @fit:                FIT to check
1324  * @image_noffset:      Offset of image node to check
1325  * @data:               Image data to check
1326  * @size:               Size of image data
1327  * @sig_blob:           FDT containing public keys
1328  * @no_sigsp:           Returns 1 if no signatures were required, and
1329  *                      therefore nothing was checked. The caller may wish
1330  *                      to fall back to other mechanisms, or refuse to
1331  *                      boot.
1332  * @return 0 if all verified ok, <0 on error
1333  */
1334 int fit_image_verify_required_sigs(const void *fit, int image_noffset,
1335                 const char *data, size_t size, const void *sig_blob,
1336                 int *no_sigsp);
1337
1338 /**
1339  * fit_image_check_sig() - Check a single image signature node
1340  *
1341  * @fit:                FIT to check
1342  * @noffset:            Offset of signature node to check
1343  * @data:               Image data to check
1344  * @size:               Size of image data
1345  * @required_keynode:   Offset in the control FDT of the required key node,
1346  *                      if any. If this is given, then the image wil not
1347  *                      pass verification unless that key is used. If this is
1348  *                      -1 then any signature will do.
1349  * @err_msgp:           In the event of an error, this will be pointed to a
1350  *                      help error string to display to the user.
1351  * @return 0 if all verified ok, <0 on error
1352  */
1353 int fit_image_check_sig(const void *fit, int noffset, const void *data,
1354                 size_t size, int required_keynode, char **err_msgp);
1355
1356 int fit_image_decrypt_data(const void *fit,
1357                            int image_noffset, int cipher_noffset,
1358                            const void *data, size_t size,
1359                            void **data_unciphered, size_t *size_unciphered);
1360
1361 /**
1362  * fit_region_make_list() - Make a list of regions to hash
1363  *
1364  * Given a list of FIT regions (offset, size) provided by libfdt, create
1365  * a list of regions (void *, size) for use by the signature creationg
1366  * and verification code.
1367  *
1368  * @fit:                FIT image to process
1369  * @fdt_regions:        Regions as returned by libfdt
1370  * @count:              Number of regions returned by libfdt
1371  * @region:             Place to put list of regions (NULL to allocate it)
1372  * @return pointer to list of regions, or NULL if out of memory
1373  */
1374 struct image_region *fit_region_make_list(const void *fit,
1375                 struct fdt_region *fdt_regions, int count,
1376                 struct image_region *region);
1377
1378 static inline int fit_image_check_target_arch(const void *fdt, int node)
1379 {
1380 #ifndef USE_HOSTCC
1381         return fit_image_check_arch(fdt, node, IH_ARCH_DEFAULT);
1382 #else
1383         return 0;
1384 #endif
1385 }
1386
1387 /*
1388  * At present we only support ciphering on the host, and unciphering on the
1389  * device
1390  */
1391 #if defined(USE_HOSTCC)
1392 # if defined(CONFIG_FIT_CIPHER)
1393 #  define IMAGE_ENABLE_ENCRYPT  1
1394 #  define IMAGE_ENABLE_DECRYPT  1
1395 #  include <openssl/evp.h>
1396 # else
1397 #  define IMAGE_ENABLE_ENCRYPT  0
1398 #  define IMAGE_ENABLE_DECRYPT  0
1399 # endif
1400 #else
1401 # define IMAGE_ENABLE_ENCRYPT   0
1402 # define IMAGE_ENABLE_DECRYPT   CONFIG_IS_ENABLED(FIT_CIPHER)
1403 #endif
1404
1405 /* Information passed to the ciphering routines */
1406 struct image_cipher_info {
1407         const char *keydir;             /* Directory containing keys */
1408         const char *keyname;            /* Name of key to use */
1409         const char *ivname;             /* Name of IV to use */
1410         const void *fit;                /* Pointer to FIT blob */
1411         int node_noffset;               /* Offset of the cipher node */
1412         const char *name;               /* Algorithm name */
1413         struct cipher_algo *cipher;     /* Cipher algorithm information */
1414         const void *fdt_blob;           /* FDT containing key and IV */
1415         const void *key;                /* Value of the key */
1416         const void *iv;                 /* Value of the IV */
1417         size_t size_unciphered;         /* Size of the unciphered data */
1418 };
1419
1420 struct cipher_algo {
1421         const char *name;               /* Name of algorithm */
1422         int key_len;                    /* Length of the key */
1423         int iv_len;                     /* Length of the IV */
1424
1425 #if IMAGE_ENABLE_ENCRYPT
1426         const EVP_CIPHER * (*calculate_type)(void);
1427 #endif
1428
1429         int (*encrypt)(struct image_cipher_info *info,
1430                        const unsigned char *data, int data_len,
1431                        unsigned char **cipher, int *cipher_len);
1432
1433         int (*add_cipher_data)(struct image_cipher_info *info,
1434                                void *keydest, void *fit, int node_noffset);
1435
1436         int (*decrypt)(struct image_cipher_info *info,
1437                        const void *cipher, size_t cipher_len,
1438                        void **data, size_t *data_len);
1439 };
1440
1441 int fit_image_cipher_get_algo(const void *fit, int noffset, char **algo);
1442
1443 struct cipher_algo *image_get_cipher_algo(const char *full_name);
1444
1445 #if CONFIG_IS_ENABLED(FIT_VERBOSE)
1446 #define fit_unsupported(msg)    printf("! %s:%d " \
1447                                 "FIT images not supported for '%s'\n", \
1448                                 __FILE__, __LINE__, (msg))
1449
1450 #define fit_unsupported_reset(msg)      printf("! %s:%d " \
1451                                 "FIT images not supported for '%s' " \
1452                                 "- must reset board to recover!\n", \
1453                                 __FILE__, __LINE__, (msg))
1454 #else
1455 #define fit_unsupported(msg)
1456 #define fit_unsupported_reset(msg)
1457 #endif /* FIT_VERBOSE */
1458 #endif /* CONFIG_FIT */
1459
1460 #if !defined(USE_HOSTCC)
1461 #if defined(CONFIG_ANDROID_BOOT_IMAGE)
1462 struct andr_img_hdr;
1463 int android_image_check_header(const struct andr_img_hdr *hdr);
1464 int android_image_get_kernel(const struct andr_img_hdr *hdr, int verify,
1465                              ulong *os_data, ulong *os_len);
1466 int android_image_get_ramdisk(const struct andr_img_hdr *hdr,
1467                               ulong *rd_data, ulong *rd_len);
1468 int android_image_get_second(const struct andr_img_hdr *hdr,
1469                               ulong *second_data, ulong *second_len);
1470 bool android_image_get_dtbo(ulong hdr_addr, ulong *addr, u32 *size);
1471 bool android_image_get_dtb_by_index(ulong hdr_addr, u32 index, ulong *addr,
1472                                     u32 *size);
1473 ulong android_image_get_end(const struct andr_img_hdr *hdr);
1474 ulong android_image_get_kload(const struct andr_img_hdr *hdr);
1475 ulong android_image_get_kcomp(const struct andr_img_hdr *hdr);
1476 void android_print_contents(const struct andr_img_hdr *hdr);
1477 #if !defined(CONFIG_SPL_BUILD)
1478 bool android_image_print_dtb_contents(ulong hdr_addr);
1479 #endif
1480
1481 #endif /* CONFIG_ANDROID_BOOT_IMAGE */
1482 #endif /* !USE_HOSTCC */
1483
1484 /**
1485  * board_fit_config_name_match() - Check for a matching board name
1486  *
1487  * This is used when SPL loads a FIT containing multiple device tree files
1488  * and wants to work out which one to use. The description of each one is
1489  * passed to this function. The description comes from the 'description' field
1490  * in each (FDT) image node.
1491  *
1492  * @name: Device tree description
1493  * @return 0 if this device tree should be used, non-zero to try the next
1494  */
1495 int board_fit_config_name_match(const char *name);
1496
1497 /**
1498  * board_fit_image_post_process() - Do any post-process on FIT binary data
1499  *
1500  * This is used to do any sort of image manipulation, verification, decryption
1501  * etc. in a platform or board specific way. Obviously, anything done here would
1502  * need to be comprehended in how the images were prepared before being injected
1503  * into the FIT creation (i.e. the binary blobs would have been pre-processed
1504  * before being added to the FIT image).
1505  *
1506  * @fit: pointer to fit image
1507  * @node: offset of image node
1508  * @image: pointer to the image start pointer
1509  * @size: pointer to the image size
1510  * @return no return value (failure should be handled internally)
1511  */
1512 void board_fit_image_post_process(const void *fit, int node, void **p_image,
1513                                   size_t *p_size);
1514
1515 #define FDT_ERROR       ((ulong)(-1))
1516
1517 ulong fdt_getprop_u32(const void *fdt, int node, const char *prop);
1518
1519 /**
1520  * fit_find_config_node() - Find the node for the best DTB in a FIT image
1521  *
1522  * A FIT image contains one or more DTBs. This function parses the
1523  * configurations described in the FIT images and returns the node of
1524  * the first matching DTB. To check if a DTB matches a board, this function
1525  * calls board_fit_config_name_match(). If no matching DTB is found, it returns
1526  * the node described by the default configuration if it exists.
1527  *
1528  * @fdt: pointer to flat device tree
1529  * @return the node if found, -ve otherwise
1530  */
1531 int fit_find_config_node(const void *fdt);
1532
1533 /**
1534  * Mapping of image types to function handlers to be invoked on the associated
1535  * loaded images
1536  *
1537  * @type: Type of image, I.E. IH_TYPE_*
1538  * @handler: Function to call on loaded image
1539  */
1540 struct fit_loadable_tbl {
1541         int type;
1542         /**
1543          * handler() - Process a loaded image
1544          *
1545          * @data: Pointer to start of loaded image data
1546          * @size: Size of loaded image data
1547          */
1548         void (*handler)(ulong data, size_t size);
1549 };
1550
1551 /*
1552  * Define a FIT loadable image type handler
1553  *
1554  * _type is a valid uimage_type ID as defined in the "Image Type" enum above
1555  * _handler is the handler function to call after this image type is loaded
1556  */
1557 #define U_BOOT_FIT_LOADABLE_HANDLER(_type, _handler) \
1558         ll_entry_declare(struct fit_loadable_tbl, _function, fit_loadable) = { \
1559                 .type = _type, \
1560                 .handler = _handler, \
1561         }
1562
1563 /**
1564  * fit_update - update storage with FIT image
1565  * @fit:        Pointer to FIT image
1566  *
1567  * Update firmware on storage using FIT image as input.
1568  * The storage area to be update will be identified by the name
1569  * in FIT and matching it to "dfu_alt_info" variable.
1570  *
1571  * Return:      0 on success, non-zero otherwise
1572  */
1573 int fit_update(const void *fit);
1574
1575 #endif  /* __IMAGE_H__ */