1 /*
2  * Copyright 2022 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/drivers/sdhc.h>
9 #include <zephyr/sd/sd.h>
10 #include <zephyr/sd/sdmmc.h>
11 #include <zephyr/sd/sd_spec.h>
12 #include <zephyr/logging/log.h>
13 #include <zephyr/sys/byteorder.h>
14 #include <zephyr/drivers/disk.h>
15 
16 #include "sd_utils.h"
17 #include "sd_ops.h"
18 
19 LOG_MODULE_DECLARE(sd, CONFIG_SD_LOG_LEVEL);
20 
sdmmc_decode_scr(struct sd_scr * scr,uint32_t * raw_scr,uint8_t * version)21 static inline void sdmmc_decode_scr(struct sd_scr *scr, uint32_t *raw_scr, uint8_t *version)
22 {
23 	uint32_t tmp_version = 0;
24 
25 	scr->flags = 0U;
26 	scr->scr_structure = (uint8_t)((raw_scr[0U] & 0xF0000000U) >> 28U);
27 	scr->sd_spec = (uint8_t)((raw_scr[0U] & 0xF000000U) >> 24U);
28 	if ((uint8_t)((raw_scr[0U] & 0x800000U) >> 23U)) {
29 		scr->flags |= SD_SCR_DATA_STATUS_AFTER_ERASE;
30 	}
31 	scr->sd_sec = (uint8_t)((raw_scr[0U] & 0x700000U) >> 20U);
32 	scr->sd_width = (uint8_t)((raw_scr[0U] & 0xF0000U) >> 16U);
33 	if ((uint8_t)((raw_scr[0U] & 0x8000U) >> 15U)) {
34 		scr->flags |= SD_SCR_SPEC3;
35 	}
36 	scr->sd_ext_sec = (uint8_t)((raw_scr[0U] & 0x7800U) >> 10U);
37 	scr->cmd_support = (uint8_t)(raw_scr[0U] & 0x3U);
38 	scr->rsvd = raw_scr[1U];
39 	/* Get specification version. */
40 	switch (scr->sd_spec) {
41 	case 0U:
42 		tmp_version = SD_SPEC_VER1_0;
43 		break;
44 	case 1U:
45 		tmp_version = SD_SPEC_VER1_1;
46 		break;
47 	case 2U:
48 		tmp_version = SD_SPEC_VER2_0;
49 		if (scr->flags & SD_SCR_SPEC3) {
50 			tmp_version = SD_SPEC_VER3_0;
51 		}
52 		break;
53 	default:
54 		break;
55 	}
56 
57 	if (version && tmp_version) {
58 		*version = tmp_version;
59 	}
60 }
61 
62 /* Helper to send SD app command */
sdmmc_app_command(struct sd_card * card,int relative_card_address)63 static int sdmmc_app_command(struct sd_card *card, int relative_card_address)
64 {
65 	return card_app_command(card, relative_card_address);
66 }
67 
68 /* Reads OCR from SPI mode card using CMD58 */
sdmmc_spi_send_ocr(struct sd_card * card,uint32_t arg)69 static int sdmmc_spi_send_ocr(struct sd_card *card, uint32_t arg)
70 {
71 	struct sdhc_command cmd;
72 	int ret;
73 
74 	cmd.opcode = SD_SPI_READ_OCR;
75 	cmd.arg = arg;
76 	cmd.response_type = SD_SPI_RSP_TYPE_R3;
77 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
78 	cmd.retries = CONFIG_SD_CMD_RETRIES;
79 
80 	ret = sdhc_request(card->sdhc, &cmd, NULL);
81 
82 	if (ret) {
83 		LOG_DBG("CMD58 failed: %d", ret);
84 		return ret;
85 	}
86 
87 	card->ocr = cmd.response[1];
88 	if (card->ocr == 0) {
89 		LOG_DBG("No OCR detected");
90 		return -ENOTSUP;
91 	}
92 
93 	return ret;
94 }
95 
96 /* Sends OCR to card using ACMD41 */
sdmmc_send_ocr(struct sd_card * card,int ocr)97 static int sdmmc_send_ocr(struct sd_card *card, int ocr)
98 {
99 	struct sdhc_command cmd;
100 	int ret;
101 	int retries;
102 
103 	cmd.opcode = SD_APP_SEND_OP_COND;
104 	cmd.arg = ocr;
105 	cmd.response_type = (SD_RSP_TYPE_R3 | SD_SPI_RSP_TYPE_R1);
106 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
107 	cmd.retries = CONFIG_SD_CMD_RETRIES;
108 
109 	/* Send initialization ACMD41 */
110 	for (retries = 0; retries < CONFIG_SD_OCR_RETRY_COUNT; retries++) {
111 		ret = sdmmc_app_command(card, 0U);
112 		if (ret == SD_RETRY) {
113 			/* Retry */
114 			continue;
115 		} else if (ret) {
116 			return ret;
117 		}
118 		ret = sdhc_request(card->sdhc, &cmd, NULL);
119 		if (ret) {
120 			/* OCR failed */
121 			return ret;
122 		}
123 		if (ocr == 0) {
124 			/* Just probing, don't wait for card to exit busy state */
125 			return 0;
126 		}
127 		/*
128 		 * Check to see if card is busy with power up. PWR_BUSY
129 		 * flag will be cleared when card finishes power up sequence
130 		 */
131 		if (card->host_props.is_spi) {
132 			if (!(cmd.response[0] & SD_SPI_R1IDLE_STATE)) {
133 				break;
134 			}
135 		} else {
136 			if ((cmd.response[0U] & SD_OCR_PWR_BUSY_FLAG)) {
137 				break;
138 			}
139 		}
140 		sd_delay(10);
141 	}
142 	if (retries >= CONFIG_SD_OCR_RETRY_COUNT) {
143 		/* OCR timed out */
144 		LOG_ERR("Card never left busy state");
145 		return -ETIMEDOUT;
146 	}
147 	LOG_DBG("SDMMC responded to ACMD41 after %d attempts", retries);
148 	if (!card->host_props.is_spi) {
149 		/* Save OCR */
150 		card->ocr = cmd.response[0U];
151 	}
152 	return 0;
153 }
154 
155 /* Reads SD configuration register */
sdmmc_read_scr(struct sd_card * card)156 static int sdmmc_read_scr(struct sd_card *card)
157 {
158 	struct sdhc_command cmd = {0};
159 	struct sdhc_data data = {0};
160 	/* Place SCR struct on stack to reduce flash usage */
161 	struct sd_scr card_scr;
162 	int ret;
163 	/* DMA onto stack is unsafe, so we use an internal card buffer */
164 	uint32_t *scr = (uint32_t *)card->card_buffer;
165 	uint32_t raw_scr[2];
166 
167 	ret = sdmmc_app_command(card, card->relative_addr);
168 	if (ret) {
169 		LOG_DBG("SD app command failed for SD SCR");
170 		return ret;
171 	}
172 
173 	cmd.opcode = SD_APP_SEND_SCR;
174 	cmd.arg = 0;
175 	cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
176 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
177 	cmd.retries = CONFIG_SD_CMD_RETRIES;
178 
179 	data.block_size = 8U;
180 	data.blocks = 1U;
181 	data.data = scr;
182 	data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
183 
184 	ret = sdhc_request(card->sdhc, &cmd, &data);
185 	if (ret) {
186 		LOG_DBG("ACMD51 failed: %d", ret);
187 		return ret;
188 	}
189 	/* Decode SCR */
190 	raw_scr[0] = sys_be32_to_cpu(scr[0]);
191 	raw_scr[1] = sys_be32_to_cpu(scr[1]);
192 	sdmmc_decode_scr(&card_scr, raw_scr, &card->sd_version);
193 	LOG_DBG("SD reports specification version %d", card->sd_version);
194 	/* Check card supported bus width */
195 	if (card_scr.sd_width & 0x4U) {
196 		card->flags |= SD_4BITS_WIDTH;
197 	}
198 	/* Check if card supports speed class command (CMD20) */
199 	if (card_scr.cmd_support & 0x1U) {
200 		card->flags |= SD_SPEED_CLASS_CONTROL_FLAG;
201 	}
202 	/* Check for set block count (CMD 23) support */
203 	if (card_scr.cmd_support & 0x2U) {
204 		card->flags |= SD_CMD23_FLAG;
205 	}
206 	return 0;
207 }
208 
209 /* Sets block length of SD card */
sdmmc_set_blocklen(struct sd_card * card,uint32_t block_len)210 static int sdmmc_set_blocklen(struct sd_card *card, uint32_t block_len)
211 {
212 	struct sdhc_command cmd = {0};
213 
214 	cmd.opcode = SD_SET_BLOCK_SIZE;
215 	cmd.arg = block_len;
216 	cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
217 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
218 	cmd.retries = CONFIG_SD_CMD_RETRIES;
219 
220 	return sdhc_request(card->sdhc, &cmd, NULL);
221 }
222 
223 /*
224  * Sets bus width of host and card, following section 3.4 of
225  * SD host controller specification
226  */
sdmmc_set_bus_width(struct sd_card * card,enum sdhc_bus_width width)227 static int sdmmc_set_bus_width(struct sd_card *card, enum sdhc_bus_width width)
228 {
229 	struct sdhc_command cmd = {0};
230 	int ret;
231 
232 	/*
233 	 * The specification strictly requires card interrupts to be masked, but
234 	 * Linux does not do so, so we won't either.
235 	 */
236 	/* Send ACMD6 to change bus width */
237 	ret = sdmmc_app_command(card, card->relative_addr);
238 	if (ret) {
239 		LOG_DBG("SD app command failed for ACMD6");
240 		return ret;
241 	}
242 
243 	cmd.opcode = SD_APP_SET_BUS_WIDTH;
244 	cmd.response_type = SD_RSP_TYPE_R1;
245 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
246 	cmd.retries = CONFIG_SD_CMD_RETRIES;
247 
248 	switch (width) {
249 	case SDHC_BUS_WIDTH1BIT:
250 		cmd.arg = 0U;
251 		break;
252 	case SDHC_BUS_WIDTH4BIT:
253 		cmd.arg = 2U;
254 		break;
255 	default:
256 		return -ENOTSUP;
257 	}
258 	/* Send app command */
259 	ret = sdhc_request(card->sdhc, &cmd, NULL);
260 	if (ret) {
261 		LOG_DBG("Error on ACMD6: %d", ret);
262 		return ret;
263 	}
264 	ret = sd_check_response(&cmd);
265 	if (ret) {
266 		LOG_DBG("ACMD6 reports error, response 0x%x", cmd.response[0U]);
267 		return ret;
268 	}
269 	/* Card now has changed bus width. Change host bus width */
270 	card->bus_io.bus_width = width;
271 	ret = sdhc_set_io(card->sdhc, &card->bus_io);
272 	if (ret) {
273 		LOG_DBG("Could not change host bus width");
274 	}
275 	return ret;
276 }
277 
278 /*
279  * Sends SD switch function CMD6.
280  * See table 4-32 in SD physical specification for argument details.
281  * When setting a function, we should set the 4 bit block of the command
282  * argument corresponding to that function to "value", and all other 4 bit
283  * blocks should be left as 0xF (no effect on current function)
284  */
sdmmc_switch(struct sd_card * card,enum sd_switch_arg mode,enum sd_group_num group,uint8_t value,uint8_t * response)285 static int sdmmc_switch(struct sd_card *card, enum sd_switch_arg mode, enum sd_group_num group,
286 			uint8_t value, uint8_t *response)
287 {
288 	struct sdhc_command cmd = {0};
289 	struct sdhc_data data = {0};
290 
291 	cmd.opcode = SD_SWITCH;
292 	cmd.arg = ((mode & 0x1) << 31) | 0x00FFFFFF;
293 	cmd.arg &= ~(0xFU << (group * 4));
294 	cmd.arg |= (value & 0xF) << (group * 4);
295 	cmd.response_type = (SD_RSP_TYPE_R1 | SD_SPI_RSP_TYPE_R1);
296 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
297 	cmd.retries = CONFIG_SD_CMD_RETRIES;
298 
299 	data.block_size = 64U;
300 	data.blocks = 1;
301 	data.data = response;
302 	data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
303 
304 	return sdhc_request(card->sdhc, &cmd, &data);
305 }
306 
sdmmc_read_switch(struct sd_card * card)307 static int sdmmc_read_switch(struct sd_card *card)
308 {
309 	uint8_t *status;
310 	int ret;
311 
312 	if (card->sd_version < SD_SPEC_VER1_1) {
313 		/* Switch not supported */
314 		LOG_INF("SD spec 1.01 does not support CMD6");
315 		return 0;
316 	}
317 	/* Use card internal buffer to read 64 byte switch data */
318 	status = card->card_buffer;
319 	/*
320 	 * Setting switch to zero will read card's support values,
321 	 * otherwise known as SD "check function"
322 	 */
323 	ret = sdmmc_switch(card, SD_SWITCH_CHECK, 0, 0, status);
324 	if (ret) {
325 		LOG_DBG("CMD6 failed %d", ret);
326 		return ret;
327 	}
328 	/*
329 	 * See table 4-11 and 4.3.10.4 of physical layer specification for
330 	 * bit definitions. Note that response is big endian, so index 13 will
331 	 * read bits 400-408.
332 	 * Bit n being set in support bit field indicates support for function
333 	 * number n on the card. (So 0x3 indicates support for functions 0 and 1)
334 	 */
335 	/* Determine HS speed support, if any */
336 	if (status[13] & HIGH_SPEED_BUS_SPEED) {
337 		card->switch_caps.hs_max_dtr = HS_MAX_DTR;
338 	} else {
339 		card->switch_caps.hs_max_dtr = HS_UNSUPPORTED;
340 	}
341 	/* Determine UHS speed support, if any */
342 	if (status[13] & UHS_SDR104_BUS_SPEED) {
343 		card->switch_caps.uhs_max_dtr = UHS_SDR104_MAX_DTR;
344 	} else if (status[13] & UHS_DDR50_BUS_SPEED) {
345 		card->switch_caps.uhs_max_dtr = UHS_DDR50_MAX_DTR;
346 	} else if (status[13] & UHS_SDR50_BUS_SPEED) {
347 		card->switch_caps.uhs_max_dtr = UHS_SDR50_MAX_DTR;
348 	} else if (status[13] & UHS_SDR25_BUS_SPEED) {
349 		card->switch_caps.uhs_max_dtr = UHS_SDR25_MAX_DTR;
350 	} else if (status[13] & UHS_SDR12_BUS_SPEED) {
351 		card->switch_caps.uhs_max_dtr = UHS_SDR12_MAX_DTR;
352 	} else {
353 		card->switch_caps.uhs_max_dtr = UHS_UNSUPPORTED;
354 	}
355 	if (card->sd_version >= SD_SPEC_VER3_0) {
356 		card->switch_caps.bus_speed = status[13];
357 		card->switch_caps.sd_drv_type = status[9];
358 		card->switch_caps.sd_current_limit = status[7];
359 	}
360 	return 0;
361 }
362 
sdmmc_select_bus_speed(struct sd_card * card)363 static inline void sdmmc_select_bus_speed(struct sd_card *card)
364 {
365 	/*
366 	 * Note that function support is defined using bitfields, but function
367 	 * selection is defined using values 0x0-0xF.
368 	 */
369 	if ((card->flags & SD_1800MV_FLAG) && sdmmc_host_uhs(&card->host_props) &&
370 	    !(card->host_props.is_spi) && IS_ENABLED(CONFIG_SD_UHS_PROTOCOL)) {
371 		/* Select UHS mode timing */
372 		if (card->host_props.host_caps.sdr104_support &&
373 		    (card->switch_caps.bus_speed & UHS_SDR104_BUS_SPEED)) {
374 			card->card_speed = SD_TIMING_SDR104;
375 		} else if (card->host_props.host_caps.ddr50_support &&
376 			   (card->switch_caps.bus_speed & UHS_DDR50_BUS_SPEED)) {
377 			card->card_speed = SD_TIMING_DDR50;
378 		} else if (card->host_props.host_caps.sdr50_support &&
379 			   (card->switch_caps.bus_speed & UHS_SDR50_BUS_SPEED)) {
380 			card->card_speed = SD_TIMING_SDR50;
381 		} else if (card->switch_caps.bus_speed & UHS_SDR12_BUS_SPEED) {
382 			card->card_speed = SD_TIMING_SDR25;
383 		} else {
384 			card->card_speed = SD_TIMING_SDR12;
385 		}
386 	} else {
387 		/* Select HS mode timing */
388 		if (card->host_props.host_caps.high_spd_support &&
389 		    (card->switch_caps.bus_speed & HIGH_SPEED_BUS_SPEED)) {
390 			card->card_speed = SD_TIMING_HIGH_SPEED;
391 		} else {
392 			card->card_speed = SD_TIMING_DEFAULT;
393 		}
394 	}
395 }
396 
397 /* Selects driver type for SD card */
sdmmc_select_driver_type(struct sd_card * card)398 static int sdmmc_select_driver_type(struct sd_card *card)
399 {
400 	int ret = 0;
401 	uint8_t *status = card->card_buffer;
402 
403 	/*
404 	 * We will only attempt to use driver type C over the default of type B,
405 	 * since it should result in lower current consumption if supported.
406 	 */
407 	if (card->host_props.host_caps.drv_type_c_support &&
408 	    (card->switch_caps.sd_drv_type & SD_DRIVER_TYPE_C)) {
409 		card->bus_io.driver_type = SD_DRIVER_TYPE_C;
410 		/* Change drive strength */
411 		ret = sdmmc_switch(card, SD_SWITCH_SET, SD_GRP_DRIVER_STRENGTH_MODE,
412 				   (find_msb_set(SD_DRIVER_TYPE_C) - 1), status);
413 	}
414 	return ret;
415 }
416 
417 /* Sets current limit for SD card */
sdmmc_set_current_limit(struct sd_card * card)418 static int sdmmc_set_current_limit(struct sd_card *card)
419 {
420 	int ret;
421 	int max_current = -1;
422 	uint8_t *status = card->card_buffer;
423 
424 	if ((card->card_speed != SD_TIMING_SDR50) && (card->card_speed != SD_TIMING_SDR104) &&
425 	    (card->card_speed != SD_TIMING_DDR50)) {
426 		return 0; /* Cannot set current limit */
427 	} else if (card->host_props.max_current_180 >= 800 &&
428 		   (card->switch_caps.sd_current_limit & SD_MAX_CURRENT_800MA)) {
429 		max_current = SD_SET_CURRENT_800MA;
430 	} else if (card->host_props.max_current_180 >= 600 &&
431 		   (card->switch_caps.sd_current_limit & SD_MAX_CURRENT_600MA)) {
432 		max_current = SD_SET_CURRENT_600MA;
433 	} else if (card->host_props.max_current_180 >= 400 &&
434 		   (card->switch_caps.sd_current_limit & SD_MAX_CURRENT_400MA)) {
435 		max_current = SD_SET_CURRENT_400MA;
436 	} else if (card->host_props.max_current_180 >= 200 &&
437 		   (card->switch_caps.sd_current_limit & SD_MAX_CURRENT_200MA)) {
438 		max_current = SD_SET_CURRENT_200MA;
439 	}
440 	if (max_current != -1) {
441 		LOG_DBG("Changing SD current limit: %d", max_current);
442 		/* Switch SD current */
443 		ret = sdmmc_switch(card, SD_SWITCH_SET, SD_GRP_CURRENT_LIMIT_MODE, max_current,
444 				   status);
445 		if (ret) {
446 			LOG_DBG("Failed to set SD current limit");
447 			return ret;
448 		}
449 		if (((status[15] >> 4) & 0x0F) != max_current) {
450 			/* Status response indicates card did not select request limit */
451 			LOG_WRN("Card did not accept current limit");
452 		}
453 	}
454 	return 0;
455 }
456 
457 /* Applies selected card bus speed to card and host */
sdmmc_set_bus_speed(struct sd_card * card)458 static int sdmmc_set_bus_speed(struct sd_card *card)
459 {
460 	int ret;
461 	uint8_t *status = card->card_buffer;
462 	enum sdhc_timing_mode timing;
463 	uint32_t card_clock;
464 
465 	/* Set card clock and host timing. Since the card's maximum clock
466 	 * was calculated within sdmmc_read_switch(), we can safely use the
467 	 * minimum between that clock and the host's highest clock supported.
468 	 */
469 	if ((card->flags & SD_1800MV_FLAG) && sdmmc_host_uhs(&card->host_props) &&
470 	    !(card->host_props.is_spi) && IS_ENABLED(CONFIG_SD_UHS_PROTOCOL)) {
471 		/* UHS mode */
472 		card_clock = MIN(card->host_props.f_max, card->switch_caps.uhs_max_dtr);
473 		switch (card->card_speed) {
474 		case SD_TIMING_SDR104:
475 			timing = SDHC_TIMING_SDR104;
476 			break;
477 		case SD_TIMING_DDR50:
478 			timing = SDHC_TIMING_DDR50;
479 			break;
480 		case SD_TIMING_SDR50:
481 			timing = SDHC_TIMING_SDR50;
482 			break;
483 		case SD_TIMING_SDR25:
484 			timing = SDHC_TIMING_SDR25;
485 			break;
486 		case SD_TIMING_SDR12:
487 			timing = SDHC_TIMING_SDR12;
488 			break;
489 		default:
490 			/* No need to change bus speed */
491 			return 0;
492 		}
493 	} else {
494 		/* High speed/default mode */
495 		card_clock = MIN(card->host_props.f_max, card->switch_caps.hs_max_dtr);
496 		switch (card->card_speed) {
497 		case SD_TIMING_HIGH_SPEED:
498 			timing = SDHC_TIMING_HS;
499 			break;
500 		case SD_TIMING_DEFAULT:
501 			timing = SDHC_TIMING_LEGACY;
502 			break;
503 		default:
504 			/* No need to change bus speed */
505 			return 0;
506 		}
507 	}
508 
509 	/* Switch bus speed */
510 	ret = sdmmc_switch(card, SD_SWITCH_SET, SD_GRP_TIMING_MODE, card->card_speed, status);
511 	if (ret) {
512 		LOG_DBG("Failed to switch SD card speed");
513 		return ret;
514 	}
515 	if ((status[16] & 0xF) != card->card_speed) {
516 		LOG_WRN("Card did not accept new speed");
517 	} else {
518 		/* Change host bus speed */
519 		card->bus_io.timing = timing;
520 		card->bus_io.clock = card_clock;
521 		LOG_DBG("Setting bus clock to: %d", card->bus_io.clock);
522 		ret = sdhc_set_io(card->sdhc, &card->bus_io);
523 		if (ret) {
524 			LOG_ERR("Failed to change host bus speed");
525 			return ret;
526 		}
527 	}
528 	return 0;
529 }
530 
531 /*
532  * Init UHS capable SD card. Follows figure 3-16 in physical layer specification.
533  */
sdmmc_init_uhs(struct sd_card * card)534 static int sdmmc_init_uhs(struct sd_card *card)
535 {
536 	int ret;
537 
538 	/* Raise bus width to 4 bits */
539 	ret = sdmmc_set_bus_width(card, SDHC_BUS_WIDTH4BIT);
540 	if (ret) {
541 		LOG_ERR("Failed to change card bus width to 4 bits");
542 		return ret;
543 	}
544 
545 	/* Select bus speed for card depending on host and card capability*/
546 	sdmmc_select_bus_speed(card);
547 	/* Now, set the driver strength for the card */
548 	ret = sdmmc_select_driver_type(card);
549 	if (ret) {
550 		LOG_DBG("Failed to select new driver type");
551 		return ret;
552 	}
553 	ret = sdmmc_set_current_limit(card);
554 	if (ret) {
555 		LOG_DBG("Failed to set card current limit");
556 		return ret;
557 	}
558 	/* Apply the bus speed selected earlier */
559 	ret = sdmmc_set_bus_speed(card);
560 	if (ret) {
561 		LOG_DBG("Failed to set card bus speed");
562 		return ret;
563 	}
564 	if (card->card_speed == SD_TIMING_SDR50 || card->card_speed == SD_TIMING_SDR104 ||
565 	    card->card_speed == SD_TIMING_DDR50) {
566 		/* SDR104, SDR50, and DDR50 mode need tuning */
567 		ret = sdhc_execute_tuning(card->sdhc);
568 		if (ret) {
569 			LOG_ERR("SD tuning failed: %d", ret);
570 		}
571 	}
572 	return ret;
573 }
574 
575 /* Performs initialization for SD high speed cards */
sdmmc_init_hs(struct sd_card * card)576 static int sdmmc_init_hs(struct sd_card *card)
577 {
578 	int ret;
579 
580 	if ((!card->host_props.host_caps.high_spd_support) ||
581 	    (card->sd_version < SD_SPEC_VER1_1) ||
582 	    (card->switch_caps.hs_max_dtr == HS_UNSUPPORTED)) {
583 		/* No high speed support. Leave card untouched */
584 		return 0;
585 	}
586 	/* Select bus speed for card depending on host and card capability*/
587 	sdmmc_select_bus_speed(card);
588 	/* Apply selected bus speed */
589 	ret = sdmmc_set_bus_speed(card);
590 	if (ret) {
591 		LOG_ERR("Failed to switch card to HS mode");
592 		return ret;
593 	}
594 	if (card->flags & SD_4BITS_WIDTH) {
595 		/* Raise bus width to 4 bits */
596 		ret = sdmmc_set_bus_width(card, SDHC_BUS_WIDTH4BIT);
597 		if (ret) {
598 			LOG_ERR("Failed to change card bus width to 4 bits");
599 			return ret;
600 		}
601 	}
602 	return 0;
603 }
604 
605 /*
606  * Initializes SDMMC card. Note that the common SD function has already
607  * sent CMD0 and CMD8 to the card at function entry.
608  */
sdmmc_card_init(struct sd_card * card)609 int sdmmc_card_init(struct sd_card *card)
610 {
611 	int ret;
612 	uint32_t ocr_arg = 0U;
613 
614 	/* First send a probing OCR */
615 	if (card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_SPI_MODE)) {
616 		/* Probe SPI card with CMD58*/
617 		ret = sdmmc_spi_send_ocr(card, ocr_arg);
618 	} else if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
619 		/* Probe Native card with ACMD41 */
620 		ret = sdmmc_send_ocr(card, ocr_arg);
621 	} else {
622 		return -ENOTSUP;
623 	}
624 	if (ret) {
625 		return ret;
626 	}
627 	/* Card responded to ACMD41, type is SDMMC */
628 	card->type = CARD_SDMMC;
629 
630 	if (card->flags & SD_SDHC_FLAG) {
631 		if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
632 			/* High capacity card. See if host supports 1.8V */
633 			if (card->host_props.host_caps.vol_180_support) {
634 				ocr_arg |= SD_OCR_SWITCH_18_REQ_FLAG;
635 			}
636 		}
637 		/* Set host high capacity support flag */
638 		ocr_arg |= SD_OCR_HOST_CAP_FLAG;
639 	}
640 	if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
641 		/* Set voltage window */
642 		if (card->host_props.host_caps.vol_300_support) {
643 			ocr_arg |= SD_OCR_VDD29_30FLAG;
644 		}
645 		ocr_arg |= (SD_OCR_VDD32_33FLAG | SD_OCR_VDD33_34FLAG);
646 	}
647 	/* Momentary delay before initialization OCR. Some cards will
648 	 * never leave busy state if init OCR is sent too soon after
649 	 * probing OCR
650 	 */
651 	k_busy_wait(100);
652 	/* Send SD OCR to card to initialize it */
653 	ret = sdmmc_send_ocr(card, ocr_arg);
654 	if (ret) {
655 		LOG_ERR("Failed to query card OCR");
656 		return ret;
657 	}
658 	if (card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_SPI_MODE)) {
659 		/* Send second CMD58 to get CCS bit */
660 		ret = sdmmc_spi_send_ocr(card, ocr_arg);
661 		if (ret) {
662 			return ret;
663 		}
664 	}
665 	/* Check SD high capacity and 1.8V support flags */
666 	if (card->ocr & SD_OCR_CARD_CAP_FLAG) {
667 		card->flags |= SD_HIGH_CAPACITY_FLAG;
668 	}
669 	if (card->ocr & SD_OCR_SWITCH_18_ACCEPT_FLAG) {
670 		LOG_DBG("Card supports 1.8V signaling");
671 		card->flags |= SD_1800MV_FLAG;
672 	}
673 	/* Check OCR voltage window */
674 	if (card->ocr & SD_OCR_VDD29_30FLAG) {
675 		card->flags |= SD_3000MV_FLAG;
676 	}
677 	/*
678 	 * If card is high capacity (SDXC or SDHC), and supports 1.8V signaling,
679 	 * switch to new signal voltage using "signal voltage switch procedure"
680 	 * described in SD specification
681 	 */
682 	if ((card->flags & SD_1800MV_FLAG) && (card->host_props.host_caps.vol_180_support) &&
683 	    (!card->host_props.is_spi) && IS_ENABLED(CONFIG_SD_UHS_PROTOCOL)) {
684 		ret = sdmmc_switch_voltage(card);
685 		if (ret) {
686 			/* Disable host support for 1.8 V */
687 			card->host_props.host_caps.vol_180_support = false;
688 			/*
689 			 * The host or SD card may have already switched to
690 			 * 1.8V. Return SD_RESTART to indicate
691 			 * negotiation should be restarted.
692 			 */
693 			card->status = CARD_ERROR;
694 			return SD_RESTART;
695 		}
696 	}
697 	/* Read the card's CID (card identification register) */
698 	ret = card_read_cid(card);
699 	if (ret) {
700 		return ret;
701 	}
702 	if (!card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
703 		/*
704 		 * Request new relative card address. This moves the card from
705 		 * identification mode to data transfer mode
706 		 */
707 		ret = sdmmc_request_rca(card);
708 		if (ret) {
709 			return ret;
710 		}
711 	}
712 	/* Card has entered data transfer mode. Get card specific data register */
713 	ret = sdmmc_read_csd(card);
714 	if (ret) {
715 		return ret;
716 	}
717 	if (!card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
718 		/* Move the card to transfer state (with CMD7) to run remaining commands */
719 		ret = sdmmc_select_card(card);
720 		if (ret) {
721 			return ret;
722 		}
723 	}
724 	/*
725 	 * With card in data transfer state, we can set SD clock to maximum
726 	 * frequency for non high speed mode (25Mhz)
727 	 */
728 	if (card->host_props.f_max < SD_CLOCK_25MHZ) {
729 		LOG_INF("Maximum SD clock is under 25MHz, using clock of %dHz",
730 			card->host_props.f_max);
731 		card->bus_io.clock = card->host_props.f_max;
732 	} else {
733 		card->bus_io.clock = SD_CLOCK_25MHZ;
734 	}
735 	ret = sdhc_set_io(card->sdhc, &card->bus_io);
736 	if (ret) {
737 		LOG_ERR("Failed to raise bus frequency to 25MHz");
738 		return ret;
739 	}
740 	/* Read SD SCR (SD configuration register),
741 	 * to get supported bus width
742 	 */
743 	ret = sdmmc_read_scr(card);
744 	if (ret) {
745 		return ret;
746 	}
747 	/* Read switch capabilities to determine what speeds card supports */
748 	if (!card->host_props.is_spi && IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
749 		ret = sdmmc_read_switch(card);
750 		if (ret) {
751 			LOG_ERR("Failed to read card functions");
752 			return ret;
753 		}
754 	}
755 	if ((card->flags & SD_1800MV_FLAG) && sdmmc_host_uhs(&card->host_props) &&
756 	    !(card->host_props.is_spi) && IS_ENABLED(CONFIG_SD_UHS_PROTOCOL)) {
757 		ret = sdmmc_init_uhs(card);
758 		if (ret) {
759 			LOG_ERR("UHS card init failed");
760 		}
761 	} else {
762 		if ((card->flags & SD_HIGH_CAPACITY_FLAG) == 0) {
763 			/* Standard capacity SDSC card. set block length to 512 */
764 			ret = sdmmc_set_blocklen(card, SDMMC_DEFAULT_BLOCK_SIZE);
765 			if (ret) {
766 				LOG_ERR("Could not set SD blocklen to 512");
767 				return ret;
768 			}
769 			card->block_size = 512;
770 		}
771 		/* Card is not UHS. Try to use high speed mode */
772 		ret = sdmmc_init_hs(card);
773 		if (ret) {
774 			LOG_ERR("HS card init failed");
775 		}
776 	}
777 	return ret;
778 }
779 
sdmmc_ioctl(struct sd_card * card,uint8_t cmd,void * buf)780 int sdmmc_ioctl(struct sd_card *card, uint8_t cmd, void *buf)
781 {
782 	return card_ioctl(card, cmd, buf);
783 }
784 
sdmmc_read_blocks(struct sd_card * card,uint8_t * rbuf,uint32_t start_block,uint32_t num_blocks)785 int sdmmc_read_blocks(struct sd_card *card, uint8_t *rbuf, uint32_t start_block,
786 		      uint32_t num_blocks)
787 {
788 	return card_read_blocks(card, rbuf, start_block, num_blocks);
789 }
790 
sdmmc_write_blocks(struct sd_card * card,const uint8_t * wbuf,uint32_t start_block,uint32_t num_blocks)791 int sdmmc_write_blocks(struct sd_card *card, const uint8_t *wbuf, uint32_t start_block,
792 		       uint32_t num_blocks)
793 {
794 	return card_write_blocks(card, wbuf, start_block, num_blocks);
795 }
796