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/coreboot.h>
28 #include <lib/el3_runtime/context_mgmt.h>
29 #include <lib/optee_utils.h>
30 #include <lib/transfer_list.h>
31 #include <lib/xlat_tables/xlat_tables_v2.h>
32 #if OPTEE_ALLOW_SMC_LOAD
33 #include <libfdt.h>
34 #endif  /* OPTEE_ALLOW_SMC_LOAD */
35 #include <plat/common/platform.h>
36 #include <services/oem/chromeos/widevine_smc_handlers.h>
37 #include <tools_share/uuid.h>
38 
39 #include "opteed_private.h"
40 #include "teesmc_opteed.h"
41 
42 #if OPTEE_ALLOW_SMC_LOAD
43 static struct transfer_list_header *bl31_tl;
44 #endif
45 
46 /*******************************************************************************
47  * Address of the entrypoint vector table in OPTEE. It is
48  * initialised once on the primary core after a cold boot.
49  ******************************************************************************/
50 struct optee_vectors *optee_vector_table;
51 
52 /*******************************************************************************
53  * Array to keep track of per-cpu OPTEE state
54  ******************************************************************************/
55 optee_context_t opteed_sp_context[OPTEED_CORE_COUNT];
56 uint32_t opteed_rw;
57 
58 #if OPTEE_ALLOW_SMC_LOAD
59 static bool opteed_allow_load;
60 /* OP-TEE image loading service UUID */
61 DEFINE_SVC_UUID2(optee_image_load_uuid,
62 	0xb1eafba3, 0x5d31, 0x4612, 0xb9, 0x06,
63 	0xc4, 0xc7, 0xa4, 0xbe, 0x3c, 0xc0);
64 
65 #define OPTEED_FDT_SIZE 1024
66 static uint8_t fdt_buf[OPTEED_FDT_SIZE] __aligned(CACHE_WRITEBACK_GRANULE);
67 
68 #else
69 static int32_t opteed_init(void);
70 #endif
71 
dual32to64(uint32_t high,uint32_t low)72 uint64_t dual32to64(uint32_t high, uint32_t low)
73 {
74 	return ((uint64_t)high << 32) | low;
75 }
76 
77 /*******************************************************************************
78  * This function is the handler registered for S-EL1 interrupts by the
79  * OPTEED. It validates the interrupt and upon success arranges entry into
80  * the OPTEE at 'optee_fiq_entry()' for handling the interrupt.
81  ******************************************************************************/
opteed_sel1_interrupt_handler(uint32_t id,uint32_t flags,void * handle,void * cookie)82 static uint64_t opteed_sel1_interrupt_handler(uint32_t id,
83 					    uint32_t flags,
84 					    void *handle,
85 					    void *cookie)
86 {
87 	uint32_t linear_id;
88 	optee_context_t *optee_ctx;
89 
90 #if OPTEE_ALLOW_SMC_LOAD
91 	if (optee_vector_table == NULL) {
92 		/* OPTEE is not loaded yet, ignore this interrupt */
93 		SMC_RET0(handle);
94 	}
95 #endif
96 
97 	/* Check the security state when the exception was generated */
98 	assert(get_interrupt_src_ss(flags) == NON_SECURE);
99 
100 	/* Sanity check the pointer to this cpu's context */
101 	assert(handle == cm_get_context(NON_SECURE));
102 
103 	/* Save the non-secure context before entering the OPTEE */
104 	cm_el1_sysregs_context_save(NON_SECURE);
105 
106 	/* Get a reference to this cpu's OPTEE context */
107 	linear_id = plat_my_core_pos();
108 	optee_ctx = &opteed_sp_context[linear_id];
109 	assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
110 
111 	cm_set_elr_el3(SECURE, (uint64_t)&optee_vector_table->fiq_entry);
112 	cm_el1_sysregs_context_restore(SECURE);
113 	cm_set_next_eret_context(SECURE);
114 
115 	/*
116 	 * Tell the OPTEE that it has to handle an FIQ (synchronously).
117 	 * Also the instruction in normal world where the interrupt was
118 	 * generated is passed for debugging purposes. It is safe to
119 	 * retrieve this address from ELR_EL3 as the secure context will
120 	 * not take effect until el3_exit().
121 	 */
122 	SMC_RET1(&optee_ctx->cpu_ctx, read_elr_el3());
123 }
124 
125 /*
126  * Registers an interrupt handler for S-EL1 interrupts when generated during
127  * code executing in the non-secure state. Panics if it fails to do so.
128  */
register_opteed_interrupt_handler(void)129 static void register_opteed_interrupt_handler(void)
130 {
131 	u_register_t flags;
132 	uint64_t rc;
133 
134 	flags = 0;
135 	set_interrupt_rm_flag(flags, NON_SECURE);
136 	rc = register_interrupt_type_handler(INTR_TYPE_S_EL1,
137 			opteed_sel1_interrupt_handler,
138 			flags);
139 	if (rc)
140 		panic();
141 }
142 
143 /*******************************************************************************
144  * OPTEE Dispatcher setup. The OPTEED finds out the OPTEE entrypoint and type
145  * (aarch32/aarch64) if not already known and initialises the context for entry
146  * into OPTEE for its initialization.
147  ******************************************************************************/
opteed_setup(void)148 static int32_t opteed_setup(void)
149 {
150 #if OPTEE_ALLOW_SMC_LOAD
151 	opteed_allow_load = true;
152 	INFO("Delaying OP-TEE setup until we receive an SMC call to load it\n");
153 	/*
154 	 * We must register the interrupt handler now so that the interrupt
155 	 * priorities are not changed after starting the linux kernel.
156 	 */
157 	register_opteed_interrupt_handler();
158 	return 0;
159 #else
160 	entry_point_info_t *optee_ep_info;
161 	uint32_t linear_id;
162 	uint64_t arg0;
163 	uint64_t arg1;
164 	uint64_t arg2;
165 	uint64_t arg3;
166 	struct transfer_list_header *tl = NULL;
167 	struct transfer_list_entry *te = NULL;
168 	void *dt = NULL;
169 
170 	linear_id = plat_my_core_pos();
171 
172 	/*
173 	 * Get information about the Secure Payload (BL32) image. Its
174 	 * absence is a critical failure.  TODO: Add support to
175 	 * conditionally include the SPD service
176 	 */
177 	optee_ep_info = bl31_plat_get_next_image_ep_info(SECURE);
178 	if (!optee_ep_info) {
179 		WARN("No OPTEE provided by BL2 boot loader, Booting device"
180 			" without OPTEE initialization. SMC`s destined for OPTEE"
181 			" will return SMC_UNK\n");
182 		return 1;
183 	}
184 
185 	/*
186 	 * If there's no valid entry point for SP, we return a non-zero value
187 	 * signalling failure initializing the service. We bail out without
188 	 * registering any handlers
189 	 */
190 	if (!optee_ep_info->pc)
191 		return 1;
192 
193 	if (TRANSFER_LIST &&
194 		optee_ep_info->args.arg1 == (TRANSFER_LIST_SIGNATURE |
195 					REGISTER_CONVENTION_VERSION_MASK)) {
196 		tl = (void *)optee_ep_info->args.arg3;
197 		if (transfer_list_check_header(tl) == TL_OPS_NON) {
198 			return 1;
199 		}
200 
201 		opteed_rw = GET_RW(optee_ep_info->spsr);
202 		te = transfer_list_find(tl, TL_TAG_FDT);
203 		dt = transfer_list_entry_data(te);
204 
205 		if (opteed_rw == OPTEE_AARCH64) {
206 			arg0 = (uint64_t)dt;
207 			arg2 = 0;
208 		} else {
209 			arg2 = (uint64_t)dt;
210 			arg0 = 0;
211 		}
212 
213 		arg1 = optee_ep_info->args.arg1;
214 		arg3 = optee_ep_info->args.arg3;
215 	} else {
216 		/* Default handoff arguments */
217 		opteed_rw = optee_ep_info->args.arg0;
218 		arg0 = optee_ep_info->args.arg1; /* opteed_pageable_part */
219 		arg1 = optee_ep_info->args.arg2; /* opteed_mem_limit */
220 		arg2 = optee_ep_info->args.arg3; /* dt_addr */
221 		arg3 = 0;
222 	}
223 
224 	opteed_init_optee_ep_state(optee_ep_info, opteed_rw, optee_ep_info->pc,
225 				arg0, arg1, arg2, arg3,
226 				&opteed_sp_context[linear_id]);
227 
228 	/*
229 	 * All OPTEED initialization done. Now register our init function with
230 	 * BL31 for deferred invocation
231 	 */
232 	bl31_register_bl32_init(&opteed_init);
233 
234 	return 0;
235 #endif  /* OPTEE_ALLOW_SMC_LOAD */
236 }
237 
238 /*******************************************************************************
239  * This function passes control to the OPTEE image (BL32) for the first time
240  * on the primary cpu after a cold boot. It assumes that a valid secure
241  * context has already been created by opteed_setup() which can be directly
242  * used.  It also assumes that a valid non-secure context has been
243  * initialised by PSCI so it does not need to save and restore any
244  * non-secure state. This function performs a synchronous entry into
245  * OPTEE. OPTEE passes control back to this routine through a SMC. This returns
246  * a non-zero value on success and zero on failure.
247  ******************************************************************************/
248 static int32_t
opteed_init_with_entry_point(entry_point_info_t * optee_entry_point)249 opteed_init_with_entry_point(entry_point_info_t *optee_entry_point)
250 {
251 	uint32_t linear_id = plat_my_core_pos();
252 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
253 	uint64_t rc;
254 	assert(optee_entry_point);
255 
256 	cm_init_my_context(optee_entry_point);
257 
258 	/*
259 	 * Arrange for an entry into OPTEE. It will be returned via
260 	 * OPTEE_ENTRY_DONE case
261 	 */
262 	rc = opteed_synchronous_sp_entry(optee_ctx);
263 	assert(rc != 0);
264 
265 	return rc;
266 }
267 
268 #if !OPTEE_ALLOW_SMC_LOAD
opteed_init(void)269 static int32_t opteed_init(void)
270 {
271 	entry_point_info_t *optee_entry_point;
272 	/*
273 	 * Get information about the OP-TEE (BL32) image. Its
274 	 * absence is a critical failure.
275 	 */
276 	optee_entry_point = bl31_plat_get_next_image_ep_info(SECURE);
277 	return opteed_init_with_entry_point(optee_entry_point);
278 }
279 #endif  /* !OPTEE_ALLOW_SMC_LOAD */
280 
281 #if OPTEE_ALLOW_SMC_LOAD
282 #if COREBOOT
283 /*
284  * Adds a firmware/coreboot node with the coreboot table information to a device
285  * tree. Returns zero on success or if there is no coreboot table information;
286  * failure code otherwise.
287  */
add_coreboot_node(void * fdt)288 static int add_coreboot_node(void *fdt)
289 {
290 	int ret;
291 	uint64_t coreboot_table_addr;
292 	uint32_t coreboot_table_size;
293 	struct {
294 		uint64_t addr;
295 		uint32_t size;
296 	} reg_node;
297 	coreboot_get_table_location(&coreboot_table_addr, &coreboot_table_size);
298 	if (!coreboot_table_addr || !coreboot_table_size) {
299 		WARN("Unable to get coreboot table location for device tree");
300 		return 0;
301 	}
302 	ret = fdt_begin_node(fdt, "firmware");
303 	if (ret)
304 		return ret;
305 
306 	ret = fdt_property(fdt, "ranges", NULL, 0);
307 	if (ret)
308 		return ret;
309 
310 	ret = fdt_begin_node(fdt, "coreboot");
311 	if (ret)
312 		return ret;
313 
314 	ret = fdt_property_string(fdt, "compatible", "coreboot");
315 	if (ret)
316 		return ret;
317 
318 	reg_node.addr = cpu_to_fdt64(coreboot_table_addr);
319 	reg_node.size = cpu_to_fdt32(coreboot_table_size);
320 	ret = fdt_property(fdt, "reg", &reg_node,
321 				sizeof(uint64_t) + sizeof(uint32_t));
322 	if (ret)
323 		return ret;
324 
325 	ret = fdt_end_node(fdt);
326 	if (ret)
327 		return ret;
328 
329 	return fdt_end_node(fdt);
330 }
331 #endif /* COREBOOT */
332 
333 #if CROS_WIDEVINE_SMC
334 /*
335  * Adds a options/widevine node with the widevine table information to a device
336  * tree. Returns zero on success or if there is no widevine table information;
337  * failure code otherwise.
338  */
add_options_widevine_node(void * fdt)339 static int add_options_widevine_node(void *fdt)
340 {
341 	int ret;
342 
343 	ret = fdt_begin_node(fdt, "options");
344 	if (ret)
345 		return ret;
346 
347 	ret = fdt_begin_node(fdt, "op-tee");
348 	if (ret)
349 		return ret;
350 
351 	ret = fdt_begin_node(fdt, "widevine");
352 	if (ret)
353 		return ret;
354 
355 	if (cros_oem_tpm_auth_pk.length) {
356 		ret = fdt_property(fdt, "tcg,tpm-auth-public-key",
357 				   cros_oem_tpm_auth_pk.buffer,
358 				   cros_oem_tpm_auth_pk.length);
359 		if (ret)
360 			return ret;
361 	}
362 
363 	if (cros_oem_huk.length) {
364 		ret = fdt_property(fdt, "op-tee,hardware-unique-key",
365 				   cros_oem_huk.buffer, cros_oem_huk.length);
366 		if (ret)
367 			return ret;
368 	}
369 
370 	if (cros_oem_rot.length) {
371 		ret = fdt_property(fdt, "google,widevine-root-of-trust-ecc-p256",
372 				   cros_oem_rot.buffer, cros_oem_rot.length);
373 		if (ret)
374 			return ret;
375 	}
376 
377 	ret = fdt_end_node(fdt);
378 	if (ret)
379 		return ret;
380 
381 	ret = fdt_end_node(fdt);
382 	if (ret)
383 		return ret;
384 
385 	return fdt_end_node(fdt);
386 }
387 #endif /* CROS_WIDEVINE_SMC */
388 
389 /*
390  * Creates a device tree for passing into OP-TEE. Currently is populated with
391  * the coreboot table address.
392  * Returns 0 on success, error code otherwise.
393  */
create_opteed_dt(void)394 static int create_opteed_dt(void)
395 {
396 	int ret;
397 
398 	ret = fdt_create(fdt_buf, OPTEED_FDT_SIZE);
399 	if (ret)
400 		return ret;
401 
402 	ret = fdt_finish_reservemap(fdt_buf);
403 	if (ret)
404 		return ret;
405 
406 	ret = fdt_begin_node(fdt_buf, "");
407 	if (ret)
408 		return ret;
409 
410 #if COREBOOT
411 	ret = add_coreboot_node(fdt_buf);
412 	if (ret)
413 		return ret;
414 #endif /* COREBOOT */
415 
416 #if CROS_WIDEVINE_SMC
417 	ret = add_options_widevine_node(fdt_buf);
418 	if (ret)
419 		return ret;
420 #endif /* CROS_WIDEVINE_SMC */
421 
422 	ret = fdt_end_node(fdt_buf);
423 	if (ret)
424 		return ret;
425 
426 	return fdt_finish(fdt_buf);
427 }
428 
create_smc_tl(const void * fdt,uint32_t fdt_sz)429 static int32_t create_smc_tl(const void *fdt, uint32_t fdt_sz)
430 {
431 #if TRANSFER_LIST
432 	bl31_tl = transfer_list_init((void *)(uintptr_t)FW_HANDOFF_BASE,
433 				FW_HANDOFF_SIZE);
434 	if (!bl31_tl) {
435 		ERROR("Failed to initialize Transfer List at 0x%lx\n",
436 		(unsigned long)FW_HANDOFF_BASE);
437 		return -1;
438 	}
439 
440 	if (!transfer_list_add(bl31_tl, TL_TAG_FDT, fdt_sz, fdt)) {
441 		return -1;
442 	}
443 	return 0;
444 #else
445 	return -1;
446 #endif
447 }
448 
449 /*******************************************************************************
450  * This function is responsible for handling the SMC that loads the OP-TEE
451  * binary image via a non-secure SMC call. It takes the size and physical
452  * address of the payload as parameters.
453  ******************************************************************************/
opteed_handle_smc_load(uint64_t data_size,uint32_t data_pa)454 static int32_t opteed_handle_smc_load(uint64_t data_size, uint32_t data_pa)
455 {
456 	uintptr_t data_va = data_pa;
457 	uint64_t mapped_data_pa;
458 	uintptr_t mapped_data_va;
459 	uint64_t data_map_size;
460 	int32_t rc;
461 	optee_header_t *image_header;
462 	uint8_t *image_ptr;
463 	uint64_t target_pa;
464 	uint64_t target_end_pa;
465 	uint64_t image_pa;
466 	uintptr_t image_va;
467 	optee_image_t *curr_image;
468 	uintptr_t target_va;
469 	uint64_t target_size;
470 	entry_point_info_t optee_ep_info;
471 	uint32_t linear_id = plat_my_core_pos();
472 	uint64_t dt_addr = 0;
473 	uint64_t arg0 = 0;
474 	uint64_t arg1 = 0;
475 	uint64_t arg2 = 0;
476 	uint64_t arg3 = 0;
477 
478 	mapped_data_pa = page_align(data_pa, DOWN);
479 	mapped_data_va = mapped_data_pa;
480 	data_map_size = page_align(data_size + (mapped_data_pa - data_pa), UP);
481 
482 	/*
483 	 * We do not validate the passed in address because we are trusting the
484 	 * non-secure world at this point still.
485 	 */
486 	rc = mmap_add_dynamic_region(mapped_data_pa, mapped_data_va,
487 				     data_map_size, MT_MEMORY | MT_RO | MT_NS);
488 	if (rc != 0) {
489 		return rc;
490 	}
491 
492 	image_header = (optee_header_t *)data_va;
493 	if (image_header->magic != TEE_MAGIC_NUM_OPTEE ||
494 	    image_header->version != 2 || image_header->nb_images != 1) {
495 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
496 		return -EINVAL;
497 	}
498 
499 	image_ptr = (uint8_t *)data_va + sizeof(optee_header_t) +
500 			sizeof(optee_image_t);
501 	if (image_header->arch == 1) {
502 		opteed_rw = OPTEE_AARCH64;
503 	} else {
504 		opteed_rw = OPTEE_AARCH32;
505 	}
506 
507 	curr_image = &image_header->optee_image_list[0];
508 	image_pa = dual32to64(curr_image->load_addr_hi,
509 			      curr_image->load_addr_lo);
510 	image_va = image_pa;
511 	target_end_pa = image_pa + curr_image->size;
512 
513 	/* Now also map the memory we want to copy it to. */
514 	target_pa = page_align(image_pa, DOWN);
515 	target_va = target_pa;
516 	target_size = page_align(target_end_pa, UP) - target_pa;
517 
518 	rc = mmap_add_dynamic_region(target_pa, target_va, target_size,
519 				     MT_MEMORY | MT_RW | MT_SECURE);
520 	if (rc != 0) {
521 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
522 		return rc;
523 	}
524 
525 	INFO("Loaded OP-TEE via SMC: size %d addr 0x%" PRIx64 "\n",
526 	     curr_image->size, image_va);
527 
528 	memcpy((void *)image_va, image_ptr, curr_image->size);
529 	flush_dcache_range(target_pa, target_size);
530 
531 	mmap_remove_dynamic_region(mapped_data_va, data_map_size);
532 	mmap_remove_dynamic_region(target_va, target_size);
533 
534 	/* Save the non-secure state */
535 	cm_el1_sysregs_context_save(NON_SECURE);
536 
537 	rc = create_opteed_dt();
538 	if (rc) {
539 		ERROR("Failed device tree creation %d\n", rc);
540 		return rc;
541 	}
542 	dt_addr = (uint64_t)fdt_buf;
543 	flush_dcache_range(dt_addr, OPTEED_FDT_SIZE);
544 
545 	if (TRANSFER_LIST &&
546 	    !create_smc_tl((void *)dt_addr, OPTEED_FDT_SIZE)) {
547 		struct transfer_list_entry *te = NULL;
548 		void *dt = NULL;
549 
550 		te = transfer_list_find(bl31_tl, TL_TAG_FDT);
551 		dt = transfer_list_entry_data(te);
552 
553 		if (opteed_rw == OPTEE_AARCH64) {
554 			arg0 = (uint64_t)dt;
555 			arg2 = 0;
556 		} else {
557 			arg2 = (uint64_t)dt;
558 			arg0 = 0;
559 		}
560 		arg1 = TRANSFER_LIST_SIGNATURE |
561 			REGISTER_CONVENTION_VERSION_MASK;
562 		arg3 = (uint64_t)bl31_tl;
563 	} else {
564 		/* Default handoff arguments */
565 		arg2 = dt_addr;
566 	}
567 
568 	opteed_init_optee_ep_state(&optee_ep_info,
569 				   opteed_rw,
570 				   image_pa,
571 				   arg0,
572 				   arg1,
573 				   arg2,
574 				   arg3,
575 				   &opteed_sp_context[linear_id]);
576 	if (opteed_init_with_entry_point(&optee_ep_info) == 0) {
577 		rc = -EFAULT;
578 	}
579 
580 	/* Restore non-secure state */
581 	cm_el1_sysregs_context_restore(NON_SECURE);
582 	cm_set_next_eret_context(NON_SECURE);
583 
584 	return rc;
585 }
586 #endif  /* OPTEE_ALLOW_SMC_LOAD */
587 
588 /*******************************************************************************
589  * This function is responsible for handling all SMCs in the Trusted OS/App
590  * range from the non-secure state as defined in the SMC Calling Convention
591  * Document. It is also responsible for communicating with the Secure
592  * payload to delegate work and return results back to the non-secure
593  * state. Lastly it will also return any information that OPTEE needs to do
594  * the work assigned to it.
595  ******************************************************************************/
opteed_smc_handler(uint32_t smc_fid,u_register_t x1,u_register_t x2,u_register_t x3,u_register_t x4,void * cookie,void * handle,u_register_t flags)596 static uintptr_t opteed_smc_handler(uint32_t smc_fid,
597 			 u_register_t x1,
598 			 u_register_t x2,
599 			 u_register_t x3,
600 			 u_register_t x4,
601 			 void *cookie,
602 			 void *handle,
603 			 u_register_t flags)
604 {
605 	cpu_context_t *ns_cpu_context;
606 	uint32_t linear_id = plat_my_core_pos();
607 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
608 
609 	/*
610 	 * Determine which security state this SMC originated from
611 	 */
612 
613 	if (is_caller_non_secure(flags)) {
614 #if OPTEE_ALLOW_SMC_LOAD
615 		if (opteed_allow_load && smc_fid == NSSMC_OPTEED_CALL_UID) {
616 			/* Provide the UUID of the image loading service. */
617 			SMC_UUID_RET(handle, optee_image_load_uuid);
618 		}
619 		if (smc_fid == NSSMC_OPTEED_CALL_LOAD_IMAGE) {
620 			/*
621 			 * TODO: Consider wiping the code for SMC loading from
622 			 * memory after it has been invoked similar to what is
623 			 * done under RECLAIM_INIT, but extended to happen
624 			 * later.
625 			 */
626 			if (!opteed_allow_load) {
627 				SMC_RET1(handle, -EPERM);
628 			}
629 
630 			opteed_allow_load = false;
631 			uint64_t data_size = dual32to64(x1, x2);
632 			uint64_t data_pa = dual32to64(x3, x4);
633 			if (!data_size || !data_pa) {
634 				/*
635 				 * This is invoked when the OP-TEE image didn't
636 				 * load correctly in the kernel but we want to
637 				 * block off loading of it later for security
638 				 * reasons.
639 				 */
640 				SMC_RET1(handle, -EINVAL);
641 			}
642 			SMC_RET1(handle, opteed_handle_smc_load(
643 					data_size, data_pa));
644 		}
645 #endif  /* OPTEE_ALLOW_SMC_LOAD */
646 		/*
647 		 * This is a fresh request from the non-secure client.
648 		 * The parameters are in x1 and x2. Figure out which
649 		 * registers need to be preserved, save the non-secure
650 		 * state and send the request to the secure payload.
651 		 */
652 		assert(handle == cm_get_context(NON_SECURE));
653 
654 		cm_el1_sysregs_context_save(NON_SECURE);
655 
656 		/*
657 		 * We are done stashing the non-secure context. Ask the
658 		 * OP-TEE to do the work now. If we are loading vi an SMC,
659 		 * then we also need to init this CPU context if not done
660 		 * already.
661 		 */
662 		if (optee_vector_table == NULL) {
663 			SMC_RET1(handle, -EINVAL);
664 		}
665 
666 		if (get_optee_pstate(optee_ctx->state) ==
667 		    OPTEE_PSTATE_UNKNOWN) {
668 			opteed_cpu_on_finish_handler(0);
669 		}
670 
671 		/*
672 		 * Verify if there is a valid context to use, copy the
673 		 * operation type and parameters to the secure context
674 		 * and jump to the fast smc entry point in the secure
675 		 * payload. Entry into S-EL1 will take place upon exit
676 		 * from this function.
677 		 */
678 		assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
679 
680 		/* Set appropriate entry for SMC.
681 		 * We expect OPTEE to manage the PSTATE.I and PSTATE.F
682 		 * flags as appropriate.
683 		 */
684 		if (GET_SMC_TYPE(smc_fid) == SMC_TYPE_FAST) {
685 			cm_set_elr_el3(SECURE, (uint64_t)
686 					&optee_vector_table->fast_smc_entry);
687 		} else {
688 			cm_set_elr_el3(SECURE, (uint64_t)
689 					&optee_vector_table->yield_smc_entry);
690 		}
691 
692 		cm_el1_sysregs_context_restore(SECURE);
693 		cm_set_next_eret_context(SECURE);
694 
695 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
696 			      CTX_GPREG_X4,
697 			      read_ctx_reg(get_gpregs_ctx(handle),
698 					   CTX_GPREG_X4));
699 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
700 			      CTX_GPREG_X5,
701 			      read_ctx_reg(get_gpregs_ctx(handle),
702 					   CTX_GPREG_X5));
703 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
704 			      CTX_GPREG_X6,
705 			      read_ctx_reg(get_gpregs_ctx(handle),
706 					   CTX_GPREG_X6));
707 		/* Propagate hypervisor client ID */
708 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
709 			      CTX_GPREG_X7,
710 			      read_ctx_reg(get_gpregs_ctx(handle),
711 					   CTX_GPREG_X7));
712 
713 		SMC_RET4(&optee_ctx->cpu_ctx, smc_fid, x1, x2, x3);
714 	}
715 
716 	/*
717 	 * Returning from OPTEE
718 	 */
719 
720 	switch (smc_fid) {
721 	/*
722 	 * OPTEE has finished initialising itself after a cold boot
723 	 */
724 	case TEESMC_OPTEED_RETURN_ENTRY_DONE:
725 		/*
726 		 * Stash the OPTEE entry points information. This is done
727 		 * only once on the primary cpu
728 		 */
729 		assert(optee_vector_table == NULL);
730 		optee_vector_table = (optee_vectors_t *) x1;
731 
732 		if (optee_vector_table) {
733 			set_optee_pstate(optee_ctx->state, OPTEE_PSTATE_ON);
734 
735 			/*
736 			 * OPTEE has been successfully initialized.
737 			 * Register power management hooks with PSCI
738 			 */
739 			psci_register_spd_pm_hook(&opteed_pm);
740 
741 #if !OPTEE_ALLOW_SMC_LOAD
742 			register_opteed_interrupt_handler();
743 #endif
744 		}
745 
746 		/*
747 		 * OPTEE reports completion. The OPTEED must have initiated
748 		 * the original request through a synchronous entry into
749 		 * OPTEE. Jump back to the original C runtime context.
750 		 */
751 		opteed_synchronous_sp_exit(optee_ctx, x1);
752 		break;
753 
754 
755 	/*
756 	 * These function IDs is used only by OP-TEE to indicate it has
757 	 * finished:
758 	 * 1. turning itself on in response to an earlier psci
759 	 *    cpu_on request
760 	 * 2. resuming itself after an earlier psci cpu_suspend
761 	 *    request.
762 	 */
763 	case TEESMC_OPTEED_RETURN_ON_DONE:
764 	case TEESMC_OPTEED_RETURN_RESUME_DONE:
765 
766 
767 	/*
768 	 * These function IDs is used only by the SP to indicate it has
769 	 * finished:
770 	 * 1. suspending itself after an earlier psci cpu_suspend
771 	 *    request.
772 	 * 2. turning itself off in response to an earlier psci
773 	 *    cpu_off request.
774 	 */
775 	case TEESMC_OPTEED_RETURN_OFF_DONE:
776 	case TEESMC_OPTEED_RETURN_SUSPEND_DONE:
777 	case TEESMC_OPTEED_RETURN_SYSTEM_OFF_DONE:
778 	case TEESMC_OPTEED_RETURN_SYSTEM_RESET_DONE:
779 
780 		/*
781 		 * OPTEE reports completion. The OPTEED must have initiated the
782 		 * original request through a synchronous entry into OPTEE.
783 		 * Jump back to the original C runtime context, and pass x1 as
784 		 * return value to the caller
785 		 */
786 		opteed_synchronous_sp_exit(optee_ctx, x1);
787 		break;
788 
789 	/*
790 	 * OPTEE is returning from a call or being preempted from a call, in
791 	 * either case execution should resume in the normal world.
792 	 */
793 	case TEESMC_OPTEED_RETURN_CALL_DONE:
794 		/*
795 		 * This is the result from the secure client of an
796 		 * earlier request. The results are in x0-x3. Copy it
797 		 * into the non-secure context, save the secure state
798 		 * and return to the non-secure state.
799 		 */
800 		assert(handle == cm_get_context(SECURE));
801 		cm_el1_sysregs_context_save(SECURE);
802 
803 		/* Get a reference to the non-secure context */
804 		ns_cpu_context = cm_get_context(NON_SECURE);
805 		assert(ns_cpu_context);
806 
807 		/* Restore non-secure state */
808 		cm_el1_sysregs_context_restore(NON_SECURE);
809 		cm_set_next_eret_context(NON_SECURE);
810 
811 		SMC_RET4(ns_cpu_context, x1, x2, x3, x4);
812 
813 	/*
814 	 * OPTEE has finished handling a S-EL1 FIQ interrupt. Execution
815 	 * should resume in the normal world.
816 	 */
817 	case TEESMC_OPTEED_RETURN_FIQ_DONE:
818 		/* Get a reference to the non-secure context */
819 		ns_cpu_context = cm_get_context(NON_SECURE);
820 		assert(ns_cpu_context);
821 
822 		/*
823 		 * Restore non-secure state. There is no need to save the
824 		 * secure system register context since OPTEE was supposed
825 		 * to preserve it during S-EL1 interrupt handling.
826 		 */
827 		cm_el1_sysregs_context_restore(NON_SECURE);
828 		cm_set_next_eret_context(NON_SECURE);
829 
830 		SMC_RET0((uint64_t) ns_cpu_context);
831 
832 	default:
833 		panic();
834 	}
835 }
836 
837 /* Define an OPTEED runtime service descriptor for fast SMC calls */
838 DECLARE_RT_SVC(
839 	opteed_fast,
840 
841 	OEN_TOS_START,
842 	OEN_TOS_END,
843 	SMC_TYPE_FAST,
844 	opteed_setup,
845 	opteed_smc_handler
846 );
847 
848 /* Define an OPTEED runtime service descriptor for yielding SMC calls */
849 DECLARE_RT_SVC(
850 	opteed_std,
851 
852 	OEN_TOS_START,
853 	OEN_TOS_END,
854 	SMC_TYPE_YIELD,
855 	NULL,
856 	opteed_smc_handler
857 );
858