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