xref: /optee_os/core/arch/arm/kernel/secure_partition.c (revision 0d4767a921bb8b809570cacc7288317c0a392e1a)
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 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 handle_fdt_mem_regions(struct sp_ctx *ctx, void *fdt)
606 {
607 	int node = 0;
608 	int subnode = 0;
609 	tee_mm_entry_t *mm = NULL;
610 	TEE_Result res = TEE_SUCCESS;
611 
612 	/*
613 	 * Memory regions are optional in the SP manifest, it's not an error if
614 	 * we don't find any.
615 	 */
616 	node = fdt_node_offset_by_compatible(fdt, 0,
617 					     "arm,ffa-manifest-memory-regions");
618 	if (node < 0)
619 		return TEE_SUCCESS;
620 
621 	fdt_for_each_subnode(subnode, fdt, node) {
622 		bool alloc_needed = false;
623 		uint32_t attributes = 0;
624 		uint64_t base_addr = 0;
625 		uint32_t pages_cnt = 0;
626 		bool is_secure = true;
627 		struct mobj *m = NULL;
628 		unsigned int idx = 0;
629 		uint32_t perm = 0;
630 		size_t size = 0;
631 		vaddr_t va = 0;
632 
633 		mm = NULL;
634 
635 		/*
636 		 * Base address of a memory region.
637 		 * If not present, we have to allocate the specified memory.
638 		 * If present, this field could specify a PA or VA. Currently
639 		 * only a PA is supported.
640 		 */
641 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr))
642 			alloc_needed = true;
643 
644 		/* Size of memory region as count of 4K pages */
645 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
646 			EMSG("Mandatory field is missing: pages-count");
647 			return TEE_ERROR_BAD_FORMAT;
648 		}
649 
650 		if (MUL_OVERFLOW(pages_cnt, SMALL_PAGE_SIZE, &size))
651 			return TEE_ERROR_OVERFLOW;
652 
653 		/*
654 		 * Memory region attributes:
655 		 * - Instruction/data access permissions
656 		 * - Cacheability/shareability attributes
657 		 * - Security attributes
658 		 *
659 		 * Cacheability/shareability attributes can be ignored for now.
660 		 * OP-TEE only supports a single type for normal cached memory
661 		 * and currently there is no use case that would require to
662 		 * change this.
663 		 */
664 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
665 			EMSG("Mandatory field is missing: attributes");
666 			return TEE_ERROR_BAD_FORMAT;
667 		}
668 
669 		/* Check instruction and data access permissions */
670 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
671 		case SP_MANIFEST_ATTR_RO:
672 			perm = TEE_MATTR_UR;
673 			break;
674 		case SP_MANIFEST_ATTR_RW:
675 			perm = TEE_MATTR_URW;
676 			break;
677 		case SP_MANIFEST_ATTR_RX:
678 			perm = TEE_MATTR_URX;
679 			break;
680 		default:
681 			EMSG("Invalid memory access permissions");
682 			return TEE_ERROR_BAD_FORMAT;
683 		}
684 
685 		/*
686 		 * The SP is a secure endpoint, security attribute can be
687 		 * secure or non-secure.
688 		 * The SPMC cannot allocate non-secure memory, i.e. if the base
689 		 * address is missing this attribute must be secure.
690 		 */
691 		if (attributes & SP_MANIFEST_ATTR_NSEC) {
692 			if (alloc_needed) {
693 				EMSG("Invalid memory security attribute");
694 				return TEE_ERROR_BAD_FORMAT;
695 			}
696 			is_secure = false;
697 		}
698 
699 		if (alloc_needed) {
700 			/* Base address is missing, we have to allocate */
701 			mm = tee_mm_alloc(&tee_mm_sec_ddr, size);
702 			if (!mm)
703 				return TEE_ERROR_OUT_OF_MEMORY;
704 
705 			base_addr = tee_mm_get_smem(mm);
706 		}
707 
708 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_CACHED,
709 				    is_secure);
710 		if (!m) {
711 			res = TEE_ERROR_OUT_OF_MEMORY;
712 			goto err_mm_free;
713 		}
714 
715 		res = sp_mem_add_pages(m, &idx, base_addr, pages_cnt);
716 		if (res) {
717 			mobj_put(m);
718 			goto err_mm_free;
719 		}
720 
721 		res = vm_map(&ctx->uctx, &va, size, perm, 0, m, 0);
722 		mobj_put(m);
723 		if (res)
724 			goto err_mm_free;
725 
726 		/*
727 		 * Overwrite the memory region's base address in the fdt with
728 		 * the VA. This fdt will be passed to the SP.
729 		 * If the base-address field was not present in the original
730 		 * fdt, this function will create it. This doesn't cause issues
731 		 * since the necessary extra space has been allocated when
732 		 * opening the fdt.
733 		 */
734 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
735 
736 		/*
737 		 * Unmap the region if the overwrite failed since the SP won't
738 		 * be able to access it without knowing the VA.
739 		 */
740 		if (res) {
741 			vm_unmap(&ctx->uctx, va, size);
742 			goto err_mm_free;
743 		}
744 	}
745 
746 	return TEE_SUCCESS;
747 
748 err_mm_free:
749 	tee_mm_free(mm);
750 	return res;
751 }
752 
753 static TEE_Result handle_tpm_event_log(struct sp_ctx *ctx, void *fdt)
754 {
755 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
756 	uint32_t dummy_size __maybe_unused = 0;
757 	TEE_Result res = TEE_SUCCESS;
758 	size_t page_count = 0;
759 	struct fobj *f = NULL;
760 	struct mobj *m = NULL;
761 	vaddr_t log_addr = 0;
762 	size_t log_size = 0;
763 	int node = 0;
764 
765 	node = fdt_node_offset_by_compatible(fdt, 0, "arm,tpm_event_log");
766 	if (node < 0)
767 		return TEE_SUCCESS;
768 
769 	/* Checking the existence and size of the event log properties */
770 	if (sp_dt_get_u64(fdt, node, "tpm_event_log_addr", &log_addr)) {
771 		EMSG("tpm_event_log_addr not found or has invalid size");
772 		return TEE_ERROR_BAD_FORMAT;
773 	}
774 
775 	if (sp_dt_get_u32(fdt, node, "tpm_event_log_size", &dummy_size)) {
776 		EMSG("tpm_event_log_size not found or has invalid size");
777 		return TEE_ERROR_BAD_FORMAT;
778 	}
779 
780 	/* Validating event log */
781 	res = tpm_get_event_log_size(&log_size);
782 	if (res)
783 		return res;
784 
785 	if (!log_size) {
786 		EMSG("Empty TPM event log was provided");
787 		return TEE_ERROR_ITEM_NOT_FOUND;
788 	}
789 
790 	/* Allocating memory area for the event log to share with the SP */
791 	page_count = ROUNDUP_DIV(log_size, SMALL_PAGE_SIZE);
792 
793 	f = fobj_sec_mem_alloc(page_count);
794 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
795 	fobj_put(f);
796 	if (!m)
797 		return TEE_ERROR_OUT_OF_MEMORY;
798 
799 	res = vm_map(&ctx->uctx, &log_addr, log_size, perm, 0, m, 0);
800 	mobj_put(m);
801 	if (res)
802 		return res;
803 
804 	/* Copy event log */
805 	res = tpm_get_event_log((void *)log_addr, &log_size);
806 	if (res)
807 		goto err_unmap;
808 
809 	/* Setting event log details in the manifest */
810 	res = fdt_setprop_u64(fdt, node, "tpm_event_log_addr", log_addr);
811 	if (res)
812 		goto err_unmap;
813 
814 	res = fdt_setprop_u32(fdt, node, "tpm_event_log_size", log_size);
815 	if (res)
816 		goto err_unmap;
817 
818 	return TEE_SUCCESS;
819 
820 err_unmap:
821 	vm_unmap(&ctx->uctx, log_addr, log_size);
822 
823 	return res;
824 }
825 
826 static TEE_Result sp_init_uuid(const TEE_UUID *uuid, const void * const fdt)
827 {
828 	TEE_Result res = TEE_SUCCESS;
829 	struct sp_session *sess = NULL;
830 	struct thread_smc_args args = { };
831 	vaddr_t va = 0;
832 	size_t num_pgs = 0;
833 	struct sp_ctx *ctx = NULL;
834 	void *fdt_copy = NULL;
835 
836 	res = sp_open_session(&sess,
837 			      &open_sp_sessions,
838 			      uuid);
839 	if (res)
840 		return res;
841 
842 	res = check_fdt(fdt, uuid);
843 	if (res)
844 		return res;
845 
846 	ctx = to_sp_ctx(sess->ts_sess.ctx);
847 	ts_push_current_session(&sess->ts_sess);
848 
849 	res = sp_init_info(ctx, &args, fdt, &va, &num_pgs, &fdt_copy);
850 	if (res)
851 		goto out;
852 
853 	res = handle_fdt_dev_regions(ctx, fdt_copy);
854 	if (res)
855 		goto out;
856 
857 	res = handle_fdt_mem_regions(ctx, fdt_copy);
858 	if (res)
859 		goto out;
860 
861 	if (IS_ENABLED(CFG_CORE_TPM_EVENT_LOG)) {
862 		res = handle_tpm_event_log(ctx, fdt_copy);
863 		if (res)
864 			goto out;
865 	}
866 
867 	ts_pop_current_session();
868 
869 	if (sp_enter(&args, sess)) {
870 		vm_unmap(&ctx->uctx, va, num_pgs);
871 		return FFA_ABORTED;
872 	}
873 
874 	spmc_sp_msg_handler(&args, sess);
875 
876 	ts_push_current_session(&sess->ts_sess);
877 out:
878 	/* Free the boot info page from the SP memory */
879 	vm_unmap(&ctx->uctx, va, num_pgs);
880 	ts_pop_current_session();
881 
882 	return res;
883 }
884 
885 TEE_Result sp_enter(struct thread_smc_args *args, struct sp_session *sp)
886 {
887 	TEE_Result res = FFA_OK;
888 	struct sp_ctx *ctx = to_sp_ctx(sp->ts_sess.ctx);
889 
890 	ctx->sp_regs.x[0] = args->a0;
891 	ctx->sp_regs.x[1] = args->a1;
892 	ctx->sp_regs.x[2] = args->a2;
893 	ctx->sp_regs.x[3] = args->a3;
894 	ctx->sp_regs.x[4] = args->a4;
895 	ctx->sp_regs.x[5] = args->a5;
896 	ctx->sp_regs.x[6] = args->a6;
897 	ctx->sp_regs.x[7] = args->a7;
898 
899 	res = sp->ts_sess.ctx->ops->enter_invoke_cmd(&sp->ts_sess, 0);
900 
901 	args->a0 = ctx->sp_regs.x[0];
902 	args->a1 = ctx->sp_regs.x[1];
903 	args->a2 = ctx->sp_regs.x[2];
904 	args->a3 = ctx->sp_regs.x[3];
905 	args->a4 = ctx->sp_regs.x[4];
906 	args->a5 = ctx->sp_regs.x[5];
907 	args->a6 = ctx->sp_regs.x[6];
908 	args->a7 = ctx->sp_regs.x[7];
909 
910 	return res;
911 }
912 
913 static TEE_Result sp_enter_invoke_cmd(struct ts_session *s,
914 				      uint32_t cmd __unused)
915 {
916 	struct sp_ctx *ctx = to_sp_ctx(s->ctx);
917 	TEE_Result res = TEE_SUCCESS;
918 	uint32_t exceptions = 0;
919 	uint64_t cpsr = 0;
920 	struct sp_session *sp_s = to_sp_session(s);
921 	struct ts_session *sess = NULL;
922 	struct thread_ctx_regs *sp_regs = NULL;
923 	uint32_t panicked = false;
924 	uint32_t panic_code = 0;
925 
926 	bm_timestamp();
927 
928 	sp_regs = &ctx->sp_regs;
929 	ts_push_current_session(s);
930 
931 	cpsr = sp_regs->cpsr;
932 	sp_regs->cpsr = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
933 
934 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
935 	__thread_enter_user_mode(sp_regs, &panicked, &panic_code);
936 	sp_regs->cpsr = cpsr;
937 	thread_unmask_exceptions(exceptions);
938 
939 	thread_user_clear_vfp(&ctx->uctx);
940 
941 	if (panicked) {
942 		DMSG("SP panicked with code  %#"PRIx32, panic_code);
943 		abort_print_current_ts();
944 
945 		sess = ts_pop_current_session();
946 		cpu_spin_lock(&sp_s->spinlock);
947 		sp_s->state = sp_dead;
948 		cpu_spin_unlock(&sp_s->spinlock);
949 
950 		return TEE_ERROR_TARGET_DEAD;
951 	}
952 
953 	sess = ts_pop_current_session();
954 	assert(sess == s);
955 
956 	bm_timestamp();
957 
958 	return res;
959 }
960 
961 /* We currently don't support 32 bits */
962 #ifdef ARM64
963 static void sp_svc_store_registers(struct thread_svc_regs *regs,
964 				   struct thread_ctx_regs *sp_regs)
965 {
966 	COMPILE_TIME_ASSERT(sizeof(sp_regs->x[0]) == sizeof(regs->x0));
967 	memcpy(sp_regs->x, &regs->x0, 31 * sizeof(regs->x0));
968 	sp_regs->pc = regs->elr;
969 	sp_regs->sp = regs->sp_el0;
970 }
971 #endif
972 
973 static bool sp_handle_svc(struct thread_svc_regs *regs)
974 {
975 	struct ts_session *ts = ts_get_current_session();
976 	struct sp_ctx *uctx = to_sp_ctx(ts->ctx);
977 	struct sp_session *s = uctx->open_session;
978 
979 	assert(s);
980 
981 	sp_svc_store_registers(regs, &uctx->sp_regs);
982 
983 	regs->x0 = 0;
984 	regs->x1 = 0; /* panic */
985 	regs->x2 = 0; /* panic code */
986 
987 	/*
988 	 * All the registers of the SP are saved in the SP session by the SVC
989 	 * handler.
990 	 * We always return to S-El1 after handling the SVC. We will continue
991 	 * in sp_enter_invoke_cmd() (return from __thread_enter_user_mode).
992 	 * The sp_enter() function copies the FF-A parameters (a0-a7) from the
993 	 * saved registers to the thread_smc_args. The thread_smc_args object is
994 	 * afterward used by the spmc_sp_msg_handler() to handle the
995 	 * FF-A message send by the SP.
996 	 */
997 	return false;
998 }
999 
1000 static void sp_dump_state(struct ts_ctx *ctx)
1001 {
1002 	struct sp_ctx *utc = to_sp_ctx(ctx);
1003 
1004 	if (utc->uctx.dump_entry_func) {
1005 		TEE_Result res = ldelf_dump_state(&utc->uctx);
1006 
1007 		if (!res || res == TEE_ERROR_TARGET_DEAD)
1008 			return;
1009 	}
1010 
1011 	user_mode_ctx_print_mappings(&utc->uctx);
1012 }
1013 
1014 /*
1015  * Note: this variable is weak just to ease breaking its dependency chain
1016  * when added to the unpaged area.
1017  */
1018 const struct ts_ops sp_ops __weak __relrodata_unpaged("sp_ops") = {
1019 	.enter_invoke_cmd = sp_enter_invoke_cmd,
1020 	.handle_svc = sp_handle_svc,
1021 	.dump_state = sp_dump_state,
1022 };
1023 
1024 static TEE_Result process_sp_pkg(uint64_t sp_pkg_pa, TEE_UUID *sp_uuid)
1025 {
1026 	enum teecore_memtypes mtype = MEM_AREA_RAM_SEC;
1027 	struct sp_pkg_header *sp_pkg_hdr = NULL;
1028 	TEE_Result res = TEE_SUCCESS;
1029 	tee_mm_entry_t *mm = NULL;
1030 	struct fip_sp *sp = NULL;
1031 	uint64_t sp_fdt_end = 0;
1032 	size_t sp_pkg_size = 0;
1033 	vaddr_t sp_pkg_va = 0;
1034 	size_t num_pages = 0;
1035 
1036 	/* Map only the first page of the SP package to parse the header */
1037 	if (!tee_pbuf_is_sec(sp_pkg_pa, SMALL_PAGE_SIZE))
1038 		return TEE_ERROR_GENERIC;
1039 
1040 	mm = tee_mm_alloc(&tee_mm_sec_ddr, SMALL_PAGE_SIZE);
1041 	if (!mm)
1042 		return TEE_ERROR_OUT_OF_MEMORY;
1043 
1044 	sp_pkg_va = tee_mm_get_smem(mm);
1045 
1046 	if (core_mmu_map_contiguous_pages(sp_pkg_va, sp_pkg_pa, 1, mtype)) {
1047 		res = TEE_ERROR_GENERIC;
1048 		goto err;
1049 	}
1050 
1051 	sp_pkg_hdr = (struct sp_pkg_header *)sp_pkg_va;
1052 
1053 	if (sp_pkg_hdr->magic != SP_PKG_HEADER_MAGIC) {
1054 		EMSG("Invalid SP package magic");
1055 		res = TEE_ERROR_BAD_FORMAT;
1056 		goto err_unmap;
1057 	}
1058 
1059 	if (sp_pkg_hdr->version != SP_PKG_HEADER_VERSION) {
1060 		EMSG("Invalid SP header version");
1061 		res = TEE_ERROR_BAD_FORMAT;
1062 		goto err_unmap;
1063 	}
1064 
1065 	if (ADD_OVERFLOW(sp_pkg_hdr->img_offset, sp_pkg_hdr->img_size,
1066 			 &sp_pkg_size)) {
1067 		EMSG("Invalid SP package size");
1068 		res = TEE_ERROR_BAD_FORMAT;
1069 		goto err_unmap;
1070 	}
1071 
1072 	if (ADD_OVERFLOW(sp_pkg_hdr->pm_offset, sp_pkg_hdr->pm_size,
1073 			 &sp_fdt_end) || sp_fdt_end > sp_pkg_hdr->img_offset) {
1074 		EMSG("Invalid SP manifest size");
1075 		res = TEE_ERROR_BAD_FORMAT;
1076 		goto err_unmap;
1077 	}
1078 
1079 	core_mmu_unmap_pages(sp_pkg_va, 1);
1080 	tee_mm_free(mm);
1081 
1082 	/* Map the whole package */
1083 	if (!tee_pbuf_is_sec(sp_pkg_pa, sp_pkg_size))
1084 		return TEE_ERROR_GENERIC;
1085 
1086 	num_pages = ROUNDUP_DIV(sp_pkg_size, SMALL_PAGE_SIZE);
1087 
1088 	mm = tee_mm_alloc(&tee_mm_sec_ddr, sp_pkg_size);
1089 	if (!mm)
1090 		return TEE_ERROR_OUT_OF_MEMORY;
1091 
1092 	sp_pkg_va = tee_mm_get_smem(mm);
1093 
1094 	if (core_mmu_map_contiguous_pages(sp_pkg_va, sp_pkg_pa, num_pages,
1095 					  mtype)) {
1096 		res = TEE_ERROR_GENERIC;
1097 		goto err;
1098 	}
1099 
1100 	sp_pkg_hdr = (struct sp_pkg_header *)tee_mm_get_smem(mm);
1101 
1102 	sp = calloc(1, sizeof(struct fip_sp));
1103 	if (!sp) {
1104 		res = TEE_ERROR_OUT_OF_MEMORY;
1105 		goto err_unmap;
1106 	}
1107 
1108 	memcpy(&sp->sp_img.image.uuid, sp_uuid, sizeof(*sp_uuid));
1109 	sp->sp_img.image.ts = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->img_offset);
1110 	sp->sp_img.image.size = sp_pkg_hdr->img_size;
1111 	sp->sp_img.image.flags = 0;
1112 	sp->sp_img.fdt = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->pm_offset);
1113 	sp->mm = mm;
1114 
1115 	STAILQ_INSERT_TAIL(&fip_sp_list, sp, link);
1116 
1117 	return TEE_SUCCESS;
1118 
1119 err_unmap:
1120 	core_mmu_unmap_pages(tee_mm_get_smem(mm),
1121 			     ROUNDUP_DIV(tee_mm_get_bytes(mm),
1122 					 SMALL_PAGE_SIZE));
1123 err:
1124 	tee_mm_free(mm);
1125 
1126 	return res;
1127 }
1128 
1129 static TEE_Result fip_sp_map_all(void)
1130 {
1131 	TEE_Result res = TEE_SUCCESS;
1132 	uint64_t sp_pkg_addr = 0;
1133 	const void *fdt = NULL;
1134 	TEE_UUID sp_uuid = { };
1135 	int sp_pkgs_node = 0;
1136 	int subnode = 0;
1137 	int root = 0;
1138 
1139 	fdt = get_external_dt();
1140 	if (!fdt) {
1141 		EMSG("No SPMC manifest found");
1142 		return TEE_ERROR_GENERIC;
1143 	}
1144 
1145 	root = fdt_path_offset(fdt, "/");
1146 	if (root < 0)
1147 		return TEE_ERROR_BAD_FORMAT;
1148 
1149 	if (fdt_node_check_compatible(fdt, root, "arm,ffa-core-manifest-1.0"))
1150 		return TEE_ERROR_BAD_FORMAT;
1151 
1152 	/* SP packages are optional, it's not an error if we don't find any */
1153 	sp_pkgs_node = fdt_node_offset_by_compatible(fdt, root, "arm,sp_pkg");
1154 	if (sp_pkgs_node < 0)
1155 		return TEE_SUCCESS;
1156 
1157 	fdt_for_each_subnode(subnode, fdt, sp_pkgs_node) {
1158 		res = sp_dt_get_u64(fdt, subnode, "load-address", &sp_pkg_addr);
1159 		if (res) {
1160 			EMSG("Invalid FIP SP load address");
1161 			return res;
1162 		}
1163 
1164 		res = sp_dt_get_uuid(fdt, subnode, "uuid", &sp_uuid);
1165 		if (res) {
1166 			EMSG("Invalid FIP SP uuid");
1167 			return res;
1168 		}
1169 
1170 		res = process_sp_pkg(sp_pkg_addr, &sp_uuid);
1171 		if (res) {
1172 			EMSG("Invalid FIP SP package");
1173 			return res;
1174 		}
1175 	}
1176 
1177 	return TEE_SUCCESS;
1178 }
1179 
1180 static void fip_sp_unmap_all(void)
1181 {
1182 	while (!STAILQ_EMPTY(&fip_sp_list)) {
1183 		struct fip_sp *sp = STAILQ_FIRST(&fip_sp_list);
1184 
1185 		STAILQ_REMOVE_HEAD(&fip_sp_list, link);
1186 		core_mmu_unmap_pages(tee_mm_get_smem(sp->mm),
1187 				     ROUNDUP_DIV(tee_mm_get_bytes(sp->mm),
1188 						 SMALL_PAGE_SIZE));
1189 		tee_mm_free(sp->mm);
1190 		free(sp);
1191 	}
1192 }
1193 
1194 static TEE_Result sp_init_all(void)
1195 {
1196 	TEE_Result res = TEE_SUCCESS;
1197 	const struct sp_image *sp = NULL;
1198 	const struct fip_sp *fip_sp = NULL;
1199 	char __maybe_unused msg[60] = { '\0', };
1200 
1201 	for_each_secure_partition(sp) {
1202 		if (sp->image.uncompressed_size)
1203 			snprintf(msg, sizeof(msg),
1204 				 " (compressed, uncompressed %u)",
1205 				 sp->image.uncompressed_size);
1206 		else
1207 			msg[0] = '\0';
1208 		DMSG("SP %pUl size %u%s", (void *)&sp->image.uuid,
1209 		     sp->image.size, msg);
1210 
1211 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1212 
1213 		if (res != TEE_SUCCESS) {
1214 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1215 			     &sp->image.uuid, res);
1216 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1217 				panic();
1218 		}
1219 	}
1220 
1221 	res = fip_sp_map_all();
1222 	if (res)
1223 		panic("Failed mapping FIP SPs");
1224 
1225 	for_each_fip_sp(fip_sp) {
1226 		sp = &fip_sp->sp_img;
1227 
1228 		DMSG("SP %pUl size %u", (void *)&sp->image.uuid,
1229 		     sp->image.size);
1230 
1231 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1232 
1233 		if (res != TEE_SUCCESS) {
1234 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1235 			     &sp->image.uuid, res);
1236 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1237 				panic();
1238 		}
1239 	}
1240 
1241 	/*
1242 	 * At this point all FIP SPs are loaded by ldelf so the original images
1243 	 * (loaded by BL2 earlier) can be unmapped
1244 	 */
1245 	fip_sp_unmap_all();
1246 
1247 	return TEE_SUCCESS;
1248 }
1249 
1250 boot_final(sp_init_all);
1251 
1252 static TEE_Result secure_partition_open(const TEE_UUID *uuid,
1253 					struct ts_store_handle **h)
1254 {
1255 	return emb_ts_open(uuid, h, find_secure_partition);
1256 }
1257 
1258 REGISTER_SP_STORE(2) = {
1259 	.description = "SP store",
1260 	.open = secure_partition_open,
1261 	.get_size = emb_ts_get_size,
1262 	.get_tag = emb_ts_get_tag,
1263 	.read = emb_ts_read,
1264 	.close = emb_ts_close,
1265 };
1266