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