xref: /optee_os/core/tee/tadb.c (revision e39aae81e1a40ba495893f1c4e04b23401eca3a3)
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;
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;
424 
425 	res = crypto_rng_read(ta->entry.key, sizeof(ta->entry.key));
426 	if (res)
427 		goto err;
428 
429 	res = ta_operation_open(OPTEE_MRF_CREATE, ta->entry.file_number,
430 				&ta->fd);
431 	if (res)
432 		goto err;
433 
434 	res = tadb_authenc_init(TEE_MODE_ENCRYPT, &ta->entry, &ta->ctx);
435 	if (res)
436 		goto err;
437 
438 	*ta_ret = ta;
439 
440 	return TEE_SUCCESS;
441 
442 err_mutex:
443 	mutex_unlock(&tadb_mutex);
444 err:
445 	tadb_put(ta->db);
446 	free(ta);
447 
448 	return res;
449 }
450 
451 TEE_Result tee_tadb_ta_write(struct tee_tadb_ta_write *ta, const void *buf,
452 			     size_t len)
453 {
454 	TEE_Result res;
455 	const uint8_t *rb = buf;
456 	size_t rl = len;
457 	struct tee_fs_rpc_operation op;
458 
459 	while (rl) {
460 		size_t wl = MIN(rl, TADB_MAX_BUFFER_SIZE);
461 		void *wb;
462 
463 		res = tee_fs_rpc_write_init(&op, OPTEE_MSG_RPC_CMD_FS, ta->fd,
464 					    ta->pos, wl, &wb);
465 		if (res)
466 			return res;
467 
468 		res = tadb_update_payload(ta->ctx, TEE_MODE_ENCRYPT,
469 					  rb, wl, wb);
470 		if (res)
471 			return res;
472 
473 		res = tee_fs_rpc_write_final(&op);
474 		if (res)
475 			return res;
476 
477 		rl -= wl;
478 		rb += wl;
479 		ta->pos += wl;
480 	}
481 
482 	return TEE_SUCCESS;
483 }
484 
485 void tee_tadb_ta_close_and_delete(struct tee_tadb_ta_write *ta)
486 {
487 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
488 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
489 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
490 	ta_operation_remove(ta->entry.file_number);
491 
492 	mutex_lock(&tadb_mutex);
493 	clear_file(ta->db, ta->entry.file_number);
494 	mutex_unlock(&tadb_mutex);
495 
496 	tadb_put(ta->db);
497 	free(ta);
498 }
499 
500 static TEE_Result find_ent(struct tee_tadb_dir *db, const TEE_UUID *uuid,
501 			   size_t *idx_ret, struct tadb_entry *entry_ret)
502 {
503 	TEE_Result res;
504 	size_t idx;
505 
506 	/*
507 	 * Search for the provided uuid, if it's found return the index it
508 	 * has together with TEE_SUCCESS.
509 	 *
510 	 * If the uuid can't be found return the number indexes together
511 	 * with TEE_ERROR_ITEM_NOT_FOUND.
512 	 */
513 	for (idx = 0;; idx++) {
514 		struct tadb_entry entry;
515 
516 		res = read_ent(db, idx, &entry);
517 		if (res) {
518 			if (res == TEE_ERROR_ITEM_NOT_FOUND)
519 				break;
520 			return res;
521 		}
522 
523 		if (!memcmp(&entry.prop.uuid, uuid, sizeof(*uuid))) {
524 			if (entry_ret)
525 				*entry_ret = entry;
526 			break;
527 		}
528 	}
529 
530 	*idx_ret = idx;
531 	return res;
532 }
533 
534 static TEE_Result find_free_ent_idx(struct tee_tadb_dir *db, size_t *idx)
535 {
536 	const TEE_UUID null_uuid = { 0 };
537 	TEE_Result res = find_ent(db, &null_uuid, idx, NULL);
538 
539 	/*
540 	 * Note that *idx is set to the number of entries on
541 	 * TEE_ERROR_ITEM_NOT_FOUND.
542 	 */
543 	if (res == TEE_ERROR_ITEM_NOT_FOUND)
544 		return TEE_SUCCESS;
545 	return res;
546 }
547 
548 TEE_Result tee_tadb_ta_close_and_commit(struct tee_tadb_ta_write *ta)
549 {
550 	TEE_Result res;
551 	size_t dsz = 0;
552 	size_t sz = sizeof(ta->entry.tag);
553 	size_t idx;
554 	struct tadb_entry old_ent;
555 	bool have_old_ent = false;
556 
557 	res = crypto_authenc_enc_final(ta->ctx, TADB_AUTH_ENC_ALG,
558 				       NULL, 0, NULL, &dsz,
559 				       ta->entry.tag, &sz);
560 	if (res)
561 		goto err;
562 
563 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
564 
565 	mutex_lock(&tadb_mutex);
566 	/*
567 	 * First try to find an existing TA to replace. If there's one
568 	 * we'll use the entry, but we should also remove the old encrypted
569 	 * file.
570 	 *
571 	 * If there isn't an existing TA to replace, grab a new entry.
572 	 */
573 	res = find_ent(ta->db, &ta->entry.prop.uuid, &idx, &old_ent);
574 	if (!res) {
575 		have_old_ent = true;
576 	} else {
577 		res = find_free_ent_idx(ta->db, &idx);
578 		if (res)
579 			goto err_mutex;
580 	}
581 	res = write_ent(ta->db, idx, &ta->entry);
582 	if (res)
583 		goto err_mutex;
584 	if (have_old_ent)
585 		clear_file(ta->db, old_ent.file_number);
586 	mutex_unlock(&tadb_mutex);
587 
588 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
589 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
590 	tadb_put(ta->db);
591 	free(ta);
592 	if (have_old_ent)
593 		ta_operation_remove(old_ent.file_number);
594 	return TEE_SUCCESS;
595 
596 err_mutex:
597 	mutex_unlock(&tadb_mutex);
598 err:
599 	tee_tadb_ta_close_and_delete(ta);
600 	return res;
601 }
602 
603 TEE_Result tee_tadb_ta_delete(const TEE_UUID *uuid)
604 {
605 	const struct tadb_entry null_entry = { { { 0 } } };
606 	struct tee_tadb_dir *db;
607 	struct tadb_entry entry;
608 	size_t idx;
609 	TEE_Result res;
610 
611 	if (is_null_uuid(uuid))
612 		return TEE_ERROR_GENERIC;
613 
614 	res = tee_tadb_open(&db);
615 	if (res)
616 		return res;
617 
618 	mutex_lock(&tadb_mutex);
619 	res = find_ent(db, uuid, &idx, &entry);
620 	if (res) {
621 		mutex_unlock(&tadb_mutex);
622 		tee_tadb_close(db);
623 		return res;
624 	}
625 
626 	clear_file(db, entry.file_number);
627 	res = write_ent(db, idx, &null_entry);
628 	mutex_unlock(&tadb_mutex);
629 
630 	tee_tadb_close(db);
631 	if (res)
632 		return res;
633 
634 	ta_operation_remove(entry.file_number);
635 	return TEE_SUCCESS;
636 }
637 
638 TEE_Result tee_tadb_ta_open(const TEE_UUID *uuid,
639 			    struct tee_tadb_ta_read **ta_ret)
640 {
641 	TEE_Result res;
642 	size_t idx;
643 	struct tee_tadb_ta_read *ta;
644 	static struct tadb_entry last_entry;
645 
646 	if (is_null_uuid(uuid))
647 		return TEE_ERROR_GENERIC;
648 
649 	ta = calloc(1, sizeof(*ta));
650 	if (!ta)
651 		return TEE_ERROR_OUT_OF_MEMORY;
652 
653 	if (!memcmp(uuid, &last_entry.prop.uuid, sizeof(*uuid))) {
654 		ta->entry = last_entry;
655 	} else {
656 		res = tee_tadb_open(&ta->db);
657 		if (res)
658 			goto err_free; /* Mustn't all tadb_put() */
659 
660 		mutex_read_lock(&tadb_mutex);
661 		res = find_ent(ta->db, uuid, &idx, &ta->entry);
662 		mutex_read_unlock(&tadb_mutex);
663 		if (res)
664 			goto err;
665 	}
666 
667 	res = ta_operation_open(OPTEE_MRF_OPEN, ta->entry.file_number, &ta->fd);
668 	if (res)
669 		goto err;
670 
671 	res = tadb_authenc_init(TEE_MODE_DECRYPT, &ta->entry, &ta->ctx);
672 	if (res)
673 		goto err;
674 
675 	*ta_ret = ta;
676 
677 	return TEE_SUCCESS;
678 err:
679 	tadb_put(ta->db);
680 err_free:
681 	free(ta);
682 	return res;
683 }
684 
685 const struct tee_tadb_property *
686 tee_tadb_ta_get_property(struct tee_tadb_ta_read *ta)
687 {
688 	return &ta->entry.prop;
689 }
690 
691 static TEE_Result ta_load(struct tee_tadb_ta_read *ta)
692 {
693 	TEE_Result res;
694 	const size_t sz = ta->entry.prop.custom_size + ta->entry.prop.bin_size;
695 	struct optee_msg_param params[2] = {
696 		[0] = { .attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT,
697 			.u.value.a = OPTEE_MRF_READ,
698 			.u.value.b = ta->fd,
699 			.u.value.c = 0 },
700 	};
701 
702 	if (ta->ta_mobj)
703 		return TEE_SUCCESS;
704 
705 	ta->ta_mobj = thread_rpc_alloc_payload(sz, &ta->ta_cookie);
706 	if (!ta->ta_mobj)
707 		return TEE_ERROR_OUT_OF_MEMORY;
708 
709 	ta->ta_buf = mobj_get_va(ta->ta_mobj, 0);
710 	assert(ta->ta_buf);
711 
712 	if (!msg_param_init_memparam(params + 1, ta->ta_mobj, 0, sz,
713 				     ta->ta_cookie, MSG_PARAM_MEM_DIR_OUT))
714 		return TEE_ERROR_BAD_STATE;
715 
716 	res = thread_rpc_cmd(OPTEE_MSG_RPC_CMD_FS, ARRAY_SIZE(params), params);
717 	if (res) {
718 		thread_rpc_free_payload(ta->ta_cookie, ta->ta_mobj);
719 		ta->ta_mobj = NULL;
720 	}
721 	return res;
722 }
723 
724 TEE_Result tee_tadb_ta_read(struct tee_tadb_ta_read *ta, void *buf, size_t *len)
725 {
726 	TEE_Result res;
727 	const size_t sz = ta->entry.prop.custom_size + ta->entry.prop.bin_size;
728 	size_t l = MIN(*len, sz - ta->pos);
729 
730 	res = ta_load(ta);
731 	if (res)
732 		return res;
733 
734 	if (buf) {
735 		res = tadb_update_payload(ta->ctx, TEE_MODE_DECRYPT,
736 					  ta->ta_buf + ta->pos, l, buf);
737 		if (res)
738 			return res;
739 	} else {
740 		size_t num_bytes = 0;
741 		size_t b_size = MIN(256U, l);
742 		uint8_t *b = malloc(b_size);
743 
744 		if (!b)
745 			return TEE_ERROR_OUT_OF_MEMORY;
746 
747 		while (num_bytes < l) {
748 			size_t n = MIN(b_size, l - num_bytes);
749 
750 			res = tadb_update_payload(ta->ctx, TEE_MODE_DECRYPT,
751 						  ta->ta_buf + ta->pos +
752 							num_bytes, n, b);
753 			if (res)
754 				break;
755 			num_bytes += n;
756 		}
757 
758 		free(b);
759 		if (res)
760 			return res;
761 	}
762 
763 	ta->pos += l;
764 	if (ta->pos == sz) {
765 		size_t dl = 0;
766 
767 		res = crypto_authenc_dec_final(ta->ctx, TADB_AUTH_ENC_ALG,
768 					       NULL, 0, NULL, &dl,
769 					       ta->entry.tag, TADB_TAG_SIZE);
770 		if (res)
771 			return res;
772 	}
773 	*len = l;
774 	return TEE_SUCCESS;
775 }
776 
777 void tee_tadb_ta_close(struct tee_tadb_ta_read *ta)
778 {
779 	crypto_authenc_final(ta->ctx, TADB_AUTH_ENC_ALG);
780 	crypto_authenc_free_ctx(ta->ctx, TADB_AUTH_ENC_ALG);
781 	if (ta->ta_mobj)
782 		thread_rpc_free_payload(ta->ta_cookie, ta->ta_mobj);
783 	tee_fs_rpc_close(OPTEE_MSG_RPC_CMD_FS, ta->fd);
784 	tadb_put(ta->db);
785 	free(ta);
786 }
787