1 /*
2  * Copyright (C) 2018 Marvell International Ltd.
3  *
4  * SPDX-License-Identifier:     BSD-3-Clause
5  * https://spdx.org/licenses
6  */
7 
8 #include <inttypes.h>
9 #include <stdint.h>
10 
11 #include <common/debug.h>
12 #include <drivers/marvell/addr_map.h>
13 #include <lib/mmio.h>
14 
15 #include <mvebu_def.h>
16 
17 #include "mc_trustzone.h"
18 
19 #define TZ_SIZE(x)		((x) >> 13)
20 
fls(int x)21 static int fls(int x)
22 {
23 	if (!x)
24 		return 0;
25 
26 	return 32 - __builtin_clz(x);
27 }
28 
29 /* To not duplicate types, the addr_map_win is used, but the "target"
30  * filed is referring to attributes instead of "target".
31  */
tz_enable_win(int ap_index,const struct addr_map_win * win,int win_id)32 void tz_enable_win(int ap_index, const struct addr_map_win *win, int win_id)
33 {
34 	int tz_size;
35 	uint32_t val, base = win->base_addr;
36 
37 	if ((win_id < 0) || (win_id > MVEBU_TZ_MAX_WINS)) {
38 		ERROR("Enabling wrong MC TrustZone window %d!\n", win_id);
39 		return;
40 	}
41 
42 	/* map the window size to trustzone register convention */
43 	tz_size = fls(TZ_SIZE(win->win_size));
44 
45 	VERBOSE("%s: window size = 0x%" PRIx64 " maps to tz_size %d\n",
46 		__func__, win->win_size, tz_size);
47 	if (tz_size < 0 || tz_size > 31) {
48 		ERROR("Using not allowed size for MC TrustZone window %d!\n",
49 		      win_id);
50 		return;
51 	}
52 
53 	if (base & 0xfff) {
54 		base = base & ~0xfff;
55 		WARN("Attempt to open MC TZ win. at 0x%" PRIx64 ", truncate to 0x%x\n",
56 		     win->base_addr, base);
57 	}
58 
59 	val = base | (tz_size << 7) | win->target_id | TZ_VALID;
60 
61 	VERBOSE("%s: base 0x%x, tz_size moved 0x%x, attr 0x%x, val 0x%x\n",
62 		__func__, base, (tz_size << 7), win->target_id, val);
63 
64 	mmio_write_32(MVEBU_AP_MC_TRUSTZONE_REG_LOW(ap_index, win_id), val);
65 
66 	VERBOSE("%s: Win%d[0x%x] configured to 0x%x\n", __func__, win_id,
67 		MVEBU_AP_MC_TRUSTZONE_REG_LOW(ap_index, win_id),
68 		mmio_read_32(MVEBU_AP_MC_TRUSTZONE_REG_LOW(ap_index, win_id)));
69 
70 	mmio_write_32(MVEBU_AP_MC_TRUSTZONE_REG_HIGH(ap_index, win_id),
71 		     (win->base_addr >> 32));
72 
73 	VERBOSE("%s: Win%d[0x%x] configured to 0x%x\n", __func__, win_id,
74 		MVEBU_AP_MC_TRUSTZONE_REG_HIGH(ap_index, win_id),
75 		mmio_read_32(MVEBU_AP_MC_TRUSTZONE_REG_HIGH(ap_index, win_id)));
76 }
77