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