1 /*
2  * Copyright (c) 2017 Intel Corporation
3  * Copyright (c) 2021 Espressif Systems (Shanghai) Co., Ltd.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #define DT_DRV_COMPAT espressif_esp32_i2c
9 
10 /* Include esp-idf headers first to avoid redefining BIT() macro */
11 #include <esp32/rom/gpio.h>
12 #include <soc/gpio_sig_map.h>
13 #include <hal/i2c_ll.h>
14 #include <hal/i2c_hal.h>
15 #include <hal/gpio_hal.h>
16 #include <clk_ctrl_os.h>
17 
18 #include <soc.h>
19 #include <errno.h>
20 #include <zephyr/drivers/gpio.h>
21 #include <zephyr/drivers/pinctrl.h>
22 #include <zephyr/drivers/i2c.h>
23 #include <zephyr/drivers/interrupt_controller/intc_esp32.h>
24 #include <zephyr/drivers/clock_control.h>
25 #include <zephyr/sys/util.h>
26 #include <string.h>
27 
28 #include <zephyr/logging/log.h>
29 LOG_MODULE_REGISTER(i2c_esp32, CONFIG_I2C_LOG_LEVEL);
30 
31 #include "i2c-priv.h"
32 
33 #define I2C_FILTER_CYC_NUM_DEF 7	/* Number of apb cycles filtered by default */
34 #define I2C_CLR_BUS_SCL_NUM 9		/* Number of SCL clocks to restore SDA signal */
35 #define I2C_CLR_BUS_HALF_PERIOD_US 5	/* Period of SCL clock to restore SDA signal */
36 #define I2C_TRANSFER_TIMEOUT_MSEC 500	/* Transfer timeout period */
37 
38 /* Freq limitation when using different clock sources */
39 #define I2C_CLK_LIMIT_REF_TICK (1 * 1000 * 1000 / 20)	/* REF_TICK, no more than REF_TICK/20*/
40 #define I2C_CLK_LIMIT_APB (80 * 1000 * 1000 / 20)	/* Limited by APB, no more than APB/20 */
41 #define I2C_CLK_LIMIT_RTC (20 * 1000 * 1000 / 20)	/* Limited by RTC, no more than RTC/20 */
42 #define I2C_CLK_LIMIT_XTAL (40 * 1000 * 1000 / 20)	/* Limited by RTC, no more than XTAL/20 */
43 
44 #define I2C_CLOCK_INVALID                 (-1)
45 
46 enum i2c_status_t {
47 	I2C_STATUS_READ,	/* read status for current master command */
48 	I2C_STATUS_WRITE,	/* write status for current master command */
49 	I2C_STATUS_IDLE,	/* idle status for current master command */
50 	I2C_STATUS_ACK_ERROR,	/* ack error status for current master command */
51 	I2C_STATUS_DONE,	/* I2C command done */
52 	I2C_STATUS_TIMEOUT,	/* I2C bus status error, and operation timeout */
53 };
54 
55 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
56 struct i2c_esp32_pin {
57 	struct gpio_dt_spec gpio;
58 	int sig_out;
59 	int sig_in;
60 };
61 #endif
62 
63 struct i2c_esp32_data {
64 	i2c_hal_context_t hal;
65 	struct k_sem cmd_sem;
66 	struct k_sem transfer_sem;
67 	volatile enum i2c_status_t status;
68 	uint32_t dev_config;
69 	int cmd_idx;
70 	int irq_line;
71 };
72 
73 typedef void (*irq_connect_cb)(void);
74 
75 struct i2c_esp32_config {
76 	int index;
77 
78 	const struct device *clock_dev;
79 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
80 	const struct i2c_esp32_pin scl;
81 	const struct i2c_esp32_pin sda;
82 #endif
83 	const struct pinctrl_dev_config *pcfg;
84 
85 	const clock_control_subsys_t clock_subsys;
86 
87 	const struct {
88 		bool tx_lsb_first;
89 		bool rx_lsb_first;
90 	} mode;
91 
92 	int irq_source;
93 
94 	const uint32_t bitrate;
95 	const uint32_t scl_timeout;
96 };
97 
i2c_get_src_clk_freq(i2c_clock_source_t clk_src)98 static uint32_t i2c_get_src_clk_freq(i2c_clock_source_t clk_src)
99 {
100 	uint32_t periph_src_clk_hz = 0;
101 
102 	switch (clk_src) {
103 #if SOC_I2C_SUPPORT_APB
104 	case I2C_CLK_SRC_APB:
105 		periph_src_clk_hz = esp_clk_apb_freq();
106 		break;
107 #endif
108 #if SOC_I2C_SUPPORT_XTAL
109 	case I2C_CLK_SRC_XTAL:
110 		periph_src_clk_hz = esp_clk_xtal_freq();
111 		break;
112 #endif
113 #if SOC_I2C_SUPPORT_RTC
114 	case I2C_CLK_SRC_RC_FAST:
115 		periph_rtc_dig_clk8m_enable();
116 		periph_src_clk_hz = periph_rtc_dig_clk8m_get_freq();
117 		break;
118 #endif
119 #if SOC_I2C_SUPPORT_REF_TICK
120 	case RMT_CLK_SRC_REF_TICK:
121 		periph_src_clk_hz = REF_CLK_FREQ;
122 		break;
123 #endif
124 	default:
125 		LOG_ERR("clock source %d is not supported", clk_src);
126 		break;
127 	}
128 
129 	return periph_src_clk_hz;
130 }
131 
i2c_get_clk_src(uint32_t clk_freq)132 static i2c_clock_source_t i2c_get_clk_src(uint32_t clk_freq)
133 {
134 	i2c_clock_source_t clk_srcs[] = SOC_I2C_CLKS;
135 
136 	for (size_t i = 0; i < ARRAY_SIZE(clk_srcs); i++) {
137 		/* I2C SCL clock frequency should not larger than clock source frequency/20 */
138 		if (clk_freq <= (i2c_get_src_clk_freq(clk_srcs[i]) / 20)) {
139 			return clk_srcs[i];
140 		}
141 	}
142 
143 	return I2C_CLOCK_INVALID;
144 }
145 
146 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
i2c_esp32_config_pin(const struct device * dev)147 static int i2c_esp32_config_pin(const struct device *dev)
148 {
149 	const struct i2c_esp32_config *config = dev->config;
150 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
151 	int ret = 0;
152 
153 	if (config->index >= SOC_I2C_NUM) {
154 		LOG_ERR("Invalid I2C peripheral number");
155 		return -EINVAL;
156 	}
157 
158 	gpio_pin_set_dt(&config->sda.gpio, 1);
159 	ret = gpio_pin_configure_dt(&config->sda.gpio, GPIO_PULL_UP | GPIO_OUTPUT | GPIO_INPUT);
160 	esp_rom_gpio_matrix_out(config->sda.gpio.pin, config->sda.sig_out, 0, 0);
161 	esp_rom_gpio_matrix_in(config->sda.gpio.pin, config->sda.sig_in, 0);
162 
163 	gpio_pin_set_dt(&config->scl.gpio, 1);
164 	ret |= gpio_pin_configure_dt(&config->scl.gpio, GPIO_PULL_UP | GPIO_OUTPUT | GPIO_INPUT);
165 	esp_rom_gpio_matrix_out(config->scl.gpio.pin, config->scl.sig_out, 0, 0);
166 	esp_rom_gpio_matrix_in(config->scl.gpio.pin, config->scl.sig_in, 0);
167 
168 	return ret;
169 }
170 #endif
171 
172 /* Some slave device will die by accident and keep the SDA in low level,
173  * in this case, master should send several clock to make the slave release the bus.
174  * Slave mode of ESP32 might also get in wrong state that held the SDA low,
175  * in this case, master device could send a stop signal to make esp32 slave release the bus.
176  **/
i2c_master_clear_bus(const struct device * dev)177 static void IRAM_ATTR i2c_master_clear_bus(const struct device *dev)
178 {
179 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
180 
181 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
182 	const struct i2c_esp32_config *config = dev->config;
183 	const int scl_half_period = I2C_CLR_BUS_HALF_PERIOD_US; /* use standard 100kHz data rate */
184 	int i = 0;
185 
186 	gpio_pin_configure_dt(&config->scl.gpio, GPIO_OUTPUT);
187 	gpio_pin_configure_dt(&config->sda.gpio, GPIO_OUTPUT | GPIO_INPUT);
188 	/* If a SLAVE device was in a read operation when the bus was interrupted, */
189 	/* the SLAVE device is controlling SDA. If the slave is sending a stream of ZERO bytes, */
190 	/* it will only release SDA during the  ACK bit period. So, this reset code needs */
191 	/* to synchronize the bit stream with either the ACK bit, or a 1 bit to correctly */
192 	/* generate a STOP condition. */
193 	gpio_pin_set_dt(&config->sda.gpio, 1);
194 	esp_rom_delay_us(scl_half_period);
195 	while (!gpio_pin_get_dt(&config->sda.gpio) && (i++ < I2C_CLR_BUS_SCL_NUM)) {
196 		gpio_pin_set_dt(&config->scl.gpio, 1);
197 		esp_rom_delay_us(scl_half_period);
198 		gpio_pin_set_dt(&config->scl.gpio, 0);
199 		esp_rom_delay_us(scl_half_period);
200 	}
201 	gpio_pin_set_dt(&config->sda.gpio, 0); /* setup for STOP */
202 	gpio_pin_set_dt(&config->scl.gpio, 1);
203 	esp_rom_delay_us(scl_half_period);
204 	gpio_pin_set_dt(&config->sda.gpio, 1); /* STOP, SDA low -> high while SCL is HIGH */
205 	i2c_esp32_config_pin(dev);
206 #else
207 	i2c_ll_master_clr_bus(data->hal.dev);
208 #endif
209 	i2c_ll_update(data->hal.dev);
210 }
211 
i2c_hw_fsm_reset(const struct device * dev)212 static void IRAM_ATTR i2c_hw_fsm_reset(const struct device *dev)
213 {
214 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
215 
216 #ifndef SOC_I2C_SUPPORT_HW_FSM_RST
217 	const struct i2c_esp32_config *config = dev->config;
218 	int scl_low_period, scl_high_period;
219 	int scl_start_hold, scl_rstart_setup;
220 	int scl_stop_hold, scl_stop_setup;
221 	int sda_hold, sda_sample;
222 	int timeout;
223 	uint8_t filter_cfg;
224 
225 	i2c_ll_get_scl_timing(data->hal.dev, &scl_high_period, &scl_low_period);
226 	i2c_ll_get_start_timing(data->hal.dev, &scl_rstart_setup, &scl_start_hold);
227 	i2c_ll_get_stop_timing(data->hal.dev, &scl_stop_setup, &scl_stop_hold);
228 	i2c_ll_get_sda_timing(data->hal.dev, &sda_sample, &sda_hold);
229 	i2c_ll_get_tout(data->hal.dev, &timeout);
230 	i2c_ll_get_filter(data->hal.dev, &filter_cfg);
231 
232 	/* to reset the I2C hw module, we need re-enable the hw */
233 	clock_control_off(config->clock_dev, config->clock_subsys);
234 	i2c_master_clear_bus(dev);
235 	clock_control_on(config->clock_dev, config->clock_subsys);
236 
237 	i2c_hal_master_init(&data->hal);
238 	i2c_ll_disable_intr_mask(data->hal.dev, I2C_LL_INTR_MASK);
239 	i2c_ll_clear_intr_mask(data->hal.dev, I2C_LL_INTR_MASK);
240 	i2c_ll_set_scl_timing(data->hal.dev, scl_high_period, scl_low_period);
241 	i2c_ll_set_start_timing(data->hal.dev, scl_rstart_setup, scl_start_hold);
242 	i2c_ll_set_stop_timing(data->hal.dev, scl_stop_setup, scl_stop_hold);
243 	i2c_ll_set_sda_timing(data->hal.dev, sda_sample, sda_hold);
244 	i2c_ll_set_tout(data->hal.dev, timeout);
245 	i2c_ll_set_filter(data->hal.dev, filter_cfg);
246 #else
247 	i2c_ll_master_fsm_rst(data->hal.dev);
248 	i2c_master_clear_bus(dev);
249 #endif
250 	i2c_ll_update(data->hal.dev);
251 }
252 
i2c_esp32_recover(const struct device * dev)253 static int i2c_esp32_recover(const struct device *dev)
254 {
255 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
256 
257 	k_sem_take(&data->transfer_sem, K_FOREVER);
258 	i2c_hw_fsm_reset(dev);
259 	k_sem_give(&data->transfer_sem);
260 
261 	return 0;
262 }
263 
i2c_esp32_configure_bitrate(const struct device * dev,uint32_t bitrate)264 static void IRAM_ATTR i2c_esp32_configure_bitrate(const struct device *dev, uint32_t bitrate)
265 {
266 	const struct i2c_esp32_config *config = dev->config;
267 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
268 
269 	i2c_clock_source_t sclk = i2c_get_clk_src(bitrate);
270 	uint32_t clk_freq_mhz = i2c_get_src_clk_freq(sclk);
271 
272 	i2c_hal_set_bus_timing(&data->hal, bitrate, sclk, clk_freq_mhz);
273 
274 	if (config->scl_timeout > 0) {
275 		uint32_t timeout_cycles = MIN(I2C_LL_MAX_TIMEOUT,
276 					      clk_freq_mhz / MHZ(1) * config->scl_timeout);
277 		i2c_ll_set_tout(data->hal.dev, timeout_cycles);
278 		LOG_DBG("SCL timeout: %d us, value: %d", config->scl_timeout, timeout_cycles);
279 	} else {
280 		/* Disabling the timeout by clearing the I2C_TIME_OUT_EN bit does not seem to work,
281 		 * at least for ESP32-C3 (tested with communication to bq76952 chip). So we set the
282 		 * timeout to maximum supported value instead.
283 		 */
284 		i2c_ll_set_tout(data->hal.dev, I2C_LL_MAX_TIMEOUT);
285 	}
286 
287 	i2c_ll_update(data->hal.dev);
288 }
289 
i2c_esp32_configure_data_mode(const struct device * dev)290 static void i2c_esp32_configure_data_mode(const struct device *dev)
291 {
292 	const struct i2c_esp32_config *config = dev->config;
293 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
294 
295 	i2c_trans_mode_t tx_mode = I2C_DATA_MODE_MSB_FIRST;
296 	i2c_trans_mode_t rx_mode = I2C_DATA_MODE_MSB_FIRST;
297 
298 	if (config->mode.tx_lsb_first) {
299 		tx_mode = I2C_DATA_MODE_LSB_FIRST;
300 	}
301 
302 	if (config->mode.rx_lsb_first) {
303 		rx_mode = I2C_DATA_MODE_LSB_FIRST;
304 	}
305 
306 	i2c_ll_set_data_mode(data->hal.dev, tx_mode, rx_mode);
307 	i2c_ll_set_filter(data->hal.dev, I2C_FILTER_CYC_NUM_DEF);
308 	i2c_ll_update(data->hal.dev);
309 
310 }
311 
i2c_esp32_configure(const struct device * dev,uint32_t dev_config)312 static int i2c_esp32_configure(const struct device *dev, uint32_t dev_config)
313 {
314 	const struct i2c_esp32_config *config = dev->config;
315 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
316 	uint32_t bitrate;
317 
318 	if (!(dev_config & I2C_MODE_CONTROLLER)) {
319 		LOG_ERR("Only I2C Master mode supported.");
320 		return -ENOTSUP;
321 	}
322 
323 	switch (I2C_SPEED_GET(dev_config)) {
324 	case I2C_SPEED_STANDARD:
325 		bitrate = KHZ(100);
326 		break;
327 	case I2C_SPEED_FAST:
328 		bitrate = KHZ(400);
329 		break;
330 	case I2C_SPEED_FAST_PLUS:
331 		bitrate = MHZ(1);
332 		break;
333 	default:
334 		LOG_ERR("Error configuring I2C speed.");
335 		return -ENOTSUP;
336 	}
337 
338 	k_sem_take(&data->transfer_sem, K_FOREVER);
339 
340 	data->dev_config = dev_config;
341 
342 	i2c_esp32_configure_bitrate(dev, bitrate);
343 
344 	k_sem_give(&data->transfer_sem);
345 
346 	return 0;
347 }
348 
i2c_esp32_get_config(const struct device * dev,uint32_t * config)349 static int i2c_esp32_get_config(const struct device *dev, uint32_t *config)
350 {
351 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
352 
353 	if (data->dev_config == 0) {
354 		LOG_ERR("I2C controller not configured");
355 		return -EIO;
356 	}
357 
358 	*config = data->dev_config;
359 
360 	return 0;
361 }
362 
i2c_esp32_reset_fifo(const struct device * dev)363 static void IRAM_ATTR i2c_esp32_reset_fifo(const struct device *dev)
364 {
365 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
366 
367 	/* reset fifo buffers */
368 	i2c_ll_txfifo_rst(data->hal.dev);
369 	i2c_ll_rxfifo_rst(data->hal.dev);
370 }
371 
i2c_esp32_transmit(const struct device * dev)372 static int IRAM_ATTR i2c_esp32_transmit(const struct device *dev)
373 {
374 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
375 	int ret = 0;
376 
377 	/* Start transmission*/
378 	i2c_ll_update(data->hal.dev);
379 	i2c_ll_trans_start(data->hal.dev);
380 	data->cmd_idx = 0;
381 
382 	ret = k_sem_take(&data->cmd_sem, K_MSEC(I2C_TRANSFER_TIMEOUT_MSEC));
383 	if (ret != 0) {
384 		/* If the I2C slave is powered off or the SDA/SCL is */
385 		/* connected to ground, for example, I2C hw FSM would get */
386 		/* stuck in wrong state, we have to reset the I2C module in this case. */
387 		i2c_hw_fsm_reset(dev);
388 		return -ETIMEDOUT;
389 	}
390 
391 	if (data->status == I2C_STATUS_TIMEOUT) {
392 		i2c_hw_fsm_reset(dev);
393 		ret = -ETIMEDOUT;
394 	} else if (data->status == I2C_STATUS_ACK_ERROR) {
395 		ret = -EFAULT;
396 	}
397 
398 	return ret;
399 }
400 
i2c_esp32_master_start(const struct device * dev)401 static void IRAM_ATTR i2c_esp32_master_start(const struct device *dev)
402 {
403 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
404 
405 	i2c_ll_hw_cmd_t cmd = {
406 		.op_code = I2C_LL_CMD_RESTART
407 	};
408 
409 	i2c_ll_write_cmd_reg(data->hal.dev, cmd, data->cmd_idx++);
410 }
411 
i2c_esp32_master_stop(const struct device * dev)412 static void IRAM_ATTR i2c_esp32_master_stop(const struct device *dev)
413 {
414 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
415 
416 	i2c_ll_hw_cmd_t cmd = {
417 		.op_code = I2C_LL_CMD_STOP
418 	};
419 
420 	i2c_ll_write_cmd_reg(data->hal.dev, cmd, data->cmd_idx++);
421 }
422 
i2c_esp32_write_addr(const struct device * dev,uint16_t addr)423 static int IRAM_ATTR i2c_esp32_write_addr(const struct device *dev, uint16_t addr)
424 {
425 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
426 	uint8_t addr_len = 1;
427 	uint8_t addr_byte = addr & 0xFF;
428 
429 	data->status = I2C_STATUS_WRITE;
430 
431 	/* write address value in tx buffer */
432 	i2c_ll_write_txfifo(data->hal.dev, &addr_byte, 1);
433 	if (data->dev_config & I2C_ADDR_10_BITS) {
434 		addr_byte = (addr >> 8) & 0xFF;
435 		i2c_ll_write_txfifo(data->hal.dev, &addr_byte, 1);
436 		addr_len++;
437 	}
438 
439 	const i2c_ll_hw_cmd_t cmd_end = {
440 		.op_code = I2C_LL_CMD_END,
441 	};
442 
443 	i2c_ll_hw_cmd_t cmd = {
444 		.op_code = I2C_LL_CMD_WRITE,
445 		.ack_en = true,
446 		.byte_num = addr_len,
447 	};
448 
449 	i2c_ll_write_cmd_reg(data->hal.dev, cmd, data->cmd_idx++);
450 	i2c_ll_write_cmd_reg(data->hal.dev, cmd_end, data->cmd_idx++);
451 	i2c_ll_master_enable_tx_it(data->hal.dev);
452 
453 	return i2c_esp32_transmit(dev);
454 }
455 
i2c_esp32_master_read(const struct device * dev,struct i2c_msg * msg)456 static int IRAM_ATTR i2c_esp32_master_read(const struct device *dev, struct i2c_msg *msg)
457 {
458 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
459 
460 	uint32_t msg_len = msg->len;
461 	uint8_t *msg_buf = msg->buf;
462 	uint8_t rd_filled = 0;
463 	int ret = 0;
464 
465 	data->status = I2C_STATUS_READ;
466 
467 	i2c_ll_hw_cmd_t cmd = {
468 		.op_code = I2C_LL_CMD_READ,
469 	};
470 	const i2c_ll_hw_cmd_t cmd_end = {
471 		.op_code = I2C_LL_CMD_END,
472 	};
473 
474 	while (msg_len) {
475 		rd_filled = (msg_len > SOC_I2C_FIFO_LEN) ? SOC_I2C_FIFO_LEN : (msg_len - 1);
476 
477 		/* I2C master won't acknowledge the last byte read from the
478 		 * slave device. Divide the read command in two segments as
479 		 * recommended by the ESP32 Technical Reference Manual.
480 		 */
481 		if (msg_len == 1) {
482 			rd_filled = 1;
483 			cmd.ack_val = 1;
484 		} else {
485 			cmd.ack_val = 0;
486 		}
487 		cmd.byte_num = rd_filled;
488 
489 		i2c_ll_write_cmd_reg(data->hal.dev, cmd, data->cmd_idx++);
490 		i2c_ll_write_cmd_reg(data->hal.dev, cmd_end, data->cmd_idx++);
491 		i2c_ll_master_enable_tx_it(data->hal.dev);
492 		ret = i2c_esp32_transmit(dev);
493 		if (ret < 0) {
494 			return ret;
495 		}
496 
497 		i2c_ll_read_rxfifo(data->hal.dev, msg_buf, rd_filled);
498 		msg_buf += rd_filled;
499 		msg_len -= rd_filled;
500 	}
501 
502 	return 0;
503 }
504 
i2c_esp32_read_msg(const struct device * dev,struct i2c_msg * msg,uint16_t addr)505 static int IRAM_ATTR i2c_esp32_read_msg(const struct device *dev,
506 					struct i2c_msg *msg, uint16_t addr)
507 {
508 	int ret = 0;
509 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
510 
511 	/* Set the R/W bit to R */
512 	addr |= BIT(0);
513 
514 	if (msg->flags & I2C_MSG_RESTART) {
515 		i2c_esp32_master_start(dev);
516 		ret = i2c_esp32_write_addr(dev, addr);
517 		if (ret < 0) {
518 			LOG_ERR("I2C transfer error: %d", ret);
519 			return ret;
520 		}
521 	}
522 
523 	ret = i2c_esp32_master_read(dev, msg);
524 	if (ret < 0) {
525 		LOG_ERR("I2C transfer error: %d", ret);
526 		return ret;
527 	}
528 
529 	if (msg->flags & I2C_MSG_STOP) {
530 		i2c_esp32_master_stop(dev);
531 		ret = i2c_esp32_transmit(dev);
532 		if (ret < 0) {
533 			LOG_ERR("I2C transfer error: %d", ret);
534 			return ret;
535 		}
536 	}
537 
538 	return 0;
539 }
540 
i2c_esp32_master_write(const struct device * dev,struct i2c_msg * msg)541 static int IRAM_ATTR i2c_esp32_master_write(const struct device *dev, struct i2c_msg *msg)
542 {
543 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
544 	uint8_t wr_filled = 0;
545 	uint32_t msg_len = msg->len;
546 	uint8_t *msg_buf = msg->buf;
547 	int ret = 0;
548 
549 	data->status = I2C_STATUS_WRITE;
550 
551 	i2c_ll_hw_cmd_t cmd = {
552 		.op_code = I2C_LL_CMD_WRITE,
553 		.ack_en = true,
554 	};
555 
556 	const i2c_ll_hw_cmd_t cmd_end = {
557 		.op_code = I2C_LL_CMD_END,
558 	};
559 
560 	while (msg_len) {
561 		wr_filled = (msg_len > SOC_I2C_FIFO_LEN) ? SOC_I2C_FIFO_LEN : msg_len;
562 		cmd.byte_num = wr_filled;
563 
564 		if (wr_filled > 0) {
565 			i2c_ll_write_txfifo(data->hal.dev, msg_buf, wr_filled);
566 			i2c_ll_write_cmd_reg(data->hal.dev, cmd, data->cmd_idx++);
567 			i2c_ll_write_cmd_reg(data->hal.dev, cmd_end, data->cmd_idx++);
568 			i2c_ll_master_enable_tx_it(data->hal.dev);
569 			ret = i2c_esp32_transmit(dev);
570 			if (ret < 0) {
571 				return ret;
572 			}
573 		}
574 
575 		msg_buf += wr_filled;
576 		msg_len -= wr_filled;
577 	}
578 
579 	return 0;
580 }
581 
i2c_esp32_write_msg(const struct device * dev,struct i2c_msg * msg,uint16_t addr)582 static int IRAM_ATTR i2c_esp32_write_msg(const struct device *dev,
583 					 struct i2c_msg *msg, uint16_t addr)
584 {
585 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
586 	int ret = 0;
587 
588 	if (msg->flags & I2C_MSG_RESTART) {
589 		i2c_esp32_master_start(dev);
590 		ret = i2c_esp32_write_addr(dev, addr);
591 		if (ret < 0) {
592 			LOG_ERR("I2C transfer error: %d", ret);
593 			return ret;
594 		}
595 	}
596 
597 	ret = i2c_esp32_master_write(dev, msg);
598 	if (ret < 0) {
599 		LOG_ERR("I2C transfer error: %d", ret);
600 		return ret;
601 	}
602 
603 	if (msg->flags & I2C_MSG_STOP) {
604 		i2c_esp32_master_stop(dev);
605 		ret = i2c_esp32_transmit(dev);
606 		if (ret < 0) {
607 			LOG_ERR("I2C transfer error: %d", ret);
608 			return ret;
609 		}
610 	}
611 
612 	return 0;
613 }
614 
i2c_esp32_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)615 static int IRAM_ATTR i2c_esp32_transfer(const struct device *dev, struct i2c_msg *msgs,
616 					uint8_t num_msgs, uint16_t addr)
617 {
618 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
619 	struct i2c_msg *current, *next;
620 	uint32_t timeout = I2C_TRANSFER_TIMEOUT_MSEC * USEC_PER_MSEC;
621 	int ret = 0;
622 
623 	if (!num_msgs) {
624 		return 0;
625 	}
626 
627 	while (i2c_ll_is_bus_busy(data->hal.dev)) {
628 		k_busy_wait(1);
629 		if (timeout-- == 0) {
630 			return -EBUSY;
631 		}
632 	}
633 
634 	/* Check for validity of all messages before transfer */
635 	current = msgs;
636 
637 	/* Add restart flag on first message to send start event */
638 	current->flags |= I2C_MSG_RESTART;
639 
640 	for (int k = 1; k <= num_msgs; k++) {
641 		if (k < num_msgs) {
642 			next = current + 1;
643 
644 			/* messages of different direction require restart event */
645 			if ((current->flags & I2C_MSG_RW_MASK) != (next->flags & I2C_MSG_RW_MASK)) {
646 				if (!(next->flags & I2C_MSG_RESTART)) {
647 					ret = -EINVAL;
648 					break;
649 				}
650 			}
651 
652 			/* check if there is any stop event in the middle of the transaction */
653 			if (current->flags & I2C_MSG_STOP) {
654 				ret = -EINVAL;
655 				break;
656 			}
657 		}
658 
659 		current++;
660 	}
661 
662 	if (ret) {
663 		return ret;
664 	}
665 
666 	k_sem_take(&data->transfer_sem, K_FOREVER);
667 
668 	/* Mask out unused address bits, and make room for R/W bit */
669 	addr &= BIT_MASK(data->dev_config & I2C_ADDR_10_BITS ? 10 : 7);
670 	addr <<= 1;
671 
672 	for (; num_msgs > 0; num_msgs--, msgs++) {
673 
674 		if (data->status == I2C_STATUS_TIMEOUT || i2c_ll_is_bus_busy(data->hal.dev)) {
675 			i2c_hw_fsm_reset(dev);
676 		}
677 
678 		/* reset all fifo buffer before start */
679 		i2c_esp32_reset_fifo(dev);
680 
681 		/* These two interrupts some times can not be cleared when the FSM gets stuck. */
682 		/* So we disable them when these two interrupt occurs and re-enable them here. */
683 		i2c_ll_disable_intr_mask(data->hal.dev, I2C_LL_INTR_MASK);
684 		i2c_ll_clear_intr_mask(data->hal.dev, I2C_LL_INTR_MASK);
685 
686 		if ((msgs->flags & I2C_MSG_RW_MASK) == I2C_MSG_READ) {
687 			ret = i2c_esp32_read_msg(dev, msgs, addr);
688 		} else {
689 			ret = i2c_esp32_write_msg(dev, msgs, addr);
690 		}
691 
692 		if (ret < 0) {
693 			break;
694 		}
695 	}
696 
697 	k_sem_give(&data->transfer_sem);
698 
699 	return ret;
700 }
701 
i2c_esp32_isr(void * arg)702 static void IRAM_ATTR i2c_esp32_isr(void *arg)
703 {
704 	const struct device *dev = (const struct device *)arg;
705 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
706 	i2c_intr_event_t evt_type = I2C_INTR_EVENT_ERR;
707 
708 	if (data->status == I2C_STATUS_WRITE) {
709 		i2c_hal_master_handle_tx_event(&data->hal, &evt_type);
710 	} else if (data->status == I2C_STATUS_READ) {
711 		i2c_hal_master_handle_rx_event(&data->hal, &evt_type);
712 	}
713 
714 	if (evt_type == I2C_INTR_EVENT_NACK) {
715 		data->status = I2C_STATUS_ACK_ERROR;
716 	} else if (evt_type == I2C_INTR_EVENT_TOUT) {
717 		data->status = I2C_STATUS_TIMEOUT;
718 	} else if (evt_type == I2C_INTR_EVENT_ARBIT_LOST) {
719 		data->status = I2C_STATUS_TIMEOUT;
720 	} else if (evt_type == I2C_INTR_EVENT_TRANS_DONE) {
721 		data->status = I2C_STATUS_DONE;
722 	}
723 
724 	k_sem_give(&data->cmd_sem);
725 }
726 
727 static const struct i2c_driver_api i2c_esp32_driver_api = {
728 	.configure = i2c_esp32_configure,
729 	.get_config = i2c_esp32_get_config,
730 	.transfer = i2c_esp32_transfer,
731 	.recover_bus = i2c_esp32_recover
732 };
733 
i2c_esp32_init(const struct device * dev)734 static int IRAM_ATTR i2c_esp32_init(const struct device *dev)
735 {
736 	const struct i2c_esp32_config *config = dev->config;
737 	struct i2c_esp32_data *data = (struct i2c_esp32_data *const)(dev)->data;
738 
739 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
740 	if (!gpio_is_ready_dt(&config->scl.gpio)) {
741 		LOG_ERR("SCL GPIO device is not ready");
742 		return -EINVAL;
743 	}
744 
745 	if (!gpio_is_ready_dt(&config->sda.gpio)) {
746 		LOG_ERR("SDA GPIO device is not ready");
747 		return -EINVAL;
748 	}
749 #endif
750 	int ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
751 
752 	if (ret < 0) {
753 		LOG_ERR("Failed to configure I2C pins");
754 		return -EINVAL;
755 	}
756 
757 	if (!device_is_ready(config->clock_dev)) {
758 		LOG_ERR("clock control device not ready");
759 		return -ENODEV;
760 	}
761 
762 	clock_control_on(config->clock_dev, config->clock_subsys);
763 
764 	esp_intr_alloc(config->irq_source, 0, i2c_esp32_isr, (void *)dev, NULL);
765 
766 	i2c_hal_master_init(&data->hal);
767 
768 	i2c_esp32_configure_data_mode(dev);
769 
770 	return i2c_esp32_configure(dev, I2C_MODE_CONTROLLER | i2c_map_dt_bitrate(config->bitrate));
771 }
772 
773 #define I2C(idx) DT_NODELABEL(i2c##idx)
774 
775 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
776 #define I2C_ESP32_GET_PIN_INFO(idx)					\
777 	.scl = {							\
778 		.gpio = GPIO_DT_SPEC_GET(I2C(idx), scl_gpios),		\
779 		.sig_out = I2CEXT##idx##_SCL_OUT_IDX,			\
780 		.sig_in = I2CEXT##idx##_SCL_IN_IDX,			\
781 	},								\
782 	.sda = {							\
783 		.gpio = GPIO_DT_SPEC_GET(I2C(idx), sda_gpios),		\
784 		.sig_out = I2CEXT##idx##_SDA_OUT_IDX,			\
785 		.sig_in = I2CEXT##idx##_SDA_IN_IDX,			\
786 	},
787 #else
788 #define I2C_ESP32_GET_PIN_INFO(idx)
789 #endif /* SOC_I2C_SUPPORT_HW_CLR_BUS */
790 
791 #define I2C_ESP32_TIMEOUT(inst)						\
792 	COND_CODE_1(DT_INST_NODE_HAS_PROP(inst, scl_timeout_us),	\
793 		    (DT_INST_PROP(inst, scl_timeout_us)), (0))
794 
795 #define I2C_ESP32_FREQUENCY(bitrate)					\
796 	 (bitrate == I2C_BITRATE_STANDARD ? KHZ(100)			\
797 	: bitrate == I2C_BITRATE_FAST     ? KHZ(400)			\
798 	: bitrate == I2C_BITRATE_FAST_PLUS  ? MHZ(1) : 0)
799 
800 #define I2C_FREQUENCY(idx)						\
801 	I2C_ESP32_FREQUENCY(DT_PROP(I2C(idx), clock_frequency))
802 
803 #define ESP32_I2C_INIT(idx)									   \
804 												   \
805 	PINCTRL_DT_DEFINE(I2C(idx));								   \
806 												   \
807 	static struct i2c_esp32_data i2c_esp32_data_##idx = {					   \
808 		.hal = {									   \
809 			.dev = (i2c_dev_t *) DT_REG_ADDR(I2C(idx)),				   \
810 		},										   \
811 		.cmd_sem = Z_SEM_INITIALIZER(i2c_esp32_data_##idx.cmd_sem, 0, 1),		   \
812 		.transfer_sem = Z_SEM_INITIALIZER(i2c_esp32_data_##idx.transfer_sem, 1, 1),	   \
813 	};											   \
814 												   \
815 	static const struct i2c_esp32_config i2c_esp32_config_##idx = {				   \
816 		.index = idx,									   \
817 		.clock_dev = DEVICE_DT_GET(DT_CLOCKS_CTLR(I2C(idx))),				   \
818 		.pcfg = PINCTRL_DT_DEV_CONFIG_GET(I2C(idx)),					   \
819 		.clock_subsys = (clock_control_subsys_t)DT_CLOCKS_CELL(I2C(idx), offset),	   \
820 		I2C_ESP32_GET_PIN_INFO(idx)							   \
821 		.mode = {									   \
822 			.tx_lsb_first = DT_PROP(I2C(idx), tx_lsb),				   \
823 			.rx_lsb_first = DT_PROP(I2C(idx), rx_lsb),				   \
824 		},										   \
825 		.irq_source = ETS_I2C_EXT##idx##_INTR_SOURCE,					   \
826 		.bitrate = I2C_FREQUENCY(idx),							   \
827 		.scl_timeout = I2C_ESP32_TIMEOUT(idx),						   \
828 	};											   \
829 	I2C_DEVICE_DT_DEFINE(I2C(idx), i2c_esp32_init, NULL, &i2c_esp32_data_##idx,		   \
830 			     &i2c_esp32_config_##idx, POST_KERNEL, CONFIG_I2C_INIT_PRIORITY,	   \
831 			     &i2c_esp32_driver_api);
832 
833 #if DT_NODE_HAS_STATUS(I2C(0), okay)
834 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
835 #if !DT_NODE_HAS_PROP(I2C(0), sda_gpios) || !DT_NODE_HAS_PROP(I2C(0), scl_gpios)
836 #error "Missing <sda-gpios> and <scl-gpios> properties to build for this target."
837 #endif
838 #else
839 #if DT_NODE_HAS_PROP(I2C(0), sda_gpios) || DT_NODE_HAS_PROP(I2C(0), scl_gpios)
840 #error "Properties <sda-gpios> and <scl-gpios> are not required for this target."
841 #endif
842 #endif /* !SOC_I2C_SUPPORT_HW_CLR_BUS */
843 ESP32_I2C_INIT(0);
844 #endif /* DT_NODE_HAS_STATUS(I2C(0), okay) */
845 
846 #if DT_NODE_HAS_STATUS(I2C(1), okay)
847 #ifndef SOC_I2C_SUPPORT_HW_CLR_BUS
848 #if !DT_NODE_HAS_PROP(I2C(1), sda_gpios) || !DT_NODE_HAS_PROP(I2C(1), scl_gpios)
849 #error "Missing <sda-gpios> and <scl-gpios> properties to build for this target."
850 #endif
851 #else
852 #if DT_NODE_HAS_PROP(I2C(1), sda_gpios) || DT_NODE_HAS_PROP(I2C(1), scl_gpios)
853 #error "Properties <sda-gpios> and <scl-gpios> are not required for this target."
854 #endif
855 #endif /* !SOC_I2C_SUPPORT_HW_CLR_BUS */
856 ESP32_I2C_INIT(1);
857 #endif /* DT_NODE_HAS_STATUS(I2C(1), okay) */
858