Prepare v2023.10
[platform/kernel/u-boot.git] / boot / image-fit.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2013, Google Inc.
4  *
5  * (C) Copyright 2008 Semihalf
6  *
7  * (C) Copyright 2000-2006
8  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
9  */
10
11 #define LOG_CATEGORY LOGC_BOOT
12
13 #ifdef USE_HOSTCC
14 #include "mkimage.h"
15 #include <time.h>
16 #include <linux/libfdt.h>
17 #include <u-boot/crc.h>
18 #else
19 #include <linux/compiler.h>
20 #include <linux/sizes.h>
21 #include <common.h>
22 #include <errno.h>
23 #include <log.h>
24 #include <mapmem.h>
25 #include <asm/io.h>
26 #include <malloc.h>
27 #include <memalign.h>
28 #include <asm/global_data.h>
29 #ifdef CONFIG_DM_HASH
30 #include <dm.h>
31 #include <u-boot/hash.h>
32 #endif
33 DECLARE_GLOBAL_DATA_PTR;
34 #endif /* !USE_HOSTCC*/
35
36 #include <bootm.h>
37 #include <image.h>
38 #include <bootstage.h>
39 #include <linux/kconfig.h>
40 #include <u-boot/crc.h>
41 #include <u-boot/md5.h>
42 #include <u-boot/sha1.h>
43 #include <u-boot/sha256.h>
44 #include <u-boot/sha512.h>
45
46 /*****************************************************************************/
47 /* New uImage format routines */
48 /*****************************************************************************/
49 #ifndef USE_HOSTCC
50 static int fit_parse_spec(const char *spec, char sepc, ulong addr_curr,
51                 ulong *addr, const char **name)
52 {
53         const char *sep;
54
55         *addr = addr_curr;
56         *name = NULL;
57
58         sep = strchr(spec, sepc);
59         if (sep) {
60                 if (sep - spec > 0)
61                         *addr = hextoul(spec, NULL);
62
63                 *name = sep + 1;
64                 return 1;
65         }
66
67         return 0;
68 }
69
70 /**
71  * fit_parse_conf - parse FIT configuration spec
72  * @spec: input string, containing configuration spec
73  * @add_curr: current image address (to be used as a possible default)
74  * @addr: pointer to a ulong variable, will hold FIT image address of a given
75  * configuration
76  * @conf_name double pointer to a char, will hold pointer to a configuration
77  * unit name
78  *
79  * fit_parse_conf() expects configuration spec in the form of [<addr>]#<conf>,
80  * where <addr> is a FIT image address that contains configuration
81  * with a <conf> unit name.
82  *
83  * Address part is optional, and if omitted default add_curr will
84  * be used instead.
85  *
86  * returns:
87  *     1 if spec is a valid configuration string,
88  *     addr and conf_name are set accordingly
89  *     0 otherwise
90  */
91 int fit_parse_conf(const char *spec, ulong addr_curr,
92                 ulong *addr, const char **conf_name)
93 {
94         return fit_parse_spec(spec, '#', addr_curr, addr, conf_name);
95 }
96
97 /**
98  * fit_parse_subimage - parse FIT subimage spec
99  * @spec: input string, containing subimage spec
100  * @add_curr: current image address (to be used as a possible default)
101  * @addr: pointer to a ulong variable, will hold FIT image address of a given
102  * subimage
103  * @image_name: double pointer to a char, will hold pointer to a subimage name
104  *
105  * fit_parse_subimage() expects subimage spec in the form of
106  * [<addr>]:<subimage>, where <addr> is a FIT image address that contains
107  * subimage with a <subimg> unit name.
108  *
109  * Address part is optional, and if omitted default add_curr will
110  * be used instead.
111  *
112  * returns:
113  *     1 if spec is a valid subimage string,
114  *     addr and image_name are set accordingly
115  *     0 otherwise
116  */
117 int fit_parse_subimage(const char *spec, ulong addr_curr,
118                 ulong *addr, const char **image_name)
119 {
120         return fit_parse_spec(spec, ':', addr_curr, addr, image_name);
121 }
122 #endif /* !USE_HOSTCC */
123
124 #ifdef USE_HOSTCC
125 /* Host tools use these implementations for Cipher and Signature support */
126 static void *host_blob;
127
128 void image_set_host_blob(void *blob)
129 {
130         host_blob = blob;
131 }
132
133 void *image_get_host_blob(void)
134 {
135         return host_blob;
136 }
137 #endif /* USE_HOSTCC */
138
139 static void fit_get_debug(const void *fit, int noffset,
140                 char *prop_name, int err)
141 {
142         debug("Can't get '%s' property from FIT 0x%08lx, node: offset %d, name %s (%s)\n",
143               prop_name, (ulong)fit, noffset, fit_get_name(fit, noffset, NULL),
144               fdt_strerror(err));
145 }
146
147 /**
148  * fit_get_subimage_count - get component (sub-image) count
149  * @fit: pointer to the FIT format image header
150  * @images_noffset: offset of images node
151  *
152  * returns:
153  *     number of image components
154  */
155 int fit_get_subimage_count(const void *fit, int images_noffset)
156 {
157         int noffset;
158         int ndepth;
159         int count = 0;
160
161         /* Process its subnodes, print out component images details */
162         for (ndepth = 0, count = 0,
163                 noffset = fdt_next_node(fit, images_noffset, &ndepth);
164              (noffset >= 0) && (ndepth > 0);
165              noffset = fdt_next_node(fit, noffset, &ndepth)) {
166                 if (ndepth == 1) {
167                         count++;
168                 }
169         }
170
171         return count;
172 }
173
174 /**
175  * fit_image_print_data() - prints out the hash node details
176  * @fit: pointer to the FIT format image header
177  * @noffset: offset of the hash node
178  * @p: pointer to prefix string
179  * @type: Type of information to print ("hash" or "sign")
180  *
181  * fit_image_print_data() lists properties for the processed hash node
182  *
183  * This function avoid using puts() since it prints a newline on the host
184  * but does not in U-Boot.
185  *
186  * returns:
187  *     no returned results
188  */
189 static void fit_image_print_data(const void *fit, int noffset, const char *p,
190                                  const char *type)
191 {
192         const char *keyname;
193         uint8_t *value;
194         int value_len;
195         const char *algo;
196         const char *padding;
197         bool required;
198         int ret, i;
199
200         debug("%s  %s node:    '%s'\n", p, type,
201               fit_get_name(fit, noffset, NULL));
202         printf("%s  %s algo:    ", p, type);
203         if (fit_image_hash_get_algo(fit, noffset, &algo)) {
204                 printf("invalid/unsupported\n");
205                 return;
206         }
207         printf("%s", algo);
208         keyname = fdt_getprop(fit, noffset, FIT_KEY_HINT, NULL);
209         required = fdt_getprop(fit, noffset, FIT_KEY_REQUIRED, NULL) != NULL;
210         if (keyname)
211                 printf(":%s", keyname);
212         if (required)
213                 printf(" (required)");
214         printf("\n");
215
216         padding = fdt_getprop(fit, noffset, "padding", NULL);
217         if (padding)
218                 printf("%s  %s padding: %s\n", p, type, padding);
219
220         ret = fit_image_hash_get_value(fit, noffset, &value,
221                                        &value_len);
222         printf("%s  %s value:   ", p, type);
223         if (ret) {
224                 printf("unavailable\n");
225         } else {
226                 for (i = 0; i < value_len; i++)
227                         printf("%02x", value[i]);
228                 printf("\n");
229         }
230
231         debug("%s  %s len:     %d\n", p, type, value_len);
232
233         /* Signatures have a time stamp */
234         if (IMAGE_ENABLE_TIMESTAMP && keyname) {
235                 time_t timestamp;
236
237                 printf("%s  Timestamp:    ", p);
238                 if (fit_get_timestamp(fit, noffset, &timestamp))
239                         printf("unavailable\n");
240                 else
241                         genimg_print_time(timestamp);
242         }
243 }
244
245 /**
246  * fit_image_print_verification_data() - prints out the hash/signature details
247  * @fit: pointer to the FIT format image header
248  * @noffset: offset of the hash or signature node
249  * @p: pointer to prefix string
250  *
251  * This lists properties for the processed hash node
252  *
253  * returns:
254  *     no returned results
255  */
256 static void fit_image_print_verification_data(const void *fit, int noffset,
257                                               const char *p)
258 {
259         const char *name;
260
261         /*
262          * Check subnode name, must be equal to "hash" or "signature".
263          * Multiple hash/signature nodes require unique unit node
264          * names, e.g. hash-1, hash-2, signature-1, signature-2, etc.
265          */
266         name = fit_get_name(fit, noffset, NULL);
267         if (!strncmp(name, FIT_HASH_NODENAME, strlen(FIT_HASH_NODENAME))) {
268                 fit_image_print_data(fit, noffset, p, "Hash");
269         } else if (!strncmp(name, FIT_SIG_NODENAME,
270                                 strlen(FIT_SIG_NODENAME))) {
271                 fit_image_print_data(fit, noffset, p, "Sign");
272         }
273 }
274
275 /**
276  * fit_conf_print - prints out the FIT configuration details
277  * @fit: pointer to the FIT format image header
278  * @noffset: offset of the configuration node
279  * @p: pointer to prefix string
280  *
281  * fit_conf_print() lists all mandatory properties for the processed
282  * configuration node.
283  *
284  * returns:
285  *     no returned results
286  */
287 static void fit_conf_print(const void *fit, int noffset, const char *p)
288 {
289         char *desc;
290         const char *uname;
291         int ret;
292         int fdt_index, loadables_index;
293         int ndepth;
294
295         /* Mandatory properties */
296         ret = fit_get_desc(fit, noffset, &desc);
297         printf("%s  Description:  ", p);
298         if (ret)
299                 printf("unavailable\n");
300         else
301                 printf("%s\n", desc);
302
303         uname = fdt_getprop(fit, noffset, FIT_KERNEL_PROP, NULL);
304         printf("%s  Kernel:       ", p);
305         if (!uname)
306                 printf("unavailable\n");
307         else
308                 printf("%s\n", uname);
309
310         /* Optional properties */
311         uname = fdt_getprop(fit, noffset, FIT_RAMDISK_PROP, NULL);
312         if (uname)
313                 printf("%s  Init Ramdisk: %s\n", p, uname);
314
315         uname = fdt_getprop(fit, noffset, FIT_FIRMWARE_PROP, NULL);
316         if (uname)
317                 printf("%s  Firmware:     %s\n", p, uname);
318
319         for (fdt_index = 0;
320              uname = fdt_stringlist_get(fit, noffset, FIT_FDT_PROP,
321                                         fdt_index, NULL), uname;
322              fdt_index++) {
323                 if (fdt_index == 0)
324                         printf("%s  FDT:          ", p);
325                 else
326                         printf("%s                ", p);
327                 printf("%s\n", uname);
328         }
329
330         uname = fdt_getprop(fit, noffset, FIT_FPGA_PROP, NULL);
331         if (uname)
332                 printf("%s  FPGA:         %s\n", p, uname);
333
334         /* Print out all of the specified loadables */
335         for (loadables_index = 0;
336              uname = fdt_stringlist_get(fit, noffset, FIT_LOADABLE_PROP,
337                                         loadables_index, NULL), uname;
338              loadables_index++) {
339                 if (loadables_index == 0) {
340                         printf("%s  Loadables:    ", p);
341                 } else {
342                         printf("%s                ", p);
343                 }
344                 printf("%s\n", uname);
345         }
346
347         /* Process all hash subnodes of the component configuration node */
348         for (ndepth = 0, noffset = fdt_next_node(fit, noffset, &ndepth);
349              (noffset >= 0) && (ndepth > 0);
350              noffset = fdt_next_node(fit, noffset, &ndepth)) {
351                 if (ndepth == 1) {
352                         /* Direct child node of the component configuration node */
353                         fit_image_print_verification_data(fit, noffset, p);
354                 }
355         }
356 }
357
358 /**
359  * fit_print_contents - prints out the contents of the FIT format image
360  * @fit: pointer to the FIT format image header
361  * @p: pointer to prefix string
362  *
363  * fit_print_contents() formats a multi line FIT image contents description.
364  * The routine prints out FIT image properties (root node level) followed by
365  * the details of each component image.
366  *
367  * returns:
368  *     no returned results
369  */
370 void fit_print_contents(const void *fit)
371 {
372         char *desc;
373         char *uname;
374         int images_noffset;
375         int confs_noffset;
376         int noffset;
377         int ndepth;
378         int count = 0;
379         int ret;
380         const char *p;
381         time_t timestamp;
382
383         if (!CONFIG_IS_ENABLED(FIT_PRINT))
384                 return;
385
386         /* Indent string is defined in header image.h */
387         p = IMAGE_INDENT_STRING;
388
389         /* Root node properties */
390         ret = fit_get_desc(fit, 0, &desc);
391         printf("%sFIT description: ", p);
392         if (ret)
393                 printf("unavailable\n");
394         else
395                 printf("%s\n", desc);
396
397         if (IMAGE_ENABLE_TIMESTAMP) {
398                 ret = fit_get_timestamp(fit, 0, &timestamp);
399                 printf("%sCreated:         ", p);
400                 if (ret)
401                         printf("unavailable\n");
402                 else
403                         genimg_print_time(timestamp);
404         }
405
406         /* Find images parent node offset */
407         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
408         if (images_noffset < 0) {
409                 printf("Can't find images parent node '%s' (%s)\n",
410                        FIT_IMAGES_PATH, fdt_strerror(images_noffset));
411                 return;
412         }
413
414         /* Process its subnodes, print out component images details */
415         for (ndepth = 0, count = 0,
416                 noffset = fdt_next_node(fit, images_noffset, &ndepth);
417              (noffset >= 0) && (ndepth > 0);
418              noffset = fdt_next_node(fit, noffset, &ndepth)) {
419                 if (ndepth == 1) {
420                         /*
421                          * Direct child node of the images parent node,
422                          * i.e. component image node.
423                          */
424                         printf("%s Image %u (%s)\n", p, count++,
425                                fit_get_name(fit, noffset, NULL));
426
427                         fit_image_print(fit, noffset, p);
428                 }
429         }
430
431         /* Find configurations parent node offset */
432         confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
433         if (confs_noffset < 0) {
434                 debug("Can't get configurations parent node '%s' (%s)\n",
435                       FIT_CONFS_PATH, fdt_strerror(confs_noffset));
436                 return;
437         }
438
439         /* get default configuration unit name from default property */
440         uname = (char *)fdt_getprop(fit, noffset, FIT_DEFAULT_PROP, NULL);
441         if (uname)
442                 printf("%s Default Configuration: '%s'\n", p, uname);
443
444         /* Process its subnodes, print out configurations details */
445         for (ndepth = 0, count = 0,
446                 noffset = fdt_next_node(fit, confs_noffset, &ndepth);
447              (noffset >= 0) && (ndepth > 0);
448              noffset = fdt_next_node(fit, noffset, &ndepth)) {
449                 if (ndepth == 1) {
450                         /*
451                          * Direct child node of the configurations parent node,
452                          * i.e. configuration node.
453                          */
454                         printf("%s Configuration %u (%s)\n", p, count++,
455                                fit_get_name(fit, noffset, NULL));
456
457                         fit_conf_print(fit, noffset, p);
458                 }
459         }
460 }
461
462 /**
463  * fit_image_print - prints out the FIT component image details
464  * @fit: pointer to the FIT format image header
465  * @image_noffset: offset of the component image node
466  * @p: pointer to prefix string
467  *
468  * fit_image_print() lists all mandatory properties for the processed component
469  * image. If present, hash nodes are printed out as well. Load
470  * address for images of type firmware is also printed out. Since the load
471  * address is not mandatory for firmware images, it will be output as
472  * "unavailable" when not present.
473  *
474  * returns:
475  *     no returned results
476  */
477 void fit_image_print(const void *fit, int image_noffset, const char *p)
478 {
479         char *desc;
480         uint8_t type, arch, os, comp = IH_COMP_NONE;
481         size_t size;
482         ulong load, entry;
483         const void *data;
484         int noffset;
485         int ndepth;
486         int ret;
487
488         if (!CONFIG_IS_ENABLED(FIT_PRINT))
489                 return;
490
491         /* Mandatory properties */
492         ret = fit_get_desc(fit, image_noffset, &desc);
493         printf("%s  Description:  ", p);
494         if (ret)
495                 printf("unavailable\n");
496         else
497                 printf("%s\n", desc);
498
499         if (IMAGE_ENABLE_TIMESTAMP) {
500                 time_t timestamp;
501
502                 ret = fit_get_timestamp(fit, 0, &timestamp);
503                 printf("%s  Created:      ", p);
504                 if (ret)
505                         printf("unavailable\n");
506                 else
507                         genimg_print_time(timestamp);
508         }
509
510         fit_image_get_type(fit, image_noffset, &type);
511         printf("%s  Type:         %s\n", p, genimg_get_type_name(type));
512
513         fit_image_get_comp(fit, image_noffset, &comp);
514         printf("%s  Compression:  %s\n", p, genimg_get_comp_name(comp));
515
516         ret = fit_image_get_data_and_size(fit, image_noffset, &data, &size);
517
518         if (!tools_build()) {
519                 printf("%s  Data Start:   ", p);
520                 if (ret) {
521                         printf("unavailable\n");
522                 } else {
523                         void *vdata = (void *)data;
524
525                         printf("0x%08lx\n", (ulong)map_to_sysmem(vdata));
526                 }
527         }
528
529         printf("%s  Data Size:    ", p);
530         if (ret)
531                 printf("unavailable\n");
532         else
533                 genimg_print_size(size);
534
535         /* Remaining, type dependent properties */
536         if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE) ||
537             (type == IH_TYPE_RAMDISK) || (type == IH_TYPE_FIRMWARE) ||
538             (type == IH_TYPE_FLATDT)) {
539                 fit_image_get_arch(fit, image_noffset, &arch);
540                 printf("%s  Architecture: %s\n", p, genimg_get_arch_name(arch));
541         }
542
543         if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_RAMDISK) ||
544             (type == IH_TYPE_FIRMWARE)) {
545                 fit_image_get_os(fit, image_noffset, &os);
546                 printf("%s  OS:           %s\n", p, genimg_get_os_name(os));
547         }
548
549         if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE) ||
550             (type == IH_TYPE_FIRMWARE) || (type == IH_TYPE_RAMDISK) ||
551             (type == IH_TYPE_FPGA)) {
552                 ret = fit_image_get_load(fit, image_noffset, &load);
553                 printf("%s  Load Address: ", p);
554                 if (ret)
555                         printf("unavailable\n");
556                 else
557                         printf("0x%08lx\n", load);
558         }
559
560         /* optional load address for FDT */
561         if (type == IH_TYPE_FLATDT && !fit_image_get_load(fit, image_noffset, &load))
562                 printf("%s  Load Address: 0x%08lx\n", p, load);
563
564         if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE) ||
565             (type == IH_TYPE_RAMDISK)) {
566                 ret = fit_image_get_entry(fit, image_noffset, &entry);
567                 printf("%s  Entry Point:  ", p);
568                 if (ret)
569                         printf("unavailable\n");
570                 else
571                         printf("0x%08lx\n", entry);
572         }
573
574         /* Process all hash subnodes of the component image node */
575         for (ndepth = 0, noffset = fdt_next_node(fit, image_noffset, &ndepth);
576              (noffset >= 0) && (ndepth > 0);
577              noffset = fdt_next_node(fit, noffset, &ndepth)) {
578                 if (ndepth == 1) {
579                         /* Direct child node of the component image node */
580                         fit_image_print_verification_data(fit, noffset, p);
581                 }
582         }
583 }
584
585 /**
586  * fit_get_desc - get node description property
587  * @fit: pointer to the FIT format image header
588  * @noffset: node offset
589  * @desc: double pointer to the char, will hold pointer to the description
590  *
591  * fit_get_desc() reads description property from a given node, if
592  * description is found pointer to it is returned in third call argument.
593  *
594  * returns:
595  *     0, on success
596  *     -1, on failure
597  */
598 int fit_get_desc(const void *fit, int noffset, char **desc)
599 {
600         int len;
601
602         *desc = (char *)fdt_getprop(fit, noffset, FIT_DESC_PROP, &len);
603         if (*desc == NULL) {
604                 fit_get_debug(fit, noffset, FIT_DESC_PROP, len);
605                 return -1;
606         }
607
608         return 0;
609 }
610
611 /**
612  * fit_get_timestamp - get node timestamp property
613  * @fit: pointer to the FIT format image header
614  * @noffset: node offset
615  * @timestamp: pointer to the time_t, will hold read timestamp
616  *
617  * fit_get_timestamp() reads timestamp property from given node, if timestamp
618  * is found and has a correct size its value is returned in third call
619  * argument.
620  *
621  * returns:
622  *     0, on success
623  *     -1, on property read failure
624  *     -2, on wrong timestamp size
625  */
626 int fit_get_timestamp(const void *fit, int noffset, time_t *timestamp)
627 {
628         int len;
629         const void *data;
630
631         data = fdt_getprop(fit, noffset, FIT_TIMESTAMP_PROP, &len);
632         if (data == NULL) {
633                 fit_get_debug(fit, noffset, FIT_TIMESTAMP_PROP, len);
634                 return -1;
635         }
636         if (len != sizeof(uint32_t)) {
637                 debug("FIT timestamp with incorrect size of (%u)\n", len);
638                 return -2;
639         }
640
641         *timestamp = uimage_to_cpu(*((uint32_t *)data));
642         return 0;
643 }
644
645 /**
646  * fit_image_get_node - get node offset for component image of a given unit name
647  * @fit: pointer to the FIT format image header
648  * @image_uname: component image node unit name
649  *
650  * fit_image_get_node() finds a component image (within the '/images'
651  * node) of a provided unit name. If image is found its node offset is
652  * returned to the caller.
653  *
654  * returns:
655  *     image node offset when found (>=0)
656  *     negative number on failure (FDT_ERR_* code)
657  */
658 int fit_image_get_node(const void *fit, const char *image_uname)
659 {
660         int noffset, images_noffset;
661
662         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
663         if (images_noffset < 0) {
664                 debug("Can't find images parent node '%s' (%s)\n",
665                       FIT_IMAGES_PATH, fdt_strerror(images_noffset));
666                 return images_noffset;
667         }
668
669         noffset = fdt_subnode_offset(fit, images_noffset, image_uname);
670         if (noffset < 0) {
671                 debug("Can't get node offset for image unit name: '%s' (%s)\n",
672                       image_uname, fdt_strerror(noffset));
673         }
674
675         return noffset;
676 }
677
678 /**
679  * fit_image_get_os - get os id for a given component image node
680  * @fit: pointer to the FIT format image header
681  * @noffset: component image node offset
682  * @os: pointer to the uint8_t, will hold os numeric id
683  *
684  * fit_image_get_os() finds os property in a given component image node.
685  * If the property is found, its (string) value is translated to the numeric
686  * id which is returned to the caller.
687  *
688  * returns:
689  *     0, on success
690  *     -1, on failure
691  */
692 int fit_image_get_os(const void *fit, int noffset, uint8_t *os)
693 {
694         int len;
695         const void *data;
696
697         /* Get OS name from property data */
698         data = fdt_getprop(fit, noffset, FIT_OS_PROP, &len);
699         if (data == NULL) {
700                 fit_get_debug(fit, noffset, FIT_OS_PROP, len);
701                 *os = -1;
702                 return -1;
703         }
704
705         /* Translate OS name to id */
706         *os = genimg_get_os_id(data);
707         return 0;
708 }
709
710 /**
711  * fit_image_get_arch - get arch id for a given component image node
712  * @fit: pointer to the FIT format image header
713  * @noffset: component image node offset
714  * @arch: pointer to the uint8_t, will hold arch numeric id
715  *
716  * fit_image_get_arch() finds arch property in a given component image node.
717  * If the property is found, its (string) value is translated to the numeric
718  * id which is returned to the caller.
719  *
720  * returns:
721  *     0, on success
722  *     -1, on failure
723  */
724 int fit_image_get_arch(const void *fit, int noffset, uint8_t *arch)
725 {
726         int len;
727         const void *data;
728
729         /* Get architecture name from property data */
730         data = fdt_getprop(fit, noffset, FIT_ARCH_PROP, &len);
731         if (data == NULL) {
732                 fit_get_debug(fit, noffset, FIT_ARCH_PROP, len);
733                 *arch = -1;
734                 return -1;
735         }
736
737         /* Translate architecture name to id */
738         *arch = genimg_get_arch_id(data);
739         return 0;
740 }
741
742 /**
743  * fit_image_get_type - get type id for a given component image node
744  * @fit: pointer to the FIT format image header
745  * @noffset: component image node offset
746  * @type: pointer to the uint8_t, will hold type numeric id
747  *
748  * fit_image_get_type() finds type property in a given component image node.
749  * If the property is found, its (string) value is translated to the numeric
750  * id which is returned to the caller.
751  *
752  * returns:
753  *     0, on success
754  *     -1, on failure
755  */
756 int fit_image_get_type(const void *fit, int noffset, uint8_t *type)
757 {
758         int len;
759         const void *data;
760
761         /* Get image type name from property data */
762         data = fdt_getprop(fit, noffset, FIT_TYPE_PROP, &len);
763         if (data == NULL) {
764                 fit_get_debug(fit, noffset, FIT_TYPE_PROP, len);
765                 *type = -1;
766                 return -1;
767         }
768
769         /* Translate image type name to id */
770         *type = genimg_get_type_id(data);
771         return 0;
772 }
773
774 /**
775  * fit_image_get_comp - get comp id for a given component image node
776  * @fit: pointer to the FIT format image header
777  * @noffset: component image node offset
778  * @comp: pointer to the uint8_t, will hold comp numeric id
779  *
780  * fit_image_get_comp() finds comp property in a given component image node.
781  * If the property is found, its (string) value is translated to the numeric
782  * id which is returned to the caller.
783  *
784  * returns:
785  *     0, on success
786  *     -1, on failure
787  */
788 int fit_image_get_comp(const void *fit, int noffset, uint8_t *comp)
789 {
790         int len;
791         const void *data;
792
793         /* Get compression name from property data */
794         data = fdt_getprop(fit, noffset, FIT_COMP_PROP, &len);
795         if (data == NULL) {
796                 fit_get_debug(fit, noffset, FIT_COMP_PROP, len);
797                 return -1;
798         }
799
800         /* Translate compression name to id */
801         *comp = genimg_get_comp_id(data);
802         return 0;
803 }
804
805 /**
806  * fit_image_get_phase() - get the phase for a configuration node
807  * @fit: pointer to the FIT format image header
808  * @offset: configuration-node offset
809  * @phasep: returns the phase
810  *
811  * Finds the phase property in a given configuration node. If the property is
812  * found, its (string) value is translated to the numeric id which is returned
813  * to the caller.
814  *
815  * Returns: 0 on success, -ENOENT if missing, -EINVAL for invalid value
816  */
817 int fit_image_get_phase(const void *fit, int offset, enum image_phase_t *phasep)
818 {
819         const void *data;
820         int len, ret;
821
822         /* Get phase name from property data */
823         data = fdt_getprop(fit, offset, FIT_PHASE_PROP, &len);
824         if (!data) {
825                 fit_get_debug(fit, offset, FIT_PHASE_PROP, len);
826                 *phasep = 0;
827                 return -ENOENT;
828         }
829
830         /* Translate phase name to id */
831         ret = genimg_get_phase_id(data);
832         if (ret < 0)
833                 return ret;
834         *phasep = ret;
835
836         return 0;
837 }
838
839 static int fit_image_get_address(const void *fit, int noffset, char *name,
840                           ulong *load)
841 {
842         int len, cell_len;
843         const fdt32_t *cell;
844         uint64_t load64 = 0;
845
846         cell = fdt_getprop(fit, noffset, name, &len);
847         if (cell == NULL) {
848                 fit_get_debug(fit, noffset, name, len);
849                 return -1;
850         }
851
852         cell_len = len >> 2;
853         /* Use load64 to avoid compiling warning for 32-bit target */
854         while (cell_len--) {
855                 load64 = (load64 << 32) | uimage_to_cpu(*cell);
856                 cell++;
857         }
858
859         if (len > sizeof(ulong) && (uint32_t)(load64 >> 32)) {
860                 printf("Unsupported %s address size\n", name);
861                 return -1;
862         }
863
864         *load = (ulong)load64;
865
866         return 0;
867 }
868 /**
869  * fit_image_get_load() - get load addr property for given component image node
870  * @fit: pointer to the FIT format image header
871  * @noffset: component image node offset
872  * @load: pointer to the uint32_t, will hold load address
873  *
874  * fit_image_get_load() finds load address property in a given component
875  * image node. If the property is found, its value is returned to the caller.
876  *
877  * returns:
878  *     0, on success
879  *     -1, on failure
880  */
881 int fit_image_get_load(const void *fit, int noffset, ulong *load)
882 {
883         return fit_image_get_address(fit, noffset, FIT_LOAD_PROP, load);
884 }
885
886 /**
887  * fit_image_get_entry() - get entry point address property
888  * @fit: pointer to the FIT format image header
889  * @noffset: component image node offset
890  * @entry: pointer to the uint32_t, will hold entry point address
891  *
892  * This gets the entry point address property for a given component image
893  * node.
894  *
895  * fit_image_get_entry() finds entry point address property in a given
896  * component image node.  If the property is found, its value is returned
897  * to the caller.
898  *
899  * returns:
900  *     0, on success
901  *     -1, on failure
902  */
903 int fit_image_get_entry(const void *fit, int noffset, ulong *entry)
904 {
905         return fit_image_get_address(fit, noffset, FIT_ENTRY_PROP, entry);
906 }
907
908 /**
909  * fit_image_get_data - get data property and its size for a given component image node
910  * @fit: pointer to the FIT format image header
911  * @noffset: component image node offset
912  * @data: double pointer to void, will hold data property's data address
913  * @size: pointer to size_t, will hold data property's data size
914  *
915  * fit_image_get_data() finds data property in a given component image node.
916  * If the property is found its data start address and size are returned to
917  * the caller.
918  *
919  * returns:
920  *     0, on success
921  *     -1, on failure
922  */
923 int fit_image_get_data(const void *fit, int noffset,
924                 const void **data, size_t *size)
925 {
926         int len;
927
928         *data = fdt_getprop(fit, noffset, FIT_DATA_PROP, &len);
929         if (*data == NULL) {
930                 fit_get_debug(fit, noffset, FIT_DATA_PROP, len);
931                 *size = 0;
932                 return -1;
933         }
934
935         *size = len;
936         return 0;
937 }
938
939 /**
940  * Get 'data-offset' property from a given image node.
941  *
942  * @fit: pointer to the FIT image header
943  * @noffset: component image node offset
944  * @data_offset: holds the data-offset property
945  *
946  * returns:
947  *     0, on success
948  *     -ENOENT if the property could not be found
949  */
950 int fit_image_get_data_offset(const void *fit, int noffset, int *data_offset)
951 {
952         const fdt32_t *val;
953
954         val = fdt_getprop(fit, noffset, FIT_DATA_OFFSET_PROP, NULL);
955         if (!val)
956                 return -ENOENT;
957
958         *data_offset = fdt32_to_cpu(*val);
959
960         return 0;
961 }
962
963 /**
964  * Get 'data-position' property from a given image node.
965  *
966  * @fit: pointer to the FIT image header
967  * @noffset: component image node offset
968  * @data_position: holds the data-position property
969  *
970  * returns:
971  *     0, on success
972  *     -ENOENT if the property could not be found
973  */
974 int fit_image_get_data_position(const void *fit, int noffset,
975                                 int *data_position)
976 {
977         const fdt32_t *val;
978
979         val = fdt_getprop(fit, noffset, FIT_DATA_POSITION_PROP, NULL);
980         if (!val)
981                 return -ENOENT;
982
983         *data_position = fdt32_to_cpu(*val);
984
985         return 0;
986 }
987
988 /**
989  * Get 'data-size' property from a given image node.
990  *
991  * @fit: pointer to the FIT image header
992  * @noffset: component image node offset
993  * @data_size: holds the data-size property
994  *
995  * returns:
996  *     0, on success
997  *     -ENOENT if the property could not be found
998  */
999 int fit_image_get_data_size(const void *fit, int noffset, int *data_size)
1000 {
1001         const fdt32_t *val;
1002
1003         val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, NULL);
1004         if (!val)
1005                 return -ENOENT;
1006
1007         *data_size = fdt32_to_cpu(*val);
1008
1009         return 0;
1010 }
1011
1012 /**
1013  * Get 'data-size-unciphered' property from a given image node.
1014  *
1015  * @fit: pointer to the FIT image header
1016  * @noffset: component image node offset
1017  * @data_size: holds the data-size property
1018  *
1019  * returns:
1020  *     0, on success
1021  *     -ENOENT if the property could not be found
1022  */
1023 int fit_image_get_data_size_unciphered(const void *fit, int noffset,
1024                                        size_t *data_size)
1025 {
1026         const fdt32_t *val;
1027
1028         val = fdt_getprop(fit, noffset, "data-size-unciphered", NULL);
1029         if (!val)
1030                 return -ENOENT;
1031
1032         *data_size = (size_t)fdt32_to_cpu(*val);
1033
1034         return 0;
1035 }
1036
1037 /**
1038  * fit_image_get_data_and_size - get data and its size including
1039  *                               both embedded and external data
1040  * @fit: pointer to the FIT format image header
1041  * @noffset: component image node offset
1042  * @data: double pointer to void, will hold data property's data address
1043  * @size: pointer to size_t, will hold data property's data size
1044  *
1045  * fit_image_get_data_and_size() finds data and its size including
1046  * both embedded and external data. If the property is found
1047  * its data start address and size are returned to the caller.
1048  *
1049  * returns:
1050  *     0, on success
1051  *     otherwise, on failure
1052  */
1053 int fit_image_get_data_and_size(const void *fit, int noffset,
1054                                 const void **data, size_t *size)
1055 {
1056         bool external_data = false;
1057         int offset;
1058         int len;
1059         int ret;
1060
1061         if (!fit_image_get_data_position(fit, noffset, &offset)) {
1062                 external_data = true;
1063         } else if (!fit_image_get_data_offset(fit, noffset, &offset)) {
1064                 external_data = true;
1065                 /*
1066                  * For FIT with external data, figure out where
1067                  * the external images start. This is the base
1068                  * for the data-offset properties in each image.
1069                  */
1070                 offset += ((fdt_totalsize(fit) + 3) & ~3);
1071         }
1072
1073         if (external_data) {
1074                 debug("External Data\n");
1075                 ret = fit_image_get_data_size(fit, noffset, &len);
1076                 if (!ret) {
1077                         *data = fit + offset;
1078                         *size = len;
1079                 }
1080         } else {
1081                 ret = fit_image_get_data(fit, noffset, data, size);
1082         }
1083
1084         return ret;
1085 }
1086
1087 /**
1088  * fit_image_hash_get_algo - get hash algorithm name
1089  * @fit: pointer to the FIT format image header
1090  * @noffset: hash node offset
1091  * @algo: double pointer to char, will hold pointer to the algorithm name
1092  *
1093  * fit_image_hash_get_algo() finds hash algorithm property in a given hash node.
1094  * If the property is found its data start address is returned to the caller.
1095  *
1096  * returns:
1097  *     0, on success
1098  *     -1, on failure
1099  */
1100 int fit_image_hash_get_algo(const void *fit, int noffset, const char **algo)
1101 {
1102         int len;
1103
1104         *algo = (const char *)fdt_getprop(fit, noffset, FIT_ALGO_PROP, &len);
1105         if (*algo == NULL) {
1106                 fit_get_debug(fit, noffset, FIT_ALGO_PROP, len);
1107                 return -1;
1108         }
1109
1110         return 0;
1111 }
1112
1113 /**
1114  * fit_image_hash_get_value - get hash value and length
1115  * @fit: pointer to the FIT format image header
1116  * @noffset: hash node offset
1117  * @value: double pointer to uint8_t, will hold address of a hash value data
1118  * @value_len: pointer to an int, will hold hash data length
1119  *
1120  * fit_image_hash_get_value() finds hash value property in a given hash node.
1121  * If the property is found its data start address and size are returned to
1122  * the caller.
1123  *
1124  * returns:
1125  *     0, on success
1126  *     -1, on failure
1127  */
1128 int fit_image_hash_get_value(const void *fit, int noffset, uint8_t **value,
1129                                 int *value_len)
1130 {
1131         int len;
1132
1133         *value = (uint8_t *)fdt_getprop(fit, noffset, FIT_VALUE_PROP, &len);
1134         if (*value == NULL) {
1135                 fit_get_debug(fit, noffset, FIT_VALUE_PROP, len);
1136                 *value_len = 0;
1137                 return -1;
1138         }
1139
1140         *value_len = len;
1141         return 0;
1142 }
1143
1144 /**
1145  * fit_image_hash_get_ignore - get hash ignore flag
1146  * @fit: pointer to the FIT format image header
1147  * @noffset: hash node offset
1148  * @ignore: pointer to an int, will hold hash ignore flag
1149  *
1150  * fit_image_hash_get_ignore() finds hash ignore property in a given hash node.
1151  * If the property is found and non-zero, the hash algorithm is not verified by
1152  * u-boot automatically.
1153  *
1154  * returns:
1155  *     0, on ignore not found
1156  *     value, on ignore found
1157  */
1158 static int fit_image_hash_get_ignore(const void *fit, int noffset, int *ignore)
1159 {
1160         int len;
1161         int *value;
1162
1163         value = (int *)fdt_getprop(fit, noffset, FIT_IGNORE_PROP, &len);
1164         if (value == NULL || len != sizeof(int))
1165                 *ignore = 0;
1166         else
1167                 *ignore = *value;
1168
1169         return 0;
1170 }
1171
1172 /**
1173  * fit_image_cipher_get_algo - get cipher algorithm name
1174  * @fit: pointer to the FIT format image header
1175  * @noffset: cipher node offset
1176  * @algo: double pointer to char, will hold pointer to the algorithm name
1177  *
1178  * fit_image_cipher_get_algo() finds cipher algorithm property in a given
1179  * cipher node. If the property is found its data start address is returned
1180  * to the caller.
1181  *
1182  * returns:
1183  *     0, on success
1184  *     -1, on failure
1185  */
1186 int fit_image_cipher_get_algo(const void *fit, int noffset, char **algo)
1187 {
1188         int len;
1189
1190         *algo = (char *)fdt_getprop(fit, noffset, FIT_ALGO_PROP, &len);
1191         if (!*algo) {
1192                 fit_get_debug(fit, noffset, FIT_ALGO_PROP, len);
1193                 return -1;
1194         }
1195
1196         return 0;
1197 }
1198
1199 ulong fit_get_end(const void *fit)
1200 {
1201         return map_to_sysmem((void *)(fit + fdt_totalsize(fit)));
1202 }
1203
1204 /**
1205  * fit_set_timestamp - set node timestamp property
1206  * @fit: pointer to the FIT format image header
1207  * @noffset: node offset
1208  * @timestamp: timestamp value to be set
1209  *
1210  * fit_set_timestamp() attempts to set timestamp property in the requested
1211  * node and returns operation status to the caller.
1212  *
1213  * returns:
1214  *     0, on success
1215  *     -ENOSPC if no space in device tree, -1 for other error
1216  */
1217 int fit_set_timestamp(void *fit, int noffset, time_t timestamp)
1218 {
1219         uint32_t t;
1220         int ret;
1221
1222         t = cpu_to_uimage(timestamp);
1223         ret = fdt_setprop(fit, noffset, FIT_TIMESTAMP_PROP, &t,
1224                                 sizeof(uint32_t));
1225         if (ret) {
1226                 debug("Can't set '%s' property for '%s' node (%s)\n",
1227                       FIT_TIMESTAMP_PROP, fit_get_name(fit, noffset, NULL),
1228                       fdt_strerror(ret));
1229                 return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -1;
1230         }
1231
1232         return 0;
1233 }
1234
1235 /**
1236  * calculate_hash - calculate and return hash for provided input data
1237  * @data: pointer to the input data
1238  * @data_len: data length
1239  * @name: requested hash algorithm name
1240  * @value: pointer to the char, will hold hash value data (caller must
1241  * allocate enough free space)
1242  * value_len: length of the calculated hash
1243  *
1244  * calculate_hash() computes input data hash according to the requested
1245  * algorithm.
1246  * Resulting hash value is placed in caller provided 'value' buffer, length
1247  * of the calculated hash is returned via value_len pointer argument.
1248  *
1249  * returns:
1250  *     0, on success
1251  *    -1, when algo is unsupported
1252  */
1253 int calculate_hash(const void *data, int data_len, const char *name,
1254                         uint8_t *value, int *value_len)
1255 {
1256 #if !defined(USE_HOSTCC) && defined(CONFIG_DM_HASH)
1257         int rc;
1258         enum HASH_ALGO hash_algo;
1259         struct udevice *dev;
1260
1261         rc = uclass_get_device(UCLASS_HASH, 0, &dev);
1262         if (rc) {
1263                 debug("failed to get hash device, rc=%d\n", rc);
1264                 return -1;
1265         }
1266
1267         hash_algo = hash_algo_lookup_by_name(name);
1268         if (hash_algo == HASH_ALGO_INVALID) {
1269                 debug("Unsupported hash algorithm\n");
1270                 return -1;
1271         };
1272
1273         rc = hash_digest_wd(dev, hash_algo, data, data_len, value, CHUNKSZ);
1274         if (rc) {
1275                 debug("failed to get hash value, rc=%d\n", rc);
1276                 return -1;
1277         }
1278
1279         *value_len = hash_algo_digest_size(hash_algo);
1280 #else
1281         struct hash_algo *algo;
1282         int ret;
1283
1284         ret = hash_lookup_algo(name, &algo);
1285         if (ret < 0) {
1286                 debug("Unsupported hash alogrithm\n");
1287                 return -1;
1288         }
1289
1290         algo->hash_func_ws(data, data_len, value, algo->chunk_size);
1291         *value_len = algo->digest_size;
1292 #endif
1293
1294         return 0;
1295 }
1296
1297 static int fit_image_check_hash(const void *fit, int noffset, const void *data,
1298                                 size_t size, char **err_msgp)
1299 {
1300         ALLOC_CACHE_ALIGN_BUFFER(uint8_t, value, FIT_MAX_HASH_LEN);
1301         int value_len;
1302         const char *algo;
1303         uint8_t *fit_value;
1304         int fit_value_len;
1305         int ignore;
1306
1307         *err_msgp = NULL;
1308
1309         if (fit_image_hash_get_algo(fit, noffset, &algo)) {
1310                 *err_msgp = "Can't get hash algo property";
1311                 return -1;
1312         }
1313         printf("%s", algo);
1314
1315         if (!tools_build()) {
1316                 fit_image_hash_get_ignore(fit, noffset, &ignore);
1317                 if (ignore) {
1318                         printf("-skipped ");
1319                         return 0;
1320                 }
1321         }
1322
1323         if (fit_image_hash_get_value(fit, noffset, &fit_value,
1324                                      &fit_value_len)) {
1325                 *err_msgp = "Can't get hash value property";
1326                 return -1;
1327         }
1328
1329         if (calculate_hash(data, size, algo, value, &value_len)) {
1330                 *err_msgp = "Unsupported hash algorithm";
1331                 return -1;
1332         }
1333
1334         if (value_len != fit_value_len) {
1335                 *err_msgp = "Bad hash value len";
1336                 return -1;
1337         } else if (memcmp(value, fit_value, value_len) != 0) {
1338                 *err_msgp = "Bad hash value";
1339                 return -1;
1340         }
1341
1342         return 0;
1343 }
1344
1345 int fit_image_verify_with_data(const void *fit, int image_noffset,
1346                                const void *key_blob, const void *data,
1347                                size_t size)
1348 {
1349         int             noffset = 0;
1350         char            *err_msg = "";
1351         int verify_all = 1;
1352         int ret;
1353
1354         /* Verify all required signatures */
1355         if (FIT_IMAGE_ENABLE_VERIFY &&
1356             fit_image_verify_required_sigs(fit, image_noffset, data, size,
1357                                            key_blob, &verify_all)) {
1358                 err_msg = "Unable to verify required signature";
1359                 goto error;
1360         }
1361
1362         /* Process all hash subnodes of the component image node */
1363         fdt_for_each_subnode(noffset, fit, image_noffset) {
1364                 const char *name = fit_get_name(fit, noffset, NULL);
1365
1366                 /*
1367                  * Check subnode name, must be equal to "hash".
1368                  * Multiple hash nodes require unique unit node
1369                  * names, e.g. hash-1, hash-2, etc.
1370                  */
1371                 if (!strncmp(name, FIT_HASH_NODENAME,
1372                              strlen(FIT_HASH_NODENAME))) {
1373                         if (fit_image_check_hash(fit, noffset, data, size,
1374                                                  &err_msg))
1375                                 goto error;
1376                         puts("+ ");
1377                 } else if (FIT_IMAGE_ENABLE_VERIFY && verify_all &&
1378                                 !strncmp(name, FIT_SIG_NODENAME,
1379                                         strlen(FIT_SIG_NODENAME))) {
1380                         ret = fit_image_check_sig(fit, noffset, data, size,
1381                                                   gd_fdt_blob(), -1, &err_msg);
1382
1383                         /*
1384                          * Show an indication on failure, but do not return
1385                          * an error. Only keys marked 'required' can cause
1386                          * an image validation failure. See the call to
1387                          * fit_image_verify_required_sigs() above.
1388                          */
1389                         if (ret)
1390                                 puts("- ");
1391                         else
1392                                 puts("+ ");
1393                 }
1394         }
1395
1396         if (noffset == -FDT_ERR_TRUNCATED || noffset == -FDT_ERR_BADSTRUCTURE) {
1397                 err_msg = "Corrupted or truncated tree";
1398                 goto error;
1399         }
1400
1401         return 1;
1402
1403 error:
1404         printf(" error!\n%s for '%s' hash node in '%s' image node\n",
1405                err_msg, fit_get_name(fit, noffset, NULL),
1406                fit_get_name(fit, image_noffset, NULL));
1407         return 0;
1408 }
1409
1410 /**
1411  * fit_image_verify - verify data integrity
1412  * @fit: pointer to the FIT format image header
1413  * @image_noffset: component image node offset
1414  *
1415  * fit_image_verify() goes over component image hash nodes,
1416  * re-calculates each data hash and compares with the value stored in hash
1417  * node.
1418  *
1419  * returns:
1420  *     1, if all hashes are valid
1421  *     0, otherwise (or on error)
1422  */
1423 int fit_image_verify(const void *fit, int image_noffset)
1424 {
1425         const char *name = fit_get_name(fit, image_noffset, NULL);
1426         const void      *data;
1427         size_t          size;
1428         char            *err_msg = "";
1429
1430         if (IS_ENABLED(CONFIG_FIT_SIGNATURE) && strchr(name, '@')) {
1431                 /*
1432                  * We don't support this since libfdt considers names with the
1433                  * name root but different @ suffix to be equal
1434                  */
1435                 err_msg = "Node name contains @";
1436                 goto err;
1437         }
1438         /* Get image data and data length */
1439         if (fit_image_get_data_and_size(fit, image_noffset, &data, &size)) {
1440                 err_msg = "Can't get image data/size";
1441                 goto err;
1442         }
1443
1444         return fit_image_verify_with_data(fit, image_noffset, gd_fdt_blob(),
1445                                           data, size);
1446
1447 err:
1448         printf("error!\n%s in '%s' image node\n", err_msg,
1449                fit_get_name(fit, image_noffset, NULL));
1450         return 0;
1451 }
1452
1453 /**
1454  * fit_all_image_verify - verify data integrity for all images
1455  * @fit: pointer to the FIT format image header
1456  *
1457  * fit_all_image_verify() goes over all images in the FIT and
1458  * for every images checks if all it's hashes are valid.
1459  *
1460  * returns:
1461  *     1, if all hashes of all images are valid
1462  *     0, otherwise (or on error)
1463  */
1464 int fit_all_image_verify(const void *fit)
1465 {
1466         int images_noffset;
1467         int noffset;
1468         int ndepth;
1469         int count;
1470
1471         /* Find images parent node offset */
1472         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
1473         if (images_noffset < 0) {
1474                 printf("Can't find images parent node '%s' (%s)\n",
1475                        FIT_IMAGES_PATH, fdt_strerror(images_noffset));
1476                 return 0;
1477         }
1478
1479         /* Process all image subnodes, check hashes for each */
1480         printf("## Checking hash(es) for FIT Image at %08lx ...\n",
1481                (ulong)fit);
1482         for (ndepth = 0, count = 0,
1483              noffset = fdt_next_node(fit, images_noffset, &ndepth);
1484                         (noffset >= 0) && (ndepth > 0);
1485                         noffset = fdt_next_node(fit, noffset, &ndepth)) {
1486                 if (ndepth == 1) {
1487                         /*
1488                          * Direct child node of the images parent node,
1489                          * i.e. component image node.
1490                          */
1491                         printf("   Hash(es) for Image %u (%s): ", count,
1492                                fit_get_name(fit, noffset, NULL));
1493                         count++;
1494
1495                         if (!fit_image_verify(fit, noffset))
1496                                 return 0;
1497                         printf("\n");
1498                 }
1499         }
1500         return 1;
1501 }
1502
1503 static int fit_image_uncipher(const void *fit, int image_noffset,
1504                               void **data, size_t *size)
1505 {
1506         int cipher_noffset, ret;
1507         void *dst;
1508         size_t size_dst;
1509
1510         cipher_noffset = fdt_subnode_offset(fit, image_noffset,
1511                                             FIT_CIPHER_NODENAME);
1512         if (cipher_noffset < 0)
1513                 return 0;
1514
1515         ret = fit_image_decrypt_data(fit, image_noffset, cipher_noffset,
1516                                      *data, *size, &dst, &size_dst);
1517         if (ret)
1518                 goto out;
1519
1520         *data = dst;
1521         *size = size_dst;
1522
1523  out:
1524         return ret;
1525 }
1526
1527 /**
1528  * fit_image_check_os - check whether image node is of a given os type
1529  * @fit: pointer to the FIT format image header
1530  * @noffset: component image node offset
1531  * @os: requested image os
1532  *
1533  * fit_image_check_os() reads image os property and compares its numeric
1534  * id with the requested os. Comparison result is returned to the caller.
1535  *
1536  * returns:
1537  *     1 if image is of given os type
1538  *     0 otherwise (or on error)
1539  */
1540 int fit_image_check_os(const void *fit, int noffset, uint8_t os)
1541 {
1542         uint8_t image_os;
1543
1544         if (fit_image_get_os(fit, noffset, &image_os))
1545                 return 0;
1546         return (os == image_os);
1547 }
1548
1549 /**
1550  * fit_image_check_arch - check whether image node is of a given arch
1551  * @fit: pointer to the FIT format image header
1552  * @noffset: component image node offset
1553  * @arch: requested imagearch
1554  *
1555  * fit_image_check_arch() reads image arch property and compares its numeric
1556  * id with the requested arch. Comparison result is returned to the caller.
1557  *
1558  * returns:
1559  *     1 if image is of given arch
1560  *     0 otherwise (or on error)
1561  */
1562 int fit_image_check_arch(const void *fit, int noffset, uint8_t arch)
1563 {
1564         uint8_t image_arch;
1565         int aarch32_support = 0;
1566
1567         /* Let's assume that sandbox can load any architecture */
1568         if (IS_ENABLED(CONFIG_SANDBOX))
1569                 return true;
1570
1571         if (IS_ENABLED(CONFIG_ARM64_SUPPORT_AARCH32))
1572                 aarch32_support = 1;
1573
1574         if (fit_image_get_arch(fit, noffset, &image_arch))
1575                 return 0;
1576         return (arch == image_arch) ||
1577                 (arch == IH_ARCH_I386 && image_arch == IH_ARCH_X86_64) ||
1578                 (arch == IH_ARCH_ARM64 && image_arch == IH_ARCH_ARM &&
1579                  aarch32_support);
1580 }
1581
1582 /**
1583  * fit_image_check_type - check whether image node is of a given type
1584  * @fit: pointer to the FIT format image header
1585  * @noffset: component image node offset
1586  * @type: requested image type
1587  *
1588  * fit_image_check_type() reads image type property and compares its numeric
1589  * id with the requested type. Comparison result is returned to the caller.
1590  *
1591  * returns:
1592  *     1 if image is of given type
1593  *     0 otherwise (or on error)
1594  */
1595 int fit_image_check_type(const void *fit, int noffset, uint8_t type)
1596 {
1597         uint8_t image_type;
1598
1599         if (fit_image_get_type(fit, noffset, &image_type))
1600                 return 0;
1601         return (type == image_type);
1602 }
1603
1604 /**
1605  * fit_image_check_comp - check whether image node uses given compression
1606  * @fit: pointer to the FIT format image header
1607  * @noffset: component image node offset
1608  * @comp: requested image compression type
1609  *
1610  * fit_image_check_comp() reads image compression property and compares its
1611  * numeric id with the requested compression type. Comparison result is
1612  * returned to the caller.
1613  *
1614  * returns:
1615  *     1 if image uses requested compression
1616  *     0 otherwise (or on error)
1617  */
1618 int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
1619 {
1620         uint8_t image_comp;
1621
1622         if (fit_image_get_comp(fit, noffset, &image_comp))
1623                 return 0;
1624         return (comp == image_comp);
1625 }
1626
1627 /**
1628  * fdt_check_no_at() - Check for nodes whose names contain '@'
1629  *
1630  * This checks the parent node and all subnodes recursively
1631  *
1632  * @fit: FIT to check
1633  * @parent: Parent node to check
1634  * Return: 0 if OK, -EADDRNOTAVAIL is a node has a name containing '@'
1635  */
1636 static int fdt_check_no_at(const void *fit, int parent)
1637 {
1638         const char *name;
1639         int node;
1640         int ret;
1641
1642         name = fdt_get_name(fit, parent, NULL);
1643         if (!name || strchr(name, '@'))
1644                 return -EADDRNOTAVAIL;
1645
1646         fdt_for_each_subnode(node, fit, parent) {
1647                 ret = fdt_check_no_at(fit, node);
1648                 if (ret)
1649                         return ret;
1650         }
1651
1652         return 0;
1653 }
1654
1655 int fit_check_format(const void *fit, ulong size)
1656 {
1657         int ret;
1658
1659         /* A FIT image must be a valid FDT */
1660         ret = fdt_check_header(fit);
1661         if (ret) {
1662                 log_debug("Wrong FIT format: not a flattened device tree (err=%d)\n",
1663                           ret);
1664                 return -ENOEXEC;
1665         }
1666
1667         if (CONFIG_IS_ENABLED(FIT_FULL_CHECK)) {
1668                 /*
1669                  * If we are not given the size, make do wtih calculating it.
1670                  * This is not as secure, so we should consider a flag to
1671                  * control this.
1672                  */
1673                 if (size == IMAGE_SIZE_INVAL)
1674                         size = fdt_totalsize(fit);
1675                 ret = fdt_check_full(fit, size);
1676                 if (ret)
1677                         ret = -EINVAL;
1678
1679                 /*
1680                  * U-Boot stopped using unit addressed in 2017. Since libfdt
1681                  * can match nodes ignoring any unit address, signature
1682                  * verification can see the wrong node if one is inserted with
1683                  * the same name as a valid node but with a unit address
1684                  * attached. Protect against this by disallowing unit addresses.
1685                  */
1686                 if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
1687                         ret = fdt_check_no_at(fit, 0);
1688
1689                         if (ret) {
1690                                 log_debug("FIT check error %d\n", ret);
1691                                 return ret;
1692                         }
1693                 }
1694                 if (ret) {
1695                         log_debug("FIT check error %d\n", ret);
1696                         return ret;
1697                 }
1698         }
1699
1700         /* mandatory / node 'description' property */
1701         if (!fdt_getprop(fit, 0, FIT_DESC_PROP, NULL)) {
1702                 log_debug("Wrong FIT format: no description\n");
1703                 return -ENOMSG;
1704         }
1705
1706         if (IMAGE_ENABLE_TIMESTAMP) {
1707                 /* mandatory / node 'timestamp' property */
1708                 if (!fdt_getprop(fit, 0, FIT_TIMESTAMP_PROP, NULL)) {
1709                         log_debug("Wrong FIT format: no timestamp\n");
1710                         return -EBADMSG;
1711                 }
1712         }
1713
1714         /* mandatory subimages parent '/images' node */
1715         if (fdt_path_offset(fit, FIT_IMAGES_PATH) < 0) {
1716                 log_debug("Wrong FIT format: no images parent node\n");
1717                 return -ENOENT;
1718         }
1719
1720         return 0;
1721 }
1722
1723 int fit_conf_find_compat(const void *fit, const void *fdt)
1724 {
1725         int ndepth = 0;
1726         int noffset, confs_noffset, images_noffset;
1727         const void *fdt_compat;
1728         int fdt_compat_len;
1729         int best_match_offset = 0;
1730         int best_match_pos = 0;
1731
1732         confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
1733         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
1734         if (confs_noffset < 0 || images_noffset < 0) {
1735                 debug("Can't find configurations or images nodes.\n");
1736                 return -1;
1737         }
1738
1739         fdt_compat = fdt_getprop(fdt, 0, "compatible", &fdt_compat_len);
1740         if (!fdt_compat) {
1741                 debug("Fdt for comparison has no \"compatible\" property.\n");
1742                 return -1;
1743         }
1744
1745         /*
1746          * Loop over the configurations in the FIT image.
1747          */
1748         for (noffset = fdt_next_node(fit, confs_noffset, &ndepth);
1749                         (noffset >= 0) && (ndepth > 0);
1750                         noffset = fdt_next_node(fit, noffset, &ndepth)) {
1751                 const void *fdt;
1752                 const char *kfdt_name;
1753                 int kfdt_noffset, compat_noffset;
1754                 const char *cur_fdt_compat;
1755                 int len;
1756                 size_t sz;
1757                 int i;
1758
1759                 if (ndepth > 1)
1760                         continue;
1761
1762                 /* If there's a compat property in the config node, use that. */
1763                 if (fdt_getprop(fit, noffset, "compatible", NULL)) {
1764                         fdt = fit;                /* search in FIT image */
1765                         compat_noffset = noffset; /* search under config node */
1766                 } else {        /* Otherwise extract it from the kernel FDT. */
1767                         kfdt_name = fdt_getprop(fit, noffset, "fdt", &len);
1768                         if (!kfdt_name) {
1769                                 debug("No fdt property found.\n");
1770                                 continue;
1771                         }
1772                         kfdt_noffset = fdt_subnode_offset(fit, images_noffset,
1773                                                           kfdt_name);
1774                         if (kfdt_noffset < 0) {
1775                                 debug("No image node named \"%s\" found.\n",
1776                                       kfdt_name);
1777                                 continue;
1778                         }
1779
1780                         if (!fit_image_check_comp(fit, kfdt_noffset,
1781                                                   IH_COMP_NONE)) {
1782                                 debug("Can't extract compat from \"%s\" "
1783                                       "(compressed)\n", kfdt_name);
1784                                 continue;
1785                         }
1786
1787                         /* search in this config's kernel FDT */
1788                         if (fit_image_get_data_and_size(fit, kfdt_noffset,
1789                                                         &fdt, &sz)) {
1790                                 debug("Failed to get fdt \"%s\".\n", kfdt_name);
1791                                 continue;
1792                         }
1793
1794                         compat_noffset = 0;  /* search kFDT under root node */
1795                 }
1796
1797                 len = fdt_compat_len;
1798                 cur_fdt_compat = fdt_compat;
1799                 /*
1800                  * Look for a match for each U-Boot compatibility string in
1801                  * turn in the compat string property.
1802                  */
1803                 for (i = 0; len > 0 &&
1804                      (!best_match_offset || best_match_pos > i); i++) {
1805                         int cur_len = strlen(cur_fdt_compat) + 1;
1806
1807                         if (!fdt_node_check_compatible(fdt, compat_noffset,
1808                                                        cur_fdt_compat)) {
1809                                 best_match_offset = noffset;
1810                                 best_match_pos = i;
1811                                 break;
1812                         }
1813                         len -= cur_len;
1814                         cur_fdt_compat += cur_len;
1815                 }
1816         }
1817         if (!best_match_offset) {
1818                 debug("No match found.\n");
1819                 return -1;
1820         }
1821
1822         return best_match_offset;
1823 }
1824
1825 int fit_conf_get_node(const void *fit, const char *conf_uname)
1826 {
1827         int noffset, confs_noffset;
1828         int len;
1829         const char *s;
1830         char *conf_uname_copy = NULL;
1831
1832         confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
1833         if (confs_noffset < 0) {
1834                 debug("Can't find configurations parent node '%s' (%s)\n",
1835                       FIT_CONFS_PATH, fdt_strerror(confs_noffset));
1836                 return confs_noffset;
1837         }
1838
1839         if (conf_uname == NULL) {
1840                 /* get configuration unit name from the default property */
1841                 debug("No configuration specified, trying default...\n");
1842                 if (!tools_build() && IS_ENABLED(CONFIG_MULTI_DTB_FIT)) {
1843                         noffset = fit_find_config_node(fit);
1844                         if (noffset < 0)
1845                                 return noffset;
1846                         conf_uname = fdt_get_name(fit, noffset, NULL);
1847                 } else {
1848                         conf_uname = (char *)fdt_getprop(fit, confs_noffset,
1849                                                          FIT_DEFAULT_PROP, &len);
1850                         if (conf_uname == NULL) {
1851                                 fit_get_debug(fit, confs_noffset, FIT_DEFAULT_PROP,
1852                                               len);
1853                                 return len;
1854                         }
1855                 }
1856                 debug("Found default configuration: '%s'\n", conf_uname);
1857         }
1858
1859         s = strchr(conf_uname, '#');
1860         if (s) {
1861                 len = s - conf_uname;
1862                 conf_uname_copy = malloc(len + 1);
1863                 if (!conf_uname_copy) {
1864                         debug("Can't allocate uname copy: '%s'\n",
1865                                         conf_uname);
1866                         return -ENOMEM;
1867                 }
1868                 memcpy(conf_uname_copy, conf_uname, len);
1869                 conf_uname_copy[len] = '\0';
1870                 conf_uname = conf_uname_copy;
1871         }
1872
1873         noffset = fdt_subnode_offset(fit, confs_noffset, conf_uname);
1874         if (noffset < 0) {
1875                 debug("Can't get node offset for configuration unit name: '%s' (%s)\n",
1876                       conf_uname, fdt_strerror(noffset));
1877         }
1878
1879         free(conf_uname_copy);
1880
1881         return noffset;
1882 }
1883
1884 int fit_conf_get_prop_node_count(const void *fit, int noffset,
1885                 const char *prop_name)
1886 {
1887         return fdt_stringlist_count(fit, noffset, prop_name);
1888 }
1889
1890 int fit_conf_get_prop_node_index(const void *fit, int noffset,
1891                 const char *prop_name, int index)
1892 {
1893         const char *uname;
1894         int len;
1895
1896         /* get kernel image unit name from configuration kernel property */
1897         uname = fdt_stringlist_get(fit, noffset, prop_name, index, &len);
1898         if (uname == NULL)
1899                 return len;
1900
1901         return fit_image_get_node(fit, uname);
1902 }
1903
1904 int fit_conf_get_prop_node(const void *fit, int noffset, const char *prop_name,
1905                            enum image_phase_t sel_phase)
1906 {
1907         int i, count;
1908
1909         if (sel_phase == IH_PHASE_NONE)
1910                 return fit_conf_get_prop_node_index(fit, noffset, prop_name, 0);
1911
1912         count = fit_conf_get_prop_node_count(fit, noffset, prop_name);
1913         if (count < 0)
1914                 return count;
1915
1916         /* check each image in the list */
1917         for (i = 0; i < count; i++) {
1918                 enum image_phase_t phase;
1919                 int ret, node;
1920
1921                 node = fit_conf_get_prop_node_index(fit, noffset, prop_name, i);
1922                 ret = fit_image_get_phase(fit, node, &phase);
1923
1924                 /* if the image is for any phase, let's use it */
1925                 if (ret == -ENOENT)
1926                         return node;
1927                 else if (ret < 0)
1928                         return ret;
1929
1930                 if (phase == sel_phase)
1931                         return node;
1932         }
1933
1934         return -ENOENT;
1935 }
1936
1937 static int fit_get_data_tail(const void *fit, int noffset,
1938                              const void **data, size_t *size)
1939 {
1940         char *desc;
1941
1942         if (noffset < 0)
1943                 return noffset;
1944
1945         if (!fit_image_verify(fit, noffset))
1946                 return -EINVAL;
1947
1948         if (fit_image_get_data_and_size(fit, noffset, data, size))
1949                 return -ENOENT;
1950
1951         if (!fit_get_desc(fit, noffset, &desc))
1952                 printf("%s\n", desc);
1953
1954         return 0;
1955 }
1956
1957 int fit_get_data_node(const void *fit, const char *image_uname,
1958                       const void **data, size_t *size)
1959 {
1960         int noffset = fit_image_get_node(fit, image_uname);
1961
1962         return fit_get_data_tail(fit, noffset, data, size);
1963 }
1964
1965 int fit_get_data_conf_prop(const void *fit, const char *prop_name,
1966                            const void **data, size_t *size)
1967 {
1968         int noffset = fit_conf_get_node(fit, NULL);
1969
1970         noffset = fit_conf_get_prop_node(fit, noffset, prop_name,
1971                                          IH_PHASE_NONE);
1972         return fit_get_data_tail(fit, noffset, data, size);
1973 }
1974
1975 static int fit_image_select(const void *fit, int rd_noffset, int verify)
1976 {
1977         fit_image_print(fit, rd_noffset, "   ");
1978
1979         if (verify) {
1980                 puts("   Verifying Hash Integrity ... ");
1981                 if (!fit_image_verify(fit, rd_noffset)) {
1982                         puts("Bad Data Hash\n");
1983                         return -EACCES;
1984                 }
1985                 puts("OK\n");
1986         }
1987
1988         return 0;
1989 }
1990
1991 int fit_get_node_from_config(struct bootm_headers *images,
1992                              const char *prop_name, ulong addr)
1993 {
1994         int cfg_noffset;
1995         void *fit_hdr;
1996         int noffset;
1997
1998         debug("*  %s: using config '%s' from image at 0x%08lx\n",
1999               prop_name, images->fit_uname_cfg, addr);
2000
2001         /* Check whether configuration has this property defined */
2002         fit_hdr = map_sysmem(addr, 0);
2003         cfg_noffset = fit_conf_get_node(fit_hdr, images->fit_uname_cfg);
2004         if (cfg_noffset < 0) {
2005                 debug("*  %s: no such config\n", prop_name);
2006                 return -EINVAL;
2007         }
2008
2009         noffset = fit_conf_get_prop_node(fit_hdr, cfg_noffset, prop_name,
2010                                          IH_PHASE_NONE);
2011         if (noffset < 0) {
2012                 debug("*  %s: no '%s' in config\n", prop_name, prop_name);
2013                 return -ENOENT;
2014         }
2015
2016         return noffset;
2017 }
2018
2019 /**
2020  * fit_get_image_type_property() - get property name for IH_TYPE_...
2021  *
2022  * Return: the properly name where we expect to find the image in the
2023  * config node
2024  */
2025 static const char *fit_get_image_type_property(int type)
2026 {
2027         /*
2028          * This is sort-of available in the uimage_type[] table in image.c
2029          * but we don't have access to the short name, and "fdt" is different
2030          * anyway. So let's just keep it here.
2031          */
2032         switch (type) {
2033         case IH_TYPE_FLATDT:
2034                 return FIT_FDT_PROP;
2035         case IH_TYPE_KERNEL:
2036                 return FIT_KERNEL_PROP;
2037         case IH_TYPE_FIRMWARE:
2038                 return FIT_FIRMWARE_PROP;
2039         case IH_TYPE_RAMDISK:
2040                 return FIT_RAMDISK_PROP;
2041         case IH_TYPE_X86_SETUP:
2042                 return FIT_SETUP_PROP;
2043         case IH_TYPE_LOADABLE:
2044                 return FIT_LOADABLE_PROP;
2045         case IH_TYPE_FPGA:
2046                 return FIT_FPGA_PROP;
2047         case IH_TYPE_STANDALONE:
2048                 return FIT_STANDALONE_PROP;
2049         }
2050
2051         return "unknown";
2052 }
2053
2054 int fit_image_load(struct bootm_headers *images, ulong addr,
2055                    const char **fit_unamep, const char **fit_uname_configp,
2056                    int arch, int ph_type, int bootstage_id,
2057                    enum fit_load_op load_op, ulong *datap, ulong *lenp)
2058 {
2059         int image_type = image_ph_type(ph_type);
2060         int cfg_noffset, noffset;
2061         const char *fit_uname;
2062         const char *fit_uname_config;
2063         const char *fit_base_uname_config;
2064         const void *fit;
2065         void *buf;
2066         void *loadbuf;
2067         size_t size;
2068         int type_ok, os_ok;
2069         ulong load, load_end, data, len;
2070         uint8_t os, comp;
2071         const char *prop_name;
2072         int ret;
2073
2074         fit = map_sysmem(addr, 0);
2075         fit_uname = fit_unamep ? *fit_unamep : NULL;
2076         fit_uname_config = fit_uname_configp ? *fit_uname_configp : NULL;
2077         fit_base_uname_config = NULL;
2078         prop_name = fit_get_image_type_property(image_type);
2079         printf("## Loading %s from FIT Image at %08lx ...\n", prop_name, addr);
2080
2081         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_FORMAT);
2082         ret = fit_check_format(fit, IMAGE_SIZE_INVAL);
2083         if (ret) {
2084                 printf("Bad FIT %s image format! (err=%d)\n", prop_name, ret);
2085                 if (CONFIG_IS_ENABLED(FIT_SIGNATURE) && ret == -EADDRNOTAVAIL)
2086                         printf("Signature checking prevents use of unit addresses (@) in nodes\n");
2087                 bootstage_error(bootstage_id + BOOTSTAGE_SUB_FORMAT);
2088                 return ret;
2089         }
2090         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_FORMAT_OK);
2091         if (fit_uname) {
2092                 /* get FIT component image node offset */
2093                 bootstage_mark(bootstage_id + BOOTSTAGE_SUB_UNIT_NAME);
2094                 noffset = fit_image_get_node(fit, fit_uname);
2095         } else {
2096                 /*
2097                  * no image node unit name, try to get config
2098                  * node first. If config unit node name is NULL
2099                  * fit_conf_get_node() will try to find default config node
2100                  */
2101                 bootstage_mark(bootstage_id + BOOTSTAGE_SUB_NO_UNIT_NAME);
2102                 if (IS_ENABLED(CONFIG_FIT_BEST_MATCH) && !fit_uname_config) {
2103                         cfg_noffset = fit_conf_find_compat(fit, gd_fdt_blob());
2104                 } else {
2105                         cfg_noffset = fit_conf_get_node(fit, fit_uname_config);
2106                 }
2107                 if (cfg_noffset < 0) {
2108                         puts("Could not find configuration node\n");
2109                         bootstage_error(bootstage_id +
2110                                         BOOTSTAGE_SUB_NO_UNIT_NAME);
2111                         return -ENOENT;
2112                 }
2113
2114                 fit_base_uname_config = fdt_get_name(fit, cfg_noffset, NULL);
2115                 printf("   Using '%s' configuration\n", fit_base_uname_config);
2116                 /* Remember this config */
2117                 if (image_type == IH_TYPE_KERNEL)
2118                         images->fit_uname_cfg = fit_base_uname_config;
2119
2120                 if (FIT_IMAGE_ENABLE_VERIFY && images->verify) {
2121                         puts("   Verifying Hash Integrity ... ");
2122                         if (fit_config_verify(fit, cfg_noffset)) {
2123                                 puts("Bad Data Hash\n");
2124                                 bootstage_error(bootstage_id +
2125                                         BOOTSTAGE_SUB_HASH);
2126                                 return -EACCES;
2127                         }
2128                         puts("OK\n");
2129                 }
2130
2131                 bootstage_mark(BOOTSTAGE_ID_FIT_CONFIG);
2132
2133                 noffset = fit_conf_get_prop_node(fit, cfg_noffset, prop_name,
2134                                                  image_ph_phase(ph_type));
2135                 fit_uname = fit_get_name(fit, noffset, NULL);
2136         }
2137         if (noffset < 0) {
2138                 printf("Could not find subimage node type '%s'\n", prop_name);
2139                 bootstage_error(bootstage_id + BOOTSTAGE_SUB_SUBNODE);
2140                 return -ENOENT;
2141         }
2142
2143         printf("   Trying '%s' %s subimage\n", fit_uname, prop_name);
2144
2145         ret = fit_image_select(fit, noffset, images->verify);
2146         if (ret) {
2147                 bootstage_error(bootstage_id + BOOTSTAGE_SUB_HASH);
2148                 return ret;
2149         }
2150
2151         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_CHECK_ARCH);
2152         if (!tools_build() && IS_ENABLED(CONFIG_SANDBOX)) {
2153                 if (!fit_image_check_target_arch(fit, noffset)) {
2154                         puts("Unsupported Architecture\n");
2155                         bootstage_error(bootstage_id + BOOTSTAGE_SUB_CHECK_ARCH);
2156                         return -ENOEXEC;
2157                 }
2158         }
2159
2160 #ifndef USE_HOSTCC
2161         {
2162         uint8_t os_arch;
2163
2164         fit_image_get_arch(fit, noffset, &os_arch);
2165         images->os.arch = os_arch;
2166         }
2167 #endif
2168
2169         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_CHECK_ALL);
2170         type_ok = fit_image_check_type(fit, noffset, image_type) ||
2171                   fit_image_check_type(fit, noffset, IH_TYPE_FIRMWARE) ||
2172                   fit_image_check_type(fit, noffset, IH_TYPE_TEE) ||
2173                   (image_type == IH_TYPE_KERNEL &&
2174                    fit_image_check_type(fit, noffset, IH_TYPE_KERNEL_NOLOAD));
2175
2176         os_ok = image_type == IH_TYPE_FLATDT ||
2177                 image_type == IH_TYPE_FPGA ||
2178                 fit_image_check_os(fit, noffset, IH_OS_LINUX) ||
2179                 fit_image_check_os(fit, noffset, IH_OS_U_BOOT) ||
2180                 fit_image_check_os(fit, noffset, IH_OS_TEE) ||
2181                 fit_image_check_os(fit, noffset, IH_OS_OPENRTOS) ||
2182                 fit_image_check_os(fit, noffset, IH_OS_EFI) ||
2183                 fit_image_check_os(fit, noffset, IH_OS_VXWORKS);
2184
2185         /*
2186          * If either of the checks fail, we should report an error, but
2187          * if the image type is coming from the "loadables" field, we
2188          * don't care what it is
2189          */
2190         if ((!type_ok || !os_ok) && image_type != IH_TYPE_LOADABLE) {
2191                 fit_image_get_os(fit, noffset, &os);
2192                 printf("No %s %s %s Image\n",
2193                        genimg_get_os_name(os),
2194                        genimg_get_arch_name(arch),
2195                        genimg_get_type_name(image_type));
2196                 bootstage_error(bootstage_id + BOOTSTAGE_SUB_CHECK_ALL);
2197                 return -EIO;
2198         }
2199
2200         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_CHECK_ALL_OK);
2201
2202         /* get image data address and length */
2203         if (fit_image_get_data_and_size(fit, noffset,
2204                                         (const void **)&buf, &size)) {
2205                 printf("Could not find %s subimage data!\n", prop_name);
2206                 bootstage_error(bootstage_id + BOOTSTAGE_SUB_GET_DATA);
2207                 return -ENOENT;
2208         }
2209
2210         /* Decrypt data before uncompress/move */
2211         if (IS_ENABLED(CONFIG_FIT_CIPHER) && IMAGE_ENABLE_DECRYPT) {
2212                 puts("   Decrypting Data ... ");
2213                 if (fit_image_uncipher(fit, noffset, &buf, &size)) {
2214                         puts("Error\n");
2215                         return -EACCES;
2216                 }
2217                 puts("OK\n");
2218         }
2219
2220         /* perform any post-processing on the image data */
2221         if (!tools_build() && IS_ENABLED(CONFIG_FIT_IMAGE_POST_PROCESS))
2222                 board_fit_image_post_process(fit, noffset, &buf, &size);
2223
2224         len = (ulong)size;
2225
2226         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_GET_DATA_OK);
2227
2228         data = map_to_sysmem(buf);
2229         load = data;
2230         if (load_op == FIT_LOAD_IGNORED) {
2231                 /* Don't load */
2232         } else if (fit_image_get_load(fit, noffset, &load)) {
2233                 if (load_op == FIT_LOAD_REQUIRED) {
2234                         printf("Can't get %s subimage load address!\n",
2235                                prop_name);
2236                         bootstage_error(bootstage_id + BOOTSTAGE_SUB_LOAD);
2237                         return -EBADF;
2238                 }
2239         } else if (load_op != FIT_LOAD_OPTIONAL_NON_ZERO || load) {
2240                 ulong image_start, image_end;
2241
2242                 /*
2243                  * move image data to the load address,
2244                  * make sure we don't overwrite initial image
2245                  */
2246                 image_start = addr;
2247                 image_end = addr + fit_get_size(fit);
2248
2249                 load_end = load + len;
2250                 if (image_type != IH_TYPE_KERNEL &&
2251                     load < image_end && load_end > image_start) {
2252                         printf("Error: %s overwritten\n", prop_name);
2253                         return -EXDEV;
2254                 }
2255
2256                 printf("   Loading %s from 0x%08lx to 0x%08lx\n",
2257                        prop_name, data, load);
2258         } else {
2259                 load = data;    /* No load address specified */
2260         }
2261
2262         comp = IH_COMP_NONE;
2263         loadbuf = buf;
2264         /* Kernel images get decompressed later in bootm_load_os(). */
2265         if (!fit_image_get_comp(fit, noffset, &comp) &&
2266             comp != IH_COMP_NONE &&
2267             !(image_type == IH_TYPE_KERNEL ||
2268               image_type == IH_TYPE_KERNEL_NOLOAD ||
2269               image_type == IH_TYPE_RAMDISK)) {
2270                 ulong max_decomp_len = len * 20;
2271                 if (load == data) {
2272                         loadbuf = malloc(max_decomp_len);
2273                         load = map_to_sysmem(loadbuf);
2274                 } else {
2275                         loadbuf = map_sysmem(load, max_decomp_len);
2276                 }
2277                 if (image_decomp(comp, load, data, image_type,
2278                                 loadbuf, buf, len, max_decomp_len, &load_end)) {
2279                         printf("Error decompressing %s\n", prop_name);
2280
2281                         return -ENOEXEC;
2282                 }
2283                 len = load_end - load;
2284         } else if (load != data) {
2285                 loadbuf = map_sysmem(load, len);
2286                 memcpy(loadbuf, buf, len);
2287         }
2288
2289         if (image_type == IH_TYPE_RAMDISK && comp != IH_COMP_NONE)
2290                 puts("WARNING: 'compression' nodes for ramdisks are deprecated,"
2291                      " please fix your .its file!\n");
2292
2293         /* verify that image data is a proper FDT blob */
2294         if (image_type == IH_TYPE_FLATDT && fdt_check_header(loadbuf)) {
2295                 puts("Subimage data is not a FDT");
2296                 return -ENOEXEC;
2297         }
2298
2299         bootstage_mark(bootstage_id + BOOTSTAGE_SUB_LOAD);
2300
2301         *datap = load;
2302         *lenp = len;
2303         if (fit_unamep)
2304                 *fit_unamep = (char *)fit_uname;
2305         if (fit_uname_configp)
2306                 *fit_uname_configp = (char *)(fit_uname_config ? :
2307                                               fit_base_uname_config);
2308
2309         return noffset;
2310 }
2311
2312 int boot_get_setup_fit(struct bootm_headers *images, uint8_t arch,
2313                        ulong *setup_start, ulong *setup_len)
2314 {
2315         int noffset;
2316         ulong addr;
2317         ulong len;
2318         int ret;
2319
2320         addr = map_to_sysmem(images->fit_hdr_os);
2321         noffset = fit_get_node_from_config(images, FIT_SETUP_PROP, addr);
2322         if (noffset < 0)
2323                 return noffset;
2324
2325         ret = fit_image_load(images, addr, NULL, NULL, arch,
2326                              IH_TYPE_X86_SETUP, BOOTSTAGE_ID_FIT_SETUP_START,
2327                              FIT_LOAD_REQUIRED, setup_start, &len);
2328
2329         return ret;
2330 }
2331
2332 #ifndef USE_HOSTCC
2333 int boot_get_fdt_fit(struct bootm_headers *images, ulong addr,
2334                      const char **fit_unamep, const char **fit_uname_configp,
2335                      int arch, ulong *datap, ulong *lenp)
2336 {
2337         int fdt_noffset, cfg_noffset, count;
2338         const void *fit;
2339         const char *fit_uname = NULL;
2340         const char *fit_uname_config = NULL;
2341         char *fit_uname_config_copy = NULL;
2342         char *next_config = NULL;
2343         ulong load, len;
2344 #ifdef CONFIG_OF_LIBFDT_OVERLAY
2345         ulong image_start, image_end;
2346         ulong ovload, ovlen, ovcopylen;
2347         const char *uconfig;
2348         const char *uname;
2349         void *base, *ov, *ovcopy = NULL;
2350         int i, err, noffset, ov_noffset;
2351 #endif
2352
2353         fit_uname = fit_unamep ? *fit_unamep : NULL;
2354
2355         if (fit_uname_configp && *fit_uname_configp) {
2356                 fit_uname_config_copy = strdup(*fit_uname_configp);
2357                 if (!fit_uname_config_copy)
2358                         return -ENOMEM;
2359
2360                 next_config = strchr(fit_uname_config_copy, '#');
2361                 if (next_config)
2362                         *next_config++ = '\0';
2363                 if (next_config - 1 > fit_uname_config_copy)
2364                         fit_uname_config = fit_uname_config_copy;
2365         }
2366
2367         fdt_noffset = fit_image_load(images,
2368                 addr, &fit_uname, &fit_uname_config,
2369                 arch, IH_TYPE_FLATDT,
2370                 BOOTSTAGE_ID_FIT_FDT_START,
2371                 FIT_LOAD_OPTIONAL, &load, &len);
2372
2373         if (fdt_noffset < 0)
2374                 goto out;
2375
2376         debug("fit_uname=%s, fit_uname_config=%s\n",
2377                         fit_uname ? fit_uname : "<NULL>",
2378                         fit_uname_config ? fit_uname_config : "<NULL>");
2379
2380         fit = map_sysmem(addr, 0);
2381
2382         cfg_noffset = fit_conf_get_node(fit, fit_uname_config);
2383
2384         /* single blob, or error just return as well */
2385         count = fit_conf_get_prop_node_count(fit, cfg_noffset, FIT_FDT_PROP);
2386         if (count <= 1 && !next_config)
2387                 goto out;
2388
2389         /* we need to apply overlays */
2390
2391 #ifdef CONFIG_OF_LIBFDT_OVERLAY
2392         image_start = addr;
2393         image_end = addr + fit_get_size(fit);
2394         /* verify that relocation took place by load address not being in fit */
2395         if (load >= image_start && load < image_end) {
2396                 /* check is simplified; fit load checks for overlaps */
2397                 printf("Overlayed FDT requires relocation\n");
2398                 fdt_noffset = -EBADF;
2399                 goto out;
2400         }
2401
2402         base = map_sysmem(load, len);
2403
2404         /* apply extra configs in FIT first, followed by args */
2405         for (i = 1; ; i++) {
2406                 if (i < count) {
2407                         noffset = fit_conf_get_prop_node_index(fit, cfg_noffset,
2408                                                                FIT_FDT_PROP, i);
2409                         uname = fit_get_name(fit, noffset, NULL);
2410                         uconfig = NULL;
2411                 } else {
2412                         if (!next_config)
2413                                 break;
2414                         uconfig = next_config;
2415                         next_config = strchr(next_config, '#');
2416                         if (next_config)
2417                                 *next_config++ = '\0';
2418                         uname = NULL;
2419
2420                         /*
2421                          * fit_image_load() would load the first FDT from the
2422                          * extra config only when uconfig is specified.
2423                          * Check if the extra config contains multiple FDTs and
2424                          * if so, load them.
2425                          */
2426                         cfg_noffset = fit_conf_get_node(fit, uconfig);
2427
2428                         i = 0;
2429                         count = fit_conf_get_prop_node_count(fit, cfg_noffset,
2430                                                              FIT_FDT_PROP);
2431                 }
2432
2433                 debug("%d: using uname=%s uconfig=%s\n", i, uname, uconfig);
2434
2435                 ov_noffset = fit_image_load(images,
2436                         addr, &uname, &uconfig,
2437                         arch, IH_TYPE_FLATDT,
2438                         BOOTSTAGE_ID_FIT_FDT_START,
2439                         FIT_LOAD_IGNORED, &ovload, &ovlen);
2440                 if (ov_noffset < 0) {
2441                         printf("load of %s failed\n", uname);
2442                         continue;
2443                 }
2444                 debug("%s loaded at 0x%08lx len=0x%08lx\n",
2445                                 uname, ovload, ovlen);
2446                 ov = map_sysmem(ovload, ovlen);
2447
2448                 ovcopylen = ALIGN(fdt_totalsize(ov), SZ_4K);
2449                 ovcopy = malloc(ovcopylen);
2450                 if (!ovcopy) {
2451                         printf("failed to duplicate DTO before application\n");
2452                         fdt_noffset = -ENOMEM;
2453                         goto out;
2454                 }
2455
2456                 err = fdt_open_into(ov, ovcopy, ovcopylen);
2457                 if (err < 0) {
2458                         printf("failed on fdt_open_into for DTO\n");
2459                         fdt_noffset = err;
2460                         goto out;
2461                 }
2462
2463                 base = map_sysmem(load, len + ovlen);
2464                 err = fdt_open_into(base, base, len + ovlen);
2465                 if (err < 0) {
2466                         printf("failed on fdt_open_into\n");
2467                         fdt_noffset = err;
2468                         goto out;
2469                 }
2470
2471                 /* the verbose method prints out messages on error */
2472                 err = fdt_overlay_apply_verbose(base, ovcopy);
2473                 if (err < 0) {
2474                         fdt_noffset = err;
2475                         goto out;
2476                 }
2477                 fdt_pack(base);
2478                 len = fdt_totalsize(base);
2479         }
2480 #else
2481         printf("config with overlays but CONFIG_OF_LIBFDT_OVERLAY not set\n");
2482         fdt_noffset = -EBADF;
2483 #endif
2484
2485 out:
2486         if (datap)
2487                 *datap = load;
2488         if (lenp)
2489                 *lenp = len;
2490         if (fit_unamep)
2491                 *fit_unamep = fit_uname;
2492         if (fit_uname_configp)
2493                 *fit_uname_configp = fit_uname_config;
2494
2495 #ifdef CONFIG_OF_LIBFDT_OVERLAY
2496         free(ovcopy);
2497 #endif
2498         free(fit_uname_config_copy);
2499         return fdt_noffset;
2500 }
2501 #endif