1 /*
2  * Copyright (c) 2020 Nuvoton Technology Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <zephyr/pm/policy.h>
7 
8 #define DT_DRV_COMPAT nuvoton_npcx_i2c_ctrl
9 
10 /**
11  * @file
12  * @brief Nuvoton NPCX smb/i2c module (controller) driver
13  *
14  * This file contains the driver of SMB module (controller) which provides full
15  * support for a two-wire SMBus/I2C synchronous serial interface. The following
16  * is the state diagrams for each Zephyr i2c api functions.
17  *
18  * case 1: i2c_write()/i2c_burst_write()
19  *
20  *                              All msg data sent?    Is there next msg?
21  *                              +<----------------+<----------------------+
22  *                              |       No        |                       | Yes
23  *    +------+   +------------+ |  +------- ----+ |    +------- -------+  |
24  * +->| IDLE |-->| WAIT_START |--->| WRITE_FIFO |-+--->| WRITE_SUSPEND |--+
25  * |  +------+   +------------+    +------------+  Yes +---------------+  |
26  * |      Issue START    START completed                                  | No
27  * |                                            +-----------+             |
28  * +--------------------------------------------| WAIT_STOP |<------------+
29  *             STOP is completed                +-----------+  Issue STOP
30  *
31  *
32  * case 2: i2c_read()
33  *
34  *                             All msg data received?  Is there next msg?
35  *                              +<-----------------+<---------------------+
36  *                              |       No         |                      | Yes
37  *    +------+   +------------+ |  +------- ---+   |    +------- ------+  |
38  * +->| IDLE |-->| WAIT_START |--->| READ_FIFO |---+--->| READ_SUSPEND |--+
39  * |  +------+   +------------+    +------------+   Yes +--------------+  |
40  * |     Issue START     START completed                                  | No
41  * |                                          +-----------+               |
42  * +------------------------------------------| WAIT_STOP |<--------------+
43  *             STOP is completed              +-----------+  Issue STOP
44  *
45  *
46  * case 3: i2c_write_read()/i2c_burst_read()
47  *
48  *                              All msg data sent?  Is there next write msg?
49  *                              +<----------------+<----------------------+
50  *                              |       No        |                       | Yes
51  *    +------+   +------------+ |  +------- ----+ |    +------- -------+  |
52  * +->| IDLE |-->| WAIT_START |--->| WRITE_FIFO |-+--->| WRITE_SUSPEND |--+
53  * |  +------+   +------------+    +------------+  Yes +---------------+  |
54  * |     Issue START     START completed                                  | No
55  * |      +---------------------------------------------------------------+
56  * |      |
57  * |      |                 All msg data received?  Is there next read msg?
58  * |      |                   +<-----------------+<-----------------------+
59  * |      |                   |       No         |                        | Yes
60  * |      |  +--------------+ |  +------- ---+   |    +------- ------+    |
61  * |      +--| WAIT_RESTART |--->| READ_FIFO |---+--->| READ_SUSPEND |----+
62  * |         +--------------+    +-----------+    Yes +--------------+    |
63  * |  Issue RESTART      RESTART completed                                | No
64  * |                                           +-----------+              |
65  * +-------------------------------------------| WAIT_STOP |<-------------+
66  *              STOP is completed              +-----------+  Issue STOP
67  *
68  */
69 
70 #include <assert.h>
71 #include <zephyr/drivers/clock_control.h>
72 #include <zephyr/drivers/i2c.h>
73 #include <zephyr/kernel.h>
74 #include <zephyr/sys/atomic.h>
75 #include <soc.h>
76 
77 #include <zephyr/logging/log.h>
78 #include <zephyr/irq.h>
79 LOG_MODULE_REGISTER(i2c_npcx, CONFIG_I2C_LOG_LEVEL);
80 
81 /* I2C controller mode */
82 #define NPCX_I2C_BANK_NORMAL 0
83 #define NPCX_I2C_BANK_FIFO   1
84 
85 /* Timeout for device should be available after reset (SMBus spec. unit:ms) */
86 #define I2C_MAX_TIMEOUT 35
87 
88 /* Timeout for SCL held to low by slave device . (SMBus spec. unit:ms). */
89 #define I2C_MIN_TIMEOUT 25
90 
91 /* Default maximum time we allow for an I2C transfer (unit:ms) */
92 #define I2C_TRANS_TIMEOUT K_MSEC(100)
93 
94 /*
95  * NPCX I2C module that supports FIFO mode has 32 bytes Tx FIFO and
96  * 32 bytes Rx FIFO.
97  */
98 #define NPCX_I2C_FIFO_MAX_SIZE 32
99 
100 /* Valid bit fields in SMBST register */
101 #define NPCX_VALID_SMBST_MASK ~(BIT(NPCX_SMBST_XMIT) | BIT(NPCX_SMBST_MASTER))
102 
103 /* The delay for the I2C bus recovery bitbang in ~100K Hz */
104 #define I2C_RECOVER_BUS_DELAY_US 5
105 #define I2C_RECOVER_SCL_RETRY    10
106 #define I2C_RECOVER_SDA_RETRY    3
107 
108 /* Supported I2C bus frequency */
109 enum npcx_i2c_freq {
110 	NPCX_I2C_BUS_SPEED_100KHZ,
111 	NPCX_I2C_BUS_SPEED_400KHZ,
112 	NPCX_I2C_BUS_SPEED_1MHZ,
113 };
114 
115 enum npcx_i2c_flag {
116 	NPCX_I2C_FLAG_TARGET,
117 	NPCX_I2C_FLAG_COUNT,
118 };
119 
120 /*
121  * Internal SMBus Interface driver states values, which reflect events
122  * which occurred on the bus
123  */
124 enum npcx_i2c_oper_state {
125 	NPCX_I2C_IDLE,
126 	NPCX_I2C_WAIT_START,
127 	NPCX_I2C_WAIT_RESTART,
128 	NPCX_I2C_WRITE_FIFO,
129 	NPCX_I2C_WRITE_SUSPEND,
130 	NPCX_I2C_READ_FIFO,
131 	NPCX_I2C_READ_SUSPEND,
132 	NPCX_I2C_WAIT_STOP,
133 	NPCX_I2C_ERROR_RECOVERY,
134 };
135 
136 /* I2C timing configuration for each i2c speed */
137 struct npcx_i2c_timing_cfg {
138 	uint8_t HLDT; /* i2c hold-time (Unit: clocks) */
139 	uint8_t k1; /* k1 = SCL low-time (Unit: clocks) */
140 	uint8_t k2; /* k2 = SCL high-time (Unit: clocks) */
141 };
142 
143 /* Device config */
144 struct i2c_ctrl_config {
145 	uintptr_t base; /* i2c controller base address */
146 	struct npcx_clk_cfg clk_cfg; /* clock configuration */
147 	uint8_t irq; /* i2c controller irq */
148 };
149 
150 /* Driver data */
151 struct i2c_ctrl_data {
152 	struct k_sem lock_sem; /* mutex of i2c controller */
153 	struct k_sem sync_sem; /* semaphore used for synchronization */
154 	uint32_t bus_freq; /* operation freq of i2c */
155 	enum npcx_i2c_oper_state oper_state; /* controller operation state */
156 	int trans_err;  /* error code during transaction */
157 	struct i2c_msg *msg; /* cache msg for transaction state machine */
158 	int is_write; /* direction of current msg */
159 	uint8_t *ptr_msg; /* current msg pointer for FIFO read/write */
160 	uint16_t addr; /* slave address of transaction */
161 	uint8_t port; /* current port used the controller */
162 	bool is_configured; /* is port configured? */
163 	const struct npcx_i2c_timing_cfg *ptr_speed_confs;
164 #ifdef CONFIG_I2C_TARGET
165 	struct i2c_target_config *target_cfg;
166 	atomic_t flags;
167 #endif
168 };
169 
170 /* Driver convenience defines */
171 #define HAL_I2C_INSTANCE(dev)                                                                      \
172 	((struct smb_reg *)((const struct i2c_ctrl_config *)(dev)->config)->base)
173 
174 /* Recommended I2C timing values are based on 15 MHz */
175 static const struct npcx_i2c_timing_cfg npcx_15m_speed_confs[] = {
176 	[NPCX_I2C_BUS_SPEED_100KHZ] = {.HLDT = 15, .k1 = 76, .k2 = 0},
177 	[NPCX_I2C_BUS_SPEED_400KHZ] = {.HLDT = 7, .k1 = 24, .k2 = 18,},
178 	[NPCX_I2C_BUS_SPEED_1MHZ] = {.HLDT  = 7, .k1 = 14, .k2 = 10,},
179 };
180 
181 static const struct npcx_i2c_timing_cfg npcx_20m_speed_confs[] = {
182 	[NPCX_I2C_BUS_SPEED_100KHZ] = {.HLDT = 15, .k1 = 102, .k2 = 0},
183 	[NPCX_I2C_BUS_SPEED_400KHZ] = {.HLDT = 7, .k1 = 32, .k2 = 22},
184 	[NPCX_I2C_BUS_SPEED_1MHZ] = {.HLDT  = 7, .k1 = 16, .k2 = 10},
185 };
186 
187 /* I2C controller inline functions access shared registers */
i2c_ctrl_start(const struct device * dev)188 static inline void i2c_ctrl_start(const struct device *dev)
189 {
190 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
191 
192 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_START);
193 }
194 
i2c_ctrl_stop(const struct device * dev)195 static inline void i2c_ctrl_stop(const struct device *dev)
196 {
197 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
198 
199 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_STOP);
200 }
201 
i2c_ctrl_bus_busy(const struct device * dev)202 static inline int i2c_ctrl_bus_busy(const struct device *dev)
203 {
204 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
205 
206 	return IS_BIT_SET(inst->SMBCST, NPCX_SMBCST_BB);
207 }
208 
i2c_ctrl_bank_sel(const struct device * dev,int bank)209 static inline void i2c_ctrl_bank_sel(const struct device *dev, int bank)
210 {
211 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
212 
213 	if (bank) {
214 		inst->SMBCTL3 |= BIT(NPCX_SMBCTL3_BNK_SEL);
215 	} else {
216 		inst->SMBCTL3 &= ~BIT(NPCX_SMBCTL3_BNK_SEL);
217 	}
218 }
219 
i2c_ctrl_irq_enable(const struct device * dev,int enable)220 static inline void i2c_ctrl_irq_enable(const struct device *dev, int enable)
221 {
222 	const struct i2c_ctrl_config *const config = dev->config;
223 
224 	if (enable) {
225 		irq_enable(config->irq);
226 	} else {
227 		irq_disable(config->irq);
228 	}
229 }
230 
231 /* I2C controller inline functions access registers in 'Normal' bank */
i2c_ctrl_norm_stall_scl(const struct device * dev)232 static inline void i2c_ctrl_norm_stall_scl(const struct device *dev)
233 {
234 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
235 
236 	/* Enable writing to SCL_LVL/SDA_LVL bit in SMBnCTL3 */
237 	inst->SMBCTL4 |= BIT(NPCX_SMBCTL4_LVL_WE);
238 	/* Force SCL bus to low and keep SDA floating */
239 	inst->SMBCTL3 = (inst->SMBCTL3 & ~BIT(NPCX_SMBCTL3_SCL_LVL))
240 						| BIT(NPCX_SMBCTL3_SDA_LVL);
241 	/* Disable writing to them */
242 	inst->SMBCTL4 &= ~BIT(NPCX_SMBCTL4_LVL_WE);
243 }
244 
i2c_ctrl_norm_free_scl(const struct device * dev)245 static inline void i2c_ctrl_norm_free_scl(const struct device *dev)
246 {
247 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
248 
249 	/* Enable writing to SCL_LVL/SDA_LVL bit in SMBnCTL3 */
250 	inst->SMBCTL4 |= BIT(NPCX_SMBCTL4_LVL_WE);
251 	/*
252 	 * Release SCL bus. Then it might be still driven by module itself or
253 	 * slave device.
254 	 */
255 	inst->SMBCTL3 |= BIT(NPCX_SMBCTL3_SCL_LVL) | BIT(NPCX_SMBCTL3_SDA_LVL);
256 	/* Disable writing to them */
257 	inst->SMBCTL4 &= ~BIT(NPCX_SMBCTL4_LVL_WE);
258 }
259 
260 /* I2C controller inline functions access registers in 'Normal' bank */
i2c_ctrl_norm_stall_sda(const struct device * dev)261 static inline void i2c_ctrl_norm_stall_sda(const struct device *dev)
262 {
263 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
264 
265 	/* Enable writing to SCL_LVL/SDA_LVL bit in SMBnCTL3 */
266 	inst->SMBCTL4 |= BIT(NPCX_SMBCTL4_LVL_WE);
267 	/* Force SDA bus to low and keep SCL floating */
268 	inst->SMBCTL3 = (inst->SMBCTL3 & ~BIT(NPCX_SMBCTL3_SDA_LVL))
269 						| BIT(NPCX_SMBCTL3_SCL_LVL);
270 	/* Disable writing to them */
271 	inst->SMBCTL4 &= ~BIT(NPCX_SMBCTL4_LVL_WE);
272 }
273 
i2c_ctrl_norm_free_sda(const struct device * dev)274 static inline void i2c_ctrl_norm_free_sda(const struct device *dev)
275 {
276 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
277 
278 	/* Enable writing to SCL_LVL/SDA_LVL bit in SMBnCTL3 */
279 	inst->SMBCTL4 |= BIT(NPCX_SMBCTL4_LVL_WE);
280 	/*
281 	 * Release SDA bus. Then it might be still driven by module itself or
282 	 * slave device.
283 	 */
284 	inst->SMBCTL3 |= BIT(NPCX_SMBCTL3_SDA_LVL) | BIT(NPCX_SMBCTL3_SCL_LVL);
285 	/* Disable writing to them */
286 	inst->SMBCTL4 &= ~BIT(NPCX_SMBCTL4_LVL_WE);
287 }
288 
289 /* I2C controller inline functions access registers in 'FIFO' bank */
i2c_ctrl_fifo_write(const struct device * dev,uint8_t data)290 static inline void i2c_ctrl_fifo_write(const struct device *dev, uint8_t data)
291 {
292 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
293 
294 	inst->SMBSDA = data;
295 }
296 
i2c_ctrl_fifo_read(const struct device * dev)297 static inline uint8_t i2c_ctrl_fifo_read(const struct device *dev)
298 {
299 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
300 
301 	return inst->SMBSDA;
302 }
303 
i2c_ctrl_fifo_tx_avail(const struct device * dev)304 static inline int i2c_ctrl_fifo_tx_avail(const struct device *dev)
305 {
306 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
307 
308 	return NPCX_I2C_FIFO_MAX_SIZE - (inst->SMBTXF_STS & 0x3f);
309 }
310 
i2c_ctrl_fifo_rx_occupied(const struct device * dev)311 static inline int i2c_ctrl_fifo_rx_occupied(const struct device *dev)
312 {
313 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
314 
315 	return inst->SMBRXF_STS & 0x3f;
316 }
317 
i2c_ctrl_fifo_rx_setup_threshold_nack(const struct device * dev,int threshold,int last)318 static inline void i2c_ctrl_fifo_rx_setup_threshold_nack(
319 		const struct device *dev, int threshold, int last)
320 {
321 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
322 	uint8_t value = MIN(threshold, NPCX_I2C_FIFO_MAX_SIZE);
323 
324 	SET_FIELD(inst->SMBRXF_CTL, NPCX_SMBRXF_CTL_RX_THR, value);
325 
326 	/*
327 	 * Is it last received transaction? If so, set LAST bit. Then the
328 	 * hardware will generate NACK automatically when receiving last byte.
329 	 */
330 	if (last && (value == threshold)) {
331 		inst->SMBRXF_CTL |= BIT(NPCX_SMBRXF_CTL_LAST);
332 	}
333 }
334 
i2c_ctrl_fifo_clear_status(const struct device * dev)335 static inline void i2c_ctrl_fifo_clear_status(const struct device *dev)
336 {
337 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
338 
339 	inst->SMBFIF_CTS |= BIT(NPCX_SMBFIF_CTS_CLR_FIFO);
340 }
341 
342 /*
343  * I2C local functions which touch the registers in 'Normal' bank. These
344  * utilities will change bank back to FIFO mode when leaving themselves in case
345  * the other utilities access the registers in 'FIFO' bank.
346  */
i2c_ctrl_hold_bus(const struct device * dev,int stall)347 static void i2c_ctrl_hold_bus(const struct device *dev, int stall)
348 {
349 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_NORMAL);
350 
351 	if (stall) {
352 		i2c_ctrl_norm_stall_scl(dev);
353 	} else {
354 		i2c_ctrl_norm_free_scl(dev);
355 	}
356 
357 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_FIFO);
358 }
359 
i2c_ctrl_init_module(const struct device * dev)360 static void i2c_ctrl_init_module(const struct device *dev)
361 {
362 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
363 
364 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_NORMAL);
365 
366 	/* Enable FIFO mode first */
367 	inst->SMBFIF_CTL |= BIT(NPCX_SMBFIF_CTL_FIFO_EN);
368 
369 	/* Enable module - before configuring CTL1 */
370 	inst->SMBCTL2  |= BIT(NPCX_SMBCTL2_ENABLE);
371 
372 	/* Enable SMB interrupt and 'New Address Match' interrupt source */
373 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
374 
375 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_FIFO);
376 }
377 
i2c_ctrl_config_bus_freq(const struct device * dev,enum npcx_i2c_freq bus_freq)378 static void i2c_ctrl_config_bus_freq(const struct device *dev,
379 						enum npcx_i2c_freq bus_freq)
380 {
381 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
382 	struct i2c_ctrl_data *const data = dev->data;
383 	const struct npcx_i2c_timing_cfg bus_cfg =
384 						data->ptr_speed_confs[bus_freq];
385 
386 	/* Switch to bank 0 to configure bus speed */
387 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_NORMAL);
388 
389 	/* Configure bus speed */
390 	if (bus_freq == NPCX_I2C_BUS_SPEED_100KHZ) {
391 		/* Enable 'Normal' Mode */
392 		inst->SMBCTL3 &= ~(BIT(NPCX_SMBCTL3_400K));
393 		/* Set freq of SCL. For 100KHz, only k1 is used.  */
394 		SET_FIELD(inst->SMBCTL2, NPCX_SMBCTL2_SCLFRQ0_6_FIELD,
395 				bus_cfg.k1/2 & 0x7f);
396 		SET_FIELD(inst->SMBCTL3, NPCX_SMBCTL3_SCLFRQ7_8_FIELD,
397 				bus_cfg.k1/2 >> 7);
398 		SET_FIELD(inst->SMBCTL4, NPCX_SMBCTL4_HLDT_FIELD,
399 				bus_cfg.HLDT);
400 	} else {
401 		/* Enable 'Fast' Mode for 400K or higher freq. */
402 		inst->SMBCTL3 |= BIT(NPCX_SMBCTL3_400K);
403 		/* Set high/low time of SCL and hold-time */
404 		inst->SMBSCLLT = bus_cfg.k1/2;
405 		inst->SMBSCLHT = bus_cfg.k2/2;
406 		SET_FIELD(inst->SMBCTL4, NPCX_SMBCTL4_HLDT_FIELD,
407 				bus_cfg.HLDT);
408 	}
409 
410 	/* Switch to bank 1 to access I2C FIFO registers */
411 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_FIFO);
412 }
413 
414 /* I2C controller local functions */
i2c_ctrl_wait_stop_completed(const struct device * dev,int timeout)415 static int i2c_ctrl_wait_stop_completed(const struct device *dev, int timeout)
416 {
417 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
418 
419 	if (timeout <= 0) {
420 		return -EINVAL;
421 	}
422 
423 	do {
424 		/*
425 		 * Wait till i2c bus is idle. This bit is cleared to 0
426 		 * automatically after the STOP condition is generated.
427 		 */
428 		if (!IS_BIT_SET(inst->SMBCTL1, NPCX_SMBCTL1_STOP)) {
429 			break;
430 		}
431 		k_msleep(1);
432 	} while (--timeout);
433 
434 	if (timeout > 0) {
435 		return 0;
436 	} else {
437 		return -ETIMEDOUT;
438 	}
439 }
440 
i2c_ctrl_is_scl_sda_both_high(const struct device * dev)441 static bool i2c_ctrl_is_scl_sda_both_high(const struct device *dev)
442 {
443 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
444 
445 	if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL) &&
446 	    IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
447 		return true;
448 	}
449 
450 	return false;
451 }
452 
i2c_ctrl_wait_idle_completed(const struct device * dev,int timeout)453 static int i2c_ctrl_wait_idle_completed(const struct device *dev, int timeout)
454 {
455 	if (timeout <= 0) {
456 		return -EINVAL;
457 	}
458 
459 	do {
460 		/* Wait for both SCL & SDA lines are high */
461 		if (i2c_ctrl_is_scl_sda_both_high(dev)) {
462 			break;
463 		}
464 		k_msleep(1);
465 	} while (--timeout);
466 
467 	if (timeout > 0) {
468 		return 0;
469 	} else {
470 		return -ETIMEDOUT;
471 	}
472 }
473 
i2c_ctrl_recovery(const struct device * dev)474 static int i2c_ctrl_recovery(const struct device *dev)
475 {
476 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
477 	struct i2c_ctrl_data *const data = dev->data;
478 	int ret;
479 
480 	if (data->oper_state != NPCX_I2C_ERROR_RECOVERY) {
481 		data->oper_state = NPCX_I2C_ERROR_RECOVERY;
482 	}
483 
484 	/* Step 1: Make sure the bus is not stalled before exit. */
485 	i2c_ctrl_hold_bus(dev, 0);
486 
487 	/*
488 	 * Step 2: Abort data, wait for STOP condition completed.
489 	 * - Clearing NEGACK and BER bits first
490 	 * - Wait for STOP condition completed
491 	 * - Then clear BB (BUS BUSY) bit
492 	 */
493 	inst->SMBST = BIT(NPCX_SMBST_BER) | BIT(NPCX_SMBST_NEGACK);
494 	ret = i2c_ctrl_wait_stop_completed(dev, I2C_MAX_TIMEOUT);
495 	inst->SMBCST |= BIT(NPCX_SMBCST_BB);
496 	if (ret != 0) {
497 		LOG_ERR("Abort i2c port%02x fail! Bus might be stalled.",
498 								data->port);
499 	}
500 
501 	/*
502 	 * Step 3: Reset i2c module to clear all internal state machine of it
503 	 * - Disable the SMB module first
504 	 * - Wait both SCL/SDA line are high
505 	 * - Enable i2c module again
506 	 */
507 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
508 	ret = i2c_ctrl_wait_idle_completed(dev, I2C_MAX_TIMEOUT);
509 	if (ret != 0) {
510 		LOG_ERR("Reset i2c port%02x fail! Bus might be stalled.",
511 								data->port);
512 		return -EIO;
513 	}
514 
515 	/* Reset module and internal state machine */
516 	i2c_ctrl_init_module(dev);
517 
518 	/* Recovery is completed */
519 	data->oper_state = NPCX_I2C_IDLE;
520 	return 0;
521 }
522 
i2c_ctrl_notify(const struct device * dev,int error)523 static void i2c_ctrl_notify(const struct device *dev, int error)
524 {
525 	struct i2c_ctrl_data *const data = dev->data;
526 
527 	data->trans_err = error;
528 	k_sem_give(&data->sync_sem);
529 }
530 
i2c_ctrl_wait_completion(const struct device * dev)531 static int i2c_ctrl_wait_completion(const struct device *dev)
532 {
533 	struct i2c_ctrl_data *const data = dev->data;
534 
535 	if (k_sem_take(&data->sync_sem, I2C_TRANS_TIMEOUT) == 0) {
536 		return data->trans_err;
537 	} else {
538 		return -ETIMEDOUT;
539 	}
540 }
541 
i2c_ctrl_calculate_msg_remains(const struct device * dev)542 size_t i2c_ctrl_calculate_msg_remains(const struct device *dev)
543 {
544 	struct i2c_ctrl_data *const data = dev->data;
545 	uint8_t *buf_end = data->msg->buf + data->msg->len;
546 
547 	return (buf_end > data->ptr_msg) ? (buf_end - data->ptr_msg) : 0;
548 }
549 
i2c_ctrl_handle_write_int_event(const struct device * dev)550 static void i2c_ctrl_handle_write_int_event(const struct device *dev)
551 {
552 	struct i2c_ctrl_data *const data = dev->data;
553 
554 	/* START condition is issued */
555 	if (data->oper_state == NPCX_I2C_WAIT_START) {
556 		/* Write slave address with W bit */
557 		i2c_ctrl_fifo_write(dev, ((data->addr << 1)  & ~BIT(0)));
558 		/* Start to proceed write process */
559 		data->oper_state = NPCX_I2C_WRITE_FIFO;
560 		return;
561 	}
562 
563 	/* Write message data bytes to FIFO */
564 	if (data->oper_state == NPCX_I2C_WRITE_FIFO) {
565 		/* Calculate how many remaining bytes need to transmit */
566 		size_t tx_remain = i2c_ctrl_calculate_msg_remains(dev);
567 		size_t tx_avail = MIN(tx_remain, i2c_ctrl_fifo_tx_avail(dev));
568 
569 		LOG_DBG("tx remains %d, avail %d", tx_remain, tx_avail);
570 		for (int i = 0U; i < tx_avail; i++) {
571 			i2c_ctrl_fifo_write(dev, *(data->ptr_msg++));
572 		}
573 
574 		/* Is there any remaining bytes? */
575 		if (data->ptr_msg == data->msg->buf + data->msg->len) {
576 			data->oper_state = NPCX_I2C_WRITE_SUSPEND;
577 		}
578 		return;
579 	}
580 
581 	/* Issue STOP after sending message? */
582 	if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
583 		if (data->msg->flags & I2C_MSG_STOP) {
584 			/* Generate a STOP condition immediately */
585 			i2c_ctrl_stop(dev);
586 			/* Clear rx FIFO threshold and status bits */
587 			i2c_ctrl_fifo_clear_status(dev);
588 			/* Wait for STOP completed */
589 			data->oper_state = NPCX_I2C_WAIT_STOP;
590 		} else {
591 			/* Disable interrupt and handle next message */
592 			i2c_ctrl_irq_enable(dev, 0);
593 		}
594 	}
595 
596 	i2c_ctrl_notify(dev, 0);
597 }
598 
i2c_ctrl_handle_read_int_event(const struct device * dev)599 static void i2c_ctrl_handle_read_int_event(const struct device *dev)
600 {
601 	struct i2c_ctrl_data *const data = dev->data;
602 
603 	/* START or RESTART condition is issued */
604 	if (data->oper_state == NPCX_I2C_WAIT_START ||
605 			data->oper_state == NPCX_I2C_WAIT_RESTART) {
606 		/* Setup threshold of rx FIFO before sending address byte */
607 		i2c_ctrl_fifo_rx_setup_threshold_nack(dev, data->msg->len,
608 					(data->msg->flags & I2C_MSG_STOP) != 0);
609 		/* Write slave address with R bit */
610 		i2c_ctrl_fifo_write(dev, ((data->addr << 1) | BIT(0)));
611 		/* Start to proceed read process */
612 		data->oper_state = NPCX_I2C_READ_FIFO;
613 		return;
614 	}
615 
616 	/* Read message data bytes from FIFO */
617 	if (data->oper_state == NPCX_I2C_READ_FIFO) {
618 		/* Calculate how many remaining bytes need to receive */
619 		size_t rx_remain = i2c_ctrl_calculate_msg_remains(dev);
620 		size_t rx_occupied = i2c_ctrl_fifo_rx_occupied(dev);
621 
622 		LOG_DBG("rx remains %d, occupied %d", rx_remain, rx_occupied);
623 
624 		/* Is it the last read transaction with STOP condition? */
625 		if (rx_occupied >= rx_remain &&
626 			(data->msg->flags & I2C_MSG_STOP) != 0) {
627 			/*
628 			 * Generate a STOP condition before reading data bytes
629 			 * from FIFO. It prevents a glitch on SCL.
630 			 */
631 			i2c_ctrl_stop(dev);
632 		} else {
633 			/*
634 			 * Hold SCL line here in case the hardware releases bus
635 			 * immediately after the driver start to read data from
636 			 * FIFO. Then we might lose incoming data from device.
637 			 */
638 			i2c_ctrl_hold_bus(dev, 1);
639 		}
640 
641 		/* Read data bytes from FIFO */
642 		for (int i = 0; i < rx_occupied; i++) {
643 			*(data->ptr_msg++) = i2c_ctrl_fifo_read(dev);
644 		}
645 		rx_remain = i2c_ctrl_calculate_msg_remains(dev);
646 
647 		/* Setup threshold of RX FIFO if needed */
648 		if (rx_remain > 0) {
649 			i2c_ctrl_fifo_rx_setup_threshold_nack(dev, rx_remain,
650 					(data->msg->flags & I2C_MSG_STOP) != 0);
651 			/* Release bus */
652 			i2c_ctrl_hold_bus(dev, 0);
653 			return;
654 		}
655 	}
656 
657 	/* Is the STOP condition issued? */
658 	if ((data->msg->flags & I2C_MSG_STOP) != 0) {
659 		/* Clear rx FIFO threshold and status bits */
660 		i2c_ctrl_fifo_clear_status(dev);
661 
662 		/* Wait for STOP completed */
663 		data->oper_state = NPCX_I2C_WAIT_STOP;
664 	} else {
665 		/* Disable i2c interrupt first */
666 		i2c_ctrl_irq_enable(dev, 0);
667 		data->oper_state = NPCX_I2C_READ_SUSPEND;
668 	}
669 
670 	i2c_ctrl_notify(dev, 0);
671 }
672 
i2c_ctrl_proc_write_msg(const struct device * dev,struct i2c_msg * msg)673 static int i2c_ctrl_proc_write_msg(const struct device *dev,
674 							struct i2c_msg *msg)
675 {
676 	struct i2c_ctrl_data *const data = dev->data;
677 
678 	data->is_write = 1;
679 	data->ptr_msg = msg->buf;
680 	data->msg = msg;
681 
682 	if (data->oper_state == NPCX_I2C_IDLE) {
683 		data->oper_state = NPCX_I2C_WAIT_START;
684 
685 		/* Clear FIFO status before starting a new transaction */
686 		i2c_ctrl_fifo_clear_status(dev);
687 
688 		/* Issue a START, wait for transaction completed */
689 		i2c_ctrl_start(dev);
690 
691 		return i2c_ctrl_wait_completion(dev);
692 	} else if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
693 		data->oper_state = NPCX_I2C_WRITE_FIFO;
694 		i2c_ctrl_irq_enable(dev, 1);
695 
696 		return i2c_ctrl_wait_completion(dev);
697 	}
698 
699 	LOG_ERR("Unexpected state %d during writing i2c port%02x!",
700 					data->oper_state, data->port);
701 	data->trans_err = -EIO;
702 	return data->trans_err;
703 }
704 
i2c_ctrl_proc_read_msg(const struct device * dev,struct i2c_msg * msg)705 static int i2c_ctrl_proc_read_msg(const struct device *dev, struct i2c_msg *msg)
706 {
707 	struct i2c_ctrl_data *const data = dev->data;
708 
709 	data->is_write = 0;
710 	data->ptr_msg = msg->buf;
711 	data->msg = msg;
712 
713 	if (data->oper_state == NPCX_I2C_IDLE) {
714 		data->oper_state = NPCX_I2C_WAIT_START;
715 
716 		/* Clear FIFO status before starting a new transaction */
717 		i2c_ctrl_fifo_clear_status(dev);
718 
719 		/* Issue a START, wait for transaction completed */
720 		i2c_ctrl_start(dev);
721 
722 		return i2c_ctrl_wait_completion(dev);
723 	} else if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
724 		data->oper_state = NPCX_I2C_WAIT_RESTART;
725 		/* Issue a RESTART, wait for transaction completed */
726 		i2c_ctrl_start(dev);
727 		i2c_ctrl_irq_enable(dev, 1);
728 
729 		return i2c_ctrl_wait_completion(dev);
730 	} else if (data->oper_state == NPCX_I2C_READ_SUSPEND) {
731 		data->oper_state = NPCX_I2C_READ_FIFO;
732 
733 		/* Setup threshold of RX FIFO first */
734 		i2c_ctrl_fifo_rx_setup_threshold_nack(dev, msg->len,
735 				(msg->flags & I2C_MSG_STOP) != 0);
736 
737 		/* Release bus */
738 		i2c_ctrl_hold_bus(dev, 0);
739 
740 		/* Enable i2c interrupt first */
741 		i2c_ctrl_irq_enable(dev, 1);
742 		return i2c_ctrl_wait_completion(dev);
743 	}
744 
745 	LOG_ERR("Unexpected state  %d during reading i2c port%02x!",
746 					data->oper_state, data->port);
747 	data->trans_err = -EIO;
748 	return data->trans_err;
749 }
750 
751 /* I2C controller isr function */
752 #ifdef CONFIG_I2C_TARGET
i2c_ctrl_target_isr(const struct device * dev,uint8_t status)753 static void i2c_ctrl_target_isr(const struct device *dev, uint8_t status)
754 {
755 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
756 	struct i2c_ctrl_data *const data = dev->data;
757 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
758 	uint8_t val = 0;
759 
760 	/* A 'Bus Error' has been identified */
761 	if (IS_BIT_SET(status, NPCX_SMBST_BER)) {
762 		/* Clear BER Bit */
763 		inst->SMBST = BIT(NPCX_SMBST_BER);
764 
765 		/* Notify upper layer the end of transaction */
766 		if (target_cb->stop) {
767 			target_cb->stop(data->target_cfg);
768 		}
769 
770 		/* Reset i2c module in target mode */
771 		inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
772 		inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
773 
774 		/*
775 		 * Re-enable interrupts because they are turned off after the SMBus module
776 		 * is reset above.
777 		 */
778 		inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
779 		/* End of transaction */
780 		data->oper_state = NPCX_I2C_IDLE;
781 
782 		LOG_DBG("target: Bus error on port%02x!", data->port);
783 		return;
784 	}
785 
786 	/* A 'Slave Stop' Condition has been identified */
787 	if (IS_BIT_SET(status, NPCX_SMBST_SLVSTP)) {
788 		/* Clear SLVSTP Bit */
789 		inst->SMBST = BIT(NPCX_SMBST_SLVSTP);
790 		/* End of transaction */
791 		data->oper_state = NPCX_I2C_IDLE;
792 		/* Notify upper layer a STOP condition received */
793 		if (target_cb->stop) {
794 			target_cb->stop(data->target_cfg);
795 		}
796 		return;
797 	}
798 
799 	/* A negative acknowledge has occurred */
800 	if (IS_BIT_SET(status, NPCX_SMBST_NEGACK)) {
801 		/* Clear NEGACK Bit */
802 		inst->SMBST = BIT(NPCX_SMBST_NEGACK);
803 		/* Do nothing in i2c target mode */
804 		return;
805 	}
806 
807 	/* A 'Target Address Match' has been identified */
808 	if (IS_BIT_SET(status, NPCX_SMBST_NMATCH)) {
809 		/* Clear NMATCH Bit */
810 		inst->SMBST = BIT(NPCX_SMBST_NMATCH);
811 
812 		/* Distinguish the direction of i2c target mode by reading XMIT bit */
813 		if (IS_BIT_SET(inst->SMBST, NPCX_SMBST_XMIT)) {
814 			/* Start transmitting data in i2c target mode */
815 			data->oper_state = NPCX_I2C_WRITE_FIFO;
816 			/* Write first requested byte after repeated start */
817 			if (target_cb->read_requested) {
818 				target_cb->read_requested(data->target_cfg, &val);
819 			}
820 			inst->SMBSDA = val;
821 		} else {
822 			/* Start receiving data in i2c target mode */
823 			data->oper_state = NPCX_I2C_READ_FIFO;
824 
825 			if (target_cb->write_requested) {
826 				target_cb->write_requested(data->target_cfg);
827 			}
828 		}
829 		return;
830 	}
831 
832 	/* Tx byte empty or Rx byte full has occurred */
833 	if (IS_BIT_SET(status, NPCX_SMBST_SDAST)) {
834 		if (data->oper_state == NPCX_I2C_WRITE_FIFO) {
835 			/* Notify upper layer one byte will be transmitted */
836 			if (target_cb->read_processed) {
837 				target_cb->read_processed(data->target_cfg, &val);
838 			}
839 			inst->SMBSDA = val;
840 		} else if (data->oper_state == NPCX_I2C_READ_FIFO) {
841 			if (target_cb->write_received) {
842 				val = inst->SMBSDA;
843 				/* Notify upper layer one byte received */
844 				target_cb->write_received(data->target_cfg, val);
845 			}
846 		} else {
847 			LOG_ERR("Unexpected oper state %d on i2c target port%02x!",
848 				data->oper_state, data->port);
849 		}
850 		return;
851 	}
852 
853 	/* Clear unexpected status bits */
854 	if (status != 0) {
855 		inst->SMBST = status;
856 		LOG_ERR("Unexpected  SMBST 0x%02x occurred on i2c target port%02x!",
857 			status, data->port);
858 	}
859 }
860 #endif
861 
862 /* I2C controller isr function */
i2c_ctrl_isr(const struct device * dev)863 static void i2c_ctrl_isr(const struct device *dev)
864 {
865 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
866 	struct i2c_ctrl_data *const data = dev->data;
867 	uint8_t status, tmp;
868 
869 	status = inst->SMBST & NPCX_VALID_SMBST_MASK;
870 	LOG_DBG("status: %02x, %d", status, data->oper_state);
871 
872 #ifdef CONFIG_I2C_TARGET
873 	if (atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
874 		i2c_ctrl_target_isr(dev, status);
875 		return;
876 	}
877 #endif
878 
879 	/* A 'Bus Error' has been identified */
880 	if (IS_BIT_SET(status, NPCX_SMBST_BER)) {
881 		/* Generate a STOP condition immediately */
882 		i2c_ctrl_stop(dev);
883 
884 		/* Clear BER Bit */
885 		inst->SMBST = BIT(NPCX_SMBST_BER);
886 
887 		/* Make sure slave doesn't hold bus by reading FIFO again */
888 		tmp = i2c_ctrl_fifo_read(dev);
889 
890 		LOG_ERR("Bus error occurred on i2c port%02x!", data->port);
891 		data->oper_state = NPCX_I2C_ERROR_RECOVERY;
892 
893 		/* I/O error occurred */
894 		i2c_ctrl_notify(dev, -EIO);
895 		return;
896 	}
897 
898 	/* A negative acknowledge has occurred */
899 	if (IS_BIT_SET(status, NPCX_SMBST_NEGACK)) {
900 		/* Generate a STOP condition immediately */
901 		i2c_ctrl_stop(dev);
902 
903 		/* Clear NEGACK Bit */
904 		inst->SMBST = BIT(NPCX_SMBST_NEGACK);
905 
906 		/* End transaction */
907 		data->oper_state = NPCX_I2C_WAIT_STOP;
908 
909 		/* No such device or address */
910 		i2c_ctrl_notify(dev, -ENXIO);
911 		return;
912 	}
913 
914 	/* START, tx FIFO empty or rx FIFO full has occurred */
915 	if (IS_BIT_SET(status, NPCX_SMBST_SDAST)) {
916 		if (data->is_write) {
917 			i2c_ctrl_handle_write_int_event(dev);
918 		} else {
919 			i2c_ctrl_handle_read_int_event(dev);
920 		}
921 		return;
922 	}
923 
924 	/* Clear unexpected status bits */
925 	if (status != 0) {
926 		inst->SMBST = status;
927 		LOG_ERR("Unexpected  SMBST 0x%02x occurred on i2c port%02x!",
928 			status, data->port);
929 	}
930 }
931 
932 /* NPCX specific I2C controller functions */
npcx_i2c_ctrl_mutex_lock(const struct device * i2c_dev)933 void npcx_i2c_ctrl_mutex_lock(const struct device *i2c_dev)
934 {
935 	struct i2c_ctrl_data *const data = i2c_dev->data;
936 
937 	k_sem_take(&data->lock_sem, K_FOREVER);
938 }
939 
npcx_i2c_ctrl_mutex_unlock(const struct device * i2c_dev)940 void npcx_i2c_ctrl_mutex_unlock(const struct device *i2c_dev)
941 {
942 	struct i2c_ctrl_data *const data = i2c_dev->data;
943 
944 	k_sem_give(&data->lock_sem);
945 }
946 
npcx_i2c_ctrl_configure(const struct device * i2c_dev,uint32_t dev_config)947 int npcx_i2c_ctrl_configure(const struct device *i2c_dev, uint32_t dev_config)
948 {
949 	struct i2c_ctrl_data *const data = i2c_dev->data;
950 
951 	switch (I2C_SPEED_GET(dev_config)) {
952 	case I2C_SPEED_STANDARD:
953 		data->bus_freq = NPCX_I2C_BUS_SPEED_100KHZ;
954 		break;
955 	case I2C_SPEED_FAST:
956 		data->bus_freq = NPCX_I2C_BUS_SPEED_400KHZ;
957 		break;
958 	case I2C_SPEED_FAST_PLUS:
959 		data->bus_freq = NPCX_I2C_BUS_SPEED_1MHZ;
960 		break;
961 	default:
962 		return -ERANGE;
963 	}
964 
965 	i2c_ctrl_config_bus_freq(i2c_dev, data->bus_freq);
966 	data->is_configured = true;
967 
968 	return 0;
969 }
970 
npcx_i2c_ctrl_get_speed(const struct device * i2c_dev,uint32_t * speed)971 int npcx_i2c_ctrl_get_speed(const struct device *i2c_dev, uint32_t *speed)
972 {
973 	struct i2c_ctrl_data *const data = i2c_dev->data;
974 
975 	if (!data->is_configured) {
976 		return -EIO;
977 	}
978 
979 	switch (data->bus_freq) {
980 	case NPCX_I2C_BUS_SPEED_100KHZ:
981 		*speed = I2C_SPEED_SET(I2C_SPEED_STANDARD);
982 		break;
983 	case NPCX_I2C_BUS_SPEED_400KHZ:
984 		*speed = I2C_SPEED_SET(I2C_SPEED_FAST);
985 		break;
986 	case NPCX_I2C_BUS_SPEED_1MHZ:
987 		*speed = I2C_SPEED_SET(I2C_SPEED_FAST_PLUS);
988 		break;
989 	default:
990 		return -ERANGE;
991 	}
992 
993 	return 0;
994 }
995 
npcx_i2c_ctrl_recover_bus(const struct device * dev)996 int npcx_i2c_ctrl_recover_bus(const struct device *dev)
997 {
998 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
999 	int ret = 0;
1000 
1001 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_NORMAL);
1002 
1003 	/*
1004 	 * When the SCL is low, wait for a while in case of the clock is stalled
1005 	 * by a I2C target.
1006 	 */
1007 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1008 		for (int i = 0;; i++) {
1009 			if (i >= I2C_RECOVER_SCL_RETRY) {
1010 				ret = -EBUSY;
1011 				goto recover_exit;
1012 			}
1013 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1014 			if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1015 				break;
1016 			}
1017 		}
1018 	}
1019 
1020 	if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1021 		goto recover_exit;
1022 	}
1023 
1024 	for (int i = 0; i < I2C_RECOVER_SDA_RETRY; i++) {
1025 		/* Drive the clock high. */
1026 		i2c_ctrl_norm_free_scl(dev);
1027 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1028 
1029 		/*
1030 		 * Toggle SCL to generate 9 clocks. If the I2C target releases the SDA, we can stop
1031 		 * toggle the SCL and issue a STOP.
1032 		 */
1033 		for (int j = 0; j < 9; j++) {
1034 			if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1035 				break;
1036 			}
1037 
1038 			i2c_ctrl_norm_stall_scl(dev);
1039 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1040 			i2c_ctrl_norm_free_scl(dev);
1041 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1042 		}
1043 
1044 		/* Drive the SDA line to issue STOP. */
1045 		i2c_ctrl_norm_stall_sda(dev);
1046 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1047 		i2c_ctrl_norm_free_sda(dev);
1048 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1049 
1050 		if (i2c_ctrl_is_scl_sda_both_high(dev)) {
1051 			ret = 0;
1052 			goto recover_exit;
1053 		}
1054 	}
1055 
1056 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1057 		LOG_ERR("Recover SDA fail");
1058 		ret = -EBUSY;
1059 	}
1060 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1061 		LOG_ERR("Recover SCL fail");
1062 		ret = -EBUSY;
1063 	}
1064 
1065 recover_exit:
1066 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_FIFO);
1067 
1068 	return ret;
1069 }
1070 
1071 #ifdef CONFIG_I2C_TARGET
npcx_i2c_ctrl_target_register(const struct device * i2c_dev,struct i2c_target_config * target_cfg,uint8_t port)1072 int npcx_i2c_ctrl_target_register(const struct device *i2c_dev,
1073 				 struct i2c_target_config *target_cfg, uint8_t port)
1074 {
1075 	struct smb_reg *const inst = HAL_I2C_INSTANCE(i2c_dev);
1076 	struct i2c_ctrl_data *const data = i2c_dev->data;
1077 	int idx_ctrl = (port & 0xF0) >> 4;
1078 	int idx_port = (port & 0x0F);
1079 	uint8_t addr = BIT(NPCX_SMBADDR1_SAEN) | target_cfg->address;
1080 
1081 	/* I2c module has been configured to target mode */
1082 	if (atomic_test_and_set_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1083 		return -EBUSY;
1084 	}
1085 
1086 	/* A transiaction is ongoing */
1087 	if (data->oper_state != NPCX_I2C_IDLE) {
1088 		atomic_clear_bit(&data->flags, NPCX_I2C_FLAG_TARGET);
1089 		return -EBUSY;
1090 	}
1091 
1092 	data->target_cfg = target_cfg;
1093 
1094 	i2c_ctrl_irq_enable(i2c_dev, 0);
1095 	/* Switch correct port for i2c controller first */
1096 	npcx_pinctrl_i2c_port_sel(idx_ctrl, idx_port);
1097 	/* Reset I2C module */
1098 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
1099 	inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
1100 
1101 	/* Select normal bank and single byte mode for i2c target mode */
1102 	i2c_ctrl_bank_sel(i2c_dev, NPCX_I2C_BANK_NORMAL);
1103 	inst->SMBFIF_CTL &= ~BIT(NPCX_SMBFIF_CTL_FIFO_EN);
1104 	inst->SMBADDR1 = addr; /* Enable target mode and configure its address */
1105 
1106 	/* Reconfigure SMBCTL1 */
1107 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
1108 	i2c_ctrl_irq_enable(i2c_dev, 1);
1109 
1110 	return 0;
1111 }
1112 
npcx_i2c_ctrl_target_unregister(const struct device * i2c_dev,struct i2c_target_config * target_cfg)1113 int npcx_i2c_ctrl_target_unregister(const struct device *i2c_dev,
1114 				   struct i2c_target_config *target_cfg)
1115 {
1116 	struct smb_reg *const inst = HAL_I2C_INSTANCE(i2c_dev);
1117 	struct i2c_ctrl_data *const data = i2c_dev->data;
1118 
1119 	/* No I2c module has been configured to target mode */
1120 	if (!atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1121 		return -EINVAL;
1122 	}
1123 
1124 	/* A transiaction is ongoing */
1125 	if (data->oper_state != NPCX_I2C_IDLE) {
1126 		return -EBUSY;
1127 	}
1128 	data->target_cfg = NULL;
1129 
1130 	i2c_ctrl_irq_enable(i2c_dev, 0);
1131 	/* Reset I2C module */
1132 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
1133 	inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
1134 
1135 	inst->SMBADDR1 = 0; /* Disable target mode and clear address setting */
1136 	/* Enable FIFO mode and select to FIFO bank for i2c controller mode */
1137 	inst->SMBFIF_CTL |= BIT(NPCX_SMBFIF_CTL_FIFO_EN);
1138 	i2c_ctrl_bank_sel(i2c_dev, NPCX_I2C_BANK_FIFO);
1139 
1140 	/* Reconfigure SMBCTL1 */
1141 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
1142 	i2c_ctrl_irq_enable(i2c_dev, 1);
1143 
1144 	/* Mark it as controller mode */
1145 	atomic_clear_bit(&data->flags, NPCX_I2C_FLAG_TARGET);
1146 
1147 	return 0;
1148 }
1149 #endif
1150 
npcx_i2c_ctrl_transfer(const struct device * i2c_dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,int port)1151 int npcx_i2c_ctrl_transfer(const struct device *i2c_dev, struct i2c_msg *msgs,
1152 			      uint8_t num_msgs, uint16_t addr, int port)
1153 {
1154 	struct i2c_ctrl_data *const data = i2c_dev->data;
1155 	int ret = 0;
1156 	uint8_t i;
1157 
1158 #ifdef CONFIG_I2C_TARGET
1159 	/* I2c module has been configured to target mode */
1160 	if (atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1161 		return -EBUSY;
1162 	}
1163 #endif
1164 
1165 	/*
1166 	 * suspend-to-idle stops SMB module clocks (derived from APB2/APB3), which must remain
1167 	 * active during a transaction
1168 	 */
1169 	pm_policy_state_lock_get(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
1170 
1171 	/* Does bus need recovery? */
1172 	if (data->oper_state != NPCX_I2C_WRITE_SUSPEND &&
1173 			data->oper_state != NPCX_I2C_READ_SUSPEND) {
1174 		if (i2c_ctrl_bus_busy(i2c_dev) || !i2c_ctrl_is_scl_sda_both_high(i2c_dev) ||
1175 		    data->oper_state == NPCX_I2C_ERROR_RECOVERY) {
1176 			ret = npcx_i2c_ctrl_recover_bus(i2c_dev);
1177 			if (ret != 0) {
1178 				LOG_ERR("Recover Bus failed");
1179 				goto out;
1180 			}
1181 
1182 			ret = i2c_ctrl_recovery(i2c_dev);
1183 			/* Recovery failed, return it immediately */
1184 			if (ret) {
1185 				goto out;
1186 			}
1187 		}
1188 	}
1189 
1190 	/* Start i2c transaction */
1191 	data->port = port;
1192 	data->trans_err = 0;
1193 	data->addr = addr;
1194 
1195 	/*
1196 	 * Reset i2c event-completed semaphore before starting transactions.
1197 	 * Some interrupt events such as BUS_ERROR might change its counter
1198 	 * when bus is idle.
1199 	 */
1200 	k_sem_reset(&data->sync_sem);
1201 
1202 	for (i = 0U; i < num_msgs; i++) {
1203 		struct i2c_msg *msg = msgs + i;
1204 
1205 		/* Handle write transaction */
1206 		if ((msg->flags & I2C_MSG_RW_MASK) == I2C_MSG_WRITE) {
1207 			ret = i2c_ctrl_proc_write_msg(i2c_dev, msg);
1208 		} else {/* Handle read transaction */
1209 			ret = i2c_ctrl_proc_read_msg(i2c_dev, msg);
1210 		}
1211 		if (ret < 0) {
1212 			break;
1213 		}
1214 	}
1215 
1216 	/* Check STOP completed? */
1217 	if (data->oper_state == NPCX_I2C_WAIT_STOP) {
1218 		data->trans_err = i2c_ctrl_wait_stop_completed(i2c_dev,
1219 							I2C_MIN_TIMEOUT);
1220 		if (data->trans_err == 0) {
1221 			data->oper_state = NPCX_I2C_IDLE;
1222 		} else {
1223 			LOG_ERR("STOP fail! bus is held on i2c port%02x!",
1224 								data->port);
1225 			data->oper_state = NPCX_I2C_ERROR_RECOVERY;
1226 		}
1227 	}
1228 
1229 	if (data->oper_state == NPCX_I2C_ERROR_RECOVERY || ret == -ETIMEDOUT) {
1230 		int recovery_error = i2c_ctrl_recovery(i2c_dev);
1231 		/*
1232 		 * Recovery failed, return it immediately. Otherwise, the upper
1233 		 * layer still needs to know why the transaction failed.
1234 		 */
1235 		if (recovery_error != 0) {
1236 			ret = recovery_error;
1237 		}
1238 	}
1239 
1240 out:
1241 	pm_policy_state_lock_put(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
1242 	return ret;
1243 }
1244 
1245 /* I2C controller driver registration */
i2c_ctrl_init(const struct device * dev)1246 static int i2c_ctrl_init(const struct device *dev)
1247 {
1248 	const struct i2c_ctrl_config *const config = dev->config;
1249 	struct i2c_ctrl_data *const data = dev->data;
1250 	const struct device *const clk_dev = DEVICE_DT_GET(NPCX_CLK_CTRL_NODE);
1251 	uint32_t i2c_rate;
1252 
1253 	if (!device_is_ready(clk_dev)) {
1254 		LOG_ERR("clock control device not ready");
1255 		return -ENODEV;
1256 	}
1257 
1258 	/* Turn on device clock first and get source clock freq. */
1259 	if (clock_control_on(clk_dev,
1260 		(clock_control_subsys_t) &config->clk_cfg) != 0) {
1261 		LOG_ERR("Turn on %s clock fail.", dev->name);
1262 		return -EIO;
1263 	}
1264 
1265 	/*
1266 	 * If apb2/3's clock is not 15MHz, we need to add the other timing
1267 	 * configuration of the device to meet SMBus timing spec. Please refer
1268 	 * Table 21/22/23 and section 7.5.9 SMBus Timing for more detail.
1269 	 */
1270 	if (clock_control_get_rate(clk_dev, (clock_control_subsys_t)
1271 			&config->clk_cfg, &i2c_rate) != 0) {
1272 		LOG_ERR("Get %s clock rate error.", dev->name);
1273 		return -EIO;
1274 	}
1275 
1276 	if (i2c_rate == 15000000) {
1277 		data->ptr_speed_confs = npcx_15m_speed_confs;
1278 	} else if (i2c_rate == 20000000) {
1279 		data->ptr_speed_confs = npcx_20m_speed_confs;
1280 	} else {
1281 		LOG_ERR("Unsupported apb2/3 freq for %s.", dev->name);
1282 		return -EIO;
1283 	}
1284 
1285 	/* Initialize i2c module */
1286 	i2c_ctrl_init_module(dev);
1287 
1288 	/* initialize mutex and semaphore for i2c/smb controller */
1289 	k_sem_init(&data->lock_sem, 1, 1);
1290 	k_sem_init(&data->sync_sem, 0, K_SEM_MAX_LIMIT);
1291 
1292 	/* Initialize driver status machine */
1293 	data->oper_state = NPCX_I2C_IDLE;
1294 
1295 	return 0;
1296 }
1297 
1298 /* I2C controller init macro functions */
1299 #define NPCX_I2C_CTRL_INIT_FUNC(inst) _CONCAT(i2c_ctrl_init_, inst)
1300 #define NPCX_I2C_CTRL_INIT_FUNC_DECL(inst) \
1301 	static int i2c_ctrl_init_##inst(const struct device *dev)
1302 #define NPCX_I2C_CTRL_INIT_FUNC_IMPL(inst)                                     \
1303 	static int i2c_ctrl_init_##inst(const struct device *dev)              \
1304 	{	                                                               \
1305 		int ret;                                                       \
1306 									       \
1307 		ret = i2c_ctrl_init(dev);                                      \
1308 		IRQ_CONNECT(DT_INST_IRQN(inst),		                       \
1309 			DT_INST_IRQ(inst, priority),                           \
1310 			i2c_ctrl_isr,                                          \
1311 			DEVICE_DT_INST_GET(inst),                              \
1312 			0);                                                    \
1313 		irq_enable(DT_INST_IRQN(inst));                                \
1314 									       \
1315 		return ret;                                                    \
1316 	}
1317 
1318 
1319 #define NPCX_I2C_CTRL_INIT(inst)                                               \
1320 	NPCX_I2C_CTRL_INIT_FUNC_DECL(inst);                                    \
1321 									       \
1322 	static const struct i2c_ctrl_config i2c_ctrl_cfg_##inst = {            \
1323 		.base = DT_INST_REG_ADDR(inst),                                \
1324 		.irq = DT_INST_IRQN(inst),                                     \
1325 		.clk_cfg = NPCX_DT_CLK_CFG_ITEM(inst),                         \
1326 	};                                                                     \
1327 									       \
1328 	static struct i2c_ctrl_data i2c_ctrl_data_##inst;                      \
1329 									       \
1330 	DEVICE_DT_INST_DEFINE(inst,                                            \
1331 			    NPCX_I2C_CTRL_INIT_FUNC(inst),                     \
1332 			    NULL,                                              \
1333 			    &i2c_ctrl_data_##inst, &i2c_ctrl_cfg_##inst,       \
1334 			    PRE_KERNEL_1, CONFIG_I2C_INIT_PRIORITY,            \
1335 			    NULL);                                             \
1336 									       \
1337 	NPCX_I2C_CTRL_INIT_FUNC_IMPL(inst)
1338 
1339 DT_INST_FOREACH_STATUS_OKAY(NPCX_I2C_CTRL_INIT)
1340