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