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