xref: /optee_os/core/arch/arm/kernel/secure_partition.c (revision 65ef988fd8eb7914ee1efd9ba6df8b9b91a76508)
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/embedded_ts.h>
9 #include <kernel/ldelf_loader.h>
10 #include <kernel/secure_partition.h>
11 #include <kernel/spinlock.h>
12 #include <kernel/spmc_sp_handler.h>
13 #include <kernel/thread_private.h>
14 #include <kernel/thread_spmc.h>
15 #include <kernel/tpm.h>
16 #include <kernel/ts_store.h>
17 #include <ldelf.h>
18 #include <libfdt.h>
19 #include <mm/core_mmu.h>
20 #include <mm/fobj.h>
21 #include <mm/mobj.h>
22 #include <mm/vm.h>
23 #include <optee_ffa.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <tee_api_types.h>
27 #include <tee/uuid.h>
28 #include <trace.h>
29 #include <types_ext.h>
30 #include <utee_defines.h>
31 #include <util.h>
32 #include <zlib.h>
33 
34 #define SP_MANIFEST_ATTR_READ		BIT(0)
35 #define SP_MANIFEST_ATTR_WRITE		BIT(1)
36 #define SP_MANIFEST_ATTR_EXEC		BIT(2)
37 #define SP_MANIFEST_ATTR_NSEC		BIT(3)
38 
39 const struct ts_ops sp_ops;
40 
41 /* List that holds all of the loaded SP's */
42 static struct sp_sessions_head open_sp_sessions =
43 	TAILQ_HEAD_INITIALIZER(open_sp_sessions);
44 
45 static const struct embedded_ts *find_secure_partition(const TEE_UUID *uuid)
46 {
47 	const struct sp_image *sp = NULL;
48 
49 	for_each_secure_partition(sp) {
50 		if (!memcmp(&sp->image.uuid, uuid, sizeof(*uuid)))
51 			return &sp->image;
52 	}
53 	return NULL;
54 }
55 
56 bool is_sp_ctx(struct ts_ctx *ctx)
57 {
58 	return ctx && (ctx->ops == &sp_ops);
59 }
60 
61 static void set_sp_ctx_ops(struct ts_ctx *ctx)
62 {
63 	ctx->ops = &sp_ops;
64 }
65 
66 TEE_Result sp_find_session_id(const TEE_UUID *uuid, uint32_t *session_id)
67 {
68 	struct sp_session *s = NULL;
69 
70 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
71 		if (!memcmp(&s->ts_sess.ctx->uuid, uuid, sizeof(*uuid))) {
72 			if (s->state == sp_dead)
73 				return TEE_ERROR_TARGET_DEAD;
74 
75 			*session_id  = s->endpoint_id;
76 			return TEE_SUCCESS;
77 		}
78 	}
79 
80 	return TEE_ERROR_ITEM_NOT_FOUND;
81 }
82 
83 struct sp_session *sp_get_session(uint32_t session_id)
84 {
85 	struct sp_session *s = NULL;
86 
87 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
88 		if (s->endpoint_id == session_id)
89 			return s;
90 	}
91 
92 	return NULL;
93 }
94 
95 TEE_Result sp_partition_info_get_all(struct ffa_partition_info *fpi,
96 				     size_t *elem_count)
97 {
98 	size_t in_count = *elem_count;
99 	struct sp_session *s = NULL;
100 	size_t count = 0;
101 
102 	TAILQ_FOREACH(s, &open_sp_sessions, link) {
103 		if (s->state == sp_dead)
104 			continue;
105 		if (count < in_count) {
106 			spmc_fill_partition_entry(fpi, s->endpoint_id, 1);
107 			fpi++;
108 		}
109 		count++;
110 	}
111 
112 	*elem_count = count;
113 	if (count > in_count)
114 		return TEE_ERROR_SHORT_BUFFER;
115 
116 	return TEE_SUCCESS;
117 }
118 
119 bool sp_has_exclusive_access(struct sp_mem_map_region *mem,
120 			     struct user_mode_ctx *uctx)
121 {
122 	/*
123 	 * Check that we have access to the region if it is supposed to be
124 	 * mapped to the current context.
125 	 */
126 	if (uctx) {
127 		struct vm_region *region = NULL;
128 
129 		/* Make sure that each mobj belongs to the SP */
130 		TAILQ_FOREACH(region, &uctx->vm_info.regions, link) {
131 			if (region->mobj == mem->mobj)
132 				break;
133 		}
134 
135 		if (!region)
136 			return false;
137 	}
138 
139 	/* Check that it is not shared with another SP */
140 	return !sp_mem_is_shared(mem);
141 }
142 
143 static uint16_t new_session_id(struct sp_sessions_head *open_sessions)
144 {
145 	struct sp_session *last = NULL;
146 	uint16_t id = SPMC_ENDPOINT_ID + 1;
147 
148 	last = TAILQ_LAST(open_sessions, sp_sessions_head);
149 	if (last)
150 		id = last->endpoint_id + 1;
151 
152 	assert(id > SPMC_ENDPOINT_ID);
153 	return id;
154 }
155 
156 static TEE_Result sp_create_ctx(const TEE_UUID *uuid, struct sp_session *s)
157 {
158 	TEE_Result res = TEE_SUCCESS;
159 	struct sp_ctx *spc = NULL;
160 
161 	/* Register context */
162 	spc = calloc(1, sizeof(struct sp_ctx));
163 	if (!spc)
164 		return TEE_ERROR_OUT_OF_MEMORY;
165 
166 	spc->uctx.ts_ctx = &spc->ts_ctx;
167 	spc->open_session = s;
168 	s->ts_sess.ctx = &spc->ts_ctx;
169 	spc->ts_ctx.uuid = *uuid;
170 
171 	res = vm_info_init(&spc->uctx);
172 	if (res)
173 		goto err;
174 
175 	set_sp_ctx_ops(&spc->ts_ctx);
176 
177 	return TEE_SUCCESS;
178 
179 err:
180 	free(spc);
181 	return res;
182 }
183 
184 static TEE_Result sp_create_session(struct sp_sessions_head *open_sessions,
185 				    const TEE_UUID *uuid,
186 				    struct sp_session **sess)
187 {
188 	TEE_Result res = TEE_SUCCESS;
189 	struct sp_session *s = calloc(1, sizeof(struct sp_session));
190 
191 	if (!s)
192 		return TEE_ERROR_OUT_OF_MEMORY;
193 
194 	s->endpoint_id = new_session_id(open_sessions);
195 	if (!s->endpoint_id) {
196 		res = TEE_ERROR_OVERFLOW;
197 		goto err;
198 	}
199 
200 	DMSG("Loading Secure Partition %pUl", (void *)uuid);
201 	res = sp_create_ctx(uuid, s);
202 	if (res)
203 		goto err;
204 
205 	TAILQ_INSERT_TAIL(open_sessions, s, link);
206 	*sess = s;
207 	return TEE_SUCCESS;
208 
209 err:
210 	free(s);
211 	return res;
212 }
213 
214 static TEE_Result sp_init_set_registers(struct sp_ctx *ctx)
215 {
216 	struct thread_ctx_regs *sp_regs = &ctx->sp_regs;
217 
218 	memset(sp_regs, 0, sizeof(*sp_regs));
219 	sp_regs->sp = ctx->uctx.stack_ptr;
220 	sp_regs->pc = ctx->uctx.entry_func;
221 
222 	return TEE_SUCCESS;
223 }
224 
225 TEE_Result sp_map_shared(struct sp_session *s,
226 			 struct sp_mem_receiver *receiver,
227 			 struct sp_mem *smem,
228 			 uint64_t *va)
229 {
230 	TEE_Result res = TEE_SUCCESS;
231 	struct sp_ctx *ctx = NULL;
232 	uint32_t perm = TEE_MATTR_UR;
233 	struct sp_mem_map_region *reg = NULL;
234 
235 	ctx = to_sp_ctx(s->ts_sess.ctx);
236 
237 	/* Get the permission */
238 	if (receiver->perm.perm & FFA_MEM_ACC_EXE)
239 		perm |= TEE_MATTR_UX;
240 
241 	if (receiver->perm.perm & FFA_MEM_ACC_RW) {
242 		if (receiver->perm.perm & FFA_MEM_ACC_EXE)
243 			return TEE_ERROR_ACCESS_CONFLICT;
244 
245 		perm |= TEE_MATTR_UW;
246 	}
247 	/*
248 	 * Currently we don't support passing a va. We can't guarantee that the
249 	 * full region will be mapped in a contiguous region. A smem->region can
250 	 * have multiple mobj for one share. Currently there doesn't seem to be
251 	 * an option to guarantee that these will be mapped in a contiguous va
252 	 * space.
253 	 */
254 	if (*va)
255 		return TEE_ERROR_NOT_SUPPORTED;
256 
257 	SLIST_FOREACH(reg, &smem->regions, link) {
258 		res = vm_map(&ctx->uctx, va, reg->page_count * SMALL_PAGE_SIZE,
259 			     perm, 0, reg->mobj, reg->page_offset);
260 
261 		if (res != TEE_SUCCESS) {
262 			EMSG("Failed to map memory region %#"PRIx32, res);
263 			return res;
264 		}
265 	}
266 	return TEE_SUCCESS;
267 }
268 
269 TEE_Result sp_unmap_ffa_regions(struct sp_session *s, struct sp_mem *smem)
270 {
271 	TEE_Result res = TEE_SUCCESS;
272 	vaddr_t vaddr = 0;
273 	size_t len = 0;
274 	struct sp_ctx *ctx = to_sp_ctx(s->ts_sess.ctx);
275 	struct sp_mem_map_region *reg = NULL;
276 
277 	SLIST_FOREACH(reg, &smem->regions, link) {
278 		vaddr = (vaddr_t)sp_mem_get_va(&ctx->uctx, reg->page_offset,
279 					       reg->mobj);
280 		len = reg->page_count * SMALL_PAGE_SIZE;
281 
282 		res = vm_unmap(&ctx->uctx, vaddr, len);
283 		if (res != TEE_SUCCESS)
284 			return res;
285 	}
286 
287 	return TEE_SUCCESS;
288 }
289 
290 static TEE_Result sp_open_session(struct sp_session **sess,
291 				  struct sp_sessions_head *open_sessions,
292 				  const TEE_UUID *uuid)
293 {
294 	TEE_Result res = TEE_SUCCESS;
295 	struct sp_session *s = NULL;
296 	struct sp_ctx *ctx = NULL;
297 
298 	if (!find_secure_partition(uuid))
299 		return TEE_ERROR_ITEM_NOT_FOUND;
300 
301 	res = sp_create_session(open_sessions, uuid, &s);
302 	if (res != TEE_SUCCESS) {
303 		DMSG("sp_create_session failed %#"PRIx32, res);
304 		return res;
305 	}
306 
307 	ctx = to_sp_ctx(s->ts_sess.ctx);
308 	assert(ctx);
309 	if (!ctx)
310 		return TEE_ERROR_TARGET_DEAD;
311 	*sess = s;
312 
313 	ts_push_current_session(&s->ts_sess);
314 	/* Load the SP using ldelf. */
315 	ldelf_load_ldelf(&ctx->uctx);
316 	res = ldelf_init_with_ldelf(&s->ts_sess, &ctx->uctx);
317 
318 	if (res != TEE_SUCCESS) {
319 		EMSG("Failed. loading SP using ldelf %#"PRIx32, res);
320 		ts_pop_current_session();
321 		return TEE_ERROR_TARGET_DEAD;
322 	}
323 
324 	/* Make the SP ready for its first run */
325 	s->state = sp_idle;
326 	s->caller_id = 0;
327 	sp_init_set_registers(ctx);
328 	ts_pop_current_session();
329 
330 	return TEE_SUCCESS;
331 }
332 
333 static TEE_Result sp_dt_get_u64(const void *fdt, int node, const char *property,
334 				uint64_t *value)
335 {
336 	const fdt64_t *p = NULL;
337 	int len = 0;
338 
339 	p = fdt_getprop(fdt, node, property, &len);
340 	if (!p || len != sizeof(*p))
341 		return TEE_ERROR_ITEM_NOT_FOUND;
342 
343 	*value = fdt64_to_cpu(*p);
344 
345 	return TEE_SUCCESS;
346 }
347 
348 static TEE_Result sp_dt_get_u32(const void *fdt, int node, const char *property,
349 				uint32_t *value)
350 {
351 	const fdt32_t *p = NULL;
352 	int len = 0;
353 
354 	p = fdt_getprop(fdt, node, property, &len);
355 	if (!p || len != sizeof(*p))
356 		return TEE_ERROR_ITEM_NOT_FOUND;
357 
358 	*value = fdt32_to_cpu(*p);
359 
360 	return TEE_SUCCESS;
361 }
362 
363 static TEE_Result check_fdt(const void * const fdt, const TEE_UUID *uuid)
364 {
365 	int len = 0;
366 	const fdt32_t *prop = NULL;
367 	int i = 0;
368 	const struct fdt_property *description = NULL;
369 	int description_name_len = 0;
370 	uint32_t uuid_array[4] = { 0 };
371 	TEE_UUID fdt_uuid = { };
372 
373 	if (fdt_node_check_compatible(fdt, 0, "arm,ffa-manifest-1.0")) {
374 		EMSG("Failed loading SP, manifest not found");
375 		return TEE_ERROR_BAD_PARAMETERS;
376 	}
377 
378 	description = fdt_get_property(fdt, 0, "description",
379 				       &description_name_len);
380 	if (description)
381 		DMSG("Loading SP: %s", description->data);
382 
383 	prop = fdt_getprop(fdt, 0, "uuid", &len);
384 	if (!prop || len != 16) {
385 		EMSG("Missing or invalid UUID in SP manifest");
386 		return TEE_ERROR_BAD_FORMAT;
387 	}
388 
389 	for (i = 0; i < 4; i++)
390 		uuid_array[i] = fdt32_to_cpu(prop[i]);
391 	tee_uuid_from_octets(&fdt_uuid, (uint8_t *)uuid_array);
392 
393 	if (memcmp(uuid, &fdt_uuid, sizeof(fdt_uuid))) {
394 		EMSG("Failed loading SP, UUID mismatch");
395 		return TEE_ERROR_BAD_FORMAT;
396 	}
397 
398 	return TEE_SUCCESS;
399 }
400 
401 /*
402  * sp_init_info allocates and maps the sp_ffa_init_info for the SP. It will copy
403  * the fdt into the allocated page(s) and return a pointer to the new location
404  * of the fdt. This pointer can be used to update data inside the fdt.
405  */
406 static TEE_Result sp_init_info(struct sp_ctx *ctx, struct thread_smc_args *args,
407 			       const void * const input_fdt, vaddr_t *va,
408 			       size_t *num_pgs, void **fdt_copy)
409 {
410 	struct sp_ffa_init_info *info = NULL;
411 	int nvp_count = 1;
412 	size_t nvp_size = sizeof(struct sp_name_value_pair) * nvp_count;
413 	size_t info_size = sizeof(*info) + nvp_size;
414 	size_t fdt_size = fdt_totalsize(input_fdt);
415 	TEE_Result res = TEE_SUCCESS;
416 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
417 	struct fobj *f = NULL;
418 	struct mobj *m = NULL;
419 	static const char fdt_name[16] = "TYPE_DT\0\0\0\0\0\0\0\0";
420 
421 	*num_pgs = ROUNDUP(fdt_size + info_size, SMALL_PAGE_SIZE) /
422 		   SMALL_PAGE_SIZE;
423 
424 	f = fobj_sec_mem_alloc(*num_pgs);
425 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
426 
427 	fobj_put(f);
428 	if (!m)
429 		return TEE_ERROR_OUT_OF_MEMORY;
430 
431 	res = vm_map(&ctx->uctx, va, fdt_size + info_size,
432 		     perm, 0, m, 0);
433 	mobj_put(m);
434 	if (res)
435 		return res;
436 
437 	info = (struct sp_ffa_init_info *)*va;
438 
439 	/* magic field is 4 bytes, we don't copy /0 byte. */
440 	memcpy(&info->magic, "FF-A", 4);
441 	info->count = nvp_count;
442 	args->a0 = (vaddr_t)info;
443 
444 	/*
445 	 * Store the fdt after the boot_info and store the pointer in the
446 	 * first element.
447 	 */
448 	COMPILE_TIME_ASSERT(sizeof(info->nvp[0].name) == sizeof(fdt_name));
449 	memcpy(info->nvp[0].name, fdt_name, sizeof(fdt_name));
450 	info->nvp[0].value = *va + info_size;
451 	info->nvp[0].size = fdt_size;
452 	memcpy((void *)info->nvp[0].value, input_fdt, fdt_size);
453 	*fdt_copy = (void *)info->nvp[0].value;
454 
455 	return TEE_SUCCESS;
456 }
457 
458 static TEE_Result handle_fdt_dev_regions(struct sp_ctx *ctx, void *fdt)
459 {
460 	int node = 0;
461 	int subnode = 0;
462 	TEE_Result res = TEE_SUCCESS;
463 	const char *dt_device_match_table = {
464 		"arm,ffa-manifest-device-regions",
465 	};
466 
467 	/*
468 	 * Device regions are optional in the SP manifest, it's not an error if
469 	 * we don't find any
470 	 */
471 	node = fdt_node_offset_by_compatible(fdt, 0, dt_device_match_table);
472 	if (node < 0)
473 		return TEE_SUCCESS;
474 
475 	fdt_for_each_subnode(subnode, fdt, node) {
476 		uint64_t base_addr = 0;
477 		uint32_t pages_cnt = 0;
478 		uint32_t attributes = 0;
479 		struct mobj *m = NULL;
480 		bool is_secure = true;
481 		uint32_t perm = 0;
482 		vaddr_t va = 0;
483 		unsigned int idx = 0;
484 
485 		/*
486 		 * Physical base address of a device MMIO region.
487 		 * Currently only physically contiguous region is supported.
488 		 */
489 		if (sp_dt_get_u64(fdt, subnode, "base-address", &base_addr)) {
490 			EMSG("Mandatory field is missing: base-address");
491 			return TEE_ERROR_BAD_FORMAT;
492 		}
493 
494 		/* Total size of MMIO region as count of 4K pages */
495 		if (sp_dt_get_u32(fdt, subnode, "pages-count", &pages_cnt)) {
496 			EMSG("Mandatory field is missing: pages-count");
497 			return TEE_ERROR_BAD_FORMAT;
498 		}
499 
500 		/* Data access, instruction access and security attributes */
501 		if (sp_dt_get_u32(fdt, subnode, "attributes", &attributes)) {
502 			EMSG("Mandatory field is missing: attributes");
503 			return TEE_ERROR_BAD_FORMAT;
504 		}
505 
506 		/* Instruction access permission must be not executable */
507 		if (attributes & SP_MANIFEST_ATTR_EXEC) {
508 			EMSG("Invalid instruction access permission");
509 			return TEE_ERROR_BAD_FORMAT;
510 		}
511 
512 		/* Data access permission must be read-only or read/write */
513 		if (attributes & SP_MANIFEST_ATTR_READ) {
514 			perm = TEE_MATTR_UR;
515 
516 			if (attributes & SP_MANIFEST_ATTR_WRITE)
517 				perm |= TEE_MATTR_UW;
518 		} else {
519 			EMSG("Invalid data access permissions");
520 			return TEE_ERROR_BAD_FORMAT;
521 		}
522 
523 		/*
524 		 * The SP is a secure endpoint, security attribute can be
525 		 * secure or non-secure
526 		 */
527 		if (attributes & SP_MANIFEST_ATTR_NSEC)
528 			is_secure = false;
529 
530 		/* Memory attributes must be Device-nGnRnE */
531 		m = sp_mem_new_mobj(pages_cnt, TEE_MATTR_MEM_TYPE_STRONGLY_O,
532 				    is_secure);
533 		if (!m)
534 			return TEE_ERROR_OUT_OF_MEMORY;
535 
536 		res = sp_mem_add_pages(m, &idx, (paddr_t)base_addr, pages_cnt);
537 		if (res) {
538 			mobj_put(m);
539 			return res;
540 		}
541 
542 		res = vm_map(&ctx->uctx, &va, pages_cnt * SMALL_PAGE_SIZE,
543 			     perm, 0, m, 0);
544 		mobj_put(m);
545 		if (res)
546 			return res;
547 
548 		/*
549 		 * Overwrite the device region's PA in the fdt with the VA. This
550 		 * fdt will be passed to the SP.
551 		 */
552 		res = fdt_setprop_u64(fdt, subnode, "base-address", va);
553 
554 		/*
555 		 * Unmap the region if the overwrite failed since the SP won't
556 		 * be able to access it without knowing the VA.
557 		 */
558 		if (res) {
559 			vm_unmap(&ctx->uctx, va, pages_cnt * SMALL_PAGE_SIZE);
560 			return res;
561 		}
562 	}
563 
564 	return TEE_SUCCESS;
565 }
566 
567 static TEE_Result handle_tpm_event_log(struct sp_ctx *ctx, void *fdt)
568 {
569 	uint32_t perm = TEE_MATTR_URW | TEE_MATTR_PRW;
570 	uint32_t dummy_size __maybe_unused = 0;
571 	TEE_Result res = TEE_SUCCESS;
572 	size_t page_count = 0;
573 	struct fobj *f = NULL;
574 	struct mobj *m = NULL;
575 	vaddr_t log_addr = 0;
576 	size_t log_size = 0;
577 	int node = 0;
578 
579 	node = fdt_node_offset_by_compatible(fdt, 0, "arm,tpm_event_log");
580 	if (node < 0)
581 		return TEE_SUCCESS;
582 
583 	/* Checking the existence and size of the event log properties */
584 	if (sp_dt_get_u64(fdt, node, "tpm_event_log_addr", &log_addr)) {
585 		EMSG("tpm_event_log_addr not found or has invalid size");
586 		return TEE_ERROR_BAD_FORMAT;
587 	}
588 
589 	if (sp_dt_get_u32(fdt, node, "tpm_event_log_size", &dummy_size)) {
590 		EMSG("tpm_event_log_size not found or has invalid size");
591 		return TEE_ERROR_BAD_FORMAT;
592 	}
593 
594 	/* Validating event log */
595 	res = tpm_get_event_log_size(&log_size);
596 	if (res)
597 		return res;
598 
599 	if (!log_size) {
600 		EMSG("Empty TPM event log was provided");
601 		return TEE_ERROR_ITEM_NOT_FOUND;
602 	}
603 
604 	/* Allocating memory area for the event log to share with the SP */
605 	page_count = ROUNDUP_DIV(log_size, SMALL_PAGE_SIZE);
606 
607 	f = fobj_sec_mem_alloc(page_count);
608 	m = mobj_with_fobj_alloc(f, NULL, TEE_MATTR_MEM_TYPE_TAGGED);
609 	fobj_put(f);
610 	if (!m)
611 		return TEE_ERROR_OUT_OF_MEMORY;
612 
613 	res = vm_map(&ctx->uctx, &log_addr, log_size, perm, 0, m, 0);
614 	mobj_put(m);
615 	if (res)
616 		return res;
617 
618 	/* Copy event log */
619 	res = tpm_get_event_log((void *)log_addr, &log_size);
620 	if (res)
621 		goto err_unmap;
622 
623 	/* Setting event log details in the manifest */
624 	res = fdt_setprop_u64(fdt, node, "tpm_event_log_addr", log_addr);
625 	if (res)
626 		goto err_unmap;
627 
628 	res = fdt_setprop_u32(fdt, node, "tpm_event_log_size", log_size);
629 	if (res)
630 		goto err_unmap;
631 
632 	return TEE_SUCCESS;
633 
634 err_unmap:
635 	vm_unmap(&ctx->uctx, log_addr, log_size);
636 
637 	return res;
638 }
639 
640 static TEE_Result sp_init_uuid(const TEE_UUID *uuid, const void * const fdt)
641 {
642 	TEE_Result res = TEE_SUCCESS;
643 	struct sp_session *sess = NULL;
644 	struct thread_smc_args args = { };
645 	vaddr_t va = 0;
646 	size_t num_pgs = 0;
647 	struct sp_ctx *ctx = NULL;
648 	void *fdt_copy = NULL;
649 
650 	res = sp_open_session(&sess,
651 			      &open_sp_sessions,
652 			      uuid);
653 	if (res)
654 		return res;
655 
656 	res = check_fdt(fdt, uuid);
657 	if (res)
658 		return res;
659 
660 	ctx = to_sp_ctx(sess->ts_sess.ctx);
661 	ts_push_current_session(&sess->ts_sess);
662 
663 	res = sp_init_info(ctx, &args, fdt, &va, &num_pgs, &fdt_copy);
664 	if (res)
665 		goto out;
666 
667 	res = handle_fdt_dev_regions(ctx, fdt_copy);
668 	if (res)
669 		goto out;
670 
671 	if (IS_ENABLED(CFG_CORE_TPM_EVENT_LOG)) {
672 		res = handle_tpm_event_log(ctx, fdt_copy);
673 		if (res)
674 			goto out;
675 	}
676 
677 	ts_pop_current_session();
678 
679 	if (sp_enter(&args, sess)) {
680 		vm_unmap(&ctx->uctx, va, num_pgs);
681 		return FFA_ABORTED;
682 	}
683 
684 	spmc_sp_msg_handler(&args, sess);
685 
686 	ts_push_current_session(&sess->ts_sess);
687 out:
688 	/* Free the boot info page from the SP memory */
689 	vm_unmap(&ctx->uctx, va, num_pgs);
690 	ts_pop_current_session();
691 
692 	return res;
693 }
694 
695 TEE_Result sp_enter(struct thread_smc_args *args, struct sp_session *sp)
696 {
697 	TEE_Result res = FFA_OK;
698 	struct sp_ctx *ctx = to_sp_ctx(sp->ts_sess.ctx);
699 
700 	ctx->sp_regs.x[0] = args->a0;
701 	ctx->sp_regs.x[1] = args->a1;
702 	ctx->sp_regs.x[2] = args->a2;
703 	ctx->sp_regs.x[3] = args->a3;
704 	ctx->sp_regs.x[4] = args->a4;
705 	ctx->sp_regs.x[5] = args->a5;
706 	ctx->sp_regs.x[6] = args->a6;
707 	ctx->sp_regs.x[7] = args->a7;
708 
709 	res = sp->ts_sess.ctx->ops->enter_invoke_cmd(&sp->ts_sess, 0);
710 
711 	args->a0 = ctx->sp_regs.x[0];
712 	args->a1 = ctx->sp_regs.x[1];
713 	args->a2 = ctx->sp_regs.x[2];
714 	args->a3 = ctx->sp_regs.x[3];
715 	args->a4 = ctx->sp_regs.x[4];
716 	args->a5 = ctx->sp_regs.x[5];
717 	args->a6 = ctx->sp_regs.x[6];
718 	args->a7 = ctx->sp_regs.x[7];
719 
720 	return res;
721 }
722 
723 static TEE_Result sp_enter_invoke_cmd(struct ts_session *s,
724 				      uint32_t cmd __unused)
725 {
726 	struct sp_ctx *ctx = to_sp_ctx(s->ctx);
727 	TEE_Result res = TEE_SUCCESS;
728 	uint32_t exceptions = 0;
729 	uint64_t cpsr = 0;
730 	struct sp_session *sp_s = to_sp_session(s);
731 	struct ts_session *sess = NULL;
732 	struct thread_ctx_regs *sp_regs = NULL;
733 	uint32_t panicked = false;
734 	uint32_t panic_code = 0;
735 
736 	bm_timestamp();
737 
738 	sp_regs = &ctx->sp_regs;
739 	ts_push_current_session(s);
740 
741 	cpsr = sp_regs->cpsr;
742 	sp_regs->cpsr = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
743 
744 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
745 	__thread_enter_user_mode(sp_regs, &panicked, &panic_code);
746 	sp_regs->cpsr = cpsr;
747 	thread_unmask_exceptions(exceptions);
748 
749 	thread_user_clear_vfp(&ctx->uctx);
750 
751 	if (panicked) {
752 		DMSG("SP panicked with code  %#"PRIx32, panic_code);
753 		abort_print_current_ts();
754 
755 		sess = ts_pop_current_session();
756 		cpu_spin_lock(&sp_s->spinlock);
757 		sp_s->state = sp_dead;
758 		cpu_spin_unlock(&sp_s->spinlock);
759 
760 		return TEE_ERROR_TARGET_DEAD;
761 	}
762 
763 	sess = ts_pop_current_session();
764 	assert(sess == s);
765 
766 	bm_timestamp();
767 
768 	return res;
769 }
770 
771 /* We currently don't support 32 bits */
772 #ifdef ARM64
773 static void sp_svc_store_registers(struct thread_svc_regs *regs,
774 				   struct thread_ctx_regs *sp_regs)
775 {
776 	COMPILE_TIME_ASSERT(sizeof(sp_regs->x[0]) == sizeof(regs->x0));
777 	memcpy(sp_regs->x, &regs->x0, 31 * sizeof(regs->x0));
778 	sp_regs->pc = regs->elr;
779 	sp_regs->sp = regs->sp_el0;
780 }
781 #endif
782 
783 static bool sp_handle_svc(struct thread_svc_regs *regs)
784 {
785 	struct ts_session *ts = ts_get_current_session();
786 	struct sp_ctx *uctx = to_sp_ctx(ts->ctx);
787 	struct sp_session *s = uctx->open_session;
788 
789 	assert(s);
790 
791 	sp_svc_store_registers(regs, &uctx->sp_regs);
792 
793 	regs->x0 = 0;
794 	regs->x1 = 0; /* panic */
795 	regs->x2 = 0; /* panic code */
796 
797 	/*
798 	 * All the registers of the SP are saved in the SP session by the SVC
799 	 * handler.
800 	 * We always return to S-El1 after handling the SVC. We will continue
801 	 * in sp_enter_invoke_cmd() (return from __thread_enter_user_mode).
802 	 * The sp_enter() function copies the FF-A parameters (a0-a7) from the
803 	 * saved registers to the thread_smc_args. The thread_smc_args object is
804 	 * afterward used by the spmc_sp_msg_handler() to handle the
805 	 * FF-A message send by the SP.
806 	 */
807 	return false;
808 }
809 
810 static void sp_dump_state(struct ts_ctx *ctx)
811 {
812 	struct sp_ctx *utc = to_sp_ctx(ctx);
813 
814 	if (utc->uctx.dump_entry_func) {
815 		TEE_Result res = ldelf_dump_state(&utc->uctx);
816 
817 		if (!res || res == TEE_ERROR_TARGET_DEAD)
818 			return;
819 	}
820 
821 	user_mode_ctx_print_mappings(&utc->uctx);
822 }
823 
824 /*
825  * Note: this variable is weak just to ease breaking its dependency chain
826  * when added to the unpaged area.
827  */
828 const struct ts_ops sp_ops __weak __relrodata_unpaged("sp_ops") = {
829 	.enter_invoke_cmd = sp_enter_invoke_cmd,
830 	.handle_svc = sp_handle_svc,
831 	.dump_state = sp_dump_state,
832 };
833 
834 static TEE_Result sp_init_all(void)
835 {
836 	TEE_Result res = TEE_SUCCESS;
837 	const struct sp_image *sp = NULL;
838 	char __maybe_unused msg[60] = { '\0', };
839 
840 	for_each_secure_partition(sp) {
841 		if (sp->image.uncompressed_size)
842 			snprintf(msg, sizeof(msg),
843 				 " (compressed, uncompressed %u)",
844 				 sp->image.uncompressed_size);
845 		else
846 			msg[0] = '\0';
847 		DMSG("SP %pUl size %u%s", (void *)&sp->image.uuid,
848 		     sp->image.size, msg);
849 
850 		res = sp_init_uuid(&sp->image.uuid, sp->fdt);
851 
852 		if (res != TEE_SUCCESS) {
853 			EMSG("Failed initializing SP(%pUl) err:%#"PRIx32,
854 			     &sp->image.uuid, res);
855 			if (!IS_ENABLED(CFG_SP_SKIP_FAILED))
856 				panic();
857 		}
858 	}
859 
860 	return TEE_SUCCESS;
861 }
862 
863 boot_final(sp_init_all);
864 
865 static TEE_Result secure_partition_open(const TEE_UUID *uuid,
866 					struct ts_store_handle **h)
867 {
868 	return emb_ts_open(uuid, h, find_secure_partition);
869 }
870 
871 REGISTER_SP_STORE(2) = {
872 	.description = "SP store",
873 	.open = secure_partition_open,
874 	.get_size = emb_ts_get_size,
875 	.get_tag = emb_ts_get_tag,
876 	.read = emb_ts_read,
877 	.close = emb_ts_close,
878 };
879