1 /*
2  * Copyright (c) 2016 Freescale Semiconductor, Inc.
3  * Copyright 2019-2023, NXP
4  * Copyright (c) 2022 Vestas Wind Systems A/S
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #define DT_DRV_COMPAT nxp_imx_lpi2c
10 
11 #include <errno.h>
12 #include <zephyr/drivers/i2c.h>
13 #include <zephyr/drivers/clock_control.h>
14 #include <zephyr/kernel.h>
15 #include <zephyr/irq.h>
16 #include <fsl_lpi2c.h>
17 
18 #include <zephyr/drivers/pinctrl.h>
19 
20 #ifdef CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY
21 #include "i2c_bitbang.h"
22 #include <zephyr/drivers/gpio.h>
23 #endif /* CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY */
24 
25 #include <zephyr/logging/log.h>
26 LOG_MODULE_REGISTER(mcux_lpi2c);
27 
28 
29 #include "i2c-priv.h"
30 /* Wait for the duration of 12 bits to detect a NAK after a bus
31  * address scan.  (10 appears sufficient, 20% safety factor.)
32  */
33 #define SCAN_DELAY_US(baudrate) (12 * USEC_PER_SEC / baudrate)
34 
35 struct mcux_lpi2c_config {
36 	LPI2C_Type *base;
37 	const struct device *clock_dev;
38 	clock_control_subsys_t clock_subsys;
39 	void (*irq_config_func)(const struct device *dev);
40 	uint32_t bitrate;
41 	uint32_t bus_idle_timeout_ns;
42 	const struct pinctrl_dev_config *pincfg;
43 #ifdef CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY
44 	struct gpio_dt_spec scl;
45 	struct gpio_dt_spec sda;
46 #endif /* CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY */
47 };
48 
49 struct mcux_lpi2c_data {
50 	lpi2c_master_handle_t handle;
51 	struct k_sem lock;
52 	struct k_sem device_sync_sem;
53 	status_t callback_status;
54 #ifdef CONFIG_I2C_TARGET
55 	lpi2c_slave_handle_t target_handle;
56 	struct i2c_target_config *target_cfg;
57 	bool target_attached;
58 	bool first_tx;
59 	bool read_active;
60 	bool send_ack;
61 #endif
62 };
63 
mcux_lpi2c_configure(const struct device * dev,uint32_t dev_config_raw)64 static int mcux_lpi2c_configure(const struct device *dev,
65 				uint32_t dev_config_raw)
66 {
67 	const struct mcux_lpi2c_config *config = dev->config;
68 	struct mcux_lpi2c_data *data = dev->data;
69 	LPI2C_Type *base = config->base;
70 	uint32_t clock_freq;
71 	uint32_t baudrate;
72 	int ret;
73 
74 	if (!(I2C_MODE_CONTROLLER & dev_config_raw)) {
75 		return -EINVAL;
76 	}
77 
78 	if (I2C_ADDR_10_BITS & dev_config_raw) {
79 		return -EINVAL;
80 	}
81 
82 	switch (I2C_SPEED_GET(dev_config_raw)) {
83 	case I2C_SPEED_STANDARD:
84 		baudrate = KHZ(100);
85 		break;
86 	case I2C_SPEED_FAST:
87 		baudrate = KHZ(400);
88 		break;
89 	case I2C_SPEED_FAST_PLUS:
90 		baudrate = MHZ(1);
91 		break;
92 	default:
93 		return -EINVAL;
94 	}
95 
96 	if (clock_control_get_rate(config->clock_dev, config->clock_subsys,
97 				   &clock_freq)) {
98 		return -EINVAL;
99 	}
100 
101 	ret = k_sem_take(&data->lock, K_FOREVER);
102 	if (ret) {
103 		return ret;
104 	}
105 
106 	LPI2C_MasterSetBaudRate(base, clock_freq, baudrate);
107 	k_sem_give(&data->lock);
108 
109 	return 0;
110 }
111 
mcux_lpi2c_master_transfer_callback(LPI2C_Type * base,lpi2c_master_handle_t * handle,status_t status,void * userData)112 static void mcux_lpi2c_master_transfer_callback(LPI2C_Type *base,
113 						lpi2c_master_handle_t *handle,
114 						status_t status, void *userData)
115 {
116 	struct mcux_lpi2c_data *data = userData;
117 
118 	ARG_UNUSED(handle);
119 	ARG_UNUSED(base);
120 
121 	data->callback_status = status;
122 	k_sem_give(&data->device_sync_sem);
123 }
124 
mcux_lpi2c_convert_flags(int msg_flags)125 static uint32_t mcux_lpi2c_convert_flags(int msg_flags)
126 {
127 	uint32_t flags = 0U;
128 
129 	if (!(msg_flags & I2C_MSG_STOP)) {
130 		flags |= kLPI2C_TransferNoStopFlag;
131 	}
132 
133 	if (msg_flags & I2C_MSG_RESTART) {
134 		flags |= kLPI2C_TransferRepeatedStartFlag;
135 	}
136 
137 	return flags;
138 }
139 
mcux_lpi2c_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)140 static int mcux_lpi2c_transfer(const struct device *dev, struct i2c_msg *msgs,
141 			       uint8_t num_msgs, uint16_t addr)
142 {
143 	const struct mcux_lpi2c_config *config = dev->config;
144 	struct mcux_lpi2c_data *data = dev->data;
145 	LPI2C_Type *base = config->base;
146 	lpi2c_master_transfer_t transfer;
147 	status_t status;
148 	int ret = 0;
149 
150 	ret = k_sem_take(&data->lock, K_FOREVER);
151 	if (ret) {
152 		return ret;
153 	}
154 
155 	/* Iterate over all the messages */
156 	for (int i = 0; i < num_msgs; i++) {
157 		if (I2C_MSG_ADDR_10_BITS & msgs->flags) {
158 			ret = -ENOTSUP;
159 			break;
160 		}
161 
162 		/* Initialize the transfer descriptor */
163 		transfer.flags = mcux_lpi2c_convert_flags(msgs->flags);
164 
165 		/* Prevent the controller to send a start condition between
166 		 * messages, except if explicitly requested.
167 		 */
168 		if (i != 0 && !(msgs->flags & I2C_MSG_RESTART)) {
169 			transfer.flags |= kLPI2C_TransferNoStartFlag;
170 		}
171 
172 		transfer.slaveAddress = addr;
173 		transfer.direction = (msgs->flags & I2C_MSG_READ)
174 			? kLPI2C_Read : kLPI2C_Write;
175 		transfer.subaddress = 0;
176 		transfer.subaddressSize = 0;
177 		transfer.data = msgs->buf;
178 		transfer.dataSize = msgs->len;
179 
180 		/* Start the transfer */
181 		status = LPI2C_MasterTransferNonBlocking(base,
182 				&data->handle, &transfer);
183 
184 		/* Return an error if the transfer didn't start successfully
185 		 * e.g., if the bus was busy
186 		 */
187 		if (status != kStatus_Success) {
188 			LPI2C_MasterTransferAbort(base, &data->handle);
189 			ret = -EIO;
190 			break;
191 		}
192 
193 		/* Wait for the transfer to complete */
194 		k_sem_take(&data->device_sync_sem, K_FOREVER);
195 
196 		/* Return an error if the transfer didn't complete
197 		 * successfully. e.g., nak, timeout, lost arbitration
198 		 */
199 		if (data->callback_status != kStatus_Success) {
200 			LPI2C_MasterTransferAbort(base, &data->handle);
201 			ret = -EIO;
202 			break;
203 		}
204 		if (msgs->len == 0) {
205 			k_busy_wait(SCAN_DELAY_US(config->bitrate));
206 			if (0 != (base->MSR & LPI2C_MSR_NDF_MASK)) {
207 				LPI2C_MasterTransferAbort(base, &data->handle);
208 				ret = -EIO;
209 				break;
210 			}
211 		}
212 		/* Move to the next message */
213 		msgs++;
214 	}
215 
216 	k_sem_give(&data->lock);
217 
218 	return ret;
219 }
220 
221 #if CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY
mcux_lpi2c_bitbang_set_scl(void * io_context,int state)222 static void mcux_lpi2c_bitbang_set_scl(void *io_context, int state)
223 {
224 	const struct mcux_lpi2c_config *config = io_context;
225 
226 	gpio_pin_set_dt(&config->scl, state);
227 }
228 
mcux_lpi2c_bitbang_set_sda(void * io_context,int state)229 static void mcux_lpi2c_bitbang_set_sda(void *io_context, int state)
230 {
231 	const struct mcux_lpi2c_config *config = io_context;
232 
233 	gpio_pin_set_dt(&config->sda, state);
234 }
235 
mcux_lpi2c_bitbang_get_sda(void * io_context)236 static int mcux_lpi2c_bitbang_get_sda(void *io_context)
237 {
238 	const struct mcux_lpi2c_config *config = io_context;
239 
240 	return gpio_pin_get_dt(&config->sda) == 0 ? 0 : 1;
241 }
242 
mcux_lpi2c_recover_bus(const struct device * dev)243 static int mcux_lpi2c_recover_bus(const struct device *dev)
244 {
245 	const struct mcux_lpi2c_config *config = dev->config;
246 	struct mcux_lpi2c_data *data = dev->data;
247 	struct i2c_bitbang bitbang_ctx;
248 	struct i2c_bitbang_io bitbang_io = {
249 		.set_scl = mcux_lpi2c_bitbang_set_scl,
250 		.set_sda = mcux_lpi2c_bitbang_set_sda,
251 		.get_sda = mcux_lpi2c_bitbang_get_sda,
252 	};
253 	uint32_t bitrate_cfg;
254 	int error = 0;
255 
256 	if (!gpio_is_ready_dt(&config->scl)) {
257 		LOG_ERR("SCL GPIO device not ready");
258 		return -EIO;
259 	}
260 
261 	if (!gpio_is_ready_dt(&config->sda)) {
262 		LOG_ERR("SDA GPIO device not ready");
263 		return -EIO;
264 	}
265 
266 	k_sem_take(&data->lock, K_FOREVER);
267 
268 	error = gpio_pin_configure_dt(&config->scl, GPIO_OUTPUT_HIGH);
269 	if (error != 0) {
270 		LOG_ERR("failed to configure SCL GPIO (err %d)", error);
271 		goto restore;
272 	}
273 
274 	error = gpio_pin_configure_dt(&config->sda, GPIO_OUTPUT_HIGH);
275 	if (error != 0) {
276 		LOG_ERR("failed to configure SDA GPIO (err %d)", error);
277 		goto restore;
278 	}
279 
280 	i2c_bitbang_init(&bitbang_ctx, &bitbang_io, (void *)config);
281 
282 	bitrate_cfg = i2c_map_dt_bitrate(config->bitrate) | I2C_MODE_CONTROLLER;
283 	error = i2c_bitbang_configure(&bitbang_ctx, bitrate_cfg);
284 	if (error != 0) {
285 		LOG_ERR("failed to configure I2C bitbang (err %d)", error);
286 		goto restore;
287 	}
288 
289 	error = i2c_bitbang_recover_bus(&bitbang_ctx);
290 	if (error != 0) {
291 		LOG_ERR("failed to recover bus (err %d)", error);
292 		goto restore;
293 	}
294 
295 restore:
296 	(void)pinctrl_apply_state(config->pincfg, PINCTRL_STATE_DEFAULT);
297 
298 	k_sem_give(&data->lock);
299 
300 	return error;
301 }
302 #endif /* CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY */
303 
304 #ifdef CONFIG_I2C_TARGET
mcux_lpi2c_slave_irq_handler(const struct device * dev)305 static void mcux_lpi2c_slave_irq_handler(const struct device *dev)
306 {
307 	const struct mcux_lpi2c_config *config = dev->config;
308 	struct mcux_lpi2c_data *data = dev->data;
309 	const struct i2c_target_callbacks *target_cb = data->target_cfg->callbacks;
310 	int ret;
311 	uint32_t flags;
312 	uint8_t i2c_data;
313 
314 	/* Note- the HAL provides a callback-based I2C slave API, but
315 	 * the API expects the user to provide a transmit buffer of
316 	 * a fixed length at the first byte received, and will not signal
317 	 * the user callback until this buffer is exhausted. This does not
318 	 * work well with the Zephyr API, which requires callbacks for
319 	 * every byte. For these reason, we handle the LPI2C IRQ
320 	 * directly.
321 	 */
322 	flags = LPI2C_SlaveGetStatusFlags(config->base);
323 
324 	if (flags & kLPI2C_SlaveAddressValidFlag) {
325 		/* Read Slave address to clear flag */
326 		LPI2C_SlaveGetReceivedAddress(config->base);
327 		data->first_tx = true;
328 		/* Reset to sending ACK, in case we NAK'ed before */
329 		data->send_ack = true;
330 	}
331 
332 	if (flags & kLPI2C_SlaveRxReadyFlag) {
333 		/* RX data is available, read it and issue callback */
334 		i2c_data = (uint8_t)config->base->SRDR;
335 		if (data->first_tx) {
336 			data->first_tx = false;
337 			if (target_cb->write_requested) {
338 				ret = target_cb->write_requested(data->target_cfg);
339 				if (ret < 0) {
340 					/* NAK further bytes */
341 					data->send_ack = false;
342 				}
343 			}
344 		}
345 		if (target_cb->write_received) {
346 			ret = target_cb->write_received(data->target_cfg,
347 							i2c_data);
348 			if (ret < 0) {
349 				/* NAK further bytes */
350 				data->send_ack = false;
351 			}
352 		}
353 	}
354 
355 	if (flags & kLPI2C_SlaveTxReadyFlag) {
356 		/* Space is available in TX fifo, issue callback and write out */
357 		if (data->first_tx) {
358 			data->read_active = true;
359 			data->first_tx = false;
360 			if (target_cb->read_requested) {
361 				ret = target_cb->read_requested(data->target_cfg,
362 								&i2c_data);
363 				if (ret < 0) {
364 					/* Disable TX */
365 					data->read_active = false;
366 				} else {
367 					/* Send I2C data */
368 					config->base->STDR = i2c_data;
369 				}
370 			}
371 		} else if (data->read_active) {
372 			if (target_cb->read_processed) {
373 				ret = target_cb->read_processed(data->target_cfg,
374 								&i2c_data);
375 				if (ret < 0) {
376 					/* Disable TX */
377 					data->read_active = false;
378 				} else {
379 					/* Send I2C data */
380 					config->base->STDR = i2c_data;
381 				}
382 			}
383 		}
384 	}
385 
386 	if (flags & kLPI2C_SlaveStopDetectFlag) {
387 		LPI2C_SlaveClearStatusFlags(config->base, flags);
388 		if (target_cb->stop) {
389 			target_cb->stop(data->target_cfg);
390 		}
391 	}
392 
393 	if (flags & kLPI2C_SlaveTransmitAckFlag) {
394 		LPI2C_SlaveTransmitAck(config->base, data->send_ack);
395 	}
396 }
397 
mcux_lpi2c_target_register(const struct device * dev,struct i2c_target_config * target_config)398 static int mcux_lpi2c_target_register(const struct device *dev,
399 				      struct i2c_target_config *target_config)
400 {
401 	const struct mcux_lpi2c_config *config = dev->config;
402 	struct mcux_lpi2c_data *data = dev->data;
403 	lpi2c_slave_config_t slave_config;
404 	uint32_t clock_freq;
405 
406 	LPI2C_MasterDeinit(config->base);
407 
408 	/* Get the clock frequency */
409 	if (clock_control_get_rate(config->clock_dev, config->clock_subsys,
410 				   &clock_freq)) {
411 		return -EINVAL;
412 	}
413 
414 	if (!target_config) {
415 		return -EINVAL;
416 	}
417 
418 	if (data->target_attached) {
419 		return -EBUSY;
420 	}
421 
422 	data->target_attached = true;
423 	data->target_cfg = target_config;
424 	data->first_tx = false;
425 
426 	LPI2C_SlaveGetDefaultConfig(&slave_config);
427 	slave_config.address0 = target_config->address;
428 	/* Note- this setting enables clock stretching to allow the
429 	 * slave to respond to each byte with an ACK/NAK.
430 	 * this behavior may cause issues with some I2C controllers.
431 	 */
432 	slave_config.sclStall.enableAck = true;
433 	LPI2C_SlaveInit(config->base, &slave_config, clock_freq);
434 	/* Clear all flags. */
435 	LPI2C_SlaveClearStatusFlags(config->base, (uint32_t)kLPI2C_SlaveClearFlags);
436 	/* Enable interrupt */
437 	LPI2C_SlaveEnableInterrupts(config->base,
438 					(kLPI2C_SlaveTxReadyFlag |
439 					kLPI2C_SlaveRxReadyFlag |
440 					kLPI2C_SlaveStopDetectFlag |
441 					kLPI2C_SlaveAddressValidFlag |
442 					kLPI2C_SlaveTransmitAckFlag));
443 	return 0;
444 }
445 
mcux_lpi2c_target_unregister(const struct device * dev,struct i2c_target_config * target_config)446 static int mcux_lpi2c_target_unregister(const struct device *dev,
447 					struct i2c_target_config *target_config)
448 {
449 	const struct mcux_lpi2c_config *config = dev->config;
450 	struct mcux_lpi2c_data *data = dev->data;
451 
452 	if (!data->target_attached) {
453 		return -EINVAL;
454 	}
455 
456 	data->target_cfg = NULL;
457 	data->target_attached = false;
458 
459 	LPI2C_SlaveDeinit(config->base);
460 
461 	return 0;
462 }
463 #endif /* CONFIG_I2C_TARGET */
464 
mcux_lpi2c_isr(const struct device * dev)465 static void mcux_lpi2c_isr(const struct device *dev)
466 {
467 	const struct mcux_lpi2c_config *config = dev->config;
468 	struct mcux_lpi2c_data *data = dev->data;
469 	LPI2C_Type *base = config->base;
470 
471  #ifdef CONFIG_I2C_TARGET
472 	if (data->target_attached) {
473 		mcux_lpi2c_slave_irq_handler(dev);
474 	}
475 #endif /* CONFIG_I2C_TARGET */
476 
477 	LPI2C_MasterTransferHandleIRQ(base, &data->handle);
478 }
479 
mcux_lpi2c_init(const struct device * dev)480 static int mcux_lpi2c_init(const struct device *dev)
481 {
482 	const struct mcux_lpi2c_config *config = dev->config;
483 	struct mcux_lpi2c_data *data = dev->data;
484 	LPI2C_Type *base = config->base;
485 	uint32_t clock_freq, bitrate_cfg;
486 	lpi2c_master_config_t master_config;
487 	int error;
488 
489 	k_sem_init(&data->lock, 1, 1);
490 	k_sem_init(&data->device_sync_sem, 0, K_SEM_MAX_LIMIT);
491 
492 	if (!device_is_ready(config->clock_dev)) {
493 		LOG_ERR("clock control device not ready");
494 		return -ENODEV;
495 	}
496 
497 	error = pinctrl_apply_state(config->pincfg, PINCTRL_STATE_DEFAULT);
498 	if (error) {
499 		return error;
500 	}
501 
502 	if (clock_control_get_rate(config->clock_dev, config->clock_subsys,
503 				   &clock_freq)) {
504 		return -EINVAL;
505 	}
506 
507 	LPI2C_MasterGetDefaultConfig(&master_config);
508 	master_config.busIdleTimeout_ns = config->bus_idle_timeout_ns;
509 	LPI2C_MasterInit(base, &master_config, clock_freq);
510 	LPI2C_MasterTransferCreateHandle(base, &data->handle,
511 					 mcux_lpi2c_master_transfer_callback,
512 					 data);
513 
514 	bitrate_cfg = i2c_map_dt_bitrate(config->bitrate);
515 
516 	error = mcux_lpi2c_configure(dev, I2C_MODE_CONTROLLER | bitrate_cfg);
517 	if (error) {
518 		return error;
519 	}
520 
521 	config->irq_config_func(dev);
522 
523 	return 0;
524 }
525 
526 static const struct i2c_driver_api mcux_lpi2c_driver_api = {
527 	.configure = mcux_lpi2c_configure,
528 	.transfer = mcux_lpi2c_transfer,
529 #if CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY
530 	.recover_bus = mcux_lpi2c_recover_bus,
531 #endif /* CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY */
532 #if CONFIG_I2C_TARGET
533 	.target_register = mcux_lpi2c_target_register,
534 	.target_unregister = mcux_lpi2c_target_unregister,
535 #endif /* CONFIG_I2C_TARGET */
536 };
537 
538 #if CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY
539 #define I2C_MCUX_LPI2C_SCL_INIT(n) .scl = GPIO_DT_SPEC_INST_GET_OR(n, scl_gpios, {0}),
540 #define I2C_MCUX_LPI2C_SDA_INIT(n) .sda = GPIO_DT_SPEC_INST_GET_OR(n, sda_gpios, {0}),
541 #else
542 #define I2C_MCUX_LPI2C_SCL_INIT(n)
543 #define I2C_MCUX_LPI2C_SDA_INIT(n)
544 #endif /* CONFIG_I2C_MCUX_LPI2C_BUS_RECOVERY */
545 
546 #define I2C_MCUX_LPI2C_INIT(n)						\
547 	PINCTRL_DT_INST_DEFINE(n);					\
548 									\
549 	static void mcux_lpi2c_config_func_##n(const struct device *dev); \
550 									\
551 	static const struct mcux_lpi2c_config mcux_lpi2c_config_##n = {	\
552 		.base = (LPI2C_Type *)DT_INST_REG_ADDR(n),		\
553 		.clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(n)),	\
554 		.clock_subsys =						\
555 			(clock_control_subsys_t)DT_INST_CLOCKS_CELL(n, name),\
556 		.irq_config_func = mcux_lpi2c_config_func_##n,		\
557 		.bitrate = DT_INST_PROP(n, clock_frequency),		\
558 		.pincfg = PINCTRL_DT_INST_DEV_CONFIG_GET(n),		\
559 		I2C_MCUX_LPI2C_SCL_INIT(n)				\
560 		I2C_MCUX_LPI2C_SDA_INIT(n)				\
561 		.bus_idle_timeout_ns =					\
562 			UTIL_AND(DT_INST_NODE_HAS_PROP(n, bus_idle_timeout),\
563 				 DT_INST_PROP(n, bus_idle_timeout)),	\
564 	};								\
565 									\
566 	static struct mcux_lpi2c_data mcux_lpi2c_data_##n;		\
567 									\
568 	I2C_DEVICE_DT_INST_DEFINE(n, mcux_lpi2c_init, NULL,		\
569 			    &mcux_lpi2c_data_##n,			\
570 			    &mcux_lpi2c_config_##n, POST_KERNEL,	\
571 			    CONFIG_I2C_INIT_PRIORITY,			\
572 			    &mcux_lpi2c_driver_api);			\
573 									\
574 	static void mcux_lpi2c_config_func_##n(const struct device *dev) \
575 	{								\
576 		IRQ_CONNECT(DT_INST_IRQN(n),				\
577 			    DT_INST_IRQ(n, priority),			\
578 			    mcux_lpi2c_isr,				\
579 			    DEVICE_DT_INST_GET(n), 0);			\
580 									\
581 		irq_enable(DT_INST_IRQN(n));				\
582 	}
583 
584 DT_INST_FOREACH_STATUS_OKAY(I2C_MCUX_LPI2C_INIT)
585