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, LOG_LEVEL_ERR);
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 		k_msleep(1);
431 	} while (--timeout);
432 
433 	if (timeout > 0) {
434 		return 0;
435 	} else {
436 		return -ETIMEDOUT;
437 	}
438 }
439 
i2c_ctrl_is_scl_sda_both_high(const struct device * dev)440 static bool i2c_ctrl_is_scl_sda_both_high(const struct device *dev)
441 {
442 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
443 
444 	if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL) &&
445 	    IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
446 		return true;
447 	}
448 
449 	return false;
450 }
451 
i2c_ctrl_wait_idle_completed(const struct device * dev,int timeout)452 static int i2c_ctrl_wait_idle_completed(const struct device *dev, int timeout)
453 {
454 	if (timeout <= 0) {
455 		return -EINVAL;
456 	}
457 
458 	do {
459 		/* Wait for both SCL & SDA lines are high */
460 		if (i2c_ctrl_is_scl_sda_both_high(dev)) {
461 			break;
462 		}
463 		k_msleep(1);
464 	} while (--timeout);
465 
466 	if (timeout > 0) {
467 		return 0;
468 	} else {
469 		return -ETIMEDOUT;
470 	}
471 }
472 
i2c_ctrl_recovery(const struct device * dev)473 static int i2c_ctrl_recovery(const struct device *dev)
474 {
475 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
476 	struct i2c_ctrl_data *const data = dev->data;
477 	int ret;
478 
479 	if (data->oper_state != NPCX_I2C_ERROR_RECOVERY) {
480 		data->oper_state = NPCX_I2C_ERROR_RECOVERY;
481 	}
482 
483 	/* Step 1: Make sure the bus is not stalled before exit. */
484 	i2c_ctrl_hold_bus(dev, 0);
485 
486 	/*
487 	 * Step 2: Abort data, wait for STOP condition completed.
488 	 * - Clearing NEGACK and BER bits first
489 	 * - Wait for STOP condition completed
490 	 * - Then clear BB (BUS BUSY) bit
491 	 */
492 	inst->SMBST = BIT(NPCX_SMBST_BER) | BIT(NPCX_SMBST_NEGACK);
493 	ret = i2c_ctrl_wait_stop_completed(dev, I2C_MAX_TIMEOUT);
494 	inst->SMBCST |= BIT(NPCX_SMBCST_BB);
495 	if (ret != 0) {
496 		LOG_ERR("Abort i2c port%02x fail! Bus might be stalled.",
497 								data->port);
498 	}
499 
500 	/*
501 	 * Step 3: Reset i2c module to clear all internal state machine of it
502 	 * - Disable the SMB module first
503 	 * - Wait both SCL/SDA line are high
504 	 * - Enable i2c module again
505 	 */
506 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
507 	ret = i2c_ctrl_wait_idle_completed(dev, I2C_MAX_TIMEOUT);
508 	if (ret != 0) {
509 		LOG_ERR("Reset i2c port%02x fail! Bus might be stalled.",
510 								data->port);
511 		return -EIO;
512 	}
513 
514 	/* Reset module and internal state machine */
515 	i2c_ctrl_init_module(dev);
516 
517 	/* Recovery is completed */
518 	data->oper_state = NPCX_I2C_IDLE;
519 	return 0;
520 }
521 
i2c_ctrl_notify(const struct device * dev,int error)522 static void i2c_ctrl_notify(const struct device *dev, int error)
523 {
524 	struct i2c_ctrl_data *const data = dev->data;
525 
526 	data->trans_err = error;
527 	k_sem_give(&data->sync_sem);
528 }
529 
i2c_ctrl_wait_completion(const struct device * dev)530 static int i2c_ctrl_wait_completion(const struct device *dev)
531 {
532 	struct i2c_ctrl_data *const data = dev->data;
533 
534 	if (k_sem_take(&data->sync_sem, I2C_TRANS_TIMEOUT) == 0) {
535 		return data->trans_err;
536 	} else {
537 		return -ETIMEDOUT;
538 	}
539 }
540 
i2c_ctrl_calculate_msg_remains(const struct device * dev)541 size_t i2c_ctrl_calculate_msg_remains(const struct device *dev)
542 {
543 	struct i2c_ctrl_data *const data = dev->data;
544 	uint8_t *buf_end = data->msg->buf + data->msg->len;
545 
546 	return (buf_end > data->ptr_msg) ? (buf_end - data->ptr_msg) : 0;
547 }
548 
i2c_ctrl_handle_write_int_event(const struct device * dev)549 static void i2c_ctrl_handle_write_int_event(const struct device *dev)
550 {
551 	struct i2c_ctrl_data *const data = dev->data;
552 
553 	/* START condition is issued */
554 	if (data->oper_state == NPCX_I2C_WAIT_START) {
555 		/* Write slave address with W bit */
556 		i2c_ctrl_fifo_write(dev, ((data->addr << 1)  & ~BIT(0)));
557 		/* Start to proceed write process */
558 		data->oper_state = NPCX_I2C_WRITE_FIFO;
559 		return;
560 	}
561 
562 	/* Write message data bytes to FIFO */
563 	if (data->oper_state == NPCX_I2C_WRITE_FIFO) {
564 		/* Calculate how many remaining bytes need to transmit */
565 		size_t tx_remain = i2c_ctrl_calculate_msg_remains(dev);
566 		size_t tx_avail = MIN(tx_remain, i2c_ctrl_fifo_tx_avail(dev));
567 
568 		LOG_DBG("tx remains %d, avail %d", tx_remain, tx_avail);
569 		for (int i = 0U; i < tx_avail; i++) {
570 			i2c_ctrl_fifo_write(dev, *(data->ptr_msg++));
571 		}
572 
573 		/* Is there any remaining bytes? */
574 		if (data->ptr_msg == data->msg->buf + data->msg->len) {
575 			data->oper_state = NPCX_I2C_WRITE_SUSPEND;
576 		}
577 		return;
578 	}
579 
580 	/* Issue STOP after sending message? */
581 	if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
582 		if (data->msg->flags & I2C_MSG_STOP) {
583 			/* Generate a STOP condition immediately */
584 			i2c_ctrl_stop(dev);
585 			/* Clear rx FIFO threshold and status bits */
586 			i2c_ctrl_fifo_clear_status(dev);
587 			/* Wait for STOP completed */
588 			data->oper_state = NPCX_I2C_WAIT_STOP;
589 		} else {
590 			/* Disable interrupt and handle next message */
591 			i2c_ctrl_irq_enable(dev, 0);
592 		}
593 	}
594 
595 	return i2c_ctrl_notify(dev, 0);
596 }
597 
i2c_ctrl_handle_read_int_event(const struct device * dev)598 static void i2c_ctrl_handle_read_int_event(const struct device *dev)
599 {
600 	struct i2c_ctrl_data *const data = dev->data;
601 
602 	/* START or RESTART condition is issued */
603 	if (data->oper_state == NPCX_I2C_WAIT_START ||
604 			data->oper_state == NPCX_I2C_WAIT_RESTART) {
605 		/* Setup threshold of rx FIFO before sending address byte */
606 		i2c_ctrl_fifo_rx_setup_threshold_nack(dev, data->msg->len,
607 					(data->msg->flags & I2C_MSG_STOP) != 0);
608 		/* Write slave address with R bit */
609 		i2c_ctrl_fifo_write(dev, ((data->addr << 1) | BIT(0)));
610 		/* Start to proceed read process */
611 		data->oper_state = NPCX_I2C_READ_FIFO;
612 		return;
613 	}
614 
615 	/* Read message data bytes from FIFO */
616 	if (data->oper_state == NPCX_I2C_READ_FIFO) {
617 		/* Calculate how many remaining bytes need to receive */
618 		size_t rx_remain = i2c_ctrl_calculate_msg_remains(dev);
619 		size_t rx_occupied = i2c_ctrl_fifo_rx_occupied(dev);
620 
621 		LOG_DBG("rx remains %d, occupied %d", rx_remain, rx_occupied);
622 
623 		/* Is it the last read transaction with STOP condition? */
624 		if (rx_occupied >= rx_remain &&
625 			(data->msg->flags & I2C_MSG_STOP) != 0) {
626 			/*
627 			 * Generate a STOP condition before reading data bytes
628 			 * from FIFO. It prevents a glitch on SCL.
629 			 */
630 			i2c_ctrl_stop(dev);
631 		} else {
632 			/*
633 			 * Hold SCL line here in case the hardware releases bus
634 			 * immediately after the driver start to read data from
635 			 * FIFO. Then we might lose incoming data from device.
636 			 */
637 			i2c_ctrl_hold_bus(dev, 1);
638 		}
639 
640 		/* Read data bytes from FIFO */
641 		for (int i = 0; i < rx_occupied; i++) {
642 			*(data->ptr_msg++) = i2c_ctrl_fifo_read(dev);
643 		}
644 		rx_remain = i2c_ctrl_calculate_msg_remains(dev);
645 
646 		/* Setup threshold of RX FIFO if needed */
647 		if (rx_remain > 0) {
648 			i2c_ctrl_fifo_rx_setup_threshold_nack(dev, rx_remain,
649 					(data->msg->flags & I2C_MSG_STOP) != 0);
650 			/* Release bus */
651 			i2c_ctrl_hold_bus(dev, 0);
652 			return;
653 		}
654 	}
655 
656 	/* Is the STOP condition issued? */
657 	if ((data->msg->flags & I2C_MSG_STOP) != 0) {
658 		/* Clear rx FIFO threshold and status bits */
659 		i2c_ctrl_fifo_clear_status(dev);
660 
661 		/* Wait for STOP completed */
662 		data->oper_state = NPCX_I2C_WAIT_STOP;
663 	} else {
664 		/* Disable i2c interrupt first */
665 		i2c_ctrl_irq_enable(dev, 0);
666 		data->oper_state = NPCX_I2C_READ_SUSPEND;
667 	}
668 
669 	return i2c_ctrl_notify(dev, 0);
670 }
671 
i2c_ctrl_proc_write_msg(const struct device * dev,struct i2c_msg * msg)672 static int i2c_ctrl_proc_write_msg(const struct device *dev,
673 							struct i2c_msg *msg)
674 {
675 	struct i2c_ctrl_data *const data = dev->data;
676 
677 	data->is_write = 1;
678 	data->ptr_msg = msg->buf;
679 	data->msg = msg;
680 
681 	if (data->oper_state == NPCX_I2C_IDLE) {
682 		data->oper_state = NPCX_I2C_WAIT_START;
683 
684 		/* Clear FIFO status before starting a new transaction */
685 		i2c_ctrl_fifo_clear_status(dev);
686 
687 		/* Issue a START, wait for transaction completed */
688 		i2c_ctrl_start(dev);
689 
690 		return i2c_ctrl_wait_completion(dev);
691 	} else if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
692 		data->oper_state = NPCX_I2C_WRITE_FIFO;
693 		i2c_ctrl_irq_enable(dev, 1);
694 
695 		return i2c_ctrl_wait_completion(dev);
696 	}
697 
698 	LOG_ERR("Unexpected state %d during writing i2c port%02x!",
699 					data->oper_state, data->port);
700 	data->trans_err = -EIO;
701 	return data->trans_err;
702 }
703 
i2c_ctrl_proc_read_msg(const struct device * dev,struct i2c_msg * msg)704 static int i2c_ctrl_proc_read_msg(const struct device *dev, struct i2c_msg *msg)
705 {
706 	struct i2c_ctrl_data *const data = dev->data;
707 
708 	data->is_write = 0;
709 	data->ptr_msg = msg->buf;
710 	data->msg = msg;
711 
712 	if (data->oper_state == NPCX_I2C_IDLE) {
713 		data->oper_state = NPCX_I2C_WAIT_START;
714 
715 		/* Clear FIFO status before starting a new transaction */
716 		i2c_ctrl_fifo_clear_status(dev);
717 
718 		/* Issue a START, wait for transaction completed */
719 		i2c_ctrl_start(dev);
720 
721 		return i2c_ctrl_wait_completion(dev);
722 	} else if (data->oper_state == NPCX_I2C_WRITE_SUSPEND) {
723 		data->oper_state = NPCX_I2C_WAIT_RESTART;
724 		/* Issue a RESTART, wait for transaction completed */
725 		i2c_ctrl_start(dev);
726 		i2c_ctrl_irq_enable(dev, 1);
727 
728 		return i2c_ctrl_wait_completion(dev);
729 	} else if (data->oper_state == NPCX_I2C_READ_SUSPEND) {
730 		data->oper_state = NPCX_I2C_READ_FIFO;
731 
732 		/* Setup threshold of RX FIFO first */
733 		i2c_ctrl_fifo_rx_setup_threshold_nack(dev, msg->len,
734 				(msg->flags & I2C_MSG_STOP) != 0);
735 
736 		/* Release bus */
737 		i2c_ctrl_hold_bus(dev, 0);
738 
739 		/* Enable i2c interrupt first */
740 		i2c_ctrl_irq_enable(dev, 1);
741 		return i2c_ctrl_wait_completion(dev);
742 	}
743 
744 	LOG_ERR("Unexpected state  %d during reading i2c port%02x!",
745 					data->oper_state, data->port);
746 	data->trans_err = -EIO;
747 	return data->trans_err;
748 }
749 
750 /* I2C controller isr function */
751 #ifdef CONFIG_I2C_TARGET
i2c_ctrl_target_isr(const struct device * dev,uint8_t status)752 static void i2c_ctrl_target_isr(const struct device *dev, uint8_t status)
753 {
754 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
755 	struct i2c_ctrl_data *const data = dev->data;
756 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
757 	uint8_t val = 0;
758 
759 	/* A 'Bus Error' has been identified */
760 	if (IS_BIT_SET(status, NPCX_SMBST_BER)) {
761 		/* Clear BER Bit */
762 		inst->SMBST = BIT(NPCX_SMBST_BER);
763 
764 		/* Notify upper layer the end of transaction */
765 		if (target_cb->stop) {
766 			target_cb->stop(data->target_cfg);
767 		}
768 
769 		/* Reset i2c module in target mode */
770 		inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
771 		inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
772 
773 		/*
774 		 * Re-enable interrupts because they are turned off after the SMBus module
775 		 * is reset above.
776 		 */
777 		inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
778 		/* End of transaction */
779 		data->oper_state = NPCX_I2C_IDLE;
780 
781 		LOG_DBG("target: Bus error on port%02x!", data->port);
782 		return;
783 	}
784 
785 	/* A 'Slave Stop' Condition has been identified */
786 	if (IS_BIT_SET(status, NPCX_SMBST_SLVSTP)) {
787 		/* Clear SLVSTP Bit */
788 		inst->SMBST = BIT(NPCX_SMBST_SLVSTP);
789 		/* End of transaction */
790 		data->oper_state = NPCX_I2C_IDLE;
791 		/* Notify upper layer a STOP condition received */
792 		if (target_cb->stop) {
793 			target_cb->stop(data->target_cfg);
794 		}
795 		return;
796 	}
797 
798 	/* A negative acknowledge has occurred */
799 	if (IS_BIT_SET(status, NPCX_SMBST_NEGACK)) {
800 		/* Clear NEGACK Bit */
801 		inst->SMBST = BIT(NPCX_SMBST_NEGACK);
802 		/* Do nothing in i2c target mode */
803 		return;
804 	}
805 
806 	/* A 'Target Address Match' has been identified */
807 	if (IS_BIT_SET(status, NPCX_SMBST_NMATCH)) {
808 		/* Clear NMATCH Bit */
809 		inst->SMBST = BIT(NPCX_SMBST_NMATCH);
810 
811 		/* Distinguish the direction of i2c target mode by reading XMIT bit */
812 		if (IS_BIT_SET(inst->SMBST, NPCX_SMBST_XMIT)) {
813 			/* Start transmitting data in i2c target mode */
814 			data->oper_state = NPCX_I2C_WRITE_FIFO;
815 			/* Write first requested byte after repeated start */
816 			if (target_cb->read_requested) {
817 				target_cb->read_requested(data->target_cfg, &val);
818 			}
819 			inst->SMBSDA = val;
820 		} else {
821 			/* Start receiving data in i2c target mode */
822 			data->oper_state = NPCX_I2C_READ_FIFO;
823 
824 			if (target_cb->write_requested) {
825 				target_cb->write_requested(data->target_cfg);
826 			}
827 		}
828 		return;
829 	}
830 
831 	/* Tx byte empty or Rx byte full has occurred */
832 	if (IS_BIT_SET(status, NPCX_SMBST_SDAST)) {
833 		if (data->oper_state == NPCX_I2C_WRITE_FIFO) {
834 			/* Notify upper layer one byte will be transmitted */
835 			if (target_cb->read_processed) {
836 				target_cb->read_processed(data->target_cfg, &val);
837 			}
838 			inst->SMBSDA = val;
839 		} else if (data->oper_state == NPCX_I2C_READ_FIFO) {
840 			if (target_cb->write_received) {
841 				val = inst->SMBSDA;
842 				/* Notify upper layer one byte received */
843 				target_cb->write_received(data->target_cfg, val);
844 			}
845 		} else {
846 			LOG_ERR("Unexpected oper state %d on i2c target port%02x!",
847 				data->oper_state, data->port);
848 		}
849 		return;
850 	}
851 
852 	/* Clear unexpected status bits */
853 	if (status != 0) {
854 		inst->SMBST = status;
855 		LOG_ERR("Unexpected  SMBST 0x%02x occurred on i2c target port%02x!",
856 			status, data->port);
857 	}
858 }
859 #endif
860 
861 /* I2C controller isr function */
i2c_ctrl_isr(const struct device * dev)862 static void i2c_ctrl_isr(const struct device *dev)
863 {
864 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
865 	struct i2c_ctrl_data *const data = dev->data;
866 	uint8_t status, tmp;
867 
868 	status = inst->SMBST & NPCX_VALID_SMBST_MASK;
869 	LOG_DBG("status: %02x, %d", status, data->oper_state);
870 
871 #ifdef CONFIG_I2C_TARGET
872 	if (atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
873 		return i2c_ctrl_target_isr(dev, status);
874 	}
875 #endif
876 
877 	/* A 'Bus Error' has been identified */
878 	if (IS_BIT_SET(status, NPCX_SMBST_BER)) {
879 		/* Generate a STOP condition immediately */
880 		i2c_ctrl_stop(dev);
881 
882 		/* Clear BER Bit */
883 		inst->SMBST = BIT(NPCX_SMBST_BER);
884 
885 		/* Make sure slave doesn't hold bus by reading FIFO again */
886 		tmp = i2c_ctrl_fifo_read(dev);
887 
888 		LOG_ERR("Bus error occurred on i2c port%02x!", data->port);
889 		data->oper_state = NPCX_I2C_ERROR_RECOVERY;
890 
891 		/* I/O error occurred */
892 		i2c_ctrl_notify(dev, -EIO);
893 		return;
894 	}
895 
896 	/* A negative acknowledge has occurred */
897 	if (IS_BIT_SET(status, NPCX_SMBST_NEGACK)) {
898 		/* Generate a STOP condition immediately */
899 		i2c_ctrl_stop(dev);
900 
901 		/* Clear NEGACK Bit */
902 		inst->SMBST = BIT(NPCX_SMBST_NEGACK);
903 
904 		/* End transaction */
905 		data->oper_state = NPCX_I2C_WAIT_STOP;
906 
907 		/* No such device or address */
908 		return i2c_ctrl_notify(dev, -ENXIO);
909 	}
910 
911 	/* START, tx FIFO empty or rx FIFO full has occurred */
912 	if (IS_BIT_SET(status, NPCX_SMBST_SDAST)) {
913 		if (data->is_write) {
914 			return i2c_ctrl_handle_write_int_event(dev);
915 		} else {
916 			return i2c_ctrl_handle_read_int_event(dev);
917 		}
918 	}
919 
920 	/* Clear unexpected status bits */
921 	if (status != 0) {
922 		inst->SMBST = status;
923 		LOG_ERR("Unexpected  SMBST 0x%02x occurred on i2c port%02x!",
924 			status, data->port);
925 	}
926 }
927 
928 /* NPCX specific I2C controller functions */
npcx_i2c_ctrl_mutex_lock(const struct device * i2c_dev)929 void npcx_i2c_ctrl_mutex_lock(const struct device *i2c_dev)
930 {
931 	struct i2c_ctrl_data *const data = i2c_dev->data;
932 
933 	k_sem_take(&data->lock_sem, K_FOREVER);
934 }
935 
npcx_i2c_ctrl_mutex_unlock(const struct device * i2c_dev)936 void npcx_i2c_ctrl_mutex_unlock(const struct device *i2c_dev)
937 {
938 	struct i2c_ctrl_data *const data = i2c_dev->data;
939 
940 	k_sem_give(&data->lock_sem);
941 }
942 
npcx_i2c_ctrl_configure(const struct device * i2c_dev,uint32_t dev_config)943 int npcx_i2c_ctrl_configure(const struct device *i2c_dev, uint32_t dev_config)
944 {
945 	struct i2c_ctrl_data *const data = i2c_dev->data;
946 
947 	switch (I2C_SPEED_GET(dev_config)) {
948 	case I2C_SPEED_STANDARD:
949 		data->bus_freq = NPCX_I2C_BUS_SPEED_100KHZ;
950 		break;
951 	case I2C_SPEED_FAST:
952 		data->bus_freq = NPCX_I2C_BUS_SPEED_400KHZ;
953 		break;
954 	case I2C_SPEED_FAST_PLUS:
955 		data->bus_freq = NPCX_I2C_BUS_SPEED_1MHZ;
956 		break;
957 	default:
958 		return -ERANGE;
959 	}
960 
961 	i2c_ctrl_config_bus_freq(i2c_dev, data->bus_freq);
962 	data->is_configured = true;
963 
964 	return 0;
965 }
966 
npcx_i2c_ctrl_get_speed(const struct device * i2c_dev,uint32_t * speed)967 int npcx_i2c_ctrl_get_speed(const struct device *i2c_dev, uint32_t *speed)
968 {
969 	struct i2c_ctrl_data *const data = i2c_dev->data;
970 
971 	if (!data->is_configured) {
972 		return -EIO;
973 	}
974 
975 	switch (data->bus_freq) {
976 	case NPCX_I2C_BUS_SPEED_100KHZ:
977 		*speed = I2C_SPEED_SET(I2C_SPEED_STANDARD);
978 		break;
979 	case NPCX_I2C_BUS_SPEED_400KHZ:
980 		*speed = I2C_SPEED_SET(I2C_SPEED_FAST);
981 		break;
982 	case NPCX_I2C_BUS_SPEED_1MHZ:
983 		*speed = I2C_SPEED_SET(I2C_SPEED_FAST_PLUS);
984 		break;
985 	default:
986 		return -ERANGE;
987 	}
988 
989 	return 0;
990 }
991 
npcx_i2c_ctrl_recover_bus(const struct device * dev)992 int npcx_i2c_ctrl_recover_bus(const struct device *dev)
993 {
994 	struct smb_reg *const inst = HAL_I2C_INSTANCE(dev);
995 	int ret = 0;
996 
997 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_NORMAL);
998 
999 	/*
1000 	 * When the SCL is low, wait for a while in case of the clock is stalled
1001 	 * by a I2C target.
1002 	 */
1003 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1004 		for (int i = 0;; i++) {
1005 			if (i >= I2C_RECOVER_SCL_RETRY) {
1006 				ret = -EBUSY;
1007 				goto recover_exit;
1008 			}
1009 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1010 			if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1011 				break;
1012 			}
1013 		}
1014 	}
1015 
1016 	if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1017 		goto recover_exit;
1018 	}
1019 
1020 	for (int i = 0; i < I2C_RECOVER_SDA_RETRY; i++) {
1021 		/* Drive the clock high. */
1022 		i2c_ctrl_norm_free_scl(dev);
1023 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1024 
1025 		/*
1026 		 * Toggle SCL to generate 9 clocks. If the I2C target releases the SDA, we can stop
1027 		 * toggle the SCL and issue a STOP.
1028 		 */
1029 		for (int j = 0; j < 9; j++) {
1030 			if (IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1031 				break;
1032 			}
1033 
1034 			i2c_ctrl_norm_stall_scl(dev);
1035 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1036 			i2c_ctrl_norm_free_scl(dev);
1037 			k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1038 		}
1039 
1040 		/* Drive the SDA line to issue STOP. */
1041 		i2c_ctrl_norm_stall_sda(dev);
1042 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1043 		i2c_ctrl_norm_free_sda(dev);
1044 		k_busy_wait(I2C_RECOVER_BUS_DELAY_US);
1045 
1046 		if (i2c_ctrl_is_scl_sda_both_high(dev)) {
1047 			ret = 0;
1048 			goto recover_exit;
1049 		}
1050 	}
1051 
1052 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SDA_LVL)) {
1053 		LOG_ERR("Recover SDA fail");
1054 		ret = -EBUSY;
1055 	}
1056 	if (!IS_BIT_SET(inst->SMBCTL3, NPCX_SMBCTL3_SCL_LVL)) {
1057 		LOG_ERR("Recover SCL fail");
1058 		ret = -EBUSY;
1059 	}
1060 
1061 recover_exit:
1062 	i2c_ctrl_bank_sel(dev, NPCX_I2C_BANK_FIFO);
1063 
1064 	return ret;
1065 }
1066 
1067 #ifdef CONFIG_I2C_TARGET
npcx_i2c_ctrl_target_register(const struct device * i2c_dev,struct i2c_target_config * target_cfg,uint8_t port)1068 int npcx_i2c_ctrl_target_register(const struct device *i2c_dev,
1069 				 struct i2c_target_config *target_cfg, uint8_t port)
1070 {
1071 	struct smb_reg *const inst = HAL_I2C_INSTANCE(i2c_dev);
1072 	struct i2c_ctrl_data *const data = i2c_dev->data;
1073 	int idx_ctrl = (port & 0xF0) >> 4;
1074 	int idx_port = (port & 0x0F);
1075 	uint8_t addr = BIT(NPCX_SMBADDR1_SAEN) | target_cfg->address;
1076 
1077 	/* I2c module has been configured to target mode */
1078 	if (atomic_test_and_set_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1079 		return -EBUSY;
1080 	}
1081 
1082 	/* A transiaction is ongoing */
1083 	if (data->oper_state != NPCX_I2C_IDLE) {
1084 		atomic_clear_bit(&data->flags, NPCX_I2C_FLAG_TARGET);
1085 		return -EBUSY;
1086 	}
1087 
1088 	data->target_cfg = target_cfg;
1089 
1090 	i2c_ctrl_irq_enable(i2c_dev, 0);
1091 	/* Switch correct port for i2c controller first */
1092 	npcx_pinctrl_i2c_port_sel(idx_ctrl, idx_port);
1093 	/* Reset I2C module */
1094 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
1095 	inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
1096 
1097 	/* Select normal bank and single byte mode for i2c target mode */
1098 	i2c_ctrl_bank_sel(i2c_dev, NPCX_I2C_BANK_NORMAL);
1099 	inst->SMBFIF_CTL &= ~BIT(NPCX_SMBFIF_CTL_FIFO_EN);
1100 	inst->SMBADDR1 = addr; /* Enable target mode and configure its address */
1101 
1102 	/* Reconfigure SMBCTL1 */
1103 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
1104 	i2c_ctrl_irq_enable(i2c_dev, 1);
1105 
1106 	return 0;
1107 }
1108 
npcx_i2c_ctrl_target_unregister(const struct device * i2c_dev,struct i2c_target_config * target_cfg)1109 int npcx_i2c_ctrl_target_unregister(const struct device *i2c_dev,
1110 				   struct i2c_target_config *target_cfg)
1111 {
1112 	struct smb_reg *const inst = HAL_I2C_INSTANCE(i2c_dev);
1113 	struct i2c_ctrl_data *const data = i2c_dev->data;
1114 
1115 	/* No I2c module has been configured to target mode */
1116 	if (!atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1117 		return -EINVAL;
1118 	}
1119 
1120 	/* A transiaction is ongoing */
1121 	if (data->oper_state != NPCX_I2C_IDLE) {
1122 		return -EBUSY;
1123 	}
1124 	data->target_cfg = NULL;
1125 
1126 	i2c_ctrl_irq_enable(i2c_dev, 0);
1127 	/* Reset I2C module */
1128 	inst->SMBCTL2 &= ~BIT(NPCX_SMBCTL2_ENABLE);
1129 	inst->SMBCTL2 |= BIT(NPCX_SMBCTL2_ENABLE);
1130 
1131 	inst->SMBADDR1 = 0; /* Disable target mode and clear address setting */
1132 	/* Enable FIFO mode and select to FIFO bank for i2c controller mode */
1133 	inst->SMBFIF_CTL |= BIT(NPCX_SMBFIF_CTL_FIFO_EN);
1134 	i2c_ctrl_bank_sel(i2c_dev, NPCX_I2C_BANK_FIFO);
1135 
1136 	/* Reconfigure SMBCTL1 */
1137 	inst->SMBCTL1 |= BIT(NPCX_SMBCTL1_NMINTE) | BIT(NPCX_SMBCTL1_INTEN);
1138 	i2c_ctrl_irq_enable(i2c_dev, 1);
1139 
1140 	/* Mark it as controller mode */
1141 	atomic_clear_bit(&data->flags, NPCX_I2C_FLAG_TARGET);
1142 
1143 	return 0;
1144 }
1145 #endif
1146 
npcx_i2c_ctrl_transfer(const struct device * i2c_dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,int port)1147 int npcx_i2c_ctrl_transfer(const struct device *i2c_dev, struct i2c_msg *msgs,
1148 			      uint8_t num_msgs, uint16_t addr, int port)
1149 {
1150 	struct i2c_ctrl_data *const data = i2c_dev->data;
1151 	int ret = 0;
1152 	uint8_t i;
1153 
1154 #ifdef CONFIG_I2C_TARGET
1155 	/* I2c module has been configured to target mode */
1156 	if (atomic_test_bit(&data->flags, NPCX_I2C_FLAG_TARGET)) {
1157 		return -EBUSY;
1158 	}
1159 #endif
1160 
1161 	/*
1162 	 * suspend-to-idle stops SMB module clocks (derived from APB2/APB3), which must remain
1163 	 * active during a transaction
1164 	 */
1165 	pm_policy_state_lock_get(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
1166 
1167 	/* Does bus need recovery? */
1168 	if (data->oper_state != NPCX_I2C_WRITE_SUSPEND &&
1169 			data->oper_state != NPCX_I2C_READ_SUSPEND) {
1170 		if (i2c_ctrl_bus_busy(i2c_dev) || !i2c_ctrl_is_scl_sda_both_high(i2c_dev) ||
1171 		    data->oper_state == NPCX_I2C_ERROR_RECOVERY) {
1172 			ret = npcx_i2c_ctrl_recover_bus(i2c_dev);
1173 			if (ret != 0) {
1174 				LOG_ERR("Recover Bus failed");
1175 				goto out;
1176 			}
1177 
1178 			ret = i2c_ctrl_recovery(i2c_dev);
1179 			/* Recovery failed, return it immediately */
1180 			if (ret) {
1181 				goto out;
1182 			}
1183 		}
1184 	}
1185 
1186 	/* Start i2c transaction */
1187 	data->port = port;
1188 	data->trans_err = 0;
1189 	data->addr = addr;
1190 
1191 	/*
1192 	 * Reset i2c event-completed semaphore before starting transactions.
1193 	 * Some interrupt events such as BUS_ERROR might change its counter
1194 	 * when bus is idle.
1195 	 */
1196 	k_sem_reset(&data->sync_sem);
1197 
1198 	for (i = 0U; i < num_msgs; i++) {
1199 		struct i2c_msg *msg = msgs + i;
1200 
1201 		/* Handle write transaction */
1202 		if ((msg->flags & I2C_MSG_RW_MASK) == I2C_MSG_WRITE) {
1203 			ret = i2c_ctrl_proc_write_msg(i2c_dev, msg);
1204 		} else {/* Handle read transaction */
1205 			ret = i2c_ctrl_proc_read_msg(i2c_dev, msg);
1206 		}
1207 		if (ret < 0) {
1208 			break;
1209 		}
1210 	}
1211 
1212 	/* Check STOP completed? */
1213 	if (data->oper_state == NPCX_I2C_WAIT_STOP) {
1214 		data->trans_err = i2c_ctrl_wait_stop_completed(i2c_dev,
1215 							I2C_MIN_TIMEOUT);
1216 		if (data->trans_err == 0) {
1217 			data->oper_state = NPCX_I2C_IDLE;
1218 		} else {
1219 			LOG_ERR("STOP fail! bus is held on i2c port%02x!",
1220 								data->port);
1221 			data->oper_state = NPCX_I2C_ERROR_RECOVERY;
1222 		}
1223 	}
1224 
1225 	if (data->oper_state == NPCX_I2C_ERROR_RECOVERY || ret == -ETIMEDOUT) {
1226 		int recovery_error = i2c_ctrl_recovery(i2c_dev);
1227 		/*
1228 		 * Recovery failed, return it immediately. Otherwise, the upper
1229 		 * layer still needs to know why the transaction failed.
1230 		 */
1231 		if (recovery_error != 0) {
1232 			ret = recovery_error;
1233 		}
1234 	}
1235 
1236 out:
1237 	pm_policy_state_lock_put(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
1238 	return ret;
1239 }
1240 
1241 /* I2C controller driver registration */
i2c_ctrl_init(const struct device * dev)1242 static int i2c_ctrl_init(const struct device *dev)
1243 {
1244 	const struct i2c_ctrl_config *const config = dev->config;
1245 	struct i2c_ctrl_data *const data = dev->data;
1246 	const struct device *const clk_dev = DEVICE_DT_GET(NPCX_CLK_CTRL_NODE);
1247 	uint32_t i2c_rate;
1248 
1249 	if (!device_is_ready(clk_dev)) {
1250 		LOG_ERR("clock control device not ready");
1251 		return -ENODEV;
1252 	}
1253 
1254 	/* Turn on device clock first and get source clock freq. */
1255 	if (clock_control_on(clk_dev,
1256 		(clock_control_subsys_t) &config->clk_cfg) != 0) {
1257 		LOG_ERR("Turn on %s clock fail.", dev->name);
1258 		return -EIO;
1259 	}
1260 
1261 	/*
1262 	 * If apb2/3's clock is not 15MHz, we need to add the other timing
1263 	 * configuration of the device to meet SMBus timing spec. Please refer
1264 	 * Table 21/22/23 and section 7.5.9 SMBus Timing for more detail.
1265 	 */
1266 	if (clock_control_get_rate(clk_dev, (clock_control_subsys_t)
1267 			&config->clk_cfg, &i2c_rate) != 0) {
1268 		LOG_ERR("Get %s clock rate error.", dev->name);
1269 		return -EIO;
1270 	}
1271 
1272 	if (i2c_rate == 15000000) {
1273 		data->ptr_speed_confs = npcx_15m_speed_confs;
1274 	} else if (i2c_rate == 20000000) {
1275 		data->ptr_speed_confs = npcx_20m_speed_confs;
1276 	} else {
1277 		LOG_ERR("Unsupported apb2/3 freq for %s.", dev->name);
1278 		return -EIO;
1279 	}
1280 
1281 	/* Initialize i2c module */
1282 	i2c_ctrl_init_module(dev);
1283 
1284 	/* initialize mutex and semaphore for i2c/smb controller */
1285 	k_sem_init(&data->lock_sem, 1, 1);
1286 	k_sem_init(&data->sync_sem, 0, K_SEM_MAX_LIMIT);
1287 
1288 	/* Initialize driver status machine */
1289 	data->oper_state = NPCX_I2C_IDLE;
1290 
1291 	return 0;
1292 }
1293 
1294 /* I2C controller init macro functions */
1295 #define NPCX_I2C_CTRL_INIT_FUNC(inst) _CONCAT(i2c_ctrl_init_, inst)
1296 #define NPCX_I2C_CTRL_INIT_FUNC_DECL(inst) \
1297 	static int i2c_ctrl_init_##inst(const struct device *dev)
1298 #define NPCX_I2C_CTRL_INIT_FUNC_IMPL(inst)                                     \
1299 	static int i2c_ctrl_init_##inst(const struct device *dev)              \
1300 	{	                                                               \
1301 		int ret;                                                       \
1302 									       \
1303 		ret = i2c_ctrl_init(dev);                                      \
1304 		IRQ_CONNECT(DT_INST_IRQN(inst),		                       \
1305 			DT_INST_IRQ(inst, priority),                           \
1306 			i2c_ctrl_isr,                                          \
1307 			DEVICE_DT_INST_GET(inst),                              \
1308 			0);                                                    \
1309 		irq_enable(DT_INST_IRQN(inst));                                \
1310 									       \
1311 		return ret;                                                    \
1312 	}
1313 
1314 
1315 #define NPCX_I2C_CTRL_INIT(inst)                                               \
1316 	NPCX_I2C_CTRL_INIT_FUNC_DECL(inst);                                    \
1317 									       \
1318 	static const struct i2c_ctrl_config i2c_ctrl_cfg_##inst = {            \
1319 		.base = DT_INST_REG_ADDR(inst),                                \
1320 		.irq = DT_INST_IRQN(inst),                                     \
1321 		.clk_cfg = NPCX_DT_CLK_CFG_ITEM(inst),                         \
1322 	};                                                                     \
1323 									       \
1324 	static struct i2c_ctrl_data i2c_ctrl_data_##inst;                      \
1325 									       \
1326 	DEVICE_DT_INST_DEFINE(inst,                                            \
1327 			    NPCX_I2C_CTRL_INIT_FUNC(inst),                     \
1328 			    NULL,                                              \
1329 			    &i2c_ctrl_data_##inst, &i2c_ctrl_cfg_##inst,       \
1330 			    PRE_KERNEL_1, CONFIG_I2C_INIT_PRIORITY,            \
1331 			    NULL);                                             \
1332 									       \
1333 	NPCX_I2C_CTRL_INIT_FUNC_IMPL(inst)
1334 
1335 DT_INST_FOREACH_STATUS_OKAY(NPCX_I2C_CTRL_INIT)
1336