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