1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2021 Google LLC
4  * Written by Simon Glass <sjg@chromium.org>
5  */
6 
7 #include <common.h>
8 #include <image.h>
9 #include <mapmem.h>
10 #include <os.h>
11 #include <spl.h>
12 #include <test/ut.h>
13 
14 /* Declare a new SPL test */
15 #define SPL_TEST(_name, _flags)		UNIT_TEST(_name, _flags, spl_test)
16 
17 /* Context used for this test */
18 struct text_ctx {
19 	int fd;
20 };
21 
read_fit_image(struct spl_load_info * load,ulong sector,ulong count,void * buf)22 static ulong read_fit_image(struct spl_load_info *load, ulong sector,
23 			    ulong count, void *buf)
24 {
25 	struct text_ctx *text_ctx = load->priv;
26 	off_t offset, ret;
27 	ssize_t res;
28 
29 	offset = sector * load->bl_len;
30 	ret = os_lseek(text_ctx->fd, offset, OS_SEEK_SET);
31 	if (ret != offset) {
32 		printf("Failed to seek to %zx, got %zx (errno=%d)\n", offset,
33 		       ret, errno);
34 		return 0;
35 	}
36 
37 	res = os_read(text_ctx->fd, buf, count * load->bl_len);
38 	if (res == -1) {
39 		printf("Failed to read %lx bytes, got %ld (errno=%d)\n",
40 		       count * load->bl_len, res, errno);
41 		return 0;
42 	}
43 
44 	return count;
45 }
46 
board_fit_config_name_match(const char * name)47 int board_fit_config_name_match(const char *name)
48 {
49 	return 0;
50 }
51 
spl_get_load_buffer(ssize_t offset,size_t size)52 struct image_header *spl_get_load_buffer(ssize_t offset, size_t size)
53 {
54 	return map_sysmem(0x100000, 0);
55 }
56 
spl_test_load(struct unit_test_state * uts)57 static int spl_test_load(struct unit_test_state *uts)
58 {
59 	const char *cur_prefix, *next_prefix;
60 	struct spl_image_info image;
61 	struct image_header *header;
62 	struct text_ctx text_ctx;
63 	struct spl_load_info load;
64 	char fname[256];
65 	int ret;
66 	int fd;
67 
68 	memset(&load, '\0', sizeof(load));
69 	load.bl_len = 512;
70 	load.read = read_fit_image;
71 
72 	cur_prefix = spl_phase_prefix(spl_phase());
73 	next_prefix = spl_phase_prefix(spl_next_phase());
74 	ret = os_find_u_boot(fname, sizeof(fname), true, cur_prefix,
75 			     next_prefix);
76 	if (ret) {
77 		printf("(%s not found, error %d)\n", fname, ret);
78 		return ret;
79 	}
80 	load.filename = fname;
81 
82 	header = spl_get_load_buffer(-sizeof(*header), sizeof(*header));
83 
84 	fd = os_open(fname, OS_O_RDONLY);
85 	ut_assert(fd >= 0);
86 	ut_asserteq(512, os_read(fd, header, 512));
87 	text_ctx.fd = fd;
88 
89 	load.priv = &text_ctx;
90 
91 	ut_assertok(spl_load_simple_fit(&image, &load, 0, header));
92 
93 	return 0;
94 }
95 SPL_TEST(spl_test_load, 0);
96