1 /*
2  * Copyright (c) 2015 - 2020, Nordic Semiconductor ASA
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice, this
9  *    list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * 3. Neither the name of the copyright holder nor the names of its
16  *    contributors may be used to endorse or promote products derived from this
17  *    software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <nrfx.h>
33 
34 #if NRFX_CHECK(NRFX_SPI_ENABLED)
35 
36 #if !(NRFX_CHECK(NRFX_SPI0_ENABLED) || NRFX_CHECK(NRFX_SPI1_ENABLED) || \
37       NRFX_CHECK(NRFX_SPI2_ENABLED))
38 #error "No enabled SPI instances. Check <nrfx_config.h>."
39 #endif
40 
41 #include <nrfx_spi.h>
42 #include "prs/nrfx_prs.h"
43 #include <hal/nrf_gpio.h>
44 
45 #define NRFX_LOG_MODULE SPI
46 #include <nrfx_log.h>
47 
48 // Control block - driver instance local data.
49 typedef struct
50 {
51     nrfx_spi_evt_handler_t  handler;
52     void *                  p_context;
53     nrfx_spi_evt_t          evt;  // Keep the struct that is ready for event handler. Less memcpy.
54     nrfx_drv_state_t        state;
55     volatile bool           transfer_in_progress;
56 
57     // [no need for 'volatile' attribute for the following members, as they
58     //  are not concurrently used in IRQ handlers and main line code]
59     uint8_t     ss_pin;
60     uint8_t     orc;
61     size_t      bytes_transferred;
62 
63     bool        abort;
64 } spi_control_block_t;
65 static spi_control_block_t m_cb[NRFX_SPI_ENABLED_COUNT];
66 
67 
nrfx_spi_init(nrfx_spi_t const * p_instance,nrfx_spi_config_t const * p_config,nrfx_spi_evt_handler_t handler,void * p_context)68 nrfx_err_t nrfx_spi_init(nrfx_spi_t const *        p_instance,
69                          nrfx_spi_config_t const * p_config,
70                          nrfx_spi_evt_handler_t    handler,
71                          void *                    p_context)
72 {
73     NRFX_ASSERT(p_config);
74     spi_control_block_t * p_cb  = &m_cb[p_instance->drv_inst_idx];
75     nrfx_err_t err_code;
76 
77     if (p_cb->state != NRFX_DRV_STATE_UNINITIALIZED)
78     {
79         err_code = NRFX_ERROR_INVALID_STATE;
80         NRFX_LOG_WARNING("Function: %s, error code: %s.",
81                          __func__,
82                          NRFX_LOG_ERROR_STRING_GET(err_code));
83         return err_code;
84     }
85 
86 #if NRFX_CHECK(NRFX_PRS_ENABLED)
87     static nrfx_irq_handler_t const irq_handlers[NRFX_SPI_ENABLED_COUNT] = {
88         #if NRFX_CHECK(NRFX_SPI0_ENABLED)
89         nrfx_spi_0_irq_handler,
90         #endif
91         #if NRFX_CHECK(NRFX_SPI1_ENABLED)
92         nrfx_spi_1_irq_handler,
93         #endif
94         #if NRFX_CHECK(NRFX_SPI2_ENABLED)
95         nrfx_spi_2_irq_handler,
96         #endif
97     };
98     if (nrfx_prs_acquire(p_instance->p_reg,
99             irq_handlers[p_instance->drv_inst_idx]) != NRFX_SUCCESS)
100     {
101         err_code = NRFX_ERROR_BUSY;
102         NRFX_LOG_WARNING("Function: %s, error code: %s.",
103                          __func__,
104                          NRFX_LOG_ERROR_STRING_GET(err_code));
105         return err_code;
106     }
107 #endif // NRFX_CHECK(NRFX_PRS_ENABLED)
108 
109     p_cb->handler = handler;
110     p_cb->p_context = p_context;
111 
112     uint32_t mosi_pin;
113     uint32_t miso_pin;
114     // Configure pins used by the peripheral:
115     // - SCK - output with initial value corresponding with the SPI mode used:
116     //   0 - for modes 0 and 1 (CPOL = 0), 1 - for modes 2 and 3 (CPOL = 1);
117     //   according to the reference manual guidelines this pin and its input
118     //   buffer must always be connected for the SPI to work.
119     if (p_config->mode <= NRF_SPI_MODE_1)
120     {
121         nrf_gpio_pin_clear(p_config->sck_pin);
122     }
123     else
124     {
125         nrf_gpio_pin_set(p_config->sck_pin);
126     }
127     nrf_gpio_cfg(p_config->sck_pin,
128                  NRF_GPIO_PIN_DIR_OUTPUT,
129                  NRF_GPIO_PIN_INPUT_CONNECT,
130                  NRF_GPIO_PIN_NOPULL,
131                  NRF_GPIO_PIN_S0S1,
132                  NRF_GPIO_PIN_NOSENSE);
133     // - MOSI (optional) - output with initial value 0,
134     if (p_config->mosi_pin != NRFX_SPI_PIN_NOT_USED)
135     {
136         mosi_pin = p_config->mosi_pin;
137         nrf_gpio_pin_clear(mosi_pin);
138         nrf_gpio_cfg_output(mosi_pin);
139     }
140     else
141     {
142         mosi_pin = NRF_SPI_PIN_NOT_CONNECTED;
143     }
144     // - MISO (optional) - input,
145     if (p_config->miso_pin != NRFX_SPI_PIN_NOT_USED)
146     {
147         miso_pin = p_config->miso_pin;
148         nrf_gpio_cfg_input(miso_pin, p_config->miso_pull);
149     }
150     else
151     {
152         miso_pin = NRF_SPI_PIN_NOT_CONNECTED;
153     }
154     // - Slave Select (optional) - output with initial value 1 (inactive).
155     if (p_config->ss_pin != NRFX_SPI_PIN_NOT_USED)
156     {
157         nrf_gpio_pin_set(p_config->ss_pin);
158         nrf_gpio_cfg_output(p_config->ss_pin);
159     }
160     m_cb[p_instance->drv_inst_idx].ss_pin = p_config->ss_pin;
161 
162     NRF_SPI_Type * p_spi = p_instance->p_reg;
163     nrf_spi_pins_set(p_spi, p_config->sck_pin, mosi_pin, miso_pin);
164     nrf_spi_frequency_set(p_spi, p_config->frequency);
165     nrf_spi_configure(p_spi, p_config->mode, p_config->bit_order);
166 
167     m_cb[p_instance->drv_inst_idx].orc = p_config->orc;
168 
169     nrf_spi_enable(p_spi);
170 
171     if (p_cb->handler)
172     {
173         NRFX_IRQ_PRIORITY_SET(nrfx_get_irq_number(p_instance->p_reg),
174             p_config->irq_priority);
175         NRFX_IRQ_ENABLE(nrfx_get_irq_number(p_instance->p_reg));
176     }
177 
178     p_cb->transfer_in_progress = false;
179     p_cb->state = NRFX_DRV_STATE_INITIALIZED;
180 
181     err_code = NRFX_SUCCESS;
182     NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
183     return err_code;
184 }
185 
nrfx_spi_uninit(nrfx_spi_t const * p_instance)186 void nrfx_spi_uninit(nrfx_spi_t const * p_instance)
187 {
188     spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx];
189     NRFX_ASSERT(p_cb->state != NRFX_DRV_STATE_UNINITIALIZED);
190     NRF_SPI_Type * p_spi = p_instance->p_reg;
191 
192     if (p_cb->handler)
193     {
194         NRFX_IRQ_DISABLE(nrfx_get_irq_number(p_instance->p_reg));
195         nrf_spi_int_disable(p_spi, NRF_SPI_ALL_INTS_MASK);
196     }
197 
198     nrf_spi_disable(p_spi);
199 
200     nrf_gpio_cfg_default(nrf_spi_sck_pin_get(p_spi));
201 
202     uint32_t miso_pin = nrf_spi_miso_pin_get(p_spi);
203     if (miso_pin != NRF_SPI_PIN_NOT_CONNECTED)
204     {
205         nrf_gpio_cfg_default(miso_pin);
206     }
207 
208     uint32_t mosi_pin = nrf_spi_mosi_pin_get(p_spi);
209     if (mosi_pin != NRF_SPI_PIN_NOT_CONNECTED)
210     {
211         nrf_gpio_cfg_default(mosi_pin);
212     }
213 
214     if (p_cb->ss_pin != NRFX_SPI_PIN_NOT_USED)
215     {
216         nrf_gpio_cfg_default(p_cb->ss_pin);
217     }
218 
219 #if NRFX_CHECK(NRFX_PRS_ENABLED)
220     nrfx_prs_release(p_instance->p_reg);
221 #endif
222 
223     p_cb->state = NRFX_DRV_STATE_UNINITIALIZED;
224 }
225 
finish_transfer(spi_control_block_t * p_cb)226 static void finish_transfer(spi_control_block_t * p_cb)
227 {
228     // If Slave Select signal is used, this is the time to deactivate it.
229     if (p_cb->ss_pin != NRFX_SPI_PIN_NOT_USED)
230     {
231         nrf_gpio_pin_set(p_cb->ss_pin);
232     }
233 
234     // By clearing this flag before calling the handler we allow subsequent
235     // transfers to be started directly from the handler function.
236     p_cb->transfer_in_progress = false;
237 
238     p_cb->evt.type = NRFX_SPI_EVENT_DONE;
239     p_cb->handler(&p_cb->evt, p_cb->p_context);
240 }
241 
242 // This function is called from the IRQ handler or, in blocking mode, directly
243 // from the 'spi_xfer' function.
244 // It returns true as long as the transfer should be continued, otherwise (when
245 // there is nothing more to send/receive) it returns false.
transfer_byte(NRF_SPI_Type * p_spi,spi_control_block_t * p_cb)246 static bool transfer_byte(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb)
247 {
248     // Read the data byte received in this transfer (always, because no further
249     // READY event can be generated until the current byte is read out from the
250     // RXD register), and store it in the RX buffer (only when needed).
251     volatile uint8_t rx_data = nrf_spi_rxd_get(p_spi);
252     if (p_cb->bytes_transferred < p_cb->evt.xfer_desc.rx_length)
253     {
254         p_cb->evt.xfer_desc.p_rx_buffer[p_cb->bytes_transferred] = rx_data;
255     }
256 
257     ++p_cb->bytes_transferred;
258 
259     // Check if there are more bytes to send or receive and write proper data
260     // byte (next one from TX buffer or over-run character) to the TXD register
261     // when needed.
262     // NOTE - we've already used 'p_cb->bytes_transferred + 1' bytes from our
263     //        buffers, because we take advantage of double buffering of TXD
264     //        register (so in effect one byte is still being transmitted now);
265     //        see how the transfer is started in the 'spi_xfer' function.
266     size_t bytes_used = p_cb->bytes_transferred + 1;
267 
268     if (p_cb->abort)
269     {
270         if (bytes_used < p_cb->evt.xfer_desc.tx_length)
271         {
272             p_cb->evt.xfer_desc.tx_length = bytes_used;
273         }
274         if (bytes_used < p_cb->evt.xfer_desc.rx_length)
275         {
276             p_cb->evt.xfer_desc.rx_length = bytes_used;
277         }
278     }
279 
280     if (bytes_used < p_cb->evt.xfer_desc.tx_length)
281     {
282         nrf_spi_txd_set(p_spi, p_cb->evt.xfer_desc.p_tx_buffer[bytes_used]);
283         return true;
284     }
285     else if (bytes_used < p_cb->evt.xfer_desc.rx_length)
286     {
287         nrf_spi_txd_set(p_spi, p_cb->orc);
288         return true;
289     }
290 
291     return (p_cb->bytes_transferred < p_cb->evt.xfer_desc.tx_length ||
292             p_cb->bytes_transferred < p_cb->evt.xfer_desc.rx_length);
293 }
294 
spi_xfer(NRF_SPI_Type * p_spi,spi_control_block_t * p_cb,nrfx_spi_xfer_desc_t const * p_xfer_desc)295 static void spi_xfer(NRF_SPI_Type               * p_spi,
296                      spi_control_block_t        * p_cb,
297                      nrfx_spi_xfer_desc_t const * p_xfer_desc)
298 {
299     p_cb->bytes_transferred = 0;
300     nrf_spi_int_disable(p_spi, NRF_SPI_INT_READY_MASK);
301 
302     nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY);
303 
304     // Start the transfer by writing some byte to the TXD register;
305     // if TX buffer is not empty, take the first byte from this buffer,
306     // otherwise - use over-run character.
307     nrf_spi_txd_set(p_spi,
308         (p_xfer_desc->tx_length > 0 ? p_xfer_desc->p_tx_buffer[0] : p_cb->orc));
309 
310     // TXD register is double buffered, so next byte to be transmitted can
311     // be written immediately, if needed, i.e. if TX or RX transfer is to
312     // be more that 1 byte long. Again - if there is something more in TX
313     // buffer send it, otherwise use over-run character.
314     if (p_xfer_desc->tx_length > 1)
315     {
316         nrf_spi_txd_set(p_spi, p_xfer_desc->p_tx_buffer[1]);
317     }
318     else if (p_xfer_desc->rx_length > 1)
319     {
320         nrf_spi_txd_set(p_spi, p_cb->orc);
321     }
322 
323     // For blocking mode (user handler not provided) wait here for READY
324     // events (indicating that the byte from TXD register was transmitted
325     // and a new incoming byte was moved to the RXD register) and continue
326     // transaction until all requested bytes are transferred.
327     // In non-blocking mode - IRQ service routine will do this stuff.
328     if (p_cb->handler)
329     {
330         nrf_spi_int_enable(p_spi, NRF_SPI_INT_READY_MASK);
331     }
332     else
333     {
334         do {
335             while (!nrf_spi_event_check(p_spi, NRF_SPI_EVENT_READY)) {}
336             nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY);
337             NRFX_LOG_DEBUG("SPI: Event: NRF_SPI_EVENT_READY.");
338         } while (transfer_byte(p_spi, p_cb));
339         if (p_cb->ss_pin != NRFX_SPI_PIN_NOT_USED)
340         {
341             nrf_gpio_pin_set(p_cb->ss_pin);
342         }
343     }
344 }
345 
nrfx_spi_xfer(nrfx_spi_t const * p_instance,nrfx_spi_xfer_desc_t const * p_xfer_desc,uint32_t flags)346 nrfx_err_t nrfx_spi_xfer(nrfx_spi_t const *           p_instance,
347                          nrfx_spi_xfer_desc_t const * p_xfer_desc,
348                          uint32_t                     flags)
349 {
350     spi_control_block_t * p_cb  = &m_cb[p_instance->drv_inst_idx];
351     NRFX_ASSERT(p_cb->state != NRFX_DRV_STATE_UNINITIALIZED);
352     NRFX_ASSERT(p_xfer_desc->p_tx_buffer != NULL || p_xfer_desc->tx_length == 0);
353     NRFX_ASSERT(p_xfer_desc->p_rx_buffer != NULL || p_xfer_desc->rx_length == 0);
354 
355     nrfx_err_t err_code = NRFX_SUCCESS;
356 
357     if (p_cb->transfer_in_progress)
358     {
359         err_code = NRFX_ERROR_BUSY;
360         NRFX_LOG_WARNING("Function: %s, error code: %s.",
361                          __func__,
362                          NRFX_LOG_ERROR_STRING_GET(err_code));
363         return err_code;
364     }
365     else
366     {
367         if (p_cb->handler)
368         {
369             p_cb->transfer_in_progress = true;
370         }
371     }
372 
373     p_cb->evt.xfer_desc = *p_xfer_desc;
374     p_cb->abort = false;
375 
376     if (p_cb->ss_pin != NRFX_SPI_PIN_NOT_USED)
377     {
378         nrf_gpio_pin_clear(p_cb->ss_pin);
379     }
380     if (flags)
381     {
382         p_cb->transfer_in_progress = false;
383         err_code = NRFX_ERROR_NOT_SUPPORTED;
384     }
385     else
386     {
387         spi_xfer(p_instance->p_reg, p_cb, p_xfer_desc);
388     }
389     NRFX_LOG_INFO("Function: %s, error code: %s.",
390                   __func__,
391                   NRFX_LOG_ERROR_STRING_GET(err_code));
392     return err_code;
393 }
394 
nrfx_spi_abort(nrfx_spi_t const * p_instance)395 void nrfx_spi_abort(nrfx_spi_t const * p_instance)
396 {
397     spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx];
398     NRFX_ASSERT(p_cb->state != NRFX_DRV_STATE_UNINITIALIZED);
399     p_cb->abort = true;
400 }
401 
irq_handler(NRF_SPI_Type * p_spi,spi_control_block_t * p_cb)402 static void irq_handler(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb)
403 {
404     NRFX_ASSERT(p_cb->handler);
405 
406     nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY);
407     NRFX_LOG_DEBUG("Event: NRF_SPI_EVENT_READY.");
408 
409     if (!transfer_byte(p_spi, p_cb))
410     {
411         finish_transfer(p_cb);
412     }
413 }
414 
415 #if NRFX_CHECK(NRFX_SPI0_ENABLED)
nrfx_spi_0_irq_handler(void)416 void nrfx_spi_0_irq_handler(void)
417 {
418     irq_handler(NRF_SPI0, &m_cb[NRFX_SPI0_INST_IDX]);
419 }
420 #endif
421 
422 #if NRFX_CHECK(NRFX_SPI1_ENABLED)
nrfx_spi_1_irq_handler(void)423 void nrfx_spi_1_irq_handler(void)
424 {
425     irq_handler(NRF_SPI1, &m_cb[NRFX_SPI1_INST_IDX]);
426 }
427 #endif
428 
429 #if NRFX_CHECK(NRFX_SPI2_ENABLED)
nrfx_spi_2_irq_handler(void)430 void nrfx_spi_2_irq_handler(void)
431 {
432     irq_handler(NRF_SPI2, &m_cb[NRFX_SPI2_INST_IDX]);
433 }
434 #endif
435 
436 #endif // NRFX_CHECK(NRFX_SPI_ENABLED)
437