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