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