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