1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright 2016 NXP Semiconductor, Inc.
4 */
5
6#include <common.h>
7#include <cpu_func.h>
8#include <errno.h>
9#include <fdt_support.h>
10#include <image.h>
11#include <log.h>
12#include <asm/cache.h>
13#include <asm/global_data.h>
14#include <asm/ptrace.h>
15#include <linux/kernel.h>
16#include <linux/arm-smccc.h>
17#include <asm/io.h>
18#include <asm/system.h>
19#include <asm/types.h>
20#include <asm/macro.h>
21#include <asm/armv8/sec_firmware.h>
22
23DECLARE_GLOBAL_DATA_PTR;
24extern void c_runtime_cpu_setup(void);
25
26#define SEC_FIRMWARE_LOADED	0x1
27#define SEC_FIRMWARE_RUNNING	0x2
28#define SEC_FIRMWARE_ADDR_MASK	(~0x3)
29/*
30 * Secure firmware load addr
31 * Flags used: 0x1 secure firmware has been loaded to secure memory
32 *             0x2 secure firmware is running
33 */
34phys_addr_t sec_firmware_addr;
35
36#ifndef SEC_FIRMWARE_FIT_IMAGE
37#define SEC_FIRMWARE_FIT_IMAGE		"firmware"
38#endif
39#ifndef SEC_FIRMWARE_TARGET_EL
40#define SEC_FIRMWARE_TARGET_EL		2
41#endif
42
43static int sec_firmware_get_data(const void *sec_firmware_img,
44				const void **data, size_t *size)
45{
46	return fit_get_data_conf_prop(sec_firmware_img, SEC_FIRMWARE_FIT_IMAGE,
47				      data, size);
48}
49
50/*
51 * SEC Firmware FIT image parser checks if the image is in FIT
52 * format, verifies integrity of the image and calculates raw
53 * image address and size values.
54 *
55 * Returns 0 on success and a negative errno on error task fail.
56 */
57static int sec_firmware_parse_image(const void *sec_firmware_img,
58					const void **raw_image_addr,
59					size_t *raw_image_size)
60{
61	int ret;
62
63	ret = sec_firmware_get_data(sec_firmware_img, raw_image_addr,
64					raw_image_size);
65	if (ret)
66		return ret;
67
68	debug("SEC Firmware: raw_image_addr = 0x%p, raw_image_size = 0x%lx\n",
69	      *raw_image_addr, *raw_image_size);
70
71	return 0;
72}
73
74/*
75 * SEC Firmware FIT image parser to check if any loadable is
76 * present. If present, verify integrity of the loadable and
77 * copy loadable to address provided in (loadable_h, loadable_l).
78 *
79 * Returns 0 on success and a negative errno on error task fail.
80 */
81static int sec_firmware_check_copy_loadable(const void *sec_firmware_img,
82					    u32 *loadable_l, u32 *loadable_h)
83{
84	phys_addr_t sec_firmware_loadable_addr = 0;
85	int conf_node_off, ld_node_off, images;
86	const void *data;
87	size_t size;
88	ulong load;
89	const char *name, *str, *type;
90	int len;
91
92	conf_node_off = fit_conf_get_node(sec_firmware_img, NULL);
93	if (conf_node_off < 0) {
94		puts("SEC Firmware: no config\n");
95		return -ENOENT;
96	}
97
98	/* find the node holding the images information */
99	images = fdt_path_offset(sec_firmware_img, FIT_IMAGES_PATH);
100	if (images < 0) {
101		printf("%s: Cannot find /images node: %d\n", __func__, images);
102		return -1;
103	}
104
105	type = FIT_LOADABLE_PROP;
106
107	name = fdt_getprop(sec_firmware_img, conf_node_off, type, &len);
108	if (!name) {
109		/* Loadables not present */
110		return 0;
111	}
112
113	printf("SEC Firmware: '%s' present in config\n", type);
114
115	for (str = name; str && ((str - name) < len);
116	     str = strchr(str, '\0') + 1) {
117		printf("%s: '%s'\n", type, str);
118		ld_node_off = fdt_subnode_offset(sec_firmware_img, images, str);
119		if (ld_node_off < 0) {
120			printf("cannot find image node '%s': %d\n", str,
121			       ld_node_off);
122			return -EINVAL;
123		}
124
125		/* Verify secure firmware image */
126		if (!(fit_image_verify(sec_firmware_img, ld_node_off))) {
127			printf("SEC Loadable: Bad loadable image (bad CRC)\n");
128			return -EINVAL;
129		}
130
131		if (fit_image_get_data(sec_firmware_img, ld_node_off,
132				       &data, &size)) {
133			printf("SEC Loadable: Can't get subimage data/size");
134			return -ENOENT;
135		}
136
137		/* Get load address, treated as load offset to secure memory */
138		if (fit_image_get_load(sec_firmware_img, ld_node_off, &load)) {
139			printf("SEC Loadable: Can't get subimage load");
140			return -ENOENT;
141		}
142
143		/* Compute load address for loadable in secure memory */
144		sec_firmware_loadable_addr = (sec_firmware_addr -
145						gd->arch.tlb_size) + load;
146
147		/* Copy loadable to secure memory and flush dcache */
148		debug("%s copied to address 0x%p\n",
149		      FIT_LOADABLE_PROP, (void *)sec_firmware_loadable_addr);
150		memcpy((void *)sec_firmware_loadable_addr, data, size);
151		flush_dcache_range(sec_firmware_loadable_addr,
152				   sec_firmware_loadable_addr + size);
153
154		/* Populate loadable address only for Trusted OS */
155		if (!strcmp(str, "trustedOS@1")) {
156			/*
157			 * Populate address ptrs for loadable image with
158			 * loadbale addr
159			 */
160			out_le32(loadable_l, (sec_firmware_loadable_addr &
161					      WORD_MASK));
162			out_le32(loadable_h, (sec_firmware_loadable_addr >>
163					      WORD_SHIFT));
164		}
165	}
166
167	return 0;
168}
169
170static int sec_firmware_copy_image(const char *title,
171			 u64 image_addr, u32 image_size, u64 sec_firmware)
172{
173	debug("%s copied to address 0x%p\n", title, (void *)sec_firmware);
174	memcpy((void *)sec_firmware, (void *)image_addr, image_size);
175	flush_dcache_range(sec_firmware, sec_firmware + image_size);
176
177	return 0;
178}
179
180/*
181 * This function will parse the SEC Firmware image, and then load it
182 * to secure memory. Also load any loadable if present along with SEC
183 * Firmware image.
184 */
185static int sec_firmware_load_image(const void *sec_firmware_img,
186				   u32 *loadable_l, u32 *loadable_h)
187{
188	const void *raw_image_addr;
189	size_t raw_image_size = 0;
190	int ret;
191
192	/*
193	 * The Excetpion Level must be EL3 to load and initialize
194	 * the SEC Firmware.
195	 */
196	if (current_el() != 3) {
197		ret = -EACCES;
198		goto out;
199	}
200
201#ifdef CFG_SYS_MEM_RESERVE_SECURE
202	/*
203	 * The SEC Firmware must be stored in secure memory.
204	 * Append SEC Firmware to secure mmu table.
205	 */
206	if (!(gd->arch.secure_ram & MEM_RESERVE_SECURE_MAINTAINED)) {
207		ret = -ENXIO;
208		goto out;
209	}
210
211	sec_firmware_addr = (gd->arch.secure_ram & MEM_RESERVE_SECURE_ADDR_MASK) +
212			gd->arch.tlb_size;
213#else
214#error "The CFG_SYS_MEM_RESERVE_SECURE must be defined when enabled SEC Firmware support"
215#endif
216
217	/* Align SEC Firmware base address to 4K */
218	sec_firmware_addr = (sec_firmware_addr + 0xfff) & ~0xfff;
219	debug("SEC Firmware: Load address: 0x%llx\n",
220	      sec_firmware_addr & SEC_FIRMWARE_ADDR_MASK);
221
222	ret = sec_firmware_parse_image(sec_firmware_img, &raw_image_addr,
223			&raw_image_size);
224	if (ret)
225		goto out;
226
227	/* TODO:
228	 * Check if the end addr of SEC Firmware has been extend the secure
229	 * memory.
230	 */
231
232	/* Copy the secure firmware to secure memory */
233	ret = sec_firmware_copy_image("SEC Firmware", (u64)raw_image_addr,
234			raw_image_size, sec_firmware_addr &
235			SEC_FIRMWARE_ADDR_MASK);
236	if (ret)
237		goto out;
238
239	/*
240	 * Check if any loadable are present along with firmware image, if
241	 * present load them.
242	 */
243	ret = sec_firmware_check_copy_loadable(sec_firmware_img, loadable_l,
244					       loadable_h);
245	if (ret)
246		goto out;
247
248	sec_firmware_addr |= SEC_FIRMWARE_LOADED;
249	debug("SEC Firmware: Entry point: 0x%llx\n",
250	      sec_firmware_addr & SEC_FIRMWARE_ADDR_MASK);
251
252	return 0;
253
254out:
255	printf("SEC Firmware: error (%d)\n", ret);
256	sec_firmware_addr = 0;
257
258	return ret;
259}
260
261static int sec_firmware_entry(u32 *eret_hold_l, u32 *eret_hold_h)
262{
263	const void *entry = (void *)(sec_firmware_addr &
264				SEC_FIRMWARE_ADDR_MASK);
265
266	return _sec_firmware_entry(entry, eret_hold_l, eret_hold_h);
267}
268
269/* Check the secure firmware FIT image */
270__weak bool sec_firmware_is_valid(const void *sec_firmware_img)
271{
272	if (fdt_check_header(sec_firmware_img)) {
273		printf("SEC Firmware: Bad firmware image (not a FIT image)\n");
274		return false;
275	}
276
277	if (fit_check_format(sec_firmware_img, IMAGE_SIZE_INVAL)) {
278		printf("SEC Firmware: Bad firmware image (bad FIT header)\n");
279		return false;
280	}
281
282	return true;
283}
284
285#ifdef CONFIG_SEC_FIRMWARE_ARMV8_PSCI
286/*
287 * The PSCI_VERSION function is added from PSCI v0.2. When the PSCI
288 * v0.1 received this function, the NOT_SUPPORTED (0xffff_ffff) error
289 * number will be returned according to SMC Calling Conventions. But
290 * when getting the NOT_SUPPORTED error number, we cannot ensure if
291 * the PSCI version is v0.1 or other error occurred. So, PSCI v0.1
292 * won't be supported by this framework.
293 * And if the secure firmware isn't running, return NOT_SUPPORTED.
294 *
295 * The return value on success is PSCI version in format
296 * major[31:16]:minor[15:0].
297 */
298unsigned int sec_firmware_support_psci_version(void)
299{
300	if (current_el() == SEC_FIRMWARE_TARGET_EL)
301		return _sec_firmware_support_psci_version();
302
303	return PSCI_INVALID_VER;
304}
305#endif
306
307/*
308 * Check with sec_firmware if it supports random number generation
309 * via HW RNG
310 *
311 * The return value will be true if it is supported
312 */
313bool sec_firmware_support_hwrng(void)
314{
315#ifdef CONFIG_TFABOOT
316	/* return true as TFA has one job ring reserved */
317	return true;
318#endif
319	if (sec_firmware_addr & SEC_FIRMWARE_RUNNING) {
320		return true;
321	}
322
323	return false;
324}
325
326/*
327 * sec_firmware_get_random - Get a random number from SEC Firmware
328 * @rand:		random number buffer to be filled
329 * @bytes:		Number of bytes of random number to be supported
330 * @eret:		-1 in case of error, 0 for success
331 */
332int sec_firmware_get_random(uint8_t *rand, int bytes)
333{
334	struct arm_smccc_res res;
335	unsigned long long num;
336	int param1;
337
338	if (!bytes || bytes > 8) {
339		printf("Max Random bytes genration supported is 8\n");
340		return -1;
341	}
342	if (bytes <= 4)
343		param1 = 0;
344	else
345		param1 = 1;
346
347#define SIP_RNG_64 0xC200FF11
348	arm_smccc_smc(SIP_RNG_64, param1, 0, 0, 0, 0, 0, 0, &res);
349	if (res.a0)
350		return -1;
351
352	num = res.a1;
353	memcpy(rand, &num, bytes);
354
355	return 0;
356}
357
358/*
359 * sec_firmware_init - Initialize the SEC Firmware
360 * @sec_firmware_img:	the SEC Firmware image address
361 * @eret_hold_l:	the address to hold exception return address low
362 * @eret_hold_h:	the address to hold exception return address high
363 * @loadable_l:		the address to hold loadable address low
364 * @loadable_h:		the address to hold loadable address high
365 */
366int sec_firmware_init(const void *sec_firmware_img,
367			u32 *eret_hold_l,
368			u32 *eret_hold_h,
369			u32 *loadable_l,
370			u32 *loadable_h)
371{
372	int ret;
373
374	if (!sec_firmware_is_valid(sec_firmware_img))
375		return -EINVAL;
376
377	ret = sec_firmware_load_image(sec_firmware_img, loadable_l,
378				      loadable_h);
379	if (ret) {
380		printf("SEC Firmware: Failed to load image\n");
381		return ret;
382	} else if (sec_firmware_addr & SEC_FIRMWARE_LOADED) {
383		ret = sec_firmware_entry(eret_hold_l, eret_hold_h);
384		if (ret) {
385			printf("SEC Firmware: Failed to initialize\n");
386			return ret;
387		}
388	}
389
390	debug("SEC Firmware: Return from SEC Firmware: current_el = %d\n",
391	      current_el());
392
393	/*
394	 * The PE will be turned into target EL when returned from
395	 * SEC Firmware.
396	 */
397	if (current_el() != SEC_FIRMWARE_TARGET_EL)
398		return -EACCES;
399
400	sec_firmware_addr |= SEC_FIRMWARE_RUNNING;
401
402	/* Set exception table and enable caches if it isn't EL3 */
403	if (current_el() != 3) {
404		c_runtime_cpu_setup();
405		enable_caches();
406	}
407
408	return 0;
409}
410
411/*
412 * fdt_fix_kaslr - Add kalsr-seed node in Device tree
413 * @fdt:		Device tree
414 * @eret:		0 in case of error, 1 for success
415 */
416int fdt_fixup_kaslr(void *fdt)
417{
418	int nodeoffset;
419	int err, ret = 0;
420	u8 rand[8];
421
422#if defined(CONFIG_ARMV8_SEC_FIRMWARE_SUPPORT)
423	/* Check if random seed generation is  supported */
424	if (sec_firmware_support_hwrng() == false) {
425		printf("WARNING: SEC firmware not running, no kaslr-seed\n");
426		return 0;
427	}
428
429	err = sec_firmware_get_random(rand, 8);
430	if (err < 0) {
431		printf("WARNING: No random number to set kaslr-seed\n");
432		return 0;
433	}
434
435	err = fdt_check_header(fdt);
436	if (err < 0) {
437		printf("fdt_chosen: %s\n", fdt_strerror(err));
438		return 0;
439	}
440
441	/* find or create "/chosen" node. */
442	nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
443	if (nodeoffset < 0)
444		return 0;
445
446	err = fdt_setprop(fdt, nodeoffset, "kaslr-seed", rand,
447				  sizeof(rand));
448	if (err < 0) {
449		printf("WARNING: can't set kaslr-seed %s.\n",
450		       fdt_strerror(err));
451		return 0;
452	}
453	ret = 1;
454#endif
455
456	return ret;
457}
458