1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (C) 2022 Sean Anderson <sean.anderson@seco.com>
4 */
5
6#include <common.h>
7#include <image.h>
8#include <log.h>
9#include <semihosting.h>
10#include <spl.h>
11#include <spl_load.h>
12
13static ulong smh_fit_read(struct spl_load_info *load, ulong file_offset,
14			  ulong size, void *buf)
15{
16	long fd = *(long *)load->priv;
17	ulong ret;
18
19	if (smh_seek(fd, file_offset))
20		return 0;
21
22	ret = smh_read(fd, buf, size);
23	return ret < 0 ? 0 : ret;
24}
25
26static int spl_smh_load_image(struct spl_image_info *spl_image,
27			      struct spl_boot_device *bootdev)
28{
29	const char *filename = CONFIG_SPL_FS_LOAD_PAYLOAD_NAME;
30	int ret;
31	long fd, len;
32	struct spl_load_info load;
33
34	fd = smh_open(filename, MODE_READ | MODE_BINARY);
35	if (fd < 0) {
36		log_debug("could not open %s: %ld\n", filename, fd);
37		return fd;
38	}
39
40	ret = smh_flen(fd);
41	if (ret < 0) {
42		log_debug("could not get length of image: %d\n", ret);
43		goto out;
44	}
45	len = ret;
46
47	load.read = smh_fit_read;
48	spl_set_bl_len(&load, 1);
49	load.priv = &fd;
50	ret = spl_load(spl_image, bootdev, &load, len, 0);
51	if (ret)
52		log_debug("could not read %s: %d\n", filename, ret);
53out:
54	smh_close(fd);
55	return ret;
56}
57SPL_LOAD_IMAGE_METHOD("SEMIHOSTING", 0, BOOT_DEVICE_SMH, spl_smh_load_image);
58