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