xref: /optee_os/core/kernel/tee_ta_manager.c (revision 1bb929836182ecb96d2d9d268daa807c67596396)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, STMicroelectronics International N.V.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright notice,
10  * this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <types_ext.h>
30 #include <stdbool.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <arm.h>
35 #include <assert.h>
36 #include <kernel/mutex.h>
37 #include <kernel/panic.h>
38 #include <kernel/pseudo_ta.h>
39 #include <kernel/tee_common.h>
40 #include <kernel/tee_misc.h>
41 #include <kernel/tee_ta_manager.h>
42 #include <kernel/tee_time.h>
43 #include <kernel/thread.h>
44 #include <kernel/user_ta.h>
45 #include <mm/core_mmu.h>
46 #include <mm/core_memprot.h>
47 #include <mm/mobj.h>
48 #include <mm/tee_mmu.h>
49 #include <tee/tee_svc_cryp.h>
50 #include <tee/tee_obj.h>
51 #include <tee/tee_svc_storage.h>
52 #include <tee_api_types.h>
53 #include <trace.h>
54 #include <utee_types.h>
55 #include <util.h>
56 
57 /* This mutex protects the critical section in tee_ta_init_session */
58 struct mutex tee_ta_mutex = MUTEX_INITIALIZER;
59 struct tee_ta_ctx_head tee_ctxes = TAILQ_HEAD_INITIALIZER(tee_ctxes);
60 
61 #ifndef CFG_CONCURRENT_SINGLE_INSTANCE_TA
62 static struct condvar tee_ta_cv = CONDVAR_INITIALIZER;
63 static int tee_ta_single_instance_thread = THREAD_ID_INVALID;
64 static size_t tee_ta_single_instance_count;
65 #endif
66 
67 #ifdef CFG_CONCURRENT_SINGLE_INSTANCE_TA
68 static void lock_single_instance(void)
69 {
70 }
71 
72 static void unlock_single_instance(void)
73 {
74 }
75 
76 static bool has_single_instance_lock(void)
77 {
78 	return false;
79 }
80 #else
81 static void lock_single_instance(void)
82 {
83 	/* Requires tee_ta_mutex to be held */
84 	if (tee_ta_single_instance_thread != thread_get_id()) {
85 		/* Wait until the single-instance lock is available. */
86 		while (tee_ta_single_instance_thread != THREAD_ID_INVALID)
87 			condvar_wait(&tee_ta_cv, &tee_ta_mutex);
88 
89 		tee_ta_single_instance_thread = thread_get_id();
90 		assert(tee_ta_single_instance_count == 0);
91 	}
92 
93 	tee_ta_single_instance_count++;
94 }
95 
96 static void unlock_single_instance(void)
97 {
98 	/* Requires tee_ta_mutex to be held */
99 	assert(tee_ta_single_instance_thread == thread_get_id());
100 	assert(tee_ta_single_instance_count > 0);
101 
102 	tee_ta_single_instance_count--;
103 	if (tee_ta_single_instance_count == 0) {
104 		tee_ta_single_instance_thread = THREAD_ID_INVALID;
105 		condvar_signal(&tee_ta_cv);
106 	}
107 }
108 
109 static bool has_single_instance_lock(void)
110 {
111 	/* Requires tee_ta_mutex to be held */
112 	return tee_ta_single_instance_thread == thread_get_id();
113 }
114 #endif
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->flags & TA_FLAG_SINGLE_INSTANCE)
173 		unlock_single_instance();
174 
175 	mutex_unlock(&tee_ta_mutex);
176 }
177 
178 static void dec_session_ref_count(struct tee_ta_session *s)
179 {
180 	assert(s->ref_count > 0);
181 	s->ref_count--;
182 	if (s->ref_count == 1)
183 		condvar_signal(&s->refc_cv);
184 }
185 
186 void tee_ta_put_session(struct tee_ta_session *s)
187 {
188 	mutex_lock(&tee_ta_mutex);
189 
190 	if (s->lock_thread == thread_get_id()) {
191 		s->lock_thread = THREAD_ID_INVALID;
192 		condvar_signal(&s->lock_cv);
193 	}
194 	dec_session_ref_count(s);
195 
196 	mutex_unlock(&tee_ta_mutex);
197 }
198 
199 static struct tee_ta_session *find_session(uint32_t id,
200 			struct tee_ta_session_head *open_sessions)
201 {
202 	struct tee_ta_session *s;
203 
204 	TAILQ_FOREACH(s, open_sessions, link) {
205 		if ((vaddr_t)s == id)
206 			return s;
207 	}
208 	return NULL;
209 }
210 
211 struct tee_ta_session *tee_ta_get_session(uint32_t id, bool exclusive,
212 			struct tee_ta_session_head *open_sessions)
213 {
214 	struct tee_ta_session *s;
215 
216 	mutex_lock(&tee_ta_mutex);
217 
218 	while (true) {
219 		s = find_session(id, open_sessions);
220 		if (!s)
221 			break;
222 		if (s->unlink) {
223 			s = NULL;
224 			break;
225 		}
226 		s->ref_count++;
227 		if (!exclusive)
228 			break;
229 
230 		assert(s->lock_thread != thread_get_id());
231 
232 		while (s->lock_thread != THREAD_ID_INVALID && !s->unlink)
233 			condvar_wait(&s->lock_cv, &tee_ta_mutex);
234 
235 		if (s->unlink) {
236 			dec_session_ref_count(s);
237 			s = NULL;
238 			break;
239 		}
240 
241 		s->lock_thread = thread_get_id();
242 		break;
243 	}
244 
245 	mutex_unlock(&tee_ta_mutex);
246 	return s;
247 }
248 
249 static void tee_ta_unlink_session(struct tee_ta_session *s,
250 			struct tee_ta_session_head *open_sessions)
251 {
252 	mutex_lock(&tee_ta_mutex);
253 
254 	assert(s->ref_count >= 1);
255 	assert(s->lock_thread == thread_get_id());
256 	assert(!s->unlink);
257 
258 	s->unlink = true;
259 	condvar_broadcast(&s->lock_cv);
260 
261 	while (s->ref_count != 1)
262 		condvar_wait(&s->refc_cv, &tee_ta_mutex);
263 
264 	TAILQ_REMOVE(open_sessions, s, link);
265 
266 	mutex_unlock(&tee_ta_mutex);
267 }
268 
269 /*
270  * tee_ta_context_find - Find TA in session list based on a UUID (input)
271  * Returns a pointer to the session
272  */
273 static struct tee_ta_ctx *tee_ta_context_find(const TEE_UUID *uuid)
274 {
275 	struct tee_ta_ctx *ctx;
276 
277 	TAILQ_FOREACH(ctx, &tee_ctxes, link) {
278 		if (memcmp(&ctx->uuid, uuid, sizeof(TEE_UUID)) == 0)
279 			return ctx;
280 	}
281 
282 	return NULL;
283 }
284 
285 /* check if requester (client ID) matches session initial client */
286 static TEE_Result check_client(struct tee_ta_session *s, const TEE_Identity *id)
287 {
288 	if (id == KERN_IDENTITY)
289 		return TEE_SUCCESS;
290 
291 	if (id == NSAPP_IDENTITY) {
292 		if (s->clnt_id.login == TEE_LOGIN_TRUSTED_APP) {
293 			DMSG("nsec tries to hijack TA session");
294 			return TEE_ERROR_ACCESS_DENIED;
295 		}
296 		return TEE_SUCCESS;
297 	}
298 
299 	if (memcmp(&s->clnt_id, id, sizeof(TEE_Identity)) != 0) {
300 		DMSG("client id mismatch");
301 		return TEE_ERROR_ACCESS_DENIED;
302 	}
303 	return TEE_SUCCESS;
304 }
305 
306 /*
307  * Check if invocation parameters matches TA properties
308  *
309  * @s - current session handle
310  * @param - already identified memory references hold a valid 'mobj'.
311  *
312  * Policy:
313  * - All TAs can access 'non-secure' shared memory.
314  * - All TAs can access TEE private memory (seccpy)
315  * - Only SDP flagged TAs can accept SDP memory references.
316  */
317 #ifndef CFG_SECURE_DATA_PATH
318 static bool check_params(struct tee_ta_session *sess __unused,
319 			 struct tee_ta_param *param __unused)
320 {
321 	/*
322 	 * When CFG_SECURE_DATA_PATH is not enabled, SDP memory references
323 	 * are rejected at OP-TEE core entry. Hence here all TAs have same
324 	 * permissions regarding memory reference parameters.
325 	 */
326 	return true;
327 }
328 #else
329 static bool check_params(struct tee_ta_session *sess,
330 			 struct tee_ta_param *param)
331 {
332 	int n;
333 
334 	/*
335 	 * When CFG_SECURE_DATA_PATH is enabled, OP-TEE entry allows SHM and
336 	 * SDP memory references. Only TAs flagged SDP can access SDP memory.
337 	 */
338 	if (sess->ctx->flags & TA_FLAG_SECURE_DATA_PATH)
339 		return true;
340 
341 	for (n = 0; n < TEE_NUM_PARAMS; n++) {
342 		uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
343 		struct param_mem *mem = &param->u[n].mem;
344 
345 		if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
346 		    param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
347 		    param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
348 			continue;
349 		if (!mem->size)
350 			continue;
351 		if (mobj_is_sdp_mem(mem->mobj))
352 			return false;
353 	}
354 	return true;
355 }
356 #endif
357 
358 static void set_invoke_timeout(struct tee_ta_session *sess,
359 				      uint32_t cancel_req_to)
360 {
361 	TEE_Time current_time;
362 	TEE_Time cancel_time;
363 
364 	if (cancel_req_to == TEE_TIMEOUT_INFINITE)
365 		goto infinite;
366 
367 	if (tee_time_get_sys_time(&current_time) != TEE_SUCCESS)
368 		goto infinite;
369 
370 	if (ADD_OVERFLOW(current_time.seconds, cancel_req_to / 1000,
371 			 &cancel_time.seconds))
372 		goto infinite;
373 
374 	cancel_time.millis = current_time.millis + cancel_req_to % 1000;
375 	if (cancel_time.millis > 1000) {
376 		if (ADD_OVERFLOW(current_time.seconds, 1,
377 				 &cancel_time.seconds))
378 			goto infinite;
379 
380 		cancel_time.seconds++;
381 		cancel_time.millis -= 1000;
382 	}
383 
384 	sess->cancel_time = cancel_time;
385 	return;
386 
387 infinite:
388 	sess->cancel_time.seconds = UINT32_MAX;
389 	sess->cancel_time.millis = UINT32_MAX;
390 }
391 
392 /*-----------------------------------------------------------------------------
393  * Close a Trusted Application and free available resources
394  *---------------------------------------------------------------------------*/
395 TEE_Result tee_ta_close_session(struct tee_ta_session *csess,
396 				struct tee_ta_session_head *open_sessions,
397 				const TEE_Identity *clnt_id)
398 {
399 	struct tee_ta_session *sess;
400 	struct tee_ta_ctx *ctx;
401 	bool keep_alive;
402 
403 	DMSG("tee_ta_close_session(0x%" PRIxVA ")",  (vaddr_t)csess);
404 
405 	if (!csess)
406 		return TEE_ERROR_ITEM_NOT_FOUND;
407 
408 	sess = tee_ta_get_session((vaddr_t)csess, true, open_sessions);
409 
410 	if (!sess) {
411 		EMSG("session 0x%" PRIxVA " to be removed is not found",
412 		     (vaddr_t)csess);
413 		return TEE_ERROR_ITEM_NOT_FOUND;
414 	}
415 
416 	if (check_client(sess, clnt_id) != TEE_SUCCESS) {
417 		tee_ta_put_session(sess);
418 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
419 	}
420 
421 	ctx = sess->ctx;
422 	DMSG("Destroy session");
423 
424 	tee_ta_set_busy(ctx);
425 
426 	if (!ctx->panicked) {
427 		set_invoke_timeout(sess, TEE_TIMEOUT_INFINITE);
428 		ctx->ops->enter_close_session(sess);
429 	}
430 
431 	tee_ta_unlink_session(sess, open_sessions);
432 #if defined(CFG_TA_GPROF_SUPPORT)
433 	free(sess->sbuf);
434 #endif
435 	free(sess);
436 
437 	tee_ta_clear_busy(ctx);
438 
439 	mutex_lock(&tee_ta_mutex);
440 
441 	if (ctx->ref_count <= 0)
442 		panic();
443 
444 	ctx->ref_count--;
445 	keep_alive = (ctx->flags & TA_FLAG_INSTANCE_KEEP_ALIVE) &&
446 			(ctx->flags & TA_FLAG_SINGLE_INSTANCE);
447 	if (!ctx->ref_count && !keep_alive) {
448 		DMSG("Destroy TA ctx");
449 
450 		TAILQ_REMOVE(&tee_ctxes, ctx, link);
451 		mutex_unlock(&tee_ta_mutex);
452 
453 		condvar_destroy(&ctx->busy_cv);
454 
455 		pgt_flush_ctx(ctx);
456 		ctx->ops->destroy(ctx);
457 	} else
458 		mutex_unlock(&tee_ta_mutex);
459 
460 	return TEE_SUCCESS;
461 }
462 
463 static TEE_Result tee_ta_init_session_with_context(struct tee_ta_ctx *ctx,
464 			struct tee_ta_session *s)
465 {
466 	/*
467 	 * If TA isn't single instance it should be loaded as new
468 	 * instance instead of doing anything with this instance.
469 	 * So tell the caller that we didn't find the TA it the
470 	 * caller will load a new instance.
471 	 */
472 	if ((ctx->flags & TA_FLAG_SINGLE_INSTANCE) == 0)
473 		return TEE_ERROR_ITEM_NOT_FOUND;
474 
475 	/*
476 	 * The TA is single instance, if it isn't multi session we
477 	 * can't create another session unless its reference is zero
478 	 */
479 	if (!(ctx->flags & TA_FLAG_MULTI_SESSION) && ctx->ref_count)
480 		return TEE_ERROR_BUSY;
481 
482 	DMSG("Re-open TA %pUl", (void *)&ctx->uuid);
483 
484 	ctx->ref_count++;
485 	s->ctx = ctx;
486 	return TEE_SUCCESS;
487 }
488 
489 
490 static TEE_Result tee_ta_init_session(TEE_ErrorOrigin *err,
491 				struct tee_ta_session_head *open_sessions,
492 				const TEE_UUID *uuid,
493 				struct tee_ta_session **sess)
494 {
495 	TEE_Result res;
496 	struct tee_ta_ctx *ctx;
497 	struct tee_ta_session *s = calloc(1, sizeof(struct tee_ta_session));
498 
499 	*err = TEE_ORIGIN_TEE;
500 	if (!s)
501 		return TEE_ERROR_OUT_OF_MEMORY;
502 
503 	s->cancel_mask = true;
504 	condvar_init(&s->refc_cv);
505 	condvar_init(&s->lock_cv);
506 	s->lock_thread = THREAD_ID_INVALID;
507 	s->ref_count = 1;
508 
509 
510 	/*
511 	 * We take the global TA mutex here and hold it while doing
512 	 * RPC to load the TA. This big critical section should be broken
513 	 * down into smaller pieces.
514 	 */
515 
516 
517 	mutex_lock(&tee_ta_mutex);
518 	TAILQ_INSERT_TAIL(open_sessions, s, link);
519 
520 	/* Look for already loaded TA */
521 	ctx = tee_ta_context_find(uuid);
522 	if (ctx) {
523 		res = tee_ta_init_session_with_context(ctx, s);
524 		if (res == TEE_SUCCESS || res != TEE_ERROR_ITEM_NOT_FOUND)
525 			goto out;
526 	}
527 
528 	/* Look for static TA */
529 	res = tee_ta_init_pseudo_ta_session(uuid, s);
530 	if (res == TEE_SUCCESS || res != TEE_ERROR_ITEM_NOT_FOUND)
531 		goto out;
532 
533 	/* Look for user TA */
534 	res = tee_ta_init_user_ta_session(uuid, s);
535 
536 out:
537 	if (res == TEE_SUCCESS) {
538 		*sess = s;
539 	} else {
540 		TAILQ_REMOVE(open_sessions, s, link);
541 		free(s);
542 	}
543 	mutex_unlock(&tee_ta_mutex);
544 	return res;
545 }
546 
547 TEE_Result tee_ta_open_session(TEE_ErrorOrigin *err,
548 			       struct tee_ta_session **sess,
549 			       struct tee_ta_session_head *open_sessions,
550 			       const TEE_UUID *uuid,
551 			       const TEE_Identity *clnt_id,
552 			       uint32_t cancel_req_to,
553 			       struct tee_ta_param *param)
554 {
555 	TEE_Result res;
556 	struct tee_ta_session *s = NULL;
557 	struct tee_ta_ctx *ctx;
558 	bool panicked;
559 	bool was_busy = false;
560 
561 	res = tee_ta_init_session(err, open_sessions, uuid, &s);
562 	if (res != TEE_SUCCESS) {
563 		DMSG("init session failed 0x%x", res);
564 		return res;
565 	}
566 
567 	if (!check_params(s, param))
568 		return TEE_ERROR_BAD_PARAMETERS;
569 
570 	ctx = s->ctx;
571 
572 	if (ctx->panicked) {
573 		DMSG("panicked, call tee_ta_close_session()");
574 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
575 		*err = TEE_ORIGIN_TEE;
576 		return TEE_ERROR_TARGET_DEAD;
577 	}
578 
579 	*sess = s;
580 	/* Save identity of the owner of the session */
581 	s->clnt_id = *clnt_id;
582 
583 	if (tee_ta_try_set_busy(ctx)) {
584 		set_invoke_timeout(s, cancel_req_to);
585 		res = ctx->ops->enter_open_session(s, param, err);
586 		tee_ta_clear_busy(ctx);
587 	} else {
588 		/* Deadlock avoided */
589 		res = TEE_ERROR_BUSY;
590 		was_busy = true;
591 	}
592 
593 	panicked = ctx->panicked;
594 
595 	tee_ta_put_session(s);
596 	if (panicked || (res != TEE_SUCCESS))
597 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
598 
599 	/*
600 	 * Origin error equal to TEE_ORIGIN_TRUSTED_APP for "regular" error,
601 	 * apart from panicking.
602 	 */
603 	if (panicked || was_busy)
604 		*err = TEE_ORIGIN_TEE;
605 	else
606 		*err = TEE_ORIGIN_TRUSTED_APP;
607 
608 	if (res != TEE_SUCCESS)
609 		EMSG("Failed. Return error 0x%x", res);
610 
611 	return res;
612 }
613 
614 TEE_Result tee_ta_invoke_command(TEE_ErrorOrigin *err,
615 				 struct tee_ta_session *sess,
616 				 const TEE_Identity *clnt_id,
617 				 uint32_t cancel_req_to, uint32_t cmd,
618 				 struct tee_ta_param *param)
619 {
620 	TEE_Result res;
621 
622 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
623 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
624 
625 	if (!check_params(sess, param))
626 		return TEE_ERROR_BAD_PARAMETERS;
627 
628 	if (sess->ctx->panicked) {
629 		DMSG("Panicked !");
630 		*err = TEE_ORIGIN_TEE;
631 		return TEE_ERROR_TARGET_DEAD;
632 	}
633 
634 	tee_ta_set_busy(sess->ctx);
635 
636 	set_invoke_timeout(sess, cancel_req_to);
637 	res = sess->ctx->ops->enter_invoke_cmd(sess, cmd, param, err);
638 
639 	if (sess->ctx->panicked) {
640 		*err = TEE_ORIGIN_TEE;
641 		res = TEE_ERROR_TARGET_DEAD;
642 	}
643 
644 	tee_ta_clear_busy(sess->ctx);
645 	if (res != TEE_SUCCESS)
646 		DMSG("Error: %x of %d\n", res, *err);
647 	return res;
648 }
649 
650 TEE_Result tee_ta_cancel_command(TEE_ErrorOrigin *err,
651 				 struct tee_ta_session *sess,
652 				 const TEE_Identity *clnt_id)
653 {
654 	*err = TEE_ORIGIN_TEE;
655 
656 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
657 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
658 
659 	sess->cancel = true;
660 	return TEE_SUCCESS;
661 }
662 
663 bool tee_ta_session_is_cancelled(struct tee_ta_session *s, TEE_Time *curr_time)
664 {
665 	TEE_Time current_time;
666 
667 	if (s->cancel_mask)
668 		return false;
669 
670 	if (s->cancel)
671 		return true;
672 
673 	if (s->cancel_time.seconds == UINT32_MAX)
674 		return false;
675 
676 	if (curr_time != NULL)
677 		current_time = *curr_time;
678 	else if (tee_time_get_sys_time(&current_time) != TEE_SUCCESS)
679 		return false;
680 
681 	if (current_time.seconds > s->cancel_time.seconds ||
682 	    (current_time.seconds == s->cancel_time.seconds &&
683 	     current_time.millis >= s->cancel_time.millis)) {
684 		return true;
685 	}
686 
687 	return false;
688 }
689 
690 static void update_current_ctx(struct thread_specific_data *tsd)
691 {
692 	struct tee_ta_ctx *ctx = NULL;
693 	struct tee_ta_session *s = TAILQ_FIRST(&tsd->sess_stack);
694 
695 	if (s) {
696 		if (is_pseudo_ta_ctx(s->ctx))
697 			s = TAILQ_NEXT(s, link_tsd);
698 
699 		if (s)
700 			ctx = s->ctx;
701 	}
702 
703 	if (tsd->ctx != ctx)
704 		tee_mmu_set_ctx(ctx);
705 	/*
706 	 * If ctx->mmu == NULL we must not have user mapping active,
707 	 * if ctx->mmu != NULL we must have user mapping active.
708 	 */
709 	if (((ctx && is_user_ta_ctx(ctx) ?
710 			to_user_ta_ctx(ctx)->mmu : NULL) == NULL) ==
711 					core_mmu_user_mapping_is_active())
712 		panic("unexpected active mapping");
713 }
714 
715 void tee_ta_push_current_session(struct tee_ta_session *sess)
716 {
717 	struct thread_specific_data *tsd = thread_get_tsd();
718 
719 	TAILQ_INSERT_HEAD(&tsd->sess_stack, sess, link_tsd);
720 	update_current_ctx(tsd);
721 }
722 
723 struct tee_ta_session *tee_ta_pop_current_session(void)
724 {
725 	struct thread_specific_data *tsd = thread_get_tsd();
726 	struct tee_ta_session *s = TAILQ_FIRST(&tsd->sess_stack);
727 
728 	if (s) {
729 		TAILQ_REMOVE(&tsd->sess_stack, s, link_tsd);
730 		update_current_ctx(tsd);
731 	}
732 	return s;
733 }
734 
735 TEE_Result tee_ta_get_current_session(struct tee_ta_session **sess)
736 {
737 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
738 
739 	if (!s)
740 		return TEE_ERROR_BAD_STATE;
741 	*sess = s;
742 	return TEE_SUCCESS;
743 }
744 
745 struct tee_ta_session *tee_ta_get_calling_session(void)
746 {
747 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
748 
749 	if (s)
750 		s = TAILQ_NEXT(s, link_tsd);
751 	return s;
752 }
753 
754 TEE_Result tee_ta_get_client_id(TEE_Identity *id)
755 {
756 	TEE_Result res;
757 	struct tee_ta_session *sess;
758 
759 	res = tee_ta_get_current_session(&sess);
760 	if (res != TEE_SUCCESS)
761 		return res;
762 
763 	if (id == NULL)
764 		return TEE_ERROR_BAD_PARAMETERS;
765 
766 	*id = sess->clnt_id;
767 	return TEE_SUCCESS;
768 }
769 
770 /*
771  * dump_state - Display TA state as an error log.
772  */
773 static void dump_state(struct tee_ta_ctx *ctx)
774 {
775 	struct tee_ta_session *s = NULL;
776 	bool active __maybe_unused;
777 
778 	active = ((tee_ta_get_current_session(&s) == TEE_SUCCESS) &&
779 		  s && s->ctx == ctx);
780 
781 	EMSG_RAW("Status of TA %pUl (%p) %s", (void *)&ctx->uuid, (void *)ctx,
782 		active ? "(active)" : "");
783 	ctx->ops->dump_state(ctx);
784 }
785 
786 void tee_ta_dump_current(void)
787 {
788 	struct tee_ta_session *s = NULL;
789 
790 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS) {
791 		EMSG("no valid session found, cannot log TA status");
792 		return;
793 	}
794 
795 	dump_state(s->ctx);
796 }
797 
798 #if defined(CFG_TA_GPROF_SUPPORT)
799 void tee_ta_gprof_sample_pc(vaddr_t pc)
800 {
801 	struct tee_ta_session *s;
802 	struct sample_buf *sbuf;
803 	size_t idx;
804 
805 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS)
806 		return;
807 	sbuf = s->sbuf;
808 	if (!sbuf || !sbuf->enabled)
809 		return; /* PC sampling is not enabled */
810 
811 	idx = (((uint64_t)pc - sbuf->offset)/2 * sbuf->scale)/65536;
812 	if (idx < sbuf->nsamples)
813 		sbuf->samples[idx]++;
814 	sbuf->count++;
815 }
816 
817 /*
818  * Update user-mode CPU time for the current session
819  * @suspend: true if session is being suspended (leaving user mode), false if
820  * it is resumed (entering user mode)
821  */
822 static void tee_ta_update_session_utime(bool suspend)
823 {
824 	struct tee_ta_session *s;
825 	struct sample_buf *sbuf;
826 	uint64_t now;
827 
828 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS)
829 		return;
830 	sbuf = s->sbuf;
831 	if (!sbuf)
832 		return;
833 	now = read_cntpct();
834 	if (suspend) {
835 		assert(sbuf->usr_entered);
836 		sbuf->usr += now - sbuf->usr_entered;
837 		sbuf->usr_entered = 0;
838 	} else {
839 		assert(!sbuf->usr_entered);
840 		if (!now)
841 			now++; /* 0 is reserved */
842 		sbuf->usr_entered = now;
843 	}
844 }
845 
846 void tee_ta_update_session_utime_suspend(void)
847 {
848 	tee_ta_update_session_utime(true);
849 }
850 
851 void tee_ta_update_session_utime_resume(void)
852 {
853 	tee_ta_update_session_utime(false);
854 }
855 #endif
856