xref: /optee_os/core/drivers/stm32_i2c.c (revision 37fbce01492df780cfef1e326bebaa6ad384cf4f)
1 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
2 /*
3  * Copyright (c) 2017-2019, STMicroelectronics
4  *
5  * The driver API is defined in header file stm32_i2c.h.
6  *
7  * I2C bus driver does not register to the PM framework. It is the
8  * responsibility of the bus owner to call the related STM32 I2C driver
9  * API functions when bus suspends or resumes.
10  */
11 
12 #include <arm.h>
13 #include <drivers/clk.h>
14 #include <drivers/clk_dt.h>
15 #include <drivers/pinctrl.h>
16 #include <drivers/stm32_gpio.h>
17 #include <drivers/stm32_i2c.h>
18 #include <io.h>
19 #include <kernel/boot.h>
20 #include <kernel/delay.h>
21 #include <kernel/dt.h>
22 #include <kernel/dt_driver.h>
23 #include <kernel/panic.h>
24 #include <libfdt.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include <stm32_util.h>
28 #include <trace.h>
29 
30 /* STM32 I2C registers offsets */
31 #define I2C_CR1				0x00U
32 #define I2C_CR2				0x04U
33 #define I2C_OAR1			0x08U
34 #define I2C_OAR2			0x0CU
35 #define I2C_TIMINGR			0x10U
36 #define I2C_TIMEOUTR			0x14U
37 #define I2C_ISR				0x18U
38 #define I2C_ICR				0x1CU
39 #define I2C_PECR			0x20U
40 #define I2C_RXDR			0x24U
41 #define I2C_TXDR			0x28U
42 #define I2C_SIZE			0x2CU
43 
44 /* Bit definition for I2C_CR1 register */
45 #define I2C_CR1_PE			BIT(0)
46 #define I2C_CR1_TXIE			BIT(1)
47 #define I2C_CR1_RXIE			BIT(2)
48 #define I2C_CR1_ADDRIE			BIT(3)
49 #define I2C_CR1_NACKIE			BIT(4)
50 #define I2C_CR1_STOPIE			BIT(5)
51 #define I2C_CR1_TCIE			BIT(6)
52 #define I2C_CR1_ERRIE			BIT(7)
53 #define I2C_CR1_DNF			GENMASK_32(11, 8)
54 #define I2C_CR1_ANFOFF			BIT(12)
55 #define I2C_CR1_SWRST			BIT(13)
56 #define I2C_CR1_TXDMAEN			BIT(14)
57 #define I2C_CR1_RXDMAEN			BIT(15)
58 #define I2C_CR1_SBC			BIT(16)
59 #define I2C_CR1_NOSTRETCH		BIT(17)
60 #define I2C_CR1_WUPEN			BIT(18)
61 #define I2C_CR1_GCEN			BIT(19)
62 #define I2C_CR1_SMBHEN			BIT(22)
63 #define I2C_CR1_SMBDEN			BIT(21)
64 #define I2C_CR1_ALERTEN			BIT(22)
65 #define I2C_CR1_PECEN			BIT(23)
66 
67 /* Bit definition for I2C_CR2 register */
68 #define I2C_CR2_SADD			GENMASK_32(9, 0)
69 #define I2C_CR2_RD_WRN			BIT(10)
70 #define I2C_CR2_RD_WRN_OFFSET		10U
71 #define I2C_CR2_ADD10			BIT(11)
72 #define I2C_CR2_HEAD10R			BIT(12)
73 #define I2C_CR2_START			BIT(13)
74 #define I2C_CR2_STOP			BIT(14)
75 #define I2C_CR2_NACK			BIT(15)
76 #define I2C_CR2_NBYTES			GENMASK_32(23, 16)
77 #define I2C_CR2_NBYTES_OFFSET		16U
78 #define I2C_CR2_RELOAD			BIT(24)
79 #define I2C_CR2_AUTOEND			BIT(25)
80 #define I2C_CR2_PECBYTE			BIT(26)
81 
82 /* Bit definition for I2C_OAR1 register */
83 #define I2C_OAR1_OA1			GENMASK_32(9, 0)
84 #define I2C_OAR1_OA1MODE		BIT(10)
85 #define I2C_OAR1_OA1EN			BIT(15)
86 
87 /* Bit definition for I2C_OAR2 register */
88 #define I2C_OAR2_OA2			GENMASK_32(7, 1)
89 #define I2C_OAR2_OA2MSK			GENMASK_32(10, 8)
90 #define I2C_OAR2_OA2NOMASK		0
91 #define I2C_OAR2_OA2MASK01		BIT(8)
92 #define I2C_OAR2_OA2MASK02		BIT(9)
93 #define I2C_OAR2_OA2MASK03		GENMASK_32(9, 8)
94 #define I2C_OAR2_OA2MASK04		BIT(10)
95 #define I2C_OAR2_OA2MASK05		(BIT(8) | BIT(10))
96 #define I2C_OAR2_OA2MASK06		(BIT(9) | BIT(10))
97 #define I2C_OAR2_OA2MASK07		GENMASK_32(10, 8)
98 #define I2C_OAR2_OA2EN			BIT(15)
99 
100 /* Bit definition for I2C_TIMINGR register */
101 #define I2C_TIMINGR_SCLL		GENMASK_32(7, 0)
102 #define I2C_TIMINGR_SCLH		GENMASK_32(15, 8)
103 #define I2C_TIMINGR_SDADEL		GENMASK_32(19, 16)
104 #define I2C_TIMINGR_SCLDEL		GENMASK_32(23, 20)
105 #define I2C_TIMINGR_PRESC		GENMASK_32(31, 28)
106 #define I2C_TIMINGR_SCLL_MAX		(I2C_TIMINGR_SCLL + 1)
107 #define I2C_TIMINGR_SCLH_MAX		((I2C_TIMINGR_SCLH >> 8) + 1)
108 #define I2C_TIMINGR_SDADEL_MAX		((I2C_TIMINGR_SDADEL >> 16) + 1)
109 #define I2C_TIMINGR_SCLDEL_MAX		((I2C_TIMINGR_SCLDEL >> 20) + 1)
110 #define I2C_TIMINGR_PRESC_MAX		((I2C_TIMINGR_PRESC >> 28) + 1)
111 #define I2C_SET_TIMINGR_SCLL(n)		((n) & \
112 					 (I2C_TIMINGR_SCLL_MAX - 1))
113 #define I2C_SET_TIMINGR_SCLH(n)		(((n) & \
114 					  (I2C_TIMINGR_SCLH_MAX - 1)) << 8)
115 #define I2C_SET_TIMINGR_SDADEL(n)	(((n) & \
116 					  (I2C_TIMINGR_SDADEL_MAX - 1)) << 16)
117 #define I2C_SET_TIMINGR_SCLDEL(n)	(((n) & \
118 					  (I2C_TIMINGR_SCLDEL_MAX - 1)) << 20)
119 #define I2C_SET_TIMINGR_PRESC(n)	(((n) & \
120 					  (I2C_TIMINGR_PRESC_MAX - 1)) << 28)
121 
122 /* Bit definition for I2C_TIMEOUTR register */
123 #define I2C_TIMEOUTR_TIMEOUTA		GENMASK_32(11, 0)
124 #define I2C_TIMEOUTR_TIDLE		BIT(12)
125 #define I2C_TIMEOUTR_TIMOUTEN		BIT(15)
126 #define I2C_TIMEOUTR_TIMEOUTB		GENMASK_32(27, 16)
127 #define I2C_TIMEOUTR_TEXTEN		BIT(31)
128 
129 /* Bit definition for I2C_ISR register */
130 #define I2C_ISR_TXE			BIT(0)
131 #define I2C_ISR_TXIS			BIT(1)
132 #define I2C_ISR_RXNE			BIT(2)
133 #define I2C_ISR_ADDR			BIT(3)
134 #define I2C_ISR_NACKF			BIT(4)
135 #define I2C_ISR_STOPF			BIT(5)
136 #define I2C_ISR_TC			BIT(6)
137 #define I2C_ISR_TCR			BIT(7)
138 #define I2C_ISR_BERR			BIT(8)
139 #define I2C_ISR_ARLO			BIT(9)
140 #define I2C_ISR_OVR			BIT(10)
141 #define I2C_ISR_PECERR			BIT(11)
142 #define I2C_ISR_TIMEOUT			BIT(12)
143 #define I2C_ISR_ALERT			BIT(13)
144 #define I2C_ISR_BUSY			BIT(15)
145 #define I2C_ISR_DIR			BIT(16)
146 #define I2C_ISR_ADDCODE			GENMASK_32(23, 17)
147 
148 /* Bit definition for I2C_ICR register */
149 #define I2C_ICR_ADDRCF			BIT(3)
150 #define I2C_ICR_NACKCF			BIT(4)
151 #define I2C_ICR_STOPCF			BIT(5)
152 #define I2C_ICR_BERRCF			BIT(8)
153 #define I2C_ICR_ARLOCF			BIT(9)
154 #define I2C_ICR_OVRCF			BIT(10)
155 #define I2C_ICR_PECCF			BIT(11)
156 #define I2C_ICR_TIMOUTCF		BIT(12)
157 #define I2C_ICR_ALERTCF			BIT(13)
158 
159 /* Max data size for a single I2C transfer */
160 #define MAX_NBYTE_SIZE			255U
161 
162 #define I2C_NSEC_PER_SEC		1000000000UL
163 #define I2C_TIMEOUT_BUSY_MS		25
164 #define I2C_TIMEOUT_BUSY_US		(I2C_TIMEOUT_BUSY_MS * 1000)
165 #define I2C_TIMEOUT_RXNE_MS		5
166 
167 #define I2C_TIMEOUT_DEFAULT_MS		100
168 
169 #define CR2_RESET_MASK			(I2C_CR2_SADD | I2C_CR2_HEAD10R | \
170 					 I2C_CR2_NBYTES | I2C_CR2_RELOAD | \
171 					 I2C_CR2_RD_WRN)
172 
173 #define TIMINGR_CLEAR_MASK		(I2C_TIMINGR_SCLL | I2C_TIMINGR_SCLH | \
174 					 I2C_TIMINGR_SDADEL | \
175 					 I2C_TIMINGR_SCLDEL | I2C_TIMINGR_PRESC)
176 
177 /*
178  * I2C transfer modes
179  * I2C_RELOAD: Enable Reload mode
180  * I2C_AUTOEND_MODE: Enable automatic end mode
181  * I2C_SOFTEND_MODE: Enable software end mode
182  */
183 #define I2C_RELOAD_MODE				I2C_CR2_RELOAD
184 #define I2C_AUTOEND_MODE			I2C_CR2_AUTOEND
185 #define I2C_SOFTEND_MODE			0x0
186 
187 /*
188  * Start/restart/stop I2C transfer requests.
189  *
190  * I2C_NO_STARTSTOP: Don't Generate stop and start condition
191  * I2C_GENERATE_STOP: Generate stop condition (size should be set to 0)
192  * I2C_GENERATE_START_READ: Generate Restart for read request.
193  * I2C_GENERATE_START_WRITE: Generate Restart for write request
194  */
195 #define I2C_NO_STARTSTOP			0x0
196 #define I2C_GENERATE_STOP			(BIT(31) | I2C_CR2_STOP)
197 #define I2C_GENERATE_START_READ			(BIT(31) | I2C_CR2_START | \
198 						 I2C_CR2_RD_WRN)
199 #define I2C_GENERATE_START_WRITE		(BIT(31) | I2C_CR2_START)
200 
201 /* Memory address byte sizes */
202 #define I2C_MEMADD_SIZE_8BIT		1
203 #define I2C_MEMADD_SIZE_16BIT		2
204 
205 /* Effective rate cannot be lower than 80% target rate */
206 #define RATE_MIN(rate)			(((rate) * 80U) / 100U)
207 
208 /*
209  * struct i2c_spec_s - Private I2C timing specifications.
210  * @rate: I2C bus speed (Hz)
211  * @fall_max: Max fall time of both SDA and SCL signals (ns)
212  * @rise_max: Max rise time of both SDA and SCL signals (ns)
213  * @hddat_min: Min data hold time (ns)
214  * @vddat_max: Max data valid time (ns)
215  * @sudat_min: Min data setup time (ns)
216  * @l_min: Min low period of the SCL clock (ns)
217  * @h_min: Min high period of the SCL clock (ns)
218  */
219 struct i2c_spec_s {
220 	uint32_t rate;
221 	uint32_t fall_max;
222 	uint32_t rise_max;
223 	uint32_t hddat_min;
224 	uint32_t vddat_max;
225 	uint32_t sudat_min;
226 	uint32_t l_min;
227 	uint32_t h_min;
228 };
229 
230 /*
231  * struct i2c_timing_s - Private I2C output parameters.
232  * @scldel: Data setup time
233  * @sdadel: Data hold time
234  * @sclh: SCL high period (master mode)
235  * @sclh: SCL low period (master mode)
236  * @is_saved: True if relating to a configuration candidate
237  */
238 struct i2c_timing_s {
239 	uint8_t scldel;
240 	uint8_t sdadel;
241 	uint8_t sclh;
242 	uint8_t scll;
243 	bool is_saved;
244 };
245 
246 /* This table must be sorted in increasing value for field @rate */
247 static const struct i2c_spec_s i2c_specs[] = {
248 	/* Standard - 100KHz */
249 	{
250 		.rate = I2C_STANDARD_RATE,
251 		.fall_max = 300,
252 		.rise_max = 1000,
253 		.hddat_min = 0,
254 		.vddat_max = 3450,
255 		.sudat_min = 250,
256 		.l_min = 4700,
257 		.h_min = 4000,
258 	},
259 	/* Fast - 400KHz */
260 	{
261 		.rate = I2C_FAST_RATE,
262 		.fall_max = 300,
263 		.rise_max = 300,
264 		.hddat_min = 0,
265 		.vddat_max = 900,
266 		.sudat_min = 100,
267 		.l_min = 1300,
268 		.h_min = 600,
269 	},
270 	/* FastPlus - 1MHz */
271 	{
272 		.rate = I2C_FAST_PLUS_RATE,
273 		.fall_max = 100,
274 		.rise_max = 120,
275 		.hddat_min = 0,
276 		.vddat_max = 450,
277 		.sudat_min = 50,
278 		.l_min = 500,
279 		.h_min = 260,
280 	},
281 };
282 
283 /*
284  * I2C request parameters
285  * @dev_addr: I2C address of the target device
286  * @mode: Communication mode, one of I2C_MODE_(MASTER|MEM)
287  * @mem_addr: Target memory cell accessed in device (memory mode)
288  * @mem_addr_size: Byte size of the memory cell address (memory mode)
289  * @timeout_ms: Timeout in millisenconds for the request
290  */
291 struct i2c_request {
292 	uint32_t dev_addr;
293 	enum i2c_mode_e mode;
294 	uint32_t mem_addr;
295 	uint32_t mem_addr_size;
296 	unsigned int timeout_ms;
297 };
298 
299 static vaddr_t get_base(struct i2c_handle_s *hi2c)
300 {
301 	return io_pa_or_va_secure(&hi2c->base, hi2c->reg_size);
302 }
303 
304 static void notif_i2c_timeout(struct i2c_handle_s *hi2c)
305 {
306 	hi2c->i2c_err |= I2C_ERROR_TIMEOUT;
307 	hi2c->i2c_state = I2C_STATE_READY;
308 }
309 
310 static const struct i2c_spec_s *get_specs(uint32_t rate)
311 {
312 	size_t i = 0;
313 
314 	for (i = 0; i < ARRAY_SIZE(i2c_specs); i++)
315 		if (rate <= i2c_specs[i].rate)
316 			return i2c_specs + i;
317 
318 	return NULL;
319 }
320 
321 static void save_cfg(struct i2c_handle_s *hi2c, struct i2c_cfg *cfg)
322 {
323 	vaddr_t base = get_base(hi2c);
324 
325 	clk_enable(hi2c->clock);
326 
327 	cfg->cr1 = io_read32(base + I2C_CR1);
328 	cfg->cr2 = io_read32(base + I2C_CR2);
329 	cfg->oar1 = io_read32(base + I2C_OAR1);
330 	cfg->oar2 = io_read32(base + I2C_OAR2);
331 	cfg->timingr = io_read32(base + I2C_TIMINGR);
332 
333 	clk_disable(hi2c->clock);
334 }
335 
336 static void restore_cfg(struct i2c_handle_s *hi2c, struct i2c_cfg *cfg)
337 {
338 	vaddr_t base = get_base(hi2c);
339 
340 	clk_enable(hi2c->clock);
341 
342 	io_clrbits32(base + I2C_CR1, I2C_CR1_PE);
343 	io_write32(base + I2C_TIMINGR, cfg->timingr & TIMINGR_CLEAR_MASK);
344 	io_write32(base + I2C_OAR1, cfg->oar1);
345 	io_write32(base + I2C_CR2, cfg->cr2);
346 	io_write32(base + I2C_OAR2, cfg->oar2);
347 	io_write32(base + I2C_CR1, cfg->cr1 & ~I2C_CR1_PE);
348 	io_setbits32(base + I2C_CR1, cfg->cr1 & I2C_CR1_PE);
349 
350 	clk_disable(hi2c->clock);
351 }
352 
353 static void __maybe_unused dump_cfg(struct i2c_cfg *cfg __maybe_unused)
354 {
355 	DMSG("CR1:  %#"PRIx32, cfg->cr1);
356 	DMSG("CR2:  %#"PRIx32, cfg->cr2);
357 	DMSG("OAR1: %#"PRIx32, cfg->oar1);
358 	DMSG("OAR2: %#"PRIx32, cfg->oar2);
359 	DMSG("TIM:  %#"PRIx32, cfg->timingr);
360 }
361 
362 static void __maybe_unused dump_i2c(struct i2c_handle_s *hi2c)
363 {
364 	vaddr_t __maybe_unused base = get_base(hi2c);
365 
366 	clk_enable(hi2c->clock);
367 
368 	DMSG("CR1:  %#"PRIx32, io_read32(base + I2C_CR1));
369 	DMSG("CR2:  %#"PRIx32, io_read32(base + I2C_CR2));
370 	DMSG("OAR1: %#"PRIx32, io_read32(base + I2C_OAR1));
371 	DMSG("OAR2: %#"PRIx32, io_read32(base + I2C_OAR2));
372 	DMSG("TIM:  %#"PRIx32, io_read32(base + I2C_TIMINGR));
373 
374 	clk_disable(hi2c->clock);
375 }
376 
377 /*
378  * Compute the I2C device timings
379  *
380  * @init: Ref to the initialization configuration structure
381  * @clock_src: I2C clock source frequency (Hz)
382  * @timing: Pointer to the final computed timing result
383  * Return 0 on success or a negative value
384  */
385 static int i2c_compute_timing(struct stm32_i2c_init_s *init,
386 			      unsigned long clock_src, uint32_t *timing)
387 {
388 	const struct i2c_spec_s *specs = NULL;
389 	uint32_t speed_freq = 0;
390 	uint32_t i2cbus = UDIV_ROUND_NEAREST(I2C_NSEC_PER_SEC, speed_freq);
391 	uint32_t i2cclk = UDIV_ROUND_NEAREST(I2C_NSEC_PER_SEC, clock_src);
392 	uint32_t p_prev = I2C_TIMINGR_PRESC_MAX;
393 	uint32_t af_delay_min = 0;
394 	uint32_t af_delay_max = 0;
395 	uint32_t dnf_delay = 0;
396 	uint32_t tsync = 0;
397 	uint32_t clk_min = 0;
398 	uint32_t clk_max = 0;
399 	int clk_error_prev = 0;
400 	uint16_t p = 0;
401 	uint16_t l = 0;
402 	uint16_t a = 0;
403 	uint16_t h = 0;
404 	unsigned int sdadel_min = 0;
405 	unsigned int sdadel_max = 0;
406 	unsigned int scldel_min = 0;
407 	unsigned int delay = 0;
408 	int s = -1;
409 	struct i2c_timing_s solutions[I2C_TIMINGR_PRESC_MAX] = { 0 };
410 
411 	specs = get_specs(init->bus_rate);
412 	if (!specs) {
413 		DMSG("I2C speed out of bound: %"PRId32"Hz", init->bus_rate);
414 		return -1;
415 	}
416 
417 	speed_freq = specs->rate;
418 	i2cbus = UDIV_ROUND_NEAREST(I2C_NSEC_PER_SEC, speed_freq);
419 	clk_error_prev = INT_MAX;
420 
421 	if (init->rise_time > specs->rise_max ||
422 	    init->fall_time > specs->fall_max) {
423 		DMSG("I2C rise{%"PRId32">%"PRId32"}/fall{%"PRId32">%"PRId32"}",
424 		     init->rise_time, specs->rise_max,
425 		     init->fall_time, specs->fall_max);
426 		return -1;
427 	}
428 
429 	if (init->digital_filter_coef > STM32_I2C_DIGITAL_FILTER_MAX) {
430 		DMSG("DNF out of bound %"PRId8"/%d",
431 		     init->digital_filter_coef, STM32_I2C_DIGITAL_FILTER_MAX);
432 		return -1;
433 	}
434 
435 	/* Analog and Digital Filters */
436 	if (init->analog_filter) {
437 		af_delay_min = STM32_I2C_ANALOG_FILTER_DELAY_MIN;
438 		af_delay_max = STM32_I2C_ANALOG_FILTER_DELAY_MAX;
439 	}
440 	dnf_delay = init->digital_filter_coef * i2cclk;
441 
442 	sdadel_min = specs->hddat_min + init->fall_time;
443 	delay = af_delay_min - ((init->digital_filter_coef + 3) * i2cclk);
444 	if (SUB_OVERFLOW(sdadel_min, delay, &sdadel_min))
445 		sdadel_min = 0;
446 
447 	sdadel_max = specs->vddat_max - init->rise_time;
448 	delay = af_delay_max - ((init->digital_filter_coef + 4) * i2cclk);
449 	if (SUB_OVERFLOW(sdadel_max, delay, &sdadel_max))
450 		sdadel_max = 0;
451 
452 	scldel_min = init->rise_time + specs->sudat_min;
453 
454 	DMSG("I2C SDADEL(min/max): %u/%u, SCLDEL(Min): %u",
455 	     sdadel_min, sdadel_max, scldel_min);
456 
457 	/* Compute possible values for PRESC, SCLDEL and SDADEL */
458 	for (p = 0; p < I2C_TIMINGR_PRESC_MAX; p++) {
459 		for (l = 0; l < I2C_TIMINGR_SCLDEL_MAX; l++) {
460 			uint32_t scldel = (l + 1) * (p + 1) * i2cclk;
461 
462 			if (scldel < scldel_min)
463 				continue;
464 
465 			for (a = 0; a < I2C_TIMINGR_SDADEL_MAX; a++) {
466 				uint32_t sdadel = (a * (p + 1) + 1) * i2cclk;
467 
468 				if ((sdadel >= sdadel_min) &&
469 				    (sdadel <= sdadel_max) &&
470 				    (p != p_prev)) {
471 					solutions[p].scldel = l;
472 					solutions[p].sdadel = a;
473 					solutions[p].is_saved = true;
474 					p_prev = p;
475 					break;
476 				}
477 			}
478 
479 			if (p_prev == p)
480 				break;
481 		}
482 	}
483 
484 	if (p_prev == I2C_TIMINGR_PRESC_MAX) {
485 		DMSG("I2C no Prescaler solution");
486 		return -1;
487 	}
488 
489 	tsync = af_delay_min + dnf_delay + (2 * i2cclk);
490 	clk_max = I2C_NSEC_PER_SEC / RATE_MIN(specs->rate);
491 	clk_min = I2C_NSEC_PER_SEC / specs->rate;
492 
493 	/*
494 	 * Among prescaler possibilities discovered above figures out SCL Low
495 	 * and High Period. Provided:
496 	 * - SCL Low Period has to be higher than Low Period of the SCL Clock
497 	 *   defined by I2C Specification. I2C Clock has to be lower than
498 	 *   (SCL Low Period - Analog/Digital filters) / 4.
499 	 * - SCL High Period has to be lower than High Period of the SCL Clock
500 	 *   defined by I2C Specification.
501 	 * - I2C Clock has to be lower than SCL High Period.
502 	 */
503 	for (p = 0; p < I2C_TIMINGR_PRESC_MAX; p++) {
504 		uint32_t prescaler = (p + 1) * i2cclk;
505 
506 		if (!solutions[p].is_saved)
507 			continue;
508 
509 		for (l = 0; l < I2C_TIMINGR_SCLL_MAX; l++) {
510 			uint32_t tscl_l = ((l + 1) * prescaler) + tsync;
511 
512 			if (tscl_l < specs->l_min ||
513 			    i2cclk >= ((tscl_l - af_delay_min - dnf_delay) / 4))
514 				continue;
515 
516 			for (h = 0; h < I2C_TIMINGR_SCLH_MAX; h++) {
517 				uint32_t tscl_h = ((h + 1) * prescaler) + tsync;
518 				uint32_t tscl = tscl_l + tscl_h +
519 						init->rise_time +
520 						init->fall_time;
521 
522 				if (tscl >= clk_min && tscl <= clk_max &&
523 				    tscl_h >= specs->h_min && i2cclk < tscl_h) {
524 					int clk_error = tscl - i2cbus;
525 
526 					if (clk_error < 0)
527 						clk_error = -clk_error;
528 
529 					if (clk_error < clk_error_prev) {
530 						clk_error_prev = clk_error;
531 						solutions[p].scll = l;
532 						solutions[p].sclh = h;
533 						s = p;
534 					}
535 				}
536 			}
537 		}
538 	}
539 
540 	if (s < 0) {
541 		DMSG("I2C no solution at all");
542 		return -1;
543 	}
544 
545 	/* Finalize timing settings */
546 	*timing = I2C_SET_TIMINGR_PRESC(s) |
547 		   I2C_SET_TIMINGR_SCLDEL(solutions[s].scldel) |
548 		   I2C_SET_TIMINGR_SDADEL(solutions[s].sdadel) |
549 		   I2C_SET_TIMINGR_SCLH(solutions[s].sclh) |
550 		   I2C_SET_TIMINGR_SCLL(solutions[s].scll);
551 
552 	DMSG("I2C TIMINGR (PRESC/SCLDEL/SDADEL): %i/%"PRIu8"/%"PRIu8,
553 	     s, solutions[s].scldel, solutions[s].sdadel);
554 	DMSG("I2C TIMINGR (SCLH/SCLL): %"PRIu8"/%"PRIu8,
555 	     solutions[s].sclh, solutions[s].scll);
556 	DMSG("I2C TIMINGR: 0x%"PRIx32, *timing);
557 
558 	return 0;
559 }
560 
561 /* i2c_specs[] must be sorted by increasing rate */
562 static bool __maybe_unused i2c_specs_is_consistent(void)
563 {
564 	size_t i = 0;
565 
566 	COMPILE_TIME_ASSERT(ARRAY_SIZE(i2c_specs));
567 
568 	for (i = 1; i < ARRAY_SIZE(i2c_specs); i++)
569 		if (i2c_specs[i - 1].rate >= i2c_specs[i].rate)
570 			return false;
571 
572 	return true;
573 }
574 
575 /*
576  * @brief  From requested rate, get the closest I2C rate without exceeding it,
577  *         within I2C specification values defined in @i2c_specs.
578  * @param  rate: The requested rate.
579  * @retval Found rate, else the lowest value supported by platform.
580  */
581 static uint32_t get_lower_rate(uint32_t rate)
582 {
583 	size_t i = 0;
584 
585 	for (i = ARRAY_SIZE(i2c_specs); i > 0; i--)
586 		if (rate > i2c_specs[i - 1].rate)
587 			return i2c_specs[i - 1].rate;
588 
589 	return i2c_specs[0].rate;
590 }
591 
592 /*
593  * Setup the I2C device timings
594  *
595  * @hi2c: I2C handle structure
596  * @init: Ref to the initialization configuration structure
597  * @timing: Output TIMINGR register configuration value
598  * @retval 0 if OK, negative value else
599  */
600 static int i2c_setup_timing(struct i2c_handle_s *hi2c,
601 			    struct stm32_i2c_init_s *init,
602 			    uint32_t *timing)
603 {
604 	int rc = 0;
605 	unsigned long clock_src = 0;
606 
607 	assert(i2c_specs_is_consistent());
608 
609 	clock_src = clk_get_rate(hi2c->clock);
610 	if (!clock_src) {
611 		DMSG("Null I2C clock rate");
612 		return -1;
613 	}
614 
615 	/*
616 	 * If the timing has already been computed, and the frequency is the
617 	 * same as when it was computed, then use the saved timing.
618 	 */
619 	if (clock_src == hi2c->saved_frequency) {
620 		*timing = hi2c->saved_timing;
621 		return 0;
622 	}
623 
624 	do {
625 		rc = i2c_compute_timing(init, clock_src, timing);
626 		if (rc) {
627 			DMSG("Failed to compute I2C timings");
628 			if (init->bus_rate > I2C_STANDARD_RATE) {
629 				init->bus_rate = get_lower_rate(init->bus_rate);
630 				IMSG("Downgrade I2C speed to %"PRIu32"Hz)",
631 				     init->bus_rate);
632 			} else {
633 				break;
634 			}
635 		}
636 	} while (rc);
637 
638 	if (rc) {
639 		DMSG("Impossible to compute I2C timings");
640 		return rc;
641 	}
642 
643 	DMSG("I2C Freq(%"PRIu32"Hz), Clk Source(%lu)",
644 	     init->bus_rate, clock_src);
645 	DMSG("I2C Rise(%"PRId32") and Fall(%"PRId32") Time",
646 	     init->rise_time, init->fall_time);
647 	DMSG("I2C Analog Filter(%s), DNF(%"PRIu8")",
648 	     init->analog_filter ? "On" : "Off", init->digital_filter_coef);
649 
650 	hi2c->saved_timing = *timing;
651 	hi2c->saved_frequency = clock_src;
652 
653 	return 0;
654 }
655 
656 /*
657  * Configure I2C Analog noise filter.
658  * @hi2c: I2C handle structure
659  * @analog_filter_on: True if enabling analog filter, false otherwise
660  */
661 static void i2c_config_analog_filter(struct i2c_handle_s *hi2c,
662 				     bool analog_filter_on)
663 {
664 	vaddr_t base = get_base(hi2c);
665 
666 	/* Disable the selected I2C peripheral */
667 	io_clrbits32(base + I2C_CR1, I2C_CR1_PE);
668 
669 	/* Reset I2Cx ANOFF bit */
670 	io_clrbits32(base + I2C_CR1, I2C_CR1_ANFOFF);
671 
672 	/* Set analog filter bit if filter is disabled */
673 	if (!analog_filter_on)
674 		io_setbits32(base + I2C_CR1, I2C_CR1_ANFOFF);
675 
676 	/* Enable the selected I2C peripheral */
677 	io_setbits32(base + I2C_CR1, I2C_CR1_PE);
678 }
679 
680 TEE_Result stm32_i2c_get_setup_from_fdt(void *fdt, int node,
681 					struct stm32_i2c_init_s *init,
682 					struct pinctrl_state **pinctrl,
683 					struct pinctrl_state **pinctrl_sleep)
684 {
685 	TEE_Result res = TEE_ERROR_GENERIC;
686 	const fdt32_t *cuint = NULL;
687 	struct dt_node_info info = { .status = 0 };
688 	int __maybe_unused count = 0;
689 
690 	/* Default STM32 specific configs caller may need to overwrite */
691 	memset(init, 0, sizeof(*init));
692 
693 	fdt_fill_device_info(fdt, &info, node);
694 	assert(info.reg != DT_INFO_INVALID_REG &&
695 	       info.reg_size != DT_INFO_INVALID_REG_SIZE);
696 
697 	init->dt_status = info.status;
698 	init->pbase = info.reg;
699 	init->reg_size = info.reg_size;
700 
701 	res = clk_dt_get_by_index(fdt, node, 0, &init->clock);
702 	if (res)
703 		return res;
704 
705 	cuint = fdt_getprop(fdt, node, "i2c-scl-rising-time-ns", NULL);
706 	if (cuint)
707 		init->rise_time = fdt32_to_cpu(*cuint);
708 	else
709 		init->rise_time = STM32_I2C_RISE_TIME_DEFAULT;
710 
711 	cuint = fdt_getprop(fdt, node, "i2c-scl-falling-time-ns", NULL);
712 	if (cuint)
713 		init->fall_time = fdt32_to_cpu(*cuint);
714 	else
715 		init->fall_time = STM32_I2C_FALL_TIME_DEFAULT;
716 
717 	cuint = fdt_getprop(fdt, node, "clock-frequency", NULL);
718 	if (cuint) {
719 		init->bus_rate = fdt32_to_cpu(*cuint);
720 
721 		if (init->bus_rate > I2C_FAST_PLUS_RATE) {
722 			DMSG("Invalid bus speed (%"PRIu32" > %i)",
723 			     init->bus_rate, I2C_FAST_PLUS_RATE);
724 			return TEE_ERROR_GENERIC;
725 		}
726 	} else {
727 		init->bus_rate = I2C_STANDARD_RATE;
728 	}
729 
730 	if (pinctrl) {
731 		res = pinctrl_get_state_by_name(fdt, node, "default", pinctrl);
732 		if (res)
733 			return res;
734 	}
735 
736 	if (pinctrl_sleep) {
737 		res = pinctrl_get_state_by_name(fdt, node, "sleep",
738 						pinctrl_sleep);
739 		if (res == TEE_ERROR_ITEM_NOT_FOUND)
740 			res = TEE_SUCCESS;
741 		if (res)
742 			return res;
743 	}
744 
745 	return TEE_SUCCESS;
746 }
747 
748 int stm32_i2c_init(struct i2c_handle_s *hi2c,
749 		   struct stm32_i2c_init_s *init_data)
750 {
751 	int rc = 0;
752 	uint32_t timing = 0;
753 	vaddr_t base = 0;
754 	uint32_t val = 0;
755 
756 	rc = i2c_setup_timing(hi2c, init_data, &timing);
757 	if (rc)
758 		return rc;
759 
760 	clk_enable(hi2c->clock);
761 
762 	base = get_base(hi2c);
763 	hi2c->i2c_state = I2C_STATE_BUSY;
764 
765 	/* Disable the selected I2C peripheral */
766 	io_clrbits32(base + I2C_CR1, I2C_CR1_PE);
767 
768 	/* Configure I2Cx: Frequency range */
769 	io_write32(base + I2C_TIMINGR, timing & TIMINGR_CLEAR_MASK);
770 
771 	/* Disable Own Address1 before set the Own Address1 configuration */
772 	io_write32(base + I2C_OAR1, 0);
773 
774 	/* Configure I2Cx: Own Address1 and ack own address1 mode */
775 	if (init_data->addr_mode_10b_not_7b)
776 		io_write32(base + I2C_OAR1,
777 			   I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE |
778 			   init_data->own_address1);
779 	else
780 		io_write32(base + I2C_OAR1,
781 			   I2C_OAR1_OA1EN | init_data->own_address1);
782 
783 	/* Configure I2Cx: Addressing Master mode */
784 	io_write32(base + I2C_CR2, 0);
785 	if (init_data->addr_mode_10b_not_7b)
786 		io_setbits32(base + I2C_CR2, I2C_CR2_ADD10);
787 
788 	/*
789 	 * Enable the AUTOEND by default, and enable NACK
790 	 * (should be disabled only during Slave process).
791 	 */
792 	io_setbits32(base + I2C_CR2, I2C_CR2_AUTOEND | I2C_CR2_NACK);
793 
794 	/* Disable Own Address2 before set the Own Address2 configuration */
795 	io_write32(base + I2C_OAR2, 0);
796 
797 	/* Configure I2Cx: Dual mode and Own Address2 */
798 	if (init_data->dual_address_mode)
799 		io_write32(base + I2C_OAR2,
800 			   I2C_OAR2_OA2EN | init_data->own_address2 |
801 			   (init_data->own_address2_masks << 8));
802 
803 	/* Configure I2Cx: Generalcall and NoStretch mode */
804 	val = 0;
805 	if (init_data->general_call_mode)
806 		val |= I2C_CR1_GCEN;
807 	if (init_data->no_stretch_mode)
808 		val |= I2C_CR1_NOSTRETCH;
809 	io_write32(base + I2C_CR1, val);
810 
811 	/* Enable the selected I2C peripheral */
812 	io_setbits32(base + I2C_CR1, I2C_CR1_PE);
813 
814 	hi2c->i2c_err = I2C_ERROR_NONE;
815 	hi2c->i2c_state = I2C_STATE_READY;
816 
817 	i2c_config_analog_filter(hi2c, init_data->analog_filter);
818 
819 	if (IS_ENABLED(CFG_STM32MP13))
820 		stm32_pinctrl_set_secure_cfg(hi2c->pinctrl, true);
821 
822 	clk_disable(hi2c->clock);
823 
824 	if (hi2c->pinctrl && pinctrl_apply_state(hi2c->pinctrl))
825 		return -1;
826 
827 	return 0;
828 }
829 
830 /* I2C transmit (TX) data register flush sequence */
831 static void i2c_flush_txdr(struct i2c_handle_s *hi2c)
832 {
833 	vaddr_t base = get_base(hi2c);
834 
835 	/*
836 	 * If a pending TXIS flag is set,
837 	 * write a dummy data in TXDR to clear it.
838 	 */
839 	if (io_read32(base + I2C_ISR) & I2C_ISR_TXIS)
840 		io_write32(base + I2C_TXDR, 0);
841 
842 	/* Flush TX register if not empty */
843 	if ((io_read32(base + I2C_ISR) & I2C_ISR_TXE) == 0)
844 		io_setbits32(base + I2C_ISR, I2C_ISR_TXE);
845 }
846 
847 /*
848  * Wait for a single target I2C_ISR bit to reach an awaited value (0 or 1)
849  *
850  * @hi2c: I2C handle structure
851  * @bit_mask: Bit mask for the target single bit position to consider
852  * @awaited_value: Awaited value of the target bit in I2C_ISR, 0 or 1
853  * @timeout_ref: Expriation timeout reference
854  * Return 0 on success and a non-zero value on timeout
855  */
856 static int wait_isr_event(struct i2c_handle_s *hi2c, uint32_t bit_mask,
857 			  unsigned int awaited_value, uint64_t timeout_ref)
858 {
859 	vaddr_t isr = get_base(hi2c) + I2C_ISR;
860 
861 	assert(IS_POWER_OF_TWO(bit_mask) && !(awaited_value & ~1U));
862 
863 	/* May timeout while TEE thread is suspended */
864 	while (!timeout_elapsed(timeout_ref))
865 		if (!!(io_read32(isr) & bit_mask) == awaited_value)
866 			break;
867 
868 	if (!!(io_read32(isr) & bit_mask) == awaited_value)
869 		return 0;
870 
871 	notif_i2c_timeout(hi2c);
872 	return -1;
873 }
874 
875 /* Handle Acknowledge-Failed sequence detection during an I2C Communication */
876 static int i2c_ack_failed(struct i2c_handle_s *hi2c, uint64_t timeout_ref)
877 {
878 	vaddr_t base = get_base(hi2c);
879 
880 	if ((io_read32(base + I2C_ISR) & I2C_ISR_NACKF) == 0U)
881 		return 0;
882 
883 	/*
884 	 * Wait until STOP Flag is reset. Use polling method.
885 	 * AutoEnd should be initiate after AF.
886 	 * Timeout may elpased while TEE thread is suspended.
887 	 */
888 	while (!timeout_elapsed(timeout_ref))
889 		if (io_read32(base + I2C_ISR) & I2C_ISR_STOPF)
890 			break;
891 
892 	if ((io_read32(base + I2C_ISR) & I2C_ISR_STOPF) == 0) {
893 		notif_i2c_timeout(hi2c);
894 		return -1;
895 	}
896 
897 	io_write32(base + I2C_ICR, I2C_ISR_NACKF);
898 
899 	io_write32(base + I2C_ICR, I2C_ISR_STOPF);
900 
901 	i2c_flush_txdr(hi2c);
902 
903 	io_clrbits32(base + I2C_CR2, CR2_RESET_MASK);
904 
905 	hi2c->i2c_err |= I2C_ERROR_ACKF;
906 	hi2c->i2c_state = I2C_STATE_READY;
907 
908 	return -1;
909 }
910 
911 /* Wait TXIS bit is 1 in I2C_ISR register */
912 static int i2c_wait_txis(struct i2c_handle_s *hi2c, uint64_t timeout_ref)
913 {
914 	while (!timeout_elapsed(timeout_ref)) {
915 		if (io_read32(get_base(hi2c) + I2C_ISR) & I2C_ISR_TXIS)
916 			break;
917 		if (i2c_ack_failed(hi2c, timeout_ref))
918 			return -1;
919 	}
920 
921 	if (io_read32(get_base(hi2c) + I2C_ISR) & I2C_ISR_TXIS)
922 		return 0;
923 
924 	if (i2c_ack_failed(hi2c, timeout_ref))
925 		return -1;
926 
927 	notif_i2c_timeout(hi2c);
928 	return -1;
929 }
930 
931 /* Wait STOPF bit is 1 in I2C_ISR register */
932 static int i2c_wait_stop(struct i2c_handle_s *hi2c, uint64_t timeout_ref)
933 {
934 	while (!timeout_elapsed(timeout_ref)) {
935 		if (io_read32(get_base(hi2c) + I2C_ISR) & I2C_ISR_STOPF)
936 			break;
937 
938 		if (i2c_ack_failed(hi2c, timeout_ref))
939 			return -1;
940 	}
941 
942 	if (io_read32(get_base(hi2c) + I2C_ISR) & I2C_ISR_STOPF)
943 		return 0;
944 
945 	if (i2c_ack_failed(hi2c, timeout_ref))
946 		return -1;
947 
948 	notif_i2c_timeout(hi2c);
949 	return -1;
950 }
951 
952 /*
953  * Load I2C_CR2 register for a I2C transfer
954  *
955  * @hi2c: I2C handle structure
956  * @dev_addr: Slave address to be transferred
957  * @size: Number of bytes to be transferred
958  * @i2c_mode: One of I2C_{RELOAD|AUTOEND|SOFTEND}_MODE: Enable Reload mode.
959  * @startstop: One of I2C_NO_STARTSTOP, I2C_GENERATE_STOP,
960  *		I2C_GENERATE_START_{READ|WRITE}
961  */
962 static void i2c_transfer_config(struct i2c_handle_s *hi2c, uint32_t dev_addr,
963 				uint32_t size, uint32_t i2c_mode,
964 				uint32_t startstop)
965 {
966 	uint32_t clr_value = I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD |
967 			     I2C_CR2_AUTOEND | I2C_CR2_START | I2C_CR2_STOP |
968 			     (I2C_CR2_RD_WRN &
969 			      (startstop >> (31U - I2C_CR2_RD_WRN_OFFSET)));
970 	uint32_t set_value = (dev_addr & I2C_CR2_SADD) |
971 			     ((size << I2C_CR2_NBYTES_OFFSET) &
972 			      I2C_CR2_NBYTES) |
973 			     i2c_mode | startstop;
974 
975 	io_clrsetbits32(get_base(hi2c) + I2C_CR2, clr_value, set_value);
976 }
977 
978 /*
979  * Master sends target device address followed by internal memory
980  * address for a memory write request.
981  * Function returns 0 on success or a negative value.
982  */
983 static int i2c_request_mem_write(struct i2c_handle_s *hi2c,
984 				 struct i2c_request *request,
985 				 uint64_t timeout_ref)
986 {
987 	vaddr_t base = get_base(hi2c);
988 
989 	i2c_transfer_config(hi2c, request->dev_addr, request->mem_addr_size,
990 			    I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE);
991 
992 	if (i2c_wait_txis(hi2c, timeout_ref))
993 		return -1;
994 
995 	if (request->mem_addr_size == I2C_MEMADD_SIZE_8BIT) {
996 		/* Send memory address */
997 		io_write8(base + I2C_TXDR, request->mem_addr & 0x00FFU);
998 	} else {
999 		/* Send MSB of memory address */
1000 		io_write8(base + I2C_TXDR, (request->mem_addr & 0xFF00U) >> 8);
1001 
1002 		if (i2c_wait_txis(hi2c, timeout_ref))
1003 			return -1;
1004 
1005 		/* Send LSB of memory address */
1006 		io_write8(base + I2C_TXDR, request->mem_addr & 0x00FFU);
1007 	}
1008 
1009 	if (wait_isr_event(hi2c, I2C_ISR_TCR, 1, timeout_ref))
1010 		return -1;
1011 
1012 	return 0;
1013 }
1014 
1015 /*
1016  * Master sends target device address followed by internal memory
1017  * address to prepare a memory read request.
1018  * Function returns 0 on success or a negative value.
1019  */
1020 static int i2c_request_mem_read(struct i2c_handle_s *hi2c,
1021 				struct i2c_request *request,
1022 				uint64_t timeout_ref)
1023 {
1024 	vaddr_t base = get_base(hi2c);
1025 
1026 	i2c_transfer_config(hi2c, request->dev_addr, request->mem_addr_size,
1027 			    I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE);
1028 
1029 	if (i2c_wait_txis(hi2c, timeout_ref))
1030 		return -1;
1031 
1032 	if (request->mem_addr_size == I2C_MEMADD_SIZE_8BIT) {
1033 		/* Send memory address */
1034 		io_write8(base + I2C_TXDR, request->mem_addr & 0x00FFU);
1035 	} else {
1036 		/* Send MSB of memory address */
1037 		io_write8(base + I2C_TXDR, (request->mem_addr & 0xFF00U) >> 8);
1038 
1039 		if (i2c_wait_txis(hi2c, timeout_ref))
1040 			return -1;
1041 
1042 		/* Send LSB of memory address */
1043 		io_write8(base + I2C_TXDR, request->mem_addr & 0x00FFU);
1044 	}
1045 
1046 	if (wait_isr_event(hi2c, I2C_ISR_TC, 1, timeout_ref))
1047 		return -1;
1048 
1049 	return 0;
1050 }
1051 
1052 /*
1053  * Write an amount of data in blocking mode
1054  *
1055  * @hi2c: Reference to struct i2c_handle_s
1056  * @request: I2C request parameters
1057  * @p_data: Pointer to data buffer
1058  * @size: Amount of data to be sent
1059  * Return 0 on success or a negative value
1060  */
1061 static int do_write(struct i2c_handle_s *hi2c, struct i2c_request *request,
1062 		    uint8_t *p_data, uint16_t size)
1063 {
1064 	uint64_t timeout_ref = 0;
1065 	vaddr_t base = get_base(hi2c);
1066 	int rc = -1;
1067 	uint8_t *p_buff = p_data;
1068 	size_t xfer_size = 0;
1069 	size_t xfer_count = size;
1070 
1071 	if (request->mode != I2C_MODE_MASTER && request->mode != I2C_MODE_MEM)
1072 		return -1;
1073 
1074 	if (hi2c->i2c_state != I2C_STATE_READY)
1075 		return -1;
1076 
1077 	if (!p_data || !size)
1078 		return -1;
1079 
1080 	clk_enable(hi2c->clock);
1081 
1082 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_MS * 1000);
1083 	if (wait_isr_event(hi2c, I2C_ISR_BUSY, 0, timeout_ref))
1084 		goto bail;
1085 
1086 	hi2c->i2c_state = I2C_STATE_BUSY_TX;
1087 	hi2c->i2c_err = I2C_ERROR_NONE;
1088 	timeout_ref = timeout_init_us(request->timeout_ms * 1000);
1089 
1090 	if (request->mode == I2C_MODE_MEM) {
1091 		/* In memory mode, send slave address and memory address */
1092 		if (i2c_request_mem_write(hi2c, request, timeout_ref))
1093 			goto bail;
1094 
1095 		if (xfer_count > MAX_NBYTE_SIZE) {
1096 			xfer_size = MAX_NBYTE_SIZE;
1097 			i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1098 					    I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
1099 		} else {
1100 			xfer_size = xfer_count;
1101 			i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1102 					    I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
1103 		}
1104 	} else {
1105 		/* In master mode, send slave address */
1106 		if (xfer_count > MAX_NBYTE_SIZE) {
1107 			xfer_size = MAX_NBYTE_SIZE;
1108 			i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1109 					    I2C_RELOAD_MODE,
1110 					    I2C_GENERATE_START_WRITE);
1111 		} else {
1112 			xfer_size = xfer_count;
1113 			i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1114 					    I2C_AUTOEND_MODE,
1115 					    I2C_GENERATE_START_WRITE);
1116 		}
1117 	}
1118 
1119 	do {
1120 		if (i2c_wait_txis(hi2c, timeout_ref))
1121 			goto bail;
1122 
1123 		io_write8(base + I2C_TXDR, *p_buff);
1124 		p_buff++;
1125 		xfer_count--;
1126 		xfer_size--;
1127 
1128 		if (xfer_count && !xfer_size) {
1129 			/* Wait until TCR flag is set */
1130 			if (wait_isr_event(hi2c, I2C_ISR_TCR, 1, timeout_ref))
1131 				goto bail;
1132 
1133 			if (xfer_count > MAX_NBYTE_SIZE) {
1134 				xfer_size = MAX_NBYTE_SIZE;
1135 				i2c_transfer_config(hi2c, request->dev_addr,
1136 						    xfer_size,
1137 						    I2C_RELOAD_MODE,
1138 						    I2C_NO_STARTSTOP);
1139 			} else {
1140 				xfer_size = xfer_count;
1141 				i2c_transfer_config(hi2c, request->dev_addr,
1142 						    xfer_size,
1143 						    I2C_AUTOEND_MODE,
1144 						    I2C_NO_STARTSTOP);
1145 			}
1146 		}
1147 
1148 	} while (xfer_count > 0U);
1149 
1150 	/*
1151 	 * No need to Check TC flag, with AUTOEND mode the stop
1152 	 * is automatically generated.
1153 	 * Wait until STOPF flag is reset.
1154 	 */
1155 	if (i2c_wait_stop(hi2c, timeout_ref))
1156 		goto bail;
1157 
1158 	io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1159 
1160 	io_clrbits32(base + I2C_CR2, CR2_RESET_MASK);
1161 
1162 	hi2c->i2c_state = I2C_STATE_READY;
1163 
1164 	rc = 0;
1165 
1166 bail:
1167 	clk_disable(hi2c->clock);
1168 
1169 	return rc;
1170 }
1171 
1172 int stm32_i2c_mem_write(struct i2c_handle_s *hi2c, uint32_t dev_addr,
1173 			uint32_t mem_addr, uint32_t mem_addr_size,
1174 			uint8_t *p_data, size_t size, unsigned int timeout_ms)
1175 {
1176 	struct i2c_request request = {
1177 		.dev_addr = dev_addr,
1178 		.mode = I2C_MODE_MEM,
1179 		.mem_addr = mem_addr,
1180 		.mem_addr_size = mem_addr_size,
1181 		.timeout_ms = timeout_ms,
1182 	};
1183 
1184 	return do_write(hi2c, &request, p_data, size);
1185 }
1186 
1187 int stm32_i2c_master_transmit(struct i2c_handle_s *hi2c, uint32_t dev_addr,
1188 			      uint8_t *p_data, size_t size,
1189 			      unsigned int timeout_ms)
1190 {
1191 	struct i2c_request request = {
1192 		.dev_addr = dev_addr,
1193 		.mode = I2C_MODE_MASTER,
1194 		.timeout_ms = timeout_ms,
1195 	};
1196 
1197 	return do_write(hi2c, &request, p_data, size);
1198 }
1199 
1200 int stm32_i2c_read_write_membyte(struct i2c_handle_s *hi2c, uint16_t dev_addr,
1201 				 unsigned int mem_addr, uint8_t *p_data,
1202 				 bool write)
1203 {
1204 	uint64_t timeout_ref = 0;
1205 	uintptr_t base = get_base(hi2c);
1206 	int rc = -1;
1207 	uint8_t *p_buff = p_data;
1208 	uint32_t event_mask = 0;
1209 
1210 	if (hi2c->i2c_state != I2C_STATE_READY || !p_data)
1211 		return -1;
1212 
1213 	clk_enable(hi2c->clock);
1214 
1215 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_US);
1216 	if (wait_isr_event(hi2c, I2C_ISR_BUSY, 0, timeout_ref))
1217 		goto bail;
1218 
1219 	hi2c->i2c_state = write ? I2C_STATE_BUSY_TX : I2C_STATE_BUSY_RX;
1220 	hi2c->i2c_err = I2C_ERROR_NONE;
1221 
1222 	i2c_transfer_config(hi2c, dev_addr, I2C_MEMADD_SIZE_8BIT,
1223 			    write ? I2C_RELOAD_MODE : I2C_SOFTEND_MODE,
1224 			    I2C_GENERATE_START_WRITE);
1225 
1226 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_US);
1227 	if (i2c_wait_txis(hi2c, timeout_ref))
1228 		goto bail;
1229 
1230 	io_write8(base + I2C_TXDR, mem_addr);
1231 
1232 	if (write)
1233 		event_mask = I2C_ISR_TCR;
1234 	else
1235 		event_mask = I2C_ISR_TC;
1236 
1237 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_US);
1238 	if (wait_isr_event(hi2c, event_mask, 1, timeout_ref))
1239 		goto bail;
1240 
1241 	i2c_transfer_config(hi2c, dev_addr, I2C_MEMADD_SIZE_8BIT,
1242 			    I2C_AUTOEND_MODE,
1243 			    write ? I2C_NO_STARTSTOP : I2C_GENERATE_START_READ);
1244 
1245 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_US);
1246 	if (write) {
1247 		if (i2c_wait_txis(hi2c, timeout_ref))
1248 			goto bail;
1249 
1250 		io_write8(base + I2C_TXDR, *p_buff);
1251 	} else {
1252 		if (wait_isr_event(hi2c, I2C_ISR_RXNE, 1, timeout_ref))
1253 			goto bail;
1254 
1255 		*p_buff = io_read8(base + I2C_RXDR);
1256 	}
1257 
1258 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_US);
1259 	if (i2c_wait_stop(hi2c, timeout_ref))
1260 		goto bail;
1261 
1262 	io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1263 	io_clrbits32(base + I2C_CR2, CR2_RESET_MASK);
1264 
1265 	hi2c->i2c_state = I2C_STATE_READY;
1266 
1267 	rc = 0;
1268 
1269 bail:
1270 	clk_disable(hi2c->clock);
1271 
1272 	return rc;
1273 }
1274 
1275 /*
1276  * Read an amount of data in blocking mode
1277  *
1278  * @hi2c: Reference to struct i2c_handle_s
1279  * @request: I2C request parameters
1280  * @p_data: Pointer to data buffer
1281  * @size: Amount of data to be sent
1282  * Return 0 on success or a negative value
1283  */
1284 static int do_read(struct i2c_handle_s *hi2c, struct i2c_request *request,
1285 		   uint8_t *p_data, uint32_t size)
1286 {
1287 	vaddr_t base = get_base(hi2c);
1288 	uint64_t timeout_ref = 0;
1289 	int rc = -1;
1290 	uint8_t *p_buff = p_data;
1291 	size_t xfer_count = size;
1292 	size_t xfer_size = 0;
1293 
1294 	if (request->mode != I2C_MODE_MASTER && request->mode != I2C_MODE_MEM)
1295 		return -1;
1296 
1297 	if (hi2c->i2c_state != I2C_STATE_READY)
1298 		return -1;
1299 
1300 	if (!p_data || !size)
1301 		return -1;
1302 
1303 	clk_enable(hi2c->clock);
1304 
1305 	timeout_ref = timeout_init_us(I2C_TIMEOUT_BUSY_MS * 1000);
1306 	if (wait_isr_event(hi2c, I2C_ISR_BUSY, 0, timeout_ref))
1307 		goto bail;
1308 
1309 	hi2c->i2c_state = I2C_STATE_BUSY_RX;
1310 	hi2c->i2c_err = I2C_ERROR_NONE;
1311 	timeout_ref = timeout_init_us(request->timeout_ms * 1000);
1312 
1313 	if (request->mode == I2C_MODE_MEM) {
1314 		/* Send memory address */
1315 		if (i2c_request_mem_read(hi2c, request, timeout_ref))
1316 			goto bail;
1317 	}
1318 
1319 	/*
1320 	 * Send slave address.
1321 	 * Set NBYTES to write and reload if xfer_count > MAX_NBYTE_SIZE
1322 	 * and generate RESTART.
1323 	 */
1324 	if (xfer_count > MAX_NBYTE_SIZE) {
1325 		xfer_size = MAX_NBYTE_SIZE;
1326 		i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1327 				    I2C_RELOAD_MODE, I2C_GENERATE_START_READ);
1328 	} else {
1329 		xfer_size = xfer_count;
1330 		i2c_transfer_config(hi2c, request->dev_addr, xfer_size,
1331 				    I2C_AUTOEND_MODE, I2C_GENERATE_START_READ);
1332 	}
1333 
1334 	do {
1335 		if (wait_isr_event(hi2c, I2C_ISR_RXNE, 1,
1336 				   timeout_init_us(I2C_TIMEOUT_RXNE_MS * 1000)))
1337 			goto bail;
1338 
1339 		*p_buff = io_read8(base + I2C_RXDR);
1340 		p_buff++;
1341 		xfer_size--;
1342 		xfer_count--;
1343 
1344 		if (xfer_count && !xfer_size) {
1345 			if (wait_isr_event(hi2c, I2C_ISR_TCR, 1, timeout_ref))
1346 				goto bail;
1347 
1348 			if (xfer_count > MAX_NBYTE_SIZE) {
1349 				xfer_size = MAX_NBYTE_SIZE;
1350 				i2c_transfer_config(hi2c, request->dev_addr,
1351 						    xfer_size,
1352 						    I2C_RELOAD_MODE,
1353 						    I2C_NO_STARTSTOP);
1354 			} else {
1355 				xfer_size = xfer_count;
1356 				i2c_transfer_config(hi2c, request->dev_addr,
1357 						    xfer_size,
1358 						    I2C_AUTOEND_MODE,
1359 						    I2C_NO_STARTSTOP);
1360 			}
1361 		}
1362 	} while (xfer_count > 0U);
1363 
1364 	/*
1365 	 * No need to Check TC flag, with AUTOEND mode the stop
1366 	 * is automatically generated.
1367 	 * Wait until STOPF flag is reset.
1368 	 */
1369 	if (i2c_wait_stop(hi2c, timeout_ref))
1370 		goto bail;
1371 
1372 	/* Clear the NACK generated at the end of the transfer */
1373 	if ((io_read32(get_base(hi2c) + I2C_ISR) & I2C_ISR_NACKF))
1374 		io_write32(get_base(hi2c) + I2C_ICR, I2C_ICR_NACKCF);
1375 
1376 	io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1377 
1378 	io_clrbits32(base + I2C_CR2, CR2_RESET_MASK);
1379 
1380 	hi2c->i2c_state = I2C_STATE_READY;
1381 
1382 	rc = 0;
1383 
1384 bail:
1385 	clk_disable(hi2c->clock);
1386 
1387 	return rc;
1388 }
1389 
1390 int stm32_i2c_mem_read(struct i2c_handle_s *hi2c, uint32_t dev_addr,
1391 		       uint32_t mem_addr, uint32_t mem_addr_size,
1392 		       uint8_t *p_data, size_t size, unsigned int timeout_ms)
1393 {
1394 	struct i2c_request request = {
1395 		.dev_addr = dev_addr,
1396 		.mode = I2C_MODE_MEM,
1397 		.mem_addr = mem_addr,
1398 		.mem_addr_size = mem_addr_size,
1399 		.timeout_ms = timeout_ms,
1400 	};
1401 
1402 	return do_read(hi2c, &request, p_data, size);
1403 }
1404 
1405 int stm32_i2c_master_receive(struct i2c_handle_s *hi2c, uint32_t dev_addr,
1406 			     uint8_t *p_data, size_t size,
1407 			     unsigned int timeout_ms)
1408 {
1409 	struct i2c_request request = {
1410 		.dev_addr = dev_addr,
1411 		.mode = I2C_MODE_MASTER,
1412 		.timeout_ms = timeout_ms,
1413 	};
1414 
1415 	return do_read(hi2c, &request, p_data, size);
1416 }
1417 
1418 static struct i2c_handle_s *stm32_i2c_dev_to_handle(struct i2c_dev *i2c_dev)
1419 {
1420 	struct stm32_i2c_dev *dev = container_of(i2c_dev, struct stm32_i2c_dev,
1421 						 i2c_dev);
1422 
1423 	return dev->handle;
1424 }
1425 
1426 static TEE_Result stm32_i2c_read_data(struct i2c_dev *i2c_dev, uint8_t *buf,
1427 				      size_t len)
1428 {
1429 	struct i2c_handle_s *i2c_handle = stm32_i2c_dev_to_handle(i2c_dev);
1430 	int rc = 0;
1431 
1432 	rc = stm32_i2c_master_receive(i2c_handle, i2c_dev->addr, buf, len,
1433 				      I2C_TIMEOUT_DEFAULT_MS);
1434 	if (!rc)
1435 		return TEE_SUCCESS;
1436 	else
1437 		return TEE_ERROR_GENERIC;
1438 }
1439 
1440 static TEE_Result stm32_i2c_write_data(struct i2c_dev *i2c_dev,
1441 				       const uint8_t *buf, size_t len)
1442 {
1443 	struct i2c_handle_s *i2c_handle = stm32_i2c_dev_to_handle(i2c_dev);
1444 	uint8_t *buf2 = (uint8_t *)buf;
1445 	int rc = 0;
1446 
1447 	rc = stm32_i2c_master_transmit(i2c_handle, i2c_dev->addr, buf2, len,
1448 				       I2C_TIMEOUT_DEFAULT_MS);
1449 	if (!rc)
1450 		return TEE_SUCCESS;
1451 	else
1452 		return TEE_ERROR_GENERIC;
1453 }
1454 
1455 static const struct i2c_ctrl_ops stm32_i2c_ops = {
1456 	.read = stm32_i2c_read_data,
1457 	.write = stm32_i2c_write_data,
1458 };
1459 
1460 bool stm32_i2c_is_device_ready(struct i2c_handle_s *hi2c, uint32_t dev_addr,
1461 			       unsigned int trials, unsigned int timeout_ms)
1462 {
1463 	vaddr_t base = get_base(hi2c);
1464 	unsigned int i2c_trials = 0U;
1465 	bool rc = false;
1466 
1467 	if (hi2c->i2c_state != I2C_STATE_READY)
1468 		return rc;
1469 
1470 	clk_enable(hi2c->clock);
1471 
1472 	if (io_read32(base + I2C_ISR) & I2C_ISR_BUSY)
1473 		goto bail;
1474 
1475 	hi2c->i2c_state = I2C_STATE_BUSY;
1476 	hi2c->i2c_err = I2C_ERROR_NONE;
1477 
1478 	do {
1479 		uint64_t timeout_ref = 0;
1480 		vaddr_t isr = base + I2C_ISR;
1481 
1482 		/* Generate Start */
1483 		if ((io_read32(base + I2C_OAR1) & I2C_OAR1_OA1MODE) == 0)
1484 			io_write32(base + I2C_CR2,
1485 				   ((dev_addr & I2C_CR2_SADD) |
1486 				    I2C_CR2_START | I2C_CR2_AUTOEND) &
1487 				   ~I2C_CR2_RD_WRN);
1488 		else
1489 			io_write32(base + I2C_CR2,
1490 				   ((dev_addr & I2C_CR2_SADD) |
1491 				    I2C_CR2_START | I2C_CR2_ADD10) &
1492 				   ~I2C_CR2_RD_WRN);
1493 
1494 		/*
1495 		 * No need to Check TC flag, with AUTOEND mode the stop
1496 		 * is automatically generated.
1497 		 * Wait until STOPF flag is set or a NACK flag is set.
1498 		 */
1499 		timeout_ref = timeout_init_us(timeout_ms * 1000);
1500 		while (!timeout_elapsed(timeout_ref))
1501 			if (io_read32(isr) & (I2C_ISR_STOPF | I2C_ISR_NACKF))
1502 				break;
1503 
1504 		if ((io_read32(isr) & (I2C_ISR_STOPF | I2C_ISR_NACKF)) == 0) {
1505 			notif_i2c_timeout(hi2c);
1506 			goto bail;
1507 		}
1508 
1509 		if ((io_read32(base + I2C_ISR) & I2C_ISR_NACKF) == 0U) {
1510 			if (wait_isr_event(hi2c, I2C_ISR_STOPF, 1, timeout_ref))
1511 				goto bail;
1512 
1513 			io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1514 
1515 			hi2c->i2c_state = I2C_STATE_READY;
1516 
1517 			rc = true;
1518 			goto bail;
1519 		}
1520 
1521 		if (wait_isr_event(hi2c, I2C_ISR_STOPF, 1, timeout_ref))
1522 			goto bail;
1523 
1524 		io_write32(base + I2C_ICR, I2C_ISR_NACKF);
1525 		io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1526 
1527 		if (i2c_trials == trials) {
1528 			io_setbits32(base + I2C_CR2, I2C_CR2_STOP);
1529 
1530 			if (wait_isr_event(hi2c, I2C_ISR_STOPF, 1, timeout_ref))
1531 				goto bail;
1532 
1533 			io_write32(base + I2C_ICR, I2C_ISR_STOPF);
1534 		}
1535 
1536 		i2c_trials++;
1537 	} while (i2c_trials < trials);
1538 
1539 	notif_i2c_timeout(hi2c);
1540 
1541 bail:
1542 	clk_disable(hi2c->clock);
1543 
1544 	return rc;
1545 }
1546 
1547 void stm32_i2c_resume(struct i2c_handle_s *hi2c)
1548 {
1549 	if (hi2c->i2c_state == I2C_STATE_READY)
1550 		return;
1551 
1552 	if ((hi2c->i2c_state != I2C_STATE_RESET) &&
1553 	    (hi2c->i2c_state != I2C_STATE_SUSPENDED))
1554 		panic();
1555 
1556 	if (pinctrl_apply_state(hi2c->pinctrl))
1557 		panic();
1558 
1559 	if (hi2c->i2c_state == I2C_STATE_RESET) {
1560 		/* There is no valid I2C configuration to be loaded yet */
1561 		return;
1562 	}
1563 
1564 	restore_cfg(hi2c, &hi2c->sec_cfg);
1565 
1566 	if (IS_ENABLED(CFG_STM32MP13))
1567 		stm32_pinctrl_set_secure_cfg(hi2c->pinctrl, true);
1568 
1569 	hi2c->i2c_state = I2C_STATE_READY;
1570 }
1571 
1572 void stm32_i2c_suspend(struct i2c_handle_s *hi2c)
1573 {
1574 	if (hi2c->i2c_state == I2C_STATE_SUSPENDED)
1575 		return;
1576 
1577 	if (hi2c->i2c_state != I2C_STATE_READY)
1578 		panic();
1579 
1580 	save_cfg(hi2c, &hi2c->sec_cfg);
1581 
1582 	if (hi2c->pinctrl_sleep && pinctrl_apply_state(hi2c->pinctrl_sleep))
1583 		panic();
1584 
1585 	hi2c->i2c_state = I2C_STATE_SUSPENDED;
1586 }
1587 
1588 static TEE_Result stm32_get_i2c_dev(struct dt_pargs *args, void *data,
1589 				    struct i2c_dev **out_device)
1590 {
1591 	struct stm32_i2c_dev *stm32_i2c_dev = NULL;
1592 	paddr_t addr = 0;
1593 
1594 	addr = fdt_reg_base_address(args->fdt, args->phandle_node);
1595 	if (addr == DT_INFO_INVALID_REG) {
1596 		DMSG("Can't get device I2C address");
1597 		return TEE_ERROR_GENERIC;
1598 	}
1599 
1600 	stm32_i2c_dev = calloc(1, sizeof(*stm32_i2c_dev));
1601 	if (!stm32_i2c_dev)
1602 		return TEE_ERROR_OUT_OF_MEMORY;
1603 
1604 	stm32_i2c_dev->handle = data;
1605 	stm32_i2c_dev->i2c_dev.addr = addr;
1606 	stm32_i2c_dev->i2c_ctrl.ops = &stm32_i2c_ops;
1607 	stm32_i2c_dev->i2c_dev.ctrl = &stm32_i2c_dev->i2c_ctrl;
1608 
1609 	*out_device = &stm32_i2c_dev->i2c_dev;
1610 
1611 	return TEE_SUCCESS;
1612 }
1613 
1614 static TEE_Result stm32_i2c_probe(const void *fdt, int node,
1615 				  const void *compat_data __unused)
1616 {
1617 	TEE_Result res = TEE_SUCCESS;
1618 	int subnode = 0;
1619 	struct i2c_handle_s *i2c_handle_p = NULL;
1620 	struct stm32_i2c_init_s init_data = { };
1621 	struct pinctrl_state *pinctrl_active = NULL;
1622 	struct pinctrl_state *pinctrl_idle = NULL;
1623 
1624 	res = stm32_i2c_get_setup_from_fdt((void *)fdt, node, &init_data,
1625 					   &pinctrl_active, &pinctrl_idle);
1626 	if (res)
1627 		return res;
1628 
1629 	i2c_handle_p = calloc(1, sizeof(struct i2c_handle_s));
1630 	if (!i2c_handle_p)
1631 		return TEE_ERROR_OUT_OF_MEMORY;
1632 
1633 	i2c_handle_p->dt_status = init_data.dt_status;
1634 	i2c_handle_p->reg_size = init_data.reg_size;
1635 	i2c_handle_p->clock = init_data.clock;
1636 	i2c_handle_p->base.pa = init_data.pbase;
1637 	i2c_handle_p->base.va = io_pa_or_va(&i2c_handle_p->base,
1638 					    init_data.reg_size);
1639 	assert(i2c_handle_p->base.va);
1640 	i2c_handle_p->clock = init_data.clock;
1641 	i2c_handle_p->i2c_state = I2C_STATE_RESET;
1642 	i2c_handle_p->pinctrl = pinctrl_active;
1643 	i2c_handle_p->pinctrl_sleep = pinctrl_idle;
1644 
1645 	init_data.analog_filter = true;
1646 	init_data.digital_filter_coef = 0;
1647 
1648 	if (stm32_i2c_init(i2c_handle_p, &init_data))
1649 		panic("Couldn't initialise I2C");
1650 
1651 	res = i2c_register_provider(fdt, node, stm32_get_i2c_dev, i2c_handle_p);
1652 	if (res)
1653 		panic("Couldn't register I2C provider");
1654 
1655 	fdt_for_each_subnode(subnode, fdt, node) {
1656 		res = dt_driver_maybe_add_probe_node(fdt, subnode);
1657 		if (res) {
1658 			EMSG("Failed on node %s with %#"PRIx32,
1659 			     fdt_get_name(fdt, subnode, NULL), res);
1660 			panic();
1661 		}
1662 	}
1663 
1664 	return res;
1665 }
1666 
1667 static const struct dt_device_match stm32_i2c_match_table[] = {
1668 	{ .compatible = "st,stm32mp15-i2c" },
1669 	{ .compatible = "st,stm32mp13-i2c" },
1670 	{ .compatible = "st,stm32mp15-i2c-non-secure" },
1671 	{ }
1672 };
1673 
1674 DEFINE_DT_DRIVER(stm32_i2c_dt_driver) = {
1675 	.name = "stm32_i2c",
1676 	.match_table = stm32_i2c_match_table,
1677 	.probe = stm32_i2c_probe,
1678 	.type = DT_DRIVER_I2C
1679 };
1680