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