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