xref: /optee_os/core/arch/arm/kernel/secure_partition.c (revision ef44161f847bb1f17e6c803e70047d749e7b394e)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2020-2023, Arm Limited.
4  */
5 #include <bench.h>
6 #include <crypto/crypto.h>
7 #include <initcall.h>
8 #include <kernel/boot.h>
9 #include <kernel/embedded_ts.h>
10 #include <kernel/ldelf_loader.h>
11 #include <kernel/secure_partition.h>
12 #include <kernel/spinlock.h>
13 #include <kernel/spmc_sp_handler.h>
14 #include <kernel/thread_private.h>
15 #include <kernel/thread_spmc.h>
16 #include <kernel/tpm.h>
17 #include <kernel/ts_store.h>
18 #include <ldelf.h>
19 #include <libfdt.h>
20 #include <mm/core_mmu.h>
21 #include <mm/fobj.h>
22 #include <mm/mobj.h>
23 #include <mm/vm.h>
24 #include <optee_ffa.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <tee_api_types.h>
28 #include <tee/uuid.h>
29 #include <trace.h>
30 #include <types_ext.h>
31 #include <utee_defines.h>
32 #include <util.h>
33 #include <zlib.h>
34 
35 #define SP_MANIFEST_ATTR_READ		BIT(0)
36 #define SP_MANIFEST_ATTR_WRITE		BIT(1)
37 #define SP_MANIFEST_ATTR_EXEC		BIT(2)
38 #define SP_MANIFEST_ATTR_NSEC		BIT(3)
39 
40 #define SP_MANIFEST_ATTR_RO		(SP_MANIFEST_ATTR_READ)
41 #define SP_MANIFEST_ATTR_RW		(SP_MANIFEST_ATTR_READ | \
42 					 SP_MANIFEST_ATTR_WRITE)
43 #define SP_MANIFEST_ATTR_RX		(SP_MANIFEST_ATTR_READ | \
44 					 SP_MANIFEST_ATTR_EXEC)
45 #define SP_MANIFEST_ATTR_RWX		(SP_MANIFEST_ATTR_READ  | \
46 					 SP_MANIFEST_ATTR_WRITE | \
47 					 SP_MANIFEST_ATTR_EXEC)
48 
49 #define SP_MANIFEST_FLAG_NOBITS	BIT(0)
50 
51 #define SP_MANIFEST_NS_INT_QUEUED	(0x0)
52 #define SP_MANIFEST_NS_INT_MANAGED_EXIT	(0x1)
53 #define SP_MANIFEST_NS_INT_SIGNALED	(0x2)
54 
55 #define SP_PKG_HEADER_MAGIC (0x474b5053)
56 #define SP_PKG_HEADER_VERSION_V1 (0x1)
57 #define SP_PKG_HEADER_VERSION_V2 (0x2)
58 
59 struct sp_pkg_header {
60 	uint32_t magic;
61 	uint32_t version;
62 	uint32_t pm_offset;
63 	uint32_t pm_size;
64 	uint32_t img_offset;
65 	uint32_t img_size;
66 };
67 
68 struct fip_sp_head fip_sp_list = STAILQ_HEAD_INITIALIZER(fip_sp_list);
69 
70 static const struct ts_ops sp_ops;
71 
72 /* List that holds all of the loaded SP's */
73 static struct sp_sessions_head open_sp_sessions =
74 	TAILQ_HEAD_INITIALIZER(open_sp_sessions);
75 
76 static const struct embedded_ts *find_secure_partition(const TEE_UUID *uuid)
77 {
78 	const struct sp_image *sp = NULL;
79 	const struct fip_sp *fip_sp = NULL;
80 
81 	for_each_secure_partition(sp) {
82 		if (!memcmp(&sp->image.uuid, uuid, sizeof(*uuid)))
83 			return &sp->image;
84 	}
85 
86 	for_each_fip_sp(fip_sp) {
87 		if (!memcmp(&fip_sp->sp_img.image.uuid, uuid, sizeof(*uuid)))
88 			return &fip_sp->sp_img.image;
89 	}
90 
91 	return NULL;
92 }
93 
94 bool is_sp_ctx(struct ts_ctx *ctx)
95 {
96 	return ctx && (ctx->ops == &sp_ops);
97 }
98 
99 static void set_sp_ctx_ops(struct ts_ctx *ctx)
100 {
101 	ctx->ops = &sp_ops;
102 }
103 
104 struct sp_session *sp_get_session(uint32_t session_id)
105 {
106 	struct sp_session *s = NULL;
107 
108 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
109 		if (s->endpoint_id == session_id)
110 			return s;
111 	}
112 
113 	return NULL;
114 }
115 
116 TEE_Result sp_partition_info_get(uint32_t ffa_vers, void *buf, size_t buf_size,
117 				 const TEE_UUID *ffa_uuid, size_t *elem_count,
118 				 bool count_only)
119 {
120 	TEE_Result res = TEE_SUCCESS;
121 	uint32_t part_props = FFA_PART_PROP_DIRECT_REQ_RECV |
122 			      FFA_PART_PROP_DIRECT_REQ_SEND;
123 	struct sp_session *s = NULL;
124 
125 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
126 		if (ffa_uuid &&
127 		    memcmp(&s->ffa_uuid, ffa_uuid, sizeof(*ffa_uuid)))
128 			continue;
129 
130 		if (s->state == sp_dead)
131 			continue;
132 		if (!count_only && !res) {
133 			uint32_t uuid_words[4] = { 0 };
134 
135 			tee_uuid_to_octets((uint8_t *)uuid_words, &s->ffa_uuid);
136 			res = spmc_fill_partition_entry(ffa_vers, buf, buf_size,
137 							*elem_count,
138 							s->endpoint_id, 1,
139 							part_props, uuid_words);
140 		}
141 		*elem_count += 1;
142 	}
143 
144 	return res;
145 }
146 
147 bool sp_has_exclusive_access(struct sp_mem_map_region *mem,
148 			     struct user_mode_ctx *uctx)
149 {
150 	/*
151 	 * Check that we have access to the region if it is supposed to be
152 	 * mapped to the current context.
153 	 */
154 	if (uctx) {
155 		struct vm_region *region = NULL;
156 
157 		/* Make sure that each mobj belongs to the SP */
158 		TAILQ_FOREACH(region, &uctx->vm_info.regions, link) {
159 			if (region->mobj == mem->mobj)
160 				break;
161 		}
162 
163 		if (!region)
164 			return false;
165 	}
166 
167 	/* Check that it is not shared with another SP */
168 	return !sp_mem_is_shared(mem);
169 }
170 
171 static uint16_t new_session_id(struct sp_sessions_head *open_sessions)
172 {
173 	struct sp_session *last = NULL;
174 	uint16_t id = SPMC_ENDPOINT_ID + 1;
175 
176 	last = TAILQ_LAST(open_sessions, sp_sessions_head);
177 	if (last)
178 		id = last->endpoint_id + 1;
179 
180 	assert(id > SPMC_ENDPOINT_ID);
181 	return id;
182 }
183 
184 static TEE_Result sp_create_ctx(const TEE_UUID *bin_uuid, struct sp_session *s)
185 {
186 	TEE_Result res = TEE_SUCCESS;
187 	struct sp_ctx *spc = NULL;
188 
189 	/* Register context */
190 	spc = calloc(1, sizeof(struct sp_ctx));
191 	if (!spc)
192 		return TEE_ERROR_OUT_OF_MEMORY;
193 
194 	spc->open_session = s;
195 	s->ts_sess.ctx = &spc->ts_ctx;
196 	spc->ts_ctx.uuid = *bin_uuid;
197 
198 	res = vm_info_init(&spc->uctx, &spc->ts_ctx);
199 	if (res)
200 		goto err;
201 
202 	set_sp_ctx_ops(&spc->ts_ctx);
203 
204 	return TEE_SUCCESS;
205 
206 err:
207 	free(spc);
208 	return res;
209 }
210 
211 static TEE_Result sp_create_session(struct sp_sessions_head *open_sessions,
212 				    const TEE_UUID *bin_uuid,
213 				    struct sp_session **sess)
214 {
215 	TEE_Result res = TEE_SUCCESS;
216 	struct sp_session *s = calloc(1, sizeof(struct sp_session));
217 
218 	if (!s)
219 		return TEE_ERROR_OUT_OF_MEMORY;
220 
221 	s->endpoint_id = new_session_id(open_sessions);
222 	if (!s->endpoint_id) {
223 		res = TEE_ERROR_OVERFLOW;
224 		goto err;
225 	}
226 
227 	DMSG("Loading Secure Partition %pUl", (void *)bin_uuid);
228 	res = sp_create_ctx(bin_uuid, s);
229 	if (res)
230 		goto err;
231 
232 	TAILQ_INSERT_TAIL(open_sessions, s, link);
233 	*sess = s;
234 	return TEE_SUCCESS;
235 
236 err:
237 	free(s);
238 	return res;
239 }
240 
241 static TEE_Result sp_init_set_registers(struct sp_ctx *ctx)
242 {
243 	struct thread_ctx_regs *sp_regs = &ctx->sp_regs;
244 
245 	memset(sp_regs, 0, sizeof(*sp_regs));
246 	sp_regs->sp = ctx->uctx.stack_ptr;
247 	sp_regs->pc = ctx->uctx.entry_func;
248 
249 	return TEE_SUCCESS;
250 }
251 
252 TEE_Result sp_map_shared(struct sp_session *s,
253 			 struct sp_mem_receiver *receiver,
254 			 struct sp_mem *smem,
255 			 uint64_t *va)
256 {
257 	TEE_Result res = TEE_SUCCESS;
258 	struct sp_ctx *ctx = NULL;
259 	uint32_t perm = TEE_MATTR_UR;
260 	struct sp_mem_map_region *reg = NULL;
261 
262 	ctx = to_sp_ctx(s->ts_sess.ctx);
263 
264 	/* Get the permission */
265 	if (receiver->perm.perm & FFA_MEM_ACC_EXE)
266 		perm |= TEE_MATTR_UX;
267 
268 	if (receiver->perm.perm & FFA_MEM_ACC_RW) {
269 		if (receiver->perm.perm & FFA_MEM_ACC_EXE)
270 			return TEE_ERROR_ACCESS_CONFLICT;
271 
272 		perm |= TEE_MATTR_UW;
273 	}
274 	/*
275 	 * Currently we don't support passing a va. We can't guarantee that the
276 	 * full region will be mapped in a contiguous region. A smem->region can
277 	 * have multiple mobj for one share. Currently there doesn't seem to be
278 	 * an option to guarantee that these will be mapped in a contiguous va
279 	 * space.
280 	 */
281 	if (*va)
282 		return TEE_ERROR_NOT_SUPPORTED;
283 
284 	SLIST_FOREACH(reg, &smem->regions, link) {
285 		res = vm_map(&ctx->uctx, va, reg->page_count * SMALL_PAGE_SIZE,
286 			     perm, 0, reg->mobj, reg->page_offset);
287 
288 		if (res != TEE_SUCCESS) {
289 			EMSG("Failed to map memory region %#"PRIx32, res);
290 			return res;
291 		}
292 	}
293 	return TEE_SUCCESS;
294 }
295 
296 TEE_Result sp_unmap_ffa_regions(struct sp_session *s, struct sp_mem *smem)
297 {
298 	TEE_Result res = TEE_SUCCESS;
299 	vaddr_t vaddr = 0;
300 	size_t len = 0;
301 	struct sp_ctx *ctx = to_sp_ctx(s->ts_sess.ctx);
302 	struct sp_mem_map_region *reg = NULL;
303 
304 	SLIST_FOREACH(reg, &smem->regions, link) {
305 		vaddr = (vaddr_t)sp_mem_get_va(&ctx->uctx, reg->page_offset,
306 					       reg->mobj);
307 		len = reg->page_count * SMALL_PAGE_SIZE;
308 
309 		res = vm_unmap(&ctx->uctx, vaddr, len);
310 		if (res != TEE_SUCCESS)
311 			return res;
312 	}
313 
314 	return TEE_SUCCESS;
315 }
316 
317 static TEE_Result sp_dt_get_u64(const void *fdt, int node, const char *property,
318 				uint64_t *value)
319 {
320 	const fdt64_t *p = NULL;
321 	int len = 0;
322 
323 	p = fdt_getprop(fdt, node, property, &len);
324 	if (!p)
325 		return TEE_ERROR_ITEM_NOT_FOUND;
326 
327 	if (len != sizeof(*p))
328 		return TEE_ERROR_BAD_FORMAT;
329 
330 	*value = fdt64_ld(p);
331 
332 	return TEE_SUCCESS;
333 }
334 
335 static TEE_Result sp_dt_get_u32(const void *fdt, int node, const char *property,
336 				uint32_t *value)
337 {
338 	const fdt32_t *p = NULL;
339 	int len = 0;
340 
341 	p = fdt_getprop(fdt, node, property, &len);
342 	if (!p)
343 		return TEE_ERROR_ITEM_NOT_FOUND;
344 
345 	if (len != sizeof(*p))
346 		return TEE_ERROR_BAD_FORMAT;
347 
348 	*value = fdt32_to_cpu(*p);
349 
350 	return TEE_SUCCESS;
351 }
352 
353 static TEE_Result sp_dt_get_uuid(const void *fdt, int node,
354 				 const char *property, TEE_UUID *uuid)
355 {
356 	uint32_t uuid_array[4] = { 0 };
357 	const fdt32_t *p = NULL;
358 	int len = 0;
359 	int i = 0;
360 
361 	p = fdt_getprop(fdt, node, property, &len);
362 	if (!p)
363 		return TEE_ERROR_ITEM_NOT_FOUND;
364 
365 	if (len != sizeof(TEE_UUID))
366 		return TEE_ERROR_BAD_FORMAT;
367 
368 	for (i = 0; i < 4; i++)
369 		uuid_array[i] = fdt32_to_cpu(p[i]);
370 
371 	tee_uuid_from_octets(uuid, (uint8_t *)uuid_array);
372 
373 	return TEE_SUCCESS;
374 }
375 
376 static TEE_Result sp_is_elf_format(const void *fdt, int sp_node,
377 				   bool *is_elf_format)
378 {
379 	TEE_Result res = TEE_SUCCESS;
380 	uint32_t elf_format = 0;
381 
382 	res = sp_dt_get_u32(fdt, sp_node, "elf-format", &elf_format);
383 	if (res != TEE_SUCCESS && res != TEE_ERROR_ITEM_NOT_FOUND)
384 		return res;
385 
386 	*is_elf_format = (elf_format != 0);
387 
388 	return TEE_SUCCESS;
389 }
390 
391 static TEE_Result sp_binary_open(const TEE_UUID *uuid,
392 				 const struct ts_store_ops **ops,
393 				 struct ts_store_handle **handle)
394 {
395 	TEE_Result res = TEE_ERROR_ITEM_NOT_FOUND;
396 
397 	SCATTERED_ARRAY_FOREACH(*ops, sp_stores, struct ts_store_ops) {
398 		res = (*ops)->open(uuid, handle);
399 		if (res != TEE_ERROR_ITEM_NOT_FOUND &&
400 		    res != TEE_ERROR_STORAGE_NOT_AVAILABLE)
401 			break;
402 	}
403 
404 	return res;
405 }
406 
407 static TEE_Result load_binary_sp(struct ts_session *s,
408 				 struct user_mode_ctx *uctx)
409 {
410 	size_t bin_size = 0, bin_size_rounded = 0, bin_page_count = 0;
411 	const struct ts_store_ops *store_ops = NULL;
412 	struct ts_store_handle *handle = NULL;
413 	TEE_Result res = TEE_SUCCESS;
414 	tee_mm_entry_t *mm = NULL;
415 	struct mobj *mobj = NULL;
416 	uaddr_t base_addr = 0;
417 	uint32_t vm_flags = 0;
418 	unsigned int idx = 0;
419 	vaddr_t va = 0;
420 
421 	if (!s || !uctx)
422 		return TEE_ERROR_BAD_PARAMETERS;
423 
424 	DMSG("Loading raw binary format SP %pUl", &uctx->ts_ctx->uuid);
425 
426 	vm_set_ctx(uctx->ts_ctx);
427 
428 	/* Find TS store and open SP binary */
429 	res = sp_binary_open(&uctx->ts_ctx->uuid, &store_ops, &handle);
430 	if (res != TEE_SUCCESS) {
431 		EMSG("Failed to open SP binary");
432 		return res;
433 	}
434 
435 	/* Query binary size and calculate page count */
436 	res = store_ops->get_size(handle, &bin_size);
437 	if (res != TEE_SUCCESS)
438 		goto err;
439 
440 	if (ROUNDUP_OVERFLOW(bin_size, SMALL_PAGE_SIZE, &bin_size_rounded)) {
441 		res = TEE_ERROR_OVERFLOW;
442 		goto err;
443 	}
444 
445 	bin_page_count = bin_size_rounded / SMALL_PAGE_SIZE;
446 
447 	/* Allocate memory */
448 	mm = tee_mm_alloc(&tee_mm_sec_ddr, bin_size_rounded);
449 	if (!mm) {
450 		res = TEE_ERROR_OUT_OF_MEMORY;
451 		goto err;
452 	}
453 
454 	base_addr = tee_mm_get_smem(mm);
455 
456 	/* Create mobj */
457 	mobj = sp_mem_new_mobj(bin_page_count, TEE_MATTR_MEM_TYPE_CACHED, true);
458 	if (!mobj) {
459 		res = TEE_ERROR_OUT_OF_MEMORY;
460 		goto err_free_tee_mm;
461 	}
462 
463 	res = sp_mem_add_pages(mobj, &idx, base_addr, bin_page_count);
464 	if (res)
465 		goto err_free_mobj;
466 
467 	/* Map memory area for the SP binary */
468 	res = vm_map(uctx, &va, bin_size_rounded, TEE_MATTR_URWX,
469 		     vm_flags, mobj, 0);
470 	if (res)
471 		goto err_free_mobj;
472 
473 	/* Read SP binary into the previously mapped memory area */
474 	res = store_ops->read(handle, NULL, (void *)va, bin_size);
475 	if (res)
476 		goto err_unmap;
477 
478 	/* Set memory protection to allow execution */
479 	res = vm_set_prot(uctx, va, bin_size_rounded, TEE_MATTR_UX);
480 	if (res)
481 		goto err_unmap;
482 
483 	mobj_put(mobj);
484 	store_ops->close(handle);
485 
486 	/* The entry point must be at the beginning of the SP binary. */
487 	uctx->entry_func = va;
488 	uctx->load_addr = va;
489 	uctx->is_32bit = false;
490 
491 	s->handle_scall = s->ctx->ops->handle_scall;
492 
493 	return TEE_SUCCESS;
494 
495 err_unmap:
496 	vm_unmap(uctx, va, bin_size_rounded);
497 
498 err_free_mobj:
499 	mobj_put(mobj);
500 
501 err_free_tee_mm:
502 	tee_mm_free(mm);
503 
504 err:
505 	store_ops->close(handle);
506 
507 	return res;
508 }
509 
510 static TEE_Result sp_open_session(struct sp_session **sess,
511 				  struct sp_sessions_head *open_sessions,
512 				  const TEE_UUID *ffa_uuid,
513 				  const TEE_UUID *bin_uuid,
514 				  const void *fdt)
515 {
516 	TEE_Result res = TEE_SUCCESS;
517 	struct sp_session *s = NULL;
518 	struct sp_ctx *ctx = NULL;
519 	bool is_elf_format = false;
520 
521 	if (!find_secure_partition(bin_uuid))
522 		return TEE_ERROR_ITEM_NOT_FOUND;
523 
524 	res = sp_create_session(open_sessions, bin_uuid, &s);
525 	if (res != TEE_SUCCESS) {
526 		DMSG("sp_create_session failed %#"PRIx32, res);
527 		return res;
528 	}
529 
530 	ctx = to_sp_ctx(s->ts_sess.ctx);
531 	assert(ctx);
532 	if (!ctx)
533 		return TEE_ERROR_TARGET_DEAD;
534 	*sess = s;
535 
536 	ts_push_current_session(&s->ts_sess);
537 
538 	res = sp_is_elf_format(fdt, 0, &is_elf_format);
539 	if (res == TEE_SUCCESS) {
540 		if (is_elf_format) {
541 			/* Load the SP using ldelf. */
542 			ldelf_load_ldelf(&ctx->uctx);
543 			res = ldelf_init_with_ldelf(&s->ts_sess, &ctx->uctx);
544 		} else {
545 			/* Raw binary format SP */
546 			res = load_binary_sp(&s->ts_sess, &ctx->uctx);
547 		}
548 	} else {
549 		EMSG("Failed to detect SP format");
550 	}
551 
552 	if (res != TEE_SUCCESS) {
553 		EMSG("Failed loading SP  %#"PRIx32, res);
554 		ts_pop_current_session();
555 		return TEE_ERROR_TARGET_DEAD;
556 	}
557 
558 	/* Make the SP ready for its first run */
559 	s->state = sp_idle;
560 	s->caller_id = 0;
561 	sp_init_set_registers(ctx);
562 	memcpy(&s->ffa_uuid, ffa_uuid, sizeof(*ffa_uuid));
563 	ts_pop_current_session();
564 
565 	return TEE_SUCCESS;
566 }
567 
568 static TEE_Result fdt_get_uuid(const void * const fdt, TEE_UUID *uuid)
569 {
570 	const struct fdt_property *description = NULL;
571 	int description_name_len = 0;
572 
573 	if (fdt_node_check_compatible(fdt, 0, "arm,ffa-manifest-1.0")) {
574 		EMSG("Failed loading SP, manifest not found");
575 		return TEE_ERROR_BAD_PARAMETERS;
576 	}
577 
578 	description = fdt_get_property(fdt, 0, "description",
579 				       &description_name_len);
580 	if (description)
581 		DMSG("Loading SP: %s", description->data);
582 
583 	if (sp_dt_get_uuid(fdt, 0, "uuid", uuid)) {
584 		EMSG("Missing or invalid UUID in SP manifest");
585 		return TEE_ERROR_BAD_FORMAT;
586 	}
587 
588 	return TEE_SUCCESS;
589 }
590 
591 static TEE_Result copy_and_map_fdt(struct sp_ctx *ctx, const void * const fdt,
592 				   void **fdt_copy, size_t *mapped_size)
593 {
594 	size_t total_size = ROUNDUP(fdt_totalsize(fdt), SMALL_PAGE_SIZE);
595 	size_t num_pages = total_size / SMALL_PAGE_SIZE;
596 	uint32_t perm = TEE_MATTR_UR | TEE_MATTR_PRW;
597 	TEE_Result res = TEE_SUCCESS;
598 	struct mobj *m = NULL;
599 	struct fobj *f = NULL;
600 	vaddr_t va = 0;
601 
602 	f = fobj_sec_mem_alloc(num_pages);
603 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
604 	fobj_put(f);
605 	if (!m)
606 		return TEE_ERROR_OUT_OF_MEMORY;
607 
608 	res = vm_map(&ctx->uctx, &va, total_size, perm, 0, m, 0);
609 	mobj_put(m);
610 	if (res)
611 		return res;
612 
613 	if (fdt_open_into(fdt, (void *)va, total_size))
614 		return TEE_ERROR_GENERIC;
615 
616 	*fdt_copy = (void *)va;
617 	*mapped_size = total_size;
618 
619 	return res;
620 }
621 
622 static void fill_boot_info_1_0(vaddr_t buf, const void *fdt)
623 {
624 	struct ffa_boot_info_1_0 *info = (struct ffa_boot_info_1_0 *)buf;
625 	static const char fdt_name[16] = "TYPE_DT\0\0\0\0\0\0\0\0";
626 
627 	memcpy(&info->magic, "FF-A", 4);
628 	info->count = 1;
629 
630 	COMPILE_TIME_ASSERT(sizeof(info->nvp[0].name) == sizeof(fdt_name));
631 	memcpy(info->nvp[0].name, fdt_name, sizeof(fdt_name));
632 	info->nvp[0].value = (uintptr_t)fdt;
633 	info->nvp[0].size = fdt_totalsize(fdt);
634 }
635 
636 static void fill_boot_info_1_1(vaddr_t buf, const void *fdt)
637 {
638 	size_t desc_offs = ROUNDUP(sizeof(struct ffa_boot_info_header_1_1), 8);
639 	struct ffa_boot_info_header_1_1 *header =
640 		(struct ffa_boot_info_header_1_1 *)buf;
641 	struct ffa_boot_info_1_1 *desc =
642 		(struct ffa_boot_info_1_1 *)(buf + desc_offs);
643 
644 	header->signature = FFA_BOOT_INFO_SIGNATURE;
645 	header->version = FFA_BOOT_INFO_VERSION;
646 	header->blob_size = desc_offs + sizeof(struct ffa_boot_info_1_1);
647 	header->desc_size = sizeof(struct ffa_boot_info_1_1);
648 	header->desc_count = 1;
649 	header->desc_offset = desc_offs;
650 
651 	memset(&desc[0].name, 0, sizeof(desc[0].name));
652 	/* Type: Standard boot info (bit[7] == 0), FDT type */
653 	desc[0].type = FFA_BOOT_INFO_TYPE_ID_FDT;
654 	/* Flags: Contents field contains an address */
655 	desc[0].flags = FFA_BOOT_INFO_FLAG_CONTENT_FORMAT_ADDR <<
656 			FFA_BOOT_INFO_FLAG_CONTENT_FORMAT_SHIFT;
657 	desc[0].size = fdt_totalsize(fdt);
658 	desc[0].contents = (uintptr_t)fdt;
659 }
660 
661 static TEE_Result create_and_map_boot_info(struct sp_ctx *ctx, const void *fdt,
662 					   struct thread_smc_args *args,
663 					   vaddr_t *va, size_t *mapped_size)
664 {
665 	size_t total_size = ROUNDUP(CFG_SP_INIT_INFO_MAX_SIZE, SMALL_PAGE_SIZE);
666 	size_t num_pages = total_size / SMALL_PAGE_SIZE;
667 	uint32_t perm = TEE_MATTR_UR | TEE_MATTR_PRW;
668 	TEE_Result res = TEE_SUCCESS;
669 	uint32_t sp_ffa_version = 0;
670 	struct fobj *f = NULL;
671 	struct mobj *m = NULL;
672 	uint32_t info_reg = 0;
673 
674 	res = sp_dt_get_u32(fdt, 0, "ffa-version", &sp_ffa_version);
675 	if (res)
676 		return res;
677 
678 	f = fobj_sec_mem_alloc(num_pages);
679 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
680 	fobj_put(f);
681 	if (!m)
682 		return TEE_ERROR_OUT_OF_MEMORY;
683 
684 	res = vm_map(&ctx->uctx, va, total_size, perm, 0, m, 0);
685 	mobj_put(m);
686 	if (res)
687 		return res;
688 
689 	*mapped_size = total_size;
690 
691 	switch (sp_ffa_version) {
692 	case MAKE_FFA_VERSION(1, 0):
693 		fill_boot_info_1_0(*va, fdt);
694 		break;
695 	case MAKE_FFA_VERSION(1, 1):
696 		fill_boot_info_1_1(*va, fdt);
697 		break;
698 	default:
699 		EMSG("Unknown FF-A version: %#"PRIx32, sp_ffa_version);
700 		return TEE_ERROR_NOT_SUPPORTED;
701 	}
702 
703 	res = sp_dt_get_u32(fdt, 0, "gp-register-num", &info_reg);
704 	if (res) {
705 		if (res == TEE_ERROR_ITEM_NOT_FOUND) {
706 			/* If the property is not present, set default to x0 */
707 			info_reg = 0;
708 		} else {
709 			return TEE_ERROR_BAD_FORMAT;
710 		}
711 	}
712 
713 	switch (info_reg) {
714 	case 0:
715 		args->a0 = *va;
716 		break;
717 	case 1:
718 		args->a1 = *va;
719 		break;
720 	case 2:
721 		args->a2 = *va;
722 		break;
723 	case 3:
724 		args->a3 = *va;
725 		break;
726 	default:
727 		EMSG("Invalid register selected for passing boot info");
728 		return TEE_ERROR_BAD_FORMAT;
729 	}
730 
731 	return TEE_SUCCESS;
732 }
733 
734 static TEE_Result handle_fdt_load_relative_mem_regions(struct sp_ctx *ctx,
735 						       const void *fdt)
736 {
737 	int node = 0;
738 	int subnode = 0;
739 	tee_mm_entry_t *mm = NULL;
740 	TEE_Result res = TEE_SUCCESS;
741 
742 	/*
743 	 * Memory regions are optional in the SP manifest, it's not an error if
744 	 * we don't find any.
745 	 */
746 	node = fdt_node_offset_by_compatible(fdt, 0,
747 					     "arm,ffa-manifest-memory-regions");
748 	if (node < 0)
749 		return TEE_SUCCESS;
750 
751 	fdt_for_each_subnode(subnode, fdt, node) {
752 		uint64_t load_rel_offset = 0;
753 		uint32_t attributes = 0;
754 		uint64_t base_addr = 0;
755 		uint32_t pages_cnt = 0;
756 		uint32_t flags = 0;
757 		uint32_t perm = 0;
758 		size_t size = 0;
759 		vaddr_t va = 0;
760 
761 		mm = NULL;
762 
763 		/* Load address relative offset of a memory region */
764 		if (!sp_dt_get_u64(fdt, subnode, "load-address-relative-offset",
765 				   &load_rel_offset)) {
766 			va = ctx->uctx.load_addr + load_rel_offset;
767 		} else {
768 			/* Skip non load address relative memory regions */
769 			continue;
770 		}
771 
772 		if (!sp_dt_get_u64(fdt, subnode, "base-address", &base_addr)) {
773 			EMSG("Both base-address and load-address-relative-offset fields are set");
774 			return TEE_ERROR_BAD_FORMAT;
775 		}
776 
777 		/* Size of memory region as count of 4K pages */
778 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
779 			EMSG("Mandatory field is missing: pages-count");
780 			return TEE_ERROR_BAD_FORMAT;
781 		}
782 
783 		if (MUL_OVERFLOW(pages_cnt, SMALL_PAGE_SIZE, &size))
784 			return TEE_ERROR_OVERFLOW;
785 
786 		/* Memory region attributes  */
787 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
788 			EMSG("Mandatory field is missing: attributes");
789 			return TEE_ERROR_BAD_FORMAT;
790 		}
791 
792 		/* Check instruction and data access permissions */
793 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
794 		case SP_MANIFEST_ATTR_RO:
795 			perm = TEE_MATTR_UR;
796 			break;
797 		case SP_MANIFEST_ATTR_RW:
798 			perm = TEE_MATTR_URW;
799 			break;
800 		case SP_MANIFEST_ATTR_RX:
801 			perm = TEE_MATTR_URX;
802 			break;
803 		default:
804 			EMSG("Invalid memory access permissions");
805 			return TEE_ERROR_BAD_FORMAT;
806 		}
807 
808 		res = sp_dt_get_u32(fdt, subnode, "load-flags", &flags);
809 		if (res != TEE_SUCCESS && res != TEE_ERROR_ITEM_NOT_FOUND) {
810 			EMSG("Optional field with invalid value: flags");
811 			return TEE_ERROR_BAD_FORMAT;
812 		}
813 
814 		/* Load relative regions must be secure */
815 		if (attributes & SP_MANIFEST_ATTR_NSEC) {
816 			EMSG("Invalid memory security attribute");
817 			return TEE_ERROR_BAD_FORMAT;
818 		}
819 
820 		if (flags & SP_MANIFEST_FLAG_NOBITS) {
821 			/*
822 			 * NOBITS flag is set, which means that loaded binary
823 			 * doesn't contain this area, so it's need to be
824 			 * allocated.
825 			 */
826 			struct mobj *m = NULL;
827 			unsigned int idx = 0;
828 
829 			mm = tee_mm_alloc(&tee_mm_sec_ddr, size);
830 			if (!mm)
831 				return TEE_ERROR_OUT_OF_MEMORY;
832 
833 			base_addr = tee_mm_get_smem(mm);
834 
835 			m = sp_mem_new_mobj(pages_cnt,
836 					    TEE_MATTR_MEM_TYPE_CACHED, true);
837 			if (!m) {
838 				res = TEE_ERROR_OUT_OF_MEMORY;
839 				goto err_mm_free;
840 			}
841 
842 			res = sp_mem_add_pages(m, &idx, base_addr, pages_cnt);
843 			if (res) {
844 				mobj_put(m);
845 				goto err_mm_free;
846 			}
847 
848 			res = vm_map(&ctx->uctx, &va, size, perm, 0, m, 0);
849 			mobj_put(m);
850 			if (res)
851 				goto err_mm_free;
852 		} else {
853 			/*
854 			 * If NOBITS is not present the memory area is already
855 			 * mapped and only need to set the correct permissions.
856 			 */
857 			res = vm_set_prot(&ctx->uctx, va, size, perm);
858 			if (res)
859 				return res;
860 		}
861 	}
862 
863 	return TEE_SUCCESS;
864 
865 err_mm_free:
866 	tee_mm_free(mm);
867 	return res;
868 }
869 
870 static TEE_Result handle_fdt_dev_regions(struct sp_ctx *ctx, void *fdt)
871 {
872 	int node = 0;
873 	int subnode = 0;
874 	TEE_Result res = TEE_SUCCESS;
875 	const char *dt_device_match_table = {
876 		"arm,ffa-manifest-device-regions",
877 	};
878 
879 	/*
880 	 * Device regions are optional in the SP manifest, it's not an error if
881 	 * we don't find any
882 	 */
883 	node = fdt_node_offset_by_compatible(fdt, 0, dt_device_match_table);
884 	if (node < 0)
885 		return TEE_SUCCESS;
886 
887 	fdt_for_each_subnode(subnode, fdt, node) {
888 		uint64_t base_addr = 0;
889 		uint32_t pages_cnt = 0;
890 		uint32_t attributes = 0;
891 		struct mobj *m = NULL;
892 		bool is_secure = true;
893 		uint32_t perm = 0;
894 		vaddr_t va = 0;
895 		unsigned int idx = 0;
896 
897 		/*
898 		 * Physical base address of a device MMIO region.
899 		 * Currently only physically contiguous region is supported.
900 		 */
901 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr)) {
902 			EMSG("Mandatory field is missing: base-address");
903 			return TEE_ERROR_BAD_FORMAT;
904 		}
905 
906 		/* Total size of MMIO region as count of 4K pages */
907 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
908 			EMSG("Mandatory field is missing: pages-count");
909 			return TEE_ERROR_BAD_FORMAT;
910 		}
911 
912 		/* Data access, instruction access and security attributes */
913 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
914 			EMSG("Mandatory field is missing: attributes");
915 			return TEE_ERROR_BAD_FORMAT;
916 		}
917 
918 		/* Check instruction and data access permissions */
919 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
920 		case SP_MANIFEST_ATTR_RO:
921 			perm = TEE_MATTR_UR;
922 			break;
923 		case SP_MANIFEST_ATTR_RW:
924 			perm = TEE_MATTR_URW;
925 			break;
926 		default:
927 			EMSG("Invalid memory access permissions");
928 			return TEE_ERROR_BAD_FORMAT;
929 		}
930 
931 		/*
932 		 * The SP is a secure endpoint, security attribute can be
933 		 * secure or non-secure
934 		 */
935 		if (attributes & SP_MANIFEST_ATTR_NSEC)
936 			is_secure = false;
937 
938 		/* Memory attributes must be Device-nGnRnE */
939 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_STRONGLY_O,
940 				    is_secure);
941 		if (!m)
942 			return TEE_ERROR_OUT_OF_MEMORY;
943 
944 		res = sp_mem_add_pages(m, &idx, (paddr_t)base_addr, pages_cnt);
945 		if (res) {
946 			mobj_put(m);
947 			return res;
948 		}
949 
950 		res = vm_map(&ctx->uctx, &va, pages_cnt * SMALL_PAGE_SIZE,
951 			     perm, 0, m, 0);
952 		mobj_put(m);
953 		if (res)
954 			return res;
955 
956 		/*
957 		 * Overwrite the device region's PA in the fdt with the VA. This
958 		 * fdt will be passed to the SP.
959 		 */
960 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
961 
962 		/*
963 		 * Unmap the region if the overwrite failed since the SP won't
964 		 * be able to access it without knowing the VA.
965 		 */
966 		if (res) {
967 			vm_unmap(&ctx->uctx, va, pages_cnt * SMALL_PAGE_SIZE);
968 			return res;
969 		}
970 	}
971 
972 	return TEE_SUCCESS;
973 }
974 
975 static TEE_Result swap_sp_endpoints(uint32_t endpoint_id,
976 				    uint32_t new_endpoint_id)
977 {
978 	struct sp_session *session = sp_get_session(endpoint_id);
979 	uint32_t manifest_endpoint_id = 0;
980 
981 	/*
982 	 * We don't know in which order the SPs are loaded. The endpoint ID
983 	 * defined in the manifest could already be generated by
984 	 * new_session_id() and used by another SP. If this is the case, we swap
985 	 * the ID's of the two SPs. We also have to make sure that the ID's are
986 	 * not defined twice in the manifest.
987 	 */
988 
989 	/* The endpoint ID was not assigned yet */
990 	if (!session)
991 		return TEE_SUCCESS;
992 
993 	/*
994 	 * Read the manifest file from the SP who originally had the endpoint.
995 	 * We can safely swap the endpoint ID's if the manifest file doesn't
996 	 * have an endpoint ID defined.
997 	 */
998 	if (!sp_dt_get_u32(session->fdt, 0, "id", &manifest_endpoint_id)) {
999 		assert(manifest_endpoint_id == endpoint_id);
1000 		EMSG("SP: Found duplicated endpoint ID %#"PRIx32, endpoint_id);
1001 		return TEE_ERROR_ACCESS_CONFLICT;
1002 	}
1003 
1004 	session->endpoint_id = new_endpoint_id;
1005 
1006 	return TEE_SUCCESS;
1007 }
1008 
1009 static TEE_Result read_manifest_endpoint_id(struct sp_session *s)
1010 {
1011 	uint32_t endpoint_id = 0;
1012 
1013 	/*
1014 	 * The endpoint ID can be optionally defined in the manifest file. We
1015 	 * have to map the ID inside the manifest to the SP if it's defined.
1016 	 * If not, the endpoint ID generated inside new_session_id() will be
1017 	 * used.
1018 	 */
1019 	if (!sp_dt_get_u32(s->fdt, 0, "id", &endpoint_id)) {
1020 		TEE_Result res = TEE_ERROR_GENERIC;
1021 
1022 		if (endpoint_id <= SPMC_ENDPOINT_ID)
1023 			return TEE_ERROR_BAD_FORMAT;
1024 
1025 		res = swap_sp_endpoints(endpoint_id, s->endpoint_id);
1026 		if (res)
1027 			return res;
1028 
1029 		DMSG("SP: endpoint ID (0x%"PRIx32") found in manifest",
1030 		     endpoint_id);
1031 		/* Assign the endpoint ID to the current SP */
1032 		s->endpoint_id = endpoint_id;
1033 	}
1034 	return TEE_SUCCESS;
1035 }
1036 
1037 static TEE_Result handle_fdt_mem_regions(struct sp_ctx *ctx, void *fdt)
1038 {
1039 	int node = 0;
1040 	int subnode = 0;
1041 	tee_mm_entry_t *mm = NULL;
1042 	TEE_Result res = TEE_SUCCESS;
1043 
1044 	/*
1045 	 * Memory regions are optional in the SP manifest, it's not an error if
1046 	 * we don't find any.
1047 	 */
1048 	node = fdt_node_offset_by_compatible(fdt, 0,
1049 					     "arm,ffa-manifest-memory-regions");
1050 	if (node < 0)
1051 		return TEE_SUCCESS;
1052 
1053 	fdt_for_each_subnode(subnode, fdt, node) {
1054 		uint64_t load_rel_offset = 0;
1055 		bool alloc_needed = false;
1056 		uint32_t attributes = 0;
1057 		uint64_t base_addr = 0;
1058 		uint32_t pages_cnt = 0;
1059 		bool is_secure = true;
1060 		struct mobj *m = NULL;
1061 		unsigned int idx = 0;
1062 		uint32_t perm = 0;
1063 		size_t size = 0;
1064 		vaddr_t va = 0;
1065 
1066 		mm = NULL;
1067 
1068 		/* Load address relative offset of a memory region */
1069 		if (!sp_dt_get_u64(fdt, subnode, "load-address-relative-offset",
1070 				   &load_rel_offset)) {
1071 			/*
1072 			 * At this point the memory region is already mapped by
1073 			 * handle_fdt_load_relative_mem_regions.
1074 			 * Only need to set the base-address in the manifest and
1075 			 * then skip the rest of the mapping process.
1076 			 */
1077 			va = ctx->uctx.load_addr + load_rel_offset;
1078 			res = fdt_setprop_u64(fdt, subnode, "base-address", va);
1079 			if (res)
1080 				return res;
1081 
1082 			continue;
1083 		}
1084 
1085 		/*
1086 		 * Base address of a memory region.
1087 		 * If not present, we have to allocate the specified memory.
1088 		 * If present, this field could specify a PA or VA. Currently
1089 		 * only a PA is supported.
1090 		 */
1091 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr))
1092 			alloc_needed = true;
1093 
1094 		/* Size of memory region as count of 4K pages */
1095 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
1096 			EMSG("Mandatory field is missing: pages-count");
1097 			return TEE_ERROR_BAD_FORMAT;
1098 		}
1099 
1100 		if (MUL_OVERFLOW(pages_cnt, SMALL_PAGE_SIZE, &size))
1101 			return TEE_ERROR_OVERFLOW;
1102 
1103 		/*
1104 		 * Memory region attributes:
1105 		 * - Instruction/data access permissions
1106 		 * - Cacheability/shareability attributes
1107 		 * - Security attributes
1108 		 *
1109 		 * Cacheability/shareability attributes can be ignored for now.
1110 		 * OP-TEE only supports a single type for normal cached memory
1111 		 * and currently there is no use case that would require to
1112 		 * change this.
1113 		 */
1114 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
1115 			EMSG("Mandatory field is missing: attributes");
1116 			return TEE_ERROR_BAD_FORMAT;
1117 		}
1118 
1119 		/* Check instruction and data access permissions */
1120 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
1121 		case SP_MANIFEST_ATTR_RO:
1122 			perm = TEE_MATTR_UR;
1123 			break;
1124 		case SP_MANIFEST_ATTR_RW:
1125 			perm = TEE_MATTR_URW;
1126 			break;
1127 		case SP_MANIFEST_ATTR_RX:
1128 			perm = TEE_MATTR_URX;
1129 			break;
1130 		default:
1131 			EMSG("Invalid memory access permissions");
1132 			return TEE_ERROR_BAD_FORMAT;
1133 		}
1134 
1135 		/*
1136 		 * The SP is a secure endpoint, security attribute can be
1137 		 * secure or non-secure.
1138 		 * The SPMC cannot allocate non-secure memory, i.e. if the base
1139 		 * address is missing this attribute must be secure.
1140 		 */
1141 		if (attributes & SP_MANIFEST_ATTR_NSEC) {
1142 			if (alloc_needed) {
1143 				EMSG("Invalid memory security attribute");
1144 				return TEE_ERROR_BAD_FORMAT;
1145 			}
1146 			is_secure = false;
1147 		}
1148 
1149 		if (alloc_needed) {
1150 			/* Base address is missing, we have to allocate */
1151 			mm = tee_mm_alloc(&tee_mm_sec_ddr, size);
1152 			if (!mm)
1153 				return TEE_ERROR_OUT_OF_MEMORY;
1154 
1155 			base_addr = tee_mm_get_smem(mm);
1156 		}
1157 
1158 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_CACHED,
1159 				    is_secure);
1160 		if (!m) {
1161 			res = TEE_ERROR_OUT_OF_MEMORY;
1162 			goto err_mm_free;
1163 		}
1164 
1165 		res = sp_mem_add_pages(m, &idx, base_addr, pages_cnt);
1166 		if (res) {
1167 			mobj_put(m);
1168 			goto err_mm_free;
1169 		}
1170 
1171 		res = vm_map(&ctx->uctx, &va, size, perm, 0, m, 0);
1172 		mobj_put(m);
1173 		if (res)
1174 			goto err_mm_free;
1175 
1176 		/*
1177 		 * Overwrite the memory region's base address in the fdt with
1178 		 * the VA. This fdt will be passed to the SP.
1179 		 * If the base-address field was not present in the original
1180 		 * fdt, this function will create it. This doesn't cause issues
1181 		 * since the necessary extra space has been allocated when
1182 		 * opening the fdt.
1183 		 */
1184 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
1185 
1186 		/*
1187 		 * Unmap the region if the overwrite failed since the SP won't
1188 		 * be able to access it without knowing the VA.
1189 		 */
1190 		if (res) {
1191 			vm_unmap(&ctx->uctx, va, size);
1192 			goto err_mm_free;
1193 		}
1194 	}
1195 
1196 	return TEE_SUCCESS;
1197 
1198 err_mm_free:
1199 	tee_mm_free(mm);
1200 	return res;
1201 }
1202 
1203 static TEE_Result handle_tpm_event_log(struct sp_ctx *ctx, void *fdt)
1204 {
1205 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
1206 	uint32_t dummy_size __maybe_unused = 0;
1207 	TEE_Result res = TEE_SUCCESS;
1208 	size_t page_count = 0;
1209 	struct fobj *f = NULL;
1210 	struct mobj *m = NULL;
1211 	vaddr_t log_addr = 0;
1212 	size_t log_size = 0;
1213 	int node = 0;
1214 
1215 	node = fdt_node_offset_by_compatible(fdt, 0, "arm,tpm_event_log");
1216 	if (node < 0)
1217 		return TEE_SUCCESS;
1218 
1219 	/* Checking the existence and size of the event log properties */
1220 	if (sp_dt_get_u64(fdt, node, "tpm_event_log_addr", &log_addr)) {
1221 		EMSG("tpm_event_log_addr not found or has invalid size");
1222 		return TEE_ERROR_BAD_FORMAT;
1223 	}
1224 
1225 	if (sp_dt_get_u32(fdt, node, "tpm_event_log_size", &dummy_size)) {
1226 		EMSG("tpm_event_log_size not found or has invalid size");
1227 		return TEE_ERROR_BAD_FORMAT;
1228 	}
1229 
1230 	/* Validating event log */
1231 	res = tpm_get_event_log_size(&log_size);
1232 	if (res)
1233 		return res;
1234 
1235 	if (!log_size) {
1236 		EMSG("Empty TPM event log was provided");
1237 		return TEE_ERROR_ITEM_NOT_FOUND;
1238 	}
1239 
1240 	/* Allocating memory area for the event log to share with the SP */
1241 	page_count = ROUNDUP_DIV(log_size, SMALL_PAGE_SIZE);
1242 
1243 	f = fobj_sec_mem_alloc(page_count);
1244 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
1245 	fobj_put(f);
1246 	if (!m)
1247 		return TEE_ERROR_OUT_OF_MEMORY;
1248 
1249 	res = vm_map(&ctx->uctx, &log_addr, log_size, perm, 0, m, 0);
1250 	mobj_put(m);
1251 	if (res)
1252 		return res;
1253 
1254 	/* Copy event log */
1255 	res = tpm_get_event_log((void *)log_addr, &log_size);
1256 	if (res)
1257 		goto err_unmap;
1258 
1259 	/* Setting event log details in the manifest */
1260 	res = fdt_setprop_u64(fdt, node, "tpm_event_log_addr", log_addr);
1261 	if (res)
1262 		goto err_unmap;
1263 
1264 	res = fdt_setprop_u32(fdt, node, "tpm_event_log_size", log_size);
1265 	if (res)
1266 		goto err_unmap;
1267 
1268 	return TEE_SUCCESS;
1269 
1270 err_unmap:
1271 	vm_unmap(&ctx->uctx, log_addr, log_size);
1272 
1273 	return res;
1274 }
1275 
1276 /*
1277  * Note: this function is called only on the primary CPU. It assumes that the
1278  * features present on the primary CPU are available on all of the secondary
1279  * CPUs as well.
1280  */
1281 static TEE_Result handle_hw_features(void *fdt)
1282 {
1283 	uint32_t val __maybe_unused = 0;
1284 	TEE_Result res = TEE_SUCCESS;
1285 	int node = 0;
1286 
1287 	/*
1288 	 * HW feature descriptions are optional in the SP manifest, it's not an
1289 	 * error if we don't find any.
1290 	 */
1291 	node = fdt_node_offset_by_compatible(fdt, 0, "arm,hw-features");
1292 	if (node < 0)
1293 		return TEE_SUCCESS;
1294 
1295 	/* Modify the crc32 property only if it's already present */
1296 	if (!sp_dt_get_u32(fdt, node, "crc32", &val)) {
1297 		res = fdt_setprop_u32(fdt, node, "crc32",
1298 				      feat_crc32_implemented());
1299 		if (res)
1300 			return res;
1301 	}
1302 
1303 	return TEE_SUCCESS;
1304 }
1305 
1306 static TEE_Result read_ns_interrupts_action(const void *fdt,
1307 					    struct sp_session *s)
1308 {
1309 	TEE_Result res = TEE_ERROR_BAD_PARAMETERS;
1310 
1311 	res = sp_dt_get_u32(fdt, 0, "ns-interrupts-action", &s->ns_int_mode);
1312 
1313 	if (res) {
1314 		EMSG("Mandatory property is missing: ns-interrupts-action");
1315 		return res;
1316 	}
1317 
1318 	switch (s->ns_int_mode) {
1319 	case SP_MANIFEST_NS_INT_QUEUED:
1320 	case SP_MANIFEST_NS_INT_SIGNALED:
1321 		/* OK */
1322 		break;
1323 
1324 	case SP_MANIFEST_NS_INT_MANAGED_EXIT:
1325 		EMSG("Managed exit is not implemented");
1326 		return TEE_ERROR_NOT_IMPLEMENTED;
1327 
1328 	default:
1329 		EMSG("Invalid ns-interrupts-action value: %"PRIu32,
1330 		     s->ns_int_mode);
1331 		return TEE_ERROR_BAD_PARAMETERS;
1332 	}
1333 
1334 	return TEE_SUCCESS;
1335 }
1336 
1337 static TEE_Result sp_init_uuid(const TEE_UUID *bin_uuid, const void * const fdt)
1338 {
1339 	TEE_Result res = TEE_SUCCESS;
1340 	struct sp_session *sess = NULL;
1341 	TEE_UUID ffa_uuid = {};
1342 
1343 	res = fdt_get_uuid(fdt, &ffa_uuid);
1344 	if (res)
1345 		return res;
1346 
1347 	res = sp_open_session(&sess,
1348 			      &open_sp_sessions,
1349 			      &ffa_uuid, bin_uuid, fdt);
1350 	if (res)
1351 		return res;
1352 
1353 	sess->fdt = fdt;
1354 	res = read_manifest_endpoint_id(sess);
1355 	if (res)
1356 		return res;
1357 	DMSG("endpoint is 0x%"PRIx16, sess->endpoint_id);
1358 
1359 	res = read_ns_interrupts_action(fdt, sess);
1360 	if (res)
1361 		return res;
1362 
1363 	return TEE_SUCCESS;
1364 }
1365 
1366 static TEE_Result sp_first_run(struct sp_session *sess)
1367 {
1368 	TEE_Result res = TEE_SUCCESS;
1369 	struct thread_smc_args args = { };
1370 	struct sp_ctx *ctx = NULL;
1371 	vaddr_t boot_info_va = 0;
1372 	size_t boot_info_size = 0;
1373 	void *fdt_copy = NULL;
1374 	size_t fdt_size = 0;
1375 
1376 	ctx = to_sp_ctx(sess->ts_sess.ctx);
1377 	ts_push_current_session(&sess->ts_sess);
1378 	sess->is_initialized = false;
1379 
1380 	/*
1381 	 * Load relative memory regions must be handled before doing any other
1382 	 * mapping to prevent conflicts in the VA space.
1383 	 */
1384 	res = handle_fdt_load_relative_mem_regions(ctx, sess->fdt);
1385 	if (res) {
1386 		ts_pop_current_session();
1387 		return res;
1388 	}
1389 
1390 	res = copy_and_map_fdt(ctx, sess->fdt, &fdt_copy, &fdt_size);
1391 	if (res)
1392 		goto out;
1393 
1394 	res = handle_fdt_dev_regions(ctx, fdt_copy);
1395 	if (res)
1396 		goto out;
1397 
1398 	res = handle_fdt_mem_regions(ctx, fdt_copy);
1399 	if (res)
1400 		goto out;
1401 
1402 	if (IS_ENABLED(CFG_CORE_TPM_EVENT_LOG)) {
1403 		res = handle_tpm_event_log(ctx, fdt_copy);
1404 		if (res)
1405 			goto out;
1406 	}
1407 
1408 	res = handle_hw_features(fdt_copy);
1409 	if (res)
1410 		goto out;
1411 
1412 	res = create_and_map_boot_info(ctx, fdt_copy, &args, &boot_info_va,
1413 				       &boot_info_size);
1414 	if (res)
1415 		goto out;
1416 
1417 	ts_pop_current_session();
1418 
1419 	res = sp_enter(&args, sess);
1420 	if (res) {
1421 		ts_push_current_session(&sess->ts_sess);
1422 		goto out;
1423 	}
1424 
1425 	spmc_sp_msg_handler(&args, sess);
1426 
1427 	ts_push_current_session(&sess->ts_sess);
1428 	sess->is_initialized = true;
1429 
1430 out:
1431 	/* Free the boot info page from the SP memory */
1432 	vm_unmap(&ctx->uctx, boot_info_va, boot_info_size);
1433 	vm_unmap(&ctx->uctx, (vaddr_t)fdt_copy, fdt_size);
1434 	ts_pop_current_session();
1435 
1436 	return res;
1437 }
1438 
1439 TEE_Result sp_enter(struct thread_smc_args *args, struct sp_session *sp)
1440 {
1441 	TEE_Result res = TEE_SUCCESS;
1442 	struct sp_ctx *ctx = to_sp_ctx(sp->ts_sess.ctx);
1443 
1444 	ctx->sp_regs.x[0] = args->a0;
1445 	ctx->sp_regs.x[1] = args->a1;
1446 	ctx->sp_regs.x[2] = args->a2;
1447 	ctx->sp_regs.x[3] = args->a3;
1448 	ctx->sp_regs.x[4] = args->a4;
1449 	ctx->sp_regs.x[5] = args->a5;
1450 	ctx->sp_regs.x[6] = args->a6;
1451 	ctx->sp_regs.x[7] = args->a7;
1452 
1453 	res = sp->ts_sess.ctx->ops->enter_invoke_cmd(&sp->ts_sess, 0);
1454 
1455 	args->a0 = ctx->sp_regs.x[0];
1456 	args->a1 = ctx->sp_regs.x[1];
1457 	args->a2 = ctx->sp_regs.x[2];
1458 	args->a3 = ctx->sp_regs.x[3];
1459 	args->a4 = ctx->sp_regs.x[4];
1460 	args->a5 = ctx->sp_regs.x[5];
1461 	args->a6 = ctx->sp_regs.x[6];
1462 	args->a7 = ctx->sp_regs.x[7];
1463 
1464 	return res;
1465 }
1466 
1467 /*
1468  * According to FF-A v1.1 section 8.3.1.4 if a caller requires less permissive
1469  * active on NS interrupt than the callee, the callee must inherit the caller's
1470  * configuration.
1471  * Each SP's own NS action setting is stored in ns_int_mode. The effective
1472  * action will be MIN([self action], [caller's action]) which is stored in the
1473  * ns_int_mode_inherited field.
1474  */
1475 static void sp_cpsr_configure_foreign_interrupts(struct sp_session *s,
1476 						 struct ts_session *caller,
1477 						 uint64_t *cpsr)
1478 {
1479 	if (caller) {
1480 		struct sp_session *caller_sp = to_sp_session(caller);
1481 
1482 		s->ns_int_mode_inherited = MIN(caller_sp->ns_int_mode_inherited,
1483 					       s->ns_int_mode);
1484 	} else {
1485 		s->ns_int_mode_inherited = s->ns_int_mode;
1486 	}
1487 
1488 	if (s->ns_int_mode_inherited == SP_MANIFEST_NS_INT_QUEUED)
1489 		*cpsr |= SHIFT_U32(THREAD_EXCP_FOREIGN_INTR,
1490 				   ARM32_CPSR_F_SHIFT);
1491 	else
1492 		*cpsr &= ~SHIFT_U32(THREAD_EXCP_FOREIGN_INTR,
1493 				    ARM32_CPSR_F_SHIFT);
1494 }
1495 
1496 static TEE_Result sp_enter_invoke_cmd(struct ts_session *s,
1497 				      uint32_t cmd __unused)
1498 {
1499 	struct sp_ctx *ctx = to_sp_ctx(s->ctx);
1500 	TEE_Result res = TEE_SUCCESS;
1501 	uint32_t exceptions = 0;
1502 	struct sp_session *sp_s = to_sp_session(s);
1503 	struct ts_session *sess = NULL;
1504 	struct thread_ctx_regs *sp_regs = NULL;
1505 	uint32_t thread_id = THREAD_ID_INVALID;
1506 	struct ts_session *caller = NULL;
1507 	uint32_t rpc_target_info = 0;
1508 	uint32_t panicked = false;
1509 	uint32_t panic_code = 0;
1510 
1511 	bm_timestamp();
1512 
1513 	sp_regs = &ctx->sp_regs;
1514 	ts_push_current_session(s);
1515 
1516 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
1517 
1518 	/* Enable/disable foreign interrupts in CPSR/SPSR */
1519 	caller = ts_get_calling_session();
1520 	sp_cpsr_configure_foreign_interrupts(sp_s, caller, &sp_regs->cpsr);
1521 
1522 	/*
1523 	 * Store endpoint ID and thread ID in rpc_target_info. This will be used
1524 	 * as w1 in FFA_INTERRUPT in case of a foreign interrupt.
1525 	 */
1526 	rpc_target_info = thread_get_tsd()->rpc_target_info;
1527 	thread_id = thread_get_id();
1528 	assert(thread_id <= UINT16_MAX);
1529 	thread_get_tsd()->rpc_target_info =
1530 		FFA_TARGET_INFO_SET(sp_s->endpoint_id, thread_id);
1531 
1532 	__thread_enter_user_mode(sp_regs, &panicked, &panic_code);
1533 
1534 	/* Restore rpc_target_info */
1535 	thread_get_tsd()->rpc_target_info = rpc_target_info;
1536 
1537 	thread_unmask_exceptions(exceptions);
1538 
1539 	thread_user_clear_vfp(&ctx->uctx);
1540 
1541 	if (panicked) {
1542 		DMSG("SP panicked with code  %#"PRIx32, panic_code);
1543 		abort_print_current_ts();
1544 
1545 		sess = ts_pop_current_session();
1546 		cpu_spin_lock(&sp_s->spinlock);
1547 		sp_s->state = sp_dead;
1548 		cpu_spin_unlock(&sp_s->spinlock);
1549 
1550 		return TEE_ERROR_TARGET_DEAD;
1551 	}
1552 
1553 	sess = ts_pop_current_session();
1554 	assert(sess == s);
1555 
1556 	bm_timestamp();
1557 
1558 	return res;
1559 }
1560 
1561 /* We currently don't support 32 bits */
1562 #ifdef ARM64
1563 static void sp_svc_store_registers(struct thread_scall_regs *regs,
1564 				   struct thread_ctx_regs *sp_regs)
1565 {
1566 	COMPILE_TIME_ASSERT(sizeof(sp_regs->x[0]) == sizeof(regs->x0));
1567 	memcpy(sp_regs->x, &regs->x0, 31 * sizeof(regs->x0));
1568 	sp_regs->pc = regs->elr;
1569 	sp_regs->sp = regs->sp_el0;
1570 }
1571 #endif
1572 
1573 static bool sp_handle_scall(struct thread_scall_regs *regs)
1574 {
1575 	struct ts_session *ts = ts_get_current_session();
1576 	struct sp_ctx *uctx = to_sp_ctx(ts->ctx);
1577 	struct sp_session *s = uctx->open_session;
1578 
1579 	assert(s);
1580 
1581 	sp_svc_store_registers(regs, &uctx->sp_regs);
1582 
1583 	regs->x0 = 0;
1584 	regs->x1 = 0; /* panic */
1585 	regs->x2 = 0; /* panic code */
1586 
1587 	/*
1588 	 * All the registers of the SP are saved in the SP session by the SVC
1589 	 * handler.
1590 	 * We always return to S-El1 after handling the SVC. We will continue
1591 	 * in sp_enter_invoke_cmd() (return from __thread_enter_user_mode).
1592 	 * The sp_enter() function copies the FF-A parameters (a0-a7) from the
1593 	 * saved registers to the thread_smc_args. The thread_smc_args object is
1594 	 * afterward used by the spmc_sp_msg_handler() to handle the
1595 	 * FF-A message send by the SP.
1596 	 */
1597 	return false;
1598 }
1599 
1600 static void sp_dump_state(struct ts_ctx *ctx)
1601 {
1602 	struct sp_ctx *utc = to_sp_ctx(ctx);
1603 
1604 	if (utc->uctx.dump_entry_func) {
1605 		TEE_Result res = ldelf_dump_state(&utc->uctx);
1606 
1607 		if (!res || res == TEE_ERROR_TARGET_DEAD)
1608 			return;
1609 	}
1610 
1611 	user_mode_ctx_print_mappings(&utc->uctx);
1612 }
1613 
1614 static const struct ts_ops sp_ops = {
1615 	.enter_invoke_cmd = sp_enter_invoke_cmd,
1616 	.handle_scall = sp_handle_scall,
1617 	.dump_state = sp_dump_state,
1618 };
1619 
1620 static TEE_Result process_sp_pkg(uint64_t sp_pkg_pa, TEE_UUID *sp_uuid)
1621 {
1622 	enum teecore_memtypes mtype = MEM_AREA_TA_RAM;
1623 	struct sp_pkg_header *sp_pkg_hdr = NULL;
1624 	struct fip_sp *sp = NULL;
1625 	uint64_t sp_fdt_end = 0;
1626 	size_t sp_pkg_size = 0;
1627 	vaddr_t sp_pkg_va = 0;
1628 
1629 	/* Process the first page which contains the SP package header */
1630 	sp_pkg_va = (vaddr_t)phys_to_virt(sp_pkg_pa, mtype, SMALL_PAGE_SIZE);
1631 	if (!sp_pkg_va) {
1632 		EMSG("Cannot find mapping for PA %#" PRIxPA, sp_pkg_pa);
1633 		return TEE_ERROR_GENERIC;
1634 	}
1635 
1636 	sp_pkg_hdr = (struct sp_pkg_header *)sp_pkg_va;
1637 
1638 	if (sp_pkg_hdr->magic != SP_PKG_HEADER_MAGIC) {
1639 		EMSG("Invalid SP package magic");
1640 		return TEE_ERROR_BAD_FORMAT;
1641 	}
1642 
1643 	if (sp_pkg_hdr->version != SP_PKG_HEADER_VERSION_V1 &&
1644 	    sp_pkg_hdr->version != SP_PKG_HEADER_VERSION_V2) {
1645 		EMSG("Invalid SP header version");
1646 		return TEE_ERROR_BAD_FORMAT;
1647 	}
1648 
1649 	if (ADD_OVERFLOW(sp_pkg_hdr->img_offset, sp_pkg_hdr->img_size,
1650 			 &sp_pkg_size)) {
1651 		EMSG("Invalid SP package size");
1652 		return TEE_ERROR_BAD_FORMAT;
1653 	}
1654 
1655 	if (ADD_OVERFLOW(sp_pkg_hdr->pm_offset, sp_pkg_hdr->pm_size,
1656 			 &sp_fdt_end) || sp_fdt_end > sp_pkg_hdr->img_offset) {
1657 		EMSG("Invalid SP manifest size");
1658 		return TEE_ERROR_BAD_FORMAT;
1659 	}
1660 
1661 	/* Process the whole SP package now that the size is known */
1662 	sp_pkg_va = (vaddr_t)phys_to_virt(sp_pkg_pa, mtype, sp_pkg_size);
1663 	if (!sp_pkg_va) {
1664 		EMSG("Cannot find mapping for PA %#" PRIxPA, sp_pkg_pa);
1665 		return TEE_ERROR_GENERIC;
1666 	}
1667 
1668 	sp_pkg_hdr = (struct sp_pkg_header *)sp_pkg_va;
1669 
1670 	sp = calloc(1, sizeof(struct fip_sp));
1671 	if (!sp)
1672 		return TEE_ERROR_OUT_OF_MEMORY;
1673 
1674 	memcpy(&sp->sp_img.image.uuid, sp_uuid, sizeof(*sp_uuid));
1675 	sp->sp_img.image.ts = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->img_offset);
1676 	sp->sp_img.image.size = sp_pkg_hdr->img_size;
1677 	sp->sp_img.image.flags = 0;
1678 	sp->sp_img.fdt = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->pm_offset);
1679 
1680 	STAILQ_INSERT_TAIL(&fip_sp_list, sp, link);
1681 
1682 	return TEE_SUCCESS;
1683 }
1684 
1685 static TEE_Result fip_sp_init_all(void)
1686 {
1687 	TEE_Result res = TEE_SUCCESS;
1688 	uint64_t sp_pkg_addr = 0;
1689 	const void *fdt = NULL;
1690 	TEE_UUID sp_uuid = { };
1691 	int sp_pkgs_node = 0;
1692 	int subnode = 0;
1693 	int root = 0;
1694 
1695 	fdt = get_tos_fw_config_dt();
1696 	if (!fdt) {
1697 		EMSG("No SPMC manifest found");
1698 		return TEE_ERROR_GENERIC;
1699 	}
1700 
1701 	root = fdt_path_offset(fdt, "/");
1702 	if (root < 0)
1703 		return TEE_ERROR_BAD_FORMAT;
1704 
1705 	if (fdt_node_check_compatible(fdt, root, "arm,ffa-core-manifest-1.0"))
1706 		return TEE_ERROR_BAD_FORMAT;
1707 
1708 	/* SP packages are optional, it's not an error if we don't find any */
1709 	sp_pkgs_node = fdt_node_offset_by_compatible(fdt, root, "arm,sp_pkg");
1710 	if (sp_pkgs_node < 0)
1711 		return TEE_SUCCESS;
1712 
1713 	fdt_for_each_subnode(subnode, fdt, sp_pkgs_node) {
1714 		res = sp_dt_get_u64(fdt, subnode, "load-address", &sp_pkg_addr);
1715 		if (res) {
1716 			EMSG("Invalid FIP SP load address");
1717 			return res;
1718 		}
1719 
1720 		res = sp_dt_get_uuid(fdt, subnode, "uuid", &sp_uuid);
1721 		if (res) {
1722 			EMSG("Invalid FIP SP uuid");
1723 			return res;
1724 		}
1725 
1726 		res = process_sp_pkg(sp_pkg_addr, &sp_uuid);
1727 		if (res) {
1728 			EMSG("Invalid FIP SP package");
1729 			return res;
1730 		}
1731 	}
1732 
1733 	return TEE_SUCCESS;
1734 }
1735 
1736 static void fip_sp_deinit_all(void)
1737 {
1738 	while (!STAILQ_EMPTY(&fip_sp_list)) {
1739 		struct fip_sp *sp = STAILQ_FIRST(&fip_sp_list);
1740 
1741 		STAILQ_REMOVE_HEAD(&fip_sp_list, link);
1742 		free(sp);
1743 	}
1744 }
1745 
1746 static TEE_Result sp_init_all(void)
1747 {
1748 	TEE_Result res = TEE_SUCCESS;
1749 	const struct sp_image *sp = NULL;
1750 	const struct fip_sp *fip_sp = NULL;
1751 	char __maybe_unused msg[60] = { '\0', };
1752 	struct sp_session *s = NULL;
1753 
1754 	for_each_secure_partition(sp) {
1755 		if (sp->image.uncompressed_size)
1756 			snprintf(msg, sizeof(msg),
1757 				 " (compressed, uncompressed %u)",
1758 				 sp->image.uncompressed_size);
1759 		else
1760 			msg[0] = '\0';
1761 		DMSG("SP %pUl size %u%s", (void *)&sp->image.uuid,
1762 		     sp->image.size, msg);
1763 
1764 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1765 
1766 		if (res != TEE_SUCCESS) {
1767 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1768 			     &sp->image.uuid, res);
1769 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1770 				panic();
1771 		}
1772 	}
1773 
1774 	res = fip_sp_init_all();
1775 	if (res)
1776 		panic("Failed initializing FIP SPs");
1777 
1778 	for_each_fip_sp(fip_sp) {
1779 		sp = &fip_sp->sp_img;
1780 
1781 		DMSG("SP %pUl size %u", (void *)&sp->image.uuid,
1782 		     sp->image.size);
1783 
1784 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1785 
1786 		if (res != TEE_SUCCESS) {
1787 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1788 			     &sp->image.uuid, res);
1789 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1790 				panic();
1791 		}
1792 	}
1793 
1794 	/*
1795 	 * At this point all FIP SPs are loaded by ldelf or by the raw binary SP
1796 	 * loader, so the original images (loaded by BL2) are not needed anymore
1797 	 */
1798 	fip_sp_deinit_all();
1799 
1800 	/* Continue the initialization and run the SP */
1801 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
1802 		res = sp_first_run(s);
1803 		if (res != TEE_SUCCESS) {
1804 			EMSG("Failed starting SP(0x%"PRIx16") err:%#"PRIx32,
1805 			     s->endpoint_id, res);
1806 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1807 				panic();
1808 		}
1809 	}
1810 
1811 	return TEE_SUCCESS;
1812 }
1813 
1814 boot_final(sp_init_all);
1815 
1816 static TEE_Result secure_partition_open(const TEE_UUID *uuid,
1817 					struct ts_store_handle **h)
1818 {
1819 	return emb_ts_open(uuid, h, find_secure_partition);
1820 }
1821 
1822 REGISTER_SP_STORE(2) = {
1823 	.description = "SP store",
1824 	.open = secure_partition_open,
1825 	.get_size = emb_ts_get_size,
1826 	.get_tag = emb_ts_get_tag,
1827 	.read = emb_ts_read,
1828 	.close = emb_ts_close,
1829 };
1830