1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * (C) Copyright 2016
4 * Xilinx, Inc.
5 *
6 * (C) Copyright 2016
7 * Toradex AG
8 *
9 * Michal Simek <michal.simek@amd.com>
10 * Stefan Agner <stefan.agner@toradex.com>
11 */
12#include <common.h>
13#include <binman_sym.h>
14#include <image.h>
15#include <log.h>
16#include <mapmem.h>
17#include <spl.h>
18#include <linux/libfdt.h>
19
20static ulong spl_ram_load_read(struct spl_load_info *load, ulong sector,
21			       ulong count, void *buf)
22{
23	ulong addr = 0;
24
25	debug("%s: sector %lx, count %lx, buf %lx\n",
26	      __func__, sector, count, (ulong)buf);
27
28	if (IS_ENABLED(CONFIG_SPL_LOAD_FIT)) {
29		addr = IF_ENABLED_INT(CONFIG_SPL_LOAD_FIT,
30				      CONFIG_SPL_LOAD_FIT_ADDRESS);
31	}
32	addr += sector;
33	if (CONFIG_IS_ENABLED(IMAGE_PRE_LOAD))
34		addr += image_load_offset;
35
36	memcpy(buf, (void *)addr, count);
37
38	return count;
39}
40
41static int spl_ram_load_image(struct spl_image_info *spl_image,
42			      struct spl_boot_device *bootdev)
43{
44	struct legacy_img_hdr *header;
45	ulong addr = 0;
46	int ret;
47
48	if (IS_ENABLED(CONFIG_SPL_LOAD_FIT)) {
49		addr = IF_ENABLED_INT(CONFIG_SPL_LOAD_FIT,
50				      CONFIG_SPL_LOAD_FIT_ADDRESS);
51	}
52
53	if (CONFIG_IS_ENABLED(IMAGE_PRE_LOAD)) {
54		ret = image_pre_load(addr);
55
56		if (ret)
57			return ret;
58
59		addr += image_load_offset;
60	}
61	header = map_sysmem(addr, 0);
62
63#if CONFIG_IS_ENABLED(DFU)
64	if (bootdev->boot_device == BOOT_DEVICE_DFU)
65		spl_dfu_cmd(0, "dfu_alt_info_ram", "ram", "0");
66#endif
67
68	if (IS_ENABLED(CONFIG_SPL_LOAD_FIT) &&
69	    image_get_magic(header) == FDT_MAGIC) {
70		struct spl_load_info load;
71
72		debug("Found FIT\n");
73		spl_set_bl_len(&load, 1);
74		load.read = spl_ram_load_read;
75		ret = spl_load_simple_fit(spl_image, &load, 0, header);
76	} else {
77		ulong u_boot_pos = spl_get_image_pos();
78
79		debug("Legacy image\n");
80		/*
81		 * Get the header.  It will point to an address defined by
82		 * handoff which will tell where the image located inside
83		 * the flash.
84		 */
85		debug("u_boot_pos = %lx\n", u_boot_pos);
86		if (u_boot_pos == BINMAN_SYM_MISSING) {
87			/*
88			 * No binman support or no information. For now, fix it
89			 * to the address pointed to by U-Boot.
90			 */
91			u_boot_pos = (ulong)spl_get_load_buffer(-sizeof(*header),
92								sizeof(*header));
93		}
94		header = map_sysmem(u_boot_pos, 0);
95
96		ret = spl_parse_image_header(spl_image, bootdev, header);
97	}
98
99	return ret;
100}
101#if CONFIG_IS_ENABLED(RAM_DEVICE)
102SPL_LOAD_IMAGE_METHOD("RAM", 0, BOOT_DEVICE_RAM, spl_ram_load_image);
103#endif
104#if CONFIG_IS_ENABLED(DFU)
105SPL_LOAD_IMAGE_METHOD("DFU", 0, BOOT_DEVICE_DFU, spl_ram_load_image);
106#endif
107