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