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