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