xref: /optee_os/core/tee/tee_rpmb_fs.c (revision 2391d619a7d07dbc2526a2a6b8ba01a44589becb)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, STMicroelectronics International N.V.
4  */
5 
6 #include <assert.h>
7 #include <config.h>
8 #include <crypto/crypto.h>
9 #include <kernel/huk_subkey.h>
10 #include <kernel/misc.h>
11 #include <kernel/msg_param.h>
12 #include <kernel/mutex.h>
13 #include <kernel/panic.h>
14 #include <kernel/tee_common.h>
15 #include <kernel/tee_common_otp.h>
16 #include <kernel/tee_misc.h>
17 #include <kernel/thread.h>
18 #include <mempool.h>
19 #include <mm/core_memprot.h>
20 #include <mm/mobj.h>
21 #include <mm/tee_mm.h>
22 #include <optee_rpc_cmd.h>
23 #include <stdlib.h>
24 #include <string_ext.h>
25 #include <string.h>
26 #include <sys/queue.h>
27 #include <tee/tee_fs.h>
28 #include <tee/tee_fs_key_manager.h>
29 #include <tee/tee_pobj.h>
30 #include <tee/tee_svc_storage.h>
31 #include <trace.h>
32 #include <util.h>
33 
34 #define RPMB_STORAGE_START_ADDRESS      0
35 #define RPMB_FS_FAT_START_ADDRESS       512
36 #define RPMB_BLOCK_SIZE_SHIFT           8
37 #define RPMB_CID_PRV_OFFSET             9
38 #define RPMB_CID_CRC_OFFSET             15
39 
40 #define RPMB_FS_MAGIC                   0x52504D42
41 #define FS_VERSION                      2
42 
43 #define FILE_IS_ACTIVE                  (1u << 0)
44 #define FILE_IS_LAST_ENTRY              (1u << 1)
45 
46 #define TEE_RPMB_FS_FILENAME_LENGTH 224
47 
48 #define TMP_BLOCK_SIZE			4096U
49 
50 #define RPMB_MAX_RETRIES		10
51 
52 /**
53  * Utilized when caching is enabled, i.e., when CFG_RPMB_FS_CACHE_ENTRIES > 0.
54  * Cache size + the number of entries that are repeatedly read in and buffered
55  * once the cache is full.
56  */
57 #define RPMB_BUF_MAX_ENTRIES (CFG_RPMB_FS_CACHE_ENTRIES + \
58 			      CFG_RPMB_FS_RD_ENTRIES)
59 
60 /**
61  * FS parameters: Information often used by internal functions.
62  * fat_start_address will be set by rpmb_fs_setup().
63  * rpmb_fs_parameters can be read by any other function.
64  */
65 struct rpmb_fs_parameters {
66 	uint32_t fat_start_address;
67 	uint32_t max_rpmb_address;
68 };
69 
70 /**
71  * File entry for a single file in a RPMB_FS partition.
72  */
73 struct rpmb_fat_entry {
74 	uint32_t start_address;
75 	uint32_t data_size;
76 	uint32_t flags;
77 	uint32_t write_counter;
78 	uint8_t fek[TEE_FS_KM_FEK_SIZE];
79 	char filename[TEE_RPMB_FS_FILENAME_LENGTH];
80 };
81 
82 /**
83  * Structure that describes buffered/cached FAT FS entries in RPMB storage.
84  * This structure is used in functions traversing the FAT FS.
85  */
86 struct rpmb_fat_entry_dir {
87 	/*
88 	 * Buffer storing the FAT FS entries read in from RPMB storage. It
89 	 * includes the optional cache entries (CFG_RPMB_FS_CACHE_ENTRIES)
90 	 * and entries temporary read for current FAT FS traversal
91 	 * (CFG_RPMB_FS_RD_ENTRIES) when not found from cached entries.
92 	 */
93 	struct rpmb_fat_entry *rpmb_fat_entry_buf;
94 	/* Current index of FAT FS entry to read from buffer. */
95 	uint32_t idx_curr;
96 	/* Total number of FAT FS entries in buffer. */
97 	uint32_t num_buffered;
98 	/* Total number of FAT FS entries read during traversal. */
99 	uint32_t num_total_read;
100 	/* Indicates that last FAT FS entry was read. */
101 	bool last_reached;
102 };
103 
104 /**
105  * FAT entry context with reference to a FAT entry and its
106  * location in RPMB.
107  */
108 struct rpmb_file_handle {
109 	struct rpmb_fat_entry fat_entry;
110 	const TEE_UUID *uuid;
111 	char filename[TEE_RPMB_FS_FILENAME_LENGTH];
112 	/* Address for current entry in RPMB */
113 	uint32_t rpmb_fat_address;
114 };
115 
116 /**
117  * RPMB_FS partition data
118  */
119 struct rpmb_fs_partition {
120 	uint32_t rpmb_fs_magic;
121 	uint32_t fs_version;
122 	uint32_t write_counter;
123 	uint32_t fat_start_address;
124 	/* Do not use reserved[] for other purpose than partition data. */
125 	uint8_t reserved[112];
126 };
127 
128 /**
129  * A node in a list of directory entries.
130  */
131 struct tee_rpmb_fs_dirent {
132 	struct tee_fs_dirent entry;
133 	SIMPLEQ_ENTRY(tee_rpmb_fs_dirent) link;
134 };
135 
136 /**
137  * The RPMB directory representation. It contains a queue of
138  * RPMB directory entries: 'next'.
139  * The current pointer points to the last directory entry
140  * returned by readdir().
141  */
142 struct tee_fs_dir {
143 	struct tee_rpmb_fs_dirent *current;
144 	/* */
145 	SIMPLEQ_HEAD(next_head, tee_rpmb_fs_dirent) next;
146 };
147 
148 static struct rpmb_fs_parameters *fs_par;
149 static struct rpmb_fat_entry_dir *fat_entry_dir;
150 
151 /*
152  * Lower interface to RPMB device
153  */
154 
155 #define RPMB_DATA_OFFSET            (RPMB_STUFF_DATA_SIZE + RPMB_KEY_MAC_SIZE)
156 #define RPMB_MAC_PROTECT_DATA_SIZE  (RPMB_DATA_FRAME_SIZE - RPMB_DATA_OFFSET)
157 
158 #define RPMB_MSG_TYPE_REQ_AUTH_KEY_PROGRAM          0x0001
159 #define RPMB_MSG_TYPE_REQ_WRITE_COUNTER_VAL_READ    0x0002
160 #define RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE           0x0003
161 #define RPMB_MSG_TYPE_REQ_AUTH_DATA_READ            0x0004
162 #define RPMB_MSG_TYPE_REQ_RESULT_READ               0x0005
163 #define RPMB_MSG_TYPE_RESP_AUTH_KEY_PROGRAM         0x0100
164 #define RPMB_MSG_TYPE_RESP_WRITE_COUNTER_VAL_READ   0x0200
165 #define RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE          0x0300
166 #define RPMB_MSG_TYPE_RESP_AUTH_DATA_READ           0x0400
167 
168 #define RPMB_STUFF_DATA_SIZE                        196
169 #define RPMB_KEY_MAC_SIZE                           32
170 #define RPMB_DATA_SIZE                              256
171 #define RPMB_NONCE_SIZE                             16
172 #define RPMB_DATA_FRAME_SIZE                        512
173 
174 #define RPMB_RESULT_OK                              0x00
175 #define RPMB_RESULT_GENERAL_FAILURE                 0x01
176 #define RPMB_RESULT_AUTH_FAILURE                    0x02
177 #define RPMB_RESULT_COUNTER_FAILURE                 0x03
178 #define RPMB_RESULT_ADDRESS_FAILURE                 0x04
179 #define RPMB_RESULT_WRITE_FAILURE                   0x05
180 #define RPMB_RESULT_READ_FAILURE                    0x06
181 #define RPMB_RESULT_AUTH_KEY_NOT_PROGRAMMED         0x07
182 #define RPMB_RESULT_MASK                            0x3F
183 #define RPMB_RESULT_WR_CNT_EXPIRED                  0x80
184 
185 /* RPMB internal commands */
186 #define RPMB_CMD_DATA_REQ      0x00
187 #define RPMB_CMD_GET_DEV_INFO  0x01
188 
189 #define RPMB_SIZE_SINGLE (128 * 1024)
190 
191 /* Error codes for get_dev_info request/response. */
192 #define RPMB_CMD_GET_DEV_INFO_RET_OK     0x00
193 #define RPMB_CMD_GET_DEV_INFO_RET_ERROR  0x01
194 
195 struct rpmb_data_frame {
196 	uint8_t stuff_bytes[RPMB_STUFF_DATA_SIZE];
197 	uint8_t key_mac[RPMB_KEY_MAC_SIZE];
198 	uint8_t data[RPMB_DATA_SIZE];
199 	uint8_t nonce[RPMB_NONCE_SIZE];
200 	uint8_t write_counter[4];
201 	uint8_t address[2];
202 	uint8_t block_count[2];
203 	uint8_t op_result[2];
204 	uint8_t msg_type[2];
205 };
206 
207 struct rpmb_req {
208 	uint16_t cmd;
209 	uint16_t dev_id;
210 	uint16_t block_count;
211 	/* variable length of data */
212 	/* uint8_t data[]; REMOVED! */
213 };
214 
215 #define TEE_RPMB_REQ_DATA(req) \
216 		((void *)((struct rpmb_req *)(req) + 1))
217 
218 struct rpmb_raw_data {
219 	uint16_t msg_type;
220 	uint16_t *op_result;
221 	uint16_t *block_count;
222 	uint16_t *blk_idx;
223 	uint32_t *write_counter;
224 	uint8_t *nonce;
225 	uint8_t *key_mac;
226 	uint8_t *data;
227 	/* data length to read or write */
228 	uint32_t len;
229 	/* Byte address offset in the first block involved */
230 	uint8_t byte_offset;
231 };
232 
233 #define RPMB_EMMC_CID_SIZE 16
234 struct rpmb_dev_info {
235 	uint8_t cid[RPMB_EMMC_CID_SIZE];
236 	/* EXT CSD-slice 168 "RPMB Size" */
237 	uint8_t rpmb_size_mult;
238 	/* EXT CSD-slice 222 "Reliable Write Sector Count" */
239 	uint8_t rel_wr_sec_c;
240 	/* Check the ret code and accept the data only if it is OK. */
241 	uint8_t ret_code;
242 };
243 
244 /*
245  * Struct for rpmb context data.
246  *
247  * @key              RPMB key.
248  * @cid              eMMC card ID.
249  * @wr_cnt           Current write counter.
250  * @max_blk_idx      The highest block index supported by current device.
251  * @rel_wr_blkcnt    Max number of data blocks for each reliable write.
252  * @dev_id           Device ID of the eMMC device.
253  * @wr_cnt_synced    Flag indicating if write counter is synced to RPMB.
254  * @key_derived      Flag indicating if key has been generated.
255  * @key_verified     Flag indicating the key generated is verified ok.
256  * @dev_info_synced  Flag indicating if dev info has been retrieved from RPMB.
257  */
258 struct tee_rpmb_ctx {
259 	uint8_t key[RPMB_KEY_MAC_SIZE];
260 	uint8_t cid[RPMB_EMMC_CID_SIZE];
261 	uint32_t wr_cnt;
262 	uint16_t max_blk_idx;
263 	uint16_t rel_wr_blkcnt;
264 	uint16_t dev_id;
265 	bool wr_cnt_synced;
266 	bool key_derived;
267 	bool key_verified;
268 	bool dev_info_synced;
269 };
270 
271 static struct tee_rpmb_ctx *rpmb_ctx;
272 
273 /* If set to true, don't try to access RPMB until rebooted */
274 static bool rpmb_dead;
275 
276 /*
277  * Mutex to serialize the operations exported by this file.
278  * It protects rpmb_ctx and prevents overlapping operations on eMMC devices with
279  * different IDs.
280  */
281 static struct mutex rpmb_mutex = MUTEX_INITIALIZER;
282 
283 #ifdef CFG_RPMB_TESTKEY
284 
285 static const uint8_t rpmb_test_key[RPMB_KEY_MAC_SIZE] = {
286 	0xD3, 0xEB, 0x3E, 0xC3, 0x6E, 0x33, 0x4C, 0x9F,
287 	0x98, 0x8C, 0xE2, 0xC0, 0xB8, 0x59, 0x54, 0x61,
288 	0x0D, 0x2B, 0xCF, 0x86, 0x64, 0x84, 0x4D, 0xF2,
289 	0xAB, 0x56, 0xE6, 0xC6, 0x1B, 0xB7, 0x01, 0xE4
290 };
291 
292 static TEE_Result tee_rpmb_key_gen(uint16_t dev_id __unused,
293 				   uint8_t *key, uint32_t len)
294 {
295 	TEE_Result res = TEE_SUCCESS;
296 
297 	if (!key || RPMB_KEY_MAC_SIZE != len) {
298 		res = TEE_ERROR_BAD_PARAMETERS;
299 		goto out;
300 	}
301 
302 	DMSG("RPMB: Using test key");
303 	memcpy(key, rpmb_test_key, RPMB_KEY_MAC_SIZE);
304 
305 out:
306 	return res;
307 }
308 
309 #else /* !CFG_RPMB_TESTKEY */
310 
311 static TEE_Result tee_rpmb_key_gen(uint16_t dev_id __unused,
312 				   uint8_t *key, uint32_t len)
313 {
314 	uint8_t message[RPMB_EMMC_CID_SIZE];
315 
316 	if (!key || RPMB_KEY_MAC_SIZE != len)
317 		return TEE_ERROR_BAD_PARAMETERS;
318 
319 	IMSG("RPMB: Using generated key");
320 
321 	/*
322 	 * PRV/CRC would be changed when doing eMMC FFU
323 	 * The following fields should be masked off when deriving RPMB key
324 	 *
325 	 * CID [55: 48]: PRV (Product revision)
326 	 * CID [07: 01]: CRC (CRC7 checksum)
327 	 * CID [00]: not used
328 	 */
329 	memcpy(message, rpmb_ctx->cid, RPMB_EMMC_CID_SIZE);
330 	memset(message + RPMB_CID_PRV_OFFSET, 0, 1);
331 	memset(message + RPMB_CID_CRC_OFFSET, 0, 1);
332 	return huk_subkey_derive(HUK_SUBKEY_RPMB, message, sizeof(message),
333 				 key, len);
334 }
335 
336 #endif /* !CFG_RPMB_TESTKEY */
337 
338 static void u32_to_bytes(uint32_t u32, uint8_t *bytes)
339 {
340 	*bytes = (uint8_t) (u32 >> 24);
341 	*(bytes + 1) = (uint8_t) (u32 >> 16);
342 	*(bytes + 2) = (uint8_t) (u32 >> 8);
343 	*(bytes + 3) = (uint8_t) u32;
344 }
345 
346 static void bytes_to_u32(uint8_t *bytes, uint32_t *u32)
347 {
348 	*u32 = (uint32_t) ((*(bytes) << 24) +
349 			   (*(bytes + 1) << 16) +
350 			   (*(bytes + 2) << 8) + (*(bytes + 3)));
351 }
352 
353 static void u16_to_bytes(uint16_t u16, uint8_t *bytes)
354 {
355 	*bytes = (uint8_t) (u16 >> 8);
356 	*(bytes + 1) = (uint8_t) u16;
357 }
358 
359 static void bytes_to_u16(uint8_t *bytes, uint16_t *u16)
360 {
361 	*u16 = (uint16_t) ((*bytes << 8) + *(bytes + 1));
362 }
363 
364 static void get_op_result_bits(uint8_t *bytes, uint8_t *res)
365 {
366 	*res = *(bytes + 1) & RPMB_RESULT_MASK;
367 }
368 
369 static TEE_Result tee_rpmb_mac_calc(uint8_t *mac, uint32_t macsize,
370 				    uint8_t *key, uint32_t keysize,
371 				    struct rpmb_data_frame *datafrms,
372 				    uint16_t blkcnt)
373 {
374 	TEE_Result res = TEE_ERROR_GENERIC;
375 	int i;
376 	void *ctx = NULL;
377 
378 	if (!mac || !key || !datafrms)
379 		return TEE_ERROR_BAD_PARAMETERS;
380 
381 	res = crypto_mac_alloc_ctx(&ctx, TEE_ALG_HMAC_SHA256);
382 	if (res)
383 		return res;
384 
385 	res = crypto_mac_init(ctx, key, keysize);
386 	if (res != TEE_SUCCESS)
387 		goto func_exit;
388 
389 	for (i = 0; i < blkcnt; i++) {
390 		res = crypto_mac_update(ctx, datafrms[i].data,
391 					RPMB_MAC_PROTECT_DATA_SIZE);
392 		if (res != TEE_SUCCESS)
393 			goto func_exit;
394 	}
395 
396 	res = crypto_mac_final(ctx, mac, macsize);
397 	if (res != TEE_SUCCESS)
398 		goto func_exit;
399 
400 	res = TEE_SUCCESS;
401 
402 func_exit:
403 	crypto_mac_free_ctx(ctx);
404 	return res;
405 }
406 
407 struct tee_rpmb_mem {
408 	struct mobj *phreq_mobj;
409 	struct mobj *phresp_mobj;
410 	size_t req_size;
411 	size_t resp_size;
412 };
413 
414 static void tee_rpmb_free(struct tee_rpmb_mem *mem)
415 {
416 	if (!mem)
417 		return;
418 
419 	if (mem->phreq_mobj) {
420 		thread_rpc_free_payload(mem->phreq_mobj);
421 		mem->phreq_mobj = NULL;
422 	}
423 	if (mem->phresp_mobj) {
424 		thread_rpc_free_payload(mem->phresp_mobj);
425 		mem->phresp_mobj = NULL;
426 	}
427 }
428 
429 
430 static TEE_Result tee_rpmb_alloc(size_t req_size, size_t resp_size,
431 		struct tee_rpmb_mem *mem, void **req, void **resp)
432 {
433 	TEE_Result res = TEE_SUCCESS;
434 	size_t req_s = ROUNDUP(req_size, sizeof(uint32_t));
435 	size_t resp_s = ROUNDUP(resp_size, sizeof(uint32_t));
436 
437 	if (!mem)
438 		return TEE_ERROR_BAD_PARAMETERS;
439 
440 	memset(mem, 0, sizeof(*mem));
441 
442 	mem->phreq_mobj = thread_rpc_alloc_payload(req_s);
443 	mem->phresp_mobj = thread_rpc_alloc_payload(resp_s);
444 
445 	if (!mem->phreq_mobj || !mem->phresp_mobj) {
446 		res = TEE_ERROR_OUT_OF_MEMORY;
447 		goto out;
448 	}
449 
450 	*req = mobj_get_va(mem->phreq_mobj, 0);
451 	*resp = mobj_get_va(mem->phresp_mobj, 0);
452 	if (!*req || !*resp) {
453 		res = TEE_ERROR_GENERIC;
454 		goto out;
455 	}
456 
457 	mem->req_size = req_size;
458 	mem->resp_size = resp_size;
459 
460 out:
461 	if (res != TEE_SUCCESS)
462 		tee_rpmb_free(mem);
463 	return res;
464 }
465 
466 static TEE_Result tee_rpmb_invoke(struct tee_rpmb_mem *mem)
467 {
468 	struct thread_param params[2] = {
469 		[0] = THREAD_PARAM_MEMREF(IN, mem->phreq_mobj, 0,
470 					  mem->req_size),
471 		[1] = THREAD_PARAM_MEMREF(OUT, mem->phresp_mobj, 0,
472 					  mem->resp_size),
473 	};
474 
475 	return thread_rpc_cmd(OPTEE_RPC_CMD_RPMB, 2, params);
476 }
477 
478 static bool is_zero(const uint8_t *buf, size_t size)
479 {
480 	size_t i;
481 
482 	for (i = 0; i < size; i++)
483 		if (buf[i])
484 			return false;
485 	return true;
486 }
487 
488 static TEE_Result encrypt_block(uint8_t *out, const uint8_t *in,
489 				uint16_t blk_idx, const uint8_t *fek,
490 				const TEE_UUID *uuid)
491 {
492 	return tee_fs_crypt_block(uuid, out, in, RPMB_DATA_SIZE,
493 				  blk_idx, fek, TEE_MODE_ENCRYPT);
494 }
495 
496 static TEE_Result decrypt_block(uint8_t *out, const uint8_t *in,
497 				uint16_t blk_idx, const uint8_t *fek,
498 				const TEE_UUID *uuid)
499 {
500 	return tee_fs_crypt_block(uuid, out, in, RPMB_DATA_SIZE,
501 				  blk_idx, fek, TEE_MODE_DECRYPT);
502 }
503 
504 /* Decrypt/copy at most one block of data */
505 static TEE_Result decrypt(uint8_t *out, const struct rpmb_data_frame *frm,
506 			  size_t size, size_t offset,
507 			  uint16_t blk_idx __maybe_unused, const uint8_t *fek,
508 			  const TEE_UUID *uuid)
509 {
510 	uint8_t *tmp __maybe_unused;
511 	TEE_Result res = TEE_SUCCESS;
512 
513 
514 	if ((size + offset < size) || (size + offset > RPMB_DATA_SIZE))
515 		panic("invalid size or offset");
516 
517 	if (!fek) {
518 		/* Block is not encrypted (not a file data block) */
519 		memcpy(out, frm->data + offset, size);
520 	} else if (is_zero(fek, TEE_FS_KM_FEK_SIZE)) {
521 		/* The file was created with encryption disabled */
522 		return TEE_ERROR_SECURITY;
523 	} else {
524 		/* Block is encrypted */
525 		if (size < RPMB_DATA_SIZE) {
526 			/*
527 			 * Since output buffer is not large enough to hold one
528 			 * block we must allocate a temporary buffer.
529 			 */
530 			tmp = malloc(RPMB_DATA_SIZE);
531 			if (!tmp)
532 				return TEE_ERROR_OUT_OF_MEMORY;
533 			res = decrypt_block(tmp, frm->data, blk_idx, fek, uuid);
534 			if (res == TEE_SUCCESS)
535 				memcpy(out, tmp + offset, size);
536 			free(tmp);
537 		} else {
538 			res = decrypt_block(out, frm->data, blk_idx, fek, uuid);
539 		}
540 	}
541 
542 	return res;
543 }
544 
545 static TEE_Result tee_rpmb_req_pack(struct rpmb_req *req,
546 				    struct rpmb_raw_data *rawdata,
547 				    uint16_t nbr_frms, uint16_t dev_id,
548 				    const uint8_t *fek, const TEE_UUID *uuid)
549 {
550 	TEE_Result res = TEE_ERROR_GENERIC;
551 	int i;
552 	struct rpmb_data_frame *datafrm;
553 
554 	if (!req || !rawdata || !nbr_frms)
555 		return TEE_ERROR_BAD_PARAMETERS;
556 
557 	/*
558 	 * Check write blockcount is not bigger than reliable write
559 	 * blockcount.
560 	 */
561 	if ((rawdata->msg_type == RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE) &&
562 	    (nbr_frms > rpmb_ctx->rel_wr_blkcnt)) {
563 		DMSG("wr_blkcnt(%d) > rel_wr_blkcnt(%d)", nbr_frms,
564 		     rpmb_ctx->rel_wr_blkcnt);
565 		return TEE_ERROR_GENERIC;
566 	}
567 
568 	req->cmd = RPMB_CMD_DATA_REQ;
569 	req->dev_id = dev_id;
570 
571 	/* Allocate memory for construct all data packets and calculate MAC. */
572 	datafrm = calloc(nbr_frms, RPMB_DATA_FRAME_SIZE);
573 	if (!datafrm)
574 		return TEE_ERROR_OUT_OF_MEMORY;
575 
576 	for (i = 0; i < nbr_frms; i++) {
577 		u16_to_bytes(rawdata->msg_type, datafrm[i].msg_type);
578 
579 		if (rawdata->block_count)
580 			u16_to_bytes(*rawdata->block_count,
581 				     datafrm[i].block_count);
582 
583 		if (rawdata->blk_idx) {
584 			/* Check the block index is within range. */
585 			if ((*rawdata->blk_idx + nbr_frms - 1) >
586 			    rpmb_ctx->max_blk_idx) {
587 				res = TEE_ERROR_GENERIC;
588 				goto func_exit;
589 			}
590 			u16_to_bytes(*rawdata->blk_idx, datafrm[i].address);
591 		}
592 
593 		if (rawdata->write_counter)
594 			u32_to_bytes(*rawdata->write_counter,
595 				     datafrm[i].write_counter);
596 
597 		if (rawdata->nonce)
598 			memcpy(datafrm[i].nonce, rawdata->nonce,
599 			       RPMB_NONCE_SIZE);
600 
601 		if (rawdata->data) {
602 			if (fek) {
603 				res = encrypt_block(datafrm[i].data,
604 						    rawdata->data +
605 						    (i * RPMB_DATA_SIZE),
606 						    *rawdata->blk_idx + i,
607 						    fek, uuid);
608 				if (res != TEE_SUCCESS)
609 					goto func_exit;
610 			} else {
611 				memcpy(datafrm[i].data,
612 				       rawdata->data + (i * RPMB_DATA_SIZE),
613 				       RPMB_DATA_SIZE);
614 			}
615 		}
616 	}
617 
618 	if (rawdata->key_mac) {
619 		if (rawdata->msg_type == RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE) {
620 			res =
621 			    tee_rpmb_mac_calc(rawdata->key_mac,
622 					      RPMB_KEY_MAC_SIZE, rpmb_ctx->key,
623 					      RPMB_KEY_MAC_SIZE, datafrm,
624 					      nbr_frms);
625 			if (res != TEE_SUCCESS)
626 				goto func_exit;
627 		}
628 		memcpy(datafrm[nbr_frms - 1].key_mac,
629 		       rawdata->key_mac, RPMB_KEY_MAC_SIZE);
630 	}
631 
632 	memcpy(TEE_RPMB_REQ_DATA(req), datafrm,
633 	       nbr_frms * RPMB_DATA_FRAME_SIZE);
634 
635 	if (IS_ENABLED(CFG_RPMB_FS_DEBUG_DATA)) {
636 		for (i = 0; i < nbr_frms; i++) {
637 			DMSG("Dumping data frame %d:", i);
638 			DHEXDUMP((uint8_t *)&datafrm[i] + RPMB_STUFF_DATA_SIZE,
639 				 512 - RPMB_STUFF_DATA_SIZE);
640 		}
641 	}
642 
643 	res = TEE_SUCCESS;
644 func_exit:
645 	free(datafrm);
646 	return res;
647 }
648 
649 static TEE_Result data_cpy_mac_calc_1b(struct rpmb_raw_data *rawdata,
650 				       struct rpmb_data_frame *frm,
651 				       const uint8_t *fek, const TEE_UUID *uuid)
652 {
653 	TEE_Result res;
654 	uint8_t *data;
655 	uint16_t idx;
656 
657 	if (rawdata->len + rawdata->byte_offset > RPMB_DATA_SIZE)
658 		return TEE_ERROR_BAD_PARAMETERS;
659 
660 	res = tee_rpmb_mac_calc(rawdata->key_mac, RPMB_KEY_MAC_SIZE,
661 				rpmb_ctx->key, RPMB_KEY_MAC_SIZE, frm, 1);
662 	if (res != TEE_SUCCESS)
663 		return res;
664 
665 	data = rawdata->data;
666 	bytes_to_u16(frm->address, &idx);
667 
668 	res = decrypt(data, frm, rawdata->len, rawdata->byte_offset, idx, fek,
669 		      uuid);
670 	return res;
671 }
672 
673 static TEE_Result tee_rpmb_data_cpy_mac_calc(struct rpmb_data_frame *datafrm,
674 					     struct rpmb_raw_data *rawdata,
675 					     uint16_t nbr_frms,
676 					     struct rpmb_data_frame *lastfrm,
677 					     const uint8_t *fek,
678 					     const TEE_UUID *uuid)
679 {
680 	TEE_Result res = TEE_ERROR_GENERIC;
681 	int i;
682 	void *ctx = NULL;
683 	uint16_t offset;
684 	uint32_t size;
685 	uint8_t *data;
686 	uint16_t start_idx;
687 	struct rpmb_data_frame localfrm;
688 
689 	if (!datafrm || !rawdata || !nbr_frms || !lastfrm)
690 		return TEE_ERROR_BAD_PARAMETERS;
691 
692 	if (nbr_frms == 1)
693 		return data_cpy_mac_calc_1b(rawdata, lastfrm, fek, uuid);
694 
695 	/* nbr_frms > 1 */
696 
697 	data = rawdata->data;
698 
699 	res = crypto_mac_alloc_ctx(&ctx, TEE_ALG_HMAC_SHA256);
700 	if (res)
701 		goto func_exit;
702 
703 	res = crypto_mac_init(ctx, rpmb_ctx->key, RPMB_KEY_MAC_SIZE);
704 	if (res != TEE_SUCCESS)
705 		goto func_exit;
706 
707 	/*
708 	 * Note: JEDEC JESD84-B51: "In every packet the address is the start
709 	 * address of the full access (not address of the individual half a
710 	 * sector)"
711 	 */
712 	bytes_to_u16(lastfrm->address, &start_idx);
713 
714 	for (i = 0; i < (nbr_frms - 1); i++) {
715 
716 		/*
717 		 * By working on a local copy of the RPMB frame, we ensure that
718 		 * the data can not be modified after the MAC is computed but
719 		 * before the payload is decrypted/copied to the output buffer.
720 		 */
721 		memcpy(&localfrm, &datafrm[i], RPMB_DATA_FRAME_SIZE);
722 
723 		res = crypto_mac_update(ctx, localfrm.data,
724 					RPMB_MAC_PROTECT_DATA_SIZE);
725 		if (res != TEE_SUCCESS)
726 			goto func_exit;
727 
728 		if (i == 0) {
729 			/* First block */
730 			offset = rawdata->byte_offset;
731 			size = RPMB_DATA_SIZE - offset;
732 		} else {
733 			/* Middle blocks */
734 			size = RPMB_DATA_SIZE;
735 			offset = 0;
736 		}
737 
738 		res = decrypt(data, &localfrm, size, offset, start_idx + i,
739 			      fek, uuid);
740 		if (res != TEE_SUCCESS)
741 			goto func_exit;
742 
743 		data += size;
744 	}
745 
746 	/* Last block */
747 	size = (rawdata->len + rawdata->byte_offset) % RPMB_DATA_SIZE;
748 	if (size == 0)
749 		size = RPMB_DATA_SIZE;
750 	res = decrypt(data, lastfrm, size, 0, start_idx + nbr_frms - 1, fek,
751 		      uuid);
752 	if (res != TEE_SUCCESS)
753 		goto func_exit;
754 
755 	/* Update MAC against the last block */
756 	res = crypto_mac_update(ctx, lastfrm->data, RPMB_MAC_PROTECT_DATA_SIZE);
757 	if (res != TEE_SUCCESS)
758 		goto func_exit;
759 
760 	res = crypto_mac_final(ctx, rawdata->key_mac, RPMB_KEY_MAC_SIZE);
761 	if (res != TEE_SUCCESS)
762 		goto func_exit;
763 
764 	res = TEE_SUCCESS;
765 
766 func_exit:
767 	crypto_mac_free_ctx(ctx);
768 	return res;
769 }
770 
771 static TEE_Result tee_rpmb_resp_unpack_verify(struct rpmb_data_frame *datafrm,
772 					      struct rpmb_raw_data *rawdata,
773 					      uint16_t nbr_frms,
774 					      const uint8_t *fek,
775 					      const TEE_UUID *uuid)
776 {
777 	TEE_Result res = TEE_ERROR_GENERIC;
778 	uint16_t msg_type;
779 	uint32_t wr_cnt;
780 	uint16_t blk_idx;
781 	uint8_t op_result;
782 	struct rpmb_data_frame lastfrm;
783 
784 	if (!datafrm || !rawdata || !nbr_frms)
785 		return TEE_ERROR_BAD_PARAMETERS;
786 
787 	if (IS_ENABLED(CFG_RPMB_FS_DEBUG_DATA)) {
788 		size_t i = 0;
789 
790 		for (i = 0; i < nbr_frms; i++) {
791 			DMSG("Dumping data frame %zu:", i);
792 			DHEXDUMP((uint8_t *)&datafrm[i] + RPMB_STUFF_DATA_SIZE,
793 				 512 - RPMB_STUFF_DATA_SIZE);
794 		}
795 	}
796 
797 	/* Make sure the last data packet can't be modified once verified */
798 	memcpy(&lastfrm, &datafrm[nbr_frms - 1], RPMB_DATA_FRAME_SIZE);
799 
800 	/* Handle operation result and translate to TEEC error code. */
801 	get_op_result_bits(lastfrm.op_result, &op_result);
802 	if (op_result == RPMB_RESULT_AUTH_KEY_NOT_PROGRAMMED)
803 		return TEE_ERROR_ITEM_NOT_FOUND;
804 	if (op_result != RPMB_RESULT_OK)
805 		return TEE_ERROR_GENERIC;
806 
807 	/* Check the response msg_type. */
808 	bytes_to_u16(lastfrm.msg_type, &msg_type);
809 	if (msg_type != rawdata->msg_type) {
810 		DMSG("Unexpected msg_type (0x%04x != 0x%04x)", msg_type,
811 		     rawdata->msg_type);
812 		return TEE_ERROR_GENERIC;
813 	}
814 
815 	if (rawdata->blk_idx) {
816 		bytes_to_u16(lastfrm.address, &blk_idx);
817 		if (blk_idx != *rawdata->blk_idx) {
818 			DMSG("Unexpected block index");
819 			return TEE_ERROR_GENERIC;
820 		}
821 	}
822 
823 	if (rawdata->write_counter) {
824 		wr_cnt = *rawdata->write_counter;
825 		bytes_to_u32(lastfrm.write_counter, rawdata->write_counter);
826 		if (msg_type == RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE) {
827 			/* Verify the write counter is incremented by 1 */
828 			if (*rawdata->write_counter != wr_cnt + 1) {
829 				DMSG("Counter mismatched (0x%04x/0x%04x)",
830 				     *rawdata->write_counter, wr_cnt + 1);
831 				return TEE_ERROR_SECURITY;
832 			}
833 			rpmb_ctx->wr_cnt++;
834 		}
835 	}
836 
837 	if (rawdata->nonce) {
838 		if (buf_compare_ct(rawdata->nonce, lastfrm.nonce,
839 				   RPMB_NONCE_SIZE) != 0) {
840 			DMSG("Nonce mismatched");
841 			return TEE_ERROR_SECURITY;
842 		}
843 	}
844 
845 	if (rawdata->key_mac) {
846 		if (msg_type == RPMB_MSG_TYPE_RESP_AUTH_DATA_READ) {
847 			if (!rawdata->data)
848 				return TEE_ERROR_GENERIC;
849 
850 			res = tee_rpmb_data_cpy_mac_calc(datafrm, rawdata,
851 							 nbr_frms, &lastfrm,
852 							 fek, uuid);
853 
854 			if (res != TEE_SUCCESS)
855 				return res;
856 		} else {
857 			/*
858 			 * There should be only one data frame for
859 			 * other msg types.
860 			 */
861 			if (nbr_frms != 1)
862 				return TEE_ERROR_GENERIC;
863 
864 			res = tee_rpmb_mac_calc(rawdata->key_mac,
865 						RPMB_KEY_MAC_SIZE,
866 						rpmb_ctx->key,
867 						RPMB_KEY_MAC_SIZE,
868 						&lastfrm, 1);
869 
870 			if (res != TEE_SUCCESS)
871 				return res;
872 		}
873 
874 		if (consttime_memcmp(rawdata->key_mac,
875 				     (datafrm + nbr_frms - 1)->key_mac,
876 				     RPMB_KEY_MAC_SIZE) != 0) {
877 			DMSG("MAC mismatched:");
878 			if (IS_ENABLED(CFG_RPMB_FS_DEBUG_DATA))
879 				DHEXDUMP(rawdata->key_mac, RPMB_KEY_MAC_SIZE);
880 
881 			return TEE_ERROR_SECURITY;
882 		}
883 	}
884 
885 	return TEE_SUCCESS;
886 }
887 
888 static TEE_Result tee_rpmb_get_dev_info(uint16_t dev_id,
889 					struct rpmb_dev_info *dev_info)
890 {
891 	TEE_Result res = TEE_ERROR_GENERIC;
892 	struct tee_rpmb_mem mem;
893 	struct rpmb_dev_info *di;
894 	struct rpmb_req *req = NULL;
895 	uint8_t *resp = NULL;
896 	uint32_t req_size;
897 	uint32_t resp_size;
898 
899 	if (!dev_info)
900 		return TEE_ERROR_BAD_PARAMETERS;
901 
902 	req_size = sizeof(struct rpmb_req);
903 	resp_size = sizeof(struct rpmb_dev_info);
904 	res = tee_rpmb_alloc(req_size, resp_size, &mem,
905 			     (void *)&req, (void *)&resp);
906 	if (res != TEE_SUCCESS)
907 		goto func_exit;
908 
909 	req->cmd = RPMB_CMD_GET_DEV_INFO;
910 	req->dev_id = dev_id;
911 
912 	di = (struct rpmb_dev_info *)resp;
913 	di->ret_code = RPMB_CMD_GET_DEV_INFO_RET_ERROR;
914 
915 	res = tee_rpmb_invoke(&mem);
916 	if (res != TEE_SUCCESS)
917 		goto func_exit;
918 
919 	if (di->ret_code != RPMB_CMD_GET_DEV_INFO_RET_OK) {
920 		res = TEE_ERROR_GENERIC;
921 		goto func_exit;
922 	}
923 
924 	memcpy((uint8_t *)dev_info, resp, sizeof(struct rpmb_dev_info));
925 
926 	if (IS_ENABLED(CFG_RPMB_FS_DEBUG_DATA)) {
927 		DMSG("Dumping dev_info:");
928 		DHEXDUMP((uint8_t *)dev_info, sizeof(struct rpmb_dev_info));
929 	}
930 
931 	res = TEE_SUCCESS;
932 
933 func_exit:
934 	tee_rpmb_free(&mem);
935 	return res;
936 }
937 
938 static TEE_Result tee_rpmb_init_read_wr_cnt(uint16_t dev_id,
939 					    uint32_t *wr_cnt,
940 					    uint16_t *op_result)
941 {
942 	TEE_Result res = TEE_ERROR_GENERIC;
943 	struct tee_rpmb_mem mem;
944 	uint16_t msg_type;
945 	uint8_t nonce[RPMB_NONCE_SIZE];
946 	uint8_t hmac[RPMB_KEY_MAC_SIZE];
947 	struct rpmb_req *req = NULL;
948 	struct rpmb_data_frame *resp = NULL;
949 	struct rpmb_raw_data rawdata;
950 	uint32_t req_size;
951 	uint32_t resp_size;
952 
953 	if (!wr_cnt)
954 		return TEE_ERROR_BAD_PARAMETERS;
955 
956 	req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE;
957 	resp_size = RPMB_DATA_FRAME_SIZE;
958 	res = tee_rpmb_alloc(req_size, resp_size, &mem,
959 			     (void *)&req, (void *)&resp);
960 	if (res != TEE_SUCCESS)
961 		goto func_exit;
962 
963 	res = crypto_rng_read(nonce, RPMB_NONCE_SIZE);
964 	if (res != TEE_SUCCESS)
965 		goto func_exit;
966 
967 	msg_type = RPMB_MSG_TYPE_REQ_WRITE_COUNTER_VAL_READ;
968 
969 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
970 	rawdata.msg_type = msg_type;
971 	rawdata.nonce = nonce;
972 
973 	res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL);
974 	if (res != TEE_SUCCESS)
975 		goto func_exit;
976 
977 	res = tee_rpmb_invoke(&mem);
978 	if (res != TEE_SUCCESS)
979 		goto func_exit;
980 
981 	msg_type = RPMB_MSG_TYPE_RESP_WRITE_COUNTER_VAL_READ;
982 
983 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
984 	rawdata.msg_type = msg_type;
985 	rawdata.op_result = op_result;
986 	rawdata.write_counter = wr_cnt;
987 	rawdata.nonce = nonce;
988 	rawdata.key_mac = hmac;
989 
990 	res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL, NULL);
991 	if (res != TEE_SUCCESS)
992 		goto func_exit;
993 
994 	res = TEE_SUCCESS;
995 
996 func_exit:
997 	tee_rpmb_free(&mem);
998 	return res;
999 }
1000 
1001 static TEE_Result tee_rpmb_verify_key_sync_counter(uint16_t dev_id)
1002 {
1003 	uint16_t op_result = 0;
1004 	TEE_Result res = TEE_ERROR_GENERIC;
1005 
1006 	res = tee_rpmb_init_read_wr_cnt(dev_id, &rpmb_ctx->wr_cnt,
1007 					&op_result);
1008 
1009 	if (res == TEE_SUCCESS) {
1010 		rpmb_ctx->key_verified = true;
1011 		rpmb_ctx->wr_cnt_synced = true;
1012 	} else
1013 		EMSG("Verify key returning 0x%x", res);
1014 	return res;
1015 }
1016 
1017 #ifdef CFG_RPMB_WRITE_KEY
1018 static TEE_Result tee_rpmb_write_key(uint16_t dev_id)
1019 {
1020 	TEE_Result res = TEE_ERROR_GENERIC;
1021 	struct tee_rpmb_mem mem = { 0 };
1022 	uint16_t msg_type;
1023 	struct rpmb_req *req = NULL;
1024 	struct rpmb_data_frame *resp = NULL;
1025 	struct rpmb_raw_data rawdata;
1026 	uint32_t req_size;
1027 	uint32_t resp_size;
1028 
1029 	req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE;
1030 	resp_size = RPMB_DATA_FRAME_SIZE;
1031 	res = tee_rpmb_alloc(req_size, resp_size, &mem,
1032 			     (void *)&req, (void *)&resp);
1033 	if (res != TEE_SUCCESS)
1034 		goto func_exit;
1035 
1036 	msg_type = RPMB_MSG_TYPE_REQ_AUTH_KEY_PROGRAM;
1037 
1038 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
1039 	rawdata.msg_type = msg_type;
1040 	rawdata.key_mac = rpmb_ctx->key;
1041 
1042 	res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL);
1043 	if (res != TEE_SUCCESS)
1044 		goto func_exit;
1045 
1046 	res = tee_rpmb_invoke(&mem);
1047 	if (res != TEE_SUCCESS)
1048 		goto func_exit;
1049 
1050 	msg_type = RPMB_MSG_TYPE_RESP_AUTH_KEY_PROGRAM;
1051 
1052 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
1053 	rawdata.msg_type = msg_type;
1054 
1055 	res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL, NULL);
1056 	if (res != TEE_SUCCESS)
1057 		goto func_exit;
1058 
1059 	res = TEE_SUCCESS;
1060 
1061 func_exit:
1062 	tee_rpmb_free(&mem);
1063 	return res;
1064 }
1065 
1066 static TEE_Result tee_rpmb_write_and_verify_key(uint16_t dev_id)
1067 {
1068 	TEE_Result res;
1069 
1070 	if (!plat_rpmb_key_is_ready()) {
1071 		DMSG("RPMB INIT: platform indicates RPMB key is not ready");
1072 		return TEE_ERROR_BAD_STATE;
1073 	}
1074 
1075 	DMSG("RPMB INIT: Writing Key value:");
1076 	DHEXDUMP(rpmb_ctx->key, RPMB_KEY_MAC_SIZE);
1077 
1078 	res = tee_rpmb_write_key(dev_id);
1079 	if (res == TEE_SUCCESS) {
1080 		DMSG("RPMB INIT: Verifying Key");
1081 		res = tee_rpmb_verify_key_sync_counter(dev_id);
1082 	}
1083 	return res;
1084 }
1085 #else
1086 static TEE_Result tee_rpmb_write_and_verify_key(uint16_t dev_id __unused)
1087 {
1088 	DMSG("RPMB INIT: CFG_RPMB_WRITE_KEY is not set");
1089 	return TEE_ERROR_BAD_STATE;
1090 }
1091 #endif
1092 
1093 /* This function must never return TEE_SUCCESS if rpmb_ctx == NULL */
1094 static TEE_Result tee_rpmb_init(uint16_t dev_id)
1095 {
1096 	TEE_Result res = TEE_SUCCESS;
1097 	struct rpmb_dev_info dev_info;
1098 	uint32_t nblocks = 0;
1099 
1100 	if (rpmb_dead)
1101 		return TEE_ERROR_COMMUNICATION;
1102 
1103 	if (!rpmb_ctx) {
1104 		rpmb_ctx = calloc(1, sizeof(struct tee_rpmb_ctx));
1105 		if (!rpmb_ctx)
1106 			return TEE_ERROR_OUT_OF_MEMORY;
1107 	} else if (rpmb_ctx->dev_id != dev_id) {
1108 		memset(rpmb_ctx, 0x00, sizeof(struct tee_rpmb_ctx));
1109 	}
1110 
1111 	rpmb_ctx->dev_id = dev_id;
1112 
1113 	if (!rpmb_ctx->dev_info_synced) {
1114 		DMSG("RPMB: Syncing device information");
1115 
1116 		dev_info.rpmb_size_mult = 0;
1117 		dev_info.rel_wr_sec_c = 0;
1118 		res = tee_rpmb_get_dev_info(dev_id, &dev_info);
1119 		if (res != TEE_SUCCESS)
1120 			goto func_exit;
1121 
1122 		DMSG("RPMB: RPMB size is %d*128 KB", dev_info.rpmb_size_mult);
1123 		DMSG("RPMB: Reliable Write Sector Count is %d",
1124 		     dev_info.rel_wr_sec_c);
1125 
1126 		if (dev_info.rpmb_size_mult == 0) {
1127 			res = TEE_ERROR_GENERIC;
1128 			goto func_exit;
1129 		}
1130 
1131 		if (MUL_OVERFLOW(dev_info.rpmb_size_mult,
1132 				 RPMB_SIZE_SINGLE / RPMB_DATA_SIZE, &nblocks) ||
1133 		    SUB_OVERFLOW(nblocks, 1, &rpmb_ctx->max_blk_idx)) {
1134 			res = TEE_ERROR_BAD_PARAMETERS;
1135 			goto func_exit;
1136 		}
1137 
1138 		memcpy(rpmb_ctx->cid, dev_info.cid, RPMB_EMMC_CID_SIZE);
1139 
1140 #ifdef RPMB_DRIVER_MULTIPLE_WRITE_FIXED
1141 		rpmb_ctx->rel_wr_blkcnt = dev_info.rel_wr_sec_c * 2;
1142 #else
1143 		rpmb_ctx->rel_wr_blkcnt = 1;
1144 #endif
1145 
1146 		rpmb_ctx->dev_info_synced = true;
1147 	}
1148 
1149 	if (!rpmb_ctx->key_derived) {
1150 		DMSG("RPMB INIT: Deriving key");
1151 
1152 		res = tee_rpmb_key_gen(dev_id, rpmb_ctx->key,
1153 				       RPMB_KEY_MAC_SIZE);
1154 		if (res != TEE_SUCCESS) {
1155 			EMSG("RPMB INIT: Deriving key failed with error 0x%x",
1156 				res);
1157 			goto func_exit;
1158 		}
1159 
1160 		rpmb_ctx->key_derived = true;
1161 	}
1162 
1163 	/* Perform a write counter read to verify if the key is ok. */
1164 	if (!rpmb_ctx->wr_cnt_synced || !rpmb_ctx->key_verified) {
1165 		DMSG("RPMB INIT: Verifying Key");
1166 
1167 		res = tee_rpmb_verify_key_sync_counter(dev_id);
1168 		if (res == TEE_ERROR_ITEM_NOT_FOUND &&
1169 			!rpmb_ctx->key_verified) {
1170 			/*
1171 			 * Need to write the key here and verify it.
1172 			 */
1173 			DMSG("RPMB INIT: Auth key not yet written");
1174 			res = tee_rpmb_write_and_verify_key(dev_id);
1175 		} else if (res != TEE_SUCCESS) {
1176 			EMSG("Verify key failed!");
1177 			EMSG("Make sure key here matches device key");
1178 		}
1179 	}
1180 
1181 func_exit:
1182 	return res;
1183 }
1184 
1185 /*
1186  * Read RPMB data in bytes.
1187  *
1188  * @dev_id     Device ID of the eMMC device.
1189  * @addr       Byte address of data.
1190  * @data       Pointer to the data.
1191  * @len        Size of data in bytes.
1192  * @fek        Encrypted File Encryption Key or NULL.
1193  */
1194 static TEE_Result tee_rpmb_read(uint16_t dev_id, uint32_t addr, uint8_t *data,
1195 				uint32_t len, const uint8_t *fek,
1196 				const TEE_UUID *uuid)
1197 {
1198 	TEE_Result res = TEE_ERROR_GENERIC;
1199 	struct tee_rpmb_mem mem = { 0 };
1200 	uint16_t msg_type;
1201 	uint8_t nonce[RPMB_NONCE_SIZE];
1202 	uint8_t hmac[RPMB_KEY_MAC_SIZE];
1203 	struct rpmb_req *req = NULL;
1204 	struct rpmb_data_frame *resp = NULL;
1205 	struct rpmb_raw_data rawdata;
1206 	uint32_t req_size;
1207 	uint32_t resp_size;
1208 	uint16_t blk_idx;
1209 	uint16_t blkcnt;
1210 	uint8_t byte_offset;
1211 
1212 	if (!data || !len)
1213 		return TEE_ERROR_BAD_PARAMETERS;
1214 
1215 	blk_idx = addr / RPMB_DATA_SIZE;
1216 	byte_offset = addr % RPMB_DATA_SIZE;
1217 
1218 	if (len + byte_offset + RPMB_DATA_SIZE < RPMB_DATA_SIZE) {
1219 		/* Overflow */
1220 		return TEE_ERROR_BAD_PARAMETERS;
1221 	}
1222 	blkcnt =
1223 	    ROUNDUP(len + byte_offset, RPMB_DATA_SIZE) / RPMB_DATA_SIZE;
1224 	res = tee_rpmb_init(dev_id);
1225 	if (res != TEE_SUCCESS)
1226 		goto func_exit;
1227 
1228 	req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE;
1229 	resp_size = RPMB_DATA_FRAME_SIZE * blkcnt;
1230 	res = tee_rpmb_alloc(req_size, resp_size, &mem,
1231 			     (void *)&req, (void *)&resp);
1232 	if (res != TEE_SUCCESS)
1233 		goto func_exit;
1234 
1235 	msg_type = RPMB_MSG_TYPE_REQ_AUTH_DATA_READ;
1236 	res = crypto_rng_read(nonce, RPMB_NONCE_SIZE);
1237 	if (res != TEE_SUCCESS)
1238 		goto func_exit;
1239 
1240 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
1241 	rawdata.msg_type = msg_type;
1242 	rawdata.nonce = nonce;
1243 	rawdata.blk_idx = &blk_idx;
1244 	res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL);
1245 	if (res != TEE_SUCCESS)
1246 		goto func_exit;
1247 
1248 	req->block_count = blkcnt;
1249 
1250 	DMSG("Read %u block%s at index %u", blkcnt, ((blkcnt > 1) ? "s" : ""),
1251 	     blk_idx);
1252 
1253 	res = tee_rpmb_invoke(&mem);
1254 	if (res != TEE_SUCCESS)
1255 		goto func_exit;
1256 
1257 	msg_type = RPMB_MSG_TYPE_RESP_AUTH_DATA_READ;
1258 
1259 	memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data));
1260 	rawdata.msg_type = msg_type;
1261 	rawdata.block_count = &blkcnt;
1262 	rawdata.blk_idx = &blk_idx;
1263 	rawdata.nonce = nonce;
1264 	rawdata.key_mac = hmac;
1265 	rawdata.data = data;
1266 
1267 	rawdata.len = len;
1268 	rawdata.byte_offset = byte_offset;
1269 
1270 	res = tee_rpmb_resp_unpack_verify(resp, &rawdata, blkcnt, fek, uuid);
1271 	if (res != TEE_SUCCESS)
1272 		goto func_exit;
1273 
1274 	res = TEE_SUCCESS;
1275 
1276 func_exit:
1277 	tee_rpmb_free(&mem);
1278 	return res;
1279 }
1280 
1281 static TEE_Result write_req(uint16_t dev_id, uint16_t blk_idx,
1282 			    const void *data_blks, uint16_t blkcnt,
1283 			    const uint8_t *fek, const TEE_UUID *uuid,
1284 			    struct tee_rpmb_mem *mem, void  *req, void *resp)
1285 {
1286 	TEE_Result res = TEE_SUCCESS;
1287 	uint8_t hmac[RPMB_KEY_MAC_SIZE] = { };
1288 	uint32_t wr_cnt = rpmb_ctx->wr_cnt;
1289 	struct rpmb_raw_data rawdata = { };
1290 	size_t retry_count = 0;
1291 
1292 	assert(mem->req_size <=
1293 	       sizeof(struct rpmb_req) + blkcnt * RPMB_DATA_FRAME_SIZE);
1294 	assert(mem->resp_size <= RPMB_DATA_FRAME_SIZE);
1295 
1296 	while (true) {
1297 		memset(req, 0, mem->req_size);
1298 		memset(resp, 0, mem->resp_size);
1299 
1300 		memset(&rawdata, 0, sizeof(struct rpmb_raw_data));
1301 		rawdata.msg_type = RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE;
1302 		rawdata.block_count = &blkcnt;
1303 		rawdata.blk_idx = &blk_idx;
1304 		rawdata.write_counter = &wr_cnt;
1305 		rawdata.key_mac = hmac;
1306 		rawdata.data = (uint8_t *)data_blks;
1307 
1308 		res = tee_rpmb_req_pack(req, &rawdata, blkcnt, dev_id, fek,
1309 					uuid);
1310 		if (res) {
1311 			/*
1312 			 * If we haven't tried to send a request yet we can
1313 			 * allow a failure here since there's no chance of
1314 			 * an intercepted request with a valid write
1315 			 * counter.
1316 			 */
1317 			if (!retry_count)
1318 				return res;
1319 
1320 			retry_count++;
1321 			if (retry_count >= RPMB_MAX_RETRIES)
1322 				goto out_of_retries;
1323 
1324 			DMSG("Request pack failed, retrying %zu", retry_count);
1325 			continue;
1326 		}
1327 
1328 		res = tee_rpmb_invoke(mem);
1329 		if (res != TEE_SUCCESS) {
1330 			retry_count++;
1331 			if (retry_count >= RPMB_MAX_RETRIES)
1332 				goto out_of_retries;
1333 			/*
1334 			 * To force wr_cnt sync next time, as it might get
1335 			 * out of sync due to inconsistent operation result!
1336 			 */
1337 			rpmb_ctx->wr_cnt_synced = false;
1338 			DMSG("Write invoke failed, retrying %zu", retry_count);
1339 			continue;
1340 		}
1341 
1342 		memset(&rawdata, 0, sizeof(struct rpmb_raw_data));
1343 		rawdata.msg_type = RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE;
1344 		rawdata.block_count = &blkcnt;
1345 		rawdata.blk_idx = &blk_idx;
1346 		rawdata.write_counter = &wr_cnt;
1347 		rawdata.key_mac = hmac;
1348 
1349 		res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL,
1350 						  NULL);
1351 		if (res != TEE_SUCCESS) {
1352 			retry_count++;
1353 			if (retry_count >= RPMB_MAX_RETRIES)
1354 				goto out_of_retries;
1355 			/*
1356 			 * To force wr_cnt sync next time, as it might get
1357 			 * out of sync due to inconsistent operation result!
1358 			 */
1359 			rpmb_ctx->wr_cnt_synced = false;
1360 			DMSG("Write resp unpack verify failed, retrying %zu",
1361 			     retry_count);
1362 			continue;
1363 		}
1364 
1365 		return TEE_SUCCESS;
1366 	}
1367 
1368 out_of_retries:
1369 	rpmb_dead = true;
1370 	/*
1371 	 * We're using this error code to cause an eventuall calling TA to
1372 	 * panic since we don't know if the data to be written has been
1373 	 * committed to storage or not.
1374 	 */
1375 	return TEE_ERROR_COMMUNICATION;
1376 }
1377 
1378 static TEE_Result tee_rpmb_write_blk(uint16_t dev_id, uint16_t blk_idx,
1379 				     const uint8_t *data_blks, uint16_t blkcnt,
1380 				     const uint8_t *fek, const TEE_UUID *uuid)
1381 {
1382 	TEE_Result res;
1383 	struct tee_rpmb_mem mem;
1384 	struct rpmb_req *req = NULL;
1385 	struct rpmb_data_frame *resp = NULL;
1386 	uint32_t req_size;
1387 	uint32_t resp_size;
1388 	uint32_t nbr_writes;
1389 	uint16_t tmp_blkcnt;
1390 	uint16_t tmp_blk_idx;
1391 	uint16_t i;
1392 
1393 	DMSG("Write %u block%s at index %u", blkcnt, ((blkcnt > 1) ? "s" : ""),
1394 	     blk_idx);
1395 
1396 	if (!data_blks || !blkcnt)
1397 		return TEE_ERROR_BAD_PARAMETERS;
1398 
1399 	res = tee_rpmb_init(dev_id);
1400 	if (res != TEE_SUCCESS)
1401 		return res;
1402 
1403 	/*
1404 	 * We need to split data when block count
1405 	 * is bigger than reliable block write count.
1406 	 */
1407 	if (blkcnt < rpmb_ctx->rel_wr_blkcnt)
1408 		req_size = sizeof(struct rpmb_req) +
1409 		    RPMB_DATA_FRAME_SIZE * blkcnt;
1410 	else
1411 		req_size = sizeof(struct rpmb_req) +
1412 		    RPMB_DATA_FRAME_SIZE * rpmb_ctx->rel_wr_blkcnt;
1413 
1414 	resp_size = RPMB_DATA_FRAME_SIZE;
1415 	res = tee_rpmb_alloc(req_size, resp_size, &mem,
1416 			     (void *)&req, (void *)&resp);
1417 	if (res != TEE_SUCCESS)
1418 		return res;
1419 
1420 	nbr_writes = blkcnt / rpmb_ctx->rel_wr_blkcnt;
1421 	if (blkcnt % rpmb_ctx->rel_wr_blkcnt > 0)
1422 		nbr_writes += 1;
1423 
1424 	tmp_blkcnt = rpmb_ctx->rel_wr_blkcnt;
1425 	tmp_blk_idx = blk_idx;
1426 	for (i = 0; i < nbr_writes; i++) {
1427 		size_t offs = i * rpmb_ctx->rel_wr_blkcnt * RPMB_DATA_SIZE;
1428 
1429 		/*
1430 		 * To handle the last write of block count which is
1431 		 * equal or smaller than reliable write block count.
1432 		 */
1433 		if (i == nbr_writes - 1)
1434 			tmp_blkcnt = blkcnt - rpmb_ctx->rel_wr_blkcnt *
1435 			    (nbr_writes - 1);
1436 
1437 		res = write_req(dev_id, tmp_blk_idx, data_blks + offs,
1438 				tmp_blkcnt, fek, uuid, &mem, req, resp);
1439 		if (res)
1440 			goto out;
1441 
1442 
1443 		tmp_blk_idx += tmp_blkcnt;
1444 	}
1445 
1446 out:
1447 	tee_rpmb_free(&mem);
1448 	return res;
1449 }
1450 
1451 static bool tee_rpmb_write_is_atomic(uint16_t dev_id __unused, uint32_t addr,
1452 				     uint32_t len)
1453 {
1454 	uint8_t byte_offset = addr % RPMB_DATA_SIZE;
1455 	uint16_t blkcnt = ROUNDUP(len + byte_offset,
1456 				  RPMB_DATA_SIZE) / RPMB_DATA_SIZE;
1457 
1458 	return (blkcnt <= rpmb_ctx->rel_wr_blkcnt);
1459 }
1460 
1461 /*
1462  * Write RPMB data in bytes.
1463  *
1464  * @dev_id     Device ID of the eMMC device.
1465  * @addr       Byte address of data.
1466  * @data       Pointer to the data.
1467  * @len        Size of data in bytes.
1468  * @fek        Encrypted File Encryption Key or NULL.
1469  */
1470 static TEE_Result tee_rpmb_write(uint16_t dev_id, uint32_t addr,
1471 				 const uint8_t *data, uint32_t len,
1472 				 const uint8_t *fek, const TEE_UUID *uuid)
1473 {
1474 	TEE_Result res = TEE_ERROR_GENERIC;
1475 	uint8_t *data_tmp = NULL;
1476 	uint16_t blk_idx;
1477 	uint16_t blkcnt;
1478 	uint8_t byte_offset;
1479 
1480 	blk_idx = addr / RPMB_DATA_SIZE;
1481 	byte_offset = addr % RPMB_DATA_SIZE;
1482 
1483 	blkcnt =
1484 	    ROUNDUP(len + byte_offset, RPMB_DATA_SIZE) / RPMB_DATA_SIZE;
1485 
1486 	if (byte_offset == 0 && (len % RPMB_DATA_SIZE) == 0) {
1487 		res = tee_rpmb_write_blk(dev_id, blk_idx, data, blkcnt, fek,
1488 					 uuid);
1489 		if (res != TEE_SUCCESS)
1490 			goto func_exit;
1491 	} else {
1492 		data_tmp = calloc(blkcnt, RPMB_DATA_SIZE);
1493 		if (!data_tmp) {
1494 			res = TEE_ERROR_OUT_OF_MEMORY;
1495 			goto func_exit;
1496 		}
1497 
1498 		/* Read the complete blocks */
1499 		res = tee_rpmb_read(dev_id, blk_idx * RPMB_DATA_SIZE, data_tmp,
1500 				    blkcnt * RPMB_DATA_SIZE, fek, uuid);
1501 		if (res != TEE_SUCCESS)
1502 			goto func_exit;
1503 
1504 		/* Partial update of the data blocks */
1505 		memcpy(data_tmp + byte_offset, data, len);
1506 
1507 		res = tee_rpmb_write_blk(dev_id, blk_idx, data_tmp, blkcnt,
1508 					 fek, uuid);
1509 		if (res != TEE_SUCCESS)
1510 			goto func_exit;
1511 	}
1512 
1513 	res = TEE_SUCCESS;
1514 
1515 func_exit:
1516 	free(data_tmp);
1517 	return res;
1518 }
1519 
1520 /*
1521  * Read the RPMB write counter.
1522  *
1523  * @dev_id     Device ID of the eMMC device.
1524  * @counter    Pointer to the counter.
1525  */
1526 static TEE_Result tee_rpmb_get_write_counter(uint16_t dev_id,
1527 					     uint32_t *counter)
1528 {
1529 	TEE_Result res = TEE_SUCCESS;
1530 
1531 	if (!counter)
1532 		return TEE_ERROR_BAD_PARAMETERS;
1533 
1534 	if (rpmb_dead)
1535 		return TEE_ERROR_COMMUNICATION;
1536 
1537 	if (!rpmb_ctx || !rpmb_ctx->wr_cnt_synced) {
1538 		res = tee_rpmb_init(dev_id);
1539 		if (res != TEE_SUCCESS)
1540 			goto func_exit;
1541 	}
1542 
1543 	*counter = rpmb_ctx->wr_cnt;
1544 
1545 func_exit:
1546 	return res;
1547 }
1548 
1549 /*
1550  * Read the RPMB max block.
1551  *
1552  * @dev_id     Device ID of the eMMC device.
1553  * @counter    Pointer to receive the max block.
1554  */
1555 static TEE_Result tee_rpmb_get_max_block(uint16_t dev_id, uint32_t *max_block)
1556 {
1557 	TEE_Result res = TEE_SUCCESS;
1558 
1559 	if (!max_block)
1560 		return TEE_ERROR_BAD_PARAMETERS;
1561 
1562 	if (rpmb_dead)
1563 		return TEE_ERROR_COMMUNICATION;
1564 
1565 	if (!rpmb_ctx || !rpmb_ctx->dev_info_synced) {
1566 		res = tee_rpmb_init(dev_id);
1567 		if (res != TEE_SUCCESS)
1568 			goto func_exit;
1569 	}
1570 
1571 	*max_block = rpmb_ctx->max_blk_idx;
1572 
1573 func_exit:
1574 	return res;
1575 }
1576 
1577 /*
1578  * End of lower interface to RPMB device
1579  */
1580 
1581 static TEE_Result get_fat_start_address(uint32_t *addr);
1582 static TEE_Result rpmb_fs_setup(void);
1583 
1584 /**
1585  * fat_entry_dir_free: Free the FAT entry dir.
1586  */
1587 static void fat_entry_dir_free(void)
1588 {
1589 	if (fat_entry_dir) {
1590 		free(fat_entry_dir->rpmb_fat_entry_buf);
1591 		free(fat_entry_dir);
1592 		fat_entry_dir = NULL;
1593 	}
1594 }
1595 
1596 /**
1597  * fat_entry_dir_init: Initialize the FAT FS entry buffer/cache
1598  * This function must be called before reading FAT FS entries using the
1599  * function fat_entry_dir_get_next. This initializes the buffer/cache with the
1600  * first FAT FS entries.
1601  */
1602 static TEE_Result fat_entry_dir_init(void)
1603 {
1604 	TEE_Result res = TEE_ERROR_GENERIC;
1605 	struct rpmb_fat_entry *fe = NULL;
1606 	uint32_t fat_address = 0;
1607 	uint32_t num_elems_read = 0;
1608 
1609 	if (fat_entry_dir)
1610 		return TEE_SUCCESS;
1611 
1612 	res = rpmb_fs_setup();
1613 	if (res)
1614 		return res;
1615 
1616 	res = get_fat_start_address(&fat_address);
1617 	if (res)
1618 		return res;
1619 
1620 	fat_entry_dir = calloc(1, sizeof(struct rpmb_fat_entry_dir));
1621 	if (!fat_entry_dir)
1622 		return TEE_ERROR_OUT_OF_MEMORY;
1623 
1624 	/*
1625 	 * If caching is enabled, read in up to the maximum cache size, but
1626 	 * never more than the single read in size. Otherwise, read in as many
1627 	 * entries fit into the temporary buffer.
1628 	 */
1629 	if (CFG_RPMB_FS_CACHE_ENTRIES)
1630 		num_elems_read = MIN(CFG_RPMB_FS_CACHE_ENTRIES,
1631 				     CFG_RPMB_FS_RD_ENTRIES);
1632 	else
1633 		num_elems_read = CFG_RPMB_FS_RD_ENTRIES;
1634 
1635 	/*
1636 	 * Allocate memory for the FAT FS entries to read in.
1637 	 */
1638 	fe = calloc(num_elems_read, sizeof(struct rpmb_fat_entry));
1639 	if (!fe) {
1640 		res = TEE_ERROR_OUT_OF_MEMORY;
1641 		goto out;
1642 	}
1643 
1644 	res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, fat_address, (uint8_t *)fe,
1645 			    num_elems_read * sizeof(*fe), NULL, NULL);
1646 	if (res)
1647 		goto out;
1648 
1649 	fat_entry_dir->rpmb_fat_entry_buf = fe;
1650 
1651 	/*
1652 	 * We use this variable when getting next entries from the buffer/cache
1653 	 * to see whether we have to read in more entries from storage.
1654 	 */
1655 	fat_entry_dir->num_buffered = num_elems_read;
1656 
1657 	return TEE_SUCCESS;
1658 out:
1659 	fat_entry_dir_free();
1660 	free(fe);
1661 	return res;
1662 }
1663 
1664 /**
1665  * fat_entry_dir_deinit: If caching is enabled, free the temporary buffer for
1666  * FAT FS entries in case the cache was too small. Keep the elements in the
1667  * cache. Reset the counter variables to start the next traversal from fresh
1668  * from the first cached entry. If caching is disabled, just free the
1669  * temporary buffer by calling fat_entry_dir_free and return.
1670  */
1671 static void fat_entry_dir_deinit(void)
1672 {
1673 	struct rpmb_fat_entry *fe = NULL;
1674 
1675 	if (!fat_entry_dir)
1676 		return;
1677 
1678 	if (!CFG_RPMB_FS_CACHE_ENTRIES) {
1679 		fat_entry_dir_free();
1680 		return;
1681 	}
1682 
1683 	fe = fat_entry_dir->rpmb_fat_entry_buf;
1684 	fat_entry_dir->idx_curr = 0;
1685 	fat_entry_dir->num_total_read = 0;
1686 	fat_entry_dir->last_reached = false;
1687 
1688 	if (fat_entry_dir->num_buffered > CFG_RPMB_FS_CACHE_ENTRIES) {
1689 		fat_entry_dir->num_buffered = CFG_RPMB_FS_CACHE_ENTRIES;
1690 
1691 		fe = realloc(fe, fat_entry_dir->num_buffered * sizeof(*fe));
1692 
1693 		/*
1694 		 * In case realloc fails, we are on the safe side if we destroy
1695 		 * the whole structure. Upon the next init, the cache has to be
1696 		 * re-established, but this case should not happen in practice.
1697 		 */
1698 		if (!fe)
1699 			fat_entry_dir_free();
1700 		else
1701 			fat_entry_dir->rpmb_fat_entry_buf = fe;
1702 	}
1703 }
1704 
1705 /**
1706  * fat_entry_dir_update: Updates a persisted FAT FS entry in the cache.
1707  * This function updates the FAT entry fat_entry that was written to address
1708  * fat_address onto RPMB storage in the cache.
1709  */
1710 static TEE_Result __maybe_unused fat_entry_dir_update
1711 					(struct rpmb_fat_entry *fat_entry,
1712 					 uint32_t fat_address)
1713 {
1714 	uint32_t fat_entry_buf_idx = 0;
1715 	/* Use a temp var to avoid compiler warning if caching disabled. */
1716 	uint32_t max_cache_entries = CFG_RPMB_FS_CACHE_ENTRIES;
1717 
1718 	assert(!((fat_address - RPMB_FS_FAT_START_ADDRESS) %
1719 	       sizeof(struct rpmb_fat_entry)));
1720 
1721 	/* Nothing to update if the cache is not initialized. */
1722 	if (!fat_entry_dir)
1723 		return TEE_SUCCESS;
1724 
1725 	fat_entry_buf_idx = (fat_address - RPMB_FS_FAT_START_ADDRESS) /
1726 			     sizeof(struct rpmb_fat_entry);
1727 
1728 	/* Only need to write if index points to an entry in cache. */
1729 	if (fat_entry_buf_idx < fat_entry_dir->num_buffered &&
1730 	    fat_entry_buf_idx < max_cache_entries) {
1731 		memcpy(fat_entry_dir->rpmb_fat_entry_buf + fat_entry_buf_idx,
1732 		       fat_entry, sizeof(struct rpmb_fat_entry));
1733 	}
1734 
1735 	return TEE_SUCCESS;
1736 }
1737 
1738 /**
1739  * fat_entry_dir_get_next: Get next FAT FS entry.
1740  * Read either from cache/buffer, or by reading from RPMB storage if the
1741  * elements in the buffer/cache are fully read. When reading in from RPMB
1742  * storage, the buffer is overwritten in case caching is disabled.
1743  * In case caching is enabled, the cache is either further filled, or a
1744  * temporary buffer populated if the cache is already full.
1745  * The FAT FS entry is written to fat_entry. The respective address in RPMB
1746  * storage is written to fat_address, if not NULL. When the last FAT FS entry
1747  * was previously read, the function indicates this case by writing a NULL
1748  * pointer to fat_entry.
1749  * Returns a value different TEE_SUCCESS if the next FAT FS entry could not be
1750  * retrieved.
1751  */
1752 static TEE_Result fat_entry_dir_get_next(struct rpmb_fat_entry **fat_entry,
1753 					 uint32_t *fat_address)
1754 {
1755 	TEE_Result res = TEE_ERROR_GENERIC;
1756 	struct rpmb_fat_entry *fe = NULL;
1757 	uint32_t num_elems_read = 0;
1758 	uint32_t fat_address_local = 0;
1759 
1760 	assert(fat_entry_dir && fat_entry);
1761 
1762 	/* Don't read further if we previously read the last FAT FS entry. */
1763 	if (fat_entry_dir->last_reached) {
1764 		*fat_entry = NULL;
1765 		return TEE_SUCCESS;
1766 	}
1767 
1768 	fe = fat_entry_dir->rpmb_fat_entry_buf;
1769 
1770 	/* Determine address of FAT FS entry in RPMB storage. */
1771 	fat_address_local = RPMB_FS_FAT_START_ADDRESS +
1772 			(fat_entry_dir->num_total_read *
1773 			sizeof(struct rpmb_fat_entry));
1774 
1775 	/*
1776 	 * We've read all so-far buffered elements, so we need to
1777 	 * read in more entries from RPMB storage.
1778 	 */
1779 	if (fat_entry_dir->idx_curr >= fat_entry_dir->num_buffered) {
1780 		/*
1781 		 * This is the case where we do not cache entries, so just read
1782 		 * in next set of FAT FS entries into the buffer.
1783 		 * Goto the end of the when statement if that is done.
1784 		 */
1785 		if (!CFG_RPMB_FS_CACHE_ENTRIES) {
1786 			num_elems_read = CFG_RPMB_FS_RD_ENTRIES;
1787 			fat_entry_dir->idx_curr = 0;
1788 
1789 			res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
1790 					    fat_address_local, (uint8_t *)fe,
1791 					    num_elems_read * sizeof(*fe), NULL,
1792 					    NULL);
1793 			if (res)
1794 				return res;
1795 			goto post_read_in;
1796 		}
1797 
1798 		/*
1799 		 * We cache FAT FS entries, and the buffer is not completely
1800 		 * filled. Further keep on extending the buffer up to its max
1801 		 * size by reading in from RPMB.
1802 		 */
1803 		if (fat_entry_dir->num_total_read < RPMB_BUF_MAX_ENTRIES) {
1804 			/*
1805 			 * Read at most as many elements as fit in the buffer
1806 			 * and no more than the defined number of entries to
1807 			 * read in at once.
1808 			 */
1809 			num_elems_read = MIN(RPMB_BUF_MAX_ENTRIES -
1810 					     fat_entry_dir->num_total_read,
1811 					     (uint32_t)CFG_RPMB_FS_RD_ENTRIES);
1812 
1813 			/*
1814 			 * Expand the buffer to fit in the additional entries.
1815 			 */
1816 			fe = realloc(fe,
1817 				     (fat_entry_dir->num_buffered +
1818 				      num_elems_read) * sizeof(*fe));
1819 			if (!fe)
1820 				return TEE_ERROR_OUT_OF_MEMORY;
1821 
1822 			fat_entry_dir->rpmb_fat_entry_buf = fe;
1823 
1824 			/* Read in to the next free slot in the buffer/cache. */
1825 			res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
1826 					    fat_address_local,
1827 					    (uint8_t *)(fe +
1828 					    fat_entry_dir->num_total_read),
1829 					    num_elems_read * sizeof(*fe),
1830 					    NULL, NULL);
1831 			if (res)
1832 				return res;
1833 
1834 			fat_entry_dir->num_buffered += num_elems_read;
1835 		} else {
1836 			/*
1837 			 * This happens when we have read as many elements as
1838 			 * can possibly fit into the buffer.
1839 			 * As the first part of the buffer serves as our cache,
1840 			 * we only overwrite the last part that serves as our
1841 			 * temporary buffer used to iteratively read in entries
1842 			 * when the cache is full. Read in the temporary buffer
1843 			 * maximum size.
1844 			 */
1845 			num_elems_read = CFG_RPMB_FS_RD_ENTRIES;
1846 			/* Reset index to beginning of the temporary buffer. */
1847 			fat_entry_dir->idx_curr = CFG_RPMB_FS_CACHE_ENTRIES;
1848 
1849 			/* Read in elements after the end of the cache. */
1850 			res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
1851 					    fat_address_local,
1852 					    (uint8_t *)(fe +
1853 					    fat_entry_dir->idx_curr),
1854 					    num_elems_read * sizeof(*fe),
1855 					    NULL, NULL);
1856 			if (res)
1857 				return res;
1858 		}
1859 	}
1860 
1861 post_read_in:
1862 	if (fat_address)
1863 		*fat_address = fat_address_local;
1864 
1865 	*fat_entry = fe + fat_entry_dir->idx_curr;
1866 
1867 	fat_entry_dir->idx_curr++;
1868 	fat_entry_dir->num_total_read++;
1869 
1870 	/*
1871 	 * Indicate last entry was read.
1872 	 * Ensures we return a zero value for fat_entry on next invocation.
1873 	 */
1874 	if ((*fat_entry)->flags & FILE_IS_LAST_ENTRY)
1875 		fat_entry_dir->last_reached = true;
1876 
1877 	return TEE_SUCCESS;
1878 }
1879 
1880 #if (TRACE_LEVEL >= TRACE_FLOW)
1881 static void dump_fat(void)
1882 {
1883 	TEE_Result res = TEE_ERROR_SECURITY;
1884 	struct rpmb_fat_entry *fe = NULL;
1885 
1886 	if (!fs_par)
1887 		return;
1888 
1889 	if (fat_entry_dir_init())
1890 		return;
1891 
1892 	while (true) {
1893 		res = fat_entry_dir_get_next(&fe, NULL);
1894 		if (res || !fe)
1895 			break;
1896 
1897 		FMSG("flags %#"PRIx32", size %"PRIu32", address %#"PRIx32
1898 		     ", filename '%s'",
1899 		     fe->flags, fe->data_size, fe->start_address, fe->filename);
1900 	}
1901 
1902 	fat_entry_dir_deinit();
1903 }
1904 #else
1905 static void dump_fat(void)
1906 {
1907 }
1908 #endif
1909 
1910 #if (TRACE_LEVEL >= TRACE_DEBUG)
1911 static void dump_fh(struct rpmb_file_handle *fh)
1912 {
1913 	DMSG("fh->filename=%s", fh->filename);
1914 	DMSG("fh->rpmb_fat_address=%u", fh->rpmb_fat_address);
1915 	DMSG("fh->fat_entry.start_address=%u", fh->fat_entry.start_address);
1916 	DMSG("fh->fat_entry.data_size=%u", fh->fat_entry.data_size);
1917 }
1918 #else
1919 static void dump_fh(struct rpmb_file_handle *fh __unused)
1920 {
1921 }
1922 #endif
1923 
1924 static struct rpmb_file_handle *alloc_file_handle(struct tee_pobj *po,
1925 						  bool temporary)
1926 {
1927 	struct rpmb_file_handle *fh = NULL;
1928 
1929 	fh = calloc(1, sizeof(struct rpmb_file_handle));
1930 	if (!fh)
1931 		return NULL;
1932 
1933 	if (po)
1934 		tee_svc_storage_create_filename(fh->filename,
1935 						sizeof(fh->filename), po,
1936 						temporary);
1937 
1938 	return fh;
1939 }
1940 
1941 /**
1942  * write_fat_entry: Store info in a fat_entry to RPMB.
1943  */
1944 static TEE_Result write_fat_entry(struct rpmb_file_handle *fh,
1945 				  bool update_write_counter)
1946 {
1947 	TEE_Result res = TEE_ERROR_GENERIC;
1948 
1949 	/* Protect partition data. */
1950 	if (fh->rpmb_fat_address < sizeof(struct rpmb_fs_partition)) {
1951 		res = TEE_ERROR_ACCESS_CONFLICT;
1952 		goto out;
1953 	}
1954 
1955 	if (fh->rpmb_fat_address % sizeof(struct rpmb_fat_entry) != 0) {
1956 		res = TEE_ERROR_BAD_PARAMETERS;
1957 		goto out;
1958 	}
1959 
1960 	if (update_write_counter) {
1961 		res = tee_rpmb_get_write_counter(CFG_RPMB_FS_DEV_ID,
1962 						 &fh->fat_entry.write_counter);
1963 		if (res)
1964 			goto out;
1965 	}
1966 
1967 	res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, fh->rpmb_fat_address,
1968 			     (uint8_t *)&fh->fat_entry,
1969 			     sizeof(struct rpmb_fat_entry), NULL, NULL);
1970 
1971 	dump_fat();
1972 
1973 	/* If caching enabled, update a successfully written entry in cache. */
1974 	if (CFG_RPMB_FS_CACHE_ENTRIES && !res)
1975 		res = fat_entry_dir_update(&fh->fat_entry,
1976 					   fh->rpmb_fat_address);
1977 
1978 out:
1979 	return res;
1980 }
1981 
1982 /**
1983  * rpmb_fs_setup: Setup RPMB FS.
1984  * Set initial partition and FS values and write to RPMB.
1985  * Store frequently used data in RAM.
1986  */
1987 static TEE_Result rpmb_fs_setup(void)
1988 {
1989 	TEE_Result res = TEE_ERROR_GENERIC;
1990 	struct rpmb_fs_partition *partition_data = NULL;
1991 	struct rpmb_file_handle *fh = NULL;
1992 	uint32_t max_rpmb_block = 0;
1993 
1994 	if (fs_par) {
1995 		res = TEE_SUCCESS;
1996 		goto out;
1997 	}
1998 
1999 	res = tee_rpmb_get_max_block(CFG_RPMB_FS_DEV_ID, &max_rpmb_block);
2000 	if (res != TEE_SUCCESS)
2001 		goto out;
2002 
2003 	/*
2004 	 * We're going to read a full block in order to have a full block
2005 	 * for the dummy write below.
2006 	 */
2007 	COMPILE_TIME_ASSERT(sizeof(struct rpmb_fs_partition) <=
2008 			    RPMB_DATA_SIZE);
2009 	partition_data = calloc(1, RPMB_DATA_SIZE);
2010 	if (!partition_data) {
2011 		res = TEE_ERROR_OUT_OF_MEMORY;
2012 		goto out;
2013 	}
2014 
2015 	res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS,
2016 			    (uint8_t *)partition_data, RPMB_DATA_SIZE,
2017 			    NULL, NULL);
2018 	if (res != TEE_SUCCESS)
2019 		goto out;
2020 	/*
2021 	 * Perform a write in order to increase the write counter. This
2022 	 * prevents late usage (replay attack) of a previously blocked
2023 	 * request with a valid write counter value.
2024 	 */
2025 	res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS,
2026 			     (uint8_t *)partition_data, RPMB_DATA_SIZE,
2027 			     NULL, NULL);
2028 	if (res != TEE_SUCCESS)
2029 		goto out;
2030 	/*
2031 	 * We're reading again in case a stale request was committed
2032 	 * instead of the one issued above. If this succeeds we're in sync
2033 	 * with the RPMB block since there are no other possible stale
2034 	 * blocks with valid write counters available.
2035 	 */
2036 	res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS,
2037 			    (uint8_t *)partition_data,
2038 			    sizeof(struct rpmb_fs_partition), NULL, NULL);
2039 	if (res != TEE_SUCCESS)
2040 		goto out;
2041 
2042 #ifndef CFG_RPMB_RESET_FAT
2043 	if (partition_data->rpmb_fs_magic == RPMB_FS_MAGIC) {
2044 		if (partition_data->fs_version == FS_VERSION) {
2045 			res = TEE_SUCCESS;
2046 			goto store_fs_par;
2047 		} else {
2048 			EMSG("Wrong software is in use.");
2049 			res = TEE_ERROR_ACCESS_DENIED;
2050 			goto out;
2051 		}
2052 	}
2053 #else
2054 	EMSG("**** Clearing Storage ****");
2055 #endif
2056 
2057 	/* Setup new partition data. */
2058 	partition_data->rpmb_fs_magic = RPMB_FS_MAGIC;
2059 	partition_data->fs_version = FS_VERSION;
2060 	partition_data->fat_start_address = RPMB_FS_FAT_START_ADDRESS;
2061 
2062 	/* Initial FAT entry with FILE_IS_LAST_ENTRY flag set. */
2063 	fh = alloc_file_handle(NULL, false);
2064 	if (!fh) {
2065 		res = TEE_ERROR_OUT_OF_MEMORY;
2066 		goto out;
2067 	}
2068 	fh->fat_entry.flags = FILE_IS_LAST_ENTRY;
2069 	fh->rpmb_fat_address = partition_data->fat_start_address;
2070 
2071 	/* Write init FAT entry and partition data to RPMB. */
2072 	res = write_fat_entry(fh, true);
2073 	if (res != TEE_SUCCESS)
2074 		goto out;
2075 
2076 	res =
2077 	    tee_rpmb_get_write_counter(CFG_RPMB_FS_DEV_ID,
2078 				       &partition_data->write_counter);
2079 	if (res != TEE_SUCCESS)
2080 		goto out;
2081 	res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS,
2082 			     (uint8_t *)partition_data,
2083 			     sizeof(struct rpmb_fs_partition), NULL, NULL);
2084 
2085 #ifndef CFG_RPMB_RESET_FAT
2086 store_fs_par:
2087 #endif
2088 
2089 	/* Store FAT start address. */
2090 	fs_par = calloc(1, sizeof(struct rpmb_fs_parameters));
2091 	if (!fs_par) {
2092 		res = TEE_ERROR_OUT_OF_MEMORY;
2093 		goto out;
2094 	}
2095 
2096 	fs_par->fat_start_address = partition_data->fat_start_address;
2097 	fs_par->max_rpmb_address = max_rpmb_block << RPMB_BLOCK_SIZE_SHIFT;
2098 
2099 	dump_fat();
2100 
2101 out:
2102 	free(fh);
2103 	free(partition_data);
2104 	return res;
2105 }
2106 
2107 /**
2108  * get_fat_start_address:
2109  * FAT start_address from fs_par.
2110  */
2111 static TEE_Result get_fat_start_address(uint32_t *addr)
2112 {
2113 	if (!fs_par)
2114 		return TEE_ERROR_NO_DATA;
2115 
2116 	*addr = fs_par->fat_start_address;
2117 
2118 	return TEE_SUCCESS;
2119 }
2120 
2121 /**
2122  * read_fat: Read FAT entries
2123  * Return matching FAT entry for read, rm rename and stat.
2124  * Build up memory pool and return matching entry for write operation.
2125  * "Last FAT entry" can be returned during write.
2126  */
2127 static TEE_Result read_fat(struct rpmb_file_handle *fh, tee_mm_pool_t *p)
2128 {
2129 	TEE_Result res = TEE_ERROR_GENERIC;
2130 	tee_mm_entry_t *mm = NULL;
2131 	struct rpmb_fat_entry *fe = NULL;
2132 	uint32_t fat_address;
2133 	bool entry_found = false;
2134 	bool expand_fat = false;
2135 	struct rpmb_file_handle last_fh;
2136 
2137 	DMSG("fat_address %d", fh->rpmb_fat_address);
2138 
2139 	res = fat_entry_dir_init();
2140 	if (res)
2141 		goto out;
2142 
2143 	/*
2144 	 * The pool is used to represent the current RPMB layout. To find
2145 	 * a slot for the file tee_mm_alloc is called on the pool. Thus
2146 	 * if it is not NULL the entire FAT must be traversed to fill in
2147 	 * the pool.
2148 	 */
2149 	while (true) {
2150 		res = fat_entry_dir_get_next(&fe, &fat_address);
2151 		if (res || !fe)
2152 			break;
2153 
2154 		/*
2155 		 * Look for an entry, matching filenames. (read, rm,
2156 		 * rename and stat.). Only store first filename match.
2157 		 */
2158 		if ((!strcmp(fh->filename, fe->filename)) &&
2159 		    (fe->flags & FILE_IS_ACTIVE) && !entry_found) {
2160 			entry_found = true;
2161 			fh->rpmb_fat_address = fat_address;
2162 			memcpy(&fh->fat_entry, fe, sizeof(*fe));
2163 			if (!p)
2164 				break;
2165 		}
2166 
2167 		/* Add existing files to memory pool. (write) */
2168 		if (p) {
2169 			if ((fe->flags & FILE_IS_ACTIVE) && fe->data_size > 0) {
2170 
2171 				mm = tee_mm_alloc2(p, fe->start_address,
2172 						   fe->data_size);
2173 				if (!mm) {
2174 					res = TEE_ERROR_OUT_OF_MEMORY;
2175 					goto out;
2176 				}
2177 			}
2178 
2179 			/* Unused FAT entries can be reused (write) */
2180 			if (((fe->flags & FILE_IS_ACTIVE) == 0) &&
2181 			    fh->rpmb_fat_address == 0) {
2182 				fh->rpmb_fat_address = fat_address;
2183 				memcpy(&fh->fat_entry, fe,
2184 				       sizeof(struct rpmb_fat_entry));
2185 			}
2186 
2187 			if (((fe->flags & FILE_IS_LAST_ENTRY) != 0) &&
2188 			    fh->rpmb_fat_address == fat_address) {
2189 
2190 				/*
2191 				 * If the last entry was reached and was chosen
2192 				 * by the previous check, then the FAT needs to
2193 				 * be expanded.
2194 				 * fh->rpmb_fat_address is the address chosen
2195 				 * to store the files FAT entry and fat_address
2196 				 * is the current FAT entry address being
2197 				 * compared.
2198 				 */
2199 				expand_fat = true;
2200 			}
2201 		}
2202 	}
2203 
2204 	if (res)
2205 		goto out;
2206 	/*
2207 	 * Represent the FAT table in the pool.
2208 	 */
2209 	if (p) {
2210 		/*
2211 		 * Since fat_address is the start of the last entry it needs to
2212 		 * be moved up by an entry.
2213 		 */
2214 		fat_address += sizeof(struct rpmb_fat_entry);
2215 
2216 		/* Make room for yet a FAT entry and add to memory pool. */
2217 		if (expand_fat)
2218 			fat_address += sizeof(struct rpmb_fat_entry);
2219 
2220 		mm = tee_mm_alloc2(p, RPMB_STORAGE_START_ADDRESS, fat_address);
2221 		if (!mm) {
2222 			res = TEE_ERROR_OUT_OF_MEMORY;
2223 			goto out;
2224 		}
2225 
2226 		if (expand_fat) {
2227 			/*
2228 			 * Point fat_address to the beginning of the new
2229 			 * entry.
2230 			 */
2231 			fat_address -= sizeof(struct rpmb_fat_entry);
2232 			memset(&last_fh, 0, sizeof(last_fh));
2233 			last_fh.fat_entry.flags = FILE_IS_LAST_ENTRY;
2234 			last_fh.rpmb_fat_address = fat_address;
2235 			res = write_fat_entry(&last_fh, true);
2236 			if (res != TEE_SUCCESS)
2237 				goto out;
2238 		}
2239 	}
2240 
2241 	if (!fh->rpmb_fat_address)
2242 		res = TEE_ERROR_ITEM_NOT_FOUND;
2243 
2244 out:
2245 	fat_entry_dir_deinit();
2246 	return res;
2247 }
2248 
2249 static TEE_Result generate_fek(struct rpmb_fat_entry *fe, const TEE_UUID *uuid)
2250 {
2251 	TEE_Result res;
2252 
2253 again:
2254 	res = tee_fs_generate_fek(uuid, fe->fek, sizeof(fe->fek));
2255 	if (res != TEE_SUCCESS)
2256 		return res;
2257 
2258 	if (is_zero(fe->fek, sizeof(fe->fek)))
2259 		goto again;
2260 
2261 	return res;
2262 }
2263 
2264 static TEE_Result rpmb_fs_open_internal(struct rpmb_file_handle *fh,
2265 					const TEE_UUID *uuid, bool create)
2266 {
2267 	tee_mm_pool_t p;
2268 	bool pool_result;
2269 	TEE_Result res = TEE_ERROR_GENERIC;
2270 
2271 	/* We need to do setup in order to make sure fs_par is filled in */
2272 	res = rpmb_fs_setup();
2273 	if (res != TEE_SUCCESS)
2274 		goto out;
2275 
2276 	fh->uuid = uuid;
2277 	if (create) {
2278 		/* Upper memory allocation must be used for RPMB_FS. */
2279 		pool_result = tee_mm_init(&p,
2280 					  RPMB_STORAGE_START_ADDRESS,
2281 					  fs_par->max_rpmb_address,
2282 					  RPMB_BLOCK_SIZE_SHIFT,
2283 					  TEE_MM_POOL_HI_ALLOC);
2284 
2285 		if (!pool_result) {
2286 			res = TEE_ERROR_OUT_OF_MEMORY;
2287 			goto out;
2288 		}
2289 
2290 		res = read_fat(fh, &p);
2291 		tee_mm_final(&p);
2292 		if (res != TEE_SUCCESS)
2293 			goto out;
2294 	} else {
2295 		res = read_fat(fh, NULL);
2296 		if (res != TEE_SUCCESS)
2297 			goto out;
2298 	}
2299 
2300 	/*
2301 	 * If this is opened with create and the entry found was not active
2302 	 * then this is a new file and the FAT entry must be written
2303 	 */
2304 	if (create) {
2305 		if ((fh->fat_entry.flags & FILE_IS_ACTIVE) == 0) {
2306 			memset(&fh->fat_entry, 0,
2307 				sizeof(struct rpmb_fat_entry));
2308 			memcpy(fh->fat_entry.filename, fh->filename,
2309 				strlen(fh->filename));
2310 			/* Start address and size are 0 */
2311 			fh->fat_entry.flags = FILE_IS_ACTIVE;
2312 
2313 			res = generate_fek(&fh->fat_entry, uuid);
2314 			if (res != TEE_SUCCESS)
2315 				goto out;
2316 			DMSG("GENERATE FEK key: %p",
2317 			     (void *)fh->fat_entry.fek);
2318 			DHEXDUMP(fh->fat_entry.fek, sizeof(fh->fat_entry.fek));
2319 
2320 			res = write_fat_entry(fh, true);
2321 			if (res != TEE_SUCCESS)
2322 				goto out;
2323 		}
2324 	}
2325 
2326 	res = TEE_SUCCESS;
2327 
2328 out:
2329 	return res;
2330 }
2331 
2332 static void rpmb_fs_close(struct tee_file_handle **tfh)
2333 {
2334 	struct rpmb_file_handle *fh = (struct rpmb_file_handle *)*tfh;
2335 
2336 	free(fh);
2337 	*tfh = NULL;
2338 }
2339 
2340 static TEE_Result rpmb_fs_read(struct tee_file_handle *tfh, size_t pos,
2341 			       void *buf, size_t *len)
2342 {
2343 	TEE_Result res;
2344 	struct rpmb_file_handle *fh = (struct rpmb_file_handle *)tfh;
2345 	size_t size = *len;
2346 
2347 	if (!size)
2348 		return TEE_SUCCESS;
2349 
2350 	mutex_lock(&rpmb_mutex);
2351 
2352 	dump_fh(fh);
2353 
2354 	res = read_fat(fh, NULL);
2355 	if (res != TEE_SUCCESS)
2356 		goto out;
2357 
2358 	if (pos >= fh->fat_entry.data_size) {
2359 		*len = 0;
2360 		goto out;
2361 	}
2362 
2363 	size = MIN(size, fh->fat_entry.data_size - pos);
2364 	if (size) {
2365 		res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
2366 				    fh->fat_entry.start_address + pos, buf,
2367 				    size, fh->fat_entry.fek, fh->uuid);
2368 		if (res != TEE_SUCCESS)
2369 			goto out;
2370 	}
2371 	*len = size;
2372 
2373 out:
2374 	mutex_unlock(&rpmb_mutex);
2375 	return res;
2376 }
2377 
2378 static TEE_Result update_write_helper(struct rpmb_file_handle *fh,
2379 				      size_t pos, const void *buf,
2380 				      size_t size, uintptr_t new_fat,
2381 				      size_t new_size)
2382 {
2383 	uintptr_t old_fat = fh->fat_entry.start_address;
2384 	size_t old_size = fh->fat_entry.data_size;
2385 	const uint8_t *rem_buf = buf;
2386 	size_t rem_size = size;
2387 	uint8_t *blk_buf = NULL;
2388 	size_t blk_offset = 0;
2389 	size_t blk_size = 0;
2390 	TEE_Result res = TEE_SUCCESS;
2391 
2392 	blk_buf = mempool_alloc(mempool_default, TMP_BLOCK_SIZE);
2393 	if (!blk_buf)
2394 		return TEE_ERROR_OUT_OF_MEMORY;
2395 
2396 	while (blk_offset < new_size) {
2397 		uint8_t *copy_dst = blk_buf;
2398 		size_t copy_size = 0;
2399 		size_t rd_size = 0;
2400 
2401 		blk_size = MIN(TMP_BLOCK_SIZE, new_size - blk_offset);
2402 		memset(blk_buf, 0, blk_size);
2403 
2404 		/* Possibly read old RPMB data in temporary buffer */
2405 		if (blk_offset < pos && blk_offset < old_size) {
2406 			rd_size = MIN(blk_size, old_size - blk_offset);
2407 
2408 			res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
2409 					    old_fat + blk_offset, blk_buf,
2410 					    rd_size, fh->fat_entry.fek,
2411 					    fh->uuid);
2412 			if (res != TEE_SUCCESS)
2413 				break;
2414 		}
2415 
2416 		/* Possibly update data in temporary buffer */
2417 		if ((blk_offset + TMP_BLOCK_SIZE > pos) &&
2418 		    (blk_offset < pos + size)) {
2419 			size_t offset = 0;
2420 
2421 			copy_dst = blk_buf;
2422 			copy_size = TMP_BLOCK_SIZE;
2423 
2424 			if (blk_offset < pos) {
2425 				offset = pos - blk_offset;
2426 
2427 				copy_dst += offset;
2428 				copy_size -= offset;
2429 			}
2430 			copy_size = MIN(copy_size, rem_size);
2431 
2432 			memcpy(copy_dst, rem_buf, copy_size);
2433 			rem_buf += copy_size;
2434 			rem_size -= copy_size;
2435 		}
2436 
2437 		/* Write temporary buffer to new RPMB destination */
2438 		res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, new_fat + blk_offset,
2439 				     blk_buf, blk_size,
2440 				     fh->fat_entry.fek, fh->uuid);
2441 		if (res != TEE_SUCCESS)
2442 			break;
2443 
2444 		blk_offset += blk_size;
2445 	}
2446 
2447 	mempool_free(mempool_default, blk_buf);
2448 
2449 	return res;
2450 }
2451 
2452 static TEE_Result rpmb_fs_write_primitive(struct rpmb_file_handle *fh,
2453 					  size_t pos, const void *buf,
2454 					  size_t size)
2455 {
2456 	TEE_Result res = TEE_ERROR_GENERIC;
2457 	tee_mm_pool_t p = { };
2458 	bool pool_result = false;
2459 	size_t end = 0;
2460 	uint32_t start_addr = 0;
2461 
2462 	if (!size)
2463 		return TEE_SUCCESS;
2464 
2465 	if (!fs_par) {
2466 		res = TEE_ERROR_GENERIC;
2467 		goto out;
2468 	}
2469 
2470 	dump_fh(fh);
2471 
2472 	/* Upper memory allocation must be used for RPMB_FS. */
2473 	pool_result = tee_mm_init(&p,
2474 				  RPMB_STORAGE_START_ADDRESS,
2475 				  fs_par->max_rpmb_address,
2476 				  RPMB_BLOCK_SIZE_SHIFT,
2477 				  TEE_MM_POOL_HI_ALLOC);
2478 	if (!pool_result) {
2479 		res = TEE_ERROR_OUT_OF_MEMORY;
2480 		goto out;
2481 	}
2482 
2483 	res = read_fat(fh, &p);
2484 	if (res != TEE_SUCCESS)
2485 		goto out;
2486 
2487 	if (fh->fat_entry.flags & FILE_IS_LAST_ENTRY)
2488 		panic("invalid last entry flag");
2489 
2490 	if (ADD_OVERFLOW(pos, size, &end)) {
2491 		res = TEE_ERROR_BAD_PARAMETERS;
2492 		goto out;
2493 	}
2494 	if (ADD_OVERFLOW(fh->fat_entry.start_address, pos, &start_addr)) {
2495 		res = TEE_ERROR_BAD_PARAMETERS;
2496 		goto out;
2497 	}
2498 
2499 	if (end <= fh->fat_entry.data_size &&
2500 	    tee_rpmb_write_is_atomic(CFG_RPMB_FS_DEV_ID, start_addr, size)) {
2501 
2502 		DMSG("Updating data in-place");
2503 		res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, start_addr, buf,
2504 				     size, fh->fat_entry.fek, fh->uuid);
2505 	} else {
2506 		/*
2507 		 * File must be extended, or update cannot be atomic: allocate,
2508 		 * read, update, write.
2509 		 */
2510 		size_t new_size = MAX(end, fh->fat_entry.data_size);
2511 		tee_mm_entry_t *mm = tee_mm_alloc(&p, new_size);
2512 		uintptr_t new_fat_entry = 0;
2513 
2514 		DMSG("Need to re-allocate");
2515 		if (!mm) {
2516 			DMSG("RPMB: No space left");
2517 			res = TEE_ERROR_STORAGE_NO_SPACE;
2518 			goto out;
2519 		}
2520 
2521 		new_fat_entry = tee_mm_get_smem(mm);
2522 
2523 		res = update_write_helper(fh, pos, buf, size,
2524 					  new_fat_entry, new_size);
2525 		if (res == TEE_SUCCESS) {
2526 			fh->fat_entry.data_size = new_size;
2527 			fh->fat_entry.start_address = new_fat_entry;
2528 
2529 			res = write_fat_entry(fh, true);
2530 		}
2531 	}
2532 
2533 out:
2534 	if (pool_result)
2535 		tee_mm_final(&p);
2536 
2537 	return res;
2538 }
2539 
2540 static TEE_Result rpmb_fs_write(struct tee_file_handle *tfh, size_t pos,
2541 				const void *buf, size_t size)
2542 {
2543 	TEE_Result res;
2544 
2545 	mutex_lock(&rpmb_mutex);
2546 	res = rpmb_fs_write_primitive((struct rpmb_file_handle *)tfh, pos,
2547 				      buf, size);
2548 	mutex_unlock(&rpmb_mutex);
2549 
2550 	return res;
2551 }
2552 
2553 static TEE_Result rpmb_fs_remove_internal(struct rpmb_file_handle *fh)
2554 {
2555 	TEE_Result res;
2556 
2557 	res = read_fat(fh, NULL);
2558 	if (res)
2559 		return res;
2560 
2561 	/* Clear this file entry. */
2562 	memset(&fh->fat_entry, 0, sizeof(struct rpmb_fat_entry));
2563 	return write_fat_entry(fh, false);
2564 }
2565 
2566 static TEE_Result rpmb_fs_remove(struct tee_pobj *po)
2567 {
2568 	TEE_Result res;
2569 	struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary);
2570 
2571 	if (!fh)
2572 		return TEE_ERROR_OUT_OF_MEMORY;
2573 
2574 	mutex_lock(&rpmb_mutex);
2575 
2576 	res = rpmb_fs_remove_internal(fh);
2577 
2578 	mutex_unlock(&rpmb_mutex);
2579 
2580 	free(fh);
2581 	return res;
2582 }
2583 
2584 static  TEE_Result rpmb_fs_rename_internal(struct tee_pobj *old,
2585 					   struct tee_pobj *new,
2586 					   bool overwrite)
2587 {
2588 	TEE_Result res = TEE_ERROR_GENERIC;
2589 	struct rpmb_file_handle *fh_old = NULL;
2590 	struct rpmb_file_handle *fh_new = NULL;
2591 
2592 	if (!old) {
2593 		res = TEE_ERROR_BAD_PARAMETERS;
2594 		goto out;
2595 	}
2596 
2597 	if (new)
2598 		fh_old = alloc_file_handle(old, old->temporary);
2599 	else
2600 		fh_old = alloc_file_handle(old, true);
2601 	if (!fh_old) {
2602 		res = TEE_ERROR_OUT_OF_MEMORY;
2603 		goto out;
2604 	}
2605 
2606 	if (new)
2607 		fh_new = alloc_file_handle(new, new->temporary);
2608 	else
2609 		fh_new = alloc_file_handle(old, false);
2610 	if (!fh_new) {
2611 		res = TEE_ERROR_OUT_OF_MEMORY;
2612 		goto out;
2613 	}
2614 
2615 	res = read_fat(fh_old, NULL);
2616 	if (res != TEE_SUCCESS)
2617 		goto out;
2618 
2619 	res = read_fat(fh_new, NULL);
2620 	if (res == TEE_SUCCESS) {
2621 		if (!overwrite) {
2622 			res = TEE_ERROR_ACCESS_CONFLICT;
2623 			goto out;
2624 		}
2625 
2626 		/* Clear this file entry. */
2627 		memset(&fh_new->fat_entry, 0, sizeof(struct rpmb_fat_entry));
2628 		res = write_fat_entry(fh_new, false);
2629 		if (res != TEE_SUCCESS)
2630 			goto out;
2631 	}
2632 
2633 	memset(fh_old->fat_entry.filename, 0, TEE_RPMB_FS_FILENAME_LENGTH);
2634 	memcpy(fh_old->fat_entry.filename, fh_new->filename,
2635 	       strlen(fh_new->filename));
2636 
2637 	res = write_fat_entry(fh_old, false);
2638 
2639 out:
2640 	free(fh_old);
2641 	free(fh_new);
2642 
2643 	return res;
2644 }
2645 
2646 static  TEE_Result rpmb_fs_rename(struct tee_pobj *old, struct tee_pobj *new,
2647 				  bool overwrite)
2648 {
2649 	TEE_Result res;
2650 
2651 	mutex_lock(&rpmb_mutex);
2652 	res = rpmb_fs_rename_internal(old, new, overwrite);
2653 	mutex_unlock(&rpmb_mutex);
2654 
2655 	return res;
2656 }
2657 
2658 static TEE_Result rpmb_fs_truncate(struct tee_file_handle *tfh, size_t length)
2659 {
2660 	struct rpmb_file_handle *fh = (struct rpmb_file_handle *)tfh;
2661 	tee_mm_pool_t p;
2662 	bool pool_result = false;
2663 	tee_mm_entry_t *mm;
2664 	uint32_t newsize;
2665 	uint8_t *newbuf = NULL;
2666 	uintptr_t newaddr;
2667 	TEE_Result res = TEE_ERROR_GENERIC;
2668 
2669 	mutex_lock(&rpmb_mutex);
2670 
2671 	if (length > INT32_MAX) {
2672 		res = TEE_ERROR_BAD_PARAMETERS;
2673 		goto out;
2674 	}
2675 	newsize = length;
2676 
2677 	res = read_fat(fh, NULL);
2678 	if (res != TEE_SUCCESS)
2679 		goto out;
2680 
2681 	if (newsize > fh->fat_entry.data_size) {
2682 		/* Extend file */
2683 
2684 		pool_result = tee_mm_init(&p,
2685 					  RPMB_STORAGE_START_ADDRESS,
2686 					  fs_par->max_rpmb_address,
2687 					  RPMB_BLOCK_SIZE_SHIFT,
2688 					  TEE_MM_POOL_HI_ALLOC);
2689 		if (!pool_result) {
2690 			res = TEE_ERROR_OUT_OF_MEMORY;
2691 			goto out;
2692 		}
2693 		res = read_fat(fh, &p);
2694 		if (res != TEE_SUCCESS)
2695 			goto out;
2696 
2697 		mm = tee_mm_alloc(&p, newsize);
2698 		newbuf = calloc(1, newsize);
2699 		if (!mm || !newbuf) {
2700 			res = TEE_ERROR_OUT_OF_MEMORY;
2701 			goto out;
2702 		}
2703 
2704 		if (fh->fat_entry.data_size) {
2705 			res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID,
2706 					    fh->fat_entry.start_address,
2707 					    newbuf, fh->fat_entry.data_size,
2708 					    fh->fat_entry.fek, fh->uuid);
2709 			if (res != TEE_SUCCESS)
2710 				goto out;
2711 		}
2712 
2713 		newaddr = tee_mm_get_smem(mm);
2714 		res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, newaddr, newbuf,
2715 				     newsize, fh->fat_entry.fek, fh->uuid);
2716 		if (res != TEE_SUCCESS)
2717 			goto out;
2718 
2719 	} else {
2720 		/* Don't change file location */
2721 		newaddr = fh->fat_entry.start_address;
2722 	}
2723 
2724 	/* fh->pos is unchanged */
2725 	fh->fat_entry.data_size = newsize;
2726 	fh->fat_entry.start_address = newaddr;
2727 	res = write_fat_entry(fh, true);
2728 
2729 out:
2730 	mutex_unlock(&rpmb_mutex);
2731 	if (pool_result)
2732 		tee_mm_final(&p);
2733 	if (newbuf)
2734 		free(newbuf);
2735 
2736 	return res;
2737 }
2738 
2739 static void rpmb_fs_dir_free(struct tee_fs_dir *dir)
2740 {
2741 	struct tee_rpmb_fs_dirent *e;
2742 
2743 	if (!dir)
2744 		return;
2745 
2746 	free(dir->current);
2747 
2748 	while ((e = SIMPLEQ_FIRST(&dir->next))) {
2749 		SIMPLEQ_REMOVE_HEAD(&dir->next, link);
2750 		free(e);
2751 	}
2752 }
2753 
2754 static TEE_Result rpmb_fs_dir_populate(const char *path,
2755 				       struct tee_fs_dir *dir)
2756 {
2757 	struct tee_rpmb_fs_dirent *current = NULL;
2758 	struct rpmb_fat_entry *fe = NULL;
2759 	uint32_t fat_address;
2760 	uint32_t filelen;
2761 	char *filename;
2762 	bool matched;
2763 	struct tee_rpmb_fs_dirent *next = NULL;
2764 	uint32_t pathlen;
2765 	TEE_Result res = TEE_ERROR_GENERIC;
2766 	char temp;
2767 
2768 	mutex_lock(&rpmb_mutex);
2769 
2770 	res = fat_entry_dir_init();
2771 	if (res)
2772 		goto out;
2773 
2774 	pathlen = strlen(path);
2775 
2776 	while (true) {
2777 		res = fat_entry_dir_get_next(&fe, &fat_address);
2778 		if (res || !fe)
2779 			break;
2780 
2781 		filename = fe->filename;
2782 		if (fe->flags & FILE_IS_ACTIVE) {
2783 			matched = false;
2784 			filelen = strlen(filename);
2785 			if (filelen > pathlen) {
2786 				temp = filename[pathlen];
2787 				filename[pathlen] = '\0';
2788 				if (strcmp(filename, path) == 0)
2789 					matched = true;
2790 
2791 				filename[pathlen] = temp;
2792 			}
2793 
2794 			if (matched) {
2795 				next = malloc(sizeof(*next));
2796 				if (!next) {
2797 					res = TEE_ERROR_OUT_OF_MEMORY;
2798 					goto out;
2799 				}
2800 
2801 				next->entry.oidlen = tee_hs2b((uint8_t *)
2802 						&filename[pathlen],
2803 						next->entry.oid,
2804 						filelen - pathlen,
2805 						sizeof(next->entry.oid));
2806 				if (next->entry.oidlen) {
2807 					SIMPLEQ_INSERT_TAIL(&dir->next,
2808 							    next, link);
2809 					current = next;
2810 				} else {
2811 					free(next);
2812 					next = NULL;
2813 				}
2814 			}
2815 		}
2816 	}
2817 
2818 	if (res)
2819 		goto out;
2820 
2821 	if (current)
2822 		res = TEE_SUCCESS;
2823 	else
2824 		res = TEE_ERROR_ITEM_NOT_FOUND; /* No directories were found. */
2825 
2826 out:
2827 	mutex_unlock(&rpmb_mutex);
2828 	fat_entry_dir_deinit();
2829 	if (res)
2830 		rpmb_fs_dir_free(dir);
2831 
2832 	return res;
2833 }
2834 
2835 static TEE_Result rpmb_fs_opendir(const TEE_UUID *uuid, struct tee_fs_dir **dir)
2836 {
2837 	uint32_t len;
2838 	char path_local[TEE_RPMB_FS_FILENAME_LENGTH];
2839 	TEE_Result res = TEE_ERROR_GENERIC;
2840 	struct tee_fs_dir *rpmb_dir = NULL;
2841 
2842 	if (!uuid || !dir) {
2843 		res = TEE_ERROR_BAD_PARAMETERS;
2844 		goto out;
2845 	}
2846 
2847 	memset(path_local, 0, sizeof(path_local));
2848 	if (tee_svc_storage_create_dirname(path_local, sizeof(path_local) - 1,
2849 					   uuid) != TEE_SUCCESS) {
2850 		res = TEE_ERROR_BAD_PARAMETERS;
2851 		goto out;
2852 	}
2853 	len = strlen(path_local);
2854 
2855 	/* Add a slash to correctly match the full directory name. */
2856 	if (path_local[len - 1] != '/')
2857 		path_local[len] = '/';
2858 
2859 	rpmb_dir = calloc(1, sizeof(*rpmb_dir));
2860 	if (!rpmb_dir) {
2861 		res = TEE_ERROR_OUT_OF_MEMORY;
2862 		goto out;
2863 	}
2864 	SIMPLEQ_INIT(&rpmb_dir->next);
2865 
2866 	res = rpmb_fs_dir_populate(path_local, rpmb_dir);
2867 	if (res != TEE_SUCCESS) {
2868 		free(rpmb_dir);
2869 		rpmb_dir = NULL;
2870 		goto out;
2871 	}
2872 
2873 	*dir = rpmb_dir;
2874 
2875 out:
2876 	return res;
2877 }
2878 
2879 static TEE_Result rpmb_fs_readdir(struct tee_fs_dir *dir,
2880 				  struct tee_fs_dirent **ent)
2881 {
2882 	if (!dir)
2883 		return TEE_ERROR_GENERIC;
2884 
2885 	free(dir->current);
2886 
2887 	dir->current = SIMPLEQ_FIRST(&dir->next);
2888 	if (!dir->current)
2889 		return TEE_ERROR_ITEM_NOT_FOUND;
2890 
2891 	SIMPLEQ_REMOVE_HEAD(&dir->next, link);
2892 
2893 	*ent = &dir->current->entry;
2894 	return TEE_SUCCESS;
2895 }
2896 
2897 static void rpmb_fs_closedir(struct tee_fs_dir *dir)
2898 {
2899 	if (dir) {
2900 		rpmb_fs_dir_free(dir);
2901 		free(dir);
2902 	}
2903 }
2904 
2905 static TEE_Result rpmb_fs_open(struct tee_pobj *po, size_t *size,
2906 			       struct tee_file_handle **ret_fh)
2907 {
2908 	TEE_Result res;
2909 	struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary);
2910 
2911 	if (!fh)
2912 		return TEE_ERROR_OUT_OF_MEMORY;
2913 
2914 	mutex_lock(&rpmb_mutex);
2915 
2916 	res = rpmb_fs_open_internal(fh, &po->uuid, false);
2917 	if (!res && size)
2918 		*size = fh->fat_entry.data_size;
2919 
2920 	mutex_unlock(&rpmb_mutex);
2921 
2922 	if (res)
2923 		free(fh);
2924 	else
2925 		*ret_fh = (struct tee_file_handle *)fh;
2926 
2927 	return res;
2928 }
2929 
2930 static TEE_Result rpmb_fs_create(struct tee_pobj *po, bool overwrite,
2931 				 const void *head, size_t head_size,
2932 				 const void *attr, size_t attr_size,
2933 				 const void *data, size_t data_size,
2934 				 struct tee_file_handle **ret_fh)
2935 {
2936 	TEE_Result res;
2937 	size_t pos = 0;
2938 	struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary);
2939 
2940 	if (!fh)
2941 		return TEE_ERROR_OUT_OF_MEMORY;
2942 
2943 	mutex_lock(&rpmb_mutex);
2944 	res = rpmb_fs_open_internal(fh, &po->uuid, true);
2945 	if (res)
2946 		goto out;
2947 
2948 	if (head && head_size) {
2949 		res = rpmb_fs_write_primitive(fh, pos, head, head_size);
2950 		if (res)
2951 			goto out;
2952 		pos += head_size;
2953 	}
2954 
2955 	if (attr && attr_size) {
2956 		res = rpmb_fs_write_primitive(fh, pos, attr, attr_size);
2957 		if (res)
2958 			goto out;
2959 		pos += attr_size;
2960 	}
2961 
2962 	if (data && data_size) {
2963 		res = rpmb_fs_write_primitive(fh, pos, data, data_size);
2964 		if (res)
2965 			goto out;
2966 	}
2967 
2968 	if (po->temporary) {
2969 		/*
2970 		 * If it's a temporary filename (which it normally is)
2971 		 * rename into the final filename now that the file is
2972 		 * fully initialized.
2973 		 */
2974 		po->temporary = false;
2975 		res = rpmb_fs_rename_internal(po, NULL, overwrite);
2976 		if (res) {
2977 			po->temporary = true;
2978 			goto out;
2979 		}
2980 		/* Update file handle after rename. */
2981 		tee_svc_storage_create_filename(fh->filename,
2982 						sizeof(fh->filename),
2983 						po, false);
2984 	}
2985 
2986 out:
2987 	if (res) {
2988 		rpmb_fs_remove_internal(fh);
2989 		free(fh);
2990 	} else {
2991 		*ret_fh = (struct tee_file_handle *)fh;
2992 	}
2993 	mutex_unlock(&rpmb_mutex);
2994 
2995 	return res;
2996 }
2997 
2998 const struct tee_file_operations rpmb_fs_ops = {
2999 	.open = rpmb_fs_open,
3000 	.create = rpmb_fs_create,
3001 	.close = rpmb_fs_close,
3002 	.read = rpmb_fs_read,
3003 	.write = rpmb_fs_write,
3004 	.truncate = rpmb_fs_truncate,
3005 	.rename = rpmb_fs_rename,
3006 	.remove = rpmb_fs_remove,
3007 	.opendir = rpmb_fs_opendir,
3008 	.closedir = rpmb_fs_closedir,
3009 	.readdir = rpmb_fs_readdir,
3010 };
3011 
3012 TEE_Result tee_rpmb_fs_raw_open(const char *fname, bool create,
3013 				struct tee_file_handle **ret_fh)
3014 {
3015 	TEE_Result res;
3016 	struct rpmb_file_handle *fh = calloc(1, sizeof(*fh));
3017 	static const TEE_UUID uuid = { 0 };
3018 
3019 	if (!fh)
3020 		return TEE_ERROR_OUT_OF_MEMORY;
3021 
3022 	snprintf(fh->filename, sizeof(fh->filename), "/%s", fname);
3023 
3024 	mutex_lock(&rpmb_mutex);
3025 
3026 	res = rpmb_fs_open_internal(fh, &uuid, create);
3027 
3028 	mutex_unlock(&rpmb_mutex);
3029 
3030 	if (res) {
3031 		if (create)
3032 			rpmb_fs_remove_internal(fh);
3033 		free(fh);
3034 	} else {
3035 		*ret_fh = (struct tee_file_handle *)fh;
3036 	}
3037 
3038 	return res;
3039 }
3040 
3041 bool __weak plat_rpmb_key_is_ready(void)
3042 {
3043 	return true;
3044 }
3045