xref: /optee_os/core/kernel/tee_ta_manager.c (revision baa999cd61495093ce1e9c43251e655b3a14da67)
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 static struct mutex tee_ta_mutex = MUTEX_INITIALIZER;
59 static 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 get_ctx(struct tee_ta_ctx *ctx)
464 {
465 	if (!ctx)
466 		return TEE_ERROR_ITEM_NOT_FOUND;
467 
468 	/*
469 	 * If TA isn't single instance it should be loaded as new
470 	 * instance instead of doing anything with this instance.
471 	 * So tell the caller that we didn't find the TA it the
472 	 * caller will load a new instance.
473 	 */
474 	if ((ctx->flags & TA_FLAG_SINGLE_INSTANCE) == 0)
475 		return TEE_ERROR_ITEM_NOT_FOUND;
476 
477 	/*
478 	 * The TA is single instance, if it isn't multi session we
479 	 * can't create another session unless its reference is zero
480 	 */
481 	if (!(ctx->flags & TA_FLAG_MULTI_SESSION) && ctx->ref_count)
482 		return TEE_ERROR_BUSY;
483 
484 	DMSG("Re-open TA %pUl", (void *)&ctx->uuid);
485 
486 	ctx->ref_count++;
487 	return TEE_SUCCESS;
488 }
489 
490 void tee_ta_register_ctx(struct tee_ta_ctx *ctx)
491 {
492 	mutex_lock(&tee_ta_mutex);
493 	TAILQ_INSERT_TAIL(&tee_ctxes, ctx, link);
494 	mutex_unlock(&tee_ta_mutex);
495 }
496 
497 static TEE_Result tee_ta_init_session(TEE_ErrorOrigin *err,
498 				struct tee_ta_session_head *open_sessions,
499 				const TEE_UUID *uuid,
500 				struct tee_ta_session **sess)
501 {
502 	TEE_Result res;
503 	struct tee_ta_ctx *ctx;
504 	struct tee_ta_session *s = calloc(1, sizeof(struct tee_ta_session));
505 
506 	*err = TEE_ORIGIN_TEE;
507 	if (!s)
508 		return TEE_ERROR_OUT_OF_MEMORY;
509 
510 
511 	/* Look for already loaded TA */
512 	mutex_lock(&tee_ta_mutex);
513 	ctx = tee_ta_context_find(uuid);
514 	res = get_ctx(ctx);
515 	mutex_unlock(&tee_ta_mutex);
516 	if (res != TEE_ERROR_ITEM_NOT_FOUND)
517 		goto out;
518 
519 	/* Look for static TA */
520 	res = pseudo_ta_get_ctx(uuid, &ctx);
521 	if (res != TEE_ERROR_ITEM_NOT_FOUND)
522 		goto out;
523 
524 	/* Look for user TA */
525 	res = user_ta_get_ctx(uuid, &ctx);
526 out:
527 	if (res) {
528 		free(s);
529 		return res;
530 	}
531 
532 	/*
533 	 * We have a context, let's finish initialization of the session
534 	 */
535 	s->cancel_mask = true;
536 	condvar_init(&s->refc_cv);
537 	condvar_init(&s->lock_cv);
538 	s->lock_thread = THREAD_ID_INVALID;
539 	s->ref_count = 1;
540 	s->ctx = ctx;
541 	mutex_lock(&tee_ta_mutex);
542 	TAILQ_INSERT_TAIL(open_sessions, s, link);
543 	mutex_unlock(&tee_ta_mutex);
544 	*sess = s;
545 
546 	return TEE_SUCCESS;
547 }
548 
549 TEE_Result tee_ta_open_session(TEE_ErrorOrigin *err,
550 			       struct tee_ta_session **sess,
551 			       struct tee_ta_session_head *open_sessions,
552 			       const TEE_UUID *uuid,
553 			       const TEE_Identity *clnt_id,
554 			       uint32_t cancel_req_to,
555 			       struct tee_ta_param *param)
556 {
557 	TEE_Result res;
558 	struct tee_ta_session *s = NULL;
559 	struct tee_ta_ctx *ctx;
560 	bool panicked;
561 	bool was_busy = false;
562 
563 	res = tee_ta_init_session(err, open_sessions, uuid, &s);
564 	if (res != TEE_SUCCESS) {
565 		DMSG("init session failed 0x%x", res);
566 		return res;
567 	}
568 
569 	if (!check_params(s, param))
570 		return TEE_ERROR_BAD_PARAMETERS;
571 
572 	ctx = s->ctx;
573 
574 	if (ctx->panicked) {
575 		DMSG("panicked, call tee_ta_close_session()");
576 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
577 		*err = TEE_ORIGIN_TEE;
578 		return TEE_ERROR_TARGET_DEAD;
579 	}
580 
581 	*sess = s;
582 	/* Save identity of the owner of the session */
583 	s->clnt_id = *clnt_id;
584 
585 	if (tee_ta_try_set_busy(ctx)) {
586 		set_invoke_timeout(s, cancel_req_to);
587 		res = ctx->ops->enter_open_session(s, param, err);
588 		tee_ta_clear_busy(ctx);
589 	} else {
590 		/* Deadlock avoided */
591 		res = TEE_ERROR_BUSY;
592 		was_busy = true;
593 	}
594 
595 	panicked = ctx->panicked;
596 
597 	tee_ta_put_session(s);
598 	if (panicked || (res != TEE_SUCCESS))
599 		tee_ta_close_session(s, open_sessions, KERN_IDENTITY);
600 
601 	/*
602 	 * Origin error equal to TEE_ORIGIN_TRUSTED_APP for "regular" error,
603 	 * apart from panicking.
604 	 */
605 	if (panicked || was_busy)
606 		*err = TEE_ORIGIN_TEE;
607 	else
608 		*err = TEE_ORIGIN_TRUSTED_APP;
609 
610 	if (res != TEE_SUCCESS)
611 		EMSG("Failed. Return error 0x%x", res);
612 
613 	return res;
614 }
615 
616 TEE_Result tee_ta_invoke_command(TEE_ErrorOrigin *err,
617 				 struct tee_ta_session *sess,
618 				 const TEE_Identity *clnt_id,
619 				 uint32_t cancel_req_to, uint32_t cmd,
620 				 struct tee_ta_param *param)
621 {
622 	TEE_Result res;
623 
624 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
625 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
626 
627 	if (!check_params(sess, param))
628 		return TEE_ERROR_BAD_PARAMETERS;
629 
630 	if (sess->ctx->panicked) {
631 		DMSG("Panicked !");
632 		*err = TEE_ORIGIN_TEE;
633 		return TEE_ERROR_TARGET_DEAD;
634 	}
635 
636 	tee_ta_set_busy(sess->ctx);
637 
638 	set_invoke_timeout(sess, cancel_req_to);
639 	res = sess->ctx->ops->enter_invoke_cmd(sess, cmd, param, err);
640 
641 	if (sess->ctx->panicked) {
642 		*err = TEE_ORIGIN_TEE;
643 		res = TEE_ERROR_TARGET_DEAD;
644 	}
645 
646 	tee_ta_clear_busy(sess->ctx);
647 	if (res != TEE_SUCCESS)
648 		DMSG("Error: %x of %d\n", res, *err);
649 	return res;
650 }
651 
652 TEE_Result tee_ta_cancel_command(TEE_ErrorOrigin *err,
653 				 struct tee_ta_session *sess,
654 				 const TEE_Identity *clnt_id)
655 {
656 	*err = TEE_ORIGIN_TEE;
657 
658 	if (check_client(sess, clnt_id) != TEE_SUCCESS)
659 		return TEE_ERROR_BAD_PARAMETERS; /* intentional generic error */
660 
661 	sess->cancel = true;
662 	return TEE_SUCCESS;
663 }
664 
665 bool tee_ta_session_is_cancelled(struct tee_ta_session *s, TEE_Time *curr_time)
666 {
667 	TEE_Time current_time;
668 
669 	if (s->cancel_mask)
670 		return false;
671 
672 	if (s->cancel)
673 		return true;
674 
675 	if (s->cancel_time.seconds == UINT32_MAX)
676 		return false;
677 
678 	if (curr_time != NULL)
679 		current_time = *curr_time;
680 	else if (tee_time_get_sys_time(&current_time) != TEE_SUCCESS)
681 		return false;
682 
683 	if (current_time.seconds > s->cancel_time.seconds ||
684 	    (current_time.seconds == s->cancel_time.seconds &&
685 	     current_time.millis >= s->cancel_time.millis)) {
686 		return true;
687 	}
688 
689 	return false;
690 }
691 
692 static void update_current_ctx(struct thread_specific_data *tsd)
693 {
694 	struct tee_ta_ctx *ctx = NULL;
695 	struct tee_ta_session *s = TAILQ_FIRST(&tsd->sess_stack);
696 
697 	if (s) {
698 		if (is_pseudo_ta_ctx(s->ctx))
699 			s = TAILQ_NEXT(s, link_tsd);
700 
701 		if (s)
702 			ctx = s->ctx;
703 	}
704 
705 	if (tsd->ctx != ctx)
706 		tee_mmu_set_ctx(ctx);
707 	/*
708 	 * If ctx->mmu == NULL we must not have user mapping active,
709 	 * if ctx->mmu != NULL we must have user mapping active.
710 	 */
711 	if (((ctx && is_user_ta_ctx(ctx) ?
712 			to_user_ta_ctx(ctx)->mmu : NULL) == NULL) ==
713 					core_mmu_user_mapping_is_active())
714 		panic("unexpected active mapping");
715 }
716 
717 void tee_ta_push_current_session(struct tee_ta_session *sess)
718 {
719 	struct thread_specific_data *tsd = thread_get_tsd();
720 
721 	TAILQ_INSERT_HEAD(&tsd->sess_stack, sess, link_tsd);
722 	update_current_ctx(tsd);
723 }
724 
725 struct tee_ta_session *tee_ta_pop_current_session(void)
726 {
727 	struct thread_specific_data *tsd = thread_get_tsd();
728 	struct tee_ta_session *s = TAILQ_FIRST(&tsd->sess_stack);
729 
730 	if (s) {
731 		TAILQ_REMOVE(&tsd->sess_stack, s, link_tsd);
732 		update_current_ctx(tsd);
733 	}
734 	return s;
735 }
736 
737 TEE_Result tee_ta_get_current_session(struct tee_ta_session **sess)
738 {
739 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
740 
741 	if (!s)
742 		return TEE_ERROR_BAD_STATE;
743 	*sess = s;
744 	return TEE_SUCCESS;
745 }
746 
747 struct tee_ta_session *tee_ta_get_calling_session(void)
748 {
749 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
750 
751 	if (s)
752 		s = TAILQ_NEXT(s, link_tsd);
753 	return s;
754 }
755 
756 TEE_Result tee_ta_get_client_id(TEE_Identity *id)
757 {
758 	TEE_Result res;
759 	struct tee_ta_session *sess;
760 
761 	res = tee_ta_get_current_session(&sess);
762 	if (res != TEE_SUCCESS)
763 		return res;
764 
765 	if (id == NULL)
766 		return TEE_ERROR_BAD_PARAMETERS;
767 
768 	*id = sess->clnt_id;
769 	return TEE_SUCCESS;
770 }
771 
772 /*
773  * dump_state - Display TA state as an error log.
774  */
775 static void dump_state(struct tee_ta_ctx *ctx)
776 {
777 	struct tee_ta_session *s = NULL;
778 	bool active __maybe_unused;
779 
780 	active = ((tee_ta_get_current_session(&s) == TEE_SUCCESS) &&
781 		  s && s->ctx == ctx);
782 
783 	EMSG_RAW("Status of TA %pUl (%p) %s", (void *)&ctx->uuid, (void *)ctx,
784 		active ? "(active)" : "");
785 	ctx->ops->dump_state(ctx);
786 }
787 
788 void tee_ta_dump_current(void)
789 {
790 	struct tee_ta_session *s = NULL;
791 
792 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS) {
793 		EMSG("no valid session found, cannot log TA status");
794 		return;
795 	}
796 
797 	dump_state(s->ctx);
798 }
799 
800 #if defined(CFG_TA_GPROF_SUPPORT)
801 void tee_ta_gprof_sample_pc(vaddr_t pc)
802 {
803 	struct tee_ta_session *s;
804 	struct sample_buf *sbuf;
805 	size_t idx;
806 
807 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS)
808 		return;
809 	sbuf = s->sbuf;
810 	if (!sbuf || !sbuf->enabled)
811 		return; /* PC sampling is not enabled */
812 
813 	idx = (((uint64_t)pc - sbuf->offset)/2 * sbuf->scale)/65536;
814 	if (idx < sbuf->nsamples)
815 		sbuf->samples[idx]++;
816 	sbuf->count++;
817 }
818 
819 /*
820  * Update user-mode CPU time for the current session
821  * @suspend: true if session is being suspended (leaving user mode), false if
822  * it is resumed (entering user mode)
823  */
824 static void tee_ta_update_session_utime(bool suspend)
825 {
826 	struct tee_ta_session *s;
827 	struct sample_buf *sbuf;
828 	uint64_t now;
829 
830 	if (tee_ta_get_current_session(&s) != TEE_SUCCESS)
831 		return;
832 	sbuf = s->sbuf;
833 	if (!sbuf)
834 		return;
835 	now = read_cntpct();
836 	if (suspend) {
837 		assert(sbuf->usr_entered);
838 		sbuf->usr += now - sbuf->usr_entered;
839 		sbuf->usr_entered = 0;
840 	} else {
841 		assert(!sbuf->usr_entered);
842 		if (!now)
843 			now++; /* 0 is reserved */
844 		sbuf->usr_entered = now;
845 	}
846 }
847 
848 void tee_ta_update_session_utime_suspend(void)
849 {
850 	tee_ta_update_session_utime(true);
851 }
852 
853 void tee_ta_update_session_utime_resume(void)
854 {
855 	tee_ta_update_session_utime(false);
856 }
857 #endif
858