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