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