1 /*
2 * Copyright 2022,2024 NXP
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/drivers/disk.h>
8 #include <zephyr/drivers/sdhc.h>
9 #include <zephyr/logging/log.h>
10 #include <zephyr/sd/sd.h>
11 #include <zephyr/sd/sd_spec.h>
12 #include <zephyr/sys/byteorder.h>
13 #include <zephyr/kernel.h>
14
15 #include "sd_utils.h"
16
17 LOG_MODULE_DECLARE(sd, CONFIG_SD_LOG_LEVEL);
18
19 /* Read card status. Return 0 if card is inactive */
sdmmc_read_status(struct sd_card * card)20 int sdmmc_read_status(struct sd_card *card)
21 {
22 struct sdhc_command cmd;
23 int ret;
24
25 cmd.opcode = SD_SEND_STATUS;
26 cmd.arg = 0;
27 if (!card->host_props.is_spi) {
28 cmd.arg = (card->relative_addr << 16U);
29 }
30 cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R2);
31 cmd.retries = CONFIG_SD_CMD_RETRIES;
32 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
33
34 ret = sdhc_request(card->sdhc, &cmd, NULL);
35 if (ret) {
36 return SD_RETRY;
37 }
38 if (card->host_props.is_spi) {
39 /* Check R2 response bits */
40 if ((cmd.response[0U] & SDHC_SPI_R2_CARD_LOCKED) ||
41 (cmd.response[0U] & SDHC_SPI_R2_UNLOCK_FAIL)) {
42 return -EACCES;
43 } else if ((cmd.response[0U] & SDHC_SPI_R2_WP_VIOLATION) ||
44 (cmd.response[0U] & SDHC_SPI_R2_ERASE_PARAM) ||
45 (cmd.response[0U] & SDHC_SPI_R2_OUT_OF_RANGE)) {
46 return -EINVAL;
47 } else if ((cmd.response[0U] & SDHC_SPI_R2_ERR) ||
48 (cmd.response[0U] & SDHC_SPI_R2_CC_ERR) ||
49 (cmd.response[0U] & SDHC_SPI_R2_ECC_FAIL)) {
50 return -EIO;
51 }
52 /* Otherwise, no error in R2 response */
53 return 0;
54 }
55 /* Otherwise, check native card response */
56 if ((cmd.response[0U] & SD_R1_RDY_DATA) &&
57 (SD_R1_CURRENT_STATE(cmd.response[0U]) == SDMMC_R1_TRANSFER)) {
58 return 0;
59 }
60 /* Valid response, the card is busy */
61 return -EBUSY;
62 }
63
64 /* Waits for SD card to be ready for data. Returns 0 if card is ready */
sdmmc_wait_ready(struct sd_card * card)65 int sdmmc_wait_ready(struct sd_card *card)
66 {
67 int ret, timeout = CONFIG_SD_DATA_TIMEOUT * 1000;
68
69 do {
70 if (!sdhc_card_busy(card->sdhc)) {
71 /* Check card status */
72 ret = sd_retry(sdmmc_read_status, card, CONFIG_SD_RETRY_COUNT);
73 if (ret == 0) {
74 return 0;
75 }
76 if (ret == -ETIMEDOUT) {
77 /* If this check timed out, then the total
78 * time elapsed in microseconds is
79 * SD_CMD_TIMEOUT * SD_RETRY_COUNT * 1000
80 */
81 timeout -= (CONFIG_SD_CMD_TIMEOUT *
82 CONFIG_SD_RETRY_COUNT) * 1000;
83 }
84 }
85 /* Delay 125us before polling again */
86 k_busy_wait(125);
87 timeout -= 125;
88 } while (timeout > 0);
89 return -EBUSY;
90 }
91
sdmmc_decode_csd(struct sd_csd * csd,uint32_t * raw_csd,uint32_t * blk_count,uint16_t * blk_size)92 static inline void sdmmc_decode_csd(struct sd_csd *csd, uint32_t *raw_csd, uint32_t *blk_count,
93 uint16_t *blk_size)
94 {
95 uint32_t tmp_blk_count;
96 uint16_t tmp_blk_size;
97
98 csd->csd_structure = (uint8_t)((raw_csd[3U] & 0xC0000000U) >> 30U);
99 csd->read_time1 = (uint8_t)((raw_csd[3U] & 0xFF0000U) >> 16U);
100 csd->read_time2 = (uint8_t)((raw_csd[3U] & 0xFF00U) >> 8U);
101 csd->xfer_rate = (uint8_t)(raw_csd[3U] & 0xFFU);
102 csd->cmd_class = (uint16_t)((raw_csd[2U] & 0xFFF00000U) >> 20U);
103 csd->read_blk_len = (uint8_t)((raw_csd[2U] & 0xF0000U) >> 16U);
104 if (raw_csd[2U] & 0x8000U) {
105 csd->flags |= SD_CSD_READ_BLK_PARTIAL_FLAG;
106 }
107 if (raw_csd[2U] & 0x4000U) {
108 csd->flags |= SD_CSD_READ_BLK_PARTIAL_FLAG;
109 }
110 if (raw_csd[2U] & 0x2000U) {
111 csd->flags |= SD_CSD_READ_BLK_MISALIGN_FLAG;
112 }
113 if (raw_csd[2U] & 0x1000U) {
114 csd->flags |= SD_CSD_DSR_IMPLEMENTED_FLAG;
115 }
116
117 switch (csd->csd_structure) {
118 case 0:
119 csd->device_size = (uint32_t)((raw_csd[2U] & 0x3FFU) << 2U);
120 csd->device_size |= (uint32_t)((raw_csd[1U] & 0xC0000000U) >> 30U);
121 csd->read_current_min = (uint8_t)((raw_csd[1U] & 0x38000000U) >> 27U);
122 csd->read_current_max = (uint8_t)((raw_csd[1U] & 0x7000000U) >> 24U);
123 csd->write_current_min = (uint8_t)((raw_csd[1U] & 0xE00000U) >> 20U);
124 csd->write_current_max = (uint8_t)((raw_csd[1U] & 0x1C0000U) >> 18U);
125 csd->dev_size_mul = (uint8_t)((raw_csd[1U] & 0x38000U) >> 15U);
126
127 /* Get card total block count and block size. */
128 tmp_blk_count = ((csd->device_size + 1U) << (csd->dev_size_mul + 2U));
129 tmp_blk_size = (1U << (csd->read_blk_len));
130 if (tmp_blk_size != SDMMC_DEFAULT_BLOCK_SIZE) {
131 tmp_blk_count = (tmp_blk_count * tmp_blk_size);
132 tmp_blk_size = SDMMC_DEFAULT_BLOCK_SIZE;
133 tmp_blk_count = (tmp_blk_count / tmp_blk_size);
134 }
135 if (blk_count) {
136 *blk_count = tmp_blk_count;
137 }
138 if (blk_size) {
139 *blk_size = tmp_blk_size;
140 }
141 break;
142 case 1:
143 tmp_blk_size = SDMMC_DEFAULT_BLOCK_SIZE;
144
145 csd->device_size = (uint32_t)((raw_csd[2U] & 0x3FU) << 16U);
146 csd->device_size |= (uint32_t)((raw_csd[1U] & 0xFFFF0000U) >> 16U);
147
148 tmp_blk_count = ((csd->device_size + 1U) * 1024U);
149 if (blk_count) {
150 *blk_count = tmp_blk_count;
151 }
152 if (blk_size) {
153 *blk_size = tmp_blk_size;
154 }
155 break;
156 default:
157 break;
158 }
159
160 if ((uint8_t)((raw_csd[1U] & 0x4000U) >> 14U)) {
161 csd->flags |= SD_CSD_ERASE_BLK_EN_FLAG;
162 }
163 csd->erase_size = (uint8_t)((raw_csd[1U] & 0x3F80U) >> 7U);
164 csd->write_prtect_size = (uint8_t)(raw_csd[1U] & 0x7FU);
165 csd->write_speed_factor = (uint8_t)((raw_csd[0U] & 0x1C000000U) >> 26U);
166 csd->write_blk_len = (uint8_t)((raw_csd[0U] & 0x3C00000U) >> 22U);
167 if ((uint8_t)((raw_csd[0U] & 0x200000U) >> 21U)) {
168 csd->flags |= SD_CSD_WRITE_BLK_PARTIAL_FLAG;
169 }
170 if ((uint8_t)((raw_csd[0U] & 0x8000U) >> 15U)) {
171 csd->flags |= SD_CSD_FILE_FMT_GRP_FLAG;
172 }
173 if ((uint8_t)((raw_csd[0U] & 0x4000U) >> 14U)) {
174 csd->flags |= SD_CSD_COPY_FLAG;
175 }
176 if ((uint8_t)((raw_csd[0U] & 0x2000U) >> 13U)) {
177 csd->flags |= SD_CSD_PERMANENT_WRITE_PROTECT_FLAG;
178 }
179 if ((uint8_t)((raw_csd[0U] & 0x1000U) >> 12U)) {
180 csd->flags |= SD_CSD_TMP_WRITE_PROTECT_FLAG;
181 }
182 csd->file_fmt = (uint8_t)((raw_csd[0U] & 0xC00U) >> 10U);
183 }
184
sdmmc_decode_cid(struct sd_cid * cid,uint32_t * raw_cid)185 static inline void sdmmc_decode_cid(struct sd_cid *cid, uint32_t *raw_cid)
186 {
187 cid->manufacturer = (uint8_t)((raw_cid[3U] & 0xFF000000U) >> 24U);
188 cid->application = (uint16_t)((raw_cid[3U] & 0xFFFF00U) >> 8U);
189
190 cid->name[0U] = (uint8_t)((raw_cid[3U] & 0xFFU));
191 cid->name[1U] = (uint8_t)((raw_cid[2U] & 0xFF000000U) >> 24U);
192 cid->name[2U] = (uint8_t)((raw_cid[2U] & 0xFF0000U) >> 16U);
193 cid->name[3U] = (uint8_t)((raw_cid[2U] & 0xFF00U) >> 8U);
194 cid->name[4U] = (uint8_t)((raw_cid[2U] & 0xFFU));
195
196 cid->version = (uint8_t)((raw_cid[1U] & 0xFF000000U) >> 24U);
197
198 cid->ser_num = (uint32_t)((raw_cid[1U] & 0xFFFFFFU) << 8U);
199 cid->ser_num |= (uint32_t)((raw_cid[0U] & 0xFF000000U) >> 24U);
200
201 cid->date = (uint16_t)((raw_cid[0U] & 0xFFF00U) >> 8U);
202 }
203
204 /* Reads card id/csd register (in SPI mode) */
sdmmc_spi_read_cxd(struct sd_card * card,uint32_t opcode,uint32_t * cxd)205 static int sdmmc_spi_read_cxd(struct sd_card *card, uint32_t opcode, uint32_t *cxd)
206 {
207 struct sdhc_command cmd;
208 struct sdhc_data data;
209 int ret, i;
210 /* Use internal card buffer for data transfer */
211 uint32_t *cxd_be = (uint32_t *)card->card_buffer;
212
213 cmd.opcode = opcode;
214 cmd.arg = 0;
215 cmd.response_type = SD_SPI_RSP_TYPE_R1;
216 cmd.retries = CONFIG_SD_CMD_RETRIES;
217 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
218
219 /* CID/CSD is 16 bytes */
220 data.block_addr = 0; /* Unused set to 0 */
221 data.block_size = 16;
222 data.blocks = 1U;
223 data.data = cxd_be;
224 data.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
225
226 ret = sdhc_request(card->sdhc, &cmd, &data);
227 if (ret) {
228 LOG_DBG("CMD%d failed: %d", opcode, ret);
229 }
230 /* Swap endianness of CXD */
231 for (i = 0; i < 4; i++) {
232 cxd[3 - i] = sys_be32_to_cpu(cxd_be[i]);
233 }
234 return 0;
235 }
236
237 /* Reads card id/csd register (native SD mode */
sdmmc_read_cxd(struct sd_card * card,uint32_t opcode,uint32_t rca,uint32_t * cxd)238 static int sdmmc_read_cxd(struct sd_card *card, uint32_t opcode, uint32_t rca, uint32_t *cxd)
239 {
240 struct sdhc_command cmd;
241 int ret;
242
243 cmd.opcode = opcode;
244 cmd.arg = (rca << 16);
245 cmd.response_type = SD_RSP_TYPE_R2;
246 cmd.retries = CONFIG_SD_CMD_RETRIES;
247 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
248
249 ret = sdhc_request(card->sdhc, &cmd, NULL);
250 if (ret) {
251 LOG_DBG("CMD%d failed: %d", opcode, ret);
252 return ret;
253 }
254 /* CSD/CID is 16 bytes */
255 memcpy(cxd, cmd.response, 16);
256 return 0;
257 }
258
259 /* Read card specific data register */
sdmmc_read_csd(struct sd_card * card)260 int sdmmc_read_csd(struct sd_card *card)
261 {
262 int ret;
263 uint32_t csd[4];
264 /* Keep CSD on stack for reduced RAM usage */
265 struct sd_csd card_csd = {0};
266
267 if (card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_SPI_MODE)) {
268 ret = sdmmc_spi_read_cxd(card, SD_SEND_CSD, csd);
269 } else if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
270 ret = sdmmc_read_cxd(card, SD_SEND_CSD, card->relative_addr, csd);
271 } else {
272 /* The host controller must run in either native or SPI mode */
273 return -ENOTSUP;
274 }
275 if (ret) {
276 return ret;
277 }
278 sdmmc_decode_csd(&card_csd, csd, &card->block_count, &card->block_size);
279 LOG_DBG("Card block count %d, block size %d", card->block_count, card->block_size);
280 return 0;
281 }
282
283 /* Reads card identification register, and decodes it */
card_read_cid(struct sd_card * card)284 int card_read_cid(struct sd_card *card)
285 {
286 uint32_t cid[4];
287 int ret;
288 #if defined(CONFIG_SDMMC_STACK) || defined(CONFIG_SDIO_STACK)
289 /* Keep CID on stack for reduced RAM usage */
290 struct sd_cid card_cid = {0};
291 #endif
292
293 if (card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_SPI_MODE)) {
294 ret = sdmmc_spi_read_cxd(card, SD_SEND_CID, cid);
295 } else if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
296 ret = sdmmc_read_cxd(card, SD_ALL_SEND_CID, 0, cid);
297 } else {
298 /* The host controller must run in either native or SPI mode */
299 return -ENOTSUP;
300 }
301 if (ret) {
302 return ret;
303 }
304
305 #if defined(CONFIG_MMC_STACK)
306 if (card->type == CARD_MMC) {
307 LOG_INF("CID decoding not supported for MMC");
308 return 0;
309 }
310 #endif
311 #if defined(CONFIG_SDMMC_STACK) || defined(CONFIG_SDIO_STACK)
312 /* Decode SD CID */
313 sdmmc_decode_cid(&card_cid, cid);
314 LOG_DBG("Card MID: 0x%x, OID: %c%c", card_cid.manufacturer,
315 ((char *)&card_cid.application)[0], ((char *)&card_cid.application)[1]);
316 #endif
317
318 return 0;
319 }
320
321 /*
322 * Implements signal voltage switch procedure described in section 3.6.1 of
323 * SD host controller specification.
324 */
sdmmc_switch_voltage(struct sd_card * card)325 int sdmmc_switch_voltage(struct sd_card *card)
326 {
327 int ret, sd_clock;
328 struct sdhc_command cmd;
329
330 /* Check to make sure card supports 1.8V */
331 if (!(card->flags & SD_1800MV_FLAG)) {
332 /* Do not attempt to switch voltages */
333 LOG_WRN("SD card reports as SDHC/SDXC, but does not support 1.8V");
334 return 0;
335 }
336 /* Send CMD11 to request a voltage switch */
337 cmd.opcode = SD_VOL_SWITCH;
338 cmd.arg = 0U;
339 cmd.response_type = SD_RSP_TYPE_R1;
340 cmd.retries = CONFIG_SD_CMD_RETRIES;
341 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
342 ret = sdhc_request(card->sdhc, &cmd, NULL);
343 if (ret) {
344 LOG_DBG("CMD11 failed");
345 return ret;
346 }
347 /* Check R1 response for error */
348 ret = sd_check_response(&cmd);
349 if (ret) {
350 LOG_DBG("SD response to CMD11 indicates error");
351 return ret;
352 }
353 /*
354 * Card should drive CMD and DAT[3:0] signals low at the next clock
355 * cycle. Some cards will only drive these
356 * lines low briefly, so we should check as soon as possible
357 */
358 if (!(sdhc_card_busy(card->sdhc))) {
359 /* Delay 1ms to allow card to drive lines low */
360 sd_delay(1);
361 if (!sdhc_card_busy(card->sdhc)) {
362 /* Card did not drive CMD and DAT lines low */
363 LOG_DBG("Card did not drive DAT lines low");
364 return -EAGAIN;
365 }
366 }
367 /*
368 * Per SD spec (section "Timing to Switch Signal Voltage"),
369 * host must gate clock at least 5ms.
370 */
371 sd_clock = card->bus_io.clock;
372 card->bus_io.clock = 0;
373 ret = sdhc_set_io(card->sdhc, &card->bus_io);
374 if (ret) {
375 LOG_DBG("Failed to gate SD clock");
376 return ret;
377 }
378 /* Now that clock is gated, change signal voltage */
379 card->bus_io.signal_voltage = SD_VOL_1_8_V;
380 ret = sdhc_set_io(card->sdhc, &card->bus_io);
381 if (ret) {
382 LOG_DBG("Failed to switch SD host to 1.8V");
383 return ret;
384 }
385 sd_delay(10); /* Gate for 10ms, even though spec requires 5 */
386 /* Restart the clock */
387 card->bus_io.clock = sd_clock;
388 ret = sdhc_set_io(card->sdhc, &card->bus_io);
389 if (ret) {
390 LOG_ERR("Failed to restart SD clock");
391 return ret;
392 }
393 /*
394 * If SD does not drive at least one of
395 * DAT[3:0] high within 1ms, switch failed
396 */
397 sd_delay(1);
398 if (sdhc_card_busy(card->sdhc)) {
399 LOG_DBG("Card failed to switch voltages");
400 return -EAGAIN;
401 }
402 card->card_voltage = SD_VOL_1_8_V;
403 LOG_INF("Card switched to 1.8V signaling");
404 return 0;
405 }
406
407 /*
408 * Requests card to publish a new relative card address, and move from
409 * identification to data mode
410 */
sdmmc_request_rca(struct sd_card * card)411 int sdmmc_request_rca(struct sd_card *card)
412 {
413 struct sdhc_command cmd;
414 int ret;
415
416 cmd.opcode = SD_SEND_RELATIVE_ADDR;
417 cmd.arg = 0;
418 cmd.response_type = SD_RSP_TYPE_R6;
419 cmd.retries = CONFIG_SD_CMD_RETRIES;
420 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
421 /* Issue CMD3 until card responds with nonzero RCA */
422 do {
423 ret = sdhc_request(card->sdhc, &cmd, NULL);
424 if (ret) {
425 LOG_DBG("CMD3 failed");
426 return ret;
427 }
428 /* Card RCA is in upper 16 bits of response */
429 card->relative_addr = ((cmd.response[0U] & 0xFFFF0000) >> 16U);
430 } while (card->relative_addr == 0U);
431 LOG_DBG("Card relative addr: %d", card->relative_addr);
432 return 0;
433 }
434
435 /*
436 * Selects card, moving it into data transfer mode
437 */
sdmmc_select_card(struct sd_card * card)438 int sdmmc_select_card(struct sd_card *card)
439 {
440 struct sdhc_command cmd;
441 int ret;
442
443 cmd.opcode = SD_SELECT_CARD;
444 cmd.arg = ((card->relative_addr) << 16U);
445 cmd.response_type = SD_RSP_TYPE_R1;
446 cmd.retries = CONFIG_SD_CMD_RETRIES;
447 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
448
449 ret = sdhc_request(card->sdhc, &cmd, NULL);
450 if (ret) {
451 LOG_DBG("CMD7 failed");
452 return ret;
453 }
454 ret = sd_check_response(&cmd);
455 if (ret) {
456 LOG_DBG("CMD7 reports error");
457 return ret;
458 }
459 return 0;
460 }
461
462 /* Helper to send SD app command */
card_app_command(struct sd_card * card,int relative_card_address)463 int card_app_command(struct sd_card *card, int relative_card_address)
464 {
465 struct sdhc_command cmd;
466 int ret;
467
468 cmd.opcode = SD_APP_CMD;
469 cmd.arg = relative_card_address << 16U;
470 cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
471 cmd.retries = CONFIG_SD_CMD_RETRIES;
472 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
473 ret = sdhc_request(card->sdhc, &cmd, NULL);
474 if (ret) {
475 /* We want to retry transmission */
476 return SD_RETRY;
477 }
478 ret = sd_check_response(&cmd);
479 if (ret) {
480 LOG_WRN("SD app command failed with R1 response of 0x%X", cmd.response[0]);
481 return -EIO;
482 }
483 /* Check application command flag to determine if card is ready for APP CMD */
484 if ((!card->host_props.is_spi) && !(cmd.response[0U] & SD_R1_APP_CMD)) {
485 /* Command succeeded, but card not ready for app command. No APP CMD support */
486 return -ENOTSUP;
487 }
488 return 0;
489 }
490
card_read(struct sd_card * card,uint8_t * rbuf,uint32_t start_block,uint32_t num_blocks)491 static int card_read(struct sd_card *card, uint8_t *rbuf, uint32_t start_block, uint32_t num_blocks)
492 {
493 int ret;
494 struct sdhc_command cmd;
495 struct sdhc_data data;
496
497 /*
498 * Note: The SD specification allows for CMD23 to be sent before a
499 * transfer in order to set the block length (often preferable).
500 * The specification also requires that CMD12 be sent to stop a transfer.
501 * However, the host specification defines support for "Auto CMD23" and
502 * "Auto CMD12", where the host sends CMD23 and CMD12 automatically to
503 * remove the overhead of interrupts in software from sending these
504 * commands. Therefore, we will not handle CMD12 or CMD23 at this layer.
505 * The host SDHC driver is expected to recognize CMD17, CMD18, CMD24,
506 * and CMD25 as special read/write commands and handle CMD23 and
507 * CMD12 appropriately.
508 */
509 cmd.opcode = (num_blocks == 1U) ? SD_READ_SINGLE_BLOCK : SD_READ_MULTIPLE_BLOCK;
510 if (!(card->flags & SD_HIGH_CAPACITY_FLAG)) {
511 /* SDSC cards require block size in bytes, not blocks */
512 cmd.arg = start_block * card->block_size;
513 } else {
514 cmd.arg = start_block;
515 }
516 cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
517 cmd.retries = CONFIG_SD_DATA_RETRIES;
518 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
519
520 data.block_addr = start_block;
521 data.block_size = card->block_size;
522 data.blocks = num_blocks;
523 data.data = rbuf;
524 data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
525
526 LOG_DBG("READ: Sector = %u, Count = %u", start_block, num_blocks);
527
528 ret = sdhc_request(card->sdhc, &cmd, &data);
529 if (ret) {
530 LOG_ERR("Failed to read from SDMMC %d", ret);
531 return ret;
532 }
533
534 /* Verify card is back in transfer state after read */
535 ret = sdmmc_wait_ready(card);
536 if (ret) {
537 LOG_ERR("Card did not return to ready state");
538 return -ETIMEDOUT;
539 }
540 return 0;
541 }
542
543 /* Reads data from SD card memory card */
card_read_blocks(struct sd_card * card,uint8_t * rbuf,uint32_t start_block,uint32_t num_blocks)544 int card_read_blocks(struct sd_card *card, uint8_t *rbuf, uint32_t start_block, uint32_t num_blocks)
545 {
546 int ret;
547 uint32_t rlen;
548 uint32_t sector;
549 uint8_t *buf_offset;
550
551 if ((start_block + num_blocks) > card->block_count) {
552 return -EINVAL;
553 }
554 if (card->type == CARD_SDIO) {
555 LOG_WRN("SDIO does not support MMC commands");
556 return -ENOTSUP;
557 }
558 ret = k_mutex_lock(&card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
559 if (ret) {
560 LOG_WRN("Could not get SD card mutex");
561 return -EBUSY;
562 }
563
564 /*
565 * If the buffer we are provided with is aligned, we can use it
566 * directly. Otherwise, we need to use the card's internal buffer
567 * and memcpy the data back out
568 */
569 if ((((uintptr_t)rbuf) & (CONFIG_SDHC_BUFFER_ALIGNMENT - 1)) != 0) {
570 /* lower bits of address are set, not aligned. Use internal buffer */
571 LOG_DBG("Unaligned buffer access to SD card may incur performance penalty");
572 if (sizeof(card->card_buffer) < card->block_size) {
573 LOG_ERR("Card buffer size needs to be increased for "
574 "unaligned writes to work");
575 k_mutex_unlock(&card->lock);
576 return -ENOBUFS;
577 }
578 rlen = sizeof(card->card_buffer) / card->block_size;
579 sector = 0;
580 buf_offset = rbuf;
581 while (sector < num_blocks) {
582 /* Read from disk to card buffer */
583 ret = card_read(card, card->card_buffer, sector + start_block, rlen);
584 if (ret) {
585 LOG_ERR("Write failed");
586 k_mutex_unlock(&card->lock);
587 return ret;
588 }
589 /* Copy data from card buffer */
590 memcpy(buf_offset, card->card_buffer, rlen * card->block_size);
591 /* Increase sector count and buffer offset */
592 sector += rlen;
593 buf_offset += rlen * card->block_size;
594 }
595 } else {
596 /* Aligned buffers can be used directly */
597 ret = card_read(card, rbuf, start_block, num_blocks);
598 if (ret) {
599 LOG_ERR("Card read failed");
600 k_mutex_unlock(&card->lock);
601 return ret;
602 }
603 }
604 k_mutex_unlock(&card->lock);
605 return 0;
606 }
607
608 /*
609 * Sends ACMD22 (number of written blocks) to see how many blocks were written
610 * to a card
611 */
card_query_written(struct sd_card * card,uint32_t * num_written)612 static int card_query_written(struct sd_card *card, uint32_t *num_written)
613 {
614 int ret;
615 struct sdhc_command cmd;
616 struct sdhc_data data;
617 uint32_t *blocks = (uint32_t *)card->card_buffer;
618
619 ret = card_app_command(card, card->relative_addr);
620 if (ret) {
621 LOG_DBG("App CMD for ACMD22 failed");
622 return ret;
623 }
624
625 cmd.opcode = SD_APP_SEND_NUM_WRITTEN_BLK;
626 cmd.arg = 0;
627 cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
628 cmd.retries = CONFIG_SD_CMD_RETRIES;
629 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
630
631 data.block_addr = 0; /* Unused set to 0 */
632 data.block_size = 4U;
633 data.blocks = 1U;
634 data.data = blocks;
635 data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
636
637 ret = sdhc_request(card->sdhc, &cmd, &data);
638 if (ret) {
639 LOG_DBG("ACMD22 failed: %d", ret);
640 return ret;
641 }
642 ret = sd_check_response(&cmd);
643 if (ret) {
644 LOG_DBG("ACMD22 reports error");
645 return ret;
646 }
647
648 /* Decode blocks */
649 *num_written = sys_be32_to_cpu(blocks[0]);
650 return 0;
651 }
652
card_write(struct sd_card * card,const uint8_t * wbuf,uint32_t start_block,uint32_t num_blocks)653 static int card_write(struct sd_card *card, const uint8_t *wbuf, uint32_t start_block,
654 uint32_t num_blocks)
655 {
656 int ret;
657 uint32_t blocks;
658 struct sdhc_command cmd;
659 struct sdhc_data data;
660
661 /*
662 * See the note in card_read() above. We will not issue CMD23
663 * or CMD12, and expect the host to handle those details.
664 */
665 cmd.opcode = (num_blocks == 1) ? SD_WRITE_SINGLE_BLOCK : SD_WRITE_MULTIPLE_BLOCK;
666 if (!(card->flags & SD_HIGH_CAPACITY_FLAG)) {
667 /* SDSC cards require block size in bytes, not blocks */
668 cmd.arg = start_block * card->block_size;
669 } else {
670 cmd.arg = start_block;
671 }
672 cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
673 cmd.retries = CONFIG_SD_DATA_RETRIES;
674 cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
675
676 data.block_addr = start_block;
677 data.block_size = card->block_size;
678 data.blocks = num_blocks;
679 data.data = (uint8_t *)wbuf;
680 data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
681
682 LOG_DBG("WRITE: Sector = %u, Count = %u", start_block, num_blocks);
683
684 ret = sdhc_request(card->sdhc, &cmd, &data);
685 if (ret) {
686 LOG_DBG("Write failed: %d", ret);
687 ret = sdmmc_wait_ready(card);
688 if (ret) {
689 return ret;
690 }
691 /* Query card to see how many blocks were actually written */
692 ret = card_query_written(card, &blocks);
693 if (ret) {
694 return ret;
695 }
696 LOG_ERR("Only %d blocks of %d were written", blocks, num_blocks);
697 return -EIO;
698 }
699 /* Verify card is back in transfer state after write */
700 ret = sdmmc_wait_ready(card);
701 if (ret) {
702 LOG_ERR("Card did not return to ready state");
703 return -ETIMEDOUT;
704 }
705 return 0;
706 }
707
708 /* Writes data to SD card memory card */
card_write_blocks(struct sd_card * card,const uint8_t * wbuf,uint32_t start_block,uint32_t num_blocks)709 int card_write_blocks(struct sd_card *card, const uint8_t *wbuf, uint32_t start_block,
710 uint32_t num_blocks)
711 {
712 int ret;
713 uint32_t wlen;
714 uint32_t sector;
715 const uint8_t *buf_offset;
716
717 if ((start_block + num_blocks) > card->block_count) {
718 return -EINVAL;
719 }
720 if (card->type == CARD_SDIO) {
721 LOG_WRN("SDIO does not support MMC commands");
722 return -ENOTSUP;
723 }
724 ret = k_mutex_lock(&card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
725 if (ret) {
726 LOG_WRN("Could not get SD card mutex");
727 return -EBUSY;
728 }
729 /*
730 * If the buffer we are provided with is aligned, we can use it
731 * directly. Otherwise, we need to use the card's internal buffer
732 * and memcpy the data back out
733 */
734 if ((((uintptr_t)wbuf) & (CONFIG_SDHC_BUFFER_ALIGNMENT - 1)) != 0) {
735 /* lower bits of address are set, not aligned. Use internal buffer */
736 LOG_DBG("Unaligned buffer access to SD card may incur performance penalty");
737 if (sizeof(card->card_buffer) < card->block_size) {
738 LOG_ERR("Card buffer size needs to be increased for "
739 "unaligned writes to work");
740 k_mutex_unlock(&card->lock);
741 return -ENOBUFS;
742 }
743 wlen = sizeof(card->card_buffer) / card->block_size;
744 sector = 0;
745 buf_offset = wbuf;
746 while (sector < num_blocks) {
747 /* Copy data into card buffer */
748 memcpy(card->card_buffer, buf_offset, wlen * card->block_size);
749 /* Write card buffer to disk */
750 ret = card_write(card, card->card_buffer, sector + start_block, wlen);
751 if (ret) {
752 LOG_ERR("Write failed");
753 k_mutex_unlock(&card->lock);
754 return ret;
755 }
756 /* Increase sector count and buffer offset */
757 sector += wlen;
758 buf_offset += wlen * card->block_size;
759 }
760 } else {
761 /* We can use aligned buffers directly */
762 ret = card_write(card, wbuf, start_block, num_blocks);
763 if (ret) {
764 LOG_ERR("Write failed");
765 k_mutex_unlock(&card->lock);
766 return ret;
767 }
768 }
769 k_mutex_unlock(&card->lock);
770 return 0;
771 }
772
773 /* IO Control handler for SD MMC */
card_ioctl(struct sd_card * card,uint8_t cmd,void * buf)774 int card_ioctl(struct sd_card *card, uint8_t cmd, void *buf)
775 {
776 int ret;
777
778 ret = k_mutex_lock(&card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
779 if (ret) {
780 LOG_WRN("Could not get SD card mutex");
781 return ret;
782 }
783 switch (cmd) {
784 case DISK_IOCTL_GET_SECTOR_COUNT:
785 (*(uint32_t *)buf) = card->block_count;
786 break;
787 case DISK_IOCTL_GET_SECTOR_SIZE:
788 case DISK_IOCTL_GET_ERASE_BLOCK_SZ:
789 (*(uint32_t *)buf) = card->block_size;
790 break;
791 case DISK_IOCTL_CTRL_SYNC:
792 /* Ensure card is not busy with data write.
793 * Note that SD stack does not support enabling caching, so
794 * cache flush is not required here
795 */
796 ret = sdmmc_wait_ready(card);
797 break;
798 default:
799 ret = -ENOTSUP;
800 }
801 k_mutex_unlock(&card->lock);
802 return ret;
803 }
804