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;
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 		k_mutex_unlock(&card->lock);
539 		return -ETIMEDOUT;
540 	}
541 	return 0;
542 }
543 
544 /* 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)545 int card_read_blocks(struct sd_card *card, uint8_t *rbuf, uint32_t start_block, uint32_t num_blocks)
546 {
547 	int ret;
548 	uint32_t rlen;
549 	uint32_t sector;
550 	uint8_t *buf_offset;
551 
552 	if ((start_block + num_blocks) > card->block_count) {
553 		return -EINVAL;
554 	}
555 	if (card->type == CARD_SDIO) {
556 		LOG_WRN("SDIO does not support MMC commands");
557 		return -ENOTSUP;
558 	}
559 	ret = k_mutex_lock(&card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
560 	if (ret) {
561 		LOG_WRN("Could not get SD card mutex");
562 		return -EBUSY;
563 	}
564 
565 	/*
566 	 * If the buffer we are provided with is aligned, we can use it
567 	 * directly. Otherwise, we need to use the card's internal buffer
568 	 * and memcpy the data back out
569 	 */
570 	if ((((uintptr_t)rbuf) & (CONFIG_SDHC_BUFFER_ALIGNMENT - 1)) != 0) {
571 		/* lower bits of address are set, not aligned. Use internal buffer */
572 		LOG_DBG("Unaligned buffer access to SD card may incur performance penalty");
573 		if (sizeof(card->card_buffer) < card->block_size) {
574 			LOG_ERR("Card buffer size needs to be increased for "
575 				"unaligned writes to work");
576 			k_mutex_unlock(&card->lock);
577 			return -ENOBUFS;
578 		}
579 		rlen = sizeof(card->card_buffer) / card->block_size;
580 		sector = 0;
581 		buf_offset = rbuf;
582 		while (sector < num_blocks) {
583 			/* Read from disk to card buffer */
584 			ret = card_read(card, card->card_buffer, sector + start_block, rlen);
585 			if (ret) {
586 				LOG_ERR("Write failed");
587 				k_mutex_unlock(&card->lock);
588 				return ret;
589 			}
590 			/* Copy data from card buffer */
591 			memcpy(buf_offset, card->card_buffer, rlen * card->block_size);
592 			/* Increase sector count and buffer offset */
593 			sector += rlen;
594 			buf_offset += rlen * card->block_size;
595 		}
596 	} else {
597 		/* Aligned buffers can be used directly */
598 		ret = card_read(card, rbuf, start_block, num_blocks);
599 		if (ret) {
600 			LOG_ERR("Card read failed");
601 			k_mutex_unlock(&card->lock);
602 			return ret;
603 		}
604 	}
605 	k_mutex_unlock(&card->lock);
606 	return 0;
607 }
608 
609 /*
610  * Sends ACMD22 (number of written blocks) to see how many blocks were written
611  * to a card
612  */
card_query_written(struct sd_card * card,uint32_t * num_written)613 static int card_query_written(struct sd_card *card, uint32_t *num_written)
614 {
615 	int ret;
616 	struct sdhc_command cmd;
617 	struct sdhc_data data;
618 	uint32_t *blocks = (uint32_t *)card->card_buffer;
619 
620 	ret = card_app_command(card, card->relative_addr);
621 	if (ret) {
622 		LOG_DBG("App CMD for ACMD22 failed");
623 		return ret;
624 	}
625 
626 	cmd.opcode = SD_APP_SEND_NUM_WRITTEN_BLK;
627 	cmd.arg = 0;
628 	cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
629 	cmd.retries = CONFIG_SD_CMD_RETRIES;
630 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
631 
632 	data.block_addr = 0;        /* Unused set to 0 */
633 	data.block_size = 4U;
634 	data.blocks = 1U;
635 	data.data = blocks;
636 	data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
637 
638 	ret = sdhc_request(card->sdhc, &cmd, &data);
639 	if (ret) {
640 		LOG_DBG("ACMD22 failed: %d", ret);
641 		return ret;
642 	}
643 	ret = sd_check_response(&cmd);
644 	if (ret) {
645 		LOG_DBG("ACMD22 reports error");
646 		return ret;
647 	}
648 
649 	/* Decode blocks */
650 	*num_written = sys_be32_to_cpu(blocks[0]);
651 	return 0;
652 }
653 
card_write(struct sd_card * card,const uint8_t * wbuf,uint32_t start_block,uint32_t num_blocks)654 static int card_write(struct sd_card *card, const uint8_t *wbuf, uint32_t start_block,
655 		      uint32_t num_blocks)
656 {
657 	int ret;
658 	uint32_t blocks;
659 	struct sdhc_command cmd;
660 	struct sdhc_data data;
661 
662 	/*
663 	 * See the note in card_read() above. We will not issue CMD23
664 	 * or CMD12, and expect the host to handle those details.
665 	 */
666 	cmd.opcode = (num_blocks == 1) ? SD_WRITE_SINGLE_BLOCK : SD_WRITE_MULTIPLE_BLOCK;
667 	if (!(card->flags & SD_HIGH_CAPACITY_FLAG)) {
668 		/* SDSC cards require block size in bytes, not blocks */
669 		cmd.arg = start_block * card->block_size;
670 	} else {
671 		cmd.arg = start_block;
672 	}
673 	cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
674 	cmd.retries = CONFIG_SD_DATA_RETRIES;
675 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
676 
677 	data.block_addr = start_block;
678 	data.block_size = card->block_size;
679 	data.blocks = num_blocks;
680 	data.data = (uint8_t *)wbuf;
681 	data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
682 
683 	LOG_DBG("WRITE: Sector = %u, Count = %u", start_block, num_blocks);
684 
685 	ret = sdhc_request(card->sdhc, &cmd, &data);
686 	if (ret) {
687 		LOG_DBG("Write failed: %d", ret);
688 		ret = sdmmc_wait_ready(card);
689 		if (ret) {
690 			return ret;
691 		}
692 		/* Query card to see how many blocks were actually written */
693 		ret = card_query_written(card, &blocks);
694 		if (ret) {
695 			return ret;
696 		}
697 		LOG_ERR("Only %d blocks of %d were written", blocks, num_blocks);
698 		return -EIO;
699 	}
700 	/* Verify card is back in transfer state after write */
701 	ret = sdmmc_wait_ready(card);
702 	if (ret) {
703 		LOG_ERR("Card did not return to ready state");
704 		return -ETIMEDOUT;
705 	}
706 	return 0;
707 }
708 
709 /* 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)710 int card_write_blocks(struct sd_card *card, const uint8_t *wbuf, uint32_t start_block,
711 		      uint32_t num_blocks)
712 {
713 	int ret;
714 	uint32_t wlen;
715 	uint32_t sector;
716 	const uint8_t *buf_offset;
717 
718 	if ((start_block + num_blocks) > card->block_count) {
719 		return -EINVAL;
720 	}
721 	if (card->type == CARD_SDIO) {
722 		LOG_WRN("SDIO does not support MMC commands");
723 		return -ENOTSUP;
724 	}
725 	ret = k_mutex_lock(&card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
726 	if (ret) {
727 		LOG_WRN("Could not get SD card mutex");
728 		return -EBUSY;
729 	}
730 	/*
731 	 * If the buffer we are provided with is aligned, we can use it
732 	 * directly. Otherwise, we need to use the card's internal buffer
733 	 * and memcpy the data back out
734 	 */
735 	if ((((uintptr_t)wbuf) & (CONFIG_SDHC_BUFFER_ALIGNMENT - 1)) != 0) {
736 		/* lower bits of address are set, not aligned. Use internal buffer */
737 		LOG_DBG("Unaligned buffer access to SD card may incur performance penalty");
738 		if (sizeof(card->card_buffer) < card->block_size) {
739 			LOG_ERR("Card buffer size needs to be increased for "
740 				"unaligned writes to work");
741 			k_mutex_unlock(&card->lock);
742 			return -ENOBUFS;
743 		}
744 		wlen = sizeof(card->card_buffer) / card->block_size;
745 		sector = 0;
746 		buf_offset = wbuf;
747 		while (sector < num_blocks) {
748 			/* Copy data into card buffer */
749 			memcpy(card->card_buffer, buf_offset, wlen * card->block_size);
750 			/* Write card buffer to disk */
751 			ret = card_write(card, card->card_buffer, sector + start_block, wlen);
752 			if (ret) {
753 				LOG_ERR("Write failed");
754 				k_mutex_unlock(&card->lock);
755 				return ret;
756 			}
757 			/* Increase sector count and buffer offset */
758 			sector += wlen;
759 			buf_offset += wlen * card->block_size;
760 		}
761 	} else {
762 		/* We can use aligned buffers directly */
763 		ret = card_write(card, wbuf, start_block, num_blocks);
764 		if (ret) {
765 			LOG_ERR("Write failed");
766 			k_mutex_unlock(&card->lock);
767 			return ret;
768 		}
769 	}
770 	k_mutex_unlock(&card->lock);
771 	return 0;
772 }
773 
774 /* IO Control handler for SD MMC */
card_ioctl(struct sd_card * card,uint8_t cmd,void * buf)775 int card_ioctl(struct sd_card *card, uint8_t cmd, void *buf)
776 {
777 	switch (cmd) {
778 	case DISK_IOCTL_GET_SECTOR_COUNT:
779 		(*(uint32_t *)buf) = card->block_count;
780 		break;
781 	case DISK_IOCTL_GET_SECTOR_SIZE:
782 	case DISK_IOCTL_GET_ERASE_BLOCK_SZ:
783 		(*(uint32_t *)buf) = card->block_size;
784 		break;
785 	case DISK_IOCTL_CTRL_SYNC:
786 		/* Ensure card is not busy with data write.
787 		 * Note that SD stack does not support enabling caching, so
788 		 * cache flush is not required here
789 		 */
790 		return sdmmc_wait_ready(card);
791 	default:
792 		return -ENOTSUP;
793 	}
794 	return 0;
795 }
796