xref: /optee_os/core/kernel/tee_ta_manager.c (revision b56ad90ebd7ed7f913ba88d03fcbcdac8962c7bd)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, STMicroelectronics International N.V.
4  * Copyright (c) 2020, Arm Limited
5  */
6 
7 #include <arm.h>
8 #include <assert.h>
9 #include <kernel/mutex.h>
10 #include <kernel/panic.h>
11 #include <kernel/pseudo_ta.h>
12 #include <kernel/stmm_sp.h>
13 #include <kernel/tee_common.h>
14 #include <kernel/tee_misc.h>
15 #include <kernel/tee_ta_manager.h>
16 #include <kernel/tee_time.h>
17 #include <kernel/thread.h>
18 #include <kernel/user_mode_ctx.h>
19 #include <kernel/user_ta.h>
20 #include <mm/core_memprot.h>
21 #include <mm/core_mmu.h>
22 #include <mm/mobj.h>
23 #include <mm/vm.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <tee_api_types.h>
28 #include <tee/entry_std.h>
29 #include <tee/tee_obj.h>
30 #include <tee/tee_svc_cryp.h>
31 #include <tee/tee_svc_storage.h>
32 #include <trace.h>
33 #include <types_ext.h>
34 #include <user_ta_header.h>
35 #include <utee_types.h>
36 #include <util.h>
37 
38 /* This mutex protects the critical section in tee_ta_init_session */
39 struct mutex tee_ta_mutex = MUTEX_INITIALIZER;
40 /* This condvar is used when waiting for a TA context to become initialized */
41 struct condvar tee_ta_init_cv = CONDVAR_INITIALIZER;
42 struct tee_ta_ctx_head tee_ctxes = TAILQ_HEAD_INITIALIZER(tee_ctxes);
43 
44 #ifndef CFG_CONCURRENT_SINGLE_INSTANCE_TA
45 static struct condvar tee_ta_cv = CONDVAR_INITIALIZER;
46 static short int tee_ta_single_instance_thread = THREAD_ID_INVALID;
47 static size_t tee_ta_single_instance_count;
48 #endif
49 
50 #ifdef CFG_CONCURRENT_SINGLE_INSTANCE_TA
51 static void lock_single_instance(void)
52 {
53 }
54 
55 static void unlock_single_instance(void)
56 {
57 }
58 
59 static bool has_single_instance_lock(void)
60 {
61 	return false;
62 }
63 #else
64 static void lock_single_instance(void)
65 {
66 	/* Requires tee_ta_mutex to be held */
67 	if (tee_ta_single_instance_thread != thread_get_id()) {
68 		/* Wait until the single-instance lock is available. */
69 		while (tee_ta_single_instance_thread != THREAD_ID_INVALID)
70 			condvar_wait(&tee_ta_cv, &tee_ta_mutex);
71 
72 		tee_ta_single_instance_thread = thread_get_id();
73 		assert(tee_ta_single_instance_count == 0);
74 	}
75 
76 	tee_ta_single_instance_count++;
77 }
78 
79 static void unlock_single_instance(void)
80 {
81 	/* Requires tee_ta_mutex to be held */
82 	assert(tee_ta_single_instance_thread == thread_get_id());
83 	assert(tee_ta_single_instance_count > 0);
84 
85 	tee_ta_single_instance_count--;
86 	if (tee_ta_single_instance_count == 0) {
87 		tee_ta_single_instance_thread = THREAD_ID_INVALID;
88 		condvar_signal(&tee_ta_cv);
89 	}
90 }
91 
92 static bool has_single_instance_lock(void)
93 {
94 	/* Requires tee_ta_mutex to be held */
95 	return tee_ta_single_instance_thread == thread_get_id();
96 }
97 #endif
98 
99 struct tee_ta_session *__noprof to_ta_session(struct ts_session *sess)
100 {
101 	assert(is_ta_ctx(sess->ctx) || is_stmm_ctx(sess->ctx));
102 	return container_of(sess, struct tee_ta_session, ts_sess);
103 }
104 
105 static struct tee_ta_ctx *ts_to_ta_ctx(struct ts_ctx *ctx)
106 {
107 	if (is_ta_ctx(ctx))
108 		return to_ta_ctx(ctx);
109 
110 	if (is_stmm_ctx(ctx))
111 		return &(to_stmm_ctx(ctx)->ta_ctx);
112 
113 	panic("bad context");
114 }
115 
116 static bool tee_ta_try_set_busy(struct tee_ta_ctx *ctx)
117 {
118 	bool rc = true;
119 
120 	if (ctx->flags & TA_FLAG_CONCURRENT)
121 		return true;
122 
123 	mutex_lock(&tee_ta_mutex);
124 
125 	if (ctx->flags & TA_FLAG_SINGLE_INSTANCE)
126 		lock_single_instance();
127 
128 	if (has_single_instance_lock()) {
129 		if (ctx->busy) {
130 			/*
131 			 * We're holding the single-instance lock and the
132 			 * TA is busy, as waiting now would only cause a
133 			 * dead-lock, we release the lock and return false.
134 			 */
135 			rc = false;
136 			if (ctx->flags & TA_FLAG_SINGLE_INSTANCE)
137 				unlock_single_instance();
138 		}
139 	} else {
140 		/*
141 		 * We're not holding the single-instance lock, we're free to
142 		 * wait for the TA to become available.
143 		 */
144 		while (ctx->busy)
145 			condvar_wait(&ctx->busy_cv, &tee_ta_mutex);
146 	}
147 
148 	/* Either it's already true or we should set it to true */
149 	ctx->busy = true;
150 
151 	mutex_unlock(&tee_ta_mutex);
152 	return rc;
153 }
154 
155 static void tee_ta_set_busy(struct tee_ta_ctx *ctx)
156 {
157 	if (!tee_ta_try_set_busy(ctx))
158 		panic();
159 }
160 
161 static void tee_ta_clear_busy(struct tee_ta_ctx *ctx)
162 {
163 	if (ctx->flags & TA_FLAG_CONCURRENT)
164 		return;
165 
166 	mutex_lock(&tee_ta_mutex);
167 
168 	assert(ctx->busy);
169 	ctx->busy = false;
170 	condvar_signal(&ctx->busy_cv);
171 
172 	if (!ctx->initializing && (ctx->flags & TA_FLAG_SINGLE_INSTANCE))
173 		unlock_single_instance();
174 
175 	ctx->initializing = false;
176 
177 	mutex_unlock(&tee_ta_mutex);
178 }
179 
180 static void dec_session_ref_count(struct tee_ta_session *s)
181 {
182 	assert(s->ref_count > 0);
183 	s->ref_count--;
184 	if (s->ref_count == 1)
185 		condvar_signal(&s->refc_cv);
186 }
187 
188 void tee_ta_put_session(struct tee_ta_session *s)
189 {
190 	mutex_lock(&tee_ta_mutex);
191 
192 	if (s->lock_thread == thread_get_id()) {
193 		s->lock_thread = THREAD_ID_INVALID;
194 		condvar_signal(&s->lock_cv);
195 	}
196 	dec_session_ref_count(s);
197 
198 	mutex_unlock(&tee_ta_mutex);
199 }
200 
201 static struct tee_ta_session *tee_ta_find_session_nolock(uint32_t id,
202 			struct tee_ta_session_head *open_sessions)
203 {
204 	struct tee_ta_session *s = NULL;
205 	struct tee_ta_session *found = NULL;
206 
207 	TAILQ_FOREACH(s, open_sessions, link) {
208 		if (s->id == id) {
209 			found = s;
210 			break;
211 		}
212 	}
213 
214 	return found;
215 }
216 
217 struct tee_ta_session *tee_ta_find_session(uint32_t id,
218 			struct tee_ta_session_head *open_sessions)
219 {
220 	struct tee_ta_session *s = NULL;
221 
222 	mutex_lock(&tee_ta_mutex);
223 
224 	s = tee_ta_find_session_nolock(id, open_sessions);
225 
226 	mutex_unlock(&tee_ta_mutex);
227 
228 	return s;
229 }
230 
231 struct tee_ta_session *tee_ta_get_session(uint32_t id, bool exclusive,
232 			struct tee_ta_session_head *open_sessions)
233 {
234 	struct tee_ta_session *s;
235 
236 	mutex_lock(&tee_ta_mutex);
237 
238 	while (true) {
239 		s = tee_ta_find_session_nolock(id, open_sessions);
240 		if (!s)
241 			break;
242 		if (s->unlink) {
243 			s = NULL;
244 			break;
245 		}
246 		s->ref_count++;
247 		if (!exclusive)
248 			break;
249 
250 		assert(s->lock_thread != thread_get_id());
251 
252 		while (s->lock_thread != THREAD_ID_INVALID && !s->unlink)
253 			condvar_wait(&s->lock_cv, &tee_ta_mutex);
254 
255 		if (s->unlink) {
256 			dec_session_ref_count(s);
257 			s = NULL;
258 			break;
259 		}
260 
261 		s->lock_thread = thread_get_id();
262 		break;
263 	}
264 
265 	mutex_unlock(&tee_ta_mutex);
266 	return s;
267 }
268 
269 static void tee_ta_unlink_session(struct tee_ta_session *s,
270 			struct tee_ta_session_head *open_sessions)
271 {
272 	mutex_lock(&tee_ta_mutex);
273 
274 	assert(s->ref_count >= 1);
275 	assert(s->lock_thread == thread_get_id());
276 	assert(!s->unlink);
277 
278 	s->unlink = true;
279 	condvar_broadcast(&s->lock_cv);
280 
281 	while (s->ref_count != 1)
282 		condvar_wait(&s->refc_cv, &tee_ta_mutex);
283 
284 	TAILQ_REMOVE(open_sessions, s, link);
285 
286 	mutex_unlock(&tee_ta_mutex);
287 }
288 
289 static void destroy_session(struct tee_ta_session *s,
290 			    struct tee_ta_session_head *open_sessions)
291 {
292 #if defined(CFG_FTRACE_SUPPORT)
293 	if (s->ts_sess.ctx && s->ts_sess.ctx->ops->dump_ftrace) {
294 		ts_push_current_session(&s->ts_sess);
295 		s->ts_sess.fbuf = NULL;
296 		s->ts_sess.ctx->ops->dump_ftrace(s->ts_sess.ctx);
297 		ts_pop_current_session();
298 	}
299 #endif
300 
301 	tee_ta_unlink_session(s, open_sessions);
302 #if defined(CFG_TA_GPROF_SUPPORT)
303 	free(s->ts_sess.sbuf);
304 #endif
305 	free(s);
306 }
307 
308 static void destroy_context(struct tee_ta_ctx *ctx)
309 {
310 	DMSG("Destroy TA ctx (0x%" PRIxVA ")",  (vaddr_t)ctx);
311 
312 	condvar_destroy(&ctx->busy_cv);
313 	pgt_flush_ctx(&ctx->ts_ctx);
314 	ctx->ts_ctx.ops->destroy(&ctx->ts_ctx);
315 }
316 
317 static void destroy_ta_ctx_from_session(struct tee_ta_session *s)
318 {
319 	struct tee_ta_session *sess = NULL;
320 	struct tee_ta_session_head *open_sessions = NULL;
321 	struct tee_ta_ctx *ctx = NULL;
322 	struct user_ta_ctx *utc = NULL;
323 	struct ts_ctx *ts_ctx = s->ts_sess.ctx;
324 	size_t count = 1; /* start counting the references to the context */
325 
326 	DMSG("Remove references to context (%#"PRIxVA")", (vaddr_t)ts_ctx);
327 
328 	mutex_lock(&tee_ta_mutex);
329 	nsec_sessions_list_head(&open_sessions);
330 
331 	/*
332 	 * Next two loops will remove all references to the context which is
333 	 * about to be destroyed, but avoiding such operation to the current
334 	 * session. That will be done later in this function, only after
335 	 * the context will be properly destroyed.
336 	 */
337 
338 	/*
339 	 * Scan the entire list of opened sessions by the clients from
340 	 * non-secure world.
341 	 */
342 	TAILQ_FOREACH(sess, open_sessions, link) {
343 		if (sess->ts_sess.ctx == ts_ctx && sess != s) {
344 			sess->ts_sess.ctx = NULL;
345 			count++;
346 		}
347 	}
348 
349 	/*
350 	 * Scan all sessions opened from secure side by searching through
351 	 * all available TA instances and for each context, scan all opened
352 	 * sessions.
353 	 */
354 	TAILQ_FOREACH(ctx, &tee_ctxes, link) {
355 		if (is_user_ta_ctx(&ctx->ts_ctx)) {
356 			utc = to_user_ta_ctx(&ctx->ts_ctx);
357 
358 			TAILQ_FOREACH(sess, &utc->open_sessions, link) {
359 				if (sess->ts_sess.ctx == ts_ctx &&
360 				    sess != s) {
361 					sess->ts_sess.ctx = NULL;
362 					count++;
363 				}
364 			}
365 		}
366 	}
367 
368 	ctx = ts_to_ta_ctx(ts_ctx);
369 	assert(count == ctx->ref_count);
370 
371 	TAILQ_REMOVE(&tee_ctxes, ctx, link);
372 	mutex_unlock(&tee_ta_mutex);
373 
374 	destroy_context(ctx);
375 	s->ts_sess.ctx = NULL;
376 }
377 
378 /*
379  * tee_ta_context_find - Find TA in session list based on a UUID (input)
380  * Returns a pointer to the session
381  */
382 static struct tee_ta_ctx *tee_ta_context_find(const TEE_UUID *uuid)
383 {
384 	struct tee_ta_ctx *ctx;
385 
386 	TAILQ_FOREACH(ctx, &tee_ctxes, link) {
387 		if (memcmp(&ctx->ts_ctx.uuid, uuid, sizeof(TEE_UUID)) == 0)
388 			return ctx;
389 	}
390 
391 	return NULL;
392 }
393 
394 /* check if requester (client ID) matches session initial client */
395 static TEE_Result check_client(struct tee_ta_session *s, const TEE_Identity *id)
396 {
397 	if (id == KERN_IDENTITY)
398 		return TEE_SUCCESS;
399 
400 	if (id == NSAPP_IDENTITY) {
401 		if (s->clnt_id.login == TEE_LOGIN_TRUSTED_APP) {
402 			DMSG("nsec tries to hijack TA session");
403 			return TEE_ERROR_ACCESS_DENIED;
404 		}
405 		return TEE_SUCCESS;
406 	}
407 
408 	if (memcmp(&s->clnt_id, id, sizeof(TEE_Identity)) != 0) {
409 		DMSG("client id mismatch");
410 		return TEE_ERROR_ACCESS_DENIED;
411 	}
412 	return TEE_SUCCESS;
413 }
414 
415 /*
416  * Check if invocation parameters matches TA properties
417  *
418  * @s - current session handle
419  * @param - already identified memory references hold a valid 'mobj'.
420  *
421  * Policy:
422  * - All TAs can access 'non-secure' shared memory.
423  * - All TAs can access TEE private memory (seccpy)
424  * - Only SDP flagged TAs can accept SDP memory references.
425  */
426 #ifndef CFG_SECURE_DATA_PATH
427 static bool check_params(struct tee_ta_session *sess __unused,
428 			 struct tee_ta_param *param __unused)
429 {
430 	/*
431 	 * When CFG_SECURE_DATA_PATH is not enabled, SDP memory references
432 	 * are rejected at OP-TEE core entry. Hence here all TAs have same
433 	 * permissions regarding memory reference parameters.
434 	 */
435 	return true;
436 }
437 #else
438 static bool check_params(struct tee_ta_session *sess,
439 			 struct tee_ta_param *param)
440 {
441 	int n;
442 
443 	/*
444 	 * When CFG_SECURE_DATA_PATH is enabled, OP-TEE entry allows SHM and
445 	 * SDP memory references. Only TAs flagged SDP can access SDP memory.
446 	 */
447 	if (sess->ts_sess.ctx &&
448 	    ts_to_ta_ctx(sess->ts_sess.ctx)->flags & TA_FLAG_SECURE_DATA_PATH)
449 		return true;
450 
451 	for (n = 0; n < TEE_NUM_PARAMS; n++) {
452 		uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
453 		struct param_mem *mem = &param->u[n].mem;
454 
455 		if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
456 		    param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
457 		    param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
458 			continue;
459 		if (!mem->size)
460 			continue;
461 		if (mobj_is_sdp_mem(mem->mobj))
462 			return false;
463 	}
464 	return true;
465 }
466 #endif
467 
468 static void set_invoke_timeout(struct tee_ta_session *sess,
469 				      uint32_t cancel_req_to)
470 {
471 	TEE_Time current_time;
472 	TEE_Time cancel_time;
473 
474 	if (cancel_req_to == TEE_TIMEOUT_INFINITE)
475 		goto infinite;
476 
477 	if (tee_time_get_sys_time(&current_time) != TEE_SUCCESS)
478 		goto infinite;
479 
480 	if (ADD_OVERFLOW(current_time.seconds, cancel_req_to / 1000,
481 			 &cancel_time.seconds))
482 		goto infinite;
483 
484 	cancel_time.millis = current_time.millis + cancel_req_to % 1000;
485 	if (cancel_time.millis > 1000) {
486 		if (ADD_OVERFLOW(current_time.seconds, 1,
487 				 &cancel_time.seconds))
488 			goto infinite;
489 
490 		cancel_time.seconds++;
491 		cancel_time.millis -= 1000;
492 	}
493 
494 	sess->cancel_time = cancel_time;
495 	return;
496 
497 infinite:
498 	sess->cancel_time.seconds = UINT32_MAX;
499 	sess->cancel_time.millis = UINT32_MAX;
500 }
501 
502 /*-----------------------------------------------------------------------------
503  * Close a Trusted Application and free available resources
504  *---------------------------------------------------------------------------*/
505 TEE_Result tee_ta_close_session(struct tee_ta_session *csess,
506 				struct tee_ta_session_head *open_sessions,
507 				const TEE_Identity *clnt_id)
508 {
509 	struct tee_ta_session *sess = NULL;
510 	struct tee_ta_ctx *ctx = NULL;
511 	struct ts_ctx *ts_ctx = NULL;
512 	bool keep_alive = false;
513 
514 	DMSG("csess 0x%" PRIxVA " id %u",
515 	     (vaddr_t)csess, csess ? csess->id : UINT_MAX);
516 
517 	if (!csess)
518 		return TEE_ERROR_ITEM_NOT_FOUND;
519 
520 	sess = tee_ta_get_session(csess->id, true, open_sessions);
521 
522 	if (!sess) {
523 		EMSG("session 0x%" PRIxVA " to be removed is not found",
524 		     (vaddr_t)csess);
525 		return TEE_ERROR_ITEM_NOT_FOUND;
526 	}
527 
528 	if (check_client(sess, clnt_id) != TEE_SUCCESS) {
529 		tee_ta_put_session(sess);
530 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
531 	}
532 
533 	DMSG("Destroy session");
534 
535 	ts_ctx = sess->ts_sess.ctx;
536 	if (!ts_ctx) {
537 		destroy_session(sess, open_sessions);
538 		return TEE_SUCCESS;
539 	}
540 
541 	ctx = ts_to_ta_ctx(ts_ctx);
542 	if (ctx->panicked) {
543 		destroy_session(sess, open_sessions);
544 	} else {
545 		tee_ta_set_busy(ctx);
546 		set_invoke_timeout(sess, TEE_TIMEOUT_INFINITE);
547 		ts_ctx->ops->enter_close_session(&sess->ts_sess);
548 		destroy_session(sess, open_sessions);
549 		tee_ta_clear_busy(ctx);
550 	}
551 
552 	mutex_lock(&tee_ta_mutex);
553 
554 	if (ctx->ref_count <= 0)
555 		panic();
556 
557 	ctx->ref_count--;
558 	keep_alive = (ctx->flags & TA_FLAG_INSTANCE_KEEP_ALIVE) &&
559 			(ctx->flags & TA_FLAG_SINGLE_INSTANCE);
560 	if (!ctx->ref_count && !keep_alive) {
561 		TAILQ_REMOVE(&tee_ctxes, ctx, link);
562 		mutex_unlock(&tee_ta_mutex);
563 
564 		destroy_context(ctx);
565 	} else
566 		mutex_unlock(&tee_ta_mutex);
567 
568 	return TEE_SUCCESS;
569 }
570 
571 static TEE_Result tee_ta_init_session_with_context(struct tee_ta_session *s,
572 						   const TEE_UUID *uuid)
573 {
574 	struct tee_ta_ctx *ctx = NULL;
575 
576 	while (true) {
577 		ctx = tee_ta_context_find(uuid);
578 		if (!ctx)
579 			return TEE_ERROR_ITEM_NOT_FOUND;
580 
581 		if (!is_user_ta_ctx(&ctx->ts_ctx) ||
582 		    !to_user_ta_ctx(&ctx->ts_ctx)->uctx.is_initializing)
583 			break;
584 		/*
585 		 * Context is still initializing, wait here until it's
586 		 * fully initialized. Note that we're searching for the
587 		 * context again since it may have been removed while we
588 		 * where sleeping.
589 		 */
590 		condvar_wait(&tee_ta_init_cv, &tee_ta_mutex);
591 	}
592 
593 	/*
594 	 * If TA isn't single instance it should be loaded as new
595 	 * instance instead of doing anything with this instance.
596 	 * So tell the caller that we didn't find the TA it the
597 	 * caller will load a new instance.
598 	 */
599 	if ((ctx->flags & TA_FLAG_SINGLE_INSTANCE) == 0)
600 		return TEE_ERROR_ITEM_NOT_FOUND;
601 
602 	/*
603 	 * The TA is single instance, if it isn't multi session we
604 	 * can't create another session unless its reference is zero
605 	 */
606 	if (!(ctx->flags & TA_FLAG_MULTI_SESSION) && ctx->ref_count)
607 		return TEE_ERROR_BUSY;
608 
609 	DMSG("Re-open TA %pUl", (void *)&ctx->ts_ctx.uuid);
610 
611 	ctx->ref_count++;
612 	s->ts_sess.ctx = &ctx->ts_ctx;
613 	return TEE_SUCCESS;
614 }
615 
616 static uint32_t new_session_id(struct tee_ta_session_head *open_sessions)
617 {
618 	struct tee_ta_session *last = NULL;
619 	uint32_t saved = 0;
620 	uint32_t id = 1;
621 
622 	last = TAILQ_LAST(open_sessions, tee_ta_session_head);
623 	if (last) {
624 		/* This value is less likely to be already used */
625 		id = last->id + 1;
626 		if (!id)
627 			id++; /* 0 is not valid */
628 	}
629 
630 	saved = id;
631 	do {
632 		if (!tee_ta_find_session_nolock(id, open_sessions))
633 			return id;
634 		id++;
635 		if (!id)
636 			id++;
637 	} while (id != saved);
638 
639 	return 0;
640 }
641 
642 static TEE_Result tee_ta_init_session(TEE_ErrorOrigin *err,
643 				struct tee_ta_session_head *open_sessions,
644 				const TEE_UUID *uuid,
645 				struct tee_ta_session **sess)
646 {
647 	TEE_Result res;
648 	struct tee_ta_session *s = calloc(1, sizeof(struct tee_ta_session));
649 
650 	*err = TEE_ORIGIN_TEE;
651 	if (!s)
652 		return TEE_ERROR_OUT_OF_MEMORY;
653 
654 	s->cancel_mask = true;
655 	condvar_init(&s->refc_cv);
656 	condvar_init(&s->lock_cv);
657 	s->lock_thread = THREAD_ID_INVALID;
658 	s->ref_count = 1;
659 
660 	mutex_lock(&tee_ta_mutex);
661 	s->id = new_session_id(open_sessions);
662 	if (!s->id) {
663 		res = TEE_ERROR_OVERFLOW;
664 		goto err_mutex_unlock;
665 	}
666 
667 	TAILQ_INSERT_TAIL(open_sessions, s, link);
668 
669 	/* Look for already loaded TA */
670 	res = tee_ta_init_session_with_context(s, uuid);
671 	mutex_unlock(&tee_ta_mutex);
672 	if (res == TEE_SUCCESS || res != TEE_ERROR_ITEM_NOT_FOUND)
673 		goto out;
674 
675 	/* Look for secure partition */
676 	res = stmm_init_session(uuid, s);
677 	if (res == TEE_SUCCESS || res != TEE_ERROR_ITEM_NOT_FOUND)
678 		goto out;
679 
680 	/* Look for pseudo TA */
681 	res = tee_ta_init_pseudo_ta_session(uuid, s);
682 	if (res == TEE_SUCCESS || res != TEE_ERROR_ITEM_NOT_FOUND)
683 		goto out;
684 
685 	/* Look for user TA */
686 	res = tee_ta_init_user_ta_session(uuid, s);
687 
688 out:
689 	if (!res) {
690 		*sess = s;
691 		return TEE_SUCCESS;
692 	}
693 
694 	mutex_lock(&tee_ta_mutex);
695 	TAILQ_REMOVE(open_sessions, s, link);
696 err_mutex_unlock:
697 	mutex_unlock(&tee_ta_mutex);
698 	free(s);
699 	return res;
700 }
701 
702 TEE_Result tee_ta_open_session(TEE_ErrorOrigin *err,
703 			       struct tee_ta_session **sess,
704 			       struct tee_ta_session_head *open_sessions,
705 			       const TEE_UUID *uuid,
706 			       const TEE_Identity *clnt_id,
707 			       uint32_t cancel_req_to,
708 			       struct tee_ta_param *param)
709 {
710 	TEE_Result res = TEE_SUCCESS;
711 	struct tee_ta_session *s = NULL;
712 	struct tee_ta_ctx *ctx = NULL;
713 	struct ts_ctx *ts_ctx = NULL;
714 	bool panicked = false;
715 	bool was_busy = false;
716 
717 	res = tee_ta_init_session(err, open_sessions, uuid, &s);
718 	if (res != TEE_SUCCESS) {
719 		DMSG("init session failed 0x%x", res);
720 		return res;
721 	}
722 
723 	if (!check_params(s, param))
724 		return TEE_ERROR_BAD_PARAMETERS;
725 
726 	ts_ctx = s->ts_sess.ctx;
727 	if (ts_ctx)
728 		ctx = ts_to_ta_ctx(ts_ctx);
729 
730 	if (!ctx || ctx->panicked) {
731 		DMSG("panicked, call tee_ta_close_session()");
732 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
733 		*err = TEE_ORIGIN_TEE;
734 		return TEE_ERROR_TARGET_DEAD;
735 	}
736 
737 	*sess = s;
738 	/* Save identity of the owner of the session */
739 	s->clnt_id = *clnt_id;
740 
741 	if (tee_ta_try_set_busy(ctx)) {
742 		s->param = param;
743 		set_invoke_timeout(s, cancel_req_to);
744 		res = ts_ctx->ops->enter_open_session(&s->ts_sess);
745 		tee_ta_clear_busy(ctx);
746 	} else {
747 		/* Deadlock avoided */
748 		res = TEE_ERROR_BUSY;
749 		was_busy = true;
750 	}
751 
752 	panicked = ctx->panicked;
753 	s->param = NULL;
754 
755 	tee_ta_put_session(s);
756 	if (panicked || (res != TEE_SUCCESS))
757 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
758 
759 	/*
760 	 * Origin error equal to TEE_ORIGIN_TRUSTED_APP for "regular" error,
761 	 * apart from panicking.
762 	 */
763 	if (panicked || was_busy)
764 		*err = TEE_ORIGIN_TEE;
765 	else
766 		*err = s->err_origin;
767 
768 	if (res != TEE_SUCCESS)
769 		EMSG("Failed. Return error 0x%x", res);
770 
771 	return res;
772 }
773 
774 TEE_Result tee_ta_invoke_command(TEE_ErrorOrigin *err,
775 				 struct tee_ta_session *sess,
776 				 const TEE_Identity *clnt_id,
777 				 uint32_t cancel_req_to, uint32_t cmd,
778 				 struct tee_ta_param *param)
779 {
780 	struct tee_ta_ctx *ta_ctx = NULL;
781 	struct ts_ctx *ts_ctx = NULL;
782 	TEE_Result res = TEE_SUCCESS;
783 
784 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
785 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
786 
787 	if (!check_params(sess, param))
788 		return TEE_ERROR_BAD_PARAMETERS;
789 
790 	ts_ctx = sess->ts_sess.ctx;
791 	if (!ts_ctx) {
792 		/* The context has been already destroyed */
793 		*err = TEE_ORIGIN_TEE;
794 		return TEE_ERROR_TARGET_DEAD;
795 	}
796 
797 	ta_ctx = ts_to_ta_ctx(ts_ctx);
798 	if (ta_ctx->panicked) {
799 		DMSG("Panicked !");
800 		destroy_ta_ctx_from_session(sess);
801 		*err = TEE_ORIGIN_TEE;
802 		return TEE_ERROR_TARGET_DEAD;
803 	}
804 
805 	tee_ta_set_busy(ta_ctx);
806 
807 	sess->param = param;
808 	set_invoke_timeout(sess, cancel_req_to);
809 	res = ts_ctx->ops->enter_invoke_cmd(&sess->ts_sess, cmd);
810 
811 	sess->param = NULL;
812 	tee_ta_clear_busy(ta_ctx);
813 
814 	if (ta_ctx->panicked) {
815 		destroy_ta_ctx_from_session(sess);
816 		*err = TEE_ORIGIN_TEE;
817 		return TEE_ERROR_TARGET_DEAD;
818 	}
819 
820 	*err = sess->err_origin;
821 
822 	/* Short buffer is not an effective error case */
823 	if (res != TEE_SUCCESS && res != TEE_ERROR_SHORT_BUFFER)
824 		DMSG("Error: %x of %d", res, *err);
825 
826 	return res;
827 }
828 
829 TEE_Result tee_ta_cancel_command(TEE_ErrorOrigin *err,
830 				 struct tee_ta_session *sess,
831 				 const TEE_Identity *clnt_id)
832 {
833 	*err = TEE_ORIGIN_TEE;
834 
835 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
836 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
837 
838 	sess->cancel = true;
839 	return TEE_SUCCESS;
840 }
841 
842 bool tee_ta_session_is_cancelled(struct tee_ta_session *s, TEE_Time *curr_time)
843 {
844 	TEE_Time current_time;
845 
846 	if (s->cancel_mask)
847 		return false;
848 
849 	if (s->cancel)
850 		return true;
851 
852 	if (s->cancel_time.seconds == UINT32_MAX)
853 		return false;
854 
855 	if (curr_time != NULL)
856 		current_time = *curr_time;
857 	else if (tee_time_get_sys_time(&current_time) != TEE_SUCCESS)
858 		return false;
859 
860 	if (current_time.seconds > s->cancel_time.seconds ||
861 	    (current_time.seconds == s->cancel_time.seconds &&
862 	     current_time.millis >= s->cancel_time.millis)) {
863 		return true;
864 	}
865 
866 	return false;
867 }
868 
869 #if defined(CFG_TA_GPROF_SUPPORT)
870 void tee_ta_gprof_sample_pc(vaddr_t pc)
871 {
872 	struct ts_session *s = ts_get_current_session();
873 	struct user_ta_ctx *utc = NULL;
874 	struct sample_buf *sbuf = NULL;
875 	TEE_Result res = 0;
876 	size_t idx = 0;
877 
878 	sbuf = s->sbuf;
879 	if (!sbuf || !sbuf->enabled)
880 		return; /* PC sampling is not enabled */
881 
882 	idx = (((uint64_t)pc - sbuf->offset)/2 * sbuf->scale)/65536;
883 	if (idx < sbuf->nsamples) {
884 		utc = to_user_ta_ctx(s->ctx);
885 		res = vm_check_access_rights(&utc->uctx,
886 					     TEE_MEMORY_ACCESS_READ |
887 					     TEE_MEMORY_ACCESS_WRITE |
888 					     TEE_MEMORY_ACCESS_ANY_OWNER,
889 					     (uaddr_t)&sbuf->samples[idx],
890 					     sizeof(*sbuf->samples));
891 		if (res != TEE_SUCCESS)
892 			return;
893 		sbuf->samples[idx]++;
894 	}
895 	sbuf->count++;
896 }
897 
898 static void gprof_update_session_utime(bool suspend, struct ts_session *s,
899 				       uint64_t now)
900 {
901 	struct sample_buf *sbuf = s->sbuf;
902 
903 	if (!sbuf)
904 		return;
905 
906 	if (suspend) {
907 		assert(sbuf->usr_entered);
908 		sbuf->usr += now - sbuf->usr_entered;
909 		sbuf->usr_entered = 0;
910 	} else {
911 		assert(!sbuf->usr_entered);
912 		if (!now)
913 			now++; /* 0 is reserved */
914 		sbuf->usr_entered = now;
915 	}
916 }
917 
918 /*
919  * Update user-mode CPU time for the current session
920  * @suspend: true if session is being suspended (leaving user mode), false if
921  * it is resumed (entering user mode)
922  */
923 static void tee_ta_update_session_utime(bool suspend)
924 {
925 	struct ts_session *s = ts_get_current_session();
926 	uint64_t now = read_cntpct();
927 
928 	gprof_update_session_utime(suspend, s, now);
929 }
930 
931 void tee_ta_update_session_utime_suspend(void)
932 {
933 	tee_ta_update_session_utime(true);
934 }
935 
936 void tee_ta_update_session_utime_resume(void)
937 {
938 	tee_ta_update_session_utime(false);
939 }
940 #endif
941 
942 #if defined(CFG_FTRACE_SUPPORT)
943 static void ftrace_update_times(bool suspend)
944 {
945 	struct ts_session *s = ts_get_current_session();
946 	struct ftrace_buf *fbuf = NULL;
947 	uint64_t now = 0;
948 	uint32_t i = 0;
949 
950 	now = read_cntpct();
951 
952 	fbuf = s->fbuf;
953 	if (!fbuf)
954 		return;
955 
956 	if (suspend) {
957 		fbuf->suspend_time = now;
958 	} else {
959 		for (i = 0; i <= fbuf->ret_idx; i++)
960 			fbuf->begin_time[i] += now - fbuf->suspend_time;
961 	}
962 }
963 
964 void tee_ta_ftrace_update_times_suspend(void)
965 {
966 	ftrace_update_times(true);
967 }
968 
969 void tee_ta_ftrace_update_times_resume(void)
970 {
971 	ftrace_update_times(false);
972 }
973 #endif
974 
975 bool is_ta_ctx(struct ts_ctx *ctx)
976 {
977 	return is_user_ta_ctx(ctx) || is_pseudo_ta_ctx(ctx);
978 }
979