common: Drop image.h from common header
[platform/kernel/u-boot.git] / common / spl / spl_fit.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2016 Google, Inc
4  * Written by Simon Glass <sjg@chromium.org>
5  */
6
7 #include <common.h>
8 #include <errno.h>
9 #include <board.h>
10 #include <fpga.h>
11 #include <gzip.h>
12 #include <image.h>
13 #include <malloc.h>
14 #include <spl.h>
15 #include <asm/cache.h>
16 #include <linux/libfdt.h>
17
18 DECLARE_GLOBAL_DATA_PTR;
19
20 #ifndef CONFIG_SPL_LOAD_FIT_APPLY_OVERLAY_BUF_SZ
21 #define CONFIG_SPL_LOAD_FIT_APPLY_OVERLAY_BUF_SZ (64 * 1024)
22 #endif
23
24 #ifndef CONFIG_SYS_BOOTM_LEN
25 #define CONFIG_SYS_BOOTM_LEN    (64 << 20)
26 #endif
27
28 __weak void board_spl_fit_post_load(ulong load_addr, size_t length)
29 {
30 }
31
32 __weak ulong board_spl_fit_size_align(ulong size)
33 {
34         return size;
35 }
36
37 static int find_node_from_desc(const void *fit, int node, const char *str)
38 {
39         int child;
40
41         if (node < 0)
42                 return -EINVAL;
43
44         /* iterate the FIT nodes and find a matching description */
45         for (child = fdt_first_subnode(fit, node); child >= 0;
46              child = fdt_next_subnode(fit, child)) {
47                 int len;
48                 const char *desc = fdt_getprop(fit, child, "description", &len);
49
50                 if (!desc)
51                         continue;
52
53                 if (!strcmp(desc, str))
54                         return child;
55         }
56
57         return -ENOENT;
58 }
59
60 /**
61  * spl_fit_get_image_name(): By using the matching configuration subnode,
62  * retrieve the name of an image, specified by a property name and an index
63  * into that.
64  * @fit:        Pointer to the FDT blob.
65  * @images:     Offset of the /images subnode.
66  * @type:       Name of the property within the configuration subnode.
67  * @index:      Index into the list of strings in this property.
68  * @outname:    Name of the image
69  *
70  * Return:      0 on success, or a negative error number
71  */
72 static int spl_fit_get_image_name(const void *fit, int images,
73                                   const char *type, int index,
74                                   const char **outname)
75 {
76         struct udevice *board;
77         const char *name, *str;
78         __maybe_unused int node;
79         int conf_node;
80         int len, i;
81         bool found = true;
82
83         conf_node = fit_find_config_node(fit);
84         if (conf_node < 0) {
85 #ifdef CONFIG_SPL_LIBCOMMON_SUPPORT
86                 printf("No matching DT out of these options:\n");
87                 for (node = fdt_first_subnode(fit, conf_node);
88                      node >= 0;
89                      node = fdt_next_subnode(fit, node)) {
90                         name = fdt_getprop(fit, node, "description", &len);
91                         printf("   %s\n", name);
92                 }
93 #endif
94                 return conf_node;
95         }
96
97         name = fdt_getprop(fit, conf_node, type, &len);
98         if (!name) {
99                 debug("cannot find property '%s': %d\n", type, len);
100                 return -EINVAL;
101         }
102
103         str = name;
104         for (i = 0; i < index; i++) {
105                 str = strchr(str, '\0') + 1;
106                 if (!str || (str - name >= len)) {
107                         found = false;
108                         break;
109                 }
110         }
111
112         if (!found && !board_get(&board)) {
113                 int rc;
114                 /*
115                  * no string in the property for this index. Check if the board
116                  * level code can supply one.
117                  */
118                 rc = board_get_fit_loadable(board, index - i - 1, type, &str);
119                 if (rc && rc != -ENOENT)
120                         return rc;
121
122                 if (!rc) {
123                         /*
124                          * The board provided a name for a loadable.
125                          * Try to match it against the description properties
126                          * first. If no matching node is found, use it as a
127                          * node name.
128                          */
129                         int node;
130                         int images = fdt_path_offset(fit, FIT_IMAGES_PATH);
131
132                         node = find_node_from_desc(fit, images, str);
133                         if (node > 0)
134                                 str = fdt_get_name(fit, node, NULL);
135
136                         found = true;
137                 }
138         }
139
140         if (!found) {
141                 debug("no string for index %d\n", index);
142                 return -E2BIG;
143         }
144
145         *outname = str;
146         return 0;
147 }
148
149 /**
150  * spl_fit_get_image_node(): By using the matching configuration subnode,
151  * retrieve the name of an image, specified by a property name and an index
152  * into that.
153  * @fit:        Pointer to the FDT blob.
154  * @images:     Offset of the /images subnode.
155  * @type:       Name of the property within the configuration subnode.
156  * @index:      Index into the list of strings in this property.
157  *
158  * Return:      the node offset of the respective image node or a negative
159  *              error number.
160  */
161 static int spl_fit_get_image_node(const void *fit, int images,
162                                   const char *type, int index)
163 {
164         const char *str;
165         int err;
166         int node;
167
168         err = spl_fit_get_image_name(fit, images, type, index, &str);
169         if (err)
170                 return err;
171
172         debug("%s: '%s'\n", type, str);
173
174         node = fdt_subnode_offset(fit, images, str);
175         if (node < 0) {
176                 pr_err("cannot find image node '%s': %d\n", str, node);
177                 return -EINVAL;
178         }
179
180         return node;
181 }
182
183 static int get_aligned_image_offset(struct spl_load_info *info, int offset)
184 {
185         /*
186          * If it is a FS read, get the first address before offset which is
187          * aligned to ARCH_DMA_MINALIGN. If it is raw read return the
188          * block number to which offset belongs.
189          */
190         if (info->filename)
191                 return offset & ~(ARCH_DMA_MINALIGN - 1);
192
193         return offset / info->bl_len;
194 }
195
196 static int get_aligned_image_overhead(struct spl_load_info *info, int offset)
197 {
198         /*
199          * If it is a FS read, get the difference between the offset and
200          * the first address before offset which is aligned to
201          * ARCH_DMA_MINALIGN. If it is raw read return the offset within the
202          * block.
203          */
204         if (info->filename)
205                 return offset & (ARCH_DMA_MINALIGN - 1);
206
207         return offset % info->bl_len;
208 }
209
210 static int get_aligned_image_size(struct spl_load_info *info, int data_size,
211                                   int offset)
212 {
213         data_size = data_size + get_aligned_image_overhead(info, offset);
214
215         if (info->filename)
216                 return data_size;
217
218         return (data_size + info->bl_len - 1) / info->bl_len;
219 }
220
221 /**
222  * spl_load_fit_image(): load the image described in a certain FIT node
223  * @info:       points to information about the device to load data from
224  * @sector:     the start sector of the FIT image on the device
225  * @fit:        points to the flattened device tree blob describing the FIT
226  *              image
227  * @base_offset: the beginning of the data area containing the actual
228  *              image data, relative to the beginning of the FIT
229  * @node:       offset of the DT node describing the image to load (relative
230  *              to @fit)
231  * @image_info: will be filled with information about the loaded image
232  *              If the FIT node does not contain a "load" (address) property,
233  *              the image gets loaded to the address pointed to by the
234  *              load_addr member in this struct.
235  *
236  * Return:      0 on success or a negative error number.
237  */
238 static int spl_load_fit_image(struct spl_load_info *info, ulong sector,
239                               void *fit, ulong base_offset, int node,
240                               struct spl_image_info *image_info)
241 {
242         int offset;
243         size_t length;
244         int len;
245         ulong size;
246         ulong load_addr, load_ptr;
247         void *src;
248         ulong overhead;
249         int nr_sectors;
250         int align_len = ARCH_DMA_MINALIGN - 1;
251         uint8_t image_comp = -1, type = -1;
252         const void *data;
253         bool external_data = false;
254
255         if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
256             (IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
257                 if (fit_image_get_type(fit, node, &type))
258                         puts("Cannot get image type.\n");
259                 else
260                         debug("%s ", genimg_get_type_name(type));
261         }
262
263         if (IS_ENABLED(CONFIG_SPL_GZIP)) {
264                 fit_image_get_comp(fit, node, &image_comp);
265                 debug("%s ", genimg_get_comp_name(image_comp));
266         }
267
268         if (fit_image_get_load(fit, node, &load_addr))
269                 load_addr = image_info->load_addr;
270
271         if (!fit_image_get_data_position(fit, node, &offset)) {
272                 external_data = true;
273         } else if (!fit_image_get_data_offset(fit, node, &offset)) {
274                 offset += base_offset;
275                 external_data = true;
276         }
277
278         if (external_data) {
279                 /* External data */
280                 if (fit_image_get_data_size(fit, node, &len))
281                         return -ENOENT;
282
283                 load_ptr = (load_addr + align_len) & ~align_len;
284                 length = len;
285
286                 overhead = get_aligned_image_overhead(info, offset);
287                 nr_sectors = get_aligned_image_size(info, length, offset);
288
289                 if (info->read(info,
290                                sector + get_aligned_image_offset(info, offset),
291                                nr_sectors, (void *)load_ptr) != nr_sectors)
292                         return -EIO;
293
294                 debug("External data: dst=%lx, offset=%x, size=%lx\n",
295                       load_ptr, offset, (unsigned long)length);
296                 src = (void *)load_ptr + overhead;
297         } else {
298                 /* Embedded data */
299                 if (fit_image_get_data(fit, node, &data, &length)) {
300                         puts("Cannot get image data/size\n");
301                         return -ENOENT;
302                 }
303                 debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
304                       (unsigned long)length);
305                 src = (void *)data;
306         }
307
308 #ifdef CONFIG_SPL_FIT_SIGNATURE
309         printf("## Checking hash(es) for Image %s ... ",
310                fit_get_name(fit, node, NULL));
311         if (!fit_image_verify_with_data(fit, node,
312                                          src, length))
313                 return -EPERM;
314         puts("OK\n");
315 #endif
316
317 #ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
318         board_fit_image_post_process(&src, &length);
319 #endif
320
321         if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
322                 size = length;
323                 if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
324                            src, &size)) {
325                         puts("Uncompressing error\n");
326                         return -EIO;
327                 }
328                 length = size;
329         } else {
330                 memcpy((void *)load_addr, src, length);
331         }
332
333         if (image_info) {
334                 image_info->load_addr = load_addr;
335                 image_info->size = length;
336                 image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
337         }
338
339         return 0;
340 }
341
342 static int spl_fit_append_fdt(struct spl_image_info *spl_image,
343                               struct spl_load_info *info, ulong sector,
344                               void *fit, int images, ulong base_offset)
345 {
346         struct spl_image_info image_info;
347         int node, ret = 0, index = 0;
348
349         /*
350          * Use the address following the image as target address for the
351          * device tree.
352          */
353         image_info.load_addr = spl_image->load_addr + spl_image->size;
354
355         /* Figure out which device tree the board wants to use */
356         node = spl_fit_get_image_node(fit, images, FIT_FDT_PROP, index++);
357         if (node < 0) {
358                 debug("%s: cannot find FDT node\n", __func__);
359
360                 /*
361                  * U-Boot did not find a device tree inside the FIT image. Use
362                  * the U-Boot device tree instead.
363                  */
364                 if (gd->fdt_blob)
365                         memcpy((void *)image_info.load_addr, gd->fdt_blob,
366                                fdt_totalsize(gd->fdt_blob));
367                 else
368                         return node;
369         } else {
370                 ret = spl_load_fit_image(info, sector, fit, base_offset, node,
371                                          &image_info);
372                 if (ret < 0)
373                         return ret;
374         }
375
376         /* Make the load-address of the FDT available for the SPL framework */
377         spl_image->fdt_addr = (void *)image_info.load_addr;
378 #if !CONFIG_IS_ENABLED(FIT_IMAGE_TINY)
379         if (CONFIG_IS_ENABLED(LOAD_FIT_APPLY_OVERLAY)) {
380                 void *tmpbuffer = NULL;
381
382                 for (; ; index++) {
383                         node = spl_fit_get_image_node(fit, images, FIT_FDT_PROP,
384                                                       index);
385                         if (node == -E2BIG) {
386                                 debug("%s: No additional FDT node\n", __func__);
387                                 break;
388                         } else if (node < 0) {
389                                 debug("%s: unable to find FDT node %d\n",
390                                       __func__, index);
391                                 continue;
392                         }
393
394                         if (!tmpbuffer) {
395                                 /*
396                                  * allocate memory to store the DT overlay
397                                  * before it is applied. It may not be used
398                                  * depending on how the overlay is stored, so
399                                  * don't fail yet if the allocation failed.
400                                  */
401                                 tmpbuffer = malloc(CONFIG_SPL_LOAD_FIT_APPLY_OVERLAY_BUF_SZ);
402                                 if (!tmpbuffer)
403                                         debug("%s: unable to allocate space for overlays\n",
404                                               __func__);
405                         }
406                         image_info.load_addr = (ulong)tmpbuffer;
407                         ret = spl_load_fit_image(info, sector, fit, base_offset,
408                                                  node, &image_info);
409                         if (ret < 0)
410                                 break;
411
412                         /* Make room in FDT for changes from the overlay */
413                         ret = fdt_increase_size(spl_image->fdt_addr,
414                                                 image_info.size);
415                         if (ret < 0)
416                                 break;
417
418                         ret = fdt_overlay_apply_verbose(spl_image->fdt_addr,
419                                                         (void *)image_info.load_addr);
420                         if (ret) {
421                                 pr_err("failed to apply DT overlay %s\n",
422                                        fit_get_name(fit, node, NULL));
423                                 break;
424                         }
425
426                         debug("%s: DT overlay %s applied\n", __func__,
427                               fit_get_name(fit, node, NULL));
428                 }
429                 free(tmpbuffer);
430                 if (ret)
431                         return ret;
432         }
433         /* Try to make space, so we can inject details on the loadables */
434         ret = fdt_shrink_to_minimum(spl_image->fdt_addr, 8192);
435         if (ret < 0)
436                 return ret;
437 #endif
438
439         return ret;
440 }
441
442 static int spl_fit_record_loadable(const void *fit, int images, int index,
443                                    void *blob, struct spl_image_info *image)
444 {
445         int ret = 0;
446 #if !CONFIG_IS_ENABLED(FIT_IMAGE_TINY)
447         const char *name;
448         int node;
449
450         ret = spl_fit_get_image_name(fit, images, "loadables",
451                                      index, &name);
452         if (ret < 0)
453                 return ret;
454
455         node = spl_fit_get_image_node(fit, images, "loadables", index);
456
457         ret = fdt_record_loadable(blob, index, name, image->load_addr,
458                                   image->size, image->entry_point,
459                                   fdt_getprop(fit, node, "type", NULL),
460                                   fdt_getprop(fit, node, "os", NULL));
461 #endif
462         return ret;
463 }
464
465 static int spl_fit_image_get_os(const void *fit, int noffset, uint8_t *os)
466 {
467 #if CONFIG_IS_ENABLED(FIT_IMAGE_TINY) && !defined(CONFIG_SPL_OS_BOOT)
468         return -ENOTSUPP;
469 #else
470         return fit_image_get_os(fit, noffset, os);
471 #endif
472 }
473
474 /*
475  * Weak default function to allow customizing SPL fit loading for load-only
476  * use cases by allowing to skip the parsing/processing of the FIT contents
477  * (so that this can be done separately in a more customized fashion)
478  */
479 __weak bool spl_load_simple_fit_skip_processing(void)
480 {
481         return false;
482 }
483
484 int spl_load_simple_fit(struct spl_image_info *spl_image,
485                         struct spl_load_info *info, ulong sector, void *fit)
486 {
487         int sectors;
488         ulong size;
489         unsigned long count;
490         struct spl_image_info image_info;
491         int node = -1;
492         int images, ret;
493         int base_offset, hsize, align_len = ARCH_DMA_MINALIGN - 1;
494         int index = 0;
495         int firmware_node;
496
497         /*
498          * For FIT with external data, figure out where the external images
499          * start. This is the base for the data-offset properties in each
500          * image.
501          */
502         size = fdt_totalsize(fit);
503         size = (size + 3) & ~3;
504         size = board_spl_fit_size_align(size);
505         base_offset = (size + 3) & ~3;
506
507         /*
508          * So far we only have one block of data from the FIT. Read the entire
509          * thing, including that first block, placing it so it finishes before
510          * where we will load the image.
511          *
512          * Note that we will load the image such that its first byte will be
513          * at the load address. Since that byte may be part-way through a
514          * block, we may load the image up to one block before the load
515          * address. So take account of that here by subtracting an addition
516          * block length from the FIT start position.
517          *
518          * In fact the FIT has its own load address, but we assume it cannot
519          * be before CONFIG_SYS_TEXT_BASE.
520          *
521          * For FIT with data embedded, data is loaded as part of FIT image.
522          * For FIT with external data, data is not loaded in this step.
523          */
524         hsize = (size + info->bl_len + align_len) & ~align_len;
525         fit = spl_get_load_buffer(-hsize, hsize);
526         sectors = get_aligned_image_size(info, size, 0);
527         count = info->read(info, sector, sectors, fit);
528         debug("fit read sector %lx, sectors=%d, dst=%p, count=%lu, size=0x%lx\n",
529               sector, sectors, fit, count, size);
530
531         if (count == 0)
532                 return -EIO;
533
534         /* skip further processing if requested to enable load-only use cases */
535         if (spl_load_simple_fit_skip_processing())
536                 return 0;
537
538         /* find the node holding the images information */
539         images = fdt_path_offset(fit, FIT_IMAGES_PATH);
540         if (images < 0) {
541                 debug("%s: Cannot find /images node: %d\n", __func__, images);
542                 return -1;
543         }
544
545 #ifdef CONFIG_SPL_FPGA_SUPPORT
546         node = spl_fit_get_image_node(fit, images, "fpga", 0);
547         if (node >= 0) {
548                 /* Load the image and set up the spl_image structure */
549                 ret = spl_load_fit_image(info, sector, fit, base_offset, node,
550                                          spl_image);
551                 if (ret) {
552                         printf("%s: Cannot load the FPGA: %i\n", __func__, ret);
553                         return ret;
554                 }
555
556                 debug("FPGA bitstream at: %x, size: %x\n",
557                       (u32)spl_image->load_addr, spl_image->size);
558
559                 ret = fpga_load(0, (const void *)spl_image->load_addr,
560                                 spl_image->size, BIT_FULL);
561                 if (ret) {
562                         printf("%s: Cannot load the image to the FPGA\n",
563                                __func__);
564                         return ret;
565                 }
566
567                 puts("FPGA image loaded from FIT\n");
568                 node = -1;
569         }
570 #endif
571
572         /*
573          * Find the U-Boot image using the following search order:
574          *   - start at 'firmware' (e.g. an ARM Trusted Firmware)
575          *   - fall back 'kernel' (e.g. a Falcon-mode OS boot
576          *   - fall back to using the first 'loadables' entry
577          */
578         if (node < 0)
579                 node = spl_fit_get_image_node(fit, images, FIT_FIRMWARE_PROP,
580                                               0);
581 #ifdef CONFIG_SPL_OS_BOOT
582         if (node < 0)
583                 node = spl_fit_get_image_node(fit, images, FIT_KERNEL_PROP, 0);
584 #endif
585         if (node < 0) {
586                 debug("could not find firmware image, trying loadables...\n");
587                 node = spl_fit_get_image_node(fit, images, "loadables", 0);
588                 /*
589                  * If we pick the U-Boot image from "loadables", start at
590                  * the second image when later loading additional images.
591                  */
592                 index = 1;
593         }
594         if (node < 0) {
595                 debug("%s: Cannot find u-boot image node: %d\n",
596                       __func__, node);
597                 return -1;
598         }
599
600         /* Load the image and set up the spl_image structure */
601         ret = spl_load_fit_image(info, sector, fit, base_offset, node,
602                                  spl_image);
603         if (ret)
604                 return ret;
605
606         /*
607          * For backward compatibility, we treat the first node that is
608          * as a U-Boot image, if no OS-type has been declared.
609          */
610         if (!spl_fit_image_get_os(fit, node, &spl_image->os))
611                 debug("Image OS is %s\n", genimg_get_os_name(spl_image->os));
612 #if !defined(CONFIG_SPL_OS_BOOT)
613         else
614                 spl_image->os = IH_OS_U_BOOT;
615 #endif
616
617         /*
618          * Booting a next-stage U-Boot may require us to append the FDT.
619          * We allow this to fail, as the U-Boot image might embed its FDT.
620          */
621         if (spl_image->os == IH_OS_U_BOOT)
622                 spl_fit_append_fdt(spl_image, info, sector, fit,
623                                    images, base_offset);
624
625         firmware_node = node;
626         /* Now check if there are more images for us to load */
627         for (; ; index++) {
628                 uint8_t os_type = IH_OS_INVALID;
629
630                 node = spl_fit_get_image_node(fit, images, "loadables", index);
631                 if (node < 0)
632                         break;
633
634                 /*
635                  * if the firmware is also a loadable, skip it because
636                  * it already has been loaded. This is typically the case with
637                  * u-boot.img generated by mkimage.
638                  */
639                 if (firmware_node == node)
640                         continue;
641
642                 ret = spl_load_fit_image(info, sector, fit, base_offset, node,
643                                          &image_info);
644                 if (ret < 0)
645                         continue;
646
647                 if (!spl_fit_image_get_os(fit, node, &os_type))
648                         debug("Loadable is %s\n", genimg_get_os_name(os_type));
649
650                 if (os_type == IH_OS_U_BOOT) {
651                         spl_fit_append_fdt(&image_info, info, sector,
652                                            fit, images, base_offset);
653                         spl_image->fdt_addr = image_info.fdt_addr;
654                 }
655
656                 /*
657                  * If the "firmware" image did not provide an entry point,
658                  * use the first valid entry point from the loadables.
659                  */
660                 if (spl_image->entry_point == FDT_ERROR &&
661                     image_info.entry_point != FDT_ERROR)
662                         spl_image->entry_point = image_info.entry_point;
663
664                 /* Record our loadables into the FDT */
665                 if (spl_image->fdt_addr)
666                         spl_fit_record_loadable(fit, images, index,
667                                                 spl_image->fdt_addr,
668                                                 &image_info);
669         }
670
671         /*
672          * If a platform does not provide CONFIG_SYS_UBOOT_START, U-Boot's
673          * Makefile will set it to 0 and it will end up as the entry point
674          * here. What it actually means is: use the load address.
675          */
676         if (spl_image->entry_point == FDT_ERROR || spl_image->entry_point == 0)
677                 spl_image->entry_point = spl_image->load_addr;
678
679         spl_image->flags |= SPL_FIT_FOUND;
680
681 #ifdef CONFIG_IMX_HAB
682         board_spl_fit_post_load((ulong)fit, size);
683 #endif
684
685         return 0;
686 }