sdcard.c 12.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

27
#include STM32_HAL_H
Damien George's avatar
Damien George committed
28

29
30
#include "py/nlr.h"
#include "py/runtime.h"
Damien George's avatar
Damien George committed
31
#include "sdcard.h"
32
#include "pin.h"
33
#include "genhdr/pins.h"
34
#include "bufhelper.h"
35
36
#include "dma.h"
#include "irq.h"
Damien George's avatar
Damien George committed
37

38
#if MICROPY_HW_HAS_SDCARD
Damien George's avatar
Damien George committed
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#if defined(MCU_SERIES_F7)

// The F7 series calls the peripheral SDMMC rather than SDIO, so provide some
// #defines for backwards compatability.

#define SDIO    SDMMC1

#define SDIO_CLOCK_EDGE_RISING              SDMMC_CLOCK_EDGE_RISING
#define SDIO_CLOCK_EDGE_FALLING             SDMMC_CLOCK_EDGE_FALLING

#define SDIO_CLOCK_BYPASS_DISABLE           SDMMC_CLOCK_BYPASS_DISABLE
#define SDIO_CLOCK_BYPASS_ENABLE            SDMMC_CLOCK_BYPASS_ENABLE

#define SDIO_CLOCK_POWER_SAVE_DISABLE       SDMMC_CLOCK_POWER_SAVE_DISABLE
#define SDIO_CLOCK_POWER_SAVE_ENABLE        SDMMC_CLOCK_POWER_SAVE_ENABLE

#define SDIO_BUS_WIDE_1B                    SDMMC_BUS_WIDE_1B
#define SDIO_BUS_WIDE_4B                    SDMMC_BUS_WIDE_4B
#define SDIO_BUS_WIDE_8B                    SDMMC_BUS_WIDE_8B

#define SDIO_HARDWARE_FLOW_CONTROL_DISABLE  SDMMC_HARDWARE_FLOW_CONTROL_DISABLE
#define SDIO_HARDWARE_FLOW_CONTROL_ENABLE   SDMMC_HARDWARE_FLOW_CONTROL_ENABLE

#define SDIO_TRANSFER_CLK_DIV               SDMMC_TRANSFER_CLK_DIV

#endif

67
68
69
// TODO: I think that as an optimization, we can allocate these dynamically
//       if an sd card is detected. This will save approx 260 bytes of RAM
//       when no sdcard was being used.
70
static SD_HandleTypeDef sd_handle;
71
72
static DMA_HandleTypeDef sd_rx_dma, sd_tx_dma;
static DMA_InitTypeDef sd_rx_dma_init, sd_tx_dma_init;
Damien George's avatar
Damien George committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

void sdcard_init(void) {
    GPIO_InitTypeDef GPIO_Init_Structure;

    // invalidate the sd_handle
    sd_handle.Instance = NULL;

    // configure SD GPIO
    // we do this here an not in HAL_SD_MspInit because it apparently
    // makes it more robust to have the pins always pulled high
    GPIO_Init_Structure.Mode = GPIO_MODE_AF_PP;
    GPIO_Init_Structure.Pull = GPIO_PULLUP;
    GPIO_Init_Structure.Speed = GPIO_SPEED_HIGH;
    GPIO_Init_Structure.Alternate = GPIO_AF12_SDIO;
    GPIO_Init_Structure.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12;
    HAL_GPIO_Init(GPIOC, &GPIO_Init_Structure);
    GPIO_Init_Structure.Pin = GPIO_PIN_2;
    HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

    // configure the SD card detect pin
    // we do this here so we can detect if the SD card is inserted before powering it on
    GPIO_Init_Structure.Mode = GPIO_MODE_INPUT;
95
    GPIO_Init_Structure.Pull = MICROPY_HW_SDCARD_DETECT_PULL;
Damien George's avatar
Damien George committed
96
    GPIO_Init_Structure.Speed = GPIO_SPEED_HIGH;
97
98
    GPIO_Init_Structure.Pin = MICROPY_HW_SDCARD_DETECT_PIN.pin_mask;
    HAL_GPIO_Init(MICROPY_HW_SDCARD_DETECT_PIN.gpio, &GPIO_Init_Structure);
Damien George's avatar
Damien George committed
99
100
101
102
103
104
}

