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