1 /*
2  * Copyright (c) 2022 ITE Corporation. All Rights Reserved.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT ite_enhance_i2c
8 
9 #include <zephyr/drivers/gpio.h>
10 #include <zephyr/drivers/i2c.h>
11 #include <zephyr/drivers/pinctrl.h>
12 #include <zephyr/irq.h>
13 #include <zephyr/kernel.h>
14 #include <zephyr/pm/policy.h>
15 #include <errno.h>
16 #include <soc.h>
17 #include <soc_dt.h>
18 #include <zephyr/sys/util.h>
19 
20 #include <zephyr/logging/log.h>
21 LOG_MODULE_REGISTER(i2c_ite_enhance, CONFIG_I2C_LOG_LEVEL);
22 
23 #include "i2c-priv.h"
24 
25 /* Start smbus session from idle state */
26 #define I2C_MSG_START BIT(5)
27 
28 #define I2C_LINE_SCL_HIGH BIT(0)
29 #define I2C_LINE_SDA_HIGH BIT(1)
30 #define I2C_LINE_IDLE (I2C_LINE_SCL_HIGH | I2C_LINE_SDA_HIGH)
31 
32 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
33 /* Reserved 5 bytes for ID and CMD_x. */
34 #define I2C_CQ_MODE_TX_MAX_PAYLOAD_SIZE  (CONFIG_I2C_CQ_MODE_MAX_PAYLOAD_SIZE - 5)
35 
36 /* Repeat Start. */
37 #define I2C_CQ_CMD_L_RS BIT(7)
38 /*
39  * R/W (Read/ Write) decides the I2C read or write direction.
40  * 1: read, 0: write
41  */
42 #define I2C_CQ_CMD_L_RW BIT(6)
43 /* P (STOP) is the I2C STOP condition. */
44 #define I2C_CQ_CMD_L_P  BIT(5)
45 /* E (End) is this device end flag. */
46 #define I2C_CQ_CMD_L_E  BIT(4)
47 /* LA (Last ACK) is Last ACK in master receiver. */
48 #define I2C_CQ_CMD_L_LA BIT(3)
49 /* bit[2:0] are number of transfer out or receive data which depends on R/W. */
50 #define I2C_CQ_CMD_L_NUM_BIT_2_0 GENMASK(2, 0)
51 
52 struct i2c_cq_packet {
53 	uint8_t id;
54 	uint8_t cmd_l;
55 	uint8_t cmd_h;
56 	uint8_t wdata[0];
57 };
58 #endif /* CONFIG_I2C_IT8XXX2_CQ_MODE */
59 
60 struct i2c_enhance_config {
61 	void (*irq_config_func)(void);
62 	uint32_t bitrate;
63 	uint8_t *base;
64 	uint8_t i2c_irq_base;
65 	uint8_t port;
66 	uint8_t channel_switch_sel;
67 	/* SCL GPIO cells */
68 	struct gpio_dt_spec scl_gpios;
69 	/* SDA GPIO cells */
70 	struct gpio_dt_spec sda_gpios;
71 	/* I2C alternate configuration */
72 	const struct pinctrl_dev_config *pcfg;
73 	uint8_t prescale_scl_low;
74 	uint8_t data_hold_time;
75 	uint32_t clock_gate_offset;
76 	bool target_enable;
77 	bool target_pio_mode;
78 };
79 
80 enum i2c_pin_fun {
81 	SCL = 0,
82 	SDA,
83 };
84 
85 enum i2c_ch_status {
86 	I2C_CH_NORMAL = 0,
87 	I2C_CH_REPEAT_START,
88 	I2C_CH_WAIT_READ,
89 	I2C_CH_WAIT_NEXT_XFER,
90 };
91 
92 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
93 struct i2c_host_cq_buffer {
94 	/* Command queue tx payload. */
95 	uint8_t i2c_cq_mode_tx_dlm[CONFIG_I2C_CQ_MODE_MAX_PAYLOAD_SIZE] __aligned(4);
96 	/* Command queue rx payload. */
97 	uint8_t i2c_cq_mode_rx_dlm[CONFIG_I2C_CQ_MODE_MAX_PAYLOAD_SIZE] __aligned(4);
98 };
99 #endif
100 #ifdef CONFIG_I2C_TARGET
101 /*
102  * When accessing data exceeds the maximum buffer, the actual reload address
103  * is one byte more than the maximum buffer size. Therefore, it is necessary to
104  * have a buffer in place to prevent overwriting other memory.
105  */
106 #define PROTECT_MEM_BUF 4
107 struct i2c_target_dma_buffer {
108 	/* Target mode DMA output buffer. */
109 	uint8_t __aligned(4)
110 		out_buffer[CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE + PROTECT_MEM_BUF];
111 	/* Target mode DMA input buffer. */
112 	uint8_t __aligned(4)
113 		in_buffer[CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE + PROTECT_MEM_BUF];
114 };
115 #endif
116 
117 struct i2c_enhance_data {
118 	enum i2c_ch_status i2ccs;
119 	struct i2c_msg *active_msg;
120 	struct k_mutex mutex;
121 	struct k_sem device_sync_sem;
122 	/* Index into output data */
123 	size_t widx;
124 	/* Index into input data */
125 	size_t ridx;
126 	/* operation freq of i2c */
127 	uint32_t bus_freq;
128 	/* Error code, if any */
129 	uint32_t err;
130 	/* address of device */
131 	uint16_t addr_16bit;
132 	/* wait for stop bit interrupt */
133 	uint8_t stop;
134 	/* Number of messages. */
135 	uint8_t num_msgs;
136 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
137 	/* Store command queue mode messages. */
138 	struct i2c_msg *cq_msgs;
139 #endif
140 #ifdef CONFIG_I2C_TARGET
141 	struct i2c_target_config *target_cfg;
142 	uint32_t buffer_size;
143 	int target_nack;
144 	bool target_attached;
145 #endif
146 	union {
147 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
148 		struct i2c_host_cq_buffer host_buffer;
149 #endif
150 #ifdef CONFIG_I2C_TARGET
151 		struct i2c_target_dma_buffer target_buffer;
152 #endif
153 	};
154 };
155 
156 enum enhanced_i2c_transfer_direct {
157 	TX_DIRECT,
158 	RX_DIRECT,
159 };
160 
161 enum enhanced_i2c_ctl {
162 	/* Hardware reset */
163 	E_HW_RST = 0x01,
164 	/* Stop */
165 	E_STOP = 0x02,
166 	/* Start & Repeat start */
167 	E_START = 0x04,
168 	/* Acknowledge */
169 	E_ACK = 0x08,
170 	/* State reset */
171 	E_STS_RST = 0x10,
172 	/* Mode select */
173 	E_MODE_SEL = 0x20,
174 	/* I2C interrupt enable */
175 	E_INT_EN = 0x40,
176 	/* 0 : Standard mode , 1 : Receive mode */
177 	E_RX_MODE = 0x80,
178 	/* State reset and hardware reset */
179 	E_STS_AND_HW_RST = (E_STS_RST | E_HW_RST),
180 	/* Generate start condition and transmit slave address */
181 	E_START_ID = (E_INT_EN | E_MODE_SEL | E_ACK | E_START | E_HW_RST),
182 	/* Generate stop condition */
183 	E_FINISH = (E_INT_EN | E_MODE_SEL | E_ACK | E_STOP | E_HW_RST),
184 	/* Start with command queue mode */
185 	E_START_CQ = (E_INT_EN | E_MODE_SEL | E_ACK | E_START),
186 };
187 
188 enum enhanced_i2c_host_status {
189 	/* ACK receive */
190 	E_HOSTA_ACK = 0x01,
191 	/* Interrupt pending */
192 	E_HOSTA_INTP = 0x02,
193 	/* Read/Write */
194 	E_HOSTA_RW = 0x04,
195 	/* Time out error */
196 	E_HOSTA_TMOE = 0x08,
197 	/* Arbitration lost */
198 	E_HOSTA_ARB = 0x10,
199 	/* Bus busy */
200 	E_HOSTA_BB = 0x20,
201 	/* Address match */
202 	E_HOSTA_AM = 0x40,
203 	/* Byte done status */
204 	E_HOSTA_BDS = 0x80,
205 	/* time out or lost arbitration */
206 	E_HOSTA_ANY_ERROR = (E_HOSTA_TMOE | E_HOSTA_ARB),
207 	/* Byte transfer done and ACK receive */
208 	E_HOSTA_BDS_AND_ACK = (E_HOSTA_BDS | E_HOSTA_ACK),
209 };
210 
211 enum i2c_reset_cause {
212 	I2C_RC_NO_IDLE_FOR_START = 1,
213 	I2C_RC_TIMEOUT,
214 };
215 
216 #ifdef CONFIG_I2C_TARGET
217 enum enhanced_i2c_target_status {
218 	/* Time out error */
219 	E_TARGET_TMOE = 0x08,
220 	/* Arbitration lost */
221 	E_TARGET_ARB = 0x10,
222 	/* Time out or lost arbitration */
223 	E_TARGET_ANY_ERROR = (E_TARGET_TMOE | E_TARGET_ARB),
224 };
225 #endif
226 
i2c_parsing_return_value(const struct device * dev)227 static int i2c_parsing_return_value(const struct device *dev)
228 {
229 	struct i2c_enhance_data *data = dev->data;
230 
231 	if (!data->err) {
232 		return 0;
233 	}
234 
235 	/* Connection timed out */
236 	if (data->err == ETIMEDOUT) {
237 		return -ETIMEDOUT;
238 	}
239 
240 	/* The device does not respond ACK */
241 	if (data->err == E_HOSTA_ACK) {
242 		return -ENXIO;
243 	} else {
244 		return -EIO;
245 	}
246 }
247 
i2c_get_line_levels(const struct device * dev)248 static int i2c_get_line_levels(const struct device *dev)
249 {
250 	const struct i2c_enhance_config *config = dev->config;
251 	uint8_t *base = config->base;
252 	int pin_sts = 0;
253 
254 	if (IT8XXX2_I2C_TOS(base) & IT8XXX2_I2C_SCL_IN) {
255 		pin_sts |= I2C_LINE_SCL_HIGH;
256 	}
257 
258 	if (IT8XXX2_I2C_TOS(base) & IT8XXX2_I2C_SDA_IN) {
259 		pin_sts |= I2C_LINE_SDA_HIGH;
260 	}
261 
262 	return pin_sts;
263 }
264 
i2c_is_busy(const struct device * dev)265 static int i2c_is_busy(const struct device *dev)
266 {
267 	const struct i2c_enhance_config *config = dev->config;
268 	uint8_t *base = config->base;
269 
270 	return (IT8XXX2_I2C_STR(base) & E_HOSTA_BB);
271 }
272 
i2c_bus_not_available(const struct device * dev)273 static int i2c_bus_not_available(const struct device *dev)
274 {
275 	if (i2c_is_busy(dev) ||
276 		(i2c_get_line_levels(dev) != I2C_LINE_IDLE)) {
277 		return -EIO;
278 	}
279 
280 	return 0;
281 }
282 
i2c_reset(const struct device * dev)283 static void i2c_reset(const struct device *dev)
284 {
285 	const struct i2c_enhance_config *config = dev->config;
286 	uint8_t *base = config->base;
287 
288 	/* State reset and hardware reset */
289 	IT8XXX2_I2C_CTR(base) = E_STS_AND_HW_RST;
290 }
291 
292 /* Set clock frequency for i2c port D, E , or F */
i2c_enhanced_port_set_frequency(const struct device * dev,int freq_hz)293 static void i2c_enhanced_port_set_frequency(const struct device *dev,
294 					    int freq_hz)
295 {
296 	const struct i2c_enhance_config *config = dev->config;
297 	uint32_t clk_div, psr, pll_clock, psr_h, psr_l;
298 	uint8_t *base = config->base;
299 	uint8_t prescale_scl = config->prescale_scl_low;
300 
301 	pll_clock = chip_get_pll_freq();
302 	/*
303 	 * Let psr(Prescale) = IT8XXX2_I2C_PSR(p_ch)
304 	 * Then, 1 SCL cycle = 2 x (psr + 2) x SMBus clock cycle
305 	 * SMBus clock = pll_clock / clk_div
306 	 * SMBus clock cycle = 1 / SMBus clock
307 	 * 1 SCL cycle = 1 / freq
308 	 * 1 / freq = 2 x (psr + 2) x (1 / (pll_clock / clk_div))
309 	 * psr = ((pll_clock / clk_div) x (1 / freq) x (1 / 2)) - 2
310 	 */
311 	if (freq_hz) {
312 		/* Get SMBus clock divide value */
313 		clk_div = (IT8XXX2_ECPM_SCDCR2 & 0x0F) + 1U;
314 		/* Calculate PSR value */
315 		psr = (pll_clock / (clk_div * (2U * freq_hz))) - 2U;
316 		/* Set psr value under 0xFD */
317 		if (psr > 0xFD) {
318 			psr = 0xFD;
319 		}
320 
321 		/* Adjust SCL low period prescale */
322 		psr_l = psr + prescale_scl;
323 		if (psr_l > 0xFD) {
324 			psr_l = 0xFD;
325 			LOG_WRN("(psr + prescale_scl) can not be greater than 0xfd.");
326 		}
327 
328 		/*
329 		 * Adjust SCL high period prescale
330 		 * The property setting prescale_scl must be less than psr and
331 		 * the minimum value of psr_h is 2.
332 		 */
333 		if (psr > (prescale_scl + 2)) {
334 			psr_h = psr - prescale_scl;
335 		} else {
336 			psr_h = 2;
337 			LOG_WRN("prescale_scl_low should be less than (psr - 2).");
338 		}
339 
340 		/* Set I2C Speed for SCL low period. */
341 		IT8XXX2_I2C_PSR(base) = psr_l & 0xFF;
342 		/* Set I2C Speed for SCL high period. */
343 		IT8XXX2_I2C_HSPR(base) = psr_h & 0xFF;
344 	}
345 
346 }
347 
i2c_enhance_configure(const struct device * dev,uint32_t dev_config_raw)348 static int i2c_enhance_configure(const struct device *dev,
349 				 uint32_t dev_config_raw)
350 {
351 	const struct i2c_enhance_config *config = dev->config;
352 	struct i2c_enhance_data *const data = dev->data;
353 
354 	if (!(I2C_MODE_CONTROLLER & dev_config_raw)) {
355 		return -EINVAL;
356 	}
357 
358 	if (I2C_ADDR_10_BITS & dev_config_raw) {
359 		return -EINVAL;
360 	}
361 
362 	data->bus_freq = I2C_SPEED_GET(dev_config_raw);
363 
364 	i2c_enhanced_port_set_frequency(dev, config->bitrate);
365 
366 	return 0;
367 }
368 
i2c_enhance_get_config(const struct device * dev,uint32_t * dev_config)369 static int i2c_enhance_get_config(const struct device *dev, uint32_t *dev_config)
370 {
371 	struct i2c_enhance_data *const data = dev->data;
372 	uint32_t speed;
373 
374 	if (!data->bus_freq) {
375 		LOG_ERR("The bus frequency is not initially configured.");
376 		return -EIO;
377 	}
378 
379 	switch (data->bus_freq) {
380 	case I2C_SPEED_DT:
381 	case I2C_SPEED_STANDARD:
382 	case I2C_SPEED_FAST:
383 	case I2C_SPEED_FAST_PLUS:
384 		speed = I2C_SPEED_SET(data->bus_freq);
385 		break;
386 	default:
387 		return -ERANGE;
388 	}
389 
390 	*dev_config = (I2C_MODE_CONTROLLER | speed);
391 
392 	return 0;
393 }
394 
enhanced_i2c_error(const struct device * dev)395 static int enhanced_i2c_error(const struct device *dev)
396 {
397 	struct i2c_enhance_data *data = dev->data;
398 	const struct i2c_enhance_config *config = dev->config;
399 	uint8_t *base = config->base;
400 	uint32_t i2c_str = IT8XXX2_I2C_STR(base);
401 
402 	if (i2c_str & E_HOSTA_ANY_ERROR) {
403 		data->err = i2c_str & E_HOSTA_ANY_ERROR;
404 	/* device does not respond ACK */
405 	} else if ((i2c_str & E_HOSTA_BDS_AND_ACK) == E_HOSTA_BDS) {
406 		if (IT8XXX2_I2C_CTR(base) & E_ACK) {
407 			data->err = E_HOSTA_ACK;
408 			/* STOP */
409 			IT8XXX2_I2C_CTR(base) = E_FINISH;
410 		}
411 	}
412 
413 	return data->err;
414 }
415 
enhanced_i2c_start(const struct device * dev)416 static void enhanced_i2c_start(const struct device *dev)
417 {
418 	const struct i2c_enhance_config *config = dev->config;
419 	uint8_t *base = config->base;
420 
421 	/* reset i2c port */
422 	i2c_reset(dev);
423 	/* Set i2c frequency */
424 	i2c_enhanced_port_set_frequency(dev, config->bitrate);
425 	/*
426 	 * Set time out register.
427 	 * I2C D/E/F clock/data low timeout.
428 	 */
429 	IT8XXX2_I2C_TOR(base) = I2C_CLK_LOW_TIMEOUT;
430 	/* bit1: Enable enhanced i2c module */
431 	IT8XXX2_I2C_CTR1(base) = IT8XXX2_I2C_MDL_EN;
432 }
433 
i2c_pio_trans_data(const struct device * dev,enum enhanced_i2c_transfer_direct direct,uint16_t trans_data,int first_byte)434 static void i2c_pio_trans_data(const struct device *dev,
435 			       enum enhanced_i2c_transfer_direct direct,
436 			       uint16_t trans_data, int first_byte)
437 {
438 	struct i2c_enhance_data *data = dev->data;
439 	const struct i2c_enhance_config *config = dev->config;
440 	uint8_t *base = config->base;
441 	uint32_t nack = 0;
442 
443 	if (first_byte) {
444 		/* First byte must be slave address. */
445 		IT8XXX2_I2C_DTR(base) = trans_data |
446 					(direct == RX_DIRECT ? BIT(0) : 0);
447 		/* start or repeat start signal. */
448 		IT8XXX2_I2C_CTR(base) = E_START_ID;
449 	} else {
450 		if (direct == TX_DIRECT) {
451 			/* Transmit data */
452 			IT8XXX2_I2C_DTR(base) = (uint8_t)trans_data;
453 		} else {
454 			/*
455 			 * Receive data.
456 			 * Last byte should be NACK in the end of read cycle
457 			 */
458 			if (((data->ridx + 1) == data->active_msg->len) &&
459 				(data->active_msg->flags & I2C_MSG_STOP)) {
460 				nack = 1;
461 			}
462 		}
463 		/* Set hardware reset to start next transmission */
464 		IT8XXX2_I2C_CTR(base) = E_INT_EN | E_MODE_SEL |
465 				E_HW_RST | (nack ? 0 : E_ACK);
466 	}
467 }
468 
enhanced_i2c_tran_read(const struct device * dev)469 static int enhanced_i2c_tran_read(const struct device *dev)
470 {
471 	struct i2c_enhance_data *data = dev->data;
472 	const struct i2c_enhance_config *config = dev->config;
473 	uint8_t *base = config->base;
474 	uint8_t in_data = 0;
475 
476 	if (data->active_msg->flags & I2C_MSG_START) {
477 		/* clear start flag */
478 		data->active_msg->flags &= ~I2C_MSG_START;
479 		enhanced_i2c_start(dev);
480 		/* Direct read  */
481 		data->i2ccs = I2C_CH_WAIT_READ;
482 		/* Send ID */
483 		i2c_pio_trans_data(dev, RX_DIRECT, data->addr_16bit << 1, 1);
484 	} else {
485 		if (data->i2ccs) {
486 			if (data->i2ccs == I2C_CH_WAIT_READ) {
487 				data->i2ccs = I2C_CH_NORMAL;
488 				/* Receive data */
489 				i2c_pio_trans_data(dev, RX_DIRECT, in_data, 0);
490 
491 			/* data->active_msg->flags == I2C_MSG_RESTART */
492 			} else {
493 				/* Write to read */
494 				data->i2ccs = I2C_CH_WAIT_READ;
495 				/* Send ID */
496 				i2c_pio_trans_data(dev, RX_DIRECT,
497 					data->addr_16bit << 1, 1);
498 			}
499 		} else {
500 			if (data->ridx < data->active_msg->len) {
501 				/* read data */
502 				*(data->active_msg->buf++) = IT8XXX2_I2C_DRR(base);
503 				data->ridx++;
504 				/* done */
505 				if (data->ridx == data->active_msg->len) {
506 					data->active_msg->len = 0;
507 					if (data->active_msg->flags & I2C_MSG_STOP) {
508 						data->i2ccs = I2C_CH_NORMAL;
509 						IT8XXX2_I2C_CTR(base) = E_FINISH;
510 						/* wait for stop bit interrupt */
511 						data->stop = 1;
512 						return 1;
513 					}
514 					/* End the transaction */
515 					data->i2ccs = I2C_CH_WAIT_READ;
516 					return 0;
517 				}
518 				/* read next byte */
519 				i2c_pio_trans_data(dev, RX_DIRECT, in_data, 0);
520 			}
521 		}
522 	}
523 	return 1;
524 }
525 
enhanced_i2c_tran_write(const struct device * dev)526 static int enhanced_i2c_tran_write(const struct device *dev)
527 {
528 	struct i2c_enhance_data *data = dev->data;
529 	const struct i2c_enhance_config *config = dev->config;
530 	uint8_t *base = config->base;
531 	uint8_t out_data;
532 
533 	if (data->active_msg->flags & I2C_MSG_START) {
534 		/* Clear start bit */
535 		data->active_msg->flags &= ~I2C_MSG_START;
536 		enhanced_i2c_start(dev);
537 		/* Send ID */
538 		i2c_pio_trans_data(dev, TX_DIRECT, data->addr_16bit << 1, 1);
539 	} else {
540 		/* Host has completed the transmission of a byte */
541 		if (data->widx < data->active_msg->len) {
542 			out_data = *(data->active_msg->buf++);
543 			data->widx++;
544 
545 			/* Send Byte */
546 			i2c_pio_trans_data(dev, TX_DIRECT, out_data, 0);
547 			if (data->i2ccs == I2C_CH_WAIT_NEXT_XFER) {
548 				data->i2ccs = I2C_CH_NORMAL;
549 			}
550 		} else {
551 			/* done */
552 			data->active_msg->len = 0;
553 			if (data->active_msg->flags & I2C_MSG_STOP) {
554 				IT8XXX2_I2C_CTR(base) = E_FINISH;
555 				/* wait for stop bit interrupt */
556 				data->stop = 1;
557 			} else {
558 				/* Direct write with direct read */
559 				data->i2ccs = I2C_CH_WAIT_NEXT_XFER;
560 				return 0;
561 			}
562 		}
563 	}
564 	return 1;
565 }
566 
i2c_transaction(const struct device * dev)567 static int i2c_transaction(const struct device *dev)
568 {
569 	struct i2c_enhance_data *data = dev->data;
570 	const struct i2c_enhance_config *config = dev->config;
571 	uint8_t *base = config->base;
572 
573 	/* no error */
574 	if (!(enhanced_i2c_error(dev))) {
575 		if (!data->stop) {
576 			/*
577 			 * The return value indicates if there is more data
578 			 * to be read or written. If the return value = 1,
579 			 * it means that the interrupt cannot be disable and
580 			 * continue to transmit data.
581 			 */
582 			if (data->active_msg->flags & I2C_MSG_READ) {
583 				return enhanced_i2c_tran_read(dev);
584 			} else {
585 				return enhanced_i2c_tran_write(dev);
586 			}
587 		}
588 	}
589 	/* reset i2c port */
590 	i2c_reset(dev);
591 	IT8XXX2_I2C_CTR1(base) = 0;
592 
593 	data->stop = 0;
594 	/* done doing work */
595 	return 0;
596 }
597 
i2c_enhance_pio_transfer(const struct device * dev,struct i2c_msg * msgs)598 static int i2c_enhance_pio_transfer(const struct device *dev,
599 				    struct i2c_msg *msgs)
600 {
601 	struct i2c_enhance_data *data = dev->data;
602 	const struct i2c_enhance_config *config = dev->config;
603 	int res;
604 
605 	if (data->i2ccs == I2C_CH_NORMAL) {
606 		struct i2c_msg *start_msg = &msgs[0];
607 
608 		start_msg->flags |= I2C_MSG_START;
609 	}
610 
611 	for (int i = 0; i < data->num_msgs; i++) {
612 
613 		data->widx = 0;
614 		data->ridx = 0;
615 		data->err = 0;
616 		data->active_msg = &msgs[i];
617 
618 		/*
619 		 * Start transaction.
620 		 * The return value indicates if the initial configuration
621 		 * of I2C transaction for read or write has been completed.
622 		 */
623 		if (i2c_transaction(dev)) {
624 			/* Enable I2C interrupt. */
625 			irq_enable(config->i2c_irq_base);
626 		}
627 		/* Wait for the transfer to complete */
628 		/* TODO: the timeout should be adjustable */
629 		res = k_sem_take(&data->device_sync_sem, K_MSEC(100));
630 		/*
631 		 * The irq will be enabled at the condition of start or
632 		 * repeat start of I2C. If timeout occurs without being
633 		 * wake up during suspend(ex: interrupt is not fired),
634 		 * the irq should be disabled immediately.
635 		 */
636 		irq_disable(config->i2c_irq_base);
637 		/*
638 		 * The transaction is dropped on any error(timeout, NACK, fail,
639 		 * bus error, device error).
640 		 */
641 		if (data->err) {
642 			break;
643 		}
644 
645 		if (res != 0) {
646 			data->err = ETIMEDOUT;
647 			/* reset i2c port */
648 			i2c_reset(dev);
649 			LOG_ERR("I2C ch%d:0x%X reset cause %d",
650 				config->port, data->addr_16bit, I2C_RC_TIMEOUT);
651 			/* If this message is sent fail, drop the transaction. */
652 			break;
653 		}
654 	}
655 
656 	/* reset i2c channel status */
657 	if (data->err || (data->active_msg->flags & I2C_MSG_STOP)) {
658 		data->i2ccs = I2C_CH_NORMAL;
659 	}
660 
661 	return data->err;
662 }
663 
664 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
enhanced_i2c_set_cmd_addr_regs(const struct device * dev)665 static void enhanced_i2c_set_cmd_addr_regs(const struct device *dev)
666 {
667 	const struct i2c_enhance_config *config = dev->config;
668 	struct i2c_enhance_data *data = dev->data;
669 	struct i2c_host_cq_buffer *host_buffer = &data->host_buffer;
670 	uint32_t dlm_base;
671 	uint8_t *base = config->base;
672 
673 	/* Set "Address Register" to store the I2C data. */
674 	dlm_base = (uint32_t)host_buffer->i2c_cq_mode_rx_dlm & 0xffffff;
675 	IT8XXX2_I2C_RAMH2A(base) = (dlm_base >> 16) & 0xff;
676 	IT8XXX2_I2C_RAMHA(base) = (dlm_base >> 8) & 0xff;
677 	IT8XXX2_I2C_RAMLA(base) = dlm_base & 0xff;
678 
679 	/* Set "Command Address Register" to get commands. */
680 	dlm_base = (uint32_t)host_buffer->i2c_cq_mode_tx_dlm & 0xffffff;
681 	IT8XXX2_I2C_CMD_ADDH2(base) = (dlm_base >> 16) & 0xff;
682 	IT8XXX2_I2C_CMD_ADDH(base) = (dlm_base >> 8) & 0xff;
683 	IT8XXX2_I2C_CMD_ADDL(base) = dlm_base & 0xff;
684 }
685 
enhanced_i2c_cq_write(const struct device * dev)686 static void enhanced_i2c_cq_write(const struct device *dev)
687 {
688 	struct i2c_enhance_data *data = dev->data;
689 	struct i2c_host_cq_buffer *host_buffer = &data->host_buffer;
690 	struct i2c_cq_packet *i2c_cq_pckt;
691 	uint8_t num_bit_2_0 = (data->cq_msgs[0].len - 1) & I2C_CQ_CMD_L_NUM_BIT_2_0;
692 	uint8_t num_bit_10_3 = ((data->cq_msgs[0].len - 1) >> 3) & 0xff;
693 
694 	i2c_cq_pckt = (struct i2c_cq_packet *)host_buffer->i2c_cq_mode_tx_dlm;
695 	/* Set commands in RAM. */
696 	i2c_cq_pckt->id = data->addr_16bit << 1;
697 	i2c_cq_pckt->cmd_l = I2C_CQ_CMD_L_P | I2C_CQ_CMD_L_E | num_bit_2_0;
698 	i2c_cq_pckt->cmd_h = num_bit_10_3;
699 	for (int i = 0; i < data->cq_msgs[0].len; i++) {
700 		i2c_cq_pckt->wdata[i] = data->cq_msgs[0].buf[i];
701 	}
702 }
703 
enhanced_i2c_cq_read(const struct device * dev)704 static void enhanced_i2c_cq_read(const struct device *dev)
705 {
706 	struct i2c_enhance_data *data = dev->data;
707 	struct i2c_host_cq_buffer *host_buffer = &data->host_buffer;
708 	struct i2c_cq_packet *i2c_cq_pckt;
709 	uint8_t num_bit_2_0 = (data->cq_msgs[0].len - 1) & I2C_CQ_CMD_L_NUM_BIT_2_0;
710 	uint8_t num_bit_10_3 = ((data->cq_msgs[0].len - 1) >> 3) & 0xff;
711 
712 	i2c_cq_pckt = (struct i2c_cq_packet *)host_buffer->i2c_cq_mode_tx_dlm;
713 	/* Set commands in RAM. */
714 	i2c_cq_pckt->id = data->addr_16bit << 1;
715 	i2c_cq_pckt->cmd_l = I2C_CQ_CMD_L_RW | I2C_CQ_CMD_L_P |
716 				I2C_CQ_CMD_L_E | num_bit_2_0;
717 	i2c_cq_pckt->cmd_h = num_bit_10_3;
718 }
719 
enhanced_i2c_cq_write_to_read(const struct device * dev)720 static void enhanced_i2c_cq_write_to_read(const struct device *dev)
721 {
722 	struct i2c_enhance_data *data = dev->data;
723 	struct i2c_host_cq_buffer *host_buffer = &data->host_buffer;
724 	struct i2c_cq_packet *i2c_cq_pckt;
725 	uint8_t num_bit_2_0 = (data->cq_msgs[0].len - 1) & I2C_CQ_CMD_L_NUM_BIT_2_0;
726 	uint8_t num_bit_10_3 = ((data->cq_msgs[0].len - 1) >> 3) & 0xff;
727 	int i;
728 
729 	i2c_cq_pckt = (struct i2c_cq_packet *)host_buffer->i2c_cq_mode_tx_dlm;
730 	/* Set commands in RAM. (command byte for write) */
731 	i2c_cq_pckt->id = data->addr_16bit << 1;
732 	i2c_cq_pckt->cmd_l = num_bit_2_0;
733 	i2c_cq_pckt->cmd_h = num_bit_10_3;
734 	for (i = 0; i < data->cq_msgs[0].len; i++) {
735 		i2c_cq_pckt->wdata[i] = data->cq_msgs[0].buf[i];
736 	}
737 
738 	/* Set commands in RAM. (command byte for read) */
739 	num_bit_2_0 = (data->cq_msgs[1].len - 1) & I2C_CQ_CMD_L_NUM_BIT_2_0;
740 	num_bit_10_3 = ((data->cq_msgs[1].len - 1) >> 3) & 0xff;
741 	i2c_cq_pckt->wdata[i++] = I2C_CQ_CMD_L_RS | I2C_CQ_CMD_L_RW |
742 				I2C_CQ_CMD_L_P | I2C_CQ_CMD_L_E | num_bit_2_0;
743 	i2c_cq_pckt->wdata[i] = num_bit_10_3;
744 }
745 
enhanced_i2c_cq_isr(const struct device * dev)746 static int enhanced_i2c_cq_isr(const struct device *dev)
747 {
748 	struct i2c_enhance_data *data = dev->data;
749 	struct i2c_host_cq_buffer *host_buffer = &data->host_buffer;
750 	const struct i2c_enhance_config *config = dev->config;
751 	uint8_t *base = config->base;
752 
753 	/* Device 1 finish IRQ. */
754 	if (IT8XXX2_I2C_FST(base) & IT8XXX2_I2C_FST_DEV1_IRQ) {
755 		uint8_t msgs_idx = data->num_msgs - 1;
756 
757 		/* Get data if this is a read transaction. */
758 		if (data->cq_msgs[msgs_idx].flags & I2C_MSG_READ) {
759 			for (int i = 0; i < data->cq_msgs[msgs_idx].len; i++) {
760 				data->cq_msgs[msgs_idx].buf[i] =
761 				host_buffer->i2c_cq_mode_rx_dlm[i];
762 			}
763 		}
764 	} else {
765 		/* Device 1 error have occurred. eg. nack, timeout... */
766 		if (IT8XXX2_I2C_NST(base) & IT8XXX2_I2C_NST_ID_NACK) {
767 			data->err = E_HOSTA_ACK;
768 		} else {
769 			data->err = IT8XXX2_I2C_STR(base) &
770 					E_HOSTA_ANY_ERROR;
771 		}
772 	}
773 	/* Reset bus. */
774 	IT8XXX2_I2C_CTR(base) = E_STS_AND_HW_RST;
775 	IT8XXX2_I2C_CTR1(base) = 0;
776 
777 	return 0;
778 }
779 
enhanced_i2c_cmd_queue_trans(const struct device * dev)780 static int enhanced_i2c_cmd_queue_trans(const struct device *dev)
781 {
782 	struct i2c_enhance_data *data = dev->data;
783 	const struct i2c_enhance_config *config = dev->config;
784 	uint8_t *base = config->base;
785 
786 	/* State reset and hardware reset. */
787 	IT8XXX2_I2C_CTR(base) = E_STS_AND_HW_RST;
788 	/* Set "PSR" registers to decide the i2c speed. */
789 	i2c_enhanced_port_set_frequency(dev, config->bitrate);
790 	/* Set time out register. port D, E, or F clock/data low timeout. */
791 	IT8XXX2_I2C_TOR(base) = I2C_CLK_LOW_TIMEOUT;
792 
793 	if (data->num_msgs == 2) {
794 		/* I2C write to read of command queue mode. */
795 		enhanced_i2c_cq_write_to_read(dev);
796 	} else {
797 		/* I2C read of command queue mode. */
798 		if (data->cq_msgs[0].flags & I2C_MSG_READ) {
799 			enhanced_i2c_cq_read(dev);
800 		/* I2C write of command queue mode. */
801 		} else {
802 			enhanced_i2c_cq_write(dev);
803 		}
804 	}
805 
806 	/* Enable i2c module with command queue mode. */
807 	IT8XXX2_I2C_CTR1(base) = IT8XXX2_I2C_MDL_EN | IT8XXX2_I2C_COMQ_EN;
808 	/* One shot on device 1. */
809 	IT8XXX2_I2C_MODE_SEL(base) = 0;
810 	IT8XXX2_I2C_CTR2(base) = 1;
811 	/*
812 	 * The EC processor(CPU) cannot be in the k_cpu_idle() and power
813 	 * policy during the transactions with the CQ mode(DMA mode).
814 	 * Otherwise, the EC processor would be clock gated.
815 	 */
816 	chip_block_idle();
817 	pm_policy_state_lock_get(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
818 	/* Start */
819 	IT8XXX2_I2C_CTR(base) = E_START_CQ;
820 
821 	return 1;
822 }
823 
i2c_enhance_cq_transfer(const struct device * dev,struct i2c_msg * msgs)824 static int i2c_enhance_cq_transfer(const struct device *dev,
825 				   struct i2c_msg *msgs)
826 {
827 	struct i2c_enhance_data *data = dev->data;
828 	const struct i2c_enhance_config *config = dev->config;
829 	int res = 0;
830 
831 	data->err = 0;
832 	data->cq_msgs = msgs;
833 
834 	/* Start transaction */
835 	if (enhanced_i2c_cmd_queue_trans(dev)) {
836 		/* Enable i2c interrupt */
837 		irq_enable(config->i2c_irq_base);
838 	}
839 	/* Wait for the transfer to complete */
840 	res = k_sem_take(&data->device_sync_sem, K_MSEC(100));
841 
842 	irq_disable(config->i2c_irq_base);
843 
844 	if (res != 0) {
845 		data->err = ETIMEDOUT;
846 		/* Reset i2c port. */
847 		i2c_reset(dev);
848 		LOG_ERR("I2C ch%d:0x%X reset cause %d",
849 			config->port, data->addr_16bit, I2C_RC_TIMEOUT);
850 	}
851 
852 	/* Permit to enter power policy and idle mode. */
853 	pm_policy_state_lock_put(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
854 	chip_permit_idle();
855 
856 	return data->err;
857 }
858 
cq_mode_allowed(const struct device * dev,struct i2c_msg * msgs)859 static bool cq_mode_allowed(const struct device *dev, struct i2c_msg *msgs)
860 {
861 	struct i2c_enhance_data *data = dev->data;
862 
863 	/*
864 	 * If the transaction of write or read is divided into two
865 	 * transfers(not two messages), the command queue mode does
866 	 * not support.
867 	 */
868 	if (data->i2ccs != I2C_CH_NORMAL) {
869 		return false;
870 	}
871 	/*
872 	 * When there is only one message, use the command queue transfer
873 	 * directly.
874 	 */
875 	if (data->num_msgs == 1 && (msgs[0].flags & I2C_MSG_STOP)) {
876 		/* Read transfer payload too long, use PIO mode */
877 		if (((msgs[0].flags & I2C_MSG_RW_MASK) == I2C_MSG_READ) &&
878 		    (msgs[0].len > CONFIG_I2C_CQ_MODE_MAX_PAYLOAD_SIZE)) {
879 			return false;
880 		}
881 		/* Write transfer payload too long, use PIO mode */
882 		if (((msgs[0].flags & I2C_MSG_RW_MASK) == I2C_MSG_WRITE) &&
883 		    (msgs[0].len > I2C_CQ_MODE_TX_MAX_PAYLOAD_SIZE)) {
884 			return false;
885 		}
886 		/*
887 		 * Write of I2C target address without writing data, used by
888 		 * cmd_i2c_scan. Use PIO mode.
889 		 */
890 		if (((msgs[0].flags & I2C_MSG_RW_MASK) == I2C_MSG_WRITE) &&
891 		    (msgs[0].len == 0)) {
892 			return false;
893 		}
894 		return true;
895 	}
896 	/*
897 	 * When there are two messages, we need to judge whether or not there
898 	 * is I2C_MSG_RESTART flag from the second message, and then decide to
899 	 * do the command queue or PIO mode transfer.
900 	 */
901 	if (data->num_msgs == 2) {
902 		/*
903 		 * The first of two messages must be write.
904 		 * If the length of write to read transfer is greater than
905 		 * command queue payload size, there will execute PIO mode.
906 		 */
907 		if (((msgs[0].flags & I2C_MSG_RW_MASK) == I2C_MSG_WRITE) &&
908 		    (msgs[0].len <= I2C_CQ_MODE_TX_MAX_PAYLOAD_SIZE)) {
909 			/*
910 			 * The transfer is i2c_burst_read().
911 			 *
912 			 * e.g. msg[0].flags = I2C_MSG_WRITE;
913 			 *      msg[1].flags = I2C_MSG_RESTART | I2C_MSG_READ |
914 			 *                     I2C_MSG_STOP;
915 			 */
916 			if ((msgs[1].flags & I2C_MSG_RESTART) &&
917 			    ((msgs[1].flags & I2C_MSG_RW_MASK) == I2C_MSG_READ) &&
918 			    (msgs[1].flags & I2C_MSG_STOP) &&
919 			    (msgs[1].len <= CONFIG_I2C_CQ_MODE_MAX_PAYLOAD_SIZE)) {
920 				return true;
921 			}
922 		}
923 	}
924 
925 	return false;
926 }
927 #endif /* CONFIG_I2C_IT8XXX2_CQ_MODE */
928 
i2c_enhance_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)929 static int i2c_enhance_transfer(const struct device *dev,
930 				struct i2c_msg *msgs,
931 				uint8_t num_msgs, uint16_t addr)
932 {
933 	struct i2c_enhance_data *data = dev->data;
934 	int ret;
935 
936 #ifdef CONFIG_I2C_TARGET
937 	if (data->target_attached) {
938 		LOG_ERR("Device is registered as target");
939 		return -EBUSY;
940 	}
941 #endif
942 	/* Lock mutex of i2c controller */
943 	k_mutex_lock(&data->mutex, K_FOREVER);
944 
945 	data->num_msgs = num_msgs;
946 	data->addr_16bit = addr;
947 	/*
948 	 * If the transaction of write to read is divided into two
949 	 * transfers, the repeat start transfer uses this flag to
950 	 * exclude checking bus busy.
951 	 */
952 	if (data->i2ccs == I2C_CH_NORMAL) {
953 		/* Make sure we're in a good state to start */
954 		if (i2c_bus_not_available(dev)) {
955 			/* Recovery I2C bus */
956 			i2c_recover_bus(dev);
957 			/*
958 			 * After resetting I2C bus, if I2C bus is not available
959 			 * (No external pull-up), drop the transaction.
960 			 */
961 			if (i2c_bus_not_available(dev)) {
962 				/* Unlock mutex of i2c controller */
963 				k_mutex_unlock(&data->mutex);
964 				return -EIO;
965 			}
966 		}
967 	}
968 
969 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
970 	if (cq_mode_allowed(dev, msgs)) {
971 		data->err = i2c_enhance_cq_transfer(dev, msgs);
972 	} else
973 #endif
974 	{
975 		data->err = i2c_enhance_pio_transfer(dev, msgs);
976 	}
977 	/* Save return value. */
978 	ret = i2c_parsing_return_value(dev);
979 	/* Unlock mutex of i2c controller */
980 	k_mutex_unlock(&data->mutex);
981 
982 	return ret;
983 }
984 
985 #ifdef CONFIG_I2C_TARGET
target_i2c_isr_dma(const struct device * dev,uint8_t interrupt_status)986 static void target_i2c_isr_dma(const struct device *dev,
987 			       uint8_t interrupt_status)
988 {
989 	struct i2c_enhance_data *data = dev->data;
990 	const struct i2c_enhance_config *config = dev->config;
991 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
992 	struct i2c_target_dma_buffer *target_buffer = &data->target_buffer;
993 	uint8_t *base = config->base;
994 
995 	/* Byte counter enable */
996 	if (interrupt_status & IT8XXX2_I2C_IDW_CLR) {
997 		IT8XXX2_I2C_BYTE_CNT_L(base) |=
998 			(IT8XXX2_I2C_DMA_ADDR_RELOAD |
999 			 IT8XXX2_I2C_BYTE_CNT_ENABLE);
1000 	}
1001 	/* The number of received data exceeds the byte counter setting */
1002 	if (interrupt_status & IT8XXX2_I2C_CNT_HOLD) {
1003 		LOG_ERR("The excess data written starts "
1004 			"from the memory address:%p",
1005 			target_buffer->in_buffer +
1006 			CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE);
1007 	}
1008 	/* Controller to write data */
1009 	if (interrupt_status & IT8XXX2_I2C_SLVDATAFLG) {
1010 		/* Number of receive data in target mode */
1011 		data->buffer_size =
1012 			((IT8XXX2_I2C_SLV_NUM_H(base) << 8) |
1013 			 IT8XXX2_I2C_SLV_NUM_L(base)) + 1;
1014 
1015 		/* Write data done callback function */
1016 		target_cb->buf_write_received(data->target_cfg,
1017 			target_buffer->in_buffer, data->buffer_size);
1018 	}
1019 	/* Controller to read data */
1020 	if (interrupt_status & IT8XXX2_I2C_IDR_CLR) {
1021 		uint32_t len;
1022 		uint8_t *rdata = NULL;
1023 
1024 		/* Clear byte counter setting */
1025 		IT8XXX2_I2C_BYTE_CNT_L(base) &=
1026 			~(IT8XXX2_I2C_DMA_ADDR_RELOAD |
1027 			  IT8XXX2_I2C_BYTE_CNT_ENABLE);
1028 		/* Read data callback function */
1029 		target_cb->buf_read_requested(data->target_cfg,
1030 			&rdata, &len);
1031 
1032 		if (len > CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE) {
1033 			LOG_ERR("The buffer size exceeds "
1034 				"I2C_TARGET_IT8XXX2_MAX_BUF_SIZE: len=%d",
1035 				len);
1036 		} else {
1037 			memcpy(target_buffer->out_buffer, rdata, len);
1038 		}
1039 	}
1040 }
1041 
target_i2c_isr_pio(const struct device * dev,uint8_t interrupt_status,uint8_t target_status)1042 static int target_i2c_isr_pio(const struct device *dev,
1043 			      uint8_t interrupt_status,
1044 			      uint8_t target_status)
1045 {
1046 	struct i2c_enhance_data *data = dev->data;
1047 	const struct i2c_enhance_config *config = dev->config;
1048 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
1049 	int ret = 0;
1050 	uint8_t *base = config->base;
1051 	uint8_t val;
1052 
1053 	/* Target ID write flag */
1054 	if (interrupt_status & IT8XXX2_I2C_IDW_CLR) {
1055 		ret = target_cb->write_requested(data->target_cfg);
1056 	}
1057 	/* Target ID read flag */
1058 	else if (interrupt_status & IT8XXX2_I2C_IDR_CLR) {
1059 		if (!target_cb->read_requested(data->target_cfg, &val)) {
1060 			IT8XXX2_I2C_DTR(base) = val;
1061 		}
1062 	}
1063 	/* Byte transfer done */
1064 	else if (target_status & IT8XXX2_I2C_BYTE_DONE) {
1065 		/* Read of write */
1066 		if (target_status & IT8XXX2_I2C_RW) {
1067 			/* Host receiving, target transmitting */
1068 			if (!target_cb->read_processed(data->target_cfg, &val)) {
1069 				IT8XXX2_I2C_DTR(base) = val;
1070 			}
1071 		} else {
1072 			/* Host transmitting, target receiving */
1073 			val = IT8XXX2_I2C_DRR(base);
1074 			ret = target_cb->write_received(data->target_cfg, val);
1075 		}
1076 	}
1077 
1078 	return ret;
1079 }
1080 
target_i2c_isr(const struct device * dev)1081 static void target_i2c_isr(const struct device *dev)
1082 {
1083 	struct i2c_enhance_data *data = dev->data;
1084 	const struct i2c_enhance_config *config = dev->config;
1085 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
1086 	uint8_t *base = config->base;
1087 	uint8_t target_status = IT8XXX2_I2C_STR(base);
1088 
1089 	/* Any error */
1090 	if (target_status & E_TARGET_ANY_ERROR) {
1091 		goto end;
1092 	}
1093 
1094 	/* Interrupt pending */
1095 	if (target_status & IT8XXX2_I2C_INT_PEND) {
1096 		uint8_t interrupt_status = IT8XXX2_I2C_IRQ_ST(base);
1097 
1098 		/* Determine whether the transaction uses PIO or DMA mode */
1099 		if (config->target_pio_mode) {
1100 			if (target_i2c_isr_pio(dev, interrupt_status, target_status) < 0) {
1101 				/* NACK */
1102 				IT8XXX2_I2C_CTR(base) &= ~IT8XXX2_I2C_ACK;
1103 				IT8XXX2_I2C_CTR(base) |= IT8XXX2_I2C_HALT;
1104 				data->target_nack = 1;
1105 			}
1106 		} else {
1107 			target_i2c_isr_dma(dev, interrupt_status);
1108 		}
1109 		/* Peripheral finish */
1110 		if (interrupt_status & IT8XXX2_I2C_P_CLR) {
1111 			/* Transfer done callback function */
1112 			target_cb->stop(data->target_cfg);
1113 
1114 			if (data->target_nack) {
1115 				/* Set acknowledge */
1116 				IT8XXX2_I2C_CTR(base) |= IT8XXX2_I2C_ACK;
1117 				data->target_nack = 0;
1118 			}
1119 		}
1120 		/* Write clear the peripheral status */
1121 		IT8XXX2_I2C_IRQ_ST(base) = interrupt_status;
1122 	}
1123 end:
1124 	/* Hardware reset */
1125 	IT8XXX2_I2C_CTR(base) |= IT8XXX2_I2C_HALT;
1126 }
1127 #endif
1128 
i2c_enhance_isr(void * arg)1129 static void i2c_enhance_isr(void *arg)
1130 {
1131 	struct device *dev = (struct device *)arg;
1132 	struct i2c_enhance_data *data = dev->data;
1133 	const struct i2c_enhance_config *config = dev->config;
1134 
1135 #ifdef CONFIG_I2C_TARGET
1136 	if (data->target_attached) {
1137 		target_i2c_isr(dev);
1138 	} else {
1139 #endif
1140 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
1141 		uint8_t *base = config->base;
1142 
1143 		/* If done doing work, wake up the task waiting for the transfer */
1144 		if (IT8XXX2_I2C_CTR1(base) & IT8XXX2_I2C_COMQ_EN) {
1145 			if (enhanced_i2c_cq_isr(dev)) {
1146 				return;
1147 			}
1148 		} else
1149 #endif
1150 		{
1151 			if (i2c_transaction(dev)) {
1152 				return;
1153 			}
1154 		}
1155 		irq_disable(config->i2c_irq_base);
1156 		k_sem_give(&data->device_sync_sem);
1157 #ifdef CONFIG_I2C_TARGET
1158 	}
1159 #endif
1160 }
1161 
i2c_enhance_init(const struct device * dev)1162 static int i2c_enhance_init(const struct device *dev)
1163 {
1164 	struct i2c_enhance_data *data = dev->data;
1165 	const struct i2c_enhance_config *config = dev->config;
1166 	uint8_t *base = config->base;
1167 	uint8_t data_hold_time = config->data_hold_time;
1168 	uint32_t bitrate_cfg;
1169 	int error, status;
1170 
1171 #ifdef CONFIG_I2C_TARGET
1172 	if (!config->target_enable) {
1173 #endif
1174 		/* Initialize mutex and semaphore */
1175 		k_mutex_init(&data->mutex);
1176 		k_sem_init(&data->device_sync_sem, 0, K_SEM_MAX_LIMIT);
1177 
1178 		/* Enable clock to specified peripheral */
1179 		volatile uint8_t *reg = (volatile uint8_t *)
1180 			(IT8XXX2_ECPM_BASE + (config->clock_gate_offset >> 8));
1181 		uint8_t reg_mask = config->clock_gate_offset & 0xff;
1182 		*reg &= ~reg_mask;
1183 
1184 		/* Enable I2C function */
1185 		/* Software reset */
1186 		IT8XXX2_I2C_DHTR(base) |= IT8XXX2_I2C_SOFT_RST;
1187 		IT8XXX2_I2C_DHTR(base) &= ~IT8XXX2_I2C_SOFT_RST;
1188 		/* reset i2c port */
1189 		i2c_reset(dev);
1190 		/* bit1, Module enable */
1191 		IT8XXX2_I2C_CTR1(base) = 0;
1192 
1193 #ifdef CONFIG_I2C_IT8XXX2_CQ_MODE
1194 		/* Set command address registers. */
1195 		enhanced_i2c_set_cmd_addr_regs(dev);
1196 #endif
1197 
1198 		/* ChannelA-F switch selection of I2C pin */
1199 		if (config->port == SMB_CHANNEL_A) {
1200 			IT8XXX2_SMB_SMB01CHS = (IT8XXX2_SMB_SMB01CHS &= ~GENMASK(2, 0)) |
1201 				config->channel_switch_sel;
1202 		} else if (config->port == SMB_CHANNEL_B) {
1203 			IT8XXX2_SMB_SMB01CHS = (config->channel_switch_sel << 4) |
1204 				(IT8XXX2_SMB_SMB01CHS &= ~GENMASK(6, 4));
1205 		} else if (config->port == SMB_CHANNEL_C) {
1206 			IT8XXX2_SMB_SMB23CHS = (IT8XXX2_SMB_SMB23CHS &= ~GENMASK(2, 0)) |
1207 				config->channel_switch_sel;
1208 		} else if (config->port == I2C_CHANNEL_D) {
1209 			IT8XXX2_SMB_SMB23CHS = (config->channel_switch_sel << 4) |
1210 				(IT8XXX2_SMB_SMB23CHS &= ~GENMASK(6, 4));
1211 		} else if (config->port == I2C_CHANNEL_E) {
1212 			IT8XXX2_SMB_SMB45CHS = (IT8XXX2_SMB_SMB45CHS &= ~GENMASK(2, 0)) |
1213 				config->channel_switch_sel;
1214 		} else if (config->port == I2C_CHANNEL_F) {
1215 			IT8XXX2_SMB_SMB45CHS = (config->channel_switch_sel << 4) |
1216 				(IT8XXX2_SMB_SMB45CHS &= ~GENMASK(6, 4));
1217 		}
1218 
1219 		/* Set I2C data hold time. */
1220 		IT8XXX2_I2C_DHTR(base) = (IT8XXX2_I2C_DHTR(base) & ~GENMASK(2, 0)) |
1221 			(data_hold_time - 3);
1222 
1223 		/* Set clock frequency for I2C ports */
1224 		if (config->bitrate == I2C_BITRATE_STANDARD ||
1225 			config->bitrate == I2C_BITRATE_FAST ||
1226 			config->bitrate == I2C_BITRATE_FAST_PLUS) {
1227 			bitrate_cfg = i2c_map_dt_bitrate(config->bitrate);
1228 		} else {
1229 			/* Device tree specified speed */
1230 			bitrate_cfg = I2C_SPEED_DT << I2C_SPEED_SHIFT;
1231 		}
1232 
1233 		error = i2c_enhance_configure(dev, I2C_MODE_CONTROLLER | bitrate_cfg);
1234 		data->i2ccs = I2C_CH_NORMAL;
1235 
1236 		if (error) {
1237 			LOG_ERR("i2c: failure initializing");
1238 			return error;
1239 		}
1240 #ifdef CONFIG_I2C_TARGET
1241 	}
1242 #endif
1243 
1244 	/* Set the pin to I2C alternate function. */
1245 	status = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
1246 	if (status < 0) {
1247 		LOG_ERR("Failed to configure I2C pins");
1248 		return status;
1249 	}
1250 
1251 
1252 	return 0;
1253 }
1254 
i2c_enhance_recover_bus(const struct device * dev)1255 static int i2c_enhance_recover_bus(const struct device *dev)
1256 {
1257 	const struct i2c_enhance_config *config = dev->config;
1258 	int i, status;
1259 
1260 	/* Set SCL of I2C as GPIO pin */
1261 	gpio_pin_configure_dt(&config->scl_gpios, GPIO_OUTPUT);
1262 	/* Set SDA of I2C as GPIO pin */
1263 	gpio_pin_configure_dt(&config->sda_gpios, GPIO_OUTPUT);
1264 
1265 	/*
1266 	 * In I2C recovery bus, 1ms sleep interval for bitbanging i2c
1267 	 * is mainly to ensure that gpio has enough time to go from
1268 	 * low to high or high to low.
1269 	 */
1270 	/* Pull SCL and SDA pin to high */
1271 	gpio_pin_set_dt(&config->scl_gpios, 1);
1272 	gpio_pin_set_dt(&config->sda_gpios, 1);
1273 	k_msleep(1);
1274 
1275 	/* Start condition */
1276 	gpio_pin_set_dt(&config->sda_gpios, 0);
1277 	k_msleep(1);
1278 	gpio_pin_set_dt(&config->scl_gpios, 0);
1279 	k_msleep(1);
1280 
1281 	/* 9 cycles of SCL with SDA held high */
1282 	for (i = 0; i < 9; i++) {
1283 		/* SDA */
1284 		gpio_pin_set_dt(&config->sda_gpios, 1);
1285 		/* SCL */
1286 		gpio_pin_set_dt(&config->scl_gpios, 1);
1287 		k_msleep(1);
1288 		/* SCL */
1289 		gpio_pin_set_dt(&config->scl_gpios, 0);
1290 		k_msleep(1);
1291 	}
1292 	/* SDA */
1293 	gpio_pin_set_dt(&config->sda_gpios, 0);
1294 	k_msleep(1);
1295 
1296 	/* Stop condition */
1297 	gpio_pin_set_dt(&config->scl_gpios, 1);
1298 	k_msleep(1);
1299 	gpio_pin_set_dt(&config->sda_gpios, 1);
1300 	k_msleep(1);
1301 
1302 	/* Set GPIO back to I2C alternate function */
1303 	status = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
1304 	if (status < 0) {
1305 		LOG_ERR("Failed to configure I2C pins");
1306 		return status;
1307 	}
1308 
1309 	/* reset i2c port */
1310 	i2c_reset(dev);
1311 	LOG_ERR("I2C ch%d reset cause %d", config->port,
1312 		I2C_RC_NO_IDLE_FOR_START);
1313 
1314 	return 0;
1315 }
1316 
1317 #ifdef CONFIG_I2C_TARGET
i2c_enhance_target_register(const struct device * dev,struct i2c_target_config * target_cfg)1318 static int i2c_enhance_target_register(const struct device *dev,
1319 				       struct i2c_target_config *target_cfg)
1320 {
1321 	const struct i2c_enhance_config *config = dev->config;
1322 	struct i2c_enhance_data *data = dev->data;
1323 	uint8_t *base = config->base;
1324 
1325 	if (!target_cfg) {
1326 		return -EINVAL;
1327 	}
1328 
1329 	if (target_cfg->flags & I2C_TARGET_FLAGS_ADDR_10_BITS) {
1330 		return -ENOTSUP;
1331 	}
1332 
1333 	if (data->target_attached) {
1334 		return -EBUSY;
1335 	}
1336 
1337 	data->target_cfg = target_cfg;
1338 	data->target_attached = true;
1339 
1340 	/* Software reset */
1341 	IT8XXX2_I2C_DHTR(base) |= IT8XXX2_I2C_SOFT_RST;
1342 	IT8XXX2_I2C_DHTR(base) &= ~IT8XXX2_I2C_SOFT_RST;
1343 	/* Disable the timeout setting when clock/data are in a low state */
1344 	IT8XXX2_I2C_TO_ARB_ST(base) &= ~(IT8XXX2_I2C_SCL_TIMEOUT_EN |
1345 					 IT8XXX2_I2C_SDA_TIMEOUT_EN);
1346 	/* Bit stretching */
1347 	IT8XXX2_I2C_TOS(base) |= IT8XXX2_I2C_CLK_STRETCH;
1348 	/* Peripheral address(8-bit) */
1349 	IT8XXX2_I2C_IDR(base) = target_cfg->address << 1;
1350 	/* I2C interrupt enable and set acknowledge */
1351 	IT8XXX2_I2C_CTR(base) = IT8XXX2_I2C_INT_EN | IT8XXX2_I2C_HALT |
1352 				     IT8XXX2_I2C_ACK;
1353 	/* Interrupt status write clear */
1354 	IT8XXX2_I2C_IRQ_ST(base) = 0xff;
1355 
1356 	/* I2C target initial configuration of PIO mode */
1357 	if (config->target_pio_mode) {
1358 		/* Block to enter power policy. */
1359 		pm_policy_state_lock_get(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
1360 
1361 		/* I2C module enable */
1362 		IT8XXX2_I2C_CTR1(base) = IT8XXX2_I2C_MDL_EN;
1363 	/* I2C target initial configuration of DMA mode */
1364 	} else {
1365 		struct i2c_target_dma_buffer *target_buffer = &data->target_buffer;
1366 		uint32_t in_data_addr, out_data_addr;
1367 		int buf_size = CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE;
1368 
1369 		/* Clear read and write data buffer of DMA */
1370 		memset(target_buffer->in_buffer, 0, buf_size);
1371 		memset(target_buffer->out_buffer, 0, buf_size);
1372 
1373 		in_data_addr = (uint32_t)target_buffer->in_buffer & 0xffffff;
1374 		out_data_addr = (uint32_t)target_buffer->out_buffer & 0xffffff;
1375 		/*
1376 		 * DMA write target address register
1377 		 * for high order byte
1378 		 */
1379 		IT8XXX2_I2C_RAMH2A(base) = in_data_addr >> 16;
1380 		IT8XXX2_I2C_RAMHA(base) = in_data_addr >> 8;
1381 		IT8XXX2_I2C_RAMLA(base) = in_data_addr;
1382 		/*
1383 		 * DMA read target address register
1384 		 * for high order byte
1385 		 */
1386 		IT8XXX2_I2C_CMD_ADDH2(base) = out_data_addr >> 16;
1387 		IT8XXX2_I2C_RAMHA2(base) = out_data_addr >> 8;
1388 		IT8XXX2_I2C_RAMLA2(base) = out_data_addr;
1389 
1390 		/* Byte counter setting */
1391 		/* This register indicates byte count[10:3]. */
1392 		IT8XXX2_I2C_BYTE_CNT_H(base) =
1393 			CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE >> 3;
1394 		/* This register indicates byte count[2:0]. */
1395 		IT8XXX2_I2C_BYTE_CNT_L(base) =
1396 			CONFIG_I2C_TARGET_IT8XXX2_MAX_BUF_SIZE & GENMASK(2, 0);
1397 
1398 		/*
1399 		 * The EC processor(CPU) cannot be in the k_cpu_idle() and power
1400 		 * policy during the transactions with the CQ mode(DMA mode).
1401 		 * Otherwise, the EC processor would be clock gated.
1402 		 */
1403 		chip_block_idle();
1404 		pm_policy_state_lock_get(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
1405 
1406 		/* I2C module enable and command queue mode */
1407 		IT8XXX2_I2C_CTR1(base) = IT8XXX2_I2C_COMQ_EN | IT8XXX2_I2C_MDL_EN;
1408 	}
1409 
1410 	ite_intc_isr_clear(config->i2c_irq_base);
1411 	irq_enable(config->i2c_irq_base);
1412 
1413 	return 0;
1414 }
1415 
i2c_enhance_target_unregister(const struct device * dev,struct i2c_target_config * cfg)1416 static int i2c_enhance_target_unregister(const struct device *dev,
1417 					 struct i2c_target_config *cfg)
1418 {
1419 	const struct i2c_enhance_config *config = dev->config;
1420 	struct i2c_enhance_data *data = dev->data;
1421 
1422 	if (!data->target_attached) {
1423 		return -EINVAL;
1424 	}
1425 
1426 	irq_disable(config->i2c_irq_base);
1427 
1428 	/* Permit to enter power policy and idle mode. */
1429 	pm_policy_state_lock_put(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
1430 	if (!config->target_pio_mode) {
1431 		chip_permit_idle();
1432 	}
1433 
1434 	data->target_cfg = NULL;
1435 	data->target_attached = false;
1436 	data->target_nack = 0;
1437 
1438 	return 0;
1439 }
1440 #endif
1441 
1442 static const struct i2c_driver_api i2c_enhance_driver_api = {
1443 	.configure = i2c_enhance_configure,
1444 	.get_config = i2c_enhance_get_config,
1445 	.transfer = i2c_enhance_transfer,
1446 	.recover_bus = i2c_enhance_recover_bus,
1447 #ifdef CONFIG_I2C_TARGET
1448 	.target_register = i2c_enhance_target_register,
1449 	.target_unregister = i2c_enhance_target_unregister,
1450 #endif
1451 };
1452 
1453 #ifdef CONFIG_I2C_TARGET
1454 BUILD_ASSERT(IS_ENABLED(CONFIG_I2C_TARGET_BUFFER_MODE),
1455 	     "When I2C target config is enabled, the buffer mode must be used.");
1456 #endif
1457 
1458 #define I2C_ITE_ENHANCE_INIT(inst)                                              \
1459 	PINCTRL_DT_INST_DEFINE(inst);                                           \
1460 	BUILD_ASSERT((DT_INST_PROP(inst, clock_frequency) ==                    \
1461 		     50000) ||                                                  \
1462 		     (DT_INST_PROP(inst, clock_frequency) ==                    \
1463 		     I2C_BITRATE_STANDARD) ||                                   \
1464 		     (DT_INST_PROP(inst, clock_frequency) ==                    \
1465 		     I2C_BITRATE_FAST) ||                                       \
1466 		     (DT_INST_PROP(inst, clock_frequency) ==                    \
1467 		     I2C_BITRATE_FAST_PLUS), "Not support I2C bit rate value"); \
1468 	static void i2c_enhance_config_func_##inst(void);                       \
1469 										\
1470 	static const struct i2c_enhance_config i2c_enhance_cfg_##inst = {       \
1471 		.base = (uint8_t *)(DT_INST_REG_ADDR(inst)),                    \
1472 		.irq_config_func = i2c_enhance_config_func_##inst,              \
1473 		.bitrate = DT_INST_PROP(inst, clock_frequency),                 \
1474 		.i2c_irq_base = DT_INST_IRQN(inst),                             \
1475 		.port = DT_INST_PROP(inst, port_num),                           \
1476 		.channel_switch_sel = DT_INST_PROP(inst, channel_switch_sel),   \
1477 		.scl_gpios = GPIO_DT_SPEC_INST_GET(inst, scl_gpios),            \
1478 		.sda_gpios = GPIO_DT_SPEC_INST_GET(inst, sda_gpios),            \
1479 		.prescale_scl_low = DT_INST_PROP_OR(inst, prescale_scl_low, 0), \
1480 		.data_hold_time = DT_INST_PROP_OR(inst, data_hold_time, 0),     \
1481 		.clock_gate_offset = DT_INST_PROP(inst, clock_gate_offset),     \
1482 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(inst),                   \
1483 		.target_enable = DT_INST_PROP(inst, target_enable),             \
1484 		.target_pio_mode = DT_INST_PROP(inst, target_pio_mode),         \
1485 	};                                                                      \
1486 										\
1487 	static struct i2c_enhance_data i2c_enhance_data_##inst;                 \
1488 										\
1489 	I2C_DEVICE_DT_INST_DEFINE(inst, i2c_enhance_init,                       \
1490 				  NULL,                                         \
1491 				  &i2c_enhance_data_##inst,                     \
1492 				  &i2c_enhance_cfg_##inst,                      \
1493 				  POST_KERNEL,                                  \
1494 				  CONFIG_I2C_INIT_PRIORITY,                     \
1495 				  &i2c_enhance_driver_api);                     \
1496 										\
1497 	static void i2c_enhance_config_func_##inst(void)                        \
1498 	{                                                                       \
1499 		IRQ_CONNECT(DT_INST_IRQN(inst),                                 \
1500 			0,                                                      \
1501 			i2c_enhance_isr,                                        \
1502 			DEVICE_DT_INST_GET(inst), 0);                           \
1503 	}
1504 
1505 DT_INST_FOREACH_STATUS_OKAY(I2C_ITE_ENHANCE_INIT)
1506