void HAL_SD_MspInit(SD_HandleTypeDef *hsd) {
    // enable SDIO clock
    __SDIO_CLK_ENABLE();

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    // NVIC configuration for SDIO interrupts
    HAL_NVIC_SetPriority(SDIO_IRQn, IRQ_PRI_SDIO, IRQ_SUBPRI_SDIO);
    HAL_NVIC_EnableIRQ(SDIO_IRQn);

    // TODO: Since SDIO is fundamentally half-duplex, we really only need to
    //       tie up one DMA channel. However, the HAL DMA API doesn't
    // seem to provide a convenient way to change the direction. I believe that
    // its as simple as changing the CR register and the Init.Direction field
    // and make DMA_SetConfig public.

    // Configure DMA Rx parameters
    sd_rx_dma_init.PeriphInc           = DMA_PINC_DISABLE;
    sd_rx_dma_init.MemInc              = DMA_MINC_ENABLE;
    sd_rx_dma_init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    sd_rx_dma_init.MemDataAlignment    = DMA_MDATAALIGN_WORD;
    sd_rx_dma_init.Mode                = DMA_PFCTRL;
    sd_rx_dma_init.Priority            = DMA_PRIORITY_VERY_HIGH;
    sd_rx_dma_init.FIFOMode            = DMA_FIFOMODE_ENABLE;
    sd_rx_dma_init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
    sd_rx_dma_init.MemBurst            = DMA_MBURST_INC4;
    sd_rx_dma_init.PeriphBurst         = DMA_PBURST_INC4;

    // Configure DMA Tx parameters
    sd_tx_dma_init.PeriphInc           = DMA_PINC_DISABLE;
    sd_tx_dma_init.MemInc              = DMA_MINC_ENABLE;
    sd_tx_dma_init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    sd_tx_dma_init.MemDataAlignment    = DMA_MDATAALIGN_WORD;
    sd_tx_dma_init.Mode                = DMA_PFCTRL;
    sd_tx_dma_init.Priority            = DMA_PRIORITY_VERY_HIGH;
    sd_tx_dma_init.FIFOMode            = DMA_FIFOMODE_ENABLE;
    sd_tx_dma_init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
    sd_tx_dma_init.MemBurst            = DMA_MBURST_INC4;
    sd_tx_dma_init.PeriphBurst         = DMA_PBURST_INC4;
Damien George's avatar
Damien George committed
138

139
    // GPIO have already been initialised by sdcard_init
Damien George's avatar
Damien George committed
140
141
142
}

void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) {
143
    HAL_NVIC_DisableIRQ(SDIO_IRQn);
Damien George's avatar
Damien George committed
144
145
146
147
    __SDIO_CLK_DISABLE();
}

bool sdcard_is_present(void) {
148
    return HAL_GPIO_ReadPin(MICROPY_HW_SDCARD_DETECT_PIN.gpio, MICROPY_HW_SDCARD_DETECT_PIN.pin_mask) == MICROPY_HW_SDCARD_DETECT_PRESENT;
Damien George's avatar
Damien George committed
149
150
151
152
153
154
}

bool sdcard_power_on(void) {
    if (!sdcard_is_present()) {
        return false;
    }
155
156
157
    if (sd_handle.Instance) {
        return true;
    }
Damien George's avatar
Damien George committed
158
159
160
161
162
163
164
165
166
167

    // SD device interface configuration
    sd_handle.Instance = SDIO;
    sd_handle.Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
    sd_handle.Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
    sd_handle.Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_DISABLE;
    sd_handle.Init.BusWide             = SDIO_BUS_WIDE_1B;
    sd_handle.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
    sd_handle.Init.ClockDiv            = SDIO_TRANSFER_CLK_DIV;

168
    // init the SD interface, with retry if it's not ready yet
Damien George's avatar
Damien George committed
169
    HAL_SD_CardInfoTypedef cardinfo;
170
171
172
173
174
    for (int retry = 10; HAL_SD_Init(&sd_handle, &cardinfo) != SD_OK; retry--) {
        if (retry == 0) {
            goto error;
        }
        HAL_Delay(50);
Damien George's avatar
Damien George committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    }

    // configure the SD bus width for wide operation
    if (HAL_SD_WideBusOperation_Config(&sd_handle, SDIO_BUS_WIDE_4B) != SD_OK) {
        HAL_SD_DeInit(&sd_handle);
        goto error;
    }

    return true;

error:
    sd_handle.Instance = NULL;
    return false;
}

void sdcard_power_off(void) {
191
192
193
194
    if (!sd_handle.Instance) {
        return;
    }
    HAL_SD_DeInit(&sd_handle); 
Damien George's avatar
Damien George committed
195
196
197
198
199
200
201
202
203
204
205
206
    sd_handle.Instance = NULL;
}

uint64_t sdcard_get_capacity_in_bytes(void) {
    if (sd_handle.Instance == NULL) {
        return 0;
    }
    HAL_SD_CardInfoTypedef cardinfo;
    HAL_SD_Get_CardInfo(&sd_handle, &cardinfo);
    return cardinfo.CardCapacity;
}

207
208
209
210
void SDIO_IRQHandler(void) {
    HAL_SD_IRQHandler(&sd_handle);
}

211
mp_uint_t sdcard_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
Damien George's avatar
Damien George committed
212
213
    // check that dest pointer is aligned on a 4-byte boundary
    if (((uint32_t)dest & 3) != 0) {
214
        return SD_ERROR;
Damien George's avatar
Damien George committed
215
216
217
218
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
219
        return SD_ERROR;
Damien George's avatar
Damien George committed
220
221
    }

222
    HAL_SD_ErrorTypedef err = SD_OK;
223

224
225
226
    if (query_irq() == IRQ_STATE_ENABLED) {
        dma_init(&sd_rx_dma, DMA_STREAM_SDIO_RX, &sd_rx_dma_init, DMA_CHANNEL_SDIO_RX, DMA_PERIPH_TO_MEMORY, &sd_handle);
        sd_handle.hdmarx = &sd_rx_dma;
Damien George's avatar
Damien George committed
227

228
229
230
231
232
        err = HAL_SD_ReadBlocks_BlockNumber_DMA(&sd_handle, (uint32_t*)dest, block_num, SDCARD_BLOCK_SIZE, num_blocks);
        if (err == SD_OK) {
            // wait for DMA transfer to finish, with a large timeout
            err = HAL_SD_CheckReadOperation(&sd_handle, 100000000);
        }
Damien George's avatar
Damien George committed
233

234
235
236
237
        dma_deinit(sd_handle.hdmarx);
        sd_handle.hdmarx = NULL;
    } else {
        err = HAL_SD_ReadBlocks_BlockNumber(&sd_handle, (uint32_t*)dest, block_num, SDCARD_BLOCK_SIZE, num_blocks);
Damien George's avatar
Damien George committed
238
239
    }

240
    return err;
Damien George's avatar
Damien George committed
241
242
}

243
mp_uint_t sdcard_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
Damien George's avatar
Damien George committed
244
245
    // check that src pointer is aligned on a 4-byte boundary
    if (((uint32_t)src & 3) != 0) {
246
        return SD_ERROR;
Damien George's avatar
Damien George committed
247
248
249
250
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
251
        return SD_ERROR;
Damien George's avatar
Damien George committed
252
253
    }

254
    HAL_SD_ErrorTypedef err = SD_OK;
Damien George's avatar
Damien George committed
255

256
257
258
    if (query_irq() == IRQ_STATE_ENABLED) {
        dma_init(&sd_tx_dma, DMA_STREAM_SDIO_TX, &sd_tx_dma_init, DMA_CHANNEL_SDIO_TX, DMA_MEMORY_TO_PERIPH, &sd_handle);
        sd_handle.hdmatx = &sd_tx_dma;
Damien George's avatar
Damien George committed
259

260
261
262
263
264
265
266
267
268
        err = HAL_SD_WriteBlocks_BlockNumber_DMA(&sd_handle, (uint32_t*)src, block_num, SDCARD_BLOCK_SIZE, num_blocks);
        if (err == SD_OK) {
            // wait for DMA transfer to finish, with a large timeout
            err = HAL_SD_CheckWriteOperation(&sd_handle, 100000000);
        }
        dma_deinit(sd_handle.hdmatx);
        sd_handle.hdmatx = NULL;
    } else {
        err = HAL_SD_WriteBlocks_BlockNumber(&sd_handle, (uint32_t*)src, block_num, SDCARD_BLOCK_SIZE, num_blocks);
Damien George's avatar
Damien George committed
269
270
    }

271
    return err;
Damien George's avatar
Damien George committed
272
273
274
275
}

/******************************************************************************/
// Micro Python bindings
276
277
278
279
//
// Note: these function are a bit ad-hoc at the moment and are mainly intended
// for testing purposes.  In the future SD should be a proper class with a
// consistent interface and methods to mount/unmount it.
Damien George's avatar
Damien George committed
280

281
STATIC mp_obj_t sd_present(mp_obj_t self) {
282
    return mp_obj_new_bool(sdcard_is_present());
Damien George's avatar
Damien George committed
283
}
284
STATIC MP_DEFINE_CONST_FUN_OBJ_1(sd_present_obj, sd_present);
Damien George's avatar
Damien George committed
285

286
STATIC mp_obj_t sd_power(mp_obj_t self, mp_obj_t state) {
Damien George's avatar
Damien George committed
287
    bool result;
Damien George's avatar
Damien George committed
288
    if (mp_obj_is_true(state)) {
Damien George's avatar
Damien George committed
289
290
291
292
293
        result = sdcard_power_on();
    } else {
        sdcard_power_off();
        result = true;
    }
294
    return mp_obj_new_bool(result);
Damien George's avatar
Damien George committed
295
}
296
STATIC MP_DEFINE_CONST_FUN_OBJ_2(sd_power_obj, sd_power);
Damien George's avatar
Damien George committed
297

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
STATIC mp_obj_t sd_info(mp_obj_t self) {
    if (sd_handle.Instance == NULL) {
        return mp_const_none;
    }
    HAL_SD_CardInfoTypedef cardinfo;
    HAL_SD_Get_CardInfo(&sd_handle, &cardinfo);
    // cardinfo.SD_csd and cardinfo.SD_cid have lots of info but we don't use them
    mp_obj_t tuple[3] = {
        mp_obj_new_int_from_ull(cardinfo.CardCapacity),
        mp_obj_new_int_from_uint(cardinfo.CardBlockSize),
        mp_obj_new_int(cardinfo.CardType),
    };
    return mp_obj_new_tuple(3, tuple);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(sd_info_obj, sd_info);
Damien George's avatar
Damien George committed
313

314
STATIC mp_obj_t sd_read(mp_obj_t self, mp_obj_t block_num) {
Damien George's avatar
Damien George committed
315
    uint8_t *dest = m_new(uint8_t, SDCARD_BLOCK_SIZE);
316
317
318
    mp_uint_t ret = sdcard_read_blocks(dest, mp_obj_get_int(block_num), 1);

    if (ret != 0) {
319
        m_del(uint8_t, dest, SDCARD_BLOCK_SIZE);
320
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "sdcard_read_blocks failed [%u]", ret));
Damien George's avatar
Damien George committed
321
    }
322

Damien George's avatar
Damien George committed
323
324
    return mp_obj_new_bytearray_by_ref(SDCARD_BLOCK_SIZE, dest);
}
325
STATIC MP_DEFINE_CONST_FUN_OBJ_2(sd_read_obj, sd_read);
Damien George's avatar
Damien George committed
326

327
STATIC mp_obj_t sd_write(mp_obj_t self, mp_obj_t block_num, mp_obj_t data) {
328
    mp_buffer_info_t bufinfo;
329
    mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
330
    if (bufinfo.len % SDCARD_BLOCK_SIZE != 0) {
331
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "writes must be a multiple of %d bytes", SDCARD_BLOCK_SIZE));
332
333
    }

334
335
336
337
    mp_uint_t ret = sdcard_write_blocks(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SDCARD_BLOCK_SIZE);

    if (ret != 0) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "sdcard_write_blocks failed [%u]", ret));
338
    }
339

340
341
    return mp_const_none;
}
342
STATIC MP_DEFINE_CONST_FUN_OBJ_3(sd_write_obj, sd_write);
343

344
345
346
STATIC const mp_map_elem_t sdcard_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_present), (mp_obj_t)&sd_present_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_power), (mp_obj_t)&sd_power_obj },
347
    { MP_OBJ_NEW_QSTR(MP_QSTR_info), (mp_obj_t)&sd_info_obj },
348
    { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&sd_read_obj },
349
    { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&sd_write_obj },
Damien George's avatar
Damien George committed
350
351
};

352
353
STATIC MP_DEFINE_CONST_DICT(sdcard_locals_dict, sdcard_locals_dict_table);

Damien George's avatar
Damien George committed
354
355
356
static const mp_obj_type_t sdcard_type = {
    { &mp_type_type },
    .name = MP_QSTR_SDcard,
357
    .locals_dict = (mp_obj_t)&sdcard_locals_dict,
Damien George's avatar
Damien George committed
358
359
360
};

const mp_obj_base_t pyb_sdcard_obj = {&sdcard_type};
361
362

#endif // MICROPY_HW_HAS_SDCARD