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