xref: /optee_os/core/arch/arm/kernel/secure_partition.c (revision fdc4a8bef4978835f05b1687c99e090c85b84b7c)
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_dt_get_u64(const void *fdt, int node, const char *property,
324 				uint64_t *value)
325 {
326 	const fdt64_t *p = NULL;
327 	int len = 0;
328 
329 	p = fdt_getprop(fdt, node, property, &len);
330 	if (!p)
331 		return TEE_ERROR_ITEM_NOT_FOUND;
332 
333 	if (len != sizeof(*p))
334 		return TEE_ERROR_BAD_FORMAT;
335 
336 	*value = fdt64_ld(p);
337 
338 	return TEE_SUCCESS;
339 }
340 
341 static TEE_Result sp_dt_get_u32(const void *fdt, int node, const char *property,
342 				uint32_t *value)
343 {
344 	const fdt32_t *p = NULL;
345 	int len = 0;
346 
347 	p = fdt_getprop(fdt, node, property, &len);
348 	if (!p)
349 		return TEE_ERROR_ITEM_NOT_FOUND;
350 
351 	if (len != sizeof(*p))
352 		return TEE_ERROR_BAD_FORMAT;
353 
354 	*value = fdt32_to_cpu(*p);
355 
356 	return TEE_SUCCESS;
357 }
358 
359 static TEE_Result sp_dt_get_uuid(const void *fdt, int node,
360 				 const char *property, TEE_UUID *uuid)
361 {
362 	uint32_t uuid_array[4] = { 0 };
363 	const fdt32_t *p = NULL;
364 	int len = 0;
365 	int i = 0;
366 
367 	p = fdt_getprop(fdt, node, property, &len);
368 	if (!p)
369 		return TEE_ERROR_ITEM_NOT_FOUND;
370 
371 	if (len != sizeof(TEE_UUID))
372 		return TEE_ERROR_BAD_FORMAT;
373 
374 	for (i = 0; i < 4; i++)
375 		uuid_array[i] = fdt32_to_cpu(p[i]);
376 
377 	tee_uuid_from_octets(uuid, (uint8_t *)uuid_array);
378 
379 	return TEE_SUCCESS;
380 }
381 
382 static TEE_Result sp_is_elf_format(const void *fdt, int sp_node,
383 				   bool *is_elf_format)
384 {
385 	TEE_Result res = TEE_SUCCESS;
386 	uint32_t elf_format = 0;
387 
388 	res = sp_dt_get_u32(fdt, sp_node, "elf-format", &elf_format);
389 	if (res != TEE_SUCCESS && res != TEE_ERROR_ITEM_NOT_FOUND)
390 		return res;
391 
392 	*is_elf_format = (elf_format != 0);
393 
394 	return TEE_SUCCESS;
395 }
396 
397 static TEE_Result sp_binary_open(const TEE_UUID *uuid,
398 				 const struct ts_store_ops **ops,
399 				 struct ts_store_handle **handle)
400 {
401 	TEE_Result res = TEE_ERROR_ITEM_NOT_FOUND;
402 
403 	SCATTERED_ARRAY_FOREACH(*ops, sp_stores, struct ts_store_ops) {
404 		res = (*ops)->open(uuid, handle);
405 		if (res != TEE_ERROR_ITEM_NOT_FOUND &&
406 		    res != TEE_ERROR_STORAGE_NOT_AVAILABLE)
407 			break;
408 	}
409 
410 	return res;
411 }
412 
413 static TEE_Result load_binary_sp(struct ts_session *s,
414 				 struct user_mode_ctx *uctx)
415 {
416 	size_t bin_size = 0, bin_size_rounded = 0, bin_page_count = 0;
417 	const struct ts_store_ops *store_ops = NULL;
418 	struct ts_store_handle *handle = NULL;
419 	TEE_Result res = TEE_SUCCESS;
420 	tee_mm_entry_t *mm = NULL;
421 	struct mobj *mobj = NULL;
422 	uaddr_t base_addr = 0;
423 	uint32_t vm_flags = 0;
424 	unsigned int idx = 0;
425 	vaddr_t va = 0;
426 
427 	if (!s || !uctx)
428 		return TEE_ERROR_BAD_PARAMETERS;
429 
430 	DMSG("Loading raw binary format SP %pUl", &uctx->ts_ctx->uuid);
431 
432 	vm_set_ctx(uctx->ts_ctx);
433 
434 	/* Find TS store and open SP binary */
435 	res = sp_binary_open(&uctx->ts_ctx->uuid, &store_ops, &handle);
436 	if (res != TEE_SUCCESS) {
437 		EMSG("Failed to open SP binary");
438 		return res;
439 	}
440 
441 	/* Query binary size and calculate page count */
442 	res = store_ops->get_size(handle, &bin_size);
443 	if (res != TEE_SUCCESS)
444 		goto err;
445 
446 	if (ROUNDUP_OVERFLOW(bin_size, SMALL_PAGE_SIZE, &bin_size_rounded)) {
447 		res = TEE_ERROR_OVERFLOW;
448 		goto err;
449 	}
450 
451 	bin_page_count = bin_size_rounded / SMALL_PAGE_SIZE;
452 
453 	/* Allocate memory */
454 	mm = tee_mm_alloc(&tee_mm_sec_ddr, bin_size_rounded);
455 	if (!mm) {
456 		res = TEE_ERROR_OUT_OF_MEMORY;
457 		goto err;
458 	}
459 
460 	base_addr = tee_mm_get_smem(mm);
461 
462 	/* Create mobj */
463 	mobj = sp_mem_new_mobj(bin_page_count, TEE_MATTR_MEM_TYPE_CACHED, true);
464 	if (!mobj) {
465 		res = TEE_ERROR_OUT_OF_MEMORY;
466 		goto err_free_tee_mm;
467 	}
468 
469 	res = sp_mem_add_pages(mobj, &idx, base_addr, bin_page_count);
470 	if (res)
471 		goto err_free_mobj;
472 
473 	/* Map memory area for the SP binary */
474 	res = vm_map(uctx, &va, bin_size_rounded, TEE_MATTR_URWX,
475 		     vm_flags, mobj, 0);
476 	if (res)
477 		goto err_free_mobj;
478 
479 	/* Read SP binary into the previously mapped memory area */
480 	res = store_ops->read(handle, (void *)va, bin_size);
481 	if (res)
482 		goto err_unmap;
483 
484 	/* Set memory protection to allow execution */
485 	res = vm_set_prot(uctx, va, bin_size_rounded, TEE_MATTR_UX);
486 	if (res)
487 		goto err_unmap;
488 
489 	mobj_put(mobj);
490 	store_ops->close(handle);
491 
492 	/* The entry point must be at the beginning of the SP binary. */
493 	uctx->entry_func = va;
494 	uctx->load_addr = va;
495 	uctx->is_32bit = false;
496 
497 	s->handle_scall = s->ctx->ops->handle_scall;
498 
499 	return TEE_SUCCESS;
500 
501 err_unmap:
502 	vm_unmap(uctx, va, bin_size_rounded);
503 
504 err_free_mobj:
505 	mobj_put(mobj);
506 
507 err_free_tee_mm:
508 	tee_mm_free(mm);
509 
510 err:
511 	store_ops->close(handle);
512 
513 	return res;
514 }
515 
516 static TEE_Result sp_open_session(struct sp_session **sess,
517 				  struct sp_sessions_head *open_sessions,
518 				  const TEE_UUID *uuid,
519 				  const void *fdt)
520 {
521 	TEE_Result res = TEE_SUCCESS;
522 	struct sp_session *s = NULL;
523 	struct sp_ctx *ctx = NULL;
524 	bool is_elf_format = false;
525 
526 	if (!find_secure_partition(uuid))
527 		return TEE_ERROR_ITEM_NOT_FOUND;
528 
529 	res = sp_create_session(open_sessions, uuid, &s);
530 	if (res != TEE_SUCCESS) {
531 		DMSG("sp_create_session failed %#"PRIx32, res);
532 		return res;
533 	}
534 
535 	ctx = to_sp_ctx(s->ts_sess.ctx);
536 	assert(ctx);
537 	if (!ctx)
538 		return TEE_ERROR_TARGET_DEAD;
539 	*sess = s;
540 
541 	ts_push_current_session(&s->ts_sess);
542 
543 	res = sp_is_elf_format(fdt, 0, &is_elf_format);
544 	if (res == TEE_SUCCESS) {
545 		if (is_elf_format) {
546 			/* Load the SP using ldelf. */
547 			ldelf_load_ldelf(&ctx->uctx);
548 			res = ldelf_init_with_ldelf(&s->ts_sess, &ctx->uctx);
549 		} else {
550 			/* Raw binary format SP */
551 			res = load_binary_sp(&s->ts_sess, &ctx->uctx);
552 		}
553 	} else {
554 		EMSG("Failed to detect SP format");
555 	}
556 
557 	if (res != TEE_SUCCESS) {
558 		EMSG("Failed loading SP  %#"PRIx32, res);
559 		ts_pop_current_session();
560 		return TEE_ERROR_TARGET_DEAD;
561 	}
562 
563 	/* Make the SP ready for its first run */
564 	s->state = sp_idle;
565 	s->caller_id = 0;
566 	sp_init_set_registers(ctx);
567 	ts_pop_current_session();
568 
569 	return TEE_SUCCESS;
570 }
571 
572 static TEE_Result check_fdt(const void * const fdt, const TEE_UUID *uuid)
573 {
574 	const struct fdt_property *description = NULL;
575 	int description_name_len = 0;
576 	TEE_UUID fdt_uuid = { };
577 
578 	if (fdt_node_check_compatible(fdt, 0, "arm,ffa-manifest-1.0")) {
579 		EMSG("Failed loading SP, manifest not found");
580 		return TEE_ERROR_BAD_PARAMETERS;
581 	}
582 
583 	description = fdt_get_property(fdt, 0, "description",
584 				       &description_name_len);
585 	if (description)
586 		DMSG("Loading SP: %s", description->data);
587 
588 	if (sp_dt_get_uuid(fdt, 0, "uuid", &fdt_uuid)) {
589 		EMSG("Missing or invalid UUID in SP manifest");
590 		return TEE_ERROR_BAD_FORMAT;
591 	}
592 
593 	if (memcmp(uuid, &fdt_uuid, sizeof(fdt_uuid))) {
594 		EMSG("Failed loading SP, UUID mismatch");
595 		return TEE_ERROR_BAD_FORMAT;
596 	}
597 
598 	return TEE_SUCCESS;
599 }
600 
601 /*
602  * sp_init_info allocates and maps the sp_ffa_init_info for the SP. It will copy
603  * the fdt into the allocated page(s) and return a pointer to the new location
604  * of the fdt. This pointer can be used to update data inside the fdt.
605  */
606 static TEE_Result sp_init_info(struct sp_ctx *ctx, struct thread_smc_args *args,
607 			       const void * const input_fdt, vaddr_t *va,
608 			       size_t *num_pgs, void **fdt_copy)
609 {
610 	struct sp_ffa_init_info *info = NULL;
611 	int nvp_count = 1;
612 	size_t total_size = ROUNDUP(CFG_SP_INIT_INFO_MAX_SIZE, SMALL_PAGE_SIZE);
613 	size_t nvp_size = sizeof(struct sp_name_value_pair) * nvp_count;
614 	size_t info_size = sizeof(*info) + nvp_size;
615 	size_t fdt_size = total_size - info_size;
616 	TEE_Result res = TEE_SUCCESS;
617 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
618 	struct fobj *f = NULL;
619 	struct mobj *m = NULL;
620 	static const char fdt_name[16] = "TYPE_DT\0\0\0\0\0\0\0\0";
621 
622 	*num_pgs = total_size / SMALL_PAGE_SIZE;
623 
624 	f = fobj_sec_mem_alloc(*num_pgs);
625 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
626 
627 	fobj_put(f);
628 	if (!m)
629 		return TEE_ERROR_OUT_OF_MEMORY;
630 
631 	res = vm_map(&ctx->uctx, va, total_size, perm, 0, m, 0);
632 	mobj_put(m);
633 	if (res)
634 		return res;
635 
636 	info = (struct sp_ffa_init_info *)*va;
637 
638 	/* magic field is 4 bytes, we don't copy /0 byte. */
639 	memcpy(&info->magic, "FF-A", 4);
640 	info->count = nvp_count;
641 	args->a0 = (vaddr_t)info;
642 
643 	/*
644 	 * Store the fdt after the boot_info and store the pointer in the
645 	 * first element.
646 	 */
647 	COMPILE_TIME_ASSERT(sizeof(info->nvp[0].name) == sizeof(fdt_name));
648 	memcpy(info->nvp[0].name, fdt_name, sizeof(fdt_name));
649 	info->nvp[0].value = *va + info_size;
650 	info->nvp[0].size = fdt_size;
651 	*fdt_copy = (void *)info->nvp[0].value;
652 
653 	if (fdt_open_into(input_fdt, *fdt_copy, fdt_size))
654 		return TEE_ERROR_GENERIC;
655 
656 	return TEE_SUCCESS;
657 }
658 
659 static TEE_Result handle_fdt_load_relative_mem_regions(struct sp_ctx *ctx,
660 						       const void *fdt)
661 {
662 	int node = 0;
663 	int subnode = 0;
664 	tee_mm_entry_t *mm = NULL;
665 	TEE_Result res = TEE_SUCCESS;
666 
667 	/*
668 	 * Memory regions are optional in the SP manifest, it's not an error if
669 	 * we don't find any.
670 	 */
671 	node = fdt_node_offset_by_compatible(fdt, 0,
672 					     "arm,ffa-manifest-memory-regions");
673 	if (node < 0)
674 		return TEE_SUCCESS;
675 
676 	fdt_for_each_subnode(subnode, fdt, node) {
677 		uint64_t load_rel_offset = 0;
678 		uint32_t attributes = 0;
679 		uint64_t base_addr = 0;
680 		uint32_t pages_cnt = 0;
681 		uint32_t flags = 0;
682 		uint32_t perm = 0;
683 		size_t size = 0;
684 		vaddr_t va = 0;
685 
686 		mm = NULL;
687 
688 		/* Load address relative offset of a memory region */
689 		if (!sp_dt_get_u64(fdt, subnode, "load-address-relative-offset",
690 				   &load_rel_offset)) {
691 			va = ctx->uctx.load_addr + load_rel_offset;
692 		} else {
693 			/* Skip non load address relative memory regions */
694 			continue;
695 		}
696 
697 		if (!sp_dt_get_u64(fdt, subnode, "base-address", &base_addr)) {
698 			EMSG("Both base-address and load-address-relative-offset fields are set");
699 			return TEE_ERROR_BAD_FORMAT;
700 		}
701 
702 		/* Size of memory region as count of 4K pages */
703 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
704 			EMSG("Mandatory field is missing: pages-count");
705 			return TEE_ERROR_BAD_FORMAT;
706 		}
707 
708 		if (MUL_OVERFLOW(pages_cnt, SMALL_PAGE_SIZE, &size))
709 			return TEE_ERROR_OVERFLOW;
710 
711 		/* Memory region attributes  */
712 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
713 			EMSG("Mandatory field is missing: attributes");
714 			return TEE_ERROR_BAD_FORMAT;
715 		}
716 
717 		/* Check instruction and data access permissions */
718 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
719 		case SP_MANIFEST_ATTR_RO:
720 			perm = TEE_MATTR_UR;
721 			break;
722 		case SP_MANIFEST_ATTR_RW:
723 			perm = TEE_MATTR_URW;
724 			break;
725 		case SP_MANIFEST_ATTR_RX:
726 			perm = TEE_MATTR_URX;
727 			break;
728 		default:
729 			EMSG("Invalid memory access permissions");
730 			return TEE_ERROR_BAD_FORMAT;
731 		}
732 
733 		res = sp_dt_get_u32(fdt, subnode, "load-flags", &flags);
734 		if (res != TEE_SUCCESS && res != TEE_ERROR_ITEM_NOT_FOUND) {
735 			EMSG("Optional field with invalid value: flags");
736 			return TEE_ERROR_BAD_FORMAT;
737 		}
738 
739 		/* Load relative regions must be secure */
740 		if (attributes & SP_MANIFEST_ATTR_NSEC) {
741 			EMSG("Invalid memory security attribute");
742 			return TEE_ERROR_BAD_FORMAT;
743 		}
744 
745 		if (flags & SP_MANIFEST_FLAG_NOBITS) {
746 			/*
747 			 * NOBITS flag is set, which means that loaded binary
748 			 * doesn't contain this area, so it's need to be
749 			 * allocated.
750 			 */
751 			struct mobj *m = NULL;
752 			unsigned int idx = 0;
753 
754 			mm = tee_mm_alloc(&tee_mm_sec_ddr, size);
755 			if (!mm)
756 				return TEE_ERROR_OUT_OF_MEMORY;
757 
758 			base_addr = tee_mm_get_smem(mm);
759 
760 			m = sp_mem_new_mobj(pages_cnt,
761 					    TEE_MATTR_MEM_TYPE_CACHED, true);
762 			if (!m) {
763 				res = TEE_ERROR_OUT_OF_MEMORY;
764 				goto err_mm_free;
765 			}
766 
767 			res = sp_mem_add_pages(m, &idx, base_addr, pages_cnt);
768 			if (res) {
769 				mobj_put(m);
770 				goto err_mm_free;
771 			}
772 
773 			res = vm_map(&ctx->uctx, &va, size, perm, 0, m, 0);
774 			mobj_put(m);
775 			if (res)
776 				goto err_mm_free;
777 		} else {
778 			/*
779 			 * If NOBITS is not present the memory area is already
780 			 * mapped and only need to set the correct permissions.
781 			 */
782 			res = vm_set_prot(&ctx->uctx, va, size, perm);
783 			if (res)
784 				return res;
785 		}
786 	}
787 
788 	return TEE_SUCCESS;
789 
790 err_mm_free:
791 	tee_mm_free(mm);
792 	return res;
793 }
794 
795 static TEE_Result handle_fdt_dev_regions(struct sp_ctx *ctx, void *fdt)
796 {
797 	int node = 0;
798 	int subnode = 0;
799 	TEE_Result res = TEE_SUCCESS;
800 	const char *dt_device_match_table = {
801 		"arm,ffa-manifest-device-regions",
802 	};
803 
804 	/*
805 	 * Device regions are optional in the SP manifest, it's not an error if
806 	 * we don't find any
807 	 */
808 	node = fdt_node_offset_by_compatible(fdt, 0, dt_device_match_table);
809 	if (node < 0)
810 		return TEE_SUCCESS;
811 
812 	fdt_for_each_subnode(subnode, fdt, node) {
813 		uint64_t base_addr = 0;
814 		uint32_t pages_cnt = 0;
815 		uint32_t attributes = 0;
816 		struct mobj *m = NULL;
817 		bool is_secure = true;
818 		uint32_t perm = 0;
819 		vaddr_t va = 0;
820 		unsigned int idx = 0;
821 
822 		/*
823 		 * Physical base address of a device MMIO region.
824 		 * Currently only physically contiguous region is supported.
825 		 */
826 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr)) {
827 			EMSG("Mandatory field is missing: base-address");
828 			return TEE_ERROR_BAD_FORMAT;
829 		}
830 
831 		/* Total size of MMIO region as count of 4K pages */
832 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
833 			EMSG("Mandatory field is missing: pages-count");
834 			return TEE_ERROR_BAD_FORMAT;
835 		}
836 
837 		/* Data access, instruction access and security attributes */
838 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
839 			EMSG("Mandatory field is missing: attributes");
840 			return TEE_ERROR_BAD_FORMAT;
841 		}
842 
843 		/* Check instruction and data access permissions */
844 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
845 		case SP_MANIFEST_ATTR_RO:
846 			perm = TEE_MATTR_UR;
847 			break;
848 		case SP_MANIFEST_ATTR_RW:
849 			perm = TEE_MATTR_URW;
850 			break;
851 		default:
852 			EMSG("Invalid memory access permissions");
853 			return TEE_ERROR_BAD_FORMAT;
854 		}
855 
856 		/*
857 		 * The SP is a secure endpoint, security attribute can be
858 		 * secure or non-secure
859 		 */
860 		if (attributes & SP_MANIFEST_ATTR_NSEC)
861 			is_secure = false;
862 
863 		/* Memory attributes must be Device-nGnRnE */
864 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_STRONGLY_O,
865 				    is_secure);
866 		if (!m)
867 			return TEE_ERROR_OUT_OF_MEMORY;
868 
869 		res = sp_mem_add_pages(m, &idx, (paddr_t)base_addr, pages_cnt);
870 		if (res) {
871 			mobj_put(m);
872 			return res;
873 		}
874 
875 		res = vm_map(&ctx->uctx, &va, pages_cnt * SMALL_PAGE_SIZE,
876 			     perm, 0, m, 0);
877 		mobj_put(m);
878 		if (res)
879 			return res;
880 
881 		/*
882 		 * Overwrite the device region's PA in the fdt with the VA. This
883 		 * fdt will be passed to the SP.
884 		 */
885 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
886 
887 		/*
888 		 * Unmap the region if the overwrite failed since the SP won't
889 		 * be able to access it without knowing the VA.
890 		 */
891 		if (res) {
892 			vm_unmap(&ctx->uctx, va, pages_cnt * SMALL_PAGE_SIZE);
893 			return res;
894 		}
895 	}
896 
897 	return TEE_SUCCESS;
898 }
899 
900 static TEE_Result swap_sp_endpoints(uint32_t endpoint_id,
901 				    uint32_t new_endpoint_id)
902 {
903 	struct sp_session *session = sp_get_session(endpoint_id);
904 	uint32_t manifest_endpoint_id = 0;
905 
906 	/*
907 	 * We don't know in which order the SPs are loaded. The endpoint ID
908 	 * defined in the manifest could already be generated by
909 	 * new_session_id() and used by another SP. If this is the case, we swap
910 	 * the ID's of the two SPs. We also have to make sure that the ID's are
911 	 * not defined twice in the manifest.
912 	 */
913 
914 	/* The endpoint ID was not assigned yet */
915 	if (!session)
916 		return TEE_SUCCESS;
917 
918 	/*
919 	 * Read the manifest file from the SP who originally had the endpoint.
920 	 * We can safely swap the endpoint ID's if the manifest file doesn't
921 	 * have an endpoint ID defined.
922 	 */
923 	if (!sp_dt_get_u32(session->fdt, 0, "id", &manifest_endpoint_id)) {
924 		assert(manifest_endpoint_id == endpoint_id);
925 		EMSG("SP: Found duplicated endpoint ID %#"PRIx32, endpoint_id);
926 		return TEE_ERROR_ACCESS_CONFLICT;
927 	}
928 
929 	session->endpoint_id = new_endpoint_id;
930 
931 	return TEE_SUCCESS;
932 }
933 
934 static TEE_Result read_manifest_endpoint_id(struct sp_session *s)
935 {
936 	uint32_t endpoint_id = 0;
937 
938 	/*
939 	 * The endpoint ID can be optionally defined in the manifest file. We
940 	 * have to map the ID inside the manifest to the SP if it's defined.
941 	 * If not, the endpoint ID generated inside new_session_id() will be
942 	 * used.
943 	 */
944 	if (!sp_dt_get_u32(s->fdt, 0, "id", &endpoint_id)) {
945 		TEE_Result res = TEE_ERROR_GENERIC;
946 
947 		if (endpoint_id <= SPMC_ENDPOINT_ID)
948 			return TEE_ERROR_BAD_FORMAT;
949 
950 		res = swap_sp_endpoints(endpoint_id, s->endpoint_id);
951 		if (res)
952 			return res;
953 
954 		DMSG("SP: endpoint ID (0x%"PRIx32") found in manifest",
955 		     endpoint_id);
956 		/* Assign the endpoint ID to the current SP */
957 		s->endpoint_id = endpoint_id;
958 	}
959 	return TEE_SUCCESS;
960 }
961 
962 static TEE_Result handle_fdt_mem_regions(struct sp_ctx *ctx, void *fdt)
963 {
964 	int node = 0;
965 	int subnode = 0;
966 	tee_mm_entry_t *mm = NULL;
967 	TEE_Result res = TEE_SUCCESS;
968 
969 	/*
970 	 * Memory regions are optional in the SP manifest, it's not an error if
971 	 * we don't find any.
972 	 */
973 	node = fdt_node_offset_by_compatible(fdt, 0,
974 					     "arm,ffa-manifest-memory-regions");
975 	if (node < 0)
976 		return TEE_SUCCESS;
977 
978 	fdt_for_each_subnode(subnode, fdt, node) {
979 		uint64_t load_rel_offset = 0;
980 		bool alloc_needed = false;
981 		uint32_t attributes = 0;
982 		uint64_t base_addr = 0;
983 		uint32_t pages_cnt = 0;
984 		bool is_secure = true;
985 		struct mobj *m = NULL;
986 		unsigned int idx = 0;
987 		uint32_t perm = 0;
988 		size_t size = 0;
989 		vaddr_t va = 0;
990 
991 		mm = NULL;
992 
993 		/* Load address relative offset of a memory region */
994 		if (!sp_dt_get_u64(fdt, subnode, "load-address-relative-offset",
995 				   &load_rel_offset)) {
996 			/*
997 			 * At this point the memory region is already mapped by
998 			 * handle_fdt_load_relative_mem_regions.
999 			 * Only need to set the base-address in the manifest and
1000 			 * then skip the rest of the mapping process.
1001 			 */
1002 			va = ctx->uctx.load_addr + load_rel_offset;
1003 			res = fdt_setprop_u64(fdt, subnode, "base-address", va);
1004 			if (res)
1005 				return res;
1006 
1007 			continue;
1008 		}
1009 
1010 		/*
1011 		 * Base address of a memory region.
1012 		 * If not present, we have to allocate the specified memory.
1013 		 * If present, this field could specify a PA or VA. Currently
1014 		 * only a PA is supported.
1015 		 */
1016 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr))
1017 			alloc_needed = true;
1018 
1019 		/* Size of memory region as count of 4K pages */
1020 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
1021 			EMSG("Mandatory field is missing: pages-count");
1022 			return TEE_ERROR_BAD_FORMAT;
1023 		}
1024 
1025 		if (MUL_OVERFLOW(pages_cnt, SMALL_PAGE_SIZE, &size))
1026 			return TEE_ERROR_OVERFLOW;
1027 
1028 		/*
1029 		 * Memory region attributes:
1030 		 * - Instruction/data access permissions
1031 		 * - Cacheability/shareability attributes
1032 		 * - Security attributes
1033 		 *
1034 		 * Cacheability/shareability attributes can be ignored for now.
1035 		 * OP-TEE only supports a single type for normal cached memory
1036 		 * and currently there is no use case that would require to
1037 		 * change this.
1038 		 */
1039 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
1040 			EMSG("Mandatory field is missing: attributes");
1041 			return TEE_ERROR_BAD_FORMAT;
1042 		}
1043 
1044 		/* Check instruction and data access permissions */
1045 		switch (attributes & SP_MANIFEST_ATTR_RWX) {
1046 		case SP_MANIFEST_ATTR_RO:
1047 			perm = TEE_MATTR_UR;
1048 			break;
1049 		case SP_MANIFEST_ATTR_RW:
1050 			perm = TEE_MATTR_URW;
1051 			break;
1052 		case SP_MANIFEST_ATTR_RX:
1053 			perm = TEE_MATTR_URX;
1054 			break;
1055 		default:
1056 			EMSG("Invalid memory access permissions");
1057 			return TEE_ERROR_BAD_FORMAT;
1058 		}
1059 
1060 		/*
1061 		 * The SP is a secure endpoint, security attribute can be
1062 		 * secure or non-secure.
1063 		 * The SPMC cannot allocate non-secure memory, i.e. if the base
1064 		 * address is missing this attribute must be secure.
1065 		 */
1066 		if (attributes & SP_MANIFEST_ATTR_NSEC) {
1067 			if (alloc_needed) {
1068 				EMSG("Invalid memory security attribute");
1069 				return TEE_ERROR_BAD_FORMAT;
1070 			}
1071 			is_secure = false;
1072 		}
1073 
1074 		if (alloc_needed) {
1075 			/* Base address is missing, we have to allocate */
1076 			mm = tee_mm_alloc(&tee_mm_sec_ddr, size);
1077 			if (!mm)
1078 				return TEE_ERROR_OUT_OF_MEMORY;
1079 
1080 			base_addr = tee_mm_get_smem(mm);
1081 		}
1082 
1083 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_CACHED,
1084 				    is_secure);
1085 		if (!m) {
1086 			res = TEE_ERROR_OUT_OF_MEMORY;
1087 			goto err_mm_free;
1088 		}
1089 
1090 		res = sp_mem_add_pages(m, &idx, base_addr, pages_cnt);
1091 		if (res) {
1092 			mobj_put(m);
1093 			goto err_mm_free;
1094 		}
1095 
1096 		res = vm_map(&ctx->uctx, &va, size, perm, 0, m, 0);
1097 		mobj_put(m);
1098 		if (res)
1099 			goto err_mm_free;
1100 
1101 		/*
1102 		 * Overwrite the memory region's base address in the fdt with
1103 		 * the VA. This fdt will be passed to the SP.
1104 		 * If the base-address field was not present in the original
1105 		 * fdt, this function will create it. This doesn't cause issues
1106 		 * since the necessary extra space has been allocated when
1107 		 * opening the fdt.
1108 		 */
1109 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
1110 
1111 		/*
1112 		 * Unmap the region if the overwrite failed since the SP won't
1113 		 * be able to access it without knowing the VA.
1114 		 */
1115 		if (res) {
1116 			vm_unmap(&ctx->uctx, va, size);
1117 			goto err_mm_free;
1118 		}
1119 	}
1120 
1121 	return TEE_SUCCESS;
1122 
1123 err_mm_free:
1124 	tee_mm_free(mm);
1125 	return res;
1126 }
1127 
1128 static TEE_Result handle_tpm_event_log(struct sp_ctx *ctx, void *fdt)
1129 {
1130 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
1131 	uint32_t dummy_size __maybe_unused = 0;
1132 	TEE_Result res = TEE_SUCCESS;
1133 	size_t page_count = 0;
1134 	struct fobj *f = NULL;
1135 	struct mobj *m = NULL;
1136 	vaddr_t log_addr = 0;
1137 	size_t log_size = 0;
1138 	int node = 0;
1139 
1140 	node = fdt_node_offset_by_compatible(fdt, 0, "arm,tpm_event_log");
1141 	if (node < 0)
1142 		return TEE_SUCCESS;
1143 
1144 	/* Checking the existence and size of the event log properties */
1145 	if (sp_dt_get_u64(fdt, node, "tpm_event_log_addr", &log_addr)) {
1146 		EMSG("tpm_event_log_addr not found or has invalid size");
1147 		return TEE_ERROR_BAD_FORMAT;
1148 	}
1149 
1150 	if (sp_dt_get_u32(fdt, node, "tpm_event_log_size", &dummy_size)) {
1151 		EMSG("tpm_event_log_size not found or has invalid size");
1152 		return TEE_ERROR_BAD_FORMAT;
1153 	}
1154 
1155 	/* Validating event log */
1156 	res = tpm_get_event_log_size(&log_size);
1157 	if (res)
1158 		return res;
1159 
1160 	if (!log_size) {
1161 		EMSG("Empty TPM event log was provided");
1162 		return TEE_ERROR_ITEM_NOT_FOUND;
1163 	}
1164 
1165 	/* Allocating memory area for the event log to share with the SP */
1166 	page_count = ROUNDUP_DIV(log_size, SMALL_PAGE_SIZE);
1167 
1168 	f = fobj_sec_mem_alloc(page_count);
1169 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
1170 	fobj_put(f);
1171 	if (!m)
1172 		return TEE_ERROR_OUT_OF_MEMORY;
1173 
1174 	res = vm_map(&ctx->uctx, &log_addr, log_size, perm, 0, m, 0);
1175 	mobj_put(m);
1176 	if (res)
1177 		return res;
1178 
1179 	/* Copy event log */
1180 	res = tpm_get_event_log((void *)log_addr, &log_size);
1181 	if (res)
1182 		goto err_unmap;
1183 
1184 	/* Setting event log details in the manifest */
1185 	res = fdt_setprop_u64(fdt, node, "tpm_event_log_addr", log_addr);
1186 	if (res)
1187 		goto err_unmap;
1188 
1189 	res = fdt_setprop_u32(fdt, node, "tpm_event_log_size", log_size);
1190 	if (res)
1191 		goto err_unmap;
1192 
1193 	return TEE_SUCCESS;
1194 
1195 err_unmap:
1196 	vm_unmap(&ctx->uctx, log_addr, log_size);
1197 
1198 	return res;
1199 }
1200 
1201 static TEE_Result sp_init_uuid(const TEE_UUID *uuid, const void * const fdt)
1202 {
1203 	TEE_Result res = TEE_SUCCESS;
1204 	struct sp_session *sess = NULL;
1205 
1206 	res = check_fdt(fdt, uuid);
1207 	if (res)
1208 		return res;
1209 
1210 	res = sp_open_session(&sess, &open_sp_sessions, uuid, fdt);
1211 	if (res)
1212 		return res;
1213 
1214 	sess->fdt = fdt;
1215 	res = read_manifest_endpoint_id(sess);
1216 	if (res)
1217 		return res;
1218 	DMSG("endpoint is 0x%"PRIx16, sess->endpoint_id);
1219 
1220 	return TEE_SUCCESS;
1221 }
1222 
1223 static TEE_Result sp_first_run(struct sp_session *sess)
1224 {
1225 	TEE_Result res = TEE_SUCCESS;
1226 	struct thread_smc_args args = { };
1227 	vaddr_t va = 0;
1228 	size_t num_pgs = 0;
1229 	struct sp_ctx *ctx = NULL;
1230 	void *fdt_copy = NULL;
1231 
1232 	ctx = to_sp_ctx(sess->ts_sess.ctx);
1233 	ts_push_current_session(&sess->ts_sess);
1234 
1235 	/*
1236 	 * Load relative memory regions must be handled before doing any other
1237 	 * mapping to prevent conflicts in the VA space.
1238 	 */
1239 	res = handle_fdt_load_relative_mem_regions(ctx, sess->fdt);
1240 	if (res) {
1241 		ts_pop_current_session();
1242 		return res;
1243 	}
1244 
1245 	res = sp_init_info(ctx, &args, sess->fdt, &va, &num_pgs, &fdt_copy);
1246 	if (res)
1247 		goto out;
1248 
1249 	res = handle_fdt_dev_regions(ctx, fdt_copy);
1250 	if (res)
1251 		goto out;
1252 
1253 	res = handle_fdt_mem_regions(ctx, fdt_copy);
1254 	if (res)
1255 		goto out;
1256 
1257 	if (IS_ENABLED(CFG_CORE_TPM_EVENT_LOG)) {
1258 		res = handle_tpm_event_log(ctx, fdt_copy);
1259 		if (res)
1260 			goto out;
1261 	}
1262 
1263 	ts_pop_current_session();
1264 
1265 	sess->is_initialized = false;
1266 	if (sp_enter(&args, sess)) {
1267 		vm_unmap(&ctx->uctx, va, num_pgs);
1268 		return FFA_ABORTED;
1269 	}
1270 
1271 	spmc_sp_msg_handler(&args, sess);
1272 
1273 	sess->is_initialized = true;
1274 
1275 	ts_push_current_session(&sess->ts_sess);
1276 out:
1277 	/* Free the boot info page from the SP memory */
1278 	vm_unmap(&ctx->uctx, va, num_pgs);
1279 	ts_pop_current_session();
1280 
1281 	return res;
1282 }
1283 
1284 TEE_Result sp_enter(struct thread_smc_args *args, struct sp_session *sp)
1285 {
1286 	TEE_Result res = FFA_OK;
1287 	struct sp_ctx *ctx = to_sp_ctx(sp->ts_sess.ctx);
1288 
1289 	ctx->sp_regs.x[0] = args->a0;
1290 	ctx->sp_regs.x[1] = args->a1;
1291 	ctx->sp_regs.x[2] = args->a2;
1292 	ctx->sp_regs.x[3] = args->a3;
1293 	ctx->sp_regs.x[4] = args->a4;
1294 	ctx->sp_regs.x[5] = args->a5;
1295 	ctx->sp_regs.x[6] = args->a6;
1296 	ctx->sp_regs.x[7] = args->a7;
1297 
1298 	res = sp->ts_sess.ctx->ops->enter_invoke_cmd(&sp->ts_sess, 0);
1299 
1300 	args->a0 = ctx->sp_regs.x[0];
1301 	args->a1 = ctx->sp_regs.x[1];
1302 	args->a2 = ctx->sp_regs.x[2];
1303 	args->a3 = ctx->sp_regs.x[3];
1304 	args->a4 = ctx->sp_regs.x[4];
1305 	args->a5 = ctx->sp_regs.x[5];
1306 	args->a6 = ctx->sp_regs.x[6];
1307 	args->a7 = ctx->sp_regs.x[7];
1308 
1309 	return res;
1310 }
1311 
1312 static TEE_Result sp_enter_invoke_cmd(struct ts_session *s,
1313 				      uint32_t cmd __unused)
1314 {
1315 	struct sp_ctx *ctx = to_sp_ctx(s->ctx);
1316 	TEE_Result res = TEE_SUCCESS;
1317 	uint32_t exceptions = 0;
1318 	uint64_t cpsr = 0;
1319 	struct sp_session *sp_s = to_sp_session(s);
1320 	struct ts_session *sess = NULL;
1321 	struct thread_ctx_regs *sp_regs = NULL;
1322 	uint32_t panicked = false;
1323 	uint32_t panic_code = 0;
1324 
1325 	bm_timestamp();
1326 
1327 	sp_regs = &ctx->sp_regs;
1328 	ts_push_current_session(s);
1329 
1330 	cpsr = sp_regs->cpsr;
1331 	sp_regs->cpsr = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1332 
1333 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
1334 	__thread_enter_user_mode(sp_regs, &panicked, &panic_code);
1335 	sp_regs->cpsr = cpsr;
1336 	thread_unmask_exceptions(exceptions);
1337 
1338 	thread_user_clear_vfp(&ctx->uctx);
1339 
1340 	if (panicked) {
1341 		DMSG("SP panicked with code  %#"PRIx32, panic_code);
1342 		abort_print_current_ts();
1343 
1344 		sess = ts_pop_current_session();
1345 		cpu_spin_lock(&sp_s->spinlock);
1346 		sp_s->state = sp_dead;
1347 		cpu_spin_unlock(&sp_s->spinlock);
1348 
1349 		return TEE_ERROR_TARGET_DEAD;
1350 	}
1351 
1352 	sess = ts_pop_current_session();
1353 	assert(sess == s);
1354 
1355 	bm_timestamp();
1356 
1357 	return res;
1358 }
1359 
1360 /* We currently don't support 32 bits */
1361 #ifdef ARM64
1362 static void sp_svc_store_registers(struct thread_scall_regs *regs,
1363 				   struct thread_ctx_regs *sp_regs)
1364 {
1365 	COMPILE_TIME_ASSERT(sizeof(sp_regs->x[0]) == sizeof(regs->x0));
1366 	memcpy(sp_regs->x, &regs->x0, 31 * sizeof(regs->x0));
1367 	sp_regs->pc = regs->elr;
1368 	sp_regs->sp = regs->sp_el0;
1369 }
1370 #endif
1371 
1372 static bool sp_handle_scall(struct thread_scall_regs *regs)
1373 {
1374 	struct ts_session *ts = ts_get_current_session();
1375 	struct sp_ctx *uctx = to_sp_ctx(ts->ctx);
1376 	struct sp_session *s = uctx->open_session;
1377 
1378 	assert(s);
1379 
1380 	sp_svc_store_registers(regs, &uctx->sp_regs);
1381 
1382 	regs->x0 = 0;
1383 	regs->x1 = 0; /* panic */
1384 	regs->x2 = 0; /* panic code */
1385 
1386 	/*
1387 	 * All the registers of the SP are saved in the SP session by the SVC
1388 	 * handler.
1389 	 * We always return to S-El1 after handling the SVC. We will continue
1390 	 * in sp_enter_invoke_cmd() (return from __thread_enter_user_mode).
1391 	 * The sp_enter() function copies the FF-A parameters (a0-a7) from the
1392 	 * saved registers to the thread_smc_args. The thread_smc_args object is
1393 	 * afterward used by the spmc_sp_msg_handler() to handle the
1394 	 * FF-A message send by the SP.
1395 	 */
1396 	return false;
1397 }
1398 
1399 static void sp_dump_state(struct ts_ctx *ctx)
1400 {
1401 	struct sp_ctx *utc = to_sp_ctx(ctx);
1402 
1403 	if (utc->uctx.dump_entry_func) {
1404 		TEE_Result res = ldelf_dump_state(&utc->uctx);
1405 
1406 		if (!res || res == TEE_ERROR_TARGET_DEAD)
1407 			return;
1408 	}
1409 
1410 	user_mode_ctx_print_mappings(&utc->uctx);
1411 }
1412 
1413 static const struct ts_ops sp_ops = {
1414 	.enter_invoke_cmd = sp_enter_invoke_cmd,
1415 	.handle_scall = sp_handle_scall,
1416 	.dump_state = sp_dump_state,
1417 };
1418 
1419 static TEE_Result process_sp_pkg(uint64_t sp_pkg_pa, TEE_UUID *sp_uuid)
1420 {
1421 	enum teecore_memtypes mtype = MEM_AREA_RAM_SEC;
1422 	struct sp_pkg_header *sp_pkg_hdr = NULL;
1423 	TEE_Result res = TEE_SUCCESS;
1424 	tee_mm_entry_t *mm = NULL;
1425 	struct fip_sp *sp = NULL;
1426 	uint64_t sp_fdt_end = 0;
1427 	size_t sp_pkg_size = 0;
1428 	vaddr_t sp_pkg_va = 0;
1429 	size_t num_pages = 0;
1430 
1431 	/* Map only the first page of the SP package to parse the header */
1432 	if (!tee_pbuf_is_sec(sp_pkg_pa, SMALL_PAGE_SIZE))
1433 		return TEE_ERROR_GENERIC;
1434 
1435 	mm = tee_mm_alloc(&tee_mm_sec_ddr, SMALL_PAGE_SIZE);
1436 	if (!mm)
1437 		return TEE_ERROR_OUT_OF_MEMORY;
1438 
1439 	sp_pkg_va = tee_mm_get_smem(mm);
1440 
1441 	if (core_mmu_map_contiguous_pages(sp_pkg_va, sp_pkg_pa, 1, mtype)) {
1442 		res = TEE_ERROR_GENERIC;
1443 		goto err;
1444 	}
1445 
1446 	sp_pkg_hdr = (struct sp_pkg_header *)sp_pkg_va;
1447 
1448 	if (sp_pkg_hdr->magic != SP_PKG_HEADER_MAGIC) {
1449 		EMSG("Invalid SP package magic");
1450 		res = TEE_ERROR_BAD_FORMAT;
1451 		goto err_unmap;
1452 	}
1453 
1454 	if (sp_pkg_hdr->version != SP_PKG_HEADER_VERSION_V1 &&
1455 	    sp_pkg_hdr->version != SP_PKG_HEADER_VERSION_V2) {
1456 		EMSG("Invalid SP header version");
1457 		res = TEE_ERROR_BAD_FORMAT;
1458 		goto err_unmap;
1459 	}
1460 
1461 	if (ADD_OVERFLOW(sp_pkg_hdr->img_offset, sp_pkg_hdr->img_size,
1462 			 &sp_pkg_size)) {
1463 		EMSG("Invalid SP package size");
1464 		res = TEE_ERROR_BAD_FORMAT;
1465 		goto err_unmap;
1466 	}
1467 
1468 	if (ADD_OVERFLOW(sp_pkg_hdr->pm_offset, sp_pkg_hdr->pm_size,
1469 			 &sp_fdt_end) || sp_fdt_end > sp_pkg_hdr->img_offset) {
1470 		EMSG("Invalid SP manifest size");
1471 		res = TEE_ERROR_BAD_FORMAT;
1472 		goto err_unmap;
1473 	}
1474 
1475 	core_mmu_unmap_pages(sp_pkg_va, 1);
1476 	tee_mm_free(mm);
1477 
1478 	/* Map the whole package */
1479 	if (!tee_pbuf_is_sec(sp_pkg_pa, sp_pkg_size))
1480 		return TEE_ERROR_GENERIC;
1481 
1482 	num_pages = ROUNDUP_DIV(sp_pkg_size, SMALL_PAGE_SIZE);
1483 
1484 	mm = tee_mm_alloc(&tee_mm_sec_ddr, sp_pkg_size);
1485 	if (!mm)
1486 		return TEE_ERROR_OUT_OF_MEMORY;
1487 
1488 	sp_pkg_va = tee_mm_get_smem(mm);
1489 
1490 	if (core_mmu_map_contiguous_pages(sp_pkg_va, sp_pkg_pa, num_pages,
1491 					  mtype)) {
1492 		res = TEE_ERROR_GENERIC;
1493 		goto err;
1494 	}
1495 
1496 	sp_pkg_hdr = (struct sp_pkg_header *)tee_mm_get_smem(mm);
1497 
1498 	sp = calloc(1, sizeof(struct fip_sp));
1499 	if (!sp) {
1500 		res = TEE_ERROR_OUT_OF_MEMORY;
1501 		goto err_unmap;
1502 	}
1503 
1504 	memcpy(&sp->sp_img.image.uuid, sp_uuid, sizeof(*sp_uuid));
1505 	sp->sp_img.image.ts = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->img_offset);
1506 	sp->sp_img.image.size = sp_pkg_hdr->img_size;
1507 	sp->sp_img.image.flags = 0;
1508 	sp->sp_img.fdt = (uint8_t *)(sp_pkg_va + sp_pkg_hdr->pm_offset);
1509 	sp->mm = mm;
1510 
1511 	STAILQ_INSERT_TAIL(&fip_sp_list, sp, link);
1512 
1513 	return TEE_SUCCESS;
1514 
1515 err_unmap:
1516 	core_mmu_unmap_pages(tee_mm_get_smem(mm),
1517 			     ROUNDUP_DIV(tee_mm_get_bytes(mm),
1518 					 SMALL_PAGE_SIZE));
1519 err:
1520 	tee_mm_free(mm);
1521 
1522 	return res;
1523 }
1524 
1525 static TEE_Result fip_sp_map_all(void)
1526 {
1527 	TEE_Result res = TEE_SUCCESS;
1528 	uint64_t sp_pkg_addr = 0;
1529 	const void *fdt = NULL;
1530 	TEE_UUID sp_uuid = { };
1531 	int sp_pkgs_node = 0;
1532 	int subnode = 0;
1533 	int root = 0;
1534 
1535 	fdt = get_tos_fw_config_dt();
1536 	if (!fdt) {
1537 		EMSG("No SPMC manifest found");
1538 		return TEE_ERROR_GENERIC;
1539 	}
1540 
1541 	root = fdt_path_offset(fdt, "/");
1542 	if (root < 0)
1543 		return TEE_ERROR_BAD_FORMAT;
1544 
1545 	if (fdt_node_check_compatible(fdt, root, "arm,ffa-core-manifest-1.0"))
1546 		return TEE_ERROR_BAD_FORMAT;
1547 
1548 	/* SP packages are optional, it's not an error if we don't find any */
1549 	sp_pkgs_node = fdt_node_offset_by_compatible(fdt, root, "arm,sp_pkg");
1550 	if (sp_pkgs_node < 0)
1551 		return TEE_SUCCESS;
1552 
1553 	fdt_for_each_subnode(subnode, fdt, sp_pkgs_node) {
1554 		res = sp_dt_get_u64(fdt, subnode, "load-address", &sp_pkg_addr);
1555 		if (res) {
1556 			EMSG("Invalid FIP SP load address");
1557 			return res;
1558 		}
1559 
1560 		res = sp_dt_get_uuid(fdt, subnode, "uuid", &sp_uuid);
1561 		if (res) {
1562 			EMSG("Invalid FIP SP uuid");
1563 			return res;
1564 		}
1565 
1566 		res = process_sp_pkg(sp_pkg_addr, &sp_uuid);
1567 		if (res) {
1568 			EMSG("Invalid FIP SP package");
1569 			return res;
1570 		}
1571 	}
1572 
1573 	return TEE_SUCCESS;
1574 }
1575 
1576 static void fip_sp_unmap_all(void)
1577 {
1578 	while (!STAILQ_EMPTY(&fip_sp_list)) {
1579 		struct fip_sp *sp = STAILQ_FIRST(&fip_sp_list);
1580 
1581 		STAILQ_REMOVE_HEAD(&fip_sp_list, link);
1582 		core_mmu_unmap_pages(tee_mm_get_smem(sp->mm),
1583 				     ROUNDUP_DIV(tee_mm_get_bytes(sp->mm),
1584 						 SMALL_PAGE_SIZE));
1585 		tee_mm_free(sp->mm);
1586 		free(sp);
1587 	}
1588 }
1589 
1590 static TEE_Result sp_init_all(void)
1591 {
1592 	TEE_Result res = TEE_SUCCESS;
1593 	const struct sp_image *sp = NULL;
1594 	const struct fip_sp *fip_sp = NULL;
1595 	char __maybe_unused msg[60] = { '\0', };
1596 	struct sp_session *s = NULL;
1597 
1598 	for_each_secure_partition(sp) {
1599 		if (sp->image.uncompressed_size)
1600 			snprintf(msg, sizeof(msg),
1601 				 " (compressed, uncompressed %u)",
1602 				 sp->image.uncompressed_size);
1603 		else
1604 			msg[0] = '\0';
1605 		DMSG("SP %pUl size %u%s", (void *)&sp->image.uuid,
1606 		     sp->image.size, msg);
1607 
1608 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1609 
1610 		if (res != TEE_SUCCESS) {
1611 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1612 			     &sp->image.uuid, res);
1613 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1614 				panic();
1615 		}
1616 	}
1617 
1618 	res = fip_sp_map_all();
1619 	if (res)
1620 		panic("Failed mapping FIP SPs");
1621 
1622 	for_each_fip_sp(fip_sp) {
1623 		sp = &fip_sp->sp_img;
1624 
1625 		DMSG("SP %pUl size %u", (void *)&sp->image.uuid,
1626 		     sp->image.size);
1627 
1628 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
1629 
1630 		if (res != TEE_SUCCESS) {
1631 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
1632 			     &sp->image.uuid, res);
1633 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1634 				panic();
1635 		}
1636 	}
1637 
1638 	/* Continue the initialization and run the SP */
1639 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
1640 		res = sp_first_run(s);
1641 		if (res != TEE_SUCCESS) {
1642 			EMSG("Failed starting SP(0x%"PRIx16") err:%#"PRIx32,
1643 			     s->endpoint_id, res);
1644 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
1645 				panic();
1646 		}
1647 	}
1648 	/*
1649 	 * At this point all FIP SPs are loaded by ldelf so the original images
1650 	 * (loaded by BL2 earlier) can be unmapped
1651 	 */
1652 	fip_sp_unmap_all();
1653 
1654 	return TEE_SUCCESS;
1655 }
1656 
1657 boot_final(sp_init_all);
1658 
1659 static TEE_Result secure_partition_open(const TEE_UUID *uuid,
1660 					struct ts_store_handle **h)
1661 {
1662 	return emb_ts_open(uuid, h, find_secure_partition);
1663 }
1664 
1665 REGISTER_SP_STORE(2) = {
1666 	.description = "SP store",
1667 	.open = secure_partition_open,
1668 	.get_size = emb_ts_get_size,
1669 	.get_tag = emb_ts_get_tag,
1670 	.read = emb_ts_read,
1671 	.close = emb_ts_close,
1672 };
1673