1 /*
2  * Copyright (c) 2018, Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/spi.h>
8 #include <zephyr/drivers/spi/rtio.h>
9 #include <zephyr/drivers/pinctrl.h>
10 #include <zephyr/drivers/gpio.h>
11 #include <soc.h>
12 #include <nrfx_spis.h>
13 #include <zephyr/pm/device.h>
14 #include <zephyr/pm/device_runtime.h>
15 
16 #include <zephyr/logging/log.h>
17 #include <zephyr/irq.h>
18 LOG_MODULE_REGISTER(spi_nrfx_spis, CONFIG_SPI_LOG_LEVEL);
19 
20 #include "spi_context.h"
21 
22 struct spi_nrfx_data {
23 	struct spi_context ctx;
24 	const struct device *dev;
25 	struct k_sem wake_sem;
26 	struct gpio_callback wake_cb_data;
27 };
28 
29 struct spi_nrfx_config {
30 	nrfx_spis_t spis;
31 	nrfx_spis_config_t config;
32 	void (*irq_connect)(void);
33 	uint16_t max_buf_len;
34 	const struct pinctrl_dev_config *pcfg;
35 	struct gpio_dt_spec wake_gpio;
36 };
37 
get_nrf_spis_mode(uint16_t operation)38 static inline nrf_spis_mode_t get_nrf_spis_mode(uint16_t operation)
39 {
40 	if (SPI_MODE_GET(operation) & SPI_MODE_CPOL) {
41 		if (SPI_MODE_GET(operation) & SPI_MODE_CPHA) {
42 			return NRF_SPIS_MODE_3;
43 		} else {
44 			return NRF_SPIS_MODE_2;
45 		}
46 	} else {
47 		if (SPI_MODE_GET(operation) & SPI_MODE_CPHA) {
48 			return NRF_SPIS_MODE_1;
49 		} else {
50 			return NRF_SPIS_MODE_0;
51 		}
52 	}
53 }
54 
get_nrf_spis_bit_order(uint16_t operation)55 static inline nrf_spis_bit_order_t get_nrf_spis_bit_order(uint16_t operation)
56 {
57 	if (operation & SPI_TRANSFER_LSB) {
58 		return NRF_SPIS_BIT_ORDER_LSB_FIRST;
59 	} else {
60 		return NRF_SPIS_BIT_ORDER_MSB_FIRST;
61 	}
62 }
63 
configure(const struct device * dev,const struct spi_config * spi_cfg)64 static int configure(const struct device *dev,
65 		     const struct spi_config *spi_cfg)
66 {
67 	const struct spi_nrfx_config *dev_config = dev->config;
68 	struct spi_nrfx_data *dev_data = dev->data;
69 	struct spi_context *ctx = &dev_data->ctx;
70 
71 	if (spi_context_configured(ctx, spi_cfg)) {
72 		/* Already configured. No need to do it again. */
73 		return 0;
74 	}
75 
76 	if (spi_cfg->operation & SPI_HALF_DUPLEX) {
77 		LOG_ERR("Half-duplex not supported");
78 		return -ENOTSUP;
79 	}
80 
81 	if (SPI_OP_MODE_GET(spi_cfg->operation) == SPI_OP_MODE_MASTER) {
82 		LOG_ERR("Master mode is not supported on %s", dev->name);
83 		return -EINVAL;
84 	}
85 
86 	if (spi_cfg->operation & SPI_MODE_LOOP) {
87 		LOG_ERR("Loopback mode is not supported");
88 		return -EINVAL;
89 	}
90 
91 	if (IS_ENABLED(CONFIG_SPI_EXTENDED_MODES) &&
92 	    (spi_cfg->operation & SPI_LINES_MASK) != SPI_LINES_SINGLE) {
93 		LOG_ERR("Only single line mode is supported");
94 		return -EINVAL;
95 	}
96 
97 	if (SPI_WORD_SIZE_GET(spi_cfg->operation) != 8) {
98 		LOG_ERR("Word sizes other than 8 bits are not supported");
99 		return -EINVAL;
100 	}
101 
102 	if (spi_cs_is_gpio(spi_cfg)) {
103 		LOG_ERR("CS control via GPIO is not supported");
104 		return -EINVAL;
105 	}
106 
107 	ctx->config = spi_cfg;
108 
109 	nrf_spis_configure(dev_config->spis.p_reg,
110 			   get_nrf_spis_mode(spi_cfg->operation),
111 			   get_nrf_spis_bit_order(spi_cfg->operation));
112 
113 	return 0;
114 }
115 
prepare_for_transfer(const struct device * dev,const uint8_t * tx_buf,size_t tx_buf_len,uint8_t * rx_buf,size_t rx_buf_len)116 static int prepare_for_transfer(const struct device *dev,
117 				const uint8_t *tx_buf, size_t tx_buf_len,
118 				uint8_t *rx_buf, size_t rx_buf_len)
119 {
120 	const struct spi_nrfx_config *dev_config = dev->config;
121 	nrfx_err_t result;
122 
123 	if (tx_buf_len > dev_config->max_buf_len ||
124 	    rx_buf_len > dev_config->max_buf_len) {
125 		LOG_ERR("Invalid buffer sizes: Tx %d/Rx %d",
126 			tx_buf_len, rx_buf_len);
127 		return -EINVAL;
128 	}
129 
130 	result = nrfx_spis_buffers_set(&dev_config->spis,
131 				       tx_buf, tx_buf_len,
132 				       rx_buf, rx_buf_len);
133 	if (result != NRFX_SUCCESS) {
134 		return -EIO;
135 	}
136 
137 	return 0;
138 }
139 
wake_callback(const struct device * dev,struct gpio_callback * cb,uint32_t pins)140 static void wake_callback(const struct device *dev, struct gpio_callback *cb,
141 			  uint32_t pins)
142 {
143 	struct spi_nrfx_data *dev_data =
144 		CONTAINER_OF(cb, struct spi_nrfx_data, wake_cb_data);
145 	const struct spi_nrfx_config *dev_config = dev_data->dev->config;
146 
147 	(void)gpio_pin_interrupt_configure_dt(&dev_config->wake_gpio,
148 					      GPIO_INT_DISABLE);
149 	k_sem_give(&dev_data->wake_sem);
150 }
151 
wait_for_wake(struct spi_nrfx_data * dev_data,const struct spi_nrfx_config * dev_config)152 static void wait_for_wake(struct spi_nrfx_data *dev_data,
153 			  const struct spi_nrfx_config *dev_config)
154 {
155 	/* If the WAKE line is low, wait until it goes high - this is a signal
156 	 * from the master that it wants to perform a transfer.
157 	 */
158 	if (gpio_pin_get_raw(dev_config->wake_gpio.port,
159 			     dev_config->wake_gpio.pin) == 0) {
160 		(void)gpio_pin_interrupt_configure_dt(&dev_config->wake_gpio,
161 						      GPIO_INT_LEVEL_HIGH);
162 		(void)k_sem_take(&dev_data->wake_sem, K_FOREVER);
163 	}
164 }
165 
transceive(const struct device * dev,const struct spi_config * spi_cfg,const struct spi_buf_set * tx_bufs,const struct spi_buf_set * rx_bufs,bool asynchronous,spi_callback_t cb,void * userdata)166 static int transceive(const struct device *dev,
167 		      const struct spi_config *spi_cfg,
168 		      const struct spi_buf_set *tx_bufs,
169 		      const struct spi_buf_set *rx_bufs,
170 		      bool asynchronous,
171 		      spi_callback_t cb,
172 		      void *userdata)
173 {
174 	struct spi_nrfx_data *dev_data = dev->data;
175 	const struct spi_nrfx_config *dev_config = dev->config;
176 	const struct spi_buf *tx_buf = tx_bufs ? tx_bufs->buffers : NULL;
177 	const struct spi_buf *rx_buf = rx_bufs ? rx_bufs->buffers : NULL;
178 	int error;
179 
180 	pm_device_runtime_get(dev);
181 
182 	spi_context_lock(&dev_data->ctx, asynchronous, cb, userdata, spi_cfg);
183 
184 	error = configure(dev, spi_cfg);
185 	if (error != 0) {
186 		/* Invalid configuration. */
187 	} else if ((tx_bufs && tx_bufs->count > 1) ||
188 		   (rx_bufs && rx_bufs->count > 1)) {
189 		LOG_ERR("Scattered buffers are not supported");
190 		error = -ENOTSUP;
191 	} else if (tx_buf && tx_buf->len && !nrfx_is_in_ram(tx_buf->buf)) {
192 		LOG_ERR("Only buffers located in RAM are supported");
193 		error = -ENOTSUP;
194 	} else {
195 		if (dev_config->wake_gpio.port) {
196 			wait_for_wake(dev_data, dev_config);
197 
198 			nrf_spis_enable(dev_config->spis.p_reg);
199 		}
200 
201 		error = prepare_for_transfer(dev,
202 					     tx_buf ? tx_buf->buf : NULL,
203 					     tx_buf ? tx_buf->len : 0,
204 					     rx_buf ? rx_buf->buf : NULL,
205 					     rx_buf ? rx_buf->len : 0);
206 		if (error == 0) {
207 			if (dev_config->wake_gpio.port) {
208 				/* Set the WAKE line low (tie it to ground)
209 				 * to signal readiness to handle the transfer.
210 				 */
211 				gpio_pin_set_raw(dev_config->wake_gpio.port,
212 						 dev_config->wake_gpio.pin,
213 						 0);
214 				/* Set the WAKE line back high (i.e. disconnect
215 				 * output for its pin since it's configured in
216 				 * open drain mode) so that it can be controlled
217 				 * by the other side again.
218 				 */
219 				gpio_pin_set_raw(dev_config->wake_gpio.port,
220 						 dev_config->wake_gpio.pin,
221 						 1);
222 			}
223 
224 			error = spi_context_wait_for_completion(&dev_data->ctx);
225 		}
226 
227 		if (dev_config->wake_gpio.port) {
228 			nrf_spis_disable(dev_config->spis.p_reg);
229 		}
230 	}
231 
232 	spi_context_release(&dev_data->ctx, error);
233 
234 	return error;
235 }
236 
spi_nrfx_transceive(const struct device * dev,const struct spi_config * spi_cfg,const struct spi_buf_set * tx_bufs,const struct spi_buf_set * rx_bufs)237 static int spi_nrfx_transceive(const struct device *dev,
238 			       const struct spi_config *spi_cfg,
239 			       const struct spi_buf_set *tx_bufs,
240 			       const struct spi_buf_set *rx_bufs)
241 {
242 	return transceive(dev, spi_cfg, tx_bufs, rx_bufs, false, NULL, NULL);
243 }
244 
245 #ifdef CONFIG_SPI_ASYNC
spi_nrfx_transceive_async(const struct device * dev,const struct spi_config * spi_cfg,const struct spi_buf_set * tx_bufs,const struct spi_buf_set * rx_bufs,spi_callback_t cb,void * userdata)246 static int spi_nrfx_transceive_async(const struct device *dev,
247 				     const struct spi_config *spi_cfg,
248 				     const struct spi_buf_set *tx_bufs,
249 				     const struct spi_buf_set *rx_bufs,
250 				     spi_callback_t cb,
251 				     void *userdata)
252 {
253 	return transceive(dev, spi_cfg, tx_bufs, rx_bufs, true, cb, userdata);
254 }
255 #endif /* CONFIG_SPI_ASYNC */
256 
spi_nrfx_release(const struct device * dev,const struct spi_config * spi_cfg)257 static int spi_nrfx_release(const struct device *dev,
258 			    const struct spi_config *spi_cfg)
259 {
260 	struct spi_nrfx_data *dev_data = dev->data;
261 
262 	if (!spi_context_configured(&dev_data->ctx, spi_cfg)) {
263 		return -EINVAL;
264 	}
265 
266 	spi_context_unlock_unconditionally(&dev_data->ctx);
267 
268 	return 0;
269 }
270 
271 static DEVICE_API(spi, spi_nrfx_driver_api) = {
272 	.transceive = spi_nrfx_transceive,
273 #ifdef CONFIG_SPI_ASYNC
274 	.transceive_async = spi_nrfx_transceive_async,
275 #endif
276 #ifdef CONFIG_SPI_RTIO
277 	.iodev_submit = spi_rtio_iodev_default_submit,
278 #endif
279 	.release = spi_nrfx_release,
280 };
281 
event_handler(const nrfx_spis_evt_t * p_event,void * p_context)282 static void event_handler(const nrfx_spis_evt_t *p_event, void *p_context)
283 {
284 	struct spi_nrfx_data *dev_data = p_context;
285 
286 	if (p_event->evt_type == NRFX_SPIS_XFER_DONE) {
287 		spi_context_complete(&dev_data->ctx, dev_data->dev,
288 				     p_event->rx_amount);
289 
290 		pm_device_runtime_put(dev_data->dev);
291 	}
292 }
293 
spi_nrfx_suspend(const struct device * dev)294 static void spi_nrfx_suspend(const struct device *dev)
295 {
296 	const struct spi_nrfx_config *dev_config = dev->config;
297 
298 	if (dev_config->wake_gpio.port == NULL) {
299 		nrf_spis_disable(dev_config->spis.p_reg);
300 	}
301 
302 	(void)pinctrl_apply_state(dev_config->pcfg, PINCTRL_STATE_SLEEP);
303 }
304 
spi_nrfx_resume(const struct device * dev)305 static void spi_nrfx_resume(const struct device *dev)
306 {
307 	const struct spi_nrfx_config *dev_config = dev->config;
308 
309 	(void)pinctrl_apply_state(dev_config->pcfg, PINCTRL_STATE_DEFAULT);
310 
311 	if (dev_config->wake_gpio.port == NULL) {
312 		nrf_spis_enable(dev_config->spis.p_reg);
313 	}
314 }
315 
spi_nrfx_pm_action(const struct device * dev,enum pm_device_action action)316 static int spi_nrfx_pm_action(const struct device *dev, enum pm_device_action action)
317 {
318 	switch (action) {
319 	case PM_DEVICE_ACTION_SUSPEND:
320 		spi_nrfx_suspend(dev);
321 		return 0;
322 
323 	case PM_DEVICE_ACTION_RESUME:
324 		spi_nrfx_resume(dev);
325 		return 0;
326 
327 	default:
328 		break;
329 	}
330 
331 	return -ENOTSUP;
332 }
333 
spi_nrfx_init(const struct device * dev)334 static int spi_nrfx_init(const struct device *dev)
335 {
336 	const struct spi_nrfx_config *dev_config = dev->config;
337 	struct spi_nrfx_data *dev_data = dev->data;
338 	nrfx_err_t result;
339 	int err;
340 
341 	err = pinctrl_apply_state(dev_config->pcfg, PINCTRL_STATE_DEFAULT);
342 	if (err < 0) {
343 		return err;
344 	}
345 
346 	/* This sets only default values of mode and bit order. The ones to be
347 	 * actually used are set in configure() when a transfer is prepared.
348 	 */
349 	result = nrfx_spis_init(&dev_config->spis, &dev_config->config,
350 				event_handler, dev_data);
351 
352 	if (result != NRFX_SUCCESS) {
353 		LOG_ERR("Failed to initialize device: %s", dev->name);
354 		return -EBUSY;
355 	}
356 
357 	/* When the WAKE line is used, the SPIS peripheral is enabled
358 	 * only after the master signals that it wants to perform a
359 	 * transfer and it is disabled right after the transfer is done.
360 	 * Waiting for the WAKE line to go high, what can be done using
361 	 * the GPIO PORT event, instead of just waiting for the transfer
362 	 * with the SPIS peripheral enabled, significantly reduces idle
363 	 * power consumption.
364 	 */
365 	nrf_spis_disable(dev_config->spis.p_reg);
366 
367 	if (dev_config->wake_gpio.port) {
368 		if (!gpio_is_ready_dt(&dev_config->wake_gpio)) {
369 			return -ENODEV;
370 		}
371 
372 		/* In open drain mode, the output is disconnected when set to
373 		 * the high state, so the following will effectively configure
374 		 * the pin as an input only.
375 		 */
376 		err = gpio_pin_configure_dt(&dev_config->wake_gpio,
377 					    GPIO_INPUT |
378 					    GPIO_OUTPUT_HIGH |
379 					    GPIO_OPEN_DRAIN);
380 		if (err < 0) {
381 			return err;
382 		}
383 
384 		gpio_init_callback(&dev_data->wake_cb_data, wake_callback,
385 				   BIT(dev_config->wake_gpio.pin));
386 		err = gpio_add_callback(dev_config->wake_gpio.port,
387 					&dev_data->wake_cb_data);
388 		if (err < 0) {
389 			return err;
390 		}
391 	}
392 
393 	spi_context_unlock_unconditionally(&dev_data->ctx);
394 
395 	return pm_device_driver_init(dev, spi_nrfx_pm_action);
396 }
397 
398 /*
399  * Current factors requiring use of DT_NODELABEL:
400  *
401  * - HAL design (requirement of drv_inst_idx in nrfx_spis_t)
402  * - Name-based HAL IRQ handlers, e.g. nrfx_spis_0_irq_handler
403  */
404 
405 #define SPIS(idx) DT_NODELABEL(spi##idx)
406 #define SPIS_PROP(idx, prop) DT_PROP(SPIS(idx), prop)
407 
408 #define SPI_NRFX_SPIS_DEFINE(idx)					       \
409 	static void irq_connect##idx(void)				       \
410 	{								       \
411 		IRQ_CONNECT(DT_IRQN(SPIS(idx)), DT_IRQ(SPIS(idx), priority),   \
412 			    nrfx_isr, nrfx_spis_##idx##_irq_handler, 0);       \
413 	}								       \
414 	static struct spi_nrfx_data spi_##idx##_data = {		       \
415 		SPI_CONTEXT_INIT_LOCK(spi_##idx##_data, ctx),		       \
416 		SPI_CONTEXT_INIT_SYNC(spi_##idx##_data, ctx),		       \
417 		.dev  = DEVICE_DT_GET(SPIS(idx)),			       \
418 		.wake_sem = Z_SEM_INITIALIZER(				       \
419 			spi_##idx##_data.wake_sem, 0, 1),		       \
420 	};								       \
421 	PINCTRL_DT_DEFINE(SPIS(idx));					       \
422 	static const struct spi_nrfx_config spi_##idx##z_config = {	       \
423 		.spis = {						       \
424 			.p_reg = (NRF_SPIS_Type *)DT_REG_ADDR(SPIS(idx)),      \
425 			.drv_inst_idx = NRFX_SPIS##idx##_INST_IDX,	       \
426 		},							       \
427 		.config = {						       \
428 			.skip_gpio_cfg = true,				       \
429 			.skip_psel_cfg = true,				       \
430 			.mode      = NRF_SPIS_MODE_0,			       \
431 			.bit_order = NRF_SPIS_BIT_ORDER_MSB_FIRST,	       \
432 			.orc       = SPIS_PROP(idx, overrun_character),	       \
433 			.def       = SPIS_PROP(idx, def_char),		       \
434 		},							       \
435 		.irq_connect = irq_connect##idx,			       \
436 		.pcfg = PINCTRL_DT_DEV_CONFIG_GET(SPIS(idx)),		       \
437 		.max_buf_len = BIT_MASK(SPIS_PROP(idx, easydma_maxcnt_bits)),  \
438 		.wake_gpio = GPIO_DT_SPEC_GET_OR(SPIS(idx), wake_gpios, {0}),  \
439 	};								       \
440 	BUILD_ASSERT(!DT_NODE_HAS_PROP(SPIS(idx), wake_gpios) ||	       \
441 		     !(DT_GPIO_FLAGS(SPIS(idx), wake_gpios) & GPIO_ACTIVE_LOW),\
442 		     "WAKE line must be configured as active high");	       \
443 	PM_DEVICE_DT_DEFINE(SPIS(idx), spi_nrfx_pm_action, 1);		       \
444 	SPI_DEVICE_DT_DEFINE(SPIS(idx),					       \
445 			    spi_nrfx_init,				       \
446 			    PM_DEVICE_DT_GET(SPIS(idx)),		       \
447 			    &spi_##idx##_data,				       \
448 			    &spi_##idx##z_config,			       \
449 			    POST_KERNEL,				       \
450 			    CONFIG_SPI_INIT_PRIORITY,			       \
451 			    &spi_nrfx_driver_api)
452 
453 /* Macro creates device instance if it is enabled in devicetree. */
454 #define SPIS_DEVICE(periph, prefix, id, _) \
455 	IF_ENABLED(CONFIG_HAS_HW_NRF_SPIS##prefix##id, (SPI_NRFX_SPIS_DEFINE(prefix##id);))
456 
457 /* Macro iterates over nrfx_spis instances enabled in the nrfx_config.h. */
458 NRFX_FOREACH_ENABLED(SPIS, SPIS_DEVICE, (), (), _)
459