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