xref: /optee_os/core/tee/tadb.c (revision daaf4f11ca8f6b033171d78e3384f4abce0e04bc)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2017, Linaro Limited
4  */
5 
6 #include <bitstring.h>
7 #include <crypto/crypto.h>
8 #include <kernel/msg_param.h>
9 #include <kernel/mutex.h>
10 #include <kernel/refcount.h>
11 #include <kernel/thread.h>
12 #include <optee_msg_supplicant.h>
13 #include <string.h>
14 #include <tee_api_defines_extensions.h>
15 #include <tee/tadb.h>
16 #include <tee/tee_fs.h>
17 #include <tee/tee_fs_rpc.h>
18 #include <tee/tee_pobj.h>
19 #include <tee/tee_svc_storage.h>
20 #include <utee_defines.h>
21 
22 #define TADB_MAX_BUFFER_SIZE	(64U * 1024)
23 
24 #define TADB_AUTH_ENC_ALG	TEE_ALG_AES_GCM
25 #define TADB_IV_SIZE		TEE_AES_BLOCK_SIZE
26 #define TADB_TAG_SIZE		TEE_AES_BLOCK_SIZE
27 #define TADB_KEY_SIZE		TEE_AES_MAX_KEY_SIZE
28 
29 struct tee_tadb_dir {
30 	const struct tee_file_operations *ops;
31 	struct tee_file_handle *fh;
32 	int nbits;
33 	bitstr_t *files;
34 };
35 
36 struct tadb_entry {
37 	struct tee_tadb_property prop;
38 	uint32_t file_number;
39 	uint8_t iv[TADB_IV_SIZE];
40 	uint8_t tag[TADB_TAG_SIZE];
41 	uint8_t key[TADB_KEY_SIZE];
42 };
43 
44 struct tadb_header {
45 	uint32_t opaque_len;
46 	uint8_t opaque[];
47 };
48 
49 struct tee_tadb_ta_write {
50 	struct tee_tadb_dir *db;
51 	int fd;
52 	struct tadb_entry entry;
53 	size_t pos;
54 	void *ctx;
55 };
56 
57 struct tee_tadb_ta_read {
58 	struct tee_tadb_dir *db;
59 	int fd;
60 	struct tadb_entry entry;
61 	size_t pos;
62 	void *ctx;
63 	uint64_t ta_cookie;
64 	struct mobj *ta_mobj;
65 	uint8_t *ta_buf;
66 };
67 
68 static const char tadb_obj_id[] = "ta.db";
69 static struct tee_tadb_dir *tadb_db;
70 static struct refcount tadb_db_refc;
71 static struct mutex tadb_mutex = MUTEX_INITIALIZER;
72 
73 static void file_num_to_str(char *buf, size_t blen, uint32_t file_number)
74 {
75 	snprintf(buf, blen, "%" PRIu32 ".ta", file_number);
76 }
77 
78 static bool is_null_uuid(const TEE_UUID *uuid)
79 {
80 	const TEE_UUID null_uuid = { 0 };
81 
82 	return !memcmp(uuid, &null_uuid, sizeof(*uuid));
83 }
84 
85 static TEE_Result ta_operation_open(unsigned int cmd, uint32_t file_number,
86 				    int *fd)
87 {
88 	struct mobj *mobj;
89 	TEE_Result res;
90 	void *va;
91 	uint64_t cookie;
92 	struct optee_msg_param params[] = {
93 		[0] = { .attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT,
94 			.u.value.a = cmd },
95 		[2] = { .attr = OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT }
96 	};
97 
98 	va = tee_fs_rpc_cache_alloc(TEE_FS_NAME_MAX, &mobj, &cookie);
99 	if (!va)
100 		return TEE_ERROR_OUT_OF_MEMORY;
101 
102 	if (!msg_param_init_memparam(params + 1, mobj, 0, TEE_FS_NAME_MAX,
103 				     cookie, MSG_PARAM_MEM_DIR_IN))
104 		return TEE_ERROR_BAD_STATE;
105 
106 	file_num_to_str(va, TEE_FS_NAME_MAX, file_number);
107 
108 	res = thread_rpc_cmd(OPTEE_MSG_RPC_CMD_FS, ARRAY_SIZE(params), params);
109 	if (!res)
110 		*fd = params[2].u.value.a;
111 
112 	return res;
113 }
114 
115 static TEE_Result ta_operation_remove(uint32_t file_number)
116 {
117 	struct mobj *mobj;
118 	void *va;
119 	uint64_t cookie;
120 	struct optee_msg_param params[2] = {
121 		[0] = { .attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT,
122 			.u.value.a = OPTEE_MRF_REMOVE },
123 	};
124 
125 	va = tee_fs_rpc_cache_alloc(TEE_FS_NAME_MAX, &mobj, &cookie);
126 	if (!va)
127 		return TEE_ERROR_OUT_OF_MEMORY;
128 
129 	if (!msg_param_init_memparam(params + 1, mobj, 0, TEE_FS_NAME_MAX,
130 				     cookie, MSG_PARAM_MEM_DIR_IN))
131 		return TEE_ERROR_BAD_STATE;
132 
133 	file_num_to_str(va, TEE_FS_NAME_MAX, file_number);
134 
135 	return thread_rpc_cmd(OPTEE_MSG_RPC_CMD_FS, ARRAY_SIZE(params), params);
136 }
137 
138 static TEE_Result maybe_grow_files(struct tee_tadb_dir *db, int idx)
139 {
140 	void *p;
141 
142 	if (idx < db->nbits)
143 		return TEE_SUCCESS;
144 
145 	p = realloc(db->files, bitstr_size(idx + 1));
146 	if (!p)
147 		return TEE_ERROR_OUT_OF_MEMORY;
148 	db->files = p;
149 
150 	bit_nclear(db->files, db->nbits, idx);
151 	db->nbits = idx + 1;
152 
153 	return TEE_SUCCESS;
154 }
155 
156 static TEE_Result set_file(struct tee_tadb_dir *db, int idx)
157 {
158 	TEE_Result res = maybe_grow_files(db, idx);
159 
160 	if (!res)
161 		bit_set(db->files, idx);
162 
163 	return res;
164 }
165 
166 static void clear_file(struct tee_tadb_dir *db, int idx)
167 {
168 	if (idx < db->nbits)
169 		bit_clear(db->files, idx);
170 }
171 
172 static bool test_file(struct tee_tadb_dir *db, int idx)
173 {
174 	if (idx < db->nbits)
175 		return bit_test(db->files, idx);
176 
177 	return false;
178 }
179 
180 static TEE_Result read_ent(struct tee_tadb_dir *db, size_t idx,
181 			   struct tadb_entry *entry)
182 {
183 	size_t l = sizeof(*entry);
184 	TEE_Result res = db->ops->read(db->fh, idx * l, entry, &l);
185 
186 	if (!res && l != sizeof(*entry))
187 		return TEE_ERROR_ITEM_NOT_FOUND;
188 
189 	return res;
190 }
191 
192 static TEE_Result write_ent(struct tee_tadb_dir *db, size_t idx,
193 			    const struct tadb_entry *entry)
194 {
195 	const size_t l = sizeof(*entry);
196 
197 	return db->ops->write(db->fh, idx * l, entry, l);
198 }
199 
200 static TEE_Result tadb_open(struct tee_tadb_dir **db_ret)
201 {
202 	TEE_Result res;
203 	struct tee_tadb_dir *db = calloc(1, sizeof(*db));
204 	struct tee_pobj po = {
205 		.obj_id = (void *)tadb_obj_id,
206 		.obj_id_len = sizeof(tadb_obj_id)
207 	};
208 
209 	if (!db)
210 		return TEE_ERROR_OUT_OF_MEMORY;
211 
212 	db->ops = tee_svc_storage_file_ops(TEE_STORAGE_PRIVATE);
213 
214 	res = db->ops->open(&po, NULL, &db->fh);
215 	if (res == TEE_ERROR_ITEM_NOT_FOUND)
216 		res = db->ops->create(&po, false, NULL, 0, NULL, 0, NULL, 0,
217 				      &db->fh);
218 
219 	if (res)
220 		free(db);
221 	else
222 		*db_ret = db;
223 
224 	return res;
225 }
226 
227 static TEE_Result tee_tadb_open(struct tee_tadb_dir **db)
228 {
229 	if (!refcount_inc(&tadb_db_refc)) {
230 		TEE_Result res;
231 
232 		mutex_lock(&tadb_mutex);
233 		if (!tadb_db) {
234 			res = tadb_open(&tadb_db);
235 			if (!res)
236 				refcount_set(&tadb_db_refc, 1);
237 		} else {
238 			/*
239 			 * This case is handling the small window where the
240 			 * reference counter was decreased to 0 but before
241 			 * the mutex was acquired by tadb_put() this thread
242 			 * acquired the mutex instead.
243 			 *
244 			 * Since tadb_db isn't NULL it's enough to increase
245 			 * the reference counter. If the value of the
246 			 * counter is 0 refcount_inc() will fail and we'll
247 			 * have to set it directly with refcount_set()
248 			 * instead.
249 			 */
250 			if (!refcount_inc(&tadb_db_refc))
251 				refcount_set(&tadb_db_refc, 1);
252 			res = TEE_SUCCESS;
253 		}
254 		mutex_unlock(&tadb_mutex);
255 		if (res)
256 			return res;
257 	}
258 
259 	*db = tadb_db;
260 	return TEE_SUCCESS;
261 }
262 
263 static void tadb_put(struct tee_tadb_dir *db)
264 {
265 	if (refcount_dec(&tadb_db_refc)) {
266 		mutex_lock(&tadb_mutex);
267 		if (!refcount_val(&tadb_db_refc) && tadb_db) {
268 			db->ops->close(&db->fh);
269 			free(db->files);
270 			free(db);
271 			tadb_db = NULL;
272 		}
273 		mutex_unlock(&tadb_mutex);
274 	}
275 }
276 
277 static void tee_tadb_close(struct tee_tadb_dir *db)
278 {
279 	tadb_put(db);
280 }
281 
282 static TEE_Result tadb_authenc_init(TEE_OperationMode mode,
283 				    const struct tadb_entry *entry,
284 				    void **ctx_ret)
285 {
286 	TEE_Result res;
287 	void *ctx;
288 	const size_t enc_size = entry->prop.custom_size + entry->prop.bin_size;
289 
290 	res = crypto_authenc_alloc_ctx(&ctx, TADB_AUTH_ENC_ALG);
291 	if (res)
292 		return res;
293 
294 	res = crypto_authenc_init(ctx, TADB_AUTH_ENC_ALG, mode,
295 				  entry->key, sizeof(entry->key),
296 				  entry->iv, sizeof(entry->iv),
297 				  sizeof(entry->tag), 0, enc_size);
298 	if (res)
299 		crypto_authenc_free_ctx(ctx, TADB_AUTH_ENC_ALG);
300 	else
301 		*ctx_ret = ctx;
302 
303 	return res;
304 }
305 
306 static TEE_Result tadb_update_payload(void *ctx, TEE_OperationMode mode,
307 				      const void *src, size_t len, void *dst)
308 {
309 	TEE_Result res;
310 	size_t sz = len;
311 
312 	res = crypto_authenc_update_payload(ctx, TADB_AUTH_ENC_ALG, mode,
313 					    (const uint8_t *)src, len, dst,
314 					    &sz);
315 	assert(res || sz == len);
316 	return res;
317 }
318 
319 static TEE_Result populate_files(struct tee_tadb_dir *db)
320 {
321 	TEE_Result res;
322 	size_t idx;
323 
324 	/*
325 	 * If db->files isn't NULL the bitfield is already populated and
326 	 * there's nothing left to do here for now.
327 	 */
328 	if (db->files)
329 		return TEE_SUCCESS;
330 
331 	/*
332 	 * Iterate over the TA database and set the bits in the bit field
333 	 * for used file numbers. Note that set_file() will allocate and
334 	 * grow the bitfield as needed.
335 	 *
336 	 * At the same time clean out duplicate file numbers, the first
337 	 * entry with the file number has precedence. Duplicate entries is
338 	 * not supposed to be able to happen, but if it still does better
339 	 * to clean it out here instead of letting the error spread with
340 	 * unexpected side effects.
341 	 */
342 	for (idx = 0;; idx++) {
343 		struct tadb_entry entry;
344 
345 		res = read_ent(db, idx, &entry);
346 		if (res) {
347 			if (res == TEE_ERROR_ITEM_NOT_FOUND)
348 				return TEE_SUCCESS;
349 			goto err;
350 		}
351 
352 		if (is_null_uuid(&entry.prop.uuid))
353 			continue;
354 
355 		if (test_file(db, entry.file_number)) {
356 			IMSG("Clearing duplicate file number %" PRIu32,
357 			     entry.file_number);
358 			memset(&entry, 0, sizeof(entry));
359 			res = write_ent(db, idx, &entry);
360 			if (res)
361 				goto err;
362 			continue;
363 		}
364 
365 		res = set_file(db, entry.file_number);
366 		if (res)
367 			goto err;
368 	}
369 
370 err:
371 	free(db->files);
372 	db->files = NULL;
373 	db->nbits = 0;
374 
375 	return res;
376 }
377 
378 TEE_Result tee_tadb_ta_create(const struct tee_tadb_property *property,
379 			      struct tee_tadb_ta_write **ta_ret)
380 {
381 	TEE_Result res;
382 	struct tee_tadb_ta_write *ta;
383 	int i = 0;
384 
385 	if (is_null_uuid(&property->uuid))
386 		return TEE_ERROR_GENERIC;
387 
388 	ta = calloc(1, sizeof(*ta));
389 	if (!ta)
390 		return TEE_ERROR_OUT_OF_MEMORY;
391 
392 	res = tee_tadb_open(&ta->db);
393 	if (res)
394 		goto err_free;
395 
396 	mutex_lock(&tadb_mutex);
397 
398 	/*
399 	 * Since we're going to search for next free file number below we
400 	 * need to populate the bitfield holding used file numbers.
401 	 */
402 	res = populate_files(ta->db);
403 	if (res)
404 		goto err_mutex;
405 
406 	if (ta->db->files) {
407 		bit_ffc(ta->db->files, ta->db->nbits, &i);
408 		if (i == -1)
409 			i = ta->db->nbits;
410 	}
411 
412 	res = set_file(ta->db, i);
413 	if (res)
414 		goto err_mutex;
415 
416 	mutex_unlock(&tadb_mutex);
417 
418 	ta->entry.file_number = i;
419 	ta->entry.prop = *property;
420 
421 	res = crypto_rng_read(ta->entry.iv, sizeof(ta->entry.iv));
422 	if (res)
423 		goto err_put;
424 
425 	res = crypto_rng_read(ta->entry.key, sizeof(ta->entry.key));
426 	if (res)
427 		goto err_put;
428 
429 	res = ta_operation_open(OPTEE_MRF_CREATE, ta->entry.file_number,
430 				&ta->fd);
431 	if (res)
432 		goto err_put;
433 
434 	res = tadb_authenc_init(TEE_MODE_ENCRYPT, &ta->entry, &ta->ctx);
435 	if (res)
436 		goto err_put;
437 
438 	*ta_ret = ta;
439 
440 	return TEE_SUCCESS;
441 
442 err_mutex:
443 	mutex_unlock(&tadb_mutex);
444 err_put:
445 	tadb_put(ta->db);
446 err_free:
447 	free(ta);
448 
449 	return res;
450 }
451 
452 TEE_Result tee_tadb_ta_write(struct tee_tadb_ta_write *ta, const void *buf,
453 			     size_t len)
454 {
455 	TEE_Result res;
456 	const uint8_t *rb = buf;
457 	size_t rl = len;
458 	struct tee_fs_rpc_operation op;
459 
460 	while (rl) {
461 		size_t wl = MIN(rl, TADB_MAX_BUFFER_SIZE);
462 		void *wb;
463 
464 		res = tee_fs_rpc_write_init(&op, OPTEE_MSG_RPC_CMD_FS, ta->fd,
465 					    ta->pos, wl, &wb);
466 		if (res)
467 			return res;
468 
469 		res = tadb_update_payload(ta->ctx, TEE_MODE_ENCRYPT,
470 					  rb, wl, wb);
471 		if (res)
472 			return res;
473 
474 		res = tee_fs_rpc_write_final(&op);
475 		if (res)
476 			return res;
477 
478 		rl -= wl;
479 		rb += wl;
480 		ta->pos += wl;
481 	}
482 
483 	return TEE_SUCCESS;
484 }
485 
486 void tee_tadb_ta_close_and_delete(struct tee_tadb_ta_write *ta)
487 {
488 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
489 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
490 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
491 	ta_operation_remove(ta->entry.file_number);
492 
493 	mutex_lock(&tadb_mutex);
494 	clear_file(ta->db, ta->entry.file_number);
495 	mutex_unlock(&tadb_mutex);
496 
497 	tadb_put(ta->db);
498 	free(ta);
499 }
500 
501 static TEE_Result find_ent(struct tee_tadb_dir *db, const TEE_UUID *uuid,
502 			   size_t *idx_ret, struct tadb_entry *entry_ret)
503 {
504 	TEE_Result res;
505 	size_t idx;
506 
507 	/*
508 	 * Search for the provided uuid, if it's found return the index it
509 	 * has together with TEE_SUCCESS.
510 	 *
511 	 * If the uuid can't be found return the number indexes together
512 	 * with TEE_ERROR_ITEM_NOT_FOUND.
513 	 */
514 	for (idx = 0;; idx++) {
515 		struct tadb_entry entry;
516 
517 		res = read_ent(db, idx, &entry);
518 		if (res) {
519 			if (res == TEE_ERROR_ITEM_NOT_FOUND)
520 				break;
521 			return res;
522 		}
523 
524 		if (!memcmp(&entry.prop.uuid, uuid, sizeof(*uuid))) {
525 			if (entry_ret)
526 				*entry_ret = entry;
527 			break;
528 		}
529 	}
530 
531 	*idx_ret = idx;
532 	return res;
533 }
534 
535 static TEE_Result find_free_ent_idx(struct tee_tadb_dir *db, size_t *idx)
536 {
537 	const TEE_UUID null_uuid = { 0 };
538 	TEE_Result res = find_ent(db, &null_uuid, idx, NULL);
539 
540 	/*
541 	 * Note that *idx is set to the number of entries on
542 	 * TEE_ERROR_ITEM_NOT_FOUND.
543 	 */
544 	if (res == TEE_ERROR_ITEM_NOT_FOUND)
545 		return TEE_SUCCESS;
546 	return res;
547 }
548 
549 TEE_Result tee_tadb_ta_close_and_commit(struct tee_tadb_ta_write *ta)
550 {
551 	TEE_Result res;
552 	size_t dsz = 0;
553 	size_t sz = sizeof(ta->entry.tag);
554 	size_t idx;
555 	struct tadb_entry old_ent;
556 	bool have_old_ent = false;
557 
558 	res = crypto_authenc_enc_final(ta->ctx, TADB_AUTH_ENC_ALG,
559 				       NULL, 0, NULL, &dsz,
560 				       ta->entry.tag, &sz);
561 	if (res)
562 		goto err;
563 
564 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
565 
566 	mutex_lock(&tadb_mutex);
567 	/*
568 	 * First try to find an existing TA to replace. If there's one
569 	 * we'll use the entry, but we should also remove the old encrypted
570 	 * file.
571 	 *
572 	 * If there isn't an existing TA to replace, grab a new entry.
573 	 */
574 	res = find_ent(ta->db, &ta->entry.prop.uuid, &idx, &old_ent);
575 	if (!res) {
576 		have_old_ent = true;
577 	} else {
578 		res = find_free_ent_idx(ta->db, &idx);
579 		if (res)
580 			goto err_mutex;
581 	}
582 	res = write_ent(ta->db, idx, &ta->entry);
583 	if (res)
584 		goto err_mutex;
585 	if (have_old_ent)
586 		clear_file(ta->db, old_ent.file_number);
587 	mutex_unlock(&tadb_mutex);
588 
589 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
590 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
591 	tadb_put(ta->db);
592 	free(ta);
593 	if (have_old_ent)
594 		ta_operation_remove(old_ent.file_number);
595 	return TEE_SUCCESS;
596 
597 err_mutex:
598 	mutex_unlock(&tadb_mutex);
599 err:
600 	tee_tadb_ta_close_and_delete(ta);
601 	return res;
602 }
603 
604 TEE_Result tee_tadb_ta_delete(const TEE_UUID *uuid)
605 {
606 	const struct tadb_entry null_entry = { { { 0 } } };
607 	struct tee_tadb_dir *db;
608 	struct tadb_entry entry;
609 	size_t idx;
610 	TEE_Result res;
611 
612 	if (is_null_uuid(uuid))
613 		return TEE_ERROR_GENERIC;
614 
615 	res = tee_tadb_open(&db);
616 	if (res)
617 		return res;
618 
619 	mutex_lock(&tadb_mutex);
620 	res = find_ent(db, uuid, &idx, &entry);
621 	if (res) {
622 		mutex_unlock(&tadb_mutex);
623 		tee_tadb_close(db);
624 		return res;
625 	}
626 
627 	clear_file(db, entry.file_number);
628 	res = write_ent(db, idx, &null_entry);
629 	mutex_unlock(&tadb_mutex);
630 
631 	tee_tadb_close(db);
632 	if (res)
633 		return res;
634 
635 	ta_operation_remove(entry.file_number);
636 	return TEE_SUCCESS;
637 }
638 
639 TEE_Result tee_tadb_ta_open(const TEE_UUID *uuid,
640 			    struct tee_tadb_ta_read **ta_ret)
641 {
642 	TEE_Result res;
643 	size_t idx;
644 	struct tee_tadb_ta_read *ta;
645 	static struct tadb_entry last_entry;
646 
647 	if (is_null_uuid(uuid))
648 		return TEE_ERROR_GENERIC;
649 
650 	ta = calloc(1, sizeof(*ta));
651 	if (!ta)
652 		return TEE_ERROR_OUT_OF_MEMORY;
653 
654 	if (!memcmp(uuid, &last_entry.prop.uuid, sizeof(*uuid))) {
655 		ta->entry = last_entry;
656 	} else {
657 		res = tee_tadb_open(&ta->db);
658 		if (res)
659 			goto err_free; /* Mustn't all tadb_put() */
660 
661 		mutex_read_lock(&tadb_mutex);
662 		res = find_ent(ta->db, uuid, &idx, &ta->entry);
663 		mutex_read_unlock(&tadb_mutex);
664 		if (res)
665 			goto err;
666 	}
667 
668 	res = ta_operation_open(OPTEE_MRF_OPEN, ta->entry.file_number, &ta->fd);
669 	if (res)
670 		goto err;
671 
672 	res = tadb_authenc_init(TEE_MODE_DECRYPT, &ta->entry, &ta->ctx);
673 	if (res)
674 		goto err;
675 
676 	*ta_ret = ta;
677 
678 	return TEE_SUCCESS;
679 err:
680 	tadb_put(ta->db);
681 err_free:
682 	free(ta);
683 	return res;
684 }
685 
686 const struct tee_tadb_property *
687 tee_tadb_ta_get_property(struct tee_tadb_ta_read *ta)
688 {
689 	return &ta->entry.prop;
690 }
691 
692 static TEE_Result ta_load(struct tee_tadb_ta_read *ta)
693 {
694 	TEE_Result res;
695 	const size_t sz = ta->entry.prop.custom_size + ta->entry.prop.bin_size;
696 	struct optee_msg_param params[2] = {
697 		[0] = { .attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT,
698 			.u.value.a = OPTEE_MRF_READ,
699 			.u.value.b = ta->fd,
700 			.u.value.c = 0 },
701 	};
702 
703 	if (ta->ta_mobj)
704 		return TEE_SUCCESS;
705 
706 	ta->ta_mobj = thread_rpc_alloc_payload(sz, &ta->ta_cookie);
707 	if (!ta->ta_mobj)
708 		return TEE_ERROR_OUT_OF_MEMORY;
709 
710 	ta->ta_buf = mobj_get_va(ta->ta_mobj, 0);
711 	assert(ta->ta_buf);
712 
713 	if (!msg_param_init_memparam(params + 1, ta->ta_mobj, 0, sz,
714 				     ta->ta_cookie, MSG_PARAM_MEM_DIR_OUT))
715 		return TEE_ERROR_BAD_STATE;
716 
717 	res = thread_rpc_cmd(OPTEE_MSG_RPC_CMD_FS, ARRAY_SIZE(params), params);
718 	if (res) {
719 		thread_rpc_free_payload(ta->ta_cookie, ta->ta_mobj);
720 		ta->ta_mobj = NULL;
721 	}
722 	return res;
723 }
724 
725 TEE_Result tee_tadb_ta_read(struct tee_tadb_ta_read *ta, void *buf, size_t *len)
726 {
727 	TEE_Result res;
728 	const size_t sz = ta->entry.prop.custom_size + ta->entry.prop.bin_size;
729 	size_t l = MIN(*len, sz - ta->pos);
730 
731 	res = ta_load(ta);
732 	if (res)
733 		return res;
734 
735 	if (buf) {
736 		res = tadb_update_payload(ta->ctx, TEE_MODE_DECRYPT,
737 					  ta->ta_buf + ta->pos, l, buf);
738 		if (res)
739 			return res;
740 	} else {
741 		size_t num_bytes = 0;
742 		size_t b_size = MIN(256U, l);
743 		uint8_t *b = malloc(b_size);
744 
745 		if (!b)
746 			return TEE_ERROR_OUT_OF_MEMORY;
747 
748 		while (num_bytes < l) {
749 			size_t n = MIN(b_size, l - num_bytes);
750 
751 			res = tadb_update_payload(ta->ctx, TEE_MODE_DECRYPT,
752 						  ta->ta_buf + ta->pos +
753 							num_bytes, n, b);
754 			if (res)
755 				break;
756 			num_bytes += n;
757 		}
758 
759 		free(b);
760 		if (res)
761 			return res;
762 	}
763 
764 	ta->pos += l;
765 	if (ta->pos == sz) {
766 		size_t dl = 0;
767 
768 		res = crypto_authenc_dec_final(ta->ctx, TADB_AUTH_ENC_ALG,
769 					       NULL, 0, NULL, &dl,
770 					       ta->entry.tag, TADB_TAG_SIZE);
771 		if (res)
772 			return res;
773 	}
774 	*len = l;
775 	return TEE_SUCCESS;
776 }
777 
778 void tee_tadb_ta_close(struct tee_tadb_ta_read *ta)
779 {
780 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
781 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
782 	if (ta->ta_mobj)
783 		thread_rpc_free_payload(ta->ta_cookie, ta->ta_mobj);
784 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
785 	tadb_put(ta->db);
786 	free(ta);
787 }
788