xref: /linux/drivers/tee/optee/smc_abi.c (revision d53b8e36925256097a08d7cb749198d85cbf9b2b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2015-2021, 2023 Linaro Limited
4  * Copyright (c) 2016, EPAM Systems
5  */
6 
7 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
8 
9 #include <linux/arm-smccc.h>
10 #include <linux/cpuhotplug.h>
11 #include <linux/errno.h>
12 #include <linux/firmware.h>
13 #include <linux/interrupt.h>
14 #include <linux/io.h>
15 #include <linux/irqdomain.h>
16 #include <linux/kernel.h>
17 #include <linux/mm.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/of_irq.h>
21 #include <linux/of_platform.h>
22 #include <linux/platform_device.h>
23 #include <linux/sched.h>
24 #include <linux/slab.h>
25 #include <linux/string.h>
26 #include <linux/tee_core.h>
27 #include <linux/types.h>
28 #include <linux/workqueue.h>
29 #include "optee_private.h"
30 #include "optee_smc.h"
31 #include "optee_rpc_cmd.h"
32 #include <linux/kmemleak.h>
33 #define CREATE_TRACE_POINTS
34 #include "optee_trace.h"
35 
36 /*
37  * This file implement the SMC ABI used when communicating with secure world
38  * OP-TEE OS via raw SMCs.
39  * This file is divided into the following sections:
40  * 1. Convert between struct tee_param and struct optee_msg_param
41  * 2. Low level support functions to register shared memory in secure world
42  * 3. Dynamic shared memory pool based on alloc_pages()
43  * 4. Do a normal scheduled call into secure world
44  * 5. Asynchronous notification
45  * 6. Driver initialization.
46  */
47 
48 /*
49  * A typical OP-TEE private shm allocation is 224 bytes (argument struct
50  * with 6 parameters, needed for open session). So with an alignment of 512
51  * we'll waste a bit more than 50%. However, it's only expected that we'll
52  * have a handful of these structs allocated at a time. Most memory will
53  * be allocated aligned to the page size, So all in all this should scale
54  * up and down quite well.
55  */
56 #define OPTEE_MIN_STATIC_POOL_ALIGN    9 /* 512 bytes aligned */
57 
58 /* SMC ABI considers at most a single TEE firmware */
59 static unsigned int pcpu_irq_num;
60 
61 static int optee_cpuhp_enable_pcpu_irq(unsigned int cpu)
62 {
63 	enable_percpu_irq(pcpu_irq_num, IRQ_TYPE_NONE);
64 
65 	return 0;
66 }
67 
68 static int optee_cpuhp_disable_pcpu_irq(unsigned int cpu)
69 {
70 	disable_percpu_irq(pcpu_irq_num);
71 
72 	return 0;
73 }
74 
75 /*
76  * 1. Convert between struct tee_param and struct optee_msg_param
77  *
78  * optee_from_msg_param() and optee_to_msg_param() are the main
79  * functions.
80  */
81 
82 static int from_msg_param_tmp_mem(struct tee_param *p, u32 attr,
83 				  const struct optee_msg_param *mp)
84 {
85 	struct tee_shm *shm;
86 	phys_addr_t pa;
87 	int rc;
88 
89 	p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT +
90 		  attr - OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
91 	p->u.memref.size = mp->u.tmem.size;
92 	shm = (struct tee_shm *)(unsigned long)mp->u.tmem.shm_ref;
93 	if (!shm) {
94 		p->u.memref.shm_offs = 0;
95 		p->u.memref.shm = NULL;
96 		return 0;
97 	}
98 
99 	rc = tee_shm_get_pa(shm, 0, &pa);
100 	if (rc)
101 		return rc;
102 
103 	p->u.memref.shm_offs = mp->u.tmem.buf_ptr - pa;
104 	p->u.memref.shm = shm;
105 
106 	return 0;
107 }
108 
109 static void from_msg_param_reg_mem(struct tee_param *p, u32 attr,
110 				   const struct optee_msg_param *mp)
111 {
112 	struct tee_shm *shm;
113 
114 	p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT +
115 		  attr - OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
116 	p->u.memref.size = mp->u.rmem.size;
117 	shm = (struct tee_shm *)(unsigned long)mp->u.rmem.shm_ref;
118 
119 	if (shm) {
120 		p->u.memref.shm_offs = mp->u.rmem.offs;
121 		p->u.memref.shm = shm;
122 	} else {
123 		p->u.memref.shm_offs = 0;
124 		p->u.memref.shm = NULL;
125 	}
126 }
127 
128 /**
129  * optee_from_msg_param() - convert from OPTEE_MSG parameters to
130  *			    struct tee_param
131  * @optee:	main service struct
132  * @params:	subsystem internal parameter representation
133  * @num_params:	number of elements in the parameter arrays
134  * @msg_params:	OPTEE_MSG parameters
135  * Returns 0 on success or <0 on failure
136  */
137 static int optee_from_msg_param(struct optee *optee, struct tee_param *params,
138 				size_t num_params,
139 				const struct optee_msg_param *msg_params)
140 {
141 	int rc;
142 	size_t n;
143 
144 	for (n = 0; n < num_params; n++) {
145 		struct tee_param *p = params + n;
146 		const struct optee_msg_param *mp = msg_params + n;
147 		u32 attr = mp->attr & OPTEE_MSG_ATTR_TYPE_MASK;
148 
149 		switch (attr) {
150 		case OPTEE_MSG_ATTR_TYPE_NONE:
151 			p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE;
152 			memset(&p->u, 0, sizeof(p->u));
153 			break;
154 		case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT:
155 		case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
156 		case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
157 			optee_from_msg_param_value(p, attr, mp);
158 			break;
159 		case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:
160 		case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
161 		case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
162 			rc = from_msg_param_tmp_mem(p, attr, mp);
163 			if (rc)
164 				return rc;
165 			break;
166 		case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:
167 		case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
168 		case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
169 			from_msg_param_reg_mem(p, attr, mp);
170 			break;
171 
172 		default:
173 			return -EINVAL;
174 		}
175 	}
176 	return 0;
177 }
178 
179 static int to_msg_param_tmp_mem(struct optee_msg_param *mp,
180 				const struct tee_param *p)
181 {
182 	int rc;
183 	phys_addr_t pa;
184 
185 	mp->attr = OPTEE_MSG_ATTR_TYPE_TMEM_INPUT + p->attr -
186 		   TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT;
187 
188 	mp->u.tmem.shm_ref = (unsigned long)p->u.memref.shm;
189 	mp->u.tmem.size = p->u.memref.size;
190 
191 	if (!p->u.memref.shm) {
192 		mp->u.tmem.buf_ptr = 0;
193 		return 0;
194 	}
195 
196 	rc = tee_shm_get_pa(p->u.memref.shm, p->u.memref.shm_offs, &pa);
197 	if (rc)
198 		return rc;
199 
200 	mp->u.tmem.buf_ptr = pa;
201 	mp->attr |= OPTEE_MSG_ATTR_CACHE_PREDEFINED <<
202 		    OPTEE_MSG_ATTR_CACHE_SHIFT;
203 
204 	return 0;
205 }
206 
207 static int to_msg_param_reg_mem(struct optee_msg_param *mp,
208 				const struct tee_param *p)
209 {
210 	mp->attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT + p->attr -
211 		   TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT;
212 
213 	mp->u.rmem.shm_ref = (unsigned long)p->u.memref.shm;
214 	mp->u.rmem.size = p->u.memref.size;
215 	mp->u.rmem.offs = p->u.memref.shm_offs;
216 	return 0;
217 }
218 
219 /**
220  * optee_to_msg_param() - convert from struct tee_params to OPTEE_MSG parameters
221  * @optee:	main service struct
222  * @msg_params:	OPTEE_MSG parameters
223  * @num_params:	number of elements in the parameter arrays
224  * @params:	subsystem itnernal parameter representation
225  * Returns 0 on success or <0 on failure
226  */
227 static int optee_to_msg_param(struct optee *optee,
228 			      struct optee_msg_param *msg_params,
229 			      size_t num_params, const struct tee_param *params)
230 {
231 	int rc;
232 	size_t n;
233 
234 	for (n = 0; n < num_params; n++) {
235 		const struct tee_param *p = params + n;
236 		struct optee_msg_param *mp = msg_params + n;
237 
238 		switch (p->attr) {
239 		case TEE_IOCTL_PARAM_ATTR_TYPE_NONE:
240 			mp->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE;
241 			memset(&mp->u, 0, sizeof(mp->u));
242 			break;
243 		case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT:
244 		case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT:
245 		case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT:
246 			optee_to_msg_param_value(mp, p);
247 			break;
248 		case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT:
249 		case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT:
250 		case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT:
251 			if (tee_shm_is_dynamic(p->u.memref.shm))
252 				rc = to_msg_param_reg_mem(mp, p);
253 			else
254 				rc = to_msg_param_tmp_mem(mp, p);
255 			if (rc)
256 				return rc;
257 			break;
258 		default:
259 			return -EINVAL;
260 		}
261 	}
262 	return 0;
263 }
264 
265 /*
266  * 2. Low level support functions to register shared memory in secure world
267  *
268  * Functions to enable/disable shared memory caching in secure world, that
269  * is, lazy freeing of previously allocated shared memory. Freeing is
270  * performed when a request has been compled.
271  *
272  * Functions to register and unregister shared memory both for normal
273  * clients and for tee-supplicant.
274  */
275 
276 /**
277  * optee_enable_shm_cache() - Enables caching of some shared memory allocation
278  *			      in OP-TEE
279  * @optee:	main service struct
280  */
281 static void optee_enable_shm_cache(struct optee *optee)
282 {
283 	struct optee_call_waiter w;
284 
285 	/* We need to retry until secure world isn't busy. */
286 	optee_cq_wait_init(&optee->call_queue, &w, false);
287 	while (true) {
288 		struct arm_smccc_res res;
289 
290 		optee->smc.invoke_fn(OPTEE_SMC_ENABLE_SHM_CACHE,
291 				     0, 0, 0, 0, 0, 0, 0, &res);
292 		if (res.a0 == OPTEE_SMC_RETURN_OK)
293 			break;
294 		optee_cq_wait_for_completion(&optee->call_queue, &w);
295 	}
296 	optee_cq_wait_final(&optee->call_queue, &w);
297 }
298 
299 /**
300  * __optee_disable_shm_cache() - Disables caching of some shared memory
301  *				 allocation in OP-TEE
302  * @optee:	main service struct
303  * @is_mapped:	true if the cached shared memory addresses were mapped by this
304  *		kernel, are safe to dereference, and should be freed
305  */
306 static void __optee_disable_shm_cache(struct optee *optee, bool is_mapped)
307 {
308 	struct optee_call_waiter w;
309 
310 	/* We need to retry until secure world isn't busy. */
311 	optee_cq_wait_init(&optee->call_queue, &w, false);
312 	while (true) {
313 		union {
314 			struct arm_smccc_res smccc;
315 			struct optee_smc_disable_shm_cache_result result;
316 		} res;
317 
318 		optee->smc.invoke_fn(OPTEE_SMC_DISABLE_SHM_CACHE,
319 				     0, 0, 0, 0, 0, 0, 0, &res.smccc);
320 		if (res.result.status == OPTEE_SMC_RETURN_ENOTAVAIL)
321 			break; /* All shm's freed */
322 		if (res.result.status == OPTEE_SMC_RETURN_OK) {
323 			struct tee_shm *shm;
324 
325 			/*
326 			 * Shared memory references that were not mapped by
327 			 * this kernel must be ignored to prevent a crash.
328 			 */
329 			if (!is_mapped)
330 				continue;
331 
332 			shm = reg_pair_to_ptr(res.result.shm_upper32,
333 					      res.result.shm_lower32);
334 			tee_shm_free(shm);
335 		} else {
336 			optee_cq_wait_for_completion(&optee->call_queue, &w);
337 		}
338 	}
339 	optee_cq_wait_final(&optee->call_queue, &w);
340 }
341 
342 /**
343  * optee_disable_shm_cache() - Disables caching of mapped shared memory
344  *			       allocations in OP-TEE
345  * @optee:	main service struct
346  */
347 static void optee_disable_shm_cache(struct optee *optee)
348 {
349 	return __optee_disable_shm_cache(optee, true);
350 }
351 
352 /**
353  * optee_disable_unmapped_shm_cache() - Disables caching of shared memory
354  *					allocations in OP-TEE which are not
355  *					currently mapped
356  * @optee:	main service struct
357  */
358 static void optee_disable_unmapped_shm_cache(struct optee *optee)
359 {
360 	return __optee_disable_shm_cache(optee, false);
361 }
362 
363 #define PAGELIST_ENTRIES_PER_PAGE				\
364 	((OPTEE_MSG_NONCONTIG_PAGE_SIZE / sizeof(u64)) - 1)
365 
366 /*
367  * The final entry in each pagelist page is a pointer to the next
368  * pagelist page.
369  */
370 static size_t get_pages_list_size(size_t num_entries)
371 {
372 	int pages = DIV_ROUND_UP(num_entries, PAGELIST_ENTRIES_PER_PAGE);
373 
374 	return pages * OPTEE_MSG_NONCONTIG_PAGE_SIZE;
375 }
376 
377 static u64 *optee_allocate_pages_list(size_t num_entries)
378 {
379 	return alloc_pages_exact(get_pages_list_size(num_entries), GFP_KERNEL);
380 }
381 
382 static void optee_free_pages_list(void *list, size_t num_entries)
383 {
384 	free_pages_exact(list, get_pages_list_size(num_entries));
385 }
386 
387 /**
388  * optee_fill_pages_list() - write list of user pages to given shared
389  * buffer.
390  *
391  * @dst: page-aligned buffer where list of pages will be stored
392  * @pages: array of pages that represents shared buffer
393  * @num_pages: number of entries in @pages
394  * @page_offset: offset of user buffer from page start
395  *
396  * @dst should be big enough to hold list of user page addresses and
397  *	links to the next pages of buffer
398  */
399 static void optee_fill_pages_list(u64 *dst, struct page **pages, int num_pages,
400 				  size_t page_offset)
401 {
402 	int n = 0;
403 	phys_addr_t optee_page;
404 	/*
405 	 * Refer to OPTEE_MSG_ATTR_NONCONTIG description in optee_msg.h
406 	 * for details.
407 	 */
408 	struct {
409 		u64 pages_list[PAGELIST_ENTRIES_PER_PAGE];
410 		u64 next_page_data;
411 	} *pages_data;
412 
413 	/*
414 	 * Currently OP-TEE uses 4k page size and it does not looks
415 	 * like this will change in the future.  On other hand, there are
416 	 * no know ARM architectures with page size < 4k.
417 	 * Thus the next built assert looks redundant. But the following
418 	 * code heavily relies on this assumption, so it is better be
419 	 * safe than sorry.
420 	 */
421 	BUILD_BUG_ON(PAGE_SIZE < OPTEE_MSG_NONCONTIG_PAGE_SIZE);
422 
423 	pages_data = (void *)dst;
424 	/*
425 	 * If linux page is bigger than 4k, and user buffer offset is
426 	 * larger than 4k/8k/12k/etc this will skip first 4k pages,
427 	 * because they bear no value data for OP-TEE.
428 	 */
429 	optee_page = page_to_phys(*pages) +
430 		round_down(page_offset, OPTEE_MSG_NONCONTIG_PAGE_SIZE);
431 
432 	while (true) {
433 		pages_data->pages_list[n++] = optee_page;
434 
435 		if (n == PAGELIST_ENTRIES_PER_PAGE) {
436 			pages_data->next_page_data =
437 				virt_to_phys(pages_data + 1);
438 			pages_data++;
439 			n = 0;
440 		}
441 
442 		optee_page += OPTEE_MSG_NONCONTIG_PAGE_SIZE;
443 		if (!(optee_page & ~PAGE_MASK)) {
444 			if (!--num_pages)
445 				break;
446 			pages++;
447 			optee_page = page_to_phys(*pages);
448 		}
449 	}
450 }
451 
452 static int optee_shm_register(struct tee_context *ctx, struct tee_shm *shm,
453 			      struct page **pages, size_t num_pages,
454 			      unsigned long start)
455 {
456 	struct optee *optee = tee_get_drvdata(ctx->teedev);
457 	struct optee_msg_arg *msg_arg;
458 	struct tee_shm *shm_arg;
459 	u64 *pages_list;
460 	size_t sz;
461 	int rc;
462 
463 	if (!num_pages)
464 		return -EINVAL;
465 
466 	rc = optee_check_mem_type(start, num_pages);
467 	if (rc)
468 		return rc;
469 
470 	pages_list = optee_allocate_pages_list(num_pages);
471 	if (!pages_list)
472 		return -ENOMEM;
473 
474 	/*
475 	 * We're about to register shared memory we can't register shared
476 	 * memory for this request or there's a catch-22.
477 	 *
478 	 * So in this we'll have to do the good old temporary private
479 	 * allocation instead of using optee_get_msg_arg().
480 	 */
481 	sz = optee_msg_arg_size(optee->rpc_param_count);
482 	shm_arg = tee_shm_alloc_priv_buf(ctx, sz);
483 	if (IS_ERR(shm_arg)) {
484 		rc = PTR_ERR(shm_arg);
485 		goto out;
486 	}
487 	msg_arg = tee_shm_get_va(shm_arg, 0);
488 	if (IS_ERR(msg_arg)) {
489 		rc = PTR_ERR(msg_arg);
490 		goto out;
491 	}
492 
493 	optee_fill_pages_list(pages_list, pages, num_pages,
494 			      tee_shm_get_page_offset(shm));
495 
496 	memset(msg_arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
497 	msg_arg->num_params = 1;
498 	msg_arg->cmd = OPTEE_MSG_CMD_REGISTER_SHM;
499 	msg_arg->params->attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
500 				OPTEE_MSG_ATTR_NONCONTIG;
501 	msg_arg->params->u.tmem.shm_ref = (unsigned long)shm;
502 	msg_arg->params->u.tmem.size = tee_shm_get_size(shm);
503 	/*
504 	 * In the least bits of msg_arg->params->u.tmem.buf_ptr we
505 	 * store buffer offset from 4k page, as described in OP-TEE ABI.
506 	 */
507 	msg_arg->params->u.tmem.buf_ptr = virt_to_phys(pages_list) |
508 	  (tee_shm_get_page_offset(shm) & (OPTEE_MSG_NONCONTIG_PAGE_SIZE - 1));
509 
510 	if (optee->ops->do_call_with_arg(ctx, shm_arg, 0, false) ||
511 	    msg_arg->ret != TEEC_SUCCESS)
512 		rc = -EINVAL;
513 
514 	tee_shm_free(shm_arg);
515 out:
516 	optee_free_pages_list(pages_list, num_pages);
517 	return rc;
518 }
519 
520 static int optee_shm_unregister(struct tee_context *ctx, struct tee_shm *shm)
521 {
522 	struct optee *optee = tee_get_drvdata(ctx->teedev);
523 	struct optee_msg_arg *msg_arg;
524 	struct tee_shm *shm_arg;
525 	int rc = 0;
526 	size_t sz;
527 
528 	/*
529 	 * We're about to unregister shared memory and we may not be able
530 	 * register shared memory for this request in case we're called
531 	 * from optee_shm_arg_cache_uninit().
532 	 *
533 	 * So in order to keep things simple in this function just as in
534 	 * optee_shm_register() we'll use temporary private allocation
535 	 * instead of using optee_get_msg_arg().
536 	 */
537 	sz = optee_msg_arg_size(optee->rpc_param_count);
538 	shm_arg = tee_shm_alloc_priv_buf(ctx, sz);
539 	if (IS_ERR(shm_arg))
540 		return PTR_ERR(shm_arg);
541 	msg_arg = tee_shm_get_va(shm_arg, 0);
542 	if (IS_ERR(msg_arg)) {
543 		rc = PTR_ERR(msg_arg);
544 		goto out;
545 	}
546 
547 	memset(msg_arg, 0, sz);
548 	msg_arg->num_params = 1;
549 	msg_arg->cmd = OPTEE_MSG_CMD_UNREGISTER_SHM;
550 	msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
551 	msg_arg->params[0].u.rmem.shm_ref = (unsigned long)shm;
552 
553 	if (optee->ops->do_call_with_arg(ctx, shm_arg, 0, false) ||
554 	    msg_arg->ret != TEEC_SUCCESS)
555 		rc = -EINVAL;
556 out:
557 	tee_shm_free(shm_arg);
558 	return rc;
559 }
560 
561 static int optee_shm_register_supp(struct tee_context *ctx, struct tee_shm *shm,
562 				   struct page **pages, size_t num_pages,
563 				   unsigned long start)
564 {
565 	/*
566 	 * We don't want to register supplicant memory in OP-TEE.
567 	 * Instead information about it will be passed in RPC code.
568 	 */
569 	return optee_check_mem_type(start, num_pages);
570 }
571 
572 static int optee_shm_unregister_supp(struct tee_context *ctx,
573 				     struct tee_shm *shm)
574 {
575 	return 0;
576 }
577 
578 /*
579  * 3. Dynamic shared memory pool based on alloc_pages()
580  *
581  * Implements an OP-TEE specific shared memory pool which is used
582  * when dynamic shared memory is supported by secure world.
583  *
584  * The main function is optee_shm_pool_alloc_pages().
585  */
586 
587 static int pool_op_alloc(struct tee_shm_pool *pool,
588 			 struct tee_shm *shm, size_t size, size_t align)
589 {
590 	/*
591 	 * Shared memory private to the OP-TEE driver doesn't need
592 	 * to be registered with OP-TEE.
593 	 */
594 	if (shm->flags & TEE_SHM_PRIV)
595 		return tee_dyn_shm_alloc_helper(shm, size, align, NULL);
596 
597 	return tee_dyn_shm_alloc_helper(shm, size, align, optee_shm_register);
598 }
599 
600 static void pool_op_free(struct tee_shm_pool *pool,
601 			 struct tee_shm *shm)
602 {
603 	if (!(shm->flags & TEE_SHM_PRIV))
604 		tee_dyn_shm_free_helper(shm, optee_shm_unregister);
605 	else
606 		tee_dyn_shm_free_helper(shm, NULL);
607 }
608 
609 static void pool_op_destroy_pool(struct tee_shm_pool *pool)
610 {
611 	kfree(pool);
612 }
613 
614 static const struct tee_shm_pool_ops pool_ops = {
615 	.alloc = pool_op_alloc,
616 	.free = pool_op_free,
617 	.destroy_pool = pool_op_destroy_pool,
618 };
619 
620 /**
621  * optee_shm_pool_alloc_pages() - create page-based allocator pool
622  *
623  * This pool is used when OP-TEE supports dymanic SHM. In this case
624  * command buffers and such are allocated from kernel's own memory.
625  */
626 static struct tee_shm_pool *optee_shm_pool_alloc_pages(void)
627 {
628 	struct tee_shm_pool *pool = kzalloc(sizeof(*pool), GFP_KERNEL);
629 
630 	if (!pool)
631 		return ERR_PTR(-ENOMEM);
632 
633 	pool->ops = &pool_ops;
634 
635 	return pool;
636 }
637 
638 /*
639  * 4. Do a normal scheduled call into secure world
640  *
641  * The function optee_smc_do_call_with_arg() performs a normal scheduled
642  * call into secure world. During this call may normal world request help
643  * from normal world using RPCs, Remote Procedure Calls. This includes
644  * delivery of non-secure interrupts to for instance allow rescheduling of
645  * the current task.
646  */
647 
648 static void handle_rpc_func_cmd_shm_free(struct tee_context *ctx,
649 					 struct optee_msg_arg *arg)
650 {
651 	struct tee_shm *shm;
652 
653 	arg->ret_origin = TEEC_ORIGIN_COMMS;
654 
655 	if (arg->num_params != 1 ||
656 	    arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) {
657 		arg->ret = TEEC_ERROR_BAD_PARAMETERS;
658 		return;
659 	}
660 
661 	shm = (struct tee_shm *)(unsigned long)arg->params[0].u.value.b;
662 	switch (arg->params[0].u.value.a) {
663 	case OPTEE_RPC_SHM_TYPE_APPL:
664 		optee_rpc_cmd_free_suppl(ctx, shm);
665 		break;
666 	case OPTEE_RPC_SHM_TYPE_KERNEL:
667 		tee_shm_free(shm);
668 		break;
669 	default:
670 		arg->ret = TEEC_ERROR_BAD_PARAMETERS;
671 	}
672 	arg->ret = TEEC_SUCCESS;
673 }
674 
675 static void handle_rpc_func_cmd_shm_alloc(struct tee_context *ctx,
676 					  struct optee *optee,
677 					  struct optee_msg_arg *arg,
678 					  struct optee_call_ctx *call_ctx)
679 {
680 	struct tee_shm *shm;
681 	size_t sz;
682 	size_t n;
683 	struct page **pages;
684 	size_t page_count;
685 
686 	arg->ret_origin = TEEC_ORIGIN_COMMS;
687 
688 	if (!arg->num_params ||
689 	    arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) {
690 		arg->ret = TEEC_ERROR_BAD_PARAMETERS;
691 		return;
692 	}
693 
694 	for (n = 1; n < arg->num_params; n++) {
695 		if (arg->params[n].attr != OPTEE_MSG_ATTR_TYPE_NONE) {
696 			arg->ret = TEEC_ERROR_BAD_PARAMETERS;
697 			return;
698 		}
699 	}
700 
701 	sz = arg->params[0].u.value.b;
702 	switch (arg->params[0].u.value.a) {
703 	case OPTEE_RPC_SHM_TYPE_APPL:
704 		shm = optee_rpc_cmd_alloc_suppl(ctx, sz);
705 		break;
706 	case OPTEE_RPC_SHM_TYPE_KERNEL:
707 		shm = tee_shm_alloc_priv_buf(optee->ctx, sz);
708 		break;
709 	default:
710 		arg->ret = TEEC_ERROR_BAD_PARAMETERS;
711 		return;
712 	}
713 
714 	if (IS_ERR(shm)) {
715 		arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
716 		return;
717 	}
718 
719 	/*
720 	 * If there are pages it's dynamically allocated shared memory (not
721 	 * from the reserved shared memory pool) and needs to be
722 	 * registered.
723 	 */
724 	pages = tee_shm_get_pages(shm, &page_count);
725 	if (pages) {
726 		u64 *pages_list;
727 
728 		pages_list = optee_allocate_pages_list(page_count);
729 		if (!pages_list) {
730 			arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
731 			goto bad;
732 		}
733 
734 		call_ctx->pages_list = pages_list;
735 		call_ctx->num_entries = page_count;
736 
737 		arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
738 				      OPTEE_MSG_ATTR_NONCONTIG;
739 		/*
740 		 * In the least bits of u.tmem.buf_ptr we store buffer offset
741 		 * from 4k page, as described in OP-TEE ABI.
742 		 */
743 		arg->params[0].u.tmem.buf_ptr = virt_to_phys(pages_list) |
744 			(tee_shm_get_page_offset(shm) &
745 			 (OPTEE_MSG_NONCONTIG_PAGE_SIZE - 1));
746 
747 		optee_fill_pages_list(pages_list, pages, page_count,
748 				      tee_shm_get_page_offset(shm));
749 	} else {
750 		phys_addr_t pa;
751 
752 		if (tee_shm_get_pa(shm, 0, &pa)) {
753 			arg->ret = TEEC_ERROR_BAD_PARAMETERS;
754 			goto bad;
755 		}
756 
757 		arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT;
758 		arg->params[0].u.tmem.buf_ptr = pa;
759 	}
760 	arg->params[0].u.tmem.size = tee_shm_get_size(shm);
761 	arg->params[0].u.tmem.shm_ref = (unsigned long)shm;
762 
763 	arg->ret = TEEC_SUCCESS;
764 	return;
765 bad:
766 	tee_shm_free(shm);
767 }
768 
769 static void free_pages_list(struct optee_call_ctx *call_ctx)
770 {
771 	if (call_ctx->pages_list) {
772 		optee_free_pages_list(call_ctx->pages_list,
773 				      call_ctx->num_entries);
774 		call_ctx->pages_list = NULL;
775 		call_ctx->num_entries = 0;
776 	}
777 }
778 
779 static void optee_rpc_finalize_call(struct optee_call_ctx *call_ctx)
780 {
781 	free_pages_list(call_ctx);
782 }
783 
784 static void handle_rpc_func_cmd(struct tee_context *ctx, struct optee *optee,
785 				struct optee_msg_arg *arg,
786 				struct optee_call_ctx *call_ctx)
787 {
788 
789 	switch (arg->cmd) {
790 	case OPTEE_RPC_CMD_SHM_ALLOC:
791 		free_pages_list(call_ctx);
792 		handle_rpc_func_cmd_shm_alloc(ctx, optee, arg, call_ctx);
793 		break;
794 	case OPTEE_RPC_CMD_SHM_FREE:
795 		handle_rpc_func_cmd_shm_free(ctx, arg);
796 		break;
797 	default:
798 		optee_rpc_cmd(ctx, optee, arg);
799 	}
800 }
801 
802 /**
803  * optee_handle_rpc() - handle RPC from secure world
804  * @ctx:	context doing the RPC
805  * @rpc_arg:	pointer to RPC arguments if any, or NULL if none
806  * @param:	value of registers for the RPC
807  * @call_ctx:	call context. Preserved during one OP-TEE invocation
808  *
809  * Result of RPC is written back into @param.
810  */
811 static void optee_handle_rpc(struct tee_context *ctx,
812 			     struct optee_msg_arg *rpc_arg,
813 			     struct optee_rpc_param *param,
814 			     struct optee_call_ctx *call_ctx)
815 {
816 	struct tee_device *teedev = ctx->teedev;
817 	struct optee *optee = tee_get_drvdata(teedev);
818 	struct optee_msg_arg *arg;
819 	struct tee_shm *shm;
820 	phys_addr_t pa;
821 
822 	switch (OPTEE_SMC_RETURN_GET_RPC_FUNC(param->a0)) {
823 	case OPTEE_SMC_RPC_FUNC_ALLOC:
824 		shm = tee_shm_alloc_priv_buf(optee->ctx, param->a1);
825 		if (!IS_ERR(shm) && !tee_shm_get_pa(shm, 0, &pa)) {
826 			reg_pair_from_64(&param->a1, &param->a2, pa);
827 			reg_pair_from_64(&param->a4, &param->a5,
828 					 (unsigned long)shm);
829 		} else {
830 			param->a1 = 0;
831 			param->a2 = 0;
832 			param->a4 = 0;
833 			param->a5 = 0;
834 		}
835 		kmemleak_not_leak(shm);
836 		break;
837 	case OPTEE_SMC_RPC_FUNC_FREE:
838 		shm = reg_pair_to_ptr(param->a1, param->a2);
839 		tee_shm_free(shm);
840 		break;
841 	case OPTEE_SMC_RPC_FUNC_FOREIGN_INTR:
842 		/*
843 		 * A foreign interrupt was raised while secure world was
844 		 * executing, since they are handled in Linux a dummy RPC is
845 		 * performed to let Linux take the interrupt through the normal
846 		 * vector.
847 		 */
848 		break;
849 	case OPTEE_SMC_RPC_FUNC_CMD:
850 		if (rpc_arg) {
851 			arg = rpc_arg;
852 		} else {
853 			shm = reg_pair_to_ptr(param->a1, param->a2);
854 			arg = tee_shm_get_va(shm, 0);
855 			if (IS_ERR(arg)) {
856 				pr_err("%s: tee_shm_get_va %p failed\n",
857 				       __func__, shm);
858 				break;
859 			}
860 		}
861 
862 		handle_rpc_func_cmd(ctx, optee, arg, call_ctx);
863 		break;
864 	default:
865 		pr_warn("Unknown RPC func 0x%x\n",
866 			(u32)OPTEE_SMC_RETURN_GET_RPC_FUNC(param->a0));
867 		break;
868 	}
869 
870 	param->a0 = OPTEE_SMC_CALL_RETURN_FROM_RPC;
871 }
872 
873 /**
874  * optee_smc_do_call_with_arg() - Do an SMC to OP-TEE in secure world
875  * @ctx:	calling context
876  * @shm:	shared memory holding the message to pass to secure world
877  * @offs:	offset of the message in @shm
878  * @system_thread: true if caller requests TEE system thread support
879  *
880  * Does and SMC to OP-TEE in secure world and handles eventual resulting
881  * Remote Procedure Calls (RPC) from OP-TEE.
882  *
883  * Returns return code from secure world, 0 is OK
884  */
885 static int optee_smc_do_call_with_arg(struct tee_context *ctx,
886 				      struct tee_shm *shm, u_int offs,
887 				      bool system_thread)
888 {
889 	struct optee *optee = tee_get_drvdata(ctx->teedev);
890 	struct optee_call_waiter w;
891 	struct optee_rpc_param param = { };
892 	struct optee_call_ctx call_ctx = { };
893 	struct optee_msg_arg *rpc_arg = NULL;
894 	int rc;
895 
896 	if (optee->rpc_param_count) {
897 		struct optee_msg_arg *arg;
898 		unsigned int rpc_arg_offs;
899 
900 		arg = tee_shm_get_va(shm, offs);
901 		if (IS_ERR(arg))
902 			return PTR_ERR(arg);
903 
904 		rpc_arg_offs = OPTEE_MSG_GET_ARG_SIZE(arg->num_params);
905 		rpc_arg = tee_shm_get_va(shm, offs + rpc_arg_offs);
906 		if (IS_ERR(rpc_arg))
907 			return PTR_ERR(rpc_arg);
908 	}
909 
910 	if  (rpc_arg && tee_shm_is_dynamic(shm)) {
911 		param.a0 = OPTEE_SMC_CALL_WITH_REGD_ARG;
912 		reg_pair_from_64(&param.a1, &param.a2, (u_long)shm);
913 		param.a3 = offs;
914 	} else {
915 		phys_addr_t parg;
916 
917 		rc = tee_shm_get_pa(shm, offs, &parg);
918 		if (rc)
919 			return rc;
920 
921 		if (rpc_arg)
922 			param.a0 = OPTEE_SMC_CALL_WITH_RPC_ARG;
923 		else
924 			param.a0 = OPTEE_SMC_CALL_WITH_ARG;
925 		reg_pair_from_64(&param.a1, &param.a2, parg);
926 	}
927 	/* Initialize waiter */
928 	optee_cq_wait_init(&optee->call_queue, &w, system_thread);
929 	while (true) {
930 		struct arm_smccc_res res;
931 
932 		trace_optee_invoke_fn_begin(&param);
933 		optee->smc.invoke_fn(param.a0, param.a1, param.a2, param.a3,
934 				     param.a4, param.a5, param.a6, param.a7,
935 				     &res);
936 		trace_optee_invoke_fn_end(&param, &res);
937 
938 		if (res.a0 == OPTEE_SMC_RETURN_ETHREAD_LIMIT) {
939 			/*
940 			 * Out of threads in secure world, wait for a thread
941 			 * become available.
942 			 */
943 			optee_cq_wait_for_completion(&optee->call_queue, &w);
944 		} else if (OPTEE_SMC_RETURN_IS_RPC(res.a0)) {
945 			cond_resched();
946 			param.a0 = res.a0;
947 			param.a1 = res.a1;
948 			param.a2 = res.a2;
949 			param.a3 = res.a3;
950 			optee_handle_rpc(ctx, rpc_arg, &param, &call_ctx);
951 		} else {
952 			rc = res.a0;
953 			break;
954 		}
955 	}
956 
957 	optee_rpc_finalize_call(&call_ctx);
958 	/*
959 	 * We're done with our thread in secure world, if there's any
960 	 * thread waiters wake up one.
961 	 */
962 	optee_cq_wait_final(&optee->call_queue, &w);
963 
964 	return rc;
965 }
966 
967 /*
968  * 5. Asynchronous notification
969  */
970 
971 static u32 get_async_notif_value(optee_invoke_fn *invoke_fn, bool *value_valid,
972 				 bool *value_pending)
973 {
974 	struct arm_smccc_res res;
975 
976 	invoke_fn(OPTEE_SMC_GET_ASYNC_NOTIF_VALUE, 0, 0, 0, 0, 0, 0, 0, &res);
977 
978 	if (res.a0) {
979 		*value_valid = false;
980 		return 0;
981 	}
982 	*value_valid = (res.a2 & OPTEE_SMC_ASYNC_NOTIF_VALUE_VALID);
983 	*value_pending = (res.a2 & OPTEE_SMC_ASYNC_NOTIF_VALUE_PENDING);
984 	return res.a1;
985 }
986 
987 static irqreturn_t irq_handler(struct optee *optee)
988 {
989 	bool do_bottom_half = false;
990 	bool value_valid;
991 	bool value_pending;
992 	u32 value;
993 
994 	do {
995 		value = get_async_notif_value(optee->smc.invoke_fn,
996 					      &value_valid, &value_pending);
997 		if (!value_valid)
998 			break;
999 
1000 		if (value == OPTEE_SMC_ASYNC_NOTIF_VALUE_DO_BOTTOM_HALF)
1001 			do_bottom_half = true;
1002 		else
1003 			optee_notif_send(optee, value);
1004 	} while (value_pending);
1005 
1006 	if (do_bottom_half)
1007 		return IRQ_WAKE_THREAD;
1008 	return IRQ_HANDLED;
1009 }
1010 
1011 static irqreturn_t notif_irq_handler(int irq, void *dev_id)
1012 {
1013 	struct optee *optee = dev_id;
1014 
1015 	return irq_handler(optee);
1016 }
1017 
1018 static irqreturn_t notif_irq_thread_fn(int irq, void *dev_id)
1019 {
1020 	struct optee *optee = dev_id;
1021 
1022 	optee_do_bottom_half(optee->ctx);
1023 
1024 	return IRQ_HANDLED;
1025 }
1026 
1027 static int init_irq(struct optee *optee, u_int irq)
1028 {
1029 	int rc;
1030 
1031 	rc = request_threaded_irq(irq, notif_irq_handler,
1032 				  notif_irq_thread_fn,
1033 				  0, "optee_notification", optee);
1034 	if (rc)
1035 		return rc;
1036 
1037 	optee->smc.notif_irq = irq;
1038 
1039 	return 0;
1040 }
1041 
1042 static irqreturn_t notif_pcpu_irq_handler(int irq, void *dev_id)
1043 {
1044 	struct optee_pcpu *pcpu = dev_id;
1045 	struct optee *optee = pcpu->optee;
1046 
1047 	if (irq_handler(optee) == IRQ_WAKE_THREAD)
1048 		queue_work(optee->smc.notif_pcpu_wq,
1049 			   &optee->smc.notif_pcpu_work);
1050 
1051 	return IRQ_HANDLED;
1052 }
1053 
1054 static void notif_pcpu_irq_work_fn(struct work_struct *work)
1055 {
1056 	struct optee_smc *optee_smc = container_of(work, struct optee_smc,
1057 						   notif_pcpu_work);
1058 	struct optee *optee = container_of(optee_smc, struct optee, smc);
1059 
1060 	optee_do_bottom_half(optee->ctx);
1061 }
1062 
1063 static int init_pcpu_irq(struct optee *optee, u_int irq)
1064 {
1065 	struct optee_pcpu __percpu *optee_pcpu;
1066 	int cpu, rc;
1067 
1068 	optee_pcpu = alloc_percpu(struct optee_pcpu);
1069 	if (!optee_pcpu)
1070 		return -ENOMEM;
1071 
1072 	for_each_present_cpu(cpu)
1073 		per_cpu_ptr(optee_pcpu, cpu)->optee = optee;
1074 
1075 	rc = request_percpu_irq(irq, notif_pcpu_irq_handler,
1076 				"optee_pcpu_notification", optee_pcpu);
1077 	if (rc)
1078 		goto err_free_pcpu;
1079 
1080 	INIT_WORK(&optee->smc.notif_pcpu_work, notif_pcpu_irq_work_fn);
1081 	optee->smc.notif_pcpu_wq = create_workqueue("optee_pcpu_notification");
1082 	if (!optee->smc.notif_pcpu_wq) {
1083 		rc = -EINVAL;
1084 		goto err_free_pcpu_irq;
1085 	}
1086 
1087 	optee->smc.optee_pcpu = optee_pcpu;
1088 	optee->smc.notif_irq = irq;
1089 
1090 	pcpu_irq_num = irq;
1091 	rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "optee/pcpu-notif:starting",
1092 			       optee_cpuhp_enable_pcpu_irq,
1093 			       optee_cpuhp_disable_pcpu_irq);
1094 	if (!rc)
1095 		rc = -EINVAL;
1096 	if (rc < 0)
1097 		goto err_free_pcpu_irq;
1098 
1099 	optee->smc.notif_cpuhp_state = rc;
1100 
1101 	return 0;
1102 
1103 err_free_pcpu_irq:
1104 	free_percpu_irq(irq, optee_pcpu);
1105 err_free_pcpu:
1106 	free_percpu(optee_pcpu);
1107 
1108 	return rc;
1109 }
1110 
1111 static int optee_smc_notif_init_irq(struct optee *optee, u_int irq)
1112 {
1113 	if (irq_is_percpu_devid(irq))
1114 		return init_pcpu_irq(optee, irq);
1115 	else
1116 		return init_irq(optee, irq);
1117 }
1118 
1119 static void uninit_pcpu_irq(struct optee *optee)
1120 {
1121 	cpuhp_remove_state(optee->smc.notif_cpuhp_state);
1122 
1123 	destroy_workqueue(optee->smc.notif_pcpu_wq);
1124 
1125 	free_percpu_irq(optee->smc.notif_irq, optee->smc.optee_pcpu);
1126 	free_percpu(optee->smc.optee_pcpu);
1127 }
1128 
1129 static void optee_smc_notif_uninit_irq(struct optee *optee)
1130 {
1131 	if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF) {
1132 		optee_stop_async_notif(optee->ctx);
1133 		if (optee->smc.notif_irq) {
1134 			if (irq_is_percpu_devid(optee->smc.notif_irq))
1135 				uninit_pcpu_irq(optee);
1136 			else
1137 				free_irq(optee->smc.notif_irq, optee);
1138 
1139 			irq_dispose_mapping(optee->smc.notif_irq);
1140 		}
1141 	}
1142 }
1143 
1144 /*
1145  * 6. Driver initialization
1146  *
1147  * During driver initialization is secure world probed to find out which
1148  * features it supports so the driver can be initialized with a matching
1149  * configuration. This involves for instance support for dynamic shared
1150  * memory instead of a static memory carvout.
1151  */
1152 
1153 static void optee_get_version(struct tee_device *teedev,
1154 			      struct tee_ioctl_version_data *vers)
1155 {
1156 	struct tee_ioctl_version_data v = {
1157 		.impl_id = TEE_IMPL_ID_OPTEE,
1158 		.impl_caps = TEE_OPTEE_CAP_TZ,
1159 		.gen_caps = TEE_GEN_CAP_GP,
1160 	};
1161 	struct optee *optee = tee_get_drvdata(teedev);
1162 
1163 	if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM)
1164 		v.gen_caps |= TEE_GEN_CAP_REG_MEM;
1165 	if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_MEMREF_NULL)
1166 		v.gen_caps |= TEE_GEN_CAP_MEMREF_NULL;
1167 	*vers = v;
1168 }
1169 
1170 static int optee_smc_open(struct tee_context *ctx)
1171 {
1172 	struct optee *optee = tee_get_drvdata(ctx->teedev);
1173 	u32 sec_caps = optee->smc.sec_caps;
1174 
1175 	return optee_open(ctx, sec_caps & OPTEE_SMC_SEC_CAP_MEMREF_NULL);
1176 }
1177 
1178 static const struct tee_driver_ops optee_clnt_ops = {
1179 	.get_version = optee_get_version,
1180 	.open = optee_smc_open,
1181 	.release = optee_release,
1182 	.open_session = optee_open_session,
1183 	.close_session = optee_close_session,
1184 	.system_session = optee_system_session,
1185 	.invoke_func = optee_invoke_func,
1186 	.cancel_req = optee_cancel_req,
1187 	.shm_register = optee_shm_register,
1188 	.shm_unregister = optee_shm_unregister,
1189 };
1190 
1191 static const struct tee_desc optee_clnt_desc = {
1192 	.name = DRIVER_NAME "-clnt",
1193 	.ops = &optee_clnt_ops,
1194 	.owner = THIS_MODULE,
1195 };
1196 
1197 static const struct tee_driver_ops optee_supp_ops = {
1198 	.get_version = optee_get_version,
1199 	.open = optee_smc_open,
1200 	.release = optee_release_supp,
1201 	.supp_recv = optee_supp_recv,
1202 	.supp_send = optee_supp_send,
1203 	.shm_register = optee_shm_register_supp,
1204 	.shm_unregister = optee_shm_unregister_supp,
1205 };
1206 
1207 static const struct tee_desc optee_supp_desc = {
1208 	.name = DRIVER_NAME "-supp",
1209 	.ops = &optee_supp_ops,
1210 	.owner = THIS_MODULE,
1211 	.flags = TEE_DESC_PRIVILEGED,
1212 };
1213 
1214 static const struct optee_ops optee_ops = {
1215 	.do_call_with_arg = optee_smc_do_call_with_arg,
1216 	.to_msg_param = optee_to_msg_param,
1217 	.from_msg_param = optee_from_msg_param,
1218 };
1219 
1220 static int enable_async_notif(optee_invoke_fn *invoke_fn)
1221 {
1222 	struct arm_smccc_res res;
1223 
1224 	invoke_fn(OPTEE_SMC_ENABLE_ASYNC_NOTIF, 0, 0, 0, 0, 0, 0, 0, &res);
1225 
1226 	if (res.a0)
1227 		return -EINVAL;
1228 	return 0;
1229 }
1230 
1231 static bool optee_msg_api_uid_is_optee_api(optee_invoke_fn *invoke_fn)
1232 {
1233 	struct arm_smccc_res res;
1234 
1235 	invoke_fn(OPTEE_SMC_CALLS_UID, 0, 0, 0, 0, 0, 0, 0, &res);
1236 
1237 	if (res.a0 == OPTEE_MSG_UID_0 && res.a1 == OPTEE_MSG_UID_1 &&
1238 	    res.a2 == OPTEE_MSG_UID_2 && res.a3 == OPTEE_MSG_UID_3)
1239 		return true;
1240 	return false;
1241 }
1242 
1243 #ifdef CONFIG_OPTEE_INSECURE_LOAD_IMAGE
1244 static bool optee_msg_api_uid_is_optee_image_load(optee_invoke_fn *invoke_fn)
1245 {
1246 	struct arm_smccc_res res;
1247 
1248 	invoke_fn(OPTEE_SMC_CALLS_UID, 0, 0, 0, 0, 0, 0, 0, &res);
1249 
1250 	if (res.a0 == OPTEE_MSG_IMAGE_LOAD_UID_0 &&
1251 	    res.a1 == OPTEE_MSG_IMAGE_LOAD_UID_1 &&
1252 	    res.a2 == OPTEE_MSG_IMAGE_LOAD_UID_2 &&
1253 	    res.a3 == OPTEE_MSG_IMAGE_LOAD_UID_3)
1254 		return true;
1255 	return false;
1256 }
1257 #endif
1258 
1259 static void optee_msg_get_os_revision(optee_invoke_fn *invoke_fn)
1260 {
1261 	union {
1262 		struct arm_smccc_res smccc;
1263 		struct optee_smc_call_get_os_revision_result result;
1264 	} res = {
1265 		.result = {
1266 			.build_id = 0
1267 		}
1268 	};
1269 
1270 	invoke_fn(OPTEE_SMC_CALL_GET_OS_REVISION, 0, 0, 0, 0, 0, 0, 0,
1271 		  &res.smccc);
1272 
1273 	if (res.result.build_id)
1274 		pr_info("revision %lu.%lu (%08lx)", res.result.major,
1275 			res.result.minor, res.result.build_id);
1276 	else
1277 		pr_info("revision %lu.%lu", res.result.major, res.result.minor);
1278 }
1279 
1280 static bool optee_msg_api_revision_is_compatible(optee_invoke_fn *invoke_fn)
1281 {
1282 	union {
1283 		struct arm_smccc_res smccc;
1284 		struct optee_smc_calls_revision_result result;
1285 	} res;
1286 
1287 	invoke_fn(OPTEE_SMC_CALLS_REVISION, 0, 0, 0, 0, 0, 0, 0, &res.smccc);
1288 
1289 	if (res.result.major == OPTEE_MSG_REVISION_MAJOR &&
1290 	    (int)res.result.minor >= OPTEE_MSG_REVISION_MINOR)
1291 		return true;
1292 	return false;
1293 }
1294 
1295 static bool optee_msg_exchange_capabilities(optee_invoke_fn *invoke_fn,
1296 					    u32 *sec_caps, u32 *max_notif_value,
1297 					    unsigned int *rpc_param_count)
1298 {
1299 	union {
1300 		struct arm_smccc_res smccc;
1301 		struct optee_smc_exchange_capabilities_result result;
1302 	} res;
1303 	u32 a1 = 0;
1304 
1305 	/*
1306 	 * TODO This isn't enough to tell if it's UP system (from kernel
1307 	 * point of view) or not, is_smp() returns the information
1308 	 * needed, but can't be called directly from here.
1309 	 */
1310 	if (!IS_ENABLED(CONFIG_SMP) || nr_cpu_ids == 1)
1311 		a1 |= OPTEE_SMC_NSEC_CAP_UNIPROCESSOR;
1312 
1313 	invoke_fn(OPTEE_SMC_EXCHANGE_CAPABILITIES, a1, 0, 0, 0, 0, 0, 0,
1314 		  &res.smccc);
1315 
1316 	if (res.result.status != OPTEE_SMC_RETURN_OK)
1317 		return false;
1318 
1319 	*sec_caps = res.result.capabilities;
1320 	if (*sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF)
1321 		*max_notif_value = res.result.max_notif_value;
1322 	else
1323 		*max_notif_value = OPTEE_DEFAULT_MAX_NOTIF_VALUE;
1324 	if (*sec_caps & OPTEE_SMC_SEC_CAP_RPC_ARG)
1325 		*rpc_param_count = (u8)res.result.data;
1326 	else
1327 		*rpc_param_count = 0;
1328 
1329 	return true;
1330 }
1331 
1332 static unsigned int optee_msg_get_thread_count(optee_invoke_fn *invoke_fn)
1333 {
1334 	struct arm_smccc_res res;
1335 
1336 	invoke_fn(OPTEE_SMC_GET_THREAD_COUNT, 0, 0, 0, 0, 0, 0, 0, &res);
1337 	if (res.a0)
1338 		return 0;
1339 	return res.a1;
1340 }
1341 
1342 static struct tee_shm_pool *
1343 optee_config_shm_memremap(optee_invoke_fn *invoke_fn, void **memremaped_shm)
1344 {
1345 	union {
1346 		struct arm_smccc_res smccc;
1347 		struct optee_smc_get_shm_config_result result;
1348 	} res;
1349 	unsigned long vaddr;
1350 	phys_addr_t paddr;
1351 	size_t size;
1352 	phys_addr_t begin;
1353 	phys_addr_t end;
1354 	void *va;
1355 	void *rc;
1356 
1357 	invoke_fn(OPTEE_SMC_GET_SHM_CONFIG, 0, 0, 0, 0, 0, 0, 0, &res.smccc);
1358 	if (res.result.status != OPTEE_SMC_RETURN_OK) {
1359 		pr_err("static shm service not available\n");
1360 		return ERR_PTR(-ENOENT);
1361 	}
1362 
1363 	if (res.result.settings != OPTEE_SMC_SHM_CACHED) {
1364 		pr_err("only normal cached shared memory supported\n");
1365 		return ERR_PTR(-EINVAL);
1366 	}
1367 
1368 	begin = roundup(res.result.start, PAGE_SIZE);
1369 	end = rounddown(res.result.start + res.result.size, PAGE_SIZE);
1370 	paddr = begin;
1371 	size = end - begin;
1372 
1373 	va = memremap(paddr, size, MEMREMAP_WB);
1374 	if (!va) {
1375 		pr_err("shared memory ioremap failed\n");
1376 		return ERR_PTR(-EINVAL);
1377 	}
1378 	vaddr = (unsigned long)va;
1379 
1380 	rc = tee_shm_pool_alloc_res_mem(vaddr, paddr, size,
1381 					OPTEE_MIN_STATIC_POOL_ALIGN);
1382 	if (IS_ERR(rc))
1383 		memunmap(va);
1384 	else
1385 		*memremaped_shm = va;
1386 
1387 	return rc;
1388 }
1389 
1390 /* Simple wrapper functions to be able to use a function pointer */
1391 static void optee_smccc_smc(unsigned long a0, unsigned long a1,
1392 			    unsigned long a2, unsigned long a3,
1393 			    unsigned long a4, unsigned long a5,
1394 			    unsigned long a6, unsigned long a7,
1395 			    struct arm_smccc_res *res)
1396 {
1397 	arm_smccc_smc(a0, a1, a2, a3, a4, a5, a6, a7, res);
1398 }
1399 
1400 static void optee_smccc_hvc(unsigned long a0, unsigned long a1,
1401 			    unsigned long a2, unsigned long a3,
1402 			    unsigned long a4, unsigned long a5,
1403 			    unsigned long a6, unsigned long a7,
1404 			    struct arm_smccc_res *res)
1405 {
1406 	arm_smccc_hvc(a0, a1, a2, a3, a4, a5, a6, a7, res);
1407 }
1408 
1409 static optee_invoke_fn *get_invoke_func(struct device *dev)
1410 {
1411 	const char *method;
1412 
1413 	pr_info("probing for conduit method.\n");
1414 
1415 	if (device_property_read_string(dev, "method", &method)) {
1416 		pr_warn("missing \"method\" property\n");
1417 		return ERR_PTR(-ENXIO);
1418 	}
1419 
1420 	if (!strcmp("hvc", method))
1421 		return optee_smccc_hvc;
1422 	else if (!strcmp("smc", method))
1423 		return optee_smccc_smc;
1424 
1425 	pr_warn("invalid \"method\" property: %s\n", method);
1426 	return ERR_PTR(-EINVAL);
1427 }
1428 
1429 /* optee_remove - Device Removal Routine
1430  * @pdev: platform device information struct
1431  *
1432  * optee_remove is called by platform subsystem to alert the driver
1433  * that it should release the device
1434  */
1435 static void optee_smc_remove(struct platform_device *pdev)
1436 {
1437 	struct optee *optee = platform_get_drvdata(pdev);
1438 
1439 	/*
1440 	 * Ask OP-TEE to free all cached shared memory objects to decrease
1441 	 * reference counters and also avoid wild pointers in secure world
1442 	 * into the old shared memory range.
1443 	 */
1444 	if (!optee->rpc_param_count)
1445 		optee_disable_shm_cache(optee);
1446 
1447 	optee_smc_notif_uninit_irq(optee);
1448 
1449 	optee_remove_common(optee);
1450 
1451 	if (optee->smc.memremaped_shm)
1452 		memunmap(optee->smc.memremaped_shm);
1453 
1454 	kfree(optee);
1455 }
1456 
1457 /* optee_shutdown - Device Removal Routine
1458  * @pdev: platform device information struct
1459  *
1460  * platform_shutdown is called by the platform subsystem to alert
1461  * the driver that a shutdown, reboot, or kexec is happening and
1462  * device must be disabled.
1463  */
1464 static void optee_shutdown(struct platform_device *pdev)
1465 {
1466 	struct optee *optee = platform_get_drvdata(pdev);
1467 
1468 	if (!optee->rpc_param_count)
1469 		optee_disable_shm_cache(optee);
1470 }
1471 
1472 #ifdef CONFIG_OPTEE_INSECURE_LOAD_IMAGE
1473 
1474 #define OPTEE_FW_IMAGE "optee/tee.bin"
1475 
1476 static optee_invoke_fn *cpuhp_invoke_fn;
1477 
1478 static int optee_cpuhp_probe(unsigned int cpu)
1479 {
1480 	/*
1481 	 * Invoking a call on a CPU will cause OP-TEE to perform the required
1482 	 * setup for that CPU. Just invoke the call to get the UID since that
1483 	 * has no side effects.
1484 	 */
1485 	if (optee_msg_api_uid_is_optee_api(cpuhp_invoke_fn))
1486 		return 0;
1487 	else
1488 		return -EINVAL;
1489 }
1490 
1491 static int optee_load_fw(struct platform_device *pdev,
1492 			 optee_invoke_fn *invoke_fn)
1493 {
1494 	const struct firmware *fw = NULL;
1495 	struct arm_smccc_res res;
1496 	phys_addr_t data_pa;
1497 	u8 *data_buf = NULL;
1498 	u64 data_size;
1499 	u32 data_pa_high, data_pa_low;
1500 	u32 data_size_high, data_size_low;
1501 	int rc;
1502 	int hp_state;
1503 
1504 	if (!optee_msg_api_uid_is_optee_image_load(invoke_fn))
1505 		return 0;
1506 
1507 	rc = request_firmware(&fw, OPTEE_FW_IMAGE, &pdev->dev);
1508 	if (rc) {
1509 		/*
1510 		 * The firmware in the rootfs will not be accessible until we
1511 		 * are in the SYSTEM_RUNNING state, so return EPROBE_DEFER until
1512 		 * that point.
1513 		 */
1514 		if (system_state < SYSTEM_RUNNING)
1515 			return -EPROBE_DEFER;
1516 		goto fw_err;
1517 	}
1518 
1519 	data_size = fw->size;
1520 	/*
1521 	 * This uses the GFP_DMA flag to ensure we are allocated memory in the
1522 	 * 32-bit space since TF-A cannot map memory beyond the 32-bit boundary.
1523 	 */
1524 	data_buf = kmemdup(fw->data, fw->size, GFP_KERNEL | GFP_DMA);
1525 	if (!data_buf) {
1526 		rc = -ENOMEM;
1527 		goto fw_err;
1528 	}
1529 	data_pa = virt_to_phys(data_buf);
1530 	reg_pair_from_64(&data_pa_high, &data_pa_low, data_pa);
1531 	reg_pair_from_64(&data_size_high, &data_size_low, data_size);
1532 	goto fw_load;
1533 
1534 fw_err:
1535 	pr_warn("image loading failed\n");
1536 	data_pa_high = 0;
1537 	data_pa_low = 0;
1538 	data_size_high = 0;
1539 	data_size_low = 0;
1540 
1541 fw_load:
1542 	/*
1543 	 * Always invoke the SMC, even if loading the image fails, to indicate
1544 	 * to EL3 that we have passed the point where it should allow invoking
1545 	 * this SMC.
1546 	 */
1547 	pr_warn("OP-TEE image loaded from kernel, this can be insecure");
1548 	invoke_fn(OPTEE_SMC_CALL_LOAD_IMAGE, data_size_high, data_size_low,
1549 		  data_pa_high, data_pa_low, 0, 0, 0, &res);
1550 	if (!rc)
1551 		rc = res.a0;
1552 	if (fw)
1553 		release_firmware(fw);
1554 	kfree(data_buf);
1555 
1556 	if (!rc) {
1557 		/*
1558 		 * We need to initialize OP-TEE on all other running cores as
1559 		 * well. Any cores that aren't running yet will get initialized
1560 		 * when they are brought up by the power management functions in
1561 		 * TF-A which are registered by the OP-TEE SPD. Due to that we
1562 		 * can un-register the callback right after registering it.
1563 		 */
1564 		cpuhp_invoke_fn = invoke_fn;
1565 		hp_state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "optee:probe",
1566 					     optee_cpuhp_probe, NULL);
1567 		if (hp_state < 0) {
1568 			pr_warn("Failed with CPU hotplug setup for OP-TEE");
1569 			return -EINVAL;
1570 		}
1571 		cpuhp_remove_state(hp_state);
1572 		cpuhp_invoke_fn = NULL;
1573 	}
1574 
1575 	return rc;
1576 }
1577 #else
1578 static inline int optee_load_fw(struct platform_device *pdev,
1579 				optee_invoke_fn *invoke_fn)
1580 {
1581 	return 0;
1582 }
1583 #endif
1584 
1585 static int optee_probe(struct platform_device *pdev)
1586 {
1587 	optee_invoke_fn *invoke_fn;
1588 	struct tee_shm_pool *pool = ERR_PTR(-EINVAL);
1589 	struct optee *optee = NULL;
1590 	void *memremaped_shm = NULL;
1591 	unsigned int rpc_param_count;
1592 	unsigned int thread_count;
1593 	struct tee_device *teedev;
1594 	struct tee_context *ctx;
1595 	u32 max_notif_value;
1596 	u32 arg_cache_flags;
1597 	u32 sec_caps;
1598 	int rc;
1599 
1600 	invoke_fn = get_invoke_func(&pdev->dev);
1601 	if (IS_ERR(invoke_fn))
1602 		return PTR_ERR(invoke_fn);
1603 
1604 	rc = optee_load_fw(pdev, invoke_fn);
1605 	if (rc)
1606 		return rc;
1607 
1608 	if (!optee_msg_api_uid_is_optee_api(invoke_fn)) {
1609 		pr_warn("api uid mismatch\n");
1610 		return -EINVAL;
1611 	}
1612 
1613 	optee_msg_get_os_revision(invoke_fn);
1614 
1615 	if (!optee_msg_api_revision_is_compatible(invoke_fn)) {
1616 		pr_warn("api revision mismatch\n");
1617 		return -EINVAL;
1618 	}
1619 
1620 	thread_count = optee_msg_get_thread_count(invoke_fn);
1621 	if (!optee_msg_exchange_capabilities(invoke_fn, &sec_caps,
1622 					     &max_notif_value,
1623 					     &rpc_param_count)) {
1624 		pr_warn("capabilities mismatch\n");
1625 		return -EINVAL;
1626 	}
1627 
1628 	/*
1629 	 * Try to use dynamic shared memory if possible
1630 	 */
1631 	if (sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM) {
1632 		/*
1633 		 * If we have OPTEE_SMC_SEC_CAP_RPC_ARG we can ask
1634 		 * optee_get_msg_arg() to pre-register (by having
1635 		 * OPTEE_SHM_ARG_ALLOC_PRIV cleared) the page used to pass
1636 		 * an argument struct.
1637 		 *
1638 		 * With the page is pre-registered we can use a non-zero
1639 		 * offset for argument struct, this is indicated with
1640 		 * OPTEE_SHM_ARG_SHARED.
1641 		 *
1642 		 * This means that optee_smc_do_call_with_arg() will use
1643 		 * OPTEE_SMC_CALL_WITH_REGD_ARG for pre-registered pages.
1644 		 */
1645 		if (sec_caps & OPTEE_SMC_SEC_CAP_RPC_ARG)
1646 			arg_cache_flags = OPTEE_SHM_ARG_SHARED;
1647 		else
1648 			arg_cache_flags = OPTEE_SHM_ARG_ALLOC_PRIV;
1649 
1650 		pool = optee_shm_pool_alloc_pages();
1651 	}
1652 
1653 	/*
1654 	 * If dynamic shared memory is not available or failed - try static one
1655 	 */
1656 	if (IS_ERR(pool) && (sec_caps & OPTEE_SMC_SEC_CAP_HAVE_RESERVED_SHM)) {
1657 		/*
1658 		 * The static memory pool can use non-zero page offsets so
1659 		 * let optee_get_msg_arg() know that with OPTEE_SHM_ARG_SHARED.
1660 		 *
1661 		 * optee_get_msg_arg() should not pre-register the
1662 		 * allocated page used to pass an argument struct, this is
1663 		 * indicated with OPTEE_SHM_ARG_ALLOC_PRIV.
1664 		 *
1665 		 * This means that optee_smc_do_call_with_arg() will use
1666 		 * OPTEE_SMC_CALL_WITH_ARG if rpc_param_count is 0, else
1667 		 * OPTEE_SMC_CALL_WITH_RPC_ARG.
1668 		 */
1669 		arg_cache_flags = OPTEE_SHM_ARG_SHARED |
1670 				  OPTEE_SHM_ARG_ALLOC_PRIV;
1671 		pool = optee_config_shm_memremap(invoke_fn, &memremaped_shm);
1672 	}
1673 
1674 	if (IS_ERR(pool))
1675 		return PTR_ERR(pool);
1676 
1677 	optee = kzalloc(sizeof(*optee), GFP_KERNEL);
1678 	if (!optee) {
1679 		rc = -ENOMEM;
1680 		goto err_free_pool;
1681 	}
1682 
1683 	optee->ops = &optee_ops;
1684 	optee->smc.invoke_fn = invoke_fn;
1685 	optee->smc.sec_caps = sec_caps;
1686 	optee->rpc_param_count = rpc_param_count;
1687 
1688 	teedev = tee_device_alloc(&optee_clnt_desc, NULL, pool, optee);
1689 	if (IS_ERR(teedev)) {
1690 		rc = PTR_ERR(teedev);
1691 		goto err_free_optee;
1692 	}
1693 	optee->teedev = teedev;
1694 
1695 	teedev = tee_device_alloc(&optee_supp_desc, NULL, pool, optee);
1696 	if (IS_ERR(teedev)) {
1697 		rc = PTR_ERR(teedev);
1698 		goto err_unreg_teedev;
1699 	}
1700 	optee->supp_teedev = teedev;
1701 
1702 	rc = tee_device_register(optee->teedev);
1703 	if (rc)
1704 		goto err_unreg_supp_teedev;
1705 
1706 	rc = tee_device_register(optee->supp_teedev);
1707 	if (rc)
1708 		goto err_unreg_supp_teedev;
1709 
1710 	optee_cq_init(&optee->call_queue, thread_count);
1711 	optee_supp_init(&optee->supp);
1712 	optee->smc.memremaped_shm = memremaped_shm;
1713 	optee->pool = pool;
1714 	optee_shm_arg_cache_init(optee, arg_cache_flags);
1715 
1716 	platform_set_drvdata(pdev, optee);
1717 	ctx = teedev_open(optee->teedev);
1718 	if (IS_ERR(ctx)) {
1719 		rc = PTR_ERR(ctx);
1720 		goto err_supp_uninit;
1721 	}
1722 	optee->ctx = ctx;
1723 	rc = optee_notif_init(optee, max_notif_value);
1724 	if (rc)
1725 		goto err_close_ctx;
1726 
1727 	if (sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF) {
1728 		unsigned int irq;
1729 
1730 		rc = platform_get_irq(pdev, 0);
1731 		if (rc < 0) {
1732 			pr_err("platform_get_irq: ret %d\n", rc);
1733 			goto err_notif_uninit;
1734 		}
1735 		irq = rc;
1736 
1737 		rc = optee_smc_notif_init_irq(optee, irq);
1738 		if (rc) {
1739 			irq_dispose_mapping(irq);
1740 			goto err_notif_uninit;
1741 		}
1742 		enable_async_notif(optee->smc.invoke_fn);
1743 		pr_info("Asynchronous notifications enabled\n");
1744 	}
1745 
1746 	/*
1747 	 * Ensure that there are no pre-existing shm objects before enabling
1748 	 * the shm cache so that there's no chance of receiving an invalid
1749 	 * address during shutdown. This could occur, for example, if we're
1750 	 * kexec booting from an older kernel that did not properly cleanup the
1751 	 * shm cache.
1752 	 */
1753 	optee_disable_unmapped_shm_cache(optee);
1754 
1755 	/*
1756 	 * Only enable the shm cache in case we're not able to pass the RPC
1757 	 * arg struct right after the normal arg struct.
1758 	 */
1759 	if (!optee->rpc_param_count)
1760 		optee_enable_shm_cache(optee);
1761 
1762 	if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM)
1763 		pr_info("dynamic shared memory is enabled\n");
1764 
1765 	rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES);
1766 	if (rc)
1767 		goto err_disable_shm_cache;
1768 
1769 	pr_info("initialized driver\n");
1770 	return 0;
1771 
1772 err_disable_shm_cache:
1773 	if (!optee->rpc_param_count)
1774 		optee_disable_shm_cache(optee);
1775 	optee_smc_notif_uninit_irq(optee);
1776 	optee_unregister_devices();
1777 err_notif_uninit:
1778 	optee_notif_uninit(optee);
1779 err_close_ctx:
1780 	teedev_close_context(ctx);
1781 err_supp_uninit:
1782 	optee_shm_arg_cache_uninit(optee);
1783 	optee_supp_uninit(&optee->supp);
1784 	mutex_destroy(&optee->call_queue.mutex);
1785 err_unreg_supp_teedev:
1786 	tee_device_unregister(optee->supp_teedev);
1787 err_unreg_teedev:
1788 	tee_device_unregister(optee->teedev);
1789 err_free_optee:
1790 	kfree(optee);
1791 err_free_pool:
1792 	tee_shm_pool_free(pool);
1793 	if (memremaped_shm)
1794 		memunmap(memremaped_shm);
1795 	return rc;
1796 }
1797 
1798 static const struct of_device_id optee_dt_match[] = {
1799 	{ .compatible = "linaro,optee-tz" },
1800 	{},
1801 };
1802 MODULE_DEVICE_TABLE(of, optee_dt_match);
1803 
1804 static struct platform_driver optee_driver = {
1805 	.probe  = optee_probe,
1806 	.remove_new = optee_smc_remove,
1807 	.shutdown = optee_shutdown,
1808 	.driver = {
1809 		.name = "optee",
1810 		.of_match_table = optee_dt_match,
1811 	},
1812 };
1813 
1814 int optee_smc_abi_register(void)
1815 {
1816 	return platform_driver_register(&optee_driver);
1817 }
1818 
1819 void optee_smc_abi_unregister(void)
1820 {
1821 	platform_driver_unregister(&optee_driver);
1822 }
1823