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