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