xref: /rk3399_ARM-atf/services/spd/opteed/opteed_main.c (revision 6d415de83fe084c08558895837d0eb90210420a9)
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 
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  ******************************************************************************/
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  */
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  ******************************************************************************/
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 	tl = (void *)optee_ep_info->args.arg3;
194 	if (TRANSFER_LIST && transfer_list_check_header(tl)) {
195 		te = transfer_list_find(tl, TL_TAG_FDT);
196 		dt = transfer_list_entry_data(te);
197 
198 		opteed_rw = GET_RW(optee_ep_info->spsr);
199 		if (opteed_rw == OPTEE_AARCH64) {
200 			if (optee_ep_info->args.arg1 !=
201 			    TRANSFER_LIST_HANDOFF_X1_VALUE(
202 				REGISTER_CONVENTION_VERSION))
203 				return 1;
204 
205 			arg0 = (uint64_t)dt;
206 			arg2 = 0;
207 		} else {
208 			if (optee_ep_info->args.arg1 !=
209 			    TRANSFER_LIST_HANDOFF_R1_VALUE(
210 				REGISTER_CONVENTION_VERSION))
211 				return 1;
212 
213 			arg0 = 0;
214 			arg2 = (uint64_t)dt;
215 		}
216 
217 		arg1 = optee_ep_info->args.arg1;
218 		arg3 = optee_ep_info->args.arg3;
219 	} else {
220 		/* Default handoff arguments */
221 		opteed_rw = optee_ep_info->args.arg0;
222 		arg0 = optee_ep_info->args.arg1; /* opteed_pageable_part */
223 		arg1 = optee_ep_info->args.arg2; /* opteed_mem_limit */
224 		arg2 = optee_ep_info->args.arg3; /* dt_addr */
225 		arg3 = 0;
226 	}
227 
228 	opteed_init_optee_ep_state(optee_ep_info, opteed_rw, optee_ep_info->pc,
229 				arg0, arg1, arg2, arg3,
230 				&opteed_sp_context[linear_id]);
231 
232 	/*
233 	 * All OPTEED initialization done. Now register our init function with
234 	 * BL31 for deferred invocation
235 	 */
236 	bl31_register_bl32_init(&opteed_init);
237 
238 	return 0;
239 #endif  /* OPTEE_ALLOW_SMC_LOAD */
240 }
241 
242 /*******************************************************************************
243  * This function passes control to the OPTEE image (BL32) for the first time
244  * on the primary cpu after a cold boot. It assumes that a valid secure
245  * context has already been created by opteed_setup() which can be directly
246  * used.  It also assumes that a valid non-secure context has been
247  * initialised by PSCI so it does not need to save and restore any
248  * non-secure state. This function performs a synchronous entry into
249  * OPTEE. OPTEE passes control back to this routine through a SMC. This returns
250  * a non-zero value on success and zero on failure.
251  ******************************************************************************/
252 static int32_t
253 opteed_init_with_entry_point(entry_point_info_t *optee_entry_point)
254 {
255 	uint32_t linear_id = plat_my_core_pos();
256 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
257 	uint64_t rc;
258 	assert(optee_entry_point);
259 
260 	cm_init_my_context(optee_entry_point);
261 
262 	/*
263 	 * Arrange for an entry into OPTEE. It will be returned via
264 	 * OPTEE_ENTRY_DONE case
265 	 */
266 	rc = opteed_synchronous_sp_entry(optee_ctx);
267 	assert(rc != 0);
268 
269 	return rc;
270 }
271 
272 #if !OPTEE_ALLOW_SMC_LOAD
273 static int32_t opteed_init(void)
274 {
275 	entry_point_info_t *optee_entry_point;
276 	/*
277 	 * Get information about the OP-TEE (BL32) image. Its
278 	 * absence is a critical failure.
279 	 */
280 	optee_entry_point = bl31_plat_get_next_image_ep_info(SECURE);
281 	return opteed_init_with_entry_point(optee_entry_point);
282 }
283 #endif  /* !OPTEE_ALLOW_SMC_LOAD */
284 
285 #if OPTEE_ALLOW_SMC_LOAD
286 #if COREBOOT
287 /*
288  * Adds a firmware/coreboot node with the coreboot table information to a device
289  * tree. Returns zero on success or if there is no coreboot table information;
290  * failure code otherwise.
291  */
292 static int add_coreboot_node(void *fdt)
293 {
294 	int ret;
295 	uint64_t coreboot_table_addr;
296 	uint32_t coreboot_table_size;
297 	struct {
298 		uint64_t addr;
299 		uint32_t size;
300 	} reg_node;
301 	coreboot_get_table_location(&coreboot_table_addr, &coreboot_table_size);
302 	if (!coreboot_table_addr || !coreboot_table_size) {
303 		WARN("Unable to get coreboot table location for device tree");
304 		return 0;
305 	}
306 	ret = fdt_begin_node(fdt, "firmware");
307 	if (ret)
308 		return ret;
309 
310 	ret = fdt_property(fdt, "ranges", NULL, 0);
311 	if (ret)
312 		return ret;
313 
314 	ret = fdt_begin_node(fdt, "coreboot");
315 	if (ret)
316 		return ret;
317 
318 	ret = fdt_property_string(fdt, "compatible", "coreboot");
319 	if (ret)
320 		return ret;
321 
322 	reg_node.addr = cpu_to_fdt64(coreboot_table_addr);
323 	reg_node.size = cpu_to_fdt32(coreboot_table_size);
324 	ret = fdt_property(fdt, "reg", &reg_node,
325 				sizeof(uint64_t) + sizeof(uint32_t));
326 	if (ret)
327 		return ret;
328 
329 	ret = fdt_end_node(fdt);
330 	if (ret)
331 		return ret;
332 
333 	return fdt_end_node(fdt);
334 }
335 #endif /* COREBOOT */
336 
337 #if CROS_WIDEVINE_SMC
338 /*
339  * Adds a options/widevine node with the widevine table information to a device
340  * tree. Returns zero on success or if there is no widevine table information;
341  * failure code otherwise.
342  */
343 static int add_options_widevine_node(void *fdt)
344 {
345 	int ret;
346 
347 	ret = fdt_begin_node(fdt, "options");
348 	if (ret)
349 		return ret;
350 
351 	ret = fdt_begin_node(fdt, "op-tee");
352 	if (ret)
353 		return ret;
354 
355 	ret = fdt_begin_node(fdt, "widevine");
356 	if (ret)
357 		return ret;
358 
359 	if (cros_oem_tpm_auth_pk.length) {
360 		ret = fdt_property(fdt, "tcg,tpm-auth-public-key",
361 				   cros_oem_tpm_auth_pk.buffer,
362 				   cros_oem_tpm_auth_pk.length);
363 		if (ret)
364 			return ret;
365 	}
366 
367 	if (cros_oem_huk.length) {
368 		ret = fdt_property(fdt, "op-tee,hardware-unique-key",
369 				   cros_oem_huk.buffer, cros_oem_huk.length);
370 		if (ret)
371 			return ret;
372 	}
373 
374 	if (cros_oem_rot.length) {
375 		ret = fdt_property(fdt, "google,widevine-root-of-trust-ecc-p256",
376 				   cros_oem_rot.buffer, cros_oem_rot.length);
377 		if (ret)
378 			return ret;
379 	}
380 
381 	ret = fdt_end_node(fdt);
382 	if (ret)
383 		return ret;
384 
385 	ret = fdt_end_node(fdt);
386 	if (ret)
387 		return ret;
388 
389 	return fdt_end_node(fdt);
390 }
391 #endif /* CROS_WIDEVINE_SMC */
392 
393 /*
394  * Creates a device tree for passing into OP-TEE. Currently is populated with
395  * the coreboot table address.
396  * Returns 0 on success, error code otherwise.
397  */
398 static int create_opteed_dt(void)
399 {
400 	int ret;
401 
402 	ret = fdt_create(fdt_buf, OPTEED_FDT_SIZE);
403 	if (ret)
404 		return ret;
405 
406 	ret = fdt_finish_reservemap(fdt_buf);
407 	if (ret)
408 		return ret;
409 
410 	ret = fdt_begin_node(fdt_buf, "");
411 	if (ret)
412 		return ret;
413 
414 #if COREBOOT
415 	ret = add_coreboot_node(fdt_buf);
416 	if (ret)
417 		return ret;
418 #endif /* COREBOOT */
419 
420 #if CROS_WIDEVINE_SMC
421 	ret = add_options_widevine_node(fdt_buf);
422 	if (ret)
423 		return ret;
424 #endif /* CROS_WIDEVINE_SMC */
425 
426 	ret = fdt_end_node(fdt_buf);
427 	if (ret)
428 		return ret;
429 
430 	return fdt_finish(fdt_buf);
431 }
432 
433 static int32_t create_smc_tl(const void *fdt, uint32_t fdt_sz)
434 {
435 #if TRANSFER_LIST
436 	bl31_tl = transfer_list_init((void *)(uintptr_t)FW_HANDOFF_BASE,
437 				FW_HANDOFF_SIZE);
438 	if (!bl31_tl) {
439 		ERROR("Failed to initialize Transfer List at 0x%lx\n",
440 		(unsigned long)FW_HANDOFF_BASE);
441 		return -1;
442 	}
443 
444 	if (!transfer_list_add(bl31_tl, TL_TAG_FDT, fdt_sz, fdt)) {
445 		return -1;
446 	}
447 	return 0;
448 #else
449 	return -1;
450 #endif
451 }
452 
453 /*******************************************************************************
454  * This function is responsible for handling the SMC that loads the OP-TEE
455  * binary image via a non-secure SMC call. It takes the size and physical
456  * address of the payload as parameters.
457  ******************************************************************************/
458 static int32_t opteed_handle_smc_load(uint64_t data_size, uint32_t data_pa)
459 {
460 	uintptr_t data_va = data_pa;
461 	uint64_t mapped_data_pa;
462 	uintptr_t mapped_data_va;
463 	uint64_t data_map_size;
464 	int32_t rc;
465 	optee_header_t *image_header;
466 	uint8_t *image_ptr;
467 	uint64_t target_pa;
468 	uint64_t target_end_pa;
469 	uint64_t image_pa;
470 	uintptr_t image_va;
471 	optee_image_t *curr_image;
472 	uintptr_t target_va;
473 	uint64_t target_size;
474 	entry_point_info_t optee_ep_info;
475 	uint32_t linear_id = plat_my_core_pos();
476 	uint64_t dt_addr = 0;
477 	uint64_t arg0 = 0;
478 	uint64_t arg1 = 0;
479 	uint64_t arg2 = 0;
480 	uint64_t arg3 = 0;
481 
482 	mapped_data_pa = page_align(data_pa, DOWN);
483 	mapped_data_va = mapped_data_pa;
484 	data_map_size = page_align(data_size + (mapped_data_pa - data_pa), UP);
485 
486 	/*
487 	 * We do not validate the passed in address because we are trusting the
488 	 * non-secure world at this point still.
489 	 */
490 	rc = mmap_add_dynamic_region(mapped_data_pa, mapped_data_va,
491 				     data_map_size, MT_MEMORY | MT_RO | MT_NS);
492 	if (rc != 0) {
493 		return rc;
494 	}
495 
496 	image_header = (optee_header_t *)data_va;
497 	if (image_header->magic != TEE_MAGIC_NUM_OPTEE ||
498 	    image_header->version != 2 || image_header->nb_images != 1) {
499 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
500 		return -EINVAL;
501 	}
502 
503 	image_ptr = (uint8_t *)data_va + sizeof(optee_header_t) +
504 			sizeof(optee_image_t);
505 	if (image_header->arch == 1) {
506 		opteed_rw = OPTEE_AARCH64;
507 	} else {
508 		opteed_rw = OPTEE_AARCH32;
509 	}
510 
511 	curr_image = &image_header->optee_image_list[0];
512 	image_pa = dual32to64(curr_image->load_addr_hi,
513 			      curr_image->load_addr_lo);
514 	image_va = image_pa;
515 	target_end_pa = image_pa + curr_image->size;
516 
517 	/* Now also map the memory we want to copy it to. */
518 	target_pa = page_align(image_pa, DOWN);
519 	target_va = target_pa;
520 	target_size = page_align(target_end_pa, UP) - target_pa;
521 
522 	rc = mmap_add_dynamic_region(target_pa, target_va, target_size,
523 				     MT_MEMORY | MT_RW | MT_SECURE);
524 	if (rc != 0) {
525 		mmap_remove_dynamic_region(mapped_data_va, data_map_size);
526 		return rc;
527 	}
528 
529 	INFO("Loaded OP-TEE via SMC: size %d addr 0x%" PRIx64 "\n",
530 	     curr_image->size, image_va);
531 
532 	memcpy((void *)image_va, image_ptr, curr_image->size);
533 	flush_dcache_range(target_pa, target_size);
534 
535 	mmap_remove_dynamic_region(mapped_data_va, data_map_size);
536 	mmap_remove_dynamic_region(target_va, target_size);
537 
538 	/* Save the non-secure state */
539 	cm_el1_sysregs_context_save(NON_SECURE);
540 
541 	rc = create_opteed_dt();
542 	if (rc) {
543 		ERROR("Failed device tree creation %d\n", rc);
544 		return rc;
545 	}
546 	dt_addr = (uint64_t)fdt_buf;
547 	flush_dcache_range(dt_addr, OPTEED_FDT_SIZE);
548 
549 	if (TRANSFER_LIST &&
550 	    !create_smc_tl((void *)dt_addr, OPTEED_FDT_SIZE)) {
551 		struct transfer_list_entry *te = NULL;
552 		void *dt = NULL;
553 
554 		te = transfer_list_find(bl31_tl, TL_TAG_FDT);
555 		dt = transfer_list_entry_data(te);
556 
557 		if (opteed_rw == OPTEE_AARCH64) {
558 			arg0 = (uint64_t)dt;
559 			arg1 = TRANSFER_LIST_HANDOFF_X1_VALUE(REGISTER_CONVENTION_VERSION);
560 			arg2 = 0;
561 		} else {
562 			arg0 = 0;
563 			arg1 = TRANSFER_LIST_HANDOFF_R1_VALUE(REGISTER_CONVENTION_VERSION);
564 			arg2 = (uint64_t)dt;
565 		}
566 
567 		arg3 = (uint64_t)bl31_tl;
568 	} else {
569 		/* Default handoff arguments */
570 		arg2 = dt_addr;
571 	}
572 
573 	opteed_init_optee_ep_state(&optee_ep_info,
574 				   opteed_rw,
575 				   image_pa,
576 				   arg0,
577 				   arg1,
578 				   arg2,
579 				   arg3,
580 				   &opteed_sp_context[linear_id]);
581 	if (opteed_init_with_entry_point(&optee_ep_info) == 0) {
582 		rc = -EFAULT;
583 	}
584 
585 	/* Restore non-secure state */
586 	cm_el1_sysregs_context_restore(NON_SECURE);
587 	cm_set_next_eret_context(NON_SECURE);
588 
589 	return rc;
590 }
591 #endif  /* OPTEE_ALLOW_SMC_LOAD */
592 
593 /*******************************************************************************
594  * This function is responsible for handling all SMCs in the Trusted OS/App
595  * range from the non-secure state as defined in the SMC Calling Convention
596  * Document. It is also responsible for communicating with the Secure
597  * payload to delegate work and return results back to the non-secure
598  * state. Lastly it will also return any information that OPTEE needs to do
599  * the work assigned to it.
600  ******************************************************************************/
601 static uintptr_t opteed_smc_handler(uint32_t smc_fid,
602 			 u_register_t x1,
603 			 u_register_t x2,
604 			 u_register_t x3,
605 			 u_register_t x4,
606 			 void *cookie,
607 			 void *handle,
608 			 u_register_t flags)
609 {
610 	cpu_context_t *ns_cpu_context;
611 	uint32_t linear_id = plat_my_core_pos();
612 	optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
613 
614 	/*
615 	 * Determine which security state this SMC originated from
616 	 */
617 
618 	if (is_caller_non_secure(flags)) {
619 #if OPTEE_ALLOW_SMC_LOAD
620 		if (opteed_allow_load && smc_fid == NSSMC_OPTEED_CALL_UID) {
621 			/* Provide the UUID of the image loading service. */
622 			SMC_UUID_RET(handle, optee_image_load_uuid);
623 		}
624 		if (smc_fid == NSSMC_OPTEED_CALL_LOAD_IMAGE) {
625 			/*
626 			 * TODO: Consider wiping the code for SMC loading from
627 			 * memory after it has been invoked similar to what is
628 			 * done under RECLAIM_INIT, but extended to happen
629 			 * later.
630 			 */
631 			if (!opteed_allow_load) {
632 				SMC_RET1(handle, -EPERM);
633 			}
634 
635 			opteed_allow_load = false;
636 			uint64_t data_size = dual32to64(x1, x2);
637 			uint64_t data_pa = dual32to64(x3, x4);
638 			if (!data_size || !data_pa) {
639 				/*
640 				 * This is invoked when the OP-TEE image didn't
641 				 * load correctly in the kernel but we want to
642 				 * block off loading of it later for security
643 				 * reasons.
644 				 */
645 				SMC_RET1(handle, -EINVAL);
646 			}
647 			SMC_RET1(handle, opteed_handle_smc_load(
648 					data_size, data_pa));
649 		}
650 #endif  /* OPTEE_ALLOW_SMC_LOAD */
651 		/*
652 		 * This is a fresh request from the non-secure client.
653 		 * The parameters are in x1 and x2. Figure out which
654 		 * registers need to be preserved, save the non-secure
655 		 * state and send the request to the secure payload.
656 		 */
657 		assert(handle == cm_get_context(NON_SECURE));
658 
659 		cm_el1_sysregs_context_save(NON_SECURE);
660 
661 		/*
662 		 * We are done stashing the non-secure context. Ask the
663 		 * OP-TEE to do the work now. If we are loading vi an SMC,
664 		 * then we also need to init this CPU context if not done
665 		 * already.
666 		 */
667 		if (optee_vector_table == NULL) {
668 			SMC_RET1(handle, -EINVAL);
669 		}
670 
671 		if (get_optee_pstate(optee_ctx->state) ==
672 		    OPTEE_PSTATE_UNKNOWN) {
673 			opteed_cpu_on_finish_handler(0);
674 		}
675 
676 		/*
677 		 * Verify if there is a valid context to use, copy the
678 		 * operation type and parameters to the secure context
679 		 * and jump to the fast smc entry point in the secure
680 		 * payload. Entry into S-EL1 will take place upon exit
681 		 * from this function.
682 		 */
683 		assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
684 
685 		/* Set appropriate entry for SMC.
686 		 * We expect OPTEE to manage the PSTATE.I and PSTATE.F
687 		 * flags as appropriate.
688 		 */
689 		if (GET_SMC_TYPE(smc_fid) == SMC_TYPE_FAST) {
690 			cm_set_elr_el3(SECURE, (uint64_t)
691 					&optee_vector_table->fast_smc_entry);
692 		} else {
693 			cm_set_elr_el3(SECURE, (uint64_t)
694 					&optee_vector_table->yield_smc_entry);
695 		}
696 
697 		cm_el1_sysregs_context_restore(SECURE);
698 		cm_set_next_eret_context(SECURE);
699 
700 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
701 			      CTX_GPREG_X4,
702 			      read_ctx_reg(get_gpregs_ctx(handle),
703 					   CTX_GPREG_X4));
704 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
705 			      CTX_GPREG_X5,
706 			      read_ctx_reg(get_gpregs_ctx(handle),
707 					   CTX_GPREG_X5));
708 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
709 			      CTX_GPREG_X6,
710 			      read_ctx_reg(get_gpregs_ctx(handle),
711 					   CTX_GPREG_X6));
712 		/* Propagate hypervisor client ID */
713 		write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
714 			      CTX_GPREG_X7,
715 			      read_ctx_reg(get_gpregs_ctx(handle),
716 					   CTX_GPREG_X7));
717 
718 		SMC_RET4(&optee_ctx->cpu_ctx, smc_fid, x1, x2, x3);
719 	}
720 
721 	/*
722 	 * Returning from OPTEE
723 	 */
724 
725 	switch (smc_fid) {
726 	/*
727 	 * OPTEE has finished initialising itself after a cold boot
728 	 */
729 	case TEESMC_OPTEED_RETURN_ENTRY_DONE:
730 		/*
731 		 * Stash the OPTEE entry points information. This is done
732 		 * only once on the primary cpu
733 		 */
734 		assert(optee_vector_table == NULL);
735 		optee_vector_table = (optee_vectors_t *) x1;
736 
737 		if (optee_vector_table) {
738 			set_optee_pstate(optee_ctx->state, OPTEE_PSTATE_ON);
739 
740 			/*
741 			 * OPTEE has been successfully initialized.
742 			 * Register power management hooks with PSCI
743 			 */
744 			psci_register_spd_pm_hook(&opteed_pm);
745 
746 #if !OPTEE_ALLOW_SMC_LOAD
747 			register_opteed_interrupt_handler();
748 #endif
749 		}
750 
751 		/*
752 		 * OPTEE reports completion. The OPTEED must have initiated
753 		 * the original request through a synchronous entry into
754 		 * OPTEE. Jump back to the original C runtime context.
755 		 */
756 		opteed_synchronous_sp_exit(optee_ctx, x1);
757 		break;
758 
759 
760 	/*
761 	 * These function IDs is used only by OP-TEE to indicate it has
762 	 * finished:
763 	 * 1. turning itself on in response to an earlier psci
764 	 *    cpu_on request
765 	 * 2. resuming itself after an earlier psci cpu_suspend
766 	 *    request.
767 	 */
768 	case TEESMC_OPTEED_RETURN_ON_DONE:
769 	case TEESMC_OPTEED_RETURN_RESUME_DONE:
770 
771 
772 	/*
773 	 * These function IDs is used only by the SP to indicate it has
774 	 * finished:
775 	 * 1. suspending itself after an earlier psci cpu_suspend
776 	 *    request.
777 	 * 2. turning itself off in response to an earlier psci
778 	 *    cpu_off request.
779 	 */
780 	case TEESMC_OPTEED_RETURN_OFF_DONE:
781 	case TEESMC_OPTEED_RETURN_SUSPEND_DONE:
782 	case TEESMC_OPTEED_RETURN_SYSTEM_OFF_DONE:
783 	case TEESMC_OPTEED_RETURN_SYSTEM_RESET_DONE:
784 
785 		/*
786 		 * OPTEE reports completion. The OPTEED must have initiated the
787 		 * original request through a synchronous entry into OPTEE.
788 		 * Jump back to the original C runtime context, and pass x1 as
789 		 * return value to the caller
790 		 */
791 		opteed_synchronous_sp_exit(optee_ctx, x1);
792 		break;
793 
794 	/*
795 	 * OPTEE is returning from a call or being preempted from a call, in
796 	 * either case execution should resume in the normal world.
797 	 */
798 	case TEESMC_OPTEED_RETURN_CALL_DONE:
799 		/*
800 		 * This is the result from the secure client of an
801 		 * earlier request. The results are in x0-x3. Copy it
802 		 * into the non-secure context, save the secure state
803 		 * and return to the non-secure state.
804 		 */
805 		assert(handle == cm_get_context(SECURE));
806 		cm_el1_sysregs_context_save(SECURE);
807 
808 		/* Get a reference to the non-secure context */
809 		ns_cpu_context = cm_get_context(NON_SECURE);
810 		assert(ns_cpu_context);
811 
812 		/* Restore non-secure state */
813 		cm_el1_sysregs_context_restore(NON_SECURE);
814 		cm_set_next_eret_context(NON_SECURE);
815 
816 		SMC_RET4(ns_cpu_context, x1, x2, x3, x4);
817 
818 	/*
819 	 * OPTEE has finished handling a S-EL1 FIQ interrupt. Execution
820 	 * should resume in the normal world.
821 	 */
822 	case TEESMC_OPTEED_RETURN_FIQ_DONE:
823 		/* Get a reference to the non-secure context */
824 		ns_cpu_context = cm_get_context(NON_SECURE);
825 		assert(ns_cpu_context);
826 
827 		/*
828 		 * Restore non-secure state. There is no need to save the
829 		 * secure system register context since OPTEE was supposed
830 		 * to preserve it during S-EL1 interrupt handling.
831 		 */
832 		cm_el1_sysregs_context_restore(NON_SECURE);
833 		cm_set_next_eret_context(NON_SECURE);
834 
835 		SMC_RET0((uint64_t) ns_cpu_context);
836 
837 	default:
838 		panic();
839 	}
840 }
841 
842 /* Define an OPTEED runtime service descriptor for fast SMC calls */
843 DECLARE_RT_SVC(
844 	opteed_fast,
845 
846 	OEN_TOS_START,
847 	OEN_TOS_END,
848 	SMC_TYPE_FAST,
849 	opteed_setup,
850 	opteed_smc_handler
851 );
852 
853 /* Define an OPTEED runtime service descriptor for yielding SMC calls */
854 DECLARE_RT_SVC(
855 	opteed_std,
856 
857 	OEN_TOS_START,
858 	OEN_TOS_END,
859 	SMC_TYPE_YIELD,
860 	NULL,
861 	opteed_smc_handler
862 );
863