xref: /rk3399_ARM-atf/services/spd/opteed/opteed_main.c (revision 1b491eead580d7849a45a38f2c6a935a5d8d1160)
1 /*
2  * Copyright (c) 2013-2023, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 
8 /*******************************************************************************
9  * This is the Secure Payload Dispatcher (SPD). The dispatcher is meant to be a
10  * plug-in component to the Secure Monitor, registered as a runtime service. The
11  * SPD is expected to be a functional extension of the Secure Payload (SP) that
12  * executes in Secure EL1. The Secure Monitor will delegate all SMCs targeting
13  * the Trusted OS/Applications range to the dispatcher. The SPD will either
14  * handle the request locally or delegate it to the Secure Payload. It is also
15  * responsible for initialising and maintaining communication with the SP.
16  ******************************************************************************/
17 #include <assert.h>
18 #include <errno.h>
19 #include <inttypes.h>
20 #include <stddef.h>
21 
22 #include <arch_helpers.h>
23 #include <bl31/bl31.h>
24 #include <common/bl_common.h>
25 #include <common/debug.h>
26 #include <common/runtime_svc.h>
27 #include <lib/el3_runtime/context_mgmt.h>
28 #include <lib/optee_utils.h>
29 #include <lib/xlat_tables/xlat_tables_v2.h>
30 #include <plat/common/platform.h>
31 #include <tools_share/uuid.h>
32 
33 #include "opteed_private.h"
34 #include "teesmc_opteed.h"
35 
36 /*******************************************************************************
37  * Address of the entrypoint vector table in OPTEE. It is
38  * initialised once on the primary core after a cold boot.
39  ******************************************************************************/
40 struct optee_vectors *optee_vector_table;
41 
42 /*******************************************************************************
43  * Array to keep track of per-cpu OPTEE state
44  ******************************************************************************/
45 optee_context_t opteed_sp_context[OPTEED_CORE_COUNT];
46 uint32_t opteed_rw;
47 
48 #if OPTEE_ALLOW_SMC_LOAD
49 static bool opteed_allow_load;
50 /* OP-TEE image loading service UUID */
51 DEFINE_SVC_UUID2(optee_image_load_uuid,
52 	0xb1eafba3, 0x5d31, 0x4612, 0xb9, 0x06,
53 	0xc4, 0xc7, 0xa4, 0xbe, 0x3c, 0xc0);
54 #else
55 static int32_t opteed_init(void);
56 #endif
57 
58 uint64_t dual32to64(uint32_t high, uint32_t low)
59 {
60 	return ((uint64_t)high << 32) | low;
61 }
62 
63 /*******************************************************************************
64  * This function is the handler registered for S-EL1 interrupts by the
65  * OPTEED. It validates the interrupt and upon success arranges entry into
66  * the OPTEE at 'optee_fiq_entry()' for handling the interrupt.
67  ******************************************************************************/
68 static uint64_t opteed_sel1_interrupt_handler(uint32_t id,
69 					    uint32_t flags,
70 					    void *handle,
71 					    void *cookie)
72 {
73 	uint32_t linear_id;
74 	optee_context_t *optee_ctx;
75 
76 	/* Check the security state when the exception was generated */
77 	assert(get_interrupt_src_ss(flags) == NON_SECURE);
78 
79 	/* Sanity check the pointer to this cpu's context */
80 	assert(handle == cm_get_context(NON_SECURE));
81 
82 	/* Save the non-secure context before entering the OPTEE */
83 	cm_el1_sysregs_context_save(NON_SECURE);
84 
85 	/* Get a reference to this cpu's OPTEE context */
86 	linear_id = plat_my_core_pos();
87 	optee_ctx = &opteed_sp_context[linear_id];
88 	assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
89 
90 	cm_set_elr_el3(SECURE, (uint64_t)&optee_vector_table->fiq_entry);
91 	cm_el1_sysregs_context_restore(SECURE);
92 	cm_set_next_eret_context(SECURE);
93 
94 	/*
95 	 * Tell the OPTEE that it has to handle an FIQ (synchronously).
96 	 * Also the instruction in normal world where the interrupt was
97 	 * generated is passed for debugging purposes. It is safe to
98 	 * retrieve this address from ELR_EL3 as the secure context will
99 	 * not take effect until el3_exit().
100 	 */
101 	SMC_RET1(&optee_ctx->cpu_ctx, read_elr_el3());
102 }
103 
104 /*******************************************************************************
105  * OPTEE Dispatcher setup. The OPTEED finds out the OPTEE entrypoint and type
106  * (aarch32/aarch64) if not already known and initialises the context for entry
107  * into OPTEE for its initialization.
108  ******************************************************************************/
109 static int32_t opteed_setup(void)
110 {
111 #if OPTEE_ALLOW_SMC_LOAD
112 	opteed_allow_load = true;
113 	INFO("Delaying OP-TEE setup until we receive an SMC call to load it\n");
114 	return 0;
115 #else
116 	entry_point_info_t *optee_ep_info;
117 	uint32_t linear_id;
118 	uint64_t opteed_pageable_part;
119 	uint64_t opteed_mem_limit;
120 	uint64_t dt_addr;
121 
122 	linear_id = plat_my_core_pos();
123 
124 	/*
125 	 * Get information about the Secure Payload (BL32) image. Its
126 	 * absence is a critical failure.  TODO: Add support to
127 	 * conditionally include the SPD service
128 	 */
129 	optee_ep_info = bl31_plat_get_next_image_ep_info(SECURE);
130 	if (!optee_ep_info) {
131 		WARN("No OPTEE provided by BL2 boot loader, Booting device"
132 			" without OPTEE initialization. SMC`s destined for OPTEE"
133 			" will return SMC_UNK\n");
134 		return 1;
135 	}
136 
137 	/*
138 	 * If there's no valid entry point for SP, we return a non-zero value
139 	 * signalling failure initializing the service. We bail out without
140 	 * registering any handlers
141 	 */
142 	if (!optee_ep_info->pc)
143 		return 1;
144 
145 	opteed_rw = optee_ep_info->args.arg0;
146 	opteed_pageable_part = optee_ep_info->args.arg1;
147 	opteed_mem_limit = optee_ep_info->args.arg2;
148 	dt_addr = optee_ep_info->args.arg3;
149 
150 	opteed_init_optee_ep_state(optee_ep_info,
151 				opteed_rw,
152 				optee_ep_info->pc,
153 				opteed_pageable_part,
154 				opteed_mem_limit,
155 				dt_addr,
156 				&opteed_sp_context[linear_id]);
157 
158 	/*
159 	 * All OPTEED initialization done. Now register our init function with
160 	 * BL31 for deferred invocation
161 	 */
162 	bl31_register_bl32_init(&opteed_init);
163 
164 	return 0;
165 #endif  /* OPTEE_ALLOW_SMC_LOAD */
166 }
167 
168 /*******************************************************************************
169  * This function passes control to the OPTEE image (BL32) for the first time
170  * on the primary cpu after a cold boot. It assumes that a valid secure
171  * context has already been created by opteed_setup() which can be directly
172  * used.  It also assumes that a valid non-secure context has been
173  * initialised by PSCI so it does not need to save and restore any
174  * non-secure state. This function performs a synchronous entry into
175  * OPTEE. OPTEE passes control back to this routine through a SMC. This returns
176  * a non-zero value on success and zero on failure.
177  ******************************************************************************/
178 static int32_t
179 opteed_init_with_entry_point(entry_point_info_t *optee_entry_point)
180 {
181 	uint32_t linear_id = plat_my_core_pos();
182 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
183 	uint64_t rc;
184 	assert(optee_entry_point);
185 
186 	cm_init_my_context(optee_entry_point);
187 
188 	/*
189 	 * Arrange for an entry into OPTEE. It will be returned via
190 	 * OPTEE_ENTRY_DONE case
191 	 */
192 	rc = opteed_synchronous_sp_entry(optee_ctx);
193 	assert(rc != 0);
194 
195 	return rc;
196 }
197 
198 #if !OPTEE_ALLOW_SMC_LOAD
199 static int32_t opteed_init(void)
200 {
201 	entry_point_info_t *optee_entry_point;
202 	/*
203 	 * Get information about the OP-TEE (BL32) image. Its
204 	 * absence is a critical failure.
205 	 */
206 	optee_entry_point = bl31_plat_get_next_image_ep_info(SECURE);
207 	return opteed_init_with_entry_point(optee_entry_point);
208 }
209 #endif  /* !OPTEE_ALLOW_SMC_LOAD */
210 
211 #if OPTEE_ALLOW_SMC_LOAD
212 /*******************************************************************************
213  * This function is responsible for handling the SMC that loads the OP-TEE
214  * binary image via a non-secure SMC call. It takes the size and physical
215  * address of the payload as parameters.
216  ******************************************************************************/
217 static int32_t opteed_handle_smc_load(uint64_t data_size, uint32_t data_pa)
218 {
219 	uintptr_t data_va = data_pa;
220 	uint64_t mapped_data_pa;
221 	uintptr_t mapped_data_va;
222 	uint64_t data_map_size;
223 	int32_t rc;
224 	optee_header_t *image_header;
225 	uint8_t *image_ptr;
226 	uint64_t target_pa;
227 	uint64_t target_end_pa;
228 	uint64_t image_pa;
229 	uintptr_t image_va;
230 	optee_image_t *curr_image;
231 	uintptr_t target_va;
232 	uint64_t target_size;
233 	entry_point_info_t optee_ep_info;
234 	uint32_t linear_id = plat_my_core_pos();
235 
236 	mapped_data_pa = page_align(data_pa, DOWN);
237 	mapped_data_va = mapped_data_pa;
238 	data_map_size = page_align(data_size + (mapped_data_pa - data_pa), UP);
239 
240 	/*
241 	 * We do not validate the passed in address because we are trusting the
242 	 * non-secure world at this point still.
243 	 */
244 	rc = mmap_add_dynamic_region(mapped_data_pa, mapped_data_va,
245 				     data_map_size, MT_MEMORY | MT_RO | MT_NS);
246 	if (rc != 0) {
247 		return rc;
248 	}
249 
250 	image_header = (optee_header_t *)data_va;
251 	if (image_header->magic != TEE_MAGIC_NUM_OPTEE ||
252 	    image_header->version != 2 || image_header->nb_images != 1) {
253 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
254 		return -EINVAL;
255 	}
256 
257 	image_ptr = (uint8_t *)data_va + sizeof(optee_header_t) +
258 			sizeof(optee_image_t);
259 	if (image_header->arch == 1) {
260 		opteed_rw = OPTEE_AARCH64;
261 	} else {
262 		opteed_rw = OPTEE_AARCH32;
263 	}
264 
265 	curr_image = &image_header->optee_image_list[0];
266 	image_pa = dual32to64(curr_image->load_addr_hi,
267 			      curr_image->load_addr_lo);
268 	image_va = image_pa;
269 	target_end_pa = image_pa + curr_image->size;
270 
271 	/* Now also map the memory we want to copy it to. */
272 	target_pa = page_align(image_pa, DOWN);
273 	target_va = target_pa;
274 	target_size = page_align(target_end_pa, UP) - target_pa;
275 
276 	rc = mmap_add_dynamic_region(target_pa, target_va, target_size,
277 				     MT_MEMORY | MT_RW | MT_SECURE);
278 	if (rc != 0) {
279 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
280 		return rc;
281 	}
282 
283 	INFO("Loaded OP-TEE via SMC: size %d addr 0x%" PRIx64 "\n",
284 	     curr_image->size, image_va);
285 
286 	memcpy((void *)image_va, image_ptr, curr_image->size);
287 	flush_dcache_range(target_pa, target_size);
288 
289 	mmap_remove_dynamic_region(mapped_data_va, data_map_size);
290 	mmap_remove_dynamic_region(target_va, target_size);
291 
292 	/* Save the non-secure state */
293 	cm_el1_sysregs_context_save(NON_SECURE);
294 
295 	opteed_init_optee_ep_state(&optee_ep_info,
296 				   opteed_rw,
297 				   image_pa,
298 				   0,
299 				   0,
300 				   0,
301 				   &opteed_sp_context[linear_id]);
302 	if (opteed_init_with_entry_point(&optee_ep_info) == 0) {
303 		rc = -EFAULT;
304 	}
305 
306 	/* Restore non-secure state */
307 	cm_el1_sysregs_context_restore(NON_SECURE);
308 	cm_set_next_eret_context(NON_SECURE);
309 
310 	return rc;
311 }
312 #endif  /* OPTEE_ALLOW_SMC_LOAD */
313 
314 /*******************************************************************************
315  * This function is responsible for handling all SMCs in the Trusted OS/App
316  * range from the non-secure state as defined in the SMC Calling Convention
317  * Document. It is also responsible for communicating with the Secure
318  * payload to delegate work and return results back to the non-secure
319  * state. Lastly it will also return any information that OPTEE needs to do
320  * the work assigned to it.
321  ******************************************************************************/
322 static uintptr_t opteed_smc_handler(uint32_t smc_fid,
323 			 u_register_t x1,
324 			 u_register_t x2,
325 			 u_register_t x3,
326 			 u_register_t x4,
327 			 void *cookie,
328 			 void *handle,
329 			 u_register_t flags)
330 {
331 	cpu_context_t *ns_cpu_context;
332 	uint32_t linear_id = plat_my_core_pos();
333 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
334 	uint64_t rc;
335 
336 	/*
337 	 * Determine which security state this SMC originated from
338 	 */
339 
340 	if (is_caller_non_secure(flags)) {
341 #if OPTEE_ALLOW_SMC_LOAD
342 		if (opteed_allow_load && smc_fid == NSSMC_OPTEED_CALL_UID) {
343 			/* Provide the UUID of the image loading service. */
344 			SMC_UUID_RET(handle, optee_image_load_uuid);
345 		}
346 		if (smc_fid == NSSMC_OPTEED_CALL_LOAD_IMAGE) {
347 			/*
348 			 * TODO: Consider wiping the code for SMC loading from
349 			 * memory after it has been invoked similar to what is
350 			 * done under RECLAIM_INIT, but extended to happen
351 			 * later.
352 			 */
353 			if (!opteed_allow_load) {
354 				SMC_RET1(handle, -EPERM);
355 			}
356 
357 			opteed_allow_load = false;
358 			uint64_t data_size = dual32to64(x1, x2);
359 			uint64_t data_pa = dual32to64(x3, x4);
360 			if (!data_size || !data_pa) {
361 				/*
362 				 * This is invoked when the OP-TEE image didn't
363 				 * load correctly in the kernel but we want to
364 				 * block off loading of it later for security
365 				 * reasons.
366 				 */
367 				SMC_RET1(handle, -EINVAL);
368 			}
369 			SMC_RET1(handle, opteed_handle_smc_load(
370 					data_size, data_pa));
371 		}
372 #endif  /* OPTEE_ALLOW_SMC_LOAD */
373 		/*
374 		 * This is a fresh request from the non-secure client.
375 		 * The parameters are in x1 and x2. Figure out which
376 		 * registers need to be preserved, save the non-secure
377 		 * state and send the request to the secure payload.
378 		 */
379 		assert(handle == cm_get_context(NON_SECURE));
380 
381 		cm_el1_sysregs_context_save(NON_SECURE);
382 
383 		/*
384 		 * We are done stashing the non-secure context. Ask the
385 		 * OP-TEE to do the work now. If we are loading vi an SMC,
386 		 * then we also need to init this CPU context if not done
387 		 * already.
388 		 */
389 		if (optee_vector_table == NULL) {
390 			SMC_RET1(handle, -EINVAL);
391 		}
392 
393 		if (get_optee_pstate(optee_ctx->state) ==
394 		    OPTEE_PSTATE_UNKNOWN) {
395 			opteed_cpu_on_finish_handler(0);
396 		}
397 
398 		/*
399 		 * Verify if there is a valid context to use, copy the
400 		 * operation type and parameters to the secure context
401 		 * and jump to the fast smc entry point in the secure
402 		 * payload. Entry into S-EL1 will take place upon exit
403 		 * from this function.
404 		 */
405 		assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
406 
407 		/* Set appropriate entry for SMC.
408 		 * We expect OPTEE to manage the PSTATE.I and PSTATE.F
409 		 * flags as appropriate.
410 		 */
411 		if (GET_SMC_TYPE(smc_fid) == SMC_TYPE_FAST) {
412 			cm_set_elr_el3(SECURE, (uint64_t)
413 					&optee_vector_table->fast_smc_entry);
414 		} else {
415 			cm_set_elr_el3(SECURE, (uint64_t)
416 					&optee_vector_table->yield_smc_entry);
417 		}
418 
419 		cm_el1_sysregs_context_restore(SECURE);
420 		cm_set_next_eret_context(SECURE);
421 
422 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
423 			      CTX_GPREG_X4,
424 			      read_ctx_reg(get_gpregs_ctx(handle),
425 					   CTX_GPREG_X4));
426 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
427 			      CTX_GPREG_X5,
428 			      read_ctx_reg(get_gpregs_ctx(handle),
429 					   CTX_GPREG_X5));
430 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
431 			      CTX_GPREG_X6,
432 			      read_ctx_reg(get_gpregs_ctx(handle),
433 					   CTX_GPREG_X6));
434 		/* Propagate hypervisor client ID */
435 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
436 			      CTX_GPREG_X7,
437 			      read_ctx_reg(get_gpregs_ctx(handle),
438 					   CTX_GPREG_X7));
439 
440 		SMC_RET4(&optee_ctx->cpu_ctx, smc_fid, x1, x2, x3);
441 	}
442 
443 	/*
444 	 * Returning from OPTEE
445 	 */
446 
447 	switch (smc_fid) {
448 	/*
449 	 * OPTEE has finished initialising itself after a cold boot
450 	 */
451 	case TEESMC_OPTEED_RETURN_ENTRY_DONE:
452 		/*
453 		 * Stash the OPTEE entry points information. This is done
454 		 * only once on the primary cpu
455 		 */
456 		assert(optee_vector_table == NULL);
457 		optee_vector_table = (optee_vectors_t *) x1;
458 
459 		if (optee_vector_table) {
460 			set_optee_pstate(optee_ctx->state, OPTEE_PSTATE_ON);
461 
462 			/*
463 			 * OPTEE has been successfully initialized.
464 			 * Register power management hooks with PSCI
465 			 */
466 			psci_register_spd_pm_hook(&opteed_pm);
467 
468 			/*
469 			 * Register an interrupt handler for S-EL1 interrupts
470 			 * when generated during code executing in the
471 			 * non-secure state.
472 			 */
473 			flags = 0;
474 			set_interrupt_rm_flag(flags, NON_SECURE);
475 			rc = register_interrupt_type_handler(INTR_TYPE_S_EL1,
476 						opteed_sel1_interrupt_handler,
477 						flags);
478 			if (rc)
479 				panic();
480 		}
481 
482 		/*
483 		 * OPTEE reports completion. The OPTEED must have initiated
484 		 * the original request through a synchronous entry into
485 		 * OPTEE. Jump back to the original C runtime context.
486 		 */
487 		opteed_synchronous_sp_exit(optee_ctx, x1);
488 		break;
489 
490 
491 	/*
492 	 * These function IDs is used only by OP-TEE to indicate it has
493 	 * finished:
494 	 * 1. turning itself on in response to an earlier psci
495 	 *    cpu_on request
496 	 * 2. resuming itself after an earlier psci cpu_suspend
497 	 *    request.
498 	 */
499 	case TEESMC_OPTEED_RETURN_ON_DONE:
500 	case TEESMC_OPTEED_RETURN_RESUME_DONE:
501 
502 
503 	/*
504 	 * These function IDs is used only by the SP to indicate it has
505 	 * finished:
506 	 * 1. suspending itself after an earlier psci cpu_suspend
507 	 *    request.
508 	 * 2. turning itself off in response to an earlier psci
509 	 *    cpu_off request.
510 	 */
511 	case TEESMC_OPTEED_RETURN_OFF_DONE:
512 	case TEESMC_OPTEED_RETURN_SUSPEND_DONE:
513 	case TEESMC_OPTEED_RETURN_SYSTEM_OFF_DONE:
514 	case TEESMC_OPTEED_RETURN_SYSTEM_RESET_DONE:
515 
516 		/*
517 		 * OPTEE reports completion. The OPTEED must have initiated the
518 		 * original request through a synchronous entry into OPTEE.
519 		 * Jump back to the original C runtime context, and pass x1 as
520 		 * return value to the caller
521 		 */
522 		opteed_synchronous_sp_exit(optee_ctx, x1);
523 		break;
524 
525 	/*
526 	 * OPTEE is returning from a call or being preempted from a call, in
527 	 * either case execution should resume in the normal world.
528 	 */
529 	case TEESMC_OPTEED_RETURN_CALL_DONE:
530 		/*
531 		 * This is the result from the secure client of an
532 		 * earlier request. The results are in x0-x3. Copy it
533 		 * into the non-secure context, save the secure state
534 		 * and return to the non-secure state.
535 		 */
536 		assert(handle == cm_get_context(SECURE));
537 		cm_el1_sysregs_context_save(SECURE);
538 
539 		/* Get a reference to the non-secure context */
540 		ns_cpu_context = cm_get_context(NON_SECURE);
541 		assert(ns_cpu_context);
542 
543 		/* Restore non-secure state */
544 		cm_el1_sysregs_context_restore(NON_SECURE);
545 		cm_set_next_eret_context(NON_SECURE);
546 
547 		SMC_RET4(ns_cpu_context, x1, x2, x3, x4);
548 
549 	/*
550 	 * OPTEE has finished handling a S-EL1 FIQ interrupt. Execution
551 	 * should resume in the normal world.
552 	 */
553 	case TEESMC_OPTEED_RETURN_FIQ_DONE:
554 		/* Get a reference to the non-secure context */
555 		ns_cpu_context = cm_get_context(NON_SECURE);
556 		assert(ns_cpu_context);
557 
558 		/*
559 		 * Restore non-secure state. There is no need to save the
560 		 * secure system register context since OPTEE was supposed
561 		 * to preserve it during S-EL1 interrupt handling.
562 		 */
563 		cm_el1_sysregs_context_restore(NON_SECURE);
564 		cm_set_next_eret_context(NON_SECURE);
565 
566 		SMC_RET0((uint64_t) ns_cpu_context);
567 
568 	default:
569 		panic();
570 	}
571 }
572 
573 /* Define an OPTEED runtime service descriptor for fast SMC calls */
574 DECLARE_RT_SVC(
575 	opteed_fast,
576 
577 	OEN_TOS_START,
578 	OEN_TOS_END,
579 	SMC_TYPE_FAST,
580 	opteed_setup,
581 	opteed_smc_handler
582 );
583 
584 /* Define an OPTEED runtime service descriptor for yielding SMC calls */
585 DECLARE_RT_SVC(
586 	opteed_std,
587 
588 	OEN_TOS_START,
589 	OEN_TOS_END,
590 	SMC_TYPE_YIELD,
591 	NULL,
592 	opteed_smc_handler
593 );
594