1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2020-2021 Damien P. George
7  * Copyright (c) 2021 Robert Hammelrath
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "py/runtime.h"
29 #include "py/mphal.h"
30 #include "py/mperrno.h"
31 #include "extmod/machine_spi.h"
32 #include "modmachine.h"
33 #include "dma_channel.h"
34 
35 #include "fsl_cache.h"
36 #include "fsl_dmamux.h"
37 #include "fsl_iomuxc.h"
38 #include "fsl_lpspi.h"
39 #include "fsl_lpspi_edma.h"
40 
41 #define DEFAULT_SPI_BAUDRATE    (1000000)
42 #define DEFAULT_SPI_POLARITY    (0)
43 #define DEFAULT_SPI_PHASE       (0)
44 #define DEFAULT_SPI_BITS        (8)
45 #define DEFAULT_SPI_FIRSTBIT    (kLPSPI_MsbFirst)
46 #define DEFAULT_SPI_DRIVE       (6)
47 
48 #define CLOCK_DIVIDER           (1)
49 
50 #define MICROPY_HW_SPI_NUM MP_ARRAY_SIZE(spi_index_table)
51 
52 #define SCK (iomux_table[index])
53 #define CS0 (iomux_table[index + 1])
54 #define SDO (iomux_table[index + 2])
55 #define SDI (iomux_table[index + 3])
56 
57 typedef struct _machine_spi_obj_t {
58     mp_obj_base_t base;
59     uint8_t spi_id;
60     uint8_t mode;
61     uint8_t spi_hw_id;
62     bool transfer_busy;
63     LPSPI_Type *spi_inst;
64     lpspi_master_config_t *master_config;
65 } machine_spi_obj_t;
66 
67 typedef struct _iomux_table_t {
68     uint32_t muxRegister;
69     uint32_t muxMode;
70     uint32_t inputRegister;
71     uint32_t inputDaisy;
72     uint32_t configRegister;
73 } iomux_table_t;
74 
75 STATIC const uint8_t spi_index_table[] = MICROPY_HW_SPI_INDEX;
76 STATIC LPSPI_Type *spi_base_ptr_table[] = LPSPI_BASE_PTRS;
77 static const iomux_table_t iomux_table[] = {
78     IOMUX_TABLE_SPI
79 };
80 
81 static uint16_t dma_req_src_rx[] = DMA_REQ_SRC_RX;
82 static uint16_t dma_req_src_tx[] = DMA_REQ_SRC_TX;
83 
lpspi_set_iomux(int8_t spi,uint8_t drive)84 bool lpspi_set_iomux(int8_t spi, uint8_t drive) {
85     int index = (spi - 1) * 4;
86 
87     if (SCK.muxRegister != 0) {
88         IOMUXC_SetPinMux(SCK.muxRegister, SCK.muxMode, SCK.inputRegister, SCK.inputDaisy, SCK.configRegister, 0U);
89         IOMUXC_SetPinConfig(SCK.muxRegister, SCK.muxMode, SCK.inputRegister, SCK.inputDaisy, SCK.configRegister,
90             0x1080u | drive << IOMUXC_SW_PAD_CTL_PAD_DSE_SHIFT);
91 
92         IOMUXC_SetPinMux(CS0.muxRegister, CS0.muxMode, CS0.inputRegister, CS0.inputDaisy, CS0.configRegister, 0U);
93         IOMUXC_SetPinConfig(CS0.muxRegister, CS0.muxMode, CS0.inputRegister, CS0.inputDaisy, CS0.configRegister,
94             0x1080u | drive << IOMUXC_SW_PAD_CTL_PAD_DSE_SHIFT);
95 
96         IOMUXC_SetPinMux(SDO.muxRegister, SDO.muxMode, SDO.inputRegister, SDO.inputDaisy, SDO.configRegister, 0U);
97         IOMUXC_SetPinConfig(SDO.muxRegister, SDO.muxMode, SDO.inputRegister, SDO.inputDaisy, SDO.configRegister,
98             0x1080u | drive << IOMUXC_SW_PAD_CTL_PAD_DSE_SHIFT);
99 
100         IOMUXC_SetPinMux(SDI.muxRegister, SDI.muxMode, SDI.inputRegister, SDI.inputDaisy, SDI.configRegister, 0U);
101         IOMUXC_SetPinConfig(SDI.muxRegister, SDI.muxMode, SDI.inputRegister, SDI.inputDaisy, SDI.configRegister,
102             0x1080u | drive << IOMUXC_SW_PAD_CTL_PAD_DSE_SHIFT);
103 
104         return true;
105     } else {
106         return false;
107     }
108 }
109 
machine_spi_print(const mp_print_t * print,mp_obj_t self_in,mp_print_kind_t kind)110 STATIC void machine_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
111     static const char *firstbit_str[] = {"MSB", "LSB"};
112     machine_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
113     mp_printf(print, "SPI(%u, baudrate=%u, polarity=%u, phase=%u, bits=%u, firstbit=%s, gap_ns=%d)",
114         self->spi_id, self->master_config->baudRate, self->master_config->cpol,
115         self->master_config->cpha, self->master_config->bitsPerFrame,
116         firstbit_str[self->master_config->direction], self->master_config->betweenTransferDelayInNanoSec);
117 }
118 
machine_spi_make_new(const mp_obj_type_t * type,size_t n_args,size_t n_kw,const mp_obj_t * all_args)119 mp_obj_t machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
120     enum { ARG_id, ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit, ARG_gap_ns, ARG_drive };
121     static const mp_arg_t allowed_args[] = {
122         { MP_QSTR_id,       MP_ARG_REQUIRED | MP_ARG_OBJ },
123         { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = DEFAULT_SPI_BAUDRATE} },
124         { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = DEFAULT_SPI_POLARITY} },
125         { MP_QSTR_phase,    MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = DEFAULT_SPI_PHASE} },
126         { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = DEFAULT_SPI_BITS} },
127         { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = DEFAULT_SPI_FIRSTBIT} },
128         { MP_QSTR_gap_ns,   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
129         { MP_QSTR_drive,    MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = DEFAULT_SPI_DRIVE} },
130     };
131 
132     static bool clk_init = true;
133 
134     // Parse the arguments.
135     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
136     mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
137 
138     // Get the SPI bus id.
139     int spi_id = mp_obj_get_int(args[ARG_id].u_obj);
140     if (spi_id < 0 || spi_id >= MP_ARRAY_SIZE(spi_index_table)) {
141         mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("SPI(%d) doesn't exist"), spi_id);
142     }
143 
144     // Get peripheral object.
145     uint8_t spi_hw_id = spi_index_table[spi_id];  // the hw spi number 1..n
146     machine_spi_obj_t *self = m_new_obj(machine_spi_obj_t);
147     self->base.type = &machine_spi_type;
148     self->spi_id = spi_id;
149     self->spi_inst = spi_base_ptr_table[spi_hw_id];
150     self->spi_hw_id = spi_hw_id;
151 
152     uint8_t drive = args[ARG_drive].u_int;
153     if (drive < 1 || drive > 7) {
154         drive = DEFAULT_SPI_DRIVE;
155     }
156 
157     if (clk_init) {
158         clk_init = false;
159         /*Set clock source for LPSPI*/
160         CLOCK_SetMux(kCLOCK_LpspiMux, 1);  // Clock source is kCLOCK_Usb1PllPfd1Clk
161         CLOCK_SetDiv(kCLOCK_LpspiDiv, CLOCK_DIVIDER);
162     }
163     lpspi_set_iomux(spi_index_table[spi_id], drive);
164     LPSPI_Reset(self->spi_inst);
165     LPSPI_Enable(self->spi_inst, false);  // Disable first before new settings are applies
166 
167     self->master_config = m_new_obj(lpspi_master_config_t);
168     LPSPI_MasterGetDefaultConfig(self->master_config);
169     // Initialise the SPI peripheral.
170     self->master_config->baudRate = args[ARG_baudrate].u_int;
171     self->master_config->betweenTransferDelayInNanoSec = 1000000000 / self->master_config->baudRate * 2;
172     self->master_config->cpol = args[ARG_polarity].u_int;
173     self->master_config->cpha = args[ARG_phase].u_int;
174     self->master_config->bitsPerFrame = args[ARG_bits].u_int;
175     self->master_config->direction = args[ARG_firstbit].u_int;
176     if (args[ARG_gap_ns].u_int != -1) {
177         self->master_config->betweenTransferDelayInNanoSec = args[ARG_gap_ns].u_int;
178     }
179     LPSPI_MasterInit(self->spi_inst, self->master_config, CLOCK_GetFreq(kCLOCK_Usb1PllPfd0Clk) / (CLOCK_DIVIDER + 1));
180 
181     return MP_OBJ_FROM_PTR(self);
182 }
183 
machine_spi_init(mp_obj_base_t * self_in,size_t n_args,const mp_obj_t * pos_args,mp_map_t * kw_args)184 STATIC void machine_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
185     enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit, ARG_gap_ns };
186     static const mp_arg_t allowed_args[] = {
187         { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
188         { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
189         { MP_QSTR_phase,    MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
190         { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
191         { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
192         { MP_QSTR_gap_ns,   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
193     };
194 
195     // Parse the arguments.
196     machine_spi_obj_t *self = (machine_spi_obj_t *)self_in;
197     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
198     mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
199 
200     // Reconfigure the baudrate if requested.
201     if (args[ARG_baudrate].u_int != -1) {
202         self->master_config->baudRate = args[ARG_baudrate].u_int;
203         self->master_config->betweenTransferDelayInNanoSec = 1000000000 / self->master_config->baudRate * 2;
204     }
205     // Reconfigure the format if requested.
206     if (args[ARG_polarity].u_int != -1) {
207         self->master_config->cpol = args[ARG_polarity].u_int;
208     }
209     if (args[ARG_phase].u_int != -1) {
210         self->master_config->cpha = args[ARG_phase].u_int;
211     }
212     if (args[ARG_bits].u_int != -1) {
213         self->master_config->bitsPerFrame = args[ARG_bits].u_int;
214     }
215     if (args[ARG_firstbit].u_int != -1) {
216         self->master_config->direction = args[ARG_firstbit].u_int;
217     }
218     if (args[ARG_gap_ns].u_int != -1) {
219         self->master_config->betweenTransferDelayInNanoSec = args[ARG_gap_ns].u_int;
220     }
221     LPSPI_Enable(self->spi_inst, false);  // Disable first before new settings are applies
222     LPSPI_MasterInit(self->spi_inst, self->master_config, CLOCK_GetFreq(kCLOCK_Usb1PllPfd0Clk) / (CLOCK_DIVIDER + 1));
223 }
224 
LPSPI_EDMAMasterCallback(LPSPI_Type * base,lpspi_master_edma_handle_t * handle,status_t status,void * self_in)225 void LPSPI_EDMAMasterCallback(LPSPI_Type *base, lpspi_master_edma_handle_t *handle, status_t status, void *self_in) {
226     machine_spi_obj_t *self = (machine_spi_obj_t *)self_in;
227     self->transfer_busy = false;
228 }
229 
machine_spi_transfer(mp_obj_base_t * self_in,size_t len,const uint8_t * src,uint8_t * dest)230 STATIC void machine_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
231     machine_spi_obj_t *self = (machine_spi_obj_t *)self_in;
232     // Use DMA for large transfers if channels are available
233     const size_t dma_min_size_threshold = 16;  // That's the FIFO size
234 
235     int chan_tx = -1;
236     int chan_rx = -1;
237     if (len >= dma_min_size_threshold) {
238         // Use two DMA channels to service the two FIFOs
239         chan_rx = allocate_dma_channel();
240         chan_tx = allocate_dma_channel();
241     }
242     bool use_dma = chan_rx >= 0 && chan_tx >= 0;
243 
244     if (use_dma) {
245         edma_config_t userConfig;
246 
247         /* DMA MUX init*/
248         DMAMUX_Init(DMAMUX);
249 
250         DMAMUX_SetSource(DMAMUX, chan_rx, dma_req_src_rx[self->spi_hw_id]); // ## SPIn source
251         DMAMUX_EnableChannel(DMAMUX, chan_rx);
252 
253         DMAMUX_SetSource(DMAMUX, chan_tx, dma_req_src_tx[self->spi_hw_id]);
254         DMAMUX_EnableChannel(DMAMUX, chan_tx);
255 
256         EDMA_GetDefaultConfig(&userConfig);
257         EDMA_Init(DMA0, &userConfig);
258 
259         lpspi_master_edma_handle_t g_master_edma_handle;
260         edma_handle_t lpspiEdmaMasterRxRegToRxDataHandle;
261         edma_handle_t lpspiEdmaMasterTxDataToTxRegHandle;
262 
263         // Set up lpspi EDMA master
264         EDMA_CreateHandle(&(lpspiEdmaMasterRxRegToRxDataHandle), DMA0, chan_rx);
265         EDMA_CreateHandle(&(lpspiEdmaMasterTxDataToTxRegHandle), DMA0, chan_tx);
266         LPSPI_MasterTransferCreateHandleEDMA(self->spi_inst, &g_master_edma_handle, LPSPI_EDMAMasterCallback, self,
267             &lpspiEdmaMasterRxRegToRxDataHandle,
268             &lpspiEdmaMasterTxDataToTxRegHandle);
269         // Start master transfer
270         lpspi_transfer_t masterXfer;
271         masterXfer.txData = (uint8_t *)src;
272         masterXfer.rxData = (uint8_t *)dest;
273         masterXfer.dataSize = len;
274         masterXfer.configFlags = kLPSPI_MasterPcs0 | kLPSPI_MasterPcsContinuous | kLPSPI_MasterByteSwap;
275 
276         // Reconfigure the TCR, required after switch between DMA vs. non-DMA
277         LPSPI_Enable(self->spi_inst, false);  // Disable first before new settings are applied
278         self->spi_inst->TCR = LPSPI_TCR_CPOL(self->master_config->cpol) | LPSPI_TCR_CPHA(self->master_config->cpha) |
279             LPSPI_TCR_LSBF(self->master_config->direction) | LPSPI_TCR_FRAMESZ(self->master_config->bitsPerFrame - 1) |
280             (self->spi_inst->TCR & LPSPI_TCR_PRESCALE_MASK) | LPSPI_TCR_PCS(self->master_config->whichPcs);
281         LPSPI_Enable(self->spi_inst, true);
282 
283         self->transfer_busy = true;
284         if (dest) {
285             L1CACHE_DisableDCache();
286         } else if (src) {
287             DCACHE_CleanByRange((uint32_t)src, len);
288         }
289         LPSPI_MasterTransferEDMA(self->spi_inst, &g_master_edma_handle, &masterXfer);
290 
291         while (self->transfer_busy) {
292             MICROPY_EVENT_POLL_HOOK
293         }
294         L1CACHE_EnableDCache();
295     }
296     // Release DMA channels, even if never allocated.
297     if (chan_rx >= 0) {
298         free_dma_channel(chan_rx);
299     }
300     if (chan_tx >= 0) {
301         free_dma_channel(chan_tx);
302     }
303 
304     if (!use_dma) {
305         // Reconfigure the TCR, required after switch between DMA vs. non-DMA
306         LPSPI_Enable(self->spi_inst, false);  // Disable first before new settings are applied
307         self->spi_inst->TCR = LPSPI_TCR_CPOL(self->master_config->cpol) | LPSPI_TCR_CPHA(self->master_config->cpha) |
308             LPSPI_TCR_LSBF(self->master_config->direction) | LPSPI_TCR_FRAMESZ(self->master_config->bitsPerFrame - 1) |
309             (self->spi_inst->TCR & LPSPI_TCR_PRESCALE_MASK) | LPSPI_TCR_PCS(self->master_config->whichPcs);
310         LPSPI_Enable(self->spi_inst, true);
311 
312         lpspi_transfer_t masterXfer;
313         masterXfer.txData = (uint8_t *)src;
314         masterXfer.rxData = (uint8_t *)dest;
315         masterXfer.dataSize = len;
316         masterXfer.configFlags = kLPSPI_MasterPcs0 | kLPSPI_MasterPcsContinuous | kLPSPI_MasterByteSwap;
317 
318         LPSPI_MasterTransferBlocking(self->spi_inst, &masterXfer);
319     }
320 }
321 
322 STATIC const mp_machine_spi_p_t machine_spi_p = {
323     .init = machine_spi_init,
324     .transfer = machine_spi_transfer,
325 };
326 
327 const mp_obj_type_t machine_spi_type = {
328     { &mp_type_type },
329     .name = MP_QSTR_SPI,
330     .print = machine_spi_print,
331     .make_new = machine_spi_make_new,
332     .protocol = &machine_spi_p,
333     .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
334 };
335