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