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