1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdbool.h>
8 #include <stddef.h>
9 #include <sys/param.h>
10 #include "esp_log.h"
11 #include "esp_intr_alloc.h"
12 #include "soc/soc_caps.h"
13 #include "soc/soc_pins.h"
14 #include "soc/gpio_periph.h"
15 #include "esp_rom_gpio.h"
16 #include "esp_rom_sys.h"
17 #include "driver/gpio.h"
18 #include "driver/sdmmc_host.h"
19 #include "driver/periph_ctrl.h"
20 #include "sdmmc_private.h"
21 #include "freertos/FreeRTOS.h"
22 #include "freertos/semphr.h"
23 #include "soc/sdmmc_periph.h"
24 #include "hal/gpio_hal.h"
25 
26 #define SDMMC_EVENT_QUEUE_LENGTH 32
27 
28 
29 static void sdmmc_isr(void* arg);
30 static void sdmmc_host_dma_init(void);
31 
32 static const char* TAG = "sdmmc_periph";
33 static intr_handle_t s_intr_handle;
34 static QueueHandle_t s_event_queue;
35 static SemaphoreHandle_t s_io_intr_event;
36 
37 static size_t s_slot_width[2] = {1, 1};
38 
39 /* The following definitions are used to simplify GPIO configuration in the driver,
40  * whether IOMUX or GPIO Matrix is used by the chip.
41  * Two simple "APIs" are provided to the driver code:
42  * - configure_pin(name, slot, mode): Configures signal "name" for the given slot and mode.
43  * - GPIO_NUM(slot, name): Returns the GPIO number of signal "name" for the given slot.
44  *
45  * To make this work, configure_pin is defined as a macro that picks the parameters required
46  * for configuring GPIO matrix or IOMUX from relevant arrays, and passes them to either of
47  * configure_pin_gpio_matrix, configure_pin_iomux functions.
48  * Likewise, GPIO_NUM is a macro that picks the pin number from one of the two structures.
49  *
50  * Macros are used rather than inline functions to look up members of different structures
51  * with same names. E.g. the number of pin d3 is obtained either from .d3 member of
52  * sdmmc_slot_gpio_num array (for IOMUX) or from .d3 member of s_sdmmc_slot_gpio_num array
53  * (for GPIO matrix).
54  */
55 #ifdef SOC_SDMMC_USE_GPIO_MATRIX
56 static void configure_pin_gpio_matrix(uint8_t gpio_num, uint8_t gpio_matrix_sig, gpio_mode_t mode, const char* name);
57 #define configure_pin(name, slot, mode) \
58     configure_pin_gpio_matrix(s_sdmmc_slot_gpio_num[slot].name, sdmmc_slot_gpio_sig[slot].name, mode, #name)
59 static sdmmc_slot_io_info_t s_sdmmc_slot_gpio_num[SOC_SDMMC_NUM_SLOTS];
60 #define GPIO_NUM(slot, name) s_sdmmc_slot_gpio_num[slot].name
61 
62 #elif SOC_SDMMC_USE_IOMUX
63 static void configure_pin_iomux(uint8_t gpio_num);
64 #define configure_pin(name, slot, mode) configure_pin_iomux(sdmmc_slot_gpio_num[slot].name)
65 #define GPIO_NUM(slot, name) sdmmc_slot_gpio_num[slot].name
66 
67 #endif // SOC_SDMMC_USE_GPIO_MATRIX
68 
69 static esp_err_t sdmmc_host_pullup_en_internal(int slot, int width);
70 
sdmmc_host_reset(void)71 void sdmmc_host_reset(void)
72 {
73     // Set reset bits
74     SDMMC.ctrl.controller_reset = 1;
75     SDMMC.ctrl.dma_reset = 1;
76     SDMMC.ctrl.fifo_reset = 1;
77     // Wait for the reset bits to be cleared by hardware
78     while (SDMMC.ctrl.controller_reset || SDMMC.ctrl.fifo_reset || SDMMC.ctrl.dma_reset) {
79         ;
80     }
81 }
82 
83 /* We have two clock divider stages:
84  * - one is the clock generator which drives SDMMC peripheral,
85  *   it can be configured using SDMMC.clock register. It can generate
86  *   frequencies 160MHz/(N + 1), where 0 < N < 16, I.e. from 10 to 80 MHz.
87  * - 4 clock dividers inside SDMMC peripheral, which can divide clock
88  *   from the first stage by 2 * M, where 0 < M < 255
89  *   (they can also be bypassed).
90  *
91  * For cards which aren't UHS-1 or UHS-2 cards, which we don't support,
92  * maximum bus frequency in high speed (HS) mode is 50 MHz.
93  * Note: for non-UHS-1 cards, HS mode is optional.
94  * Default speed (DS) mode is mandatory, it works up to 25 MHz.
95  * Whether the card supports HS or not can be determined using TRAN_SPEED
96  * field of card's CSD register.
97  *
98  * 50 MHz can not be obtained exactly, closest we can get is 53 MHz.
99  *
100  * The first stage divider is set to the highest possible value for the given
101  * frequency, and the the second stage dividers are used if division factor
102  * is >16.
103  *
104  * Of the second stage dividers, div0 is used for card 0, and div1 is used
105  * for card 1.
106  */
107 
sdmmc_host_set_clk_div(int div)108 static void sdmmc_host_set_clk_div(int div)
109 {
110     // Set frequency to 160MHz / div
111     // div = p + 1
112     // duty cycle = (h + 1)/(p + 1) (should be = 1/2)
113     assert (div > 1 && div <= 16);
114     int p = div - 1;
115     int h = div / 2 - 1;
116 
117     SDMMC.clock.div_factor_p = p;
118     SDMMC.clock.div_factor_h = h;
119     SDMMC.clock.div_factor_m = p;
120 
121     // Make sure 160 MHz source clock is used
122 #if SOC_SDMMC_SUPPORT_XTAL_CLOCK
123     SDMMC.clock.clk_sel = 1;
124 #endif
125 #if SOC_SDMMC_USE_GPIO_MATRIX
126     // 90 degree phase on input and output clocks
127     const int inout_clock_phase = 1;
128 #else
129     // 180 degree phase on input and output clocks
130     const int inout_clock_phase = 4;
131 #endif
132     // Set phases for in/out clocks
133     SDMMC.clock.phase_dout = inout_clock_phase;
134     SDMMC.clock.phase_din = inout_clock_phase;
135     SDMMC.clock.phase_core = 0;
136     // Wait for the clock to propagate
137     esp_rom_delay_us(10);
138 }
139 
sdmmc_host_input_clk_disable(void)140 static void sdmmc_host_input_clk_disable(void)
141 {
142     SDMMC.clock.val = 0;
143 }
144 
sdmmc_host_clock_update_command(int slot)145 static void sdmmc_host_clock_update_command(int slot)
146 {
147     // Clock update command (not a real command; just updates CIU registers)
148     sdmmc_hw_cmd_t cmd_val = {
149         .card_num = slot,
150         .update_clk_reg = 1,
151         .wait_complete = 1
152     };
153     bool repeat = true;
154     while(repeat) {
155         sdmmc_host_start_command(slot, cmd_val, 0);
156         while (true) {
157             // Sending clock update command to the CIU can generate HLE error.
158             // According to the manual, this is okay and we must retry the command.
159             if (SDMMC.rintsts.hle) {
160                 SDMMC.rintsts.hle = 1;
161                 repeat = true;
162                 break;
163             }
164             // When the command is accepted by CIU, start_command bit will be
165             // cleared in SDMMC.cmd register.
166             if (SDMMC.cmd.start_command == 0) {
167                 repeat = false;
168                 break;
169             }
170         }
171     }
172 }
173 
sdmmc_host_set_card_clk(int slot,uint32_t freq_khz)174 esp_err_t sdmmc_host_set_card_clk(int slot, uint32_t freq_khz)
175 {
176     if (!(slot == 0 || slot == 1)) {
177         return ESP_ERR_INVALID_ARG;
178     }
179     const int clk40m = 40000;
180 
181     // Disable clock first
182     SDMMC.clkena.cclk_enable &= ~BIT(slot);
183     sdmmc_host_clock_update_command(slot);
184 
185     int host_div = 0;   /* clock divider of the host (SDMMC.clock) */
186     int card_div = 0;   /* 1/2 of card clock divider (SDMMC.clkdiv) */
187 
188     // Calculate new dividers
189     if (freq_khz >= SDMMC_FREQ_HIGHSPEED) {
190         host_div = 4;       // 160 MHz / 4 = 40 MHz
191         card_div = 0;
192     } else if (freq_khz == SDMMC_FREQ_DEFAULT) {
193         host_div = 8;       // 160 MHz / 8 = 20 MHz
194         card_div = 0;
195     } else if (freq_khz == SDMMC_FREQ_PROBING) {
196         host_div = 10;      // 160 MHz / 10 / (20 * 2) = 400 kHz
197         card_div = 20;
198     } else {
199         host_div = 2;
200         card_div = (clk40m + freq_khz * 2 - 1) / (freq_khz * 2); // round up
201     }
202 
203     ESP_LOGD(TAG, "slot=%d host_div=%d card_div=%d freq=%dkHz",
204             slot, host_div, card_div,
205             2 * APB_CLK_FREQ / host_div / ((card_div == 0) ? 1 : card_div * 2) / 1000);
206 
207     // Program CLKDIV and CLKSRC, send them to the CIU
208     switch(slot) {
209         case 0:
210             SDMMC.clksrc.card0 = 0;
211             SDMMC.clkdiv.div0 = card_div;
212             break;
213         case 1:
214             SDMMC.clksrc.card1 = 1;
215             SDMMC.clkdiv.div1 = card_div;
216             break;
217     }
218     sdmmc_host_set_clk_div(host_div);
219     sdmmc_host_clock_update_command(slot);
220 
221     // Re-enable clocks
222     SDMMC.clkena.cclk_enable |= BIT(slot);
223     SDMMC.clkena.cclk_low_power |= BIT(slot);
224     sdmmc_host_clock_update_command(slot);
225 
226     // set data timeout
227     const uint32_t data_timeout_ms = 100;
228     uint32_t data_timeout_cycles = data_timeout_ms * freq_khz;
229     const uint32_t data_timeout_cycles_max = 0xffffff;
230     if (data_timeout_cycles > data_timeout_cycles_max) {
231         data_timeout_cycles = data_timeout_cycles_max;
232     }
233     SDMMC.tmout.data = data_timeout_cycles;
234     // always set response timeout to highest value, it's small enough anyway
235     SDMMC.tmout.response = 255;
236     return ESP_OK;
237 }
238 
sdmmc_host_start_command(int slot,sdmmc_hw_cmd_t cmd,uint32_t arg)239 esp_err_t sdmmc_host_start_command(int slot, sdmmc_hw_cmd_t cmd, uint32_t arg) {
240     if (!(slot == 0 || slot == 1)) {
241         return ESP_ERR_INVALID_ARG;
242     }
243     if ((SDMMC.cdetect.cards & BIT(slot)) != 0) {
244         return ESP_ERR_NOT_FOUND;
245     }
246     if (cmd.data_expected && cmd.rw && (SDMMC.wrtprt.cards & BIT(slot)) != 0) {
247         return ESP_ERR_INVALID_STATE;
248     }
249     while (SDMMC.cmd.start_command == 1) {
250         ;
251     }
252     SDMMC.cmdarg = arg;
253     cmd.card_num = slot;
254     cmd.start_command = 1;
255     SDMMC.cmd = cmd;
256     return ESP_OK;
257 }
258 
sdmmc_host_init(void)259 esp_err_t sdmmc_host_init(void)
260 {
261     if (s_intr_handle) {
262         return ESP_ERR_INVALID_STATE;
263     }
264 
265     periph_module_reset(PERIPH_SDMMC_MODULE);
266     periph_module_enable(PERIPH_SDMMC_MODULE);
267 
268     // Enable clock to peripheral. Use smallest divider first.
269     sdmmc_host_set_clk_div(2);
270 
271     // Reset
272     sdmmc_host_reset();
273     ESP_LOGD(TAG, "peripheral version %x, hardware config %08x", SDMMC.verid, SDMMC.hcon);
274 
275     // Clear interrupt status and set interrupt mask to known state
276     SDMMC.rintsts.val = 0xffffffff;
277     SDMMC.intmask.val = 0;
278     SDMMC.ctrl.int_enable = 0;
279 
280     // Allocate event queue
281     s_event_queue = xQueueCreate(SDMMC_EVENT_QUEUE_LENGTH, sizeof(sdmmc_event_t));
282     if (!s_event_queue) {
283         return ESP_ERR_NO_MEM;
284     }
285     s_io_intr_event = xSemaphoreCreateBinary();
286     if (!s_io_intr_event) {
287         vQueueDelete(s_event_queue);
288         s_event_queue = NULL;
289         return ESP_ERR_NO_MEM;
290     }
291     // Attach interrupt handler
292     esp_err_t ret = esp_intr_alloc(ETS_SDIO_HOST_INTR_SOURCE, 0, &sdmmc_isr, s_event_queue, &s_intr_handle);
293     if (ret != ESP_OK) {
294         vQueueDelete(s_event_queue);
295         s_event_queue = NULL;
296         vSemaphoreDelete(s_io_intr_event);
297         s_io_intr_event = NULL;
298         return ret;
299     }
300     // Enable interrupts
301     SDMMC.intmask.val =
302             SDMMC_INTMASK_CD |
303             SDMMC_INTMASK_CMD_DONE |
304             SDMMC_INTMASK_DATA_OVER |
305             SDMMC_INTMASK_RCRC | SDMMC_INTMASK_DCRC |
306             SDMMC_INTMASK_RTO | SDMMC_INTMASK_DTO | SDMMC_INTMASK_HTO |
307             SDMMC_INTMASK_SBE | SDMMC_INTMASK_EBE |
308             SDMMC_INTMASK_RESP_ERR | SDMMC_INTMASK_HLE; //sdio is enabled only when use.
309     SDMMC.ctrl.int_enable = 1;
310 
311     // Disable generation of Busy Clear Interrupt
312     SDMMC.cardthrctl.busy_clr_int_en = 0;
313 
314     // Enable DMA
315     sdmmc_host_dma_init();
316 
317     // Initialize transaction handler
318     ret = sdmmc_host_transaction_handler_init();
319     if (ret != ESP_OK) {
320         vQueueDelete(s_event_queue);
321         s_event_queue = NULL;
322         vSemaphoreDelete(s_io_intr_event);
323         s_io_intr_event = NULL;
324         esp_intr_free(s_intr_handle);
325         s_intr_handle = NULL;
326         return ret;
327     }
328 
329     return ESP_OK;
330 }
331 
332 #ifdef SOC_SDMMC_USE_IOMUX
333 
configure_pin_iomux(uint8_t gpio_num)334 static void configure_pin_iomux(uint8_t gpio_num)
335 {
336     const int sdmmc_func = 3;
337     const int drive_strength = 3;
338     assert(gpio_num != (uint8_t) GPIO_NUM_NC);
339     gpio_pulldown_dis(gpio_num);
340 
341     uint32_t reg = GPIO_PIN_MUX_REG[gpio_num];
342     assert(reg != UINT32_MAX);
343     PIN_INPUT_ENABLE(reg);
344     gpio_hal_iomux_func_sel(reg, sdmmc_func);
345     PIN_SET_DRV(reg, drive_strength);
346 }
347 
348 #elif SOC_SDMMC_USE_GPIO_MATRIX
349 
configure_pin_gpio_matrix(uint8_t gpio_num,uint8_t gpio_matrix_sig,gpio_mode_t mode,const char * name)350 static void configure_pin_gpio_matrix(uint8_t gpio_num, uint8_t gpio_matrix_sig, gpio_mode_t mode, const char* name)
351 {
352     assert (gpio_num != (uint8_t) GPIO_NUM_NC);
353     ESP_LOGD(TAG, "using GPIO%d as %s pin", gpio_num, name);
354     gpio_reset_pin(gpio_num);
355     gpio_set_direction(gpio_num, mode);
356     gpio_pulldown_dis(gpio_num);
357     if (mode == GPIO_MODE_INPUT || mode == GPIO_MODE_INPUT_OUTPUT) {
358         esp_rom_gpio_connect_in_signal(gpio_num, gpio_matrix_sig, false);
359     }
360     if (mode == GPIO_MODE_OUTPUT || mode == GPIO_MODE_INPUT_OUTPUT) {
361         esp_rom_gpio_connect_out_signal(gpio_num, gpio_matrix_sig, false, false);
362     }
363 }
364 
365 #endif // SOC_SDMMC_USE_{IOMUX,GPIO_MATRIX}
366 
sdmmc_host_init_slot(int slot,const sdmmc_slot_config_t * slot_config)367 esp_err_t sdmmc_host_init_slot(int slot, const sdmmc_slot_config_t* slot_config)
368 {
369     if (!s_intr_handle) {
370         return ESP_ERR_INVALID_STATE;
371     }
372     if (!(slot == 0 || slot == 1)) {
373         return ESP_ERR_INVALID_ARG;
374     }
375     if (slot_config == NULL) {
376         return ESP_ERR_INVALID_ARG;
377     }
378     int gpio_cd = slot_config->cd;
379     int gpio_wp = slot_config->wp;
380     uint8_t slot_width = slot_config->width;
381 
382     // Configure pins
383     const sdmmc_slot_info_t* slot_info = &sdmmc_slot_info[slot];
384 
385     if (slot_width == SDMMC_SLOT_WIDTH_DEFAULT) {
386         slot_width = slot_info->width;
387     }
388     else if (slot_width > slot_info->width) {
389         return ESP_ERR_INVALID_ARG;
390     }
391     s_slot_width[slot] = slot_width;
392 
393 #if SOC_SDMMC_USE_GPIO_MATRIX
394     /* Save pin configuration for this slot */
395     s_sdmmc_slot_gpio_num[slot].clk = slot_config->clk;
396     s_sdmmc_slot_gpio_num[slot].cmd = slot_config->cmd;
397     s_sdmmc_slot_gpio_num[slot].d0 = slot_config->d0;
398     /* Save d1 even in 1-line mode, it might be needed for SDIO INT line */
399     s_sdmmc_slot_gpio_num[slot].d1 = slot_config->d1;
400     if (slot_width >= 4) {
401         s_sdmmc_slot_gpio_num[slot].d2 = slot_config->d2;
402     }
403     /* Save d3 even for 1-line mode, as it needs to be set high */
404     s_sdmmc_slot_gpio_num[slot].d3 = slot_config->d3;
405     if (slot_width >= 8) {
406         s_sdmmc_slot_gpio_num[slot].d4 = slot_config->d4;
407         s_sdmmc_slot_gpio_num[slot].d5 = slot_config->d5;
408         s_sdmmc_slot_gpio_num[slot].d6 = slot_config->d6;
409         s_sdmmc_slot_gpio_num[slot].d7 = slot_config->d7;
410     }
411 #endif
412 
413     bool pullup = slot_config->flags & SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
414     if (pullup) {
415         sdmmc_host_pullup_en_internal(slot, slot_config->width);
416     }
417 
418     configure_pin(clk, slot, GPIO_MODE_OUTPUT);
419     configure_pin(cmd, slot, GPIO_MODE_INPUT_OUTPUT);
420     configure_pin(d0, slot, GPIO_MODE_INPUT_OUTPUT);
421 
422     if (slot_width >= 4) {
423         configure_pin(d1, slot, GPIO_MODE_INPUT_OUTPUT);
424         configure_pin(d2, slot, GPIO_MODE_INPUT_OUTPUT);
425         // Force D3 high to make slave enter SD mode.
426         // Connect to peripheral after width configuration.
427         gpio_config_t gpio_conf = {
428             .pin_bit_mask = BIT64(GPIO_NUM(slot, d3)),
429             .mode = GPIO_MODE_OUTPUT,
430             .pull_up_en = 0,
431             .pull_down_en = 0,
432             .intr_type = GPIO_INTR_DISABLE,
433         };
434         gpio_config(&gpio_conf);
435         gpio_set_level(GPIO_NUM(slot, d3), 1);
436     }
437     if (slot_width == 8) {
438         configure_pin(d4, slot, GPIO_MODE_INPUT_OUTPUT);
439         configure_pin(d5, slot, GPIO_MODE_INPUT_OUTPUT);
440         configure_pin(d6, slot, GPIO_MODE_INPUT_OUTPUT);
441         configure_pin(d7, slot, GPIO_MODE_INPUT_OUTPUT);
442     }
443 
444     // SDIO slave interrupt is edge sensitive to ~(int_n | card_int | card_detect)
445     // set this and card_detect to high to enable sdio interrupt
446     esp_rom_gpio_connect_in_signal(GPIO_MATRIX_CONST_ONE_INPUT, slot_info->card_int, false);
447 
448     // Set up Card Detect input
449     int matrix_in_cd;
450     if (gpio_cd != SDMMC_SLOT_NO_CD) {
451         ESP_LOGD(TAG, "using GPIO%d as CD pin", gpio_cd);
452         esp_rom_gpio_pad_select_gpio(gpio_cd);
453         gpio_set_direction(gpio_cd, GPIO_MODE_INPUT);
454         matrix_in_cd = gpio_cd;
455     } else {
456         // if not set, default to CD low (card present)
457         matrix_in_cd = GPIO_MATRIX_CONST_ZERO_INPUT;
458     }
459     esp_rom_gpio_connect_in_signal(matrix_in_cd, slot_info->card_detect, false);
460 
461     // Set up Write Protect input
462     int matrix_in_wp;
463     if (gpio_wp != SDMMC_SLOT_NO_WP) {
464         ESP_LOGD(TAG, "using GPIO%d as WP pin", gpio_wp);
465         esp_rom_gpio_pad_select_gpio(gpio_wp);
466         gpio_set_direction(gpio_wp, GPIO_MODE_INPUT);
467         matrix_in_wp = gpio_wp;
468     } else {
469         // if not set, default to WP high (not write protected)
470         matrix_in_wp = GPIO_MATRIX_CONST_ONE_INPUT;
471     }
472     // WP signal is normally active low, but hardware expects
473     // an active-high signal, so invert it in GPIO matrix
474     esp_rom_gpio_connect_in_signal(matrix_in_wp, slot_info->write_protect, true);
475 
476     // By default, set probing frequency (400kHz) and 1-bit bus
477     esp_err_t ret = sdmmc_host_set_card_clk(slot, 400);
478     if (ret != ESP_OK) {
479         return ret;
480     }
481     ret = sdmmc_host_set_bus_width(slot, 1);
482     if (ret != ESP_OK) {
483         return ret;
484     }
485     return ESP_OK;
486 }
487 
sdmmc_host_deinit(void)488 esp_err_t sdmmc_host_deinit(void)
489 {
490     if (!s_intr_handle) {
491         return ESP_ERR_INVALID_STATE;
492     }
493     esp_intr_free(s_intr_handle);
494     s_intr_handle = NULL;
495     vQueueDelete(s_event_queue);
496     s_event_queue = NULL;
497     vQueueDelete(s_io_intr_event);
498     s_io_intr_event = NULL;
499     sdmmc_host_input_clk_disable();
500     sdmmc_host_transaction_handler_deinit();
501     periph_module_disable(PERIPH_SDMMC_MODULE);
502     return ESP_OK;
503 }
504 
sdmmc_host_wait_for_event(int tick_count,sdmmc_event_t * out_event)505 esp_err_t sdmmc_host_wait_for_event(int tick_count, sdmmc_event_t* out_event)
506 {
507     if (!out_event) {
508         return ESP_ERR_INVALID_ARG;
509     }
510     if (!s_event_queue) {
511         return ESP_ERR_INVALID_STATE;
512     }
513     int ret = xQueueReceive(s_event_queue, out_event, tick_count);
514     if (ret == pdFALSE) {
515         return ESP_ERR_TIMEOUT;
516     }
517     return ESP_OK;
518 }
519 
sdmmc_host_set_bus_width(int slot,size_t width)520 esp_err_t sdmmc_host_set_bus_width(int slot, size_t width)
521 {
522     if (!(slot == 0 || slot == 1)) {
523         return ESP_ERR_INVALID_ARG;
524     }
525     if (sdmmc_slot_info[slot].width < width) {
526         return ESP_ERR_INVALID_ARG;
527     }
528     const uint16_t mask = BIT(slot);
529     if (width == 1) {
530         SDMMC.ctype.card_width_8 &= ~mask;
531         SDMMC.ctype.card_width &= ~mask;
532     } else if (width == 4) {
533         SDMMC.ctype.card_width_8 &= ~mask;
534         SDMMC.ctype.card_width |= mask;
535         // D3 was set to GPIO high to force slave into SD mode, until 4-bit mode is set
536         configure_pin(d3, slot, GPIO_MODE_INPUT_OUTPUT);
537     } else if (width == 8) {
538         SDMMC.ctype.card_width_8 |= mask;
539         // D3 was set to GPIO high to force slave into SD mode, until 4-bit mode is set
540         configure_pin(d3, slot, GPIO_MODE_INPUT_OUTPUT);
541     } else {
542         return ESP_ERR_INVALID_ARG;
543     }
544     ESP_LOGD(TAG, "slot=%d width=%d", slot, width);
545     return ESP_OK;
546 }
547 
sdmmc_host_get_slot_width(int slot)548 size_t sdmmc_host_get_slot_width(int slot)
549 {
550     assert( slot == 0 || slot == 1 );
551     return s_slot_width[slot];
552 }
553 
sdmmc_host_set_bus_ddr_mode(int slot,bool ddr_enabled)554 esp_err_t sdmmc_host_set_bus_ddr_mode(int slot, bool ddr_enabled)
555 {
556     if (!(slot == 0 || slot == 1)) {
557         return ESP_ERR_INVALID_ARG;
558     }
559     if (s_slot_width[slot] == 8 && ddr_enabled) {
560         ESP_LOGW(TAG, "DDR mode with 8-bit bus width is not supported yet");
561         // requires reconfiguring controller clock for 2x card frequency
562         return ESP_ERR_NOT_SUPPORTED;
563     }
564     uint32_t mask = BIT(slot);
565     if (ddr_enabled) {
566         SDMMC.uhs.ddr |= mask;
567         SDMMC.emmc_ddr_reg |= mask;
568     } else {
569         SDMMC.uhs.ddr &= ~mask;
570         SDMMC.emmc_ddr_reg &= ~mask;
571     }
572     ESP_LOGD(TAG, "slot=%d ddr=%d", slot, ddr_enabled ? 1 : 0);
573     return ESP_OK;
574 }
575 
sdmmc_host_dma_init(void)576 static void sdmmc_host_dma_init(void)
577 {
578     SDMMC.ctrl.dma_enable = 1;
579     SDMMC.bmod.val = 0;
580     SDMMC.bmod.sw_reset = 1;
581     SDMMC.idinten.ni = 1;
582     SDMMC.idinten.ri = 1;
583     SDMMC.idinten.ti = 1;
584 }
585 
586 
sdmmc_host_dma_stop(void)587 void sdmmc_host_dma_stop(void)
588 {
589     SDMMC.ctrl.use_internal_dma = 0;
590     SDMMC.ctrl.dma_reset = 1;
591     SDMMC.bmod.fb = 0;
592     SDMMC.bmod.enable = 0;
593 }
594 
sdmmc_host_dma_prepare(sdmmc_desc_t * desc,size_t block_size,size_t data_size)595 void sdmmc_host_dma_prepare(sdmmc_desc_t* desc, size_t block_size, size_t data_size)
596 {
597     // Set size of data and DMA descriptor pointer
598     SDMMC.bytcnt = data_size;
599     SDMMC.blksiz = block_size;
600     SDMMC.dbaddr = desc;
601 
602     // Enable everything needed to use DMA
603     SDMMC.ctrl.dma_enable = 1;
604     SDMMC.ctrl.use_internal_dma = 1;
605     SDMMC.bmod.enable = 1;
606     SDMMC.bmod.fb = 1;
607     sdmmc_host_dma_resume();
608 }
609 
sdmmc_host_dma_resume(void)610 void sdmmc_host_dma_resume(void)
611 {
612     SDMMC.pldmnd = 1;
613 }
614 
sdmmc_host_card_busy(void)615 bool sdmmc_host_card_busy(void)
616 {
617     return SDMMC.status.data_busy == 1;
618 }
619 
sdmmc_host_io_int_enable(int slot)620 esp_err_t sdmmc_host_io_int_enable(int slot)
621 {
622     configure_pin(d1, slot, GPIO_MODE_INPUT_OUTPUT);
623     return ESP_OK;
624 }
625 
sdmmc_host_io_int_wait(int slot,TickType_t timeout_ticks)626 esp_err_t sdmmc_host_io_int_wait(int slot, TickType_t timeout_ticks)
627 {
628     /* SDIO interrupts are negedge sensitive ones: the status bit is only set
629      * when first interrupt triggered.
630      *
631      * If D1 GPIO is low when entering this function, we know that interrupt
632      * (in SDIO sense) has occurred and we don't need to use SDMMC peripheral
633      * interrupt.
634      */
635 
636     SDMMC.intmask.sdio &= ~BIT(slot);   /* Disable SDIO interrupt */
637     SDMMC.rintsts.sdio = BIT(slot);
638     if (gpio_get_level(GPIO_NUM(slot, d1)) == 0) {
639         return ESP_OK;
640     }
641     /* Otherwise, need to wait for an interrupt. Since D1 was high,
642      * SDMMC peripheral interrupt is guaranteed to trigger on negedge.
643      */
644     xSemaphoreTake(s_io_intr_event, 0);
645     SDMMC.intmask.sdio |= BIT(slot);    /* Re-enable SDIO interrupt */
646 
647     if (xSemaphoreTake(s_io_intr_event, timeout_ticks) == pdTRUE) {
648         return ESP_OK;
649     } else {
650         return ESP_ERR_TIMEOUT;
651     }
652 }
653 
654 /**
655  * @brief SDMMC interrupt handler
656  *
657  * All communication in SD protocol is driven by the master, and the hardware
658  * handles things like stop commands automatically.
659  * So the interrupt handler doesn't need to do much, we just push interrupt
660  * status into a queue, clear interrupt flags, and let the task currently
661  * doing communication figure out what to do next.
662  * This also applies to SDIO interrupts which are generated by the slave.
663  *
664  * Card detect interrupts pose a small issue though, because if a card is
665  * plugged in and out a few times, while there is no task to process
666  * the events, event queue can become full and some card detect events
667  * may be dropped. We ignore this problem for now, since the there are no other
668  * interesting events which can get lost due to this.
669  */
sdmmc_isr(void * arg)670 static void sdmmc_isr(void* arg) {
671     QueueHandle_t queue = (QueueHandle_t) arg;
672     sdmmc_event_t event;
673     int higher_priority_task_awoken = pdFALSE;
674 
675     uint32_t pending = SDMMC.mintsts.val & 0xFFFF;
676     SDMMC.rintsts.val = pending;
677     event.sdmmc_status = pending;
678 
679     uint32_t dma_pending = SDMMC.idsts.val;
680     SDMMC.idsts.val = dma_pending;
681     event.dma_status = dma_pending & 0x1f;
682 
683     if (pending != 0 || dma_pending != 0) {
684         xQueueSendFromISR(queue, &event, &higher_priority_task_awoken);
685     }
686 
687     uint32_t sdio_pending = SDMMC.mintsts.sdio;
688     if (sdio_pending) {
689         // disable the interrupt (no need to clear here, this is done in sdmmc_host_io_wait_int)
690         SDMMC.intmask.sdio &= ~sdio_pending;
691         xSemaphoreGiveFromISR(s_io_intr_event, &higher_priority_task_awoken);
692     }
693 
694     if (higher_priority_task_awoken == pdTRUE) {
695         portYIELD_FROM_ISR();
696     }
697 }
698 
sdmmc_host_pullup_en_internal(int slot,int width)699 static esp_err_t sdmmc_host_pullup_en_internal(int slot, int width)
700 {
701     if (width > sdmmc_slot_info[slot].width) {
702         //in esp32 we only support 8 bit in slot 0, note this is occupied by the flash by default
703         return ESP_ERR_INVALID_ARG;
704     }
705     // according to the spec, the host controls the clk, we don't to pull it up here
706     gpio_pullup_en(GPIO_NUM(slot, cmd));
707     gpio_pullup_en(GPIO_NUM(slot, d0));
708     if (width >= 4) {
709         gpio_pullup_en(GPIO_NUM(slot, d1));
710         gpio_pullup_en(GPIO_NUM(slot, d2));
711         gpio_pullup_en(GPIO_NUM(slot, d3));
712     }
713     if (width == 8) {
714         gpio_pullup_en(GPIO_NUM(slot, d4));
715         gpio_pullup_en(GPIO_NUM(slot, d5));
716         gpio_pullup_en(GPIO_NUM(slot, d6));
717         gpio_pullup_en(GPIO_NUM(slot, d7));
718     }
719     return ESP_OK;
720 }
721 
722 /* Deprecared public function */
723 esp_err_t sdmmc_host_pullup_en(int slot, int width) __attribute__((alias("sdmmc_host_pullup_en_internal")));
724