1 /*
2  * Copyright (c) 2018, Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/i2c.h>
8 #include <zephyr/dt-bindings/i2c/i2c.h>
9 #include <zephyr/pm/device.h>
10 #include <zephyr/pm/device_runtime.h>
11 #include <zephyr/drivers/pinctrl.h>
12 #include <soc.h>
13 #include <nrfx_twim.h>
14 #include <zephyr/sys/util.h>
15 #include <zephyr/linker/devicetree_regions.h>
16 
17 #include <zephyr/logging/log.h>
18 #include <zephyr/irq.h>
19 
20 #include "i2c_nrfx_twim_common.h"
21 
22 LOG_MODULE_REGISTER(i2c_nrfx_twim, CONFIG_I2C_LOG_LEVEL);
23 
24 #if CONFIG_I2C_NRFX_TRANSFER_TIMEOUT
25 #define I2C_TRANSFER_TIMEOUT_MSEC K_MSEC(CONFIG_I2C_NRFX_TRANSFER_TIMEOUT)
26 #else
27 #define I2C_TRANSFER_TIMEOUT_MSEC K_FOREVER
28 #endif
29 
30 struct i2c_nrfx_twim_data {
31 	struct k_sem transfer_sync;
32 	struct k_sem completion_sync;
33 	volatile nrfx_err_t res;
34 };
35 
i2c_nrfx_twim_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)36 static int i2c_nrfx_twim_transfer(const struct device *dev,
37 				  struct i2c_msg *msgs,
38 				  uint8_t num_msgs, uint16_t addr)
39 {
40 	struct i2c_nrfx_twim_data *dev_data = dev->data;
41 	const struct i2c_nrfx_twim_common_config *dev_config = dev->config;
42 	int ret = 0;
43 	uint8_t *msg_buf = dev_config->msg_buf;
44 	uint16_t msg_buf_used = 0;
45 	uint16_t msg_buf_size = dev_config->msg_buf_size;
46 	uint8_t *buf;
47 	uint16_t buf_len;
48 
49 	k_sem_take(&dev_data->transfer_sync, K_FOREVER);
50 
51 	/* Dummy take on completion_sync sem to be sure that it is empty */
52 	k_sem_take(&dev_data->completion_sync, K_NO_WAIT);
53 
54 	(void)pm_device_runtime_get(dev);
55 
56 	for (size_t i = 0; i < num_msgs; i++) {
57 		if (I2C_MSG_ADDR_10_BITS & msgs[i].flags) {
58 			ret = -ENOTSUP;
59 			break;
60 		}
61 
62 		bool dma_accessible = nrf_dma_accessible_check(&dev_config->twim, msgs[i].buf);
63 
64 		/* This fragment needs to be merged with the next one if:
65 		 * - it is not the last fragment
66 		 * - it does not end a bus transaction
67 		 * - the next fragment does not start a bus transaction
68 		 * - the direction of the next fragment is the same as this one
69 		 */
70 		bool concat_next = ((i + 1) < num_msgs)
71 				&& !(msgs[i].flags & I2C_MSG_STOP)
72 				&& !(msgs[i + 1].flags & I2C_MSG_RESTART)
73 				&& ((msgs[i].flags & I2C_MSG_READ)
74 				    == (msgs[i + 1].flags & I2C_MSG_READ));
75 
76 		/* If we need to concatenate the next message, or we've
77 		 * already committed to concatenate this message, or its buffer
78 		 * is not accessible by DMA, add it to the internal driver
79 		 * buffer after verifying there's room.
80 		 */
81 		if (concat_next || (msg_buf_used != 0) || !dma_accessible) {
82 			if ((msg_buf_used + msgs[i].len) > msg_buf_size) {
83 				LOG_ERR("Need to use the internal driver "
84 					"buffer but its size is insufficient "
85 					"(%u + %u > %u). "
86 					"Adjust the zephyr,concat-buf-size or "
87 					"zephyr,flash-buf-max-size property "
88 					"(the one with greater value) in the "
89 					"\"%s\" node.",
90 					msg_buf_used, msgs[i].len,
91 					msg_buf_size, dev->name);
92 				ret = -ENOSPC;
93 				break;
94 			}
95 			if (!(msgs[i].flags & I2C_MSG_READ)) {
96 				memcpy(msg_buf + msg_buf_used,
97 				       msgs[i].buf,
98 				       msgs[i].len);
99 			}
100 			msg_buf_used += msgs[i].len;
101 		}
102 
103 		if (concat_next) {
104 			continue;
105 		}
106 
107 		if (msg_buf_used == 0) {
108 			buf = msgs[i].buf;
109 			buf_len = msgs[i].len;
110 		} else {
111 			buf = msg_buf;
112 			buf_len = msg_buf_used;
113 		}
114 		ret = i2c_nrfx_twim_msg_transfer(dev, msgs[i].flags, buf, buf_len, addr);
115 		if (ret < 0) {
116 			break;
117 		}
118 
119 		ret = k_sem_take(&dev_data->completion_sync,
120 				 I2C_TRANSFER_TIMEOUT_MSEC);
121 		if (ret != 0) {
122 			/* Whatever the frequency, completion_sync should have
123 			 * been given by the event handler.
124 			 *
125 			 * If it hasn't, it's probably due to an hardware issue
126 			 * on the I2C line, for example a short between SDA and
127 			 * GND.
128 			 * This is issue has also been when trying to use the
129 			 * I2C bus during MCU internal flash erase.
130 			 *
131 			 * In many situation, a retry is sufficient.
132 			 * However, some time the I2C device get stuck and need
133 			 * help to recover.
134 			 * Therefore we always call i2c_nrfx_twim_recover_bus()
135 			 * to make sure everything has been done to restore the
136 			 * bus from this error.
137 			 */
138 			(void)i2c_nrfx_twim_recover_bus(dev);
139 			ret = -EIO;
140 			break;
141 		}
142 
143 		if (dev_data->res != NRFX_SUCCESS) {
144 			ret = -EIO;
145 			break;
146 		}
147 
148 		/* If concatenated messages were I2C_MSG_READ type, then
149 		 * content of concatenation buffer has to be copied back into
150 		 * buffers provided by user. */
151 		if ((msgs[i].flags & I2C_MSG_READ) && (buf == msg_buf)) {
152 			int j = i;
153 
154 			while (msg_buf_used >= msgs[j].len) {
155 				msg_buf_used -= msgs[j].len;
156 				memcpy(msgs[j].buf,
157 				       msg_buf + msg_buf_used,
158 				       msgs[j].len);
159 				j--;
160 			}
161 
162 		}
163 
164 		msg_buf_used = 0;
165 	}
166 
167 	(void)pm_device_runtime_put(dev);
168 
169 	k_sem_give(&dev_data->transfer_sync);
170 
171 	return ret;
172 }
173 
event_handler(nrfx_twim_evt_t const * p_event,void * p_context)174 static void event_handler(nrfx_twim_evt_t const *p_event, void *p_context)
175 {
176 	const struct device *dev = p_context;
177 	struct i2c_nrfx_twim_data *dev_data = dev->data;
178 
179 	switch (p_event->type) {
180 	case NRFX_TWIM_EVT_DONE:
181 		dev_data->res = NRFX_SUCCESS;
182 		break;
183 	case NRFX_TWIM_EVT_ADDRESS_NACK:
184 		dev_data->res = NRFX_ERROR_DRV_TWI_ERR_ANACK;
185 		break;
186 	case NRFX_TWIM_EVT_DATA_NACK:
187 		dev_data->res = NRFX_ERROR_DRV_TWI_ERR_DNACK;
188 		break;
189 	default:
190 		dev_data->res = NRFX_ERROR_INTERNAL;
191 		break;
192 	}
193 
194 	k_sem_give(&dev_data->completion_sync);
195 }
196 
i2c_nrfx_twim_init(const struct device * dev)197 static int i2c_nrfx_twim_init(const struct device *dev)
198 {
199 	struct i2c_nrfx_twim_data *data = dev->data;
200 
201 	k_sem_init(&data->transfer_sync, 1, 1);
202 	k_sem_init(&data->completion_sync, 0, 1);
203 
204 	return i2c_nrfx_twim_common_init(dev);
205 }
206 
207 static DEVICE_API(i2c, i2c_nrfx_twim_driver_api) = {
208 	.configure = i2c_nrfx_twim_configure,
209 	.transfer = i2c_nrfx_twim_transfer,
210 #ifdef CONFIG_I2C_RTIO
211 	.iodev_submit = i2c_iodev_submit_fallback,
212 #endif
213 	.recover_bus = i2c_nrfx_twim_recover_bus,
214 };
215 
216 #define CONCAT_BUF_SIZE(idx)						       \
217 	COND_CODE_1(DT_NODE_HAS_PROP(I2C(idx), zephyr_concat_buf_size),	       \
218 		    (DT_PROP(I2C(idx), zephyr_concat_buf_size)), (0))
219 #define FLASH_BUF_MAX_SIZE(idx)						       \
220 	COND_CODE_1(DT_NODE_HAS_PROP(I2C(idx), zephyr_flash_buf_max_size),     \
221 		    (DT_PROP(I2C(idx), zephyr_flash_buf_max_size)), (0))
222 
223 #define USES_MSG_BUF(idx)						       \
224 	COND_CODE_0(CONCAT_BUF_SIZE(idx),				       \
225 		(COND_CODE_0(FLASH_BUF_MAX_SIZE(idx), (0), (1))),	       \
226 		(1))
227 #define MSG_BUF_SIZE(idx)  MAX(CONCAT_BUF_SIZE(idx), FLASH_BUF_MAX_SIZE(idx))
228 
229 #define I2C_NRFX_TWIM_DEVICE(idx)					       \
230 	NRF_DT_CHECK_NODE_HAS_PINCTRL_SLEEP(I2C(idx));			       \
231 	BUILD_ASSERT(I2C_FREQUENCY(idx) !=				       \
232 		     I2C_NRFX_TWIM_INVALID_FREQUENCY,			       \
233 		     "Wrong I2C " #idx " frequency setting in dts");	       \
234 	static void irq_connect##idx(void)				       \
235 	{								       \
236 		IRQ_CONNECT(DT_IRQN(I2C(idx)), DT_IRQ(I2C(idx), priority),     \
237 			    nrfx_isr, nrfx_twim_##idx##_irq_handler, 0);       \
238 	}								       \
239 	IF_ENABLED(USES_MSG_BUF(idx),					       \
240 		(static uint8_t twim_##idx##_msg_buf[MSG_BUF_SIZE(idx)]	       \
241 		 I2C_MEMORY_SECTION(idx);))				       \
242 	static struct i2c_nrfx_twim_data twim_##idx##_data;		       \
243 	PINCTRL_DT_DEFINE(I2C(idx));					       \
244 	static const							       \
245 	struct i2c_nrfx_twim_common_config twim_##idx##z_config = {	       \
246 		.twim = NRFX_TWIM_INSTANCE(idx),			       \
247 		.twim_config = {					       \
248 			.skip_gpio_cfg = true,				       \
249 			.skip_psel_cfg = true,				       \
250 			.frequency = I2C_FREQUENCY(idx),		       \
251 		},							       \
252 		.event_handler = event_handler,				       \
253 		.msg_buf_size = MSG_BUF_SIZE(idx),			       \
254 		.irq_connect = irq_connect##idx,			       \
255 		.pcfg = PINCTRL_DT_DEV_CONFIG_GET(I2C(idx)),		       \
256 		IF_ENABLED(USES_MSG_BUF(idx),				       \
257 			(.msg_buf = twim_##idx##_msg_buf,))		       \
258 		.max_transfer_size = BIT_MASK(				       \
259 				DT_PROP(I2C(idx), easydma_maxcnt_bits)),       \
260 	};								       \
261 	PM_DEVICE_DT_DEFINE(I2C(idx), twim_nrfx_pm_action,                     \
262 			PM_DEVICE_ISR_SAFE);                                   \
263 	I2C_DEVICE_DT_DEFINE(I2C(idx),					       \
264 		      i2c_nrfx_twim_init,				       \
265 		      PM_DEVICE_DT_GET(I2C(idx)),			       \
266 		      &twim_##idx##_data,				       \
267 		      &twim_##idx##z_config,				       \
268 		      POST_KERNEL,					       \
269 		      CONFIG_I2C_INIT_PRIORITY,				       \
270 		      &i2c_nrfx_twim_driver_api)
271 
272 #define I2C_MEMORY_SECTION(idx)						       \
273 	COND_CODE_1(I2C_HAS_PROP(idx, memory_regions),			       \
274 		(__attribute__((__section__(LINKER_DT_NODE_REGION_NAME(	       \
275 			DT_PHANDLE(I2C(idx), memory_regions)))))),	       \
276 		())
277 
278 #ifdef CONFIG_HAS_HW_NRF_TWIM0
279 I2C_NRFX_TWIM_DEVICE(0);
280 #endif
281 
282 #ifdef CONFIG_HAS_HW_NRF_TWIM1
283 I2C_NRFX_TWIM_DEVICE(1);
284 #endif
285 
286 #ifdef CONFIG_HAS_HW_NRF_TWIM2
287 I2C_NRFX_TWIM_DEVICE(2);
288 #endif
289 
290 #ifdef CONFIG_HAS_HW_NRF_TWIM3
291 I2C_NRFX_TWIM_DEVICE(3);
292 #endif
293 
294 #ifdef CONFIG_HAS_HW_NRF_TWIM20
295 I2C_NRFX_TWIM_DEVICE(20);
296 #endif
297 
298 #ifdef CONFIG_HAS_HW_NRF_TWIM21
299 I2C_NRFX_TWIM_DEVICE(21);
300 #endif
301 
302 #ifdef CONFIG_HAS_HW_NRF_TWIM22
303 I2C_NRFX_TWIM_DEVICE(22);
304 #endif
305 
306 #ifdef CONFIG_HAS_HW_NRF_TWIM30
307 I2C_NRFX_TWIM_DEVICE(30);
308 #endif
309 
310 #ifdef CONFIG_HAS_HW_NRF_TWIM120
311 I2C_NRFX_TWIM_DEVICE(120);
312 #endif
313 
314 #ifdef CONFIG_HAS_HW_NRF_TWIM130
315 I2C_NRFX_TWIM_DEVICE(130);
316 #endif
317 
318 #ifdef CONFIG_HAS_HW_NRF_TWIM131
319 I2C_NRFX_TWIM_DEVICE(131);
320 #endif
321 
322 #ifdef CONFIG_HAS_HW_NRF_TWIM132
323 I2C_NRFX_TWIM_DEVICE(132);
324 #endif
325 
326 #ifdef CONFIG_HAS_HW_NRF_TWIM133
327 I2C_NRFX_TWIM_DEVICE(133);
328 #endif
329 
330 #ifdef CONFIG_HAS_HW_NRF_TWIM134
331 I2C_NRFX_TWIM_DEVICE(134);
332 #endif
333 
334 #ifdef CONFIG_HAS_HW_NRF_TWIM135
335 I2C_NRFX_TWIM_DEVICE(135);
336 #endif
337 
338 #ifdef CONFIG_HAS_HW_NRF_TWIM136
339 I2C_NRFX_TWIM_DEVICE(136);
340 #endif
341 
342 #ifdef CONFIG_HAS_HW_NRF_TWIM137
343 I2C_NRFX_TWIM_DEVICE(137);
344 #endif
345