xref: /optee_os/core/drivers/stm32_bsec.c (revision cb03400251f98aed22a2664509e3ed9e183800b0)
1 // SPDX-License-Identifier: BSD-3-Clause
2 /*
3  * Copyright (c) 2017-2021, STMicroelectronics
4  */
5 
6 #include <assert.h>
7 #include <config.h>
8 #include <drivers/stm32_bsec.h>
9 #include <io.h>
10 #include <kernel/delay.h>
11 #include <kernel/dt.h>
12 #include <kernel/boot.h>
13 #include <kernel/pm.h>
14 #include <kernel/spinlock.h>
15 #include <libfdt.h>
16 #include <limits.h>
17 #include <mm/core_memprot.h>
18 #include <platform_config.h>
19 #include <stm32_util.h>
20 #include <string.h>
21 #include <tee_api_defines.h>
22 #include <types_ext.h>
23 #include <util.h>
24 
25 #ifdef CFG_STM32MP13
26 #define DT_BSEC_COMPAT "st,stm32mp13-bsec"
27 #endif
28 #ifdef CFG_STM32MP15
29 #define DT_BSEC_COMPAT "st,stm32mp15-bsec"
30 #endif
31 
32 #define BSEC_OTP_MASK			GENMASK_32(4, 0)
33 #define BSEC_OTP_BANK_SHIFT		U(5)
34 
35 /* Permanent lock bitmasks */
36 #define DATA_LOWER_OTP_PERLOCK_BIT	U(3)
37 #define DATA_UPPER_OTP_PERLOCK_BIT	U(1)
38 
39 /* BSEC register offset */
40 #define BSEC_OTP_CONF_OFF		U(0x000)
41 #define BSEC_OTP_CTRL_OFF		U(0x004)
42 #define BSEC_OTP_WRDATA_OFF		U(0x008)
43 #define BSEC_OTP_STATUS_OFF		U(0x00C)
44 #define BSEC_OTP_LOCK_OFF		U(0x010)
45 #define BSEC_DEN_OFF			U(0x014)
46 #define BSEC_FEN_OFF			U(0x018)
47 #define BSEC_DISTURBED_OFF		U(0x01C)
48 #define BSEC_DISTURBED1_OFF		U(0x020)
49 #define BSEC_DISTURBED2_OFF		U(0x024)
50 #define BSEC_ERROR_OFF			U(0x034)
51 #define BSEC_ERROR1_OFF			U(0x038)
52 #define BSEC_ERROR2_OFF			U(0x03C)
53 #define BSEC_WRLOCK_OFF			U(0x04C)
54 #define BSEC_WRLOCK1_OFF		U(0x050)
55 #define BSEC_WRLOCK2_OFF		U(0x054)
56 #define BSEC_SPLOCK_OFF			U(0x064)
57 #define BSEC_SPLOCK1_OFF		U(0x068)
58 #define BSEC_SPLOCK2_OFF		U(0x06C)
59 #define BSEC_SWLOCK_OFF			U(0x07C)
60 #define BSEC_SWLOCK1_OFF		U(0x080)
61 #define BSEC_SWLOCK2_OFF		U(0x084)
62 #define BSEC_SRLOCK_OFF			U(0x094)
63 #define BSEC_SRLOCK1_OFF		U(0x098)
64 #define BSEC_SRLOCK2_OFF		U(0x09C)
65 #define BSEC_JTAG_IN_OFF		U(0x0AC)
66 #define BSEC_JTAG_OUT_OFF		U(0x0B0)
67 #define BSEC_SCRATCH_OFF		U(0x0B4)
68 #define BSEC_OTP_DATA_OFF		U(0x200)
69 #define BSEC_IPHW_CFG_OFF		U(0xFF0)
70 #define BSEC_IPVR_OFF			U(0xFF4)
71 #define BSEC_IP_ID_OFF			U(0xFF8)
72 #define BSEC_IP_MAGIC_ID_OFF		U(0xFFC)
73 
74 /* BSEC_CONFIGURATION Register */
75 #define BSEC_CONF_POWER_UP_MASK		BIT(0)
76 #define BSEC_CONF_POWER_UP_SHIFT	U(0)
77 #define BSEC_CONF_FRQ_MASK		GENMASK_32(2, 1)
78 #define BSEC_CONF_FRQ_SHIFT		U(1)
79 #define BSEC_CONF_PRG_WIDTH_MASK	GENMASK_32(6, 3)
80 #define BSEC_CONF_PRG_WIDTH_SHIFT	U(3)
81 #define BSEC_CONF_TREAD_MASK		GENMASK_32(8, 7)
82 #define BSEC_CONF_TREAD_SHIFT		U(7)
83 
84 /* BSEC_CONTROL Register */
85 #define BSEC_READ			U(0x000)
86 #define BSEC_WRITE			U(0x100)
87 #define BSEC_LOCK			U(0x200)
88 
89 /* BSEC_STATUS Register */
90 #define BSEC_MODE_SECURED		BIT(0)
91 #define BSEC_MODE_INVALID		BIT(2)
92 #define BSEC_MODE_BUSY			BIT(3)
93 #define BSEC_MODE_PROGFAIL		BIT(4)
94 #define BSEC_MODE_PWR			BIT(5)
95 #define BSEC_MODE_CLOSED		BIT(8)
96 
97 /* BSEC_DEBUG bitfields */
98 #ifdef CFG_STM32MP13
99 #define BSEC_DEN_ALL_MSK		(GENMASK_32(11, 10) | GENMASK_32(8, 1))
100 #endif
101 #ifdef CFG_STM32MP15
102 #define BSEC_DEN_ALL_MSK		GENMASK_32(11, 1)
103 #endif
104 
105 /*
106  * OTP Lock services definition
107  * Value must corresponding to the bit position in the register
108  */
109 #define BSEC_LOCK_UPPER_OTP		U(0x00)
110 #define BSEC_LOCK_DEBUG			U(0x02)
111 #define BSEC_LOCK_PROGRAM		U(0x04)
112 
113 /* Timeout when polling on status */
114 #define BSEC_TIMEOUT_US			U(10000)
115 
116 struct bsec_dev {
117 	struct io_pa_va base;
118 	unsigned int upper_base;
119 	unsigned int max_id;
120 	uint32_t *nsec_access;
121 };
122 
123 /* Only 1 instance of BSEC is expected per platform */
124 static struct bsec_dev bsec_dev;
125 
126 /* BSEC access protection */
127 static unsigned int lock = SPINLOCK_UNLOCK;
128 
129 static uint32_t bsec_lock(void)
130 {
131 	return may_spin_lock(&lock);
132 }
133 
134 static void bsec_unlock(uint32_t exceptions)
135 {
136 	may_spin_unlock(&lock, exceptions);
137 }
138 
139 static uint32_t otp_max_id(void)
140 {
141 	return bsec_dev.max_id;
142 }
143 
144 static uint32_t otp_upper_base(void)
145 {
146 	return bsec_dev.upper_base;
147 }
148 
149 static uint32_t otp_bank_offset(uint32_t otp_id)
150 {
151 	assert(otp_id <= otp_max_id());
152 
153 	return ((otp_id & ~BSEC_OTP_MASK) >> BSEC_OTP_BANK_SHIFT) *
154 		sizeof(uint32_t);
155 }
156 
157 static vaddr_t bsec_base(void)
158 {
159 	return io_pa_or_va_secure(&bsec_dev.base, BSEC_IP_MAGIC_ID_OFF + 1);
160 }
161 
162 static uint32_t bsec_status(void)
163 {
164 	return io_read32(bsec_base() + BSEC_OTP_STATUS_OFF);
165 }
166 
167 static bool state_is_invalid_mode(void)
168 {
169 	return bsec_status() & BSEC_MODE_INVALID;
170 }
171 
172 static bool state_is_secured_mode(void)
173 {
174 	return bsec_status() & BSEC_MODE_SECURED;
175 }
176 
177 static bool state_is_closed_mode(void)
178 {
179 	uint32_t otp_cfg = 0;
180 	uint32_t close_mode = 0;
181 	TEE_Result res = TEE_ERROR_GENERIC;
182 	size_t __maybe_unused sz = 0;
183 	uint8_t __maybe_unused offset = 0;
184 
185 	if (IS_ENABLED(CFG_STM32MP13))
186 		return bsec_status() & BSEC_MODE_CLOSED;
187 
188 	res = stm32_bsec_find_otp_in_nvmem_layout("cfg0_otp", &otp_cfg,
189 						  &offset, &sz);
190 	if (res || sz != 8 || offset)
191 		panic("CFG0 OTP not found or invalid");
192 
193 	if (stm32_bsec_read_otp(&close_mode, otp_cfg))
194 		panic("Unable to read OTP");
195 
196 	return close_mode & CFG0_OTP_CLOSED_DEVICE;
197 }
198 
199 /*
200  * Check that BSEC interface does not report an error
201  * @otp_id : OTP number
202  * @check_disturbed: check only error (false) or all sources (true)
203  * Return a TEE_Result compliant value
204  */
205 static TEE_Result check_no_error(uint32_t otp_id, bool check_disturbed)
206 {
207 	uint32_t bit = BIT(otp_id & BSEC_OTP_MASK);
208 	uint32_t bank = otp_bank_offset(otp_id);
209 
210 	if (io_read32(bsec_base() + BSEC_ERROR_OFF + bank) & bit)
211 		return TEE_ERROR_GENERIC;
212 
213 	if (check_disturbed &&
214 	    io_read32(bsec_base() + BSEC_DISTURBED_OFF + bank) & bit)
215 		return TEE_ERROR_GENERIC;
216 
217 	return TEE_SUCCESS;
218 }
219 
220 static TEE_Result power_up_safmem(void)
221 {
222 	uint64_t timeout_ref = 0;
223 
224 	io_mask32(bsec_base() + BSEC_OTP_CONF_OFF, BSEC_CONF_POWER_UP_MASK,
225 		  BSEC_CONF_POWER_UP_MASK);
226 
227 	timeout_ref = timeout_init_us(BSEC_TIMEOUT_US);
228 	while (!timeout_elapsed(timeout_ref))
229 		if (bsec_status() & BSEC_MODE_PWR)
230 			break;
231 
232 	if (bsec_status() & BSEC_MODE_PWR)
233 		return TEE_SUCCESS;
234 
235 	return TEE_ERROR_GENERIC;
236 }
237 
238 static TEE_Result power_down_safmem(void)
239 {
240 	uint64_t timeout_ref = 0;
241 
242 	io_mask32(bsec_base() + BSEC_OTP_CONF_OFF, 0, BSEC_CONF_POWER_UP_MASK);
243 
244 	timeout_ref = timeout_init_us(BSEC_TIMEOUT_US);
245 	while (!timeout_elapsed(timeout_ref))
246 		if (!(bsec_status() & BSEC_MODE_PWR))
247 			break;
248 
249 	if (!(bsec_status() & BSEC_MODE_PWR))
250 		return TEE_SUCCESS;
251 
252 	return TEE_ERROR_GENERIC;
253 }
254 
255 TEE_Result stm32_bsec_shadow_register(uint32_t otp_id)
256 {
257 	TEE_Result result = 0;
258 	uint32_t exceptions = 0;
259 	uint64_t timeout_ref = 0;
260 	bool locked = false;
261 
262 	/* Check if shadowing of OTP is locked, informative only */
263 	result = stm32_bsec_read_sr_lock(otp_id, &locked);
264 	if (result)
265 		return result;
266 
267 	if (locked)
268 		DMSG("BSEC shadow warning: OTP locked");
269 
270 	if (state_is_invalid_mode())
271 		return TEE_ERROR_SECURITY;
272 
273 	exceptions = bsec_lock();
274 
275 	result = power_up_safmem();
276 	if (result)
277 		goto out;
278 
279 	io_write32(bsec_base() + BSEC_OTP_CTRL_OFF, otp_id | BSEC_READ);
280 
281 	timeout_ref = timeout_init_us(BSEC_TIMEOUT_US);
282 	while (!timeout_elapsed(timeout_ref))
283 		if (!(bsec_status() & BSEC_MODE_BUSY))
284 			break;
285 
286 	if (bsec_status() & BSEC_MODE_BUSY)
287 		result = TEE_ERROR_BUSY;
288 	else
289 		result = check_no_error(otp_id, true /* check-disturbed */);
290 
291 	power_down_safmem();
292 
293 out:
294 	bsec_unlock(exceptions);
295 
296 	return result;
297 }
298 
299 TEE_Result stm32_bsec_read_otp(uint32_t *value, uint32_t otp_id)
300 {
301 	if (otp_id > otp_max_id())
302 		return TEE_ERROR_BAD_PARAMETERS;
303 
304 	if (state_is_invalid_mode())
305 		return TEE_ERROR_SECURITY;
306 
307 	*value = io_read32(bsec_base() + BSEC_OTP_DATA_OFF +
308 			   (otp_id * sizeof(uint32_t)));
309 
310 	return TEE_SUCCESS;
311 }
312 
313 TEE_Result stm32_bsec_shadow_read_otp(uint32_t *otp_value, uint32_t otp_id)
314 {
315 	TEE_Result result = 0;
316 
317 	result = stm32_bsec_shadow_register(otp_id);
318 	if (result) {
319 		EMSG("BSEC %"PRIu32" Shadowing Error %#"PRIx32, otp_id, result);
320 		return result;
321 	}
322 
323 	result = stm32_bsec_read_otp(otp_value, otp_id);
324 	if (result)
325 		EMSG("BSEC %"PRIu32" Read Error %#"PRIx32, otp_id, result);
326 
327 	return result;
328 }
329 
330 TEE_Result stm32_bsec_write_otp(uint32_t value, uint32_t otp_id)
331 {
332 	TEE_Result result = 0;
333 	uint32_t exceptions = 0;
334 	vaddr_t otp_data_base = bsec_base() + BSEC_OTP_DATA_OFF;
335 	bool locked = false;
336 
337 	/* Check if write of OTP is locked, informative only */
338 	result = stm32_bsec_read_sw_lock(otp_id, &locked);
339 	if (result)
340 		return result;
341 
342 	if (locked)
343 		DMSG("BSEC write warning: OTP locked");
344 
345 	if (state_is_invalid_mode())
346 		return TEE_ERROR_SECURITY;
347 
348 	exceptions = bsec_lock();
349 
350 	io_write32(otp_data_base + (otp_id * sizeof(uint32_t)), value);
351 
352 	bsec_unlock(exceptions);
353 
354 	return TEE_SUCCESS;
355 }
356 
357 #ifdef CFG_STM32_BSEC_WRITE
358 TEE_Result stm32_bsec_program_otp(uint32_t value, uint32_t otp_id)
359 {
360 	TEE_Result result = 0;
361 	uint32_t exceptions = 0;
362 	uint64_t timeout_ref = 0;
363 	bool locked = false;
364 
365 	/* Check if shadowing of OTP is locked, informative only */
366 	result = stm32_bsec_read_sp_lock(otp_id, &locked);
367 	if (result)
368 		return result;
369 
370 	if (locked)
371 		DMSG("BSEC program warning: OTP locked");
372 
373 	if (io_read32(bsec_base() + BSEC_OTP_LOCK_OFF) & BIT(BSEC_LOCK_PROGRAM))
374 		DMSG("BSEC program warning: GPLOCK activated");
375 
376 	if (state_is_invalid_mode())
377 		return TEE_ERROR_SECURITY;
378 
379 	exceptions = bsec_lock();
380 
381 	result = power_up_safmem();
382 	if (result)
383 		goto out;
384 
385 	io_write32(bsec_base() + BSEC_OTP_WRDATA_OFF, value);
386 	io_write32(bsec_base() + BSEC_OTP_CTRL_OFF, otp_id | BSEC_WRITE);
387 
388 	timeout_ref = timeout_init_us(BSEC_TIMEOUT_US);
389 	while (!timeout_elapsed(timeout_ref))
390 		if (!(bsec_status() & BSEC_MODE_BUSY))
391 			break;
392 
393 	if (bsec_status() & BSEC_MODE_BUSY)
394 		result = TEE_ERROR_BUSY;
395 	else if (bsec_status() & BSEC_MODE_PROGFAIL)
396 		result = TEE_ERROR_BAD_PARAMETERS;
397 	else
398 		result = check_no_error(otp_id, true /* check-disturbed */);
399 
400 	power_down_safmem();
401 
402 out:
403 	bsec_unlock(exceptions);
404 
405 	return result;
406 }
407 
408 TEE_Result stm32_bsec_permanent_lock_otp(uint32_t otp_id)
409 {
410 	TEE_Result result = 0;
411 	uint32_t data = 0;
412 	uint32_t addr = 0;
413 	uint32_t exceptions = 0;
414 	vaddr_t base = bsec_base();
415 	uint64_t timeout_ref = 0;
416 	uint32_t upper_base = otp_upper_base();
417 
418 	if (otp_id > otp_max_id())
419 		return TEE_ERROR_BAD_PARAMETERS;
420 
421 	/*
422 	 * 2 bits per words for lower OTPs: 2:1 Redundancy
423 	 * 1 bit per word for upper OTPs : ECC support
424 	 * e.g with 32 lower and 64 upper OTPs:
425 	 * OTP word to be    ADDR[6:0]   WRDATA[31:0]
426 	 *     locked
427 	 *       0             0x00      0x0000 0003
428 	 *       1             0x00      0x0000 000C
429 	 *      ...             ...              ...
430 	 *       7             0x00      0x0000 C000
431 	 *       8             0x01      0x0000 0003
432 	 *      ...             ...              ...
433 	 *      31             0x03      0x0000 C000
434 	 *      32             0x04      0x0000 0001
435 	 *      33             0x04      0x0000 0002
436 	 *      95             0x07      0x0000 8000
437 	 */
438 	if (otp_id < upper_base) {
439 		addr = otp_id / 8U;
440 		data = DATA_LOWER_OTP_PERLOCK_BIT << ((otp_id * 2U) & 0xF);
441 	} else {
442 		addr = upper_base / 8U + (otp_id - upper_base) / 16U;
443 		data = DATA_UPPER_OTP_PERLOCK_BIT << (otp_id & 0xF);
444 	}
445 
446 	if (state_is_invalid_mode())
447 		return TEE_ERROR_SECURITY;
448 
449 	exceptions = bsec_lock();
450 
451 	result = power_up_safmem();
452 	if (result)
453 		goto out;
454 
455 	io_write32(base + BSEC_OTP_WRDATA_OFF, data);
456 	io_write32(base + BSEC_OTP_CTRL_OFF, addr | BSEC_WRITE | BSEC_LOCK);
457 
458 	timeout_ref = timeout_init_us(BSEC_TIMEOUT_US);
459 	while (!timeout_elapsed(timeout_ref))
460 		if (!(bsec_status() & BSEC_MODE_BUSY))
461 			break;
462 
463 	if (bsec_status() & BSEC_MODE_BUSY)
464 		result = TEE_ERROR_BUSY;
465 	else if (bsec_status() & BSEC_MODE_PROGFAIL)
466 		result = TEE_ERROR_BAD_PARAMETERS;
467 	else
468 		result = check_no_error(otp_id, false /* not-disturbed */);
469 
470 #ifdef CFG_STM32MP13
471 	io_write32(base + BSEC_OTP_CTRL_OFF, addr | BSEC_READ | BSEC_LOCK);
472 #endif
473 
474 	power_down_safmem();
475 
476 out:
477 	bsec_unlock(exceptions);
478 
479 	return result;
480 }
481 #endif /*CFG_STM32_BSEC_WRITE*/
482 
483 TEE_Result stm32_bsec_write_debug_conf(uint32_t value)
484 {
485 	TEE_Result result = TEE_ERROR_GENERIC;
486 	uint32_t exceptions = 0;
487 
488 	assert(!(value & ~BSEC_DEN_ALL_MSK));
489 
490 	if (state_is_invalid_mode())
491 		return TEE_ERROR_SECURITY;
492 
493 	exceptions = bsec_lock();
494 
495 	io_clrsetbits32(bsec_base() + BSEC_DEN_OFF, BSEC_DEN_ALL_MSK, value);
496 
497 	if (stm32_bsec_read_debug_conf() == value)
498 		result = TEE_SUCCESS;
499 
500 	bsec_unlock(exceptions);
501 
502 	return result;
503 }
504 
505 uint32_t stm32_bsec_read_debug_conf(void)
506 {
507 	return io_read32(bsec_base() + BSEC_DEN_OFF) & BSEC_DEN_ALL_MSK;
508 }
509 
510 static TEE_Result set_bsec_lock(uint32_t otp_id, size_t lock_offset)
511 {
512 	uint32_t bank = otp_bank_offset(otp_id);
513 	uint32_t otp_mask = BIT(otp_id & BSEC_OTP_MASK);
514 	vaddr_t lock_addr = bsec_base() + bank + lock_offset;
515 	uint32_t exceptions = 0;
516 
517 	if (otp_id > STM32MP1_OTP_MAX_ID)
518 		return TEE_ERROR_BAD_PARAMETERS;
519 
520 	if (state_is_invalid_mode())
521 		return TEE_ERROR_SECURITY;
522 
523 	exceptions = bsec_lock();
524 
525 	io_write32(lock_addr, otp_mask);
526 
527 	bsec_unlock(exceptions);
528 
529 	return TEE_SUCCESS;
530 }
531 
532 TEE_Result stm32_bsec_set_sr_lock(uint32_t otp_id)
533 {
534 	return set_bsec_lock(otp_id, BSEC_SRLOCK_OFF);
535 }
536 
537 TEE_Result stm32_bsec_set_sw_lock(uint32_t otp_id)
538 {
539 	return set_bsec_lock(otp_id, BSEC_SWLOCK_OFF);
540 }
541 
542 TEE_Result stm32_bsec_set_sp_lock(uint32_t otp_id)
543 {
544 	return set_bsec_lock(otp_id, BSEC_SPLOCK_OFF);
545 }
546 
547 static TEE_Result read_bsec_lock(uint32_t otp_id, bool *locked,
548 				 size_t lock_offset)
549 {
550 	uint32_t bank = otp_bank_offset(otp_id);
551 	uint32_t otp_mask = BIT(otp_id & BSEC_OTP_MASK);
552 	vaddr_t lock_addr = bsec_base() + bank + lock_offset;
553 
554 	if (otp_id > STM32MP1_OTP_MAX_ID)
555 		return TEE_ERROR_BAD_PARAMETERS;
556 
557 	if (state_is_invalid_mode())
558 		return TEE_ERROR_SECURITY;
559 
560 	*locked = (io_read32(lock_addr) & otp_mask) != 0;
561 
562 	return TEE_SUCCESS;
563 }
564 
565 TEE_Result stm32_bsec_read_sr_lock(uint32_t otp_id, bool *locked)
566 {
567 	return read_bsec_lock(otp_id, locked, BSEC_SRLOCK_OFF);
568 }
569 
570 TEE_Result stm32_bsec_read_sw_lock(uint32_t otp_id, bool *locked)
571 {
572 	return read_bsec_lock(otp_id, locked, BSEC_SWLOCK_OFF);
573 }
574 
575 TEE_Result stm32_bsec_read_sp_lock(uint32_t otp_id, bool *locked)
576 {
577 	return read_bsec_lock(otp_id, locked, BSEC_SPLOCK_OFF);
578 }
579 
580 TEE_Result stm32_bsec_read_permanent_lock(uint32_t otp_id, bool *locked)
581 {
582 	return read_bsec_lock(otp_id, locked, BSEC_WRLOCK_OFF);
583 }
584 
585 static size_t nsec_access_array_size(void)
586 {
587 	size_t upper_count = otp_max_id() - otp_upper_base() + 1;
588 
589 	return ROUNDUP_DIV(upper_count, BSEC_BITS_PER_WORD);
590 }
591 
592 static bool nsec_access_granted(unsigned int index)
593 {
594 	uint32_t *array = bsec_dev.nsec_access;
595 
596 	return array &&
597 	       (index / BSEC_BITS_PER_WORD) < nsec_access_array_size() &&
598 	       array[index / BSEC_BITS_PER_WORD] &
599 	       BIT(index % BSEC_BITS_PER_WORD);
600 }
601 
602 bool stm32_bsec_can_access_otp(uint32_t otp_id)
603 {
604 	return (otp_id <= otp_max_id()) && !state_is_invalid_mode();
605 }
606 
607 bool stm32_bsec_nsec_can_access_otp(uint32_t otp_id)
608 {
609 	return otp_id < otp_upper_base() ||
610 	       nsec_access_granted(otp_id - otp_upper_base());
611 }
612 
613 /*
614  * struct nvmem_layout - NVMEM cell description
615  * @name: Name of the nvmem node in the DT
616  * @otp_id: BSEC base index for the OTP words
617  * @bit_offset: Bit offset in the OTP word
618  * @bit_len: Bit size of the OTP word
619  * @phandle: Associated phandle in embedded DTB
620  */
621 struct nvmem_layout {
622 	char *name;
623 	uint32_t otp_id;
624 	uint8_t bit_offset;
625 	size_t bit_len;
626 	uint32_t phandle;
627 };
628 
629 static struct nvmem_layout *nvmem_layout;
630 static size_t nvmem_layout_count;
631 
632 static TEE_Result stm32_bsec_otp_setting(size_t i,
633 					 uint32_t *otp_id,
634 					 uint8_t *otp_bit_offset,
635 					 size_t *otp_bit_len)
636 {
637 	if (otp_id)
638 		*otp_id = nvmem_layout[i].otp_id;
639 
640 	if (otp_bit_offset)
641 		*otp_bit_offset = nvmem_layout[i].bit_offset;
642 
643 	if (otp_bit_len)
644 		*otp_bit_len = nvmem_layout[i].bit_len;
645 
646 	DMSG("nvmem[%zu] = %s at BSEC word %" PRIu32 " bits [%" PRIu8 " %zu]",
647 	     i, nvmem_layout[i].name, nvmem_layout[i].otp_id,
648 	     nvmem_layout[i].bit_offset, nvmem_layout[i].bit_len);
649 
650 	return TEE_SUCCESS;
651 }
652 
653 TEE_Result stm32_bsec_find_otp_in_nvmem_layout(const char *name,
654 					       uint32_t *otp_id,
655 					       uint8_t *otp_bit_offset,
656 					       size_t *otp_bit_len)
657 {
658 	size_t i = 0;
659 
660 	if (!name)
661 		return TEE_ERROR_BAD_PARAMETERS;
662 
663 	for (i = 0; i < nvmem_layout_count; i++) {
664 		if (!nvmem_layout[i].name || strcmp(name, nvmem_layout[i].name))
665 			continue;
666 
667 		return stm32_bsec_otp_setting(i, otp_id, otp_bit_offset,
668 					      otp_bit_len);
669 	}
670 
671 	DMSG("nvmem %s failed", name);
672 
673 	return TEE_ERROR_ITEM_NOT_FOUND;
674 }
675 
676 TEE_Result stm32_bsec_find_otp_by_phandle(const uint32_t phandle,
677 					  uint32_t *otp_id,
678 					  uint8_t *otp_bit_offset,
679 					  size_t *otp_bit_len)
680 {
681 	size_t i = 0;
682 
683 	if (!phandle)
684 		return TEE_ERROR_GENERIC;
685 
686 	for (i = 0; i < nvmem_layout_count; i++) {
687 		if (nvmem_layout[i].phandle != phandle)
688 			continue;
689 
690 		return stm32_bsec_otp_setting(i, otp_id, otp_bit_offset,
691 					      otp_bit_len);
692 	}
693 
694 	DMSG("nvmem %u not found", phandle);
695 
696 	return TEE_ERROR_ITEM_NOT_FOUND;
697 }
698 
699 TEE_Result stm32_bsec_get_state(enum stm32_bsec_sec_state *state)
700 {
701 	if (!state)
702 		return TEE_ERROR_BAD_PARAMETERS;
703 
704 	if (state_is_invalid_mode() || !state_is_secured_mode()) {
705 		*state = BSEC_STATE_INVALID;
706 	} else {
707 		if (state_is_closed_mode())
708 			*state = BSEC_STATE_SEC_CLOSED;
709 		else
710 			*state = BSEC_STATE_SEC_OPEN;
711 	}
712 
713 	return TEE_SUCCESS;
714 }
715 
716 static void enable_nsec_access(unsigned int otp_id)
717 {
718 	unsigned int idx = (otp_id - otp_upper_base()) / BSEC_BITS_PER_WORD;
719 
720 	if (otp_id < otp_upper_base())
721 		return;
722 
723 	if (otp_id > otp_max_id() || stm32_bsec_shadow_register(otp_id))
724 		panic();
725 
726 	bsec_dev.nsec_access[idx] |= BIT(otp_id % BSEC_BITS_PER_WORD);
727 }
728 
729 static void bsec_dt_otp_nsec_access(void *fdt, int bsec_node)
730 {
731 	int bsec_subnode = 0;
732 
733 	bsec_dev.nsec_access = calloc(nsec_access_array_size(),
734 				      sizeof(*bsec_dev.nsec_access));
735 	if (!bsec_dev.nsec_access)
736 		panic();
737 
738 	fdt_for_each_subnode(bsec_subnode, fdt, bsec_node) {
739 		paddr_t reg_offset = 0;
740 		size_t reg_size = 0;
741 		unsigned int otp_id = 0;
742 		unsigned int i = 0;
743 		size_t size = 0;
744 
745 		if (fdt_reg_info(fdt, bsec_subnode, &reg_offset, &reg_size))
746 			panic();
747 
748 		otp_id = reg_offset / sizeof(uint32_t);
749 
750 		if (otp_id < STM32MP1_UPPER_OTP_START) {
751 			unsigned int otp_end =
752 				ROUNDUP_DIV(reg_offset + reg_size,
753 					    sizeof(uint32_t));
754 
755 			if (otp_end > STM32MP1_UPPER_OTP_START) {
756 				/*
757 				 * OTP crosses Lower/Upper boundary, consider
758 				 * only the upper part.
759 				 */
760 				otp_id = STM32MP1_UPPER_OTP_START;
761 				reg_size -= (STM32MP1_UPPER_OTP_START *
762 					     sizeof(uint32_t)) - reg_offset;
763 				reg_offset = STM32MP1_UPPER_OTP_START *
764 					     sizeof(uint32_t);
765 
766 				DMSG("OTP crosses Lower/Upper boundary");
767 			} else {
768 				continue;
769 			}
770 		}
771 
772 		/* Handle different kinds of non-secure accesses */
773 		if (fdt_getprop(fdt, bsec_subnode,
774 				"st,non-secure-otp-provisioning", NULL)) {
775 			bool locked = false;
776 			bool locked_2 = false;
777 
778 			/* Check if write of OTP is locked */
779 			if (stm32_bsec_read_permanent_lock(otp_id, &locked))
780 				panic("Cannot read permanent lock");
781 
782 			/*
783 			 * Check if fuses of the subnode
784 			 * have the same lock status
785 			 */
786 			for (i = 1; i < (reg_size / sizeof(uint32_t)); i++) {
787 				if (stm32_bsec_read_permanent_lock(otp_id + i,
788 								   &locked_2))
789 					panic("Cannot read permanent lock");
790 
791 				if (locked != locked_2) {
792 					EMSG("Inconsistent status OTP ID %u",
793 					     otp_id + i);
794 					locked = true;
795 				}
796 			}
797 
798 			if (locked) {
799 				DMSG("BSEC: OTP locked");
800 				continue;
801 			}
802 		} else if (!fdt_getprop(fdt, bsec_subnode, "st,non-secure-otp",
803 					NULL)) {
804 			continue;
805 		}
806 
807 		if ((reg_offset % sizeof(uint32_t)) ||
808 		    (reg_size % sizeof(uint32_t)))
809 			panic("Unaligned non-secure OTP");
810 
811 		size = reg_size / sizeof(uint32_t);
812 
813 		if (otp_id + size > OTP_MAX_SIZE)
814 			panic("OTP range oversized");
815 
816 		for (i = otp_id; i < otp_id + size; i++)
817 			enable_nsec_access(i);
818 	}
819 }
820 
821 static void save_dt_nvmem_layout(void *fdt, int bsec_node)
822 {
823 	int cell_max = 0;
824 	int cell_cnt = 0;
825 	int node = 0;
826 
827 	fdt_for_each_subnode(node, fdt, bsec_node)
828 		cell_max++;
829 	if (!cell_max)
830 		return;
831 
832 	nvmem_layout = calloc(cell_max, sizeof(*nvmem_layout));
833 	if (!nvmem_layout)
834 		panic();
835 
836 	fdt_for_each_subnode(node, fdt, bsec_node) {
837 		paddr_t reg_offset = 0;
838 		size_t reg_length = 0;
839 		const char *string = NULL;
840 		const char *s = NULL;
841 		int len = 0;
842 		struct nvmem_layout *layout_cell = &nvmem_layout[cell_cnt];
843 		uint32_t bits[2] = { };
844 
845 		string = fdt_get_name(fdt, node, &len);
846 		if (!string || !len)
847 			continue;
848 
849 		layout_cell->phandle = fdt_get_phandle(fdt, node);
850 		assert(layout_cell->phandle != (uint32_t)-1);
851 
852 		if (fdt_reg_info(fdt, node, &reg_offset, &reg_length)) {
853 			DMSG("Malformed nvmem %s: ignored", string);
854 			continue;
855 		}
856 
857 		layout_cell->otp_id = reg_offset / sizeof(uint32_t);
858 		layout_cell->bit_offset = (reg_offset % sizeof(uint32_t)) *
859 					  CHAR_BIT;
860 		layout_cell->bit_len = reg_length * CHAR_BIT;
861 
862 		if (!fdt_read_uint32_array(fdt, node, "bits", bits, 2)) {
863 			layout_cell->bit_offset += bits[0];
864 			layout_cell->bit_len = bits[1];
865 		}
866 
867 		s = strchr(string, '@');
868 		if (s)
869 			len = s - string;
870 
871 		layout_cell->name = strndup(string, len);
872 		if (!layout_cell->name)
873 			panic();
874 		cell_cnt++;
875 		DMSG("nvmem[%d] = %s at BSEC word %" PRIu32
876 		     " bits [%" PRIu8 " %zu]",
877 		     cell_cnt, layout_cell->name, layout_cell->otp_id,
878 		     layout_cell->bit_offset, layout_cell->bit_len);
879 	}
880 
881 	if (cell_cnt != cell_max) {
882 		nvmem_layout = realloc(nvmem_layout,
883 				       cell_cnt * sizeof(*nvmem_layout));
884 		if (!nvmem_layout)
885 			panic();
886 	}
887 
888 	nvmem_layout_count = cell_cnt;
889 }
890 
891 static void initialize_bsec_from_dt(void)
892 {
893 	void *fdt = NULL;
894 	int node = 0;
895 	struct dt_node_info bsec_info = { };
896 
897 	fdt = get_embedded_dt();
898 	node = fdt_node_offset_by_compatible(fdt, 0, DT_BSEC_COMPAT);
899 	if (node < 0)
900 		panic();
901 
902 	fdt_fill_device_info(fdt, &bsec_info, node);
903 
904 	if (bsec_info.reg != bsec_dev.base.pa ||
905 	    !(bsec_info.status & DT_STATUS_OK_SEC))
906 		panic();
907 
908 	bsec_dt_otp_nsec_access(fdt, node);
909 
910 	save_dt_nvmem_layout(fdt, node);
911 }
912 
913 static TEE_Result bsec_pm(enum pm_op op, uint32_t pm_hint __unused,
914 			  const struct pm_callback_handle *hdl __unused)
915 {
916 	static uint32_t debug_conf;
917 
918 	assert(op == PM_OP_SUSPEND || op == PM_OP_RESUME);
919 
920 	if (op == PM_OP_SUSPEND)
921 		debug_conf = stm32_bsec_read_debug_conf();
922 	else
923 		stm32_bsec_write_debug_conf(debug_conf);
924 
925 	return TEE_SUCCESS;
926 }
927 DECLARE_KEEP_PAGER(bsec_pm);
928 
929 static TEE_Result initialize_bsec(void)
930 {
931 	struct stm32_bsec_static_cfg cfg = { };
932 
933 	stm32mp_get_bsec_static_cfg(&cfg);
934 
935 	bsec_dev.base.pa = cfg.base;
936 	bsec_dev.upper_base = cfg.upper_start;
937 	bsec_dev.max_id = cfg.max_id;
938 
939 	if (state_is_invalid_mode())
940 		panic();
941 
942 	initialize_bsec_from_dt();
943 
944 	register_pm_core_service_cb(bsec_pm, NULL, "stm32_bsec");
945 
946 	return TEE_SUCCESS;
947 }
948 
949 early_init(initialize_bsec);
950