1 /*
2  * Copyright 2022-2023 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 
14 #include "sd_ops.h"
15 #include "sd_utils.h"
16 
17 LOG_MODULE_DECLARE(sd, CONFIG_SD_LOG_LEVEL);
18 
19 uint8_t cis_tuples[] = {
20 	SDIO_TPL_CODE_MANIFID,
21 	SDIO_TPL_CODE_FUNCID,
22 	SDIO_TPL_CODE_FUNCE,
23 };
24 
25 /*
26  * Send SDIO OCR using CMD5
27  */
sdio_send_ocr(struct sd_card * card,uint32_t ocr)28 static int sdio_send_ocr(struct sd_card *card, uint32_t ocr)
29 {
30 	struct sdhc_command cmd = {0};
31 	int ret;
32 	int retries;
33 
34 	cmd.opcode = SDIO_SEND_OP_COND;
35 	cmd.arg = ocr;
36 	cmd.response_type = (SD_RSP_TYPE_R4 | SD_SPI_RSP_TYPE_R4);
37 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
38 	/* Send OCR5 to initialize card */
39 	for (retries = 0; retries < CONFIG_SD_OCR_RETRY_COUNT; retries++) {
40 		ret = sdhc_request(card->sdhc, &cmd, NULL);
41 		if (ret) {
42 			if (ocr == 0) {
43 				/* Just probing card, likely not SDIO */
44 				return SD_NOT_SDIO;
45 			}
46 			return ret;
47 		}
48 		if (ocr == 0) {
49 			/* We are probing card, check number of IO functions */
50 			card->num_io = (cmd.response[0] & SDIO_OCR_IO_NUMBER)
51 				>> SDIO_OCR_IO_NUMBER_SHIFT;
52 			if ((card->num_io == 0) ||
53 				((cmd.response[0] & SDIO_IO_OCR_MASK) == 0)) {
54 				if (cmd.response[0] & SDIO_OCR_MEM_PRESENT_FLAG) {
55 					/* Card is not an SDIO card */
56 					return SD_NOT_SDIO;
57 				}
58 				/* Card is not a supported SD device */
59 				return -ENOTSUP;
60 			}
61 			/* Card has IO present, return zero to
62 			 * indicate SDIO card
63 			 */
64 			return 0;
65 		}
66 		/* Check to see if card is busy with power up */
67 		if (cmd.response[0] & SD_OCR_PWR_BUSY_FLAG) {
68 			break;
69 		}
70 		/* Delay before retrying command */
71 		sd_delay(10);
72 	}
73 	if (retries >= CONFIG_SD_OCR_RETRY_COUNT) {
74 		/* OCR timed out */
75 		LOG_ERR("Card never left busy state");
76 		return -ETIMEDOUT;
77 	}
78 	LOG_DBG("SDIO responded to CMD5 after %d attempts", retries);
79 	if (!card->host_props.is_spi) {
80 		/* Save OCR */
81 		card->ocr = cmd.response[0U];
82 	}
83 	return 0;
84 }
85 
sdio_io_rw_direct(struct sd_card * card,enum sdio_io_dir direction,enum sdio_func_num func,uint32_t reg_addr,uint8_t data_in,uint8_t * data_out)86 static int sdio_io_rw_direct(struct sd_card *card,
87 			     enum sdio_io_dir direction,
88 			     enum sdio_func_num func,
89 			     uint32_t reg_addr,
90 			     uint8_t data_in,
91 			     uint8_t *data_out)
92 {
93 	int ret;
94 	struct sdhc_command cmd = {0};
95 
96 	cmd.opcode = SDIO_RW_DIRECT;
97 	cmd.arg = (func << SDIO_CMD_ARG_FUNC_NUM_SHIFT) |
98 		((reg_addr & SDIO_CMD_ARG_REG_ADDR_MASK) << SDIO_CMD_ARG_REG_ADDR_SHIFT);
99 	if (direction == SDIO_IO_WRITE) {
100 		cmd.arg |= data_in & SDIO_DIRECT_CMD_DATA_MASK;
101 		cmd.arg |= BIT(SDIO_CMD_ARG_RW_SHIFT);
102 		if (data_out) {
103 			cmd.arg |= BIT(SDIO_DIRECT_CMD_ARG_RAW_SHIFT);
104 		}
105 	}
106 	cmd.response_type = (SD_RSP_TYPE_R5 | SD_SPI_RSP_TYPE_R5);
107 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
108 
109 	ret = sdhc_request(card->sdhc, &cmd, NULL);
110 	if (ret) {
111 		return ret;
112 	}
113 	if (data_out) {
114 		if (card->host_props.is_spi) {
115 			*data_out = (cmd.response[0U] >> 8) & SDIO_DIRECT_CMD_DATA_MASK;
116 		} else {
117 			*data_out = cmd.response[0U] & SDIO_DIRECT_CMD_DATA_MASK;
118 		}
119 	}
120 	return ret;
121 }
122 
123 
sdio_io_rw_extended(struct sd_card * card,enum sdio_io_dir direction,enum sdio_func_num func,uint32_t reg_addr,bool increment,uint8_t * buf,uint32_t blocks,uint32_t block_size)124 static int sdio_io_rw_extended(struct sd_card *card,
125 			       enum sdio_io_dir direction,
126 			       enum sdio_func_num func,
127 			       uint32_t reg_addr,
128 			       bool increment,
129 			       uint8_t *buf,
130 			       uint32_t blocks,
131 			       uint32_t block_size)
132 {
133 	struct sdhc_command cmd = {0};
134 	struct sdhc_data data = {0};
135 
136 	cmd.opcode = SDIO_RW_EXTENDED;
137 	cmd.arg = (func << SDIO_CMD_ARG_FUNC_NUM_SHIFT) |
138 		((reg_addr & SDIO_CMD_ARG_REG_ADDR_MASK) << SDIO_CMD_ARG_REG_ADDR_SHIFT);
139 	cmd.arg |= (direction == SDIO_IO_WRITE) ? BIT(SDIO_CMD_ARG_RW_SHIFT) : 0;
140 	cmd.arg |= increment ? BIT(SDIO_EXTEND_CMD_ARG_OP_CODE_SHIFT) : 0;
141 	cmd.response_type = (SD_RSP_TYPE_R5 | SD_SPI_RSP_TYPE_R5);
142 	cmd.timeout_ms = CONFIG_SD_CMD_TIMEOUT;
143 	if (blocks == 0) {
144 		/* Byte mode */
145 		cmd.arg |= (block_size == 512) ? 0 : block_size;
146 	} else {
147 		/* Block mode */
148 		cmd.arg |= BIT(SDIO_EXTEND_CMD_ARG_BLK_SHIFT) | blocks;
149 	}
150 
151 	data.block_size = block_size;
152 	/* Host expects blocks to be at least 1 */
153 	data.blocks = blocks ? blocks : 1;
154 	data.data = buf;
155 	data.timeout_ms = CONFIG_SD_DATA_TIMEOUT;
156 	return sdhc_request(card->sdhc, &cmd, &data);
157 }
158 
159 /*
160  * Helper for extended r/w. Splits the transfer into the minimum possible
161  * number of block r/w, then uses byte transfers for remaining data
162  */
sdio_io_rw_extended_helper(struct sdio_func * func,enum sdio_io_dir direction,uint32_t reg_addr,bool increment,uint8_t * buf,uint32_t len)163 static int sdio_io_rw_extended_helper(struct sdio_func *func,
164 				      enum sdio_io_dir direction,
165 				      uint32_t reg_addr,
166 				      bool increment,
167 				      uint8_t *buf,
168 				      uint32_t len)
169 {
170 	int ret;
171 	int remaining = len;
172 	uint32_t blocks, size;
173 
174 	if (func->num > SDIO_MAX_IO_NUMS) {
175 		return -EINVAL;
176 	}
177 
178 	if ((func->card->cccr_flags & SDIO_SUPPORT_MULTIBLOCK) &&
179 		((len > func->block_size))) {
180 		/* Use block I/O for r/w where possible */
181 		while (remaining >= func->block_size) {
182 			blocks = remaining / func->block_size;
183 			size = blocks * func->block_size;
184 			ret = sdio_io_rw_extended(func->card, direction,
185 				func->num, reg_addr, increment, buf, blocks,
186 				func->block_size);
187 			if (ret) {
188 				return ret;
189 			}
190 			/* Update remaining length and buffer pointer */
191 			remaining -= size;
192 			buf += size;
193 			if (increment) {
194 				reg_addr += size;
195 			}
196 		}
197 	}
198 	/* Remaining data must be written using byte I/O */
199 	while (remaining > 0) {
200 		size = MIN(remaining, func->cis.max_blk_size);
201 
202 		ret = sdio_io_rw_extended(func->card, direction, func->num,
203 			reg_addr, increment, buf, 0, size);
204 		if (ret) {
205 			return ret;
206 		}
207 		remaining -= size;
208 		buf += size;
209 		if (increment) {
210 			reg_addr += size;
211 		}
212 	}
213 	return 0;
214 }
215 
216 /*
217  * Read card capability register to determine features card supports.
218  */
sdio_read_cccr(struct sd_card * card)219 static int sdio_read_cccr(struct sd_card *card)
220 {
221 	int ret;
222 	uint8_t data;
223 	uint32_t cccr_ver;
224 
225 	ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
226 		SDIO_CCCR_CCCR, 0, &data);
227 	if (ret) {
228 		LOG_DBG("CCCR read failed: %d", ret);
229 		return ret;
230 	}
231 	cccr_ver = (data & SDIO_CCCR_CCCR_REV_MASK) >>
232 		SDIO_CCCR_CCCR_REV_SHIFT;
233 	LOG_DBG("SDIO cccr revision %u", cccr_ver);
234 	/* Read SD spec version */
235 	ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
236 		SDIO_CCCR_SD, 0, &data);
237 	if (ret) {
238 		return ret;
239 	}
240 	card->sd_version = (data & SDIO_CCCR_SD_SPEC_MASK) >> SDIO_CCCR_SD_SPEC_SHIFT;
241 	/* Read CCCR capability flags */
242 	ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
243 		SDIO_CCCR_CAPS, 0, &data);
244 	if (ret) {
245 		return ret;
246 	}
247 	card->cccr_flags = 0;
248 	if (data & SDIO_CCCR_CAPS_BLS) {
249 		card->cccr_flags |= SDIO_SUPPORT_4BIT_LS_BUS;
250 	}
251 	if (data & SDIO_CCCR_CAPS_SMB) {
252 		card->cccr_flags |= SDIO_SUPPORT_MULTIBLOCK;
253 	}
254 	if (cccr_ver >= SDIO_CCCR_CCCR_REV_2_00) {
255 		/* Read high speed properties */
256 		ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
257 			SDIO_CCCR_SPEED, 0, &data);
258 		if (ret) {
259 			return ret;
260 		}
261 		if (data & SDIO_CCCR_SPEED_SHS) {
262 			card->cccr_flags |= SDIO_SUPPORT_HS;
263 		}
264 	}
265 	if (cccr_ver >= SDIO_CCCR_CCCR_REV_3_00 &&
266 		(card->flags & SD_1800MV_FLAG)) {
267 		/* Read UHS properties */
268 		ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
269 			SDIO_CCCR_UHS, 0, &data);
270 		if (ret) {
271 			return ret;
272 		}
273 		if (sdmmc_host_uhs(&card->host_props)) {
274 			if (data & SDIO_CCCR_UHS_SDR50) {
275 				card->cccr_flags |= SDIO_SUPPORT_SDR50;
276 			}
277 			if (data & SDIO_CCCR_UHS_SDR104) {
278 				card->cccr_flags |= SDIO_SUPPORT_SDR104;
279 			}
280 			if (data & SDIO_CCCR_UHS_DDR50) {
281 				card->cccr_flags |= SDIO_SUPPORT_DDR50;
282 			}
283 		}
284 
285 		ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
286 			SDIO_CCCR_DRIVE_STRENGTH, 0, &data);
287 		if (ret) {
288 			return ret;
289 		}
290 		card->switch_caps.sd_drv_type = 0;
291 		if (data & SDIO_CCCR_DRIVE_STRENGTH_A) {
292 			card->switch_caps.sd_drv_type |= SD_DRIVER_TYPE_A;
293 		}
294 		if (data & SDIO_CCCR_DRIVE_STRENGTH_C) {
295 			card->switch_caps.sd_drv_type |= SD_DRIVER_TYPE_C;
296 		}
297 		if (data & SDIO_CCCR_DRIVE_STRENGTH_D) {
298 			card->switch_caps.sd_drv_type |= SD_DRIVER_TYPE_D;
299 		}
300 	}
301 	return 0;
302 }
303 
sdio_decode_cis(struct sdio_cis * cis,enum sdio_func_num func,uint8_t * data,uint8_t tpl_code,uint8_t tpl_link)304 static void sdio_decode_cis(struct sdio_cis *cis, enum sdio_func_num func,
305 			    uint8_t *data, uint8_t tpl_code, uint8_t tpl_link)
306 {
307 	switch (tpl_code) {
308 	case SDIO_TPL_CODE_MANIFID:
309 		cis->manf_id = data[0] | ((uint16_t)data[1] << 8);
310 		cis->manf_code = data[2] | ((uint16_t)data[3] << 8);
311 		break;
312 	case SDIO_TPL_CODE_FUNCID:
313 		cis->func_id = data[0];
314 		break;
315 	case SDIO_TPL_CODE_FUNCE:
316 		if (func == 0) {
317 			cis->max_blk_size = data[1] | ((uint16_t)data[2] << 8);
318 			cis->max_speed = data[3];
319 		} else {
320 			cis->max_blk_size = data[12] | ((uint16_t)data[13] << 8);
321 			cis->rdy_timeout = data[28] | ((uint16_t)data[29] << 8);
322 		}
323 		break;
324 	default:
325 		LOG_WRN("Unknown CIS tuple %d", tpl_code);
326 		break;
327 	}
328 }
329 
330 /*
331  * Read CIS for a given SDIO function.
332  * Tuples provides a list of tuples that should be decoded.
333  */
sdio_read_cis(struct sdio_func * func,uint8_t * tuples,uint32_t tuple_count)334 static int sdio_read_cis(struct sdio_func *func,
335 			 uint8_t *tuples,
336 			 uint32_t tuple_count)
337 {
338 	int ret;
339 	char *data = func->card->card_buffer;
340 	uint32_t cis_ptr = 0, num = 0;
341 	uint8_t tpl_code, tpl_link;
342 	bool match_tpl = false;
343 
344 	memset(&func->cis, 0, sizeof(struct sdio_cis));
345 	/* First find the CIS pointer for this function */
346 	for (int i = 0; i < 3; i++) {
347 		ret = sdio_io_rw_direct(func->card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
348 			SDIO_FBR_BASE(func->num) + SDIO_FBR_CIS + i, 0, data);
349 		if (ret) {
350 			return ret;
351 		}
352 		cis_ptr |= *data << (i * 8);
353 	}
354 	/* Read CIS tuples until we have read all requested CIS tuple codes */
355 	do {
356 		/* Read tuple code */
357 		ret = sdio_io_rw_direct(func->card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
358 			cis_ptr++, 0, &tpl_code);
359 		if (ret) {
360 			return ret;
361 		}
362 		if (tpl_code == SDIO_TPL_CODE_END) {
363 			/* End of tuple chain */
364 			break;
365 		}
366 		if (tpl_code == SDIO_TPL_CODE_NULL) {
367 			/* Skip NULL tuple */
368 			continue;
369 		}
370 		/* Read tuple link */
371 		ret = sdio_io_rw_direct(func->card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
372 			cis_ptr++, 0, &tpl_link);
373 		if (ret) {
374 			return ret;
375 		}
376 		if (tpl_link == SDIO_TPL_CODE_END) {
377 			/* End of tuple chain */
378 			break;
379 		}
380 		/* Check to see if read tuple matches any we should look for */
381 		for (int i = 0; i < tuple_count; i++) {
382 			if (tpl_code == tuples[i]) {
383 				match_tpl = true;
384 				break;
385 			}
386 		}
387 		if (match_tpl) {
388 			/* tuple chains may be maximum of 255 bytes long */
389 			memset(data, 0, 255);
390 			for (int i = 0; i < tpl_link; i++) {
391 				ret = sdio_io_rw_direct(func->card, SDIO_IO_READ,
392 					SDIO_FUNC_NUM_0, cis_ptr++, 0, data + i);
393 				if (ret) {
394 					return ret;
395 				}
396 			}
397 			num++;
398 			match_tpl = false;
399 			/* Decode the CIS data we read */
400 			sdio_decode_cis(&func->cis, func->num, data,
401 				tpl_code, tpl_link);
402 		} else {
403 			/* Advance CIS pointer */
404 			cis_ptr += tpl_link;
405 		}
406 	} while (num < tuple_count);
407 	LOG_DBG("SDIO CIS max block size for func %d: %d", func->num,
408 		func->cis.max_blk_size);
409 	return ret;
410 }
411 
sdio_set_bus_width(struct sd_card * card,enum sdhc_bus_width width)412 static int sdio_set_bus_width(struct sd_card *card, enum sdhc_bus_width width)
413 {
414 	uint8_t reg_bus_interface = 0U;
415 	int ret;
416 
417 	ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
418 		SDIO_CCCR_BUS_IF, 0, &reg_bus_interface);
419 	if (ret) {
420 		return ret;
421 	}
422 	reg_bus_interface &= ~SDIO_CCCR_BUS_IF_WIDTH_MASK;
423 	switch (width) {
424 	case SDHC_BUS_WIDTH1BIT:
425 		reg_bus_interface |= SDIO_CCCR_BUS_IF_WIDTH_1_BIT;
426 		break;
427 	case SDHC_BUS_WIDTH4BIT:
428 		reg_bus_interface |= SDIO_CCCR_BUS_IF_WIDTH_4_BIT;
429 		break;
430 	case SDHC_BUS_WIDTH8BIT:
431 		reg_bus_interface |= SDIO_CCCR_BUS_IF_WIDTH_8_BIT;
432 		break;
433 	default:
434 		return -ENOTSUP;
435 	}
436 	ret = sdio_io_rw_direct(card, SDIO_IO_WRITE, SDIO_FUNC_NUM_0,
437 		SDIO_CCCR_BUS_IF, reg_bus_interface, &reg_bus_interface);
438 	if (ret) {
439 		return ret;
440 	}
441 	/* Card now has changed bus width. Change host bus width */
442 	card->bus_io.bus_width = width;
443 	ret = sdhc_set_io(card->sdhc, &card->bus_io);
444 	if (ret) {
445 		LOG_DBG("Could not change host bus width");
446 	}
447 	return ret;
448 }
449 
sdio_select_bus_speed(struct sd_card * card)450 static inline void sdio_select_bus_speed(struct sd_card *card)
451 {
452 	if (card->host_props.host_caps.sdr104_support &&
453 		(card->cccr_flags & SDIO_SUPPORT_SDR104)) {
454 		card->card_speed = SD_TIMING_SDR104;
455 		card->switch_caps.uhs_max_dtr = UHS_SDR104_MAX_DTR;
456 	} else if (card->host_props.host_caps.ddr50_support &&
457 		(card->cccr_flags & SDIO_SUPPORT_DDR50)) {
458 		card->card_speed = SD_TIMING_DDR50;
459 		card->switch_caps.uhs_max_dtr = UHS_DDR50_MAX_DTR;
460 	} else if (card->host_props.host_caps.sdr50_support &&
461 		(card->cccr_flags & SDIO_SUPPORT_SDR50)) {
462 		card->card_speed = SD_TIMING_SDR50;
463 		card->switch_caps.uhs_max_dtr = UHS_SDR50_MAX_DTR;
464 	} else if (card->host_props.host_caps.high_spd_support &&
465 		(card->cccr_flags & SDIO_SUPPORT_HS)) {
466 		card->card_speed = SD_TIMING_HIGH_SPEED;
467 		card->switch_caps.hs_max_dtr = HS_MAX_DTR;
468 	} else {
469 		card->card_speed = SD_TIMING_DEFAULT;
470 	}
471 }
472 
473 /* Applies selected card bus speed to card and host */
sdio_set_bus_speed(struct sd_card * card)474 static int sdio_set_bus_speed(struct sd_card *card)
475 {
476 	int ret, timing, retries = CONFIG_SD_RETRY_COUNT;
477 	uint32_t bus_clock;
478 	uint8_t speed_reg, target_speed;
479 
480 	switch (card->card_speed) {
481 	/* Set bus clock speed */
482 	case SD_TIMING_SDR104:
483 		bus_clock = MIN(card->host_props.f_max, card->switch_caps.uhs_max_dtr);
484 		target_speed = SDIO_CCCR_SPEED_SDR104;
485 		timing = SDHC_TIMING_SDR104;
486 		break;
487 	case SD_TIMING_DDR50:
488 		bus_clock = MIN(card->host_props.f_max, card->switch_caps.uhs_max_dtr);
489 		target_speed = SDIO_CCCR_SPEED_DDR50;
490 		timing = SDHC_TIMING_DDR50;
491 		break;
492 	case SD_TIMING_SDR50:
493 		bus_clock = MIN(card->host_props.f_max, card->switch_caps.uhs_max_dtr);
494 		target_speed = SDIO_CCCR_SPEED_SDR50;
495 		timing = SDHC_TIMING_SDR50;
496 		break;
497 	case SD_TIMING_HIGH_SPEED:
498 		bus_clock = MIN(card->host_props.f_max, card->switch_caps.hs_max_dtr);
499 		target_speed = SDIO_CCCR_SPEED_SDR25;
500 		timing = SDHC_TIMING_HS;
501 		break;
502 	case SD_TIMING_DEFAULT:
503 		bus_clock = MIN(card->host_props.f_max, MHZ(25));
504 		target_speed = SDIO_CCCR_SPEED_SDR12;
505 		timing = SDHC_TIMING_LEGACY;
506 		break;
507 	default:
508 		/* No need to change bus speed */
509 		return 0;
510 	}
511 	/* Read the bus speed register */
512 	ret = sdio_io_rw_direct(card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
513 		SDIO_CCCR_SPEED, 0, &speed_reg);
514 	if (ret) {
515 		return ret;
516 	}
517 	/* Attempt to set speed several times */
518 	do {
519 		/* Set new speed */
520 		speed_reg &= ~SDIO_CCCR_SPEED_MASK;
521 		speed_reg |= (target_speed << SDIO_CCCR_SPEED_SHIFT);
522 		ret = sdio_io_rw_direct(card, SDIO_IO_WRITE, SDIO_FUNC_NUM_0,
523 			SDIO_CCCR_SPEED, speed_reg, &speed_reg);
524 		if (ret) {
525 			return ret;
526 		}
527 	} while (((speed_reg & target_speed) != target_speed) && retries-- > 0);
528 	if (retries == 0) {
529 		/* Don't error out, as card can still work */
530 		LOG_WRN("Could not set target SDIO speed");
531 	} else {
532 		/* Set card bus clock and timing */
533 		card->bus_io.timing = timing;
534 		card->bus_io.clock = bus_clock;
535 		LOG_DBG("Setting bus clock to: %d", card->bus_io.clock);
536 		ret = sdhc_set_io(card->sdhc, &card->bus_io);
537 		if (ret) {
538 			LOG_ERR("Failed to change host bus speed");
539 			return ret;
540 		}
541 	}
542 	return ret;
543 }
544 
545 /*
546  * Initialize an SDIO card for use with subsystem
547  */
sdio_card_init(struct sd_card * card)548 int sdio_card_init(struct sd_card *card)
549 {
550 	int ret;
551 	uint32_t ocr_arg = 0U;
552 
553 	/* Probe card with SDIO OCR CM5 */
554 	ret = sdio_send_ocr(card, ocr_arg);
555 	if (ret) {
556 		return ret;
557 	}
558 	/* Card responded to CMD5, type is SDIO */
559 	card->type = CARD_SDIO;
560 	/* Set voltage window */
561 	if (card->host_props.host_caps.vol_300_support) {
562 		ocr_arg |= SD_OCR_VDD29_30FLAG;
563 	}
564 	ocr_arg |= (SD_OCR_VDD32_33FLAG | SD_OCR_VDD33_34FLAG);
565 	if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE) &&
566 		card->host_props.host_caps.vol_180_support) {
567 		/* See if the card also supports 1.8V */
568 		ocr_arg |= SD_OCR_SWITCH_18_REQ_FLAG;
569 	}
570 	ret = sdio_send_ocr(card, ocr_arg);
571 	if (ret) {
572 		return ret;
573 	}
574 	if (card->ocr & SD_OCR_SWITCH_18_ACCEPT_FLAG) {
575 		LOG_DBG("Card supports 1.8V signalling");
576 		card->flags |= SD_1800MV_FLAG;
577 	}
578 	/* Check OCR voltage window */
579 	if (card->ocr & SD_OCR_VDD29_30FLAG) {
580 		card->flags |= SD_3000MV_FLAG;
581 	}
582 	/* Check mem present flag */
583 	if (card->ocr & SDIO_OCR_MEM_PRESENT_FLAG) {
584 		card->flags |= SD_MEM_PRESENT_FLAG;
585 	}
586 	/* Following steps are only required when using native SD mode */
587 	if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE)) {
588 		/*
589 		 * If card and host support 1.8V, perform voltage switch sequence now.
590 		 * note that we skip this switch if the UHS protocol is not enabled.
591 		 */
592 		if ((card->flags & SD_1800MV_FLAG) &&
593 			(!card->host_props.is_spi) &&
594 			(card->host_props.host_caps.vol_180_support) &&
595 			IS_ENABLED(CONFIG_SD_UHS_PROTOCOL)) {
596 			ret = sdmmc_switch_voltage(card);
597 			if (ret) {
598 				/* Disable host support for 1.8 V */
599 				card->host_props.host_caps.vol_180_support = false;
600 				/*
601 				 * The host or SD card may have already switched to
602 				 * 1.8V. Return SD_RESTART to indicate
603 				 * negotiation should be restarted.
604 				 */
605 				card->status = CARD_ERROR;
606 				return SD_RESTART;
607 			}
608 		}
609 		if ((card->flags & SD_MEM_PRESENT_FLAG) &&
610 			((card->flags & SD_SDHC_FLAG) == 0)) {
611 			/* We must send CMD2 to get card cid */
612 			ret = card_read_cid(card);
613 			if (ret) {
614 				return ret;
615 			}
616 		}
617 		/* Send CMD3 to get card relative address */
618 		ret = sdmmc_request_rca(card);
619 		if (ret) {
620 			return ret;
621 		}
622 		/* Move the card to transfer state (with CMD7) to run
623 		 * remaining commands
624 		 */
625 		ret = sdmmc_select_card(card);
626 		if (ret) {
627 			return ret;
628 		}
629 	}
630 	/* Read SDIO card common control register */
631 	ret = sdio_read_cccr(card);
632 	if (ret) {
633 		return ret;
634 	}
635 	/* Initialize internal card function 0 structure */
636 	card->func0.num = SDIO_FUNC_NUM_0;
637 	card->func0.card = card;
638 	ret = sdio_read_cis(&card->func0, cis_tuples,
639 		ARRAY_SIZE(cis_tuples));
640 	if (ret) {
641 		return ret;
642 	}
643 
644 	/* If card and host support 4 bit bus, enable it */
645 	if (IS_ENABLED(CONFIG_SDHC_SUPPORTS_NATIVE_MODE) &&
646 		((card->cccr_flags & SDIO_SUPPORT_HS) ||
647 		(card->cccr_flags & SDIO_SUPPORT_4BIT_LS_BUS))) {
648 		/* Raise bus width to 4 bits */
649 		ret = sdio_set_bus_width(card, SDHC_BUS_WIDTH4BIT);
650 		if (ret) {
651 			return ret;
652 		}
653 		LOG_DBG("Raised card bus width to 4 bits");
654 	}
655 
656 	/* Select and set bus speed */
657 	sdio_select_bus_speed(card);
658 	ret = sdio_set_bus_speed(card);
659 	if (ret) {
660 		return ret;
661 	}
662 	if (card->card_speed == SD_TIMING_SDR50 ||
663 		card->card_speed == SD_TIMING_SDR104) {
664 		/* SDR104, SDR50, and DDR50 mode need tuning */
665 		ret = sdhc_execute_tuning(card->sdhc);
666 		if (ret) {
667 			LOG_ERR("SD tuning failed: %d", ret);
668 		}
669 	}
670 	return ret;
671 }
672 
673 /**
674  * @brief Initialize SDIO function.
675  *
676  * Initializes SDIO card function. The card function will not be enabled,
677  * but after this call returns the SDIO function structure can be used to read
678  * and write data from the card.
679  * @param func: function structure to initialize
680  * @param card: SD card to enable function on
681  * @param num: function number to initialize
682  * @retval 0 function was initialized successfully
683  * @retval -EIO: I/O error
684  */
sdio_init_func(struct sd_card * card,struct sdio_func * func,enum sdio_func_num num)685 int sdio_init_func(struct sd_card *card, struct sdio_func *func,
686 		   enum sdio_func_num num)
687 {
688 	/* Initialize function structure */
689 	func->num = num;
690 	func->card = card;
691 	func->block_size = 0;
692 	/* Read function properties from CCCR */
693 	return sdio_read_cis(func, cis_tuples, ARRAY_SIZE(cis_tuples));
694 }
695 
696 
697 
698 /**
699  * @brief Enable SDIO function
700  *
701  * Enables SDIO card function. @ref sdio_init_func must be called to
702  * initialized the function structure before enabling it in the card.
703  * @param func: function to enable
704  * @retval 0 function was enabled successfully
705  * @retval -ETIMEDOUT: card I/O timed out
706  * @retval -EIO: I/O error
707  */
sdio_enable_func(struct sdio_func * func)708 int sdio_enable_func(struct sdio_func *func)
709 {
710 	int ret;
711 	uint8_t reg;
712 	uint16_t retries = CONFIG_SD_RETRY_COUNT;
713 
714 	/* Enable the I/O function */
715 	ret = sdio_io_rw_direct(func->card, SDIO_IO_READ, SDIO_FUNC_NUM_0,
716 		SDIO_CCCR_IO_EN, 0, &reg);
717 	if (ret) {
718 		return ret;
719 	}
720 	reg |= BIT(func->num);
721 	ret = sdio_io_rw_direct(func->card, SDIO_IO_WRITE, SDIO_FUNC_NUM_0,
722 		SDIO_CCCR_IO_EN, reg, &reg);
723 	if (ret) {
724 		return ret;
725 	}
726 	/* Wait for I/O ready to be set */
727 	if (func->cis.rdy_timeout) {
728 		retries = 1U;
729 	}
730 	do {
731 		/* Timeout is in units of 10ms */
732 		sd_delay(((uint32_t)func->cis.rdy_timeout) * 10U);
733 		ret = sdio_io_rw_direct(func->card, SDIO_IO_READ,
734 			SDIO_FUNC_NUM_0, SDIO_CCCR_IO_RD, 0, &reg);
735 		if (ret) {
736 			return ret;
737 		}
738 		if (reg & BIT(func->num)) {
739 			return 0;
740 		}
741 	} while (retries-- != 0);
742 	return -ETIMEDOUT;
743 }
744 
745 /**
746  * @brief Set block size of SDIO function
747  *
748  * Set desired block size for SDIO function, used by block transfers
749  * to SDIO registers.
750  * @param func: function to set block size for
751  * @param bsize: block size
752  * @retval 0 block size was set
753  * @retval -EINVAL: unsupported/invalid block size
754  * @retval -EIO: I/O error
755  */
sdio_set_block_size(struct sdio_func * func,uint16_t bsize)756 int sdio_set_block_size(struct sdio_func *func, uint16_t bsize)
757 {
758 	int ret;
759 	uint8_t reg;
760 
761 	if (func->cis.max_blk_size < bsize) {
762 		return -EINVAL;
763 	}
764 	for (int i = 0; i < 2; i++) {
765 		reg = (bsize >> (i * 8));
766 		ret = sdio_io_rw_direct(func->card, SDIO_IO_WRITE, SDIO_FUNC_NUM_0,
767 			SDIO_FBR_BASE(func->num) + SDIO_FBR_BLK_SIZE + i, reg, NULL);
768 		if (ret) {
769 			return ret;
770 		}
771 	}
772 	func->block_size = bsize;
773 	return 0;
774 }
775 
776 /**
777  * @brief Read byte from SDIO register
778  *
779  * Reads byte from SDIO register
780  * @param func: function to read from
781  * @param reg: register address to read from
782  * @param val: filled with byte value read from register
783  * @retval 0 read succeeded
784  * @retval -EBUSY: card is busy with another request
785  * @retval -ETIMEDOUT: card read timed out
786  * @retval -EIO: I/O error
787  */
sdio_read_byte(struct sdio_func * func,uint32_t reg,uint8_t * val)788 int sdio_read_byte(struct sdio_func *func, uint32_t reg, uint8_t *val)
789 {
790 	int ret;
791 
792 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
793 		LOG_WRN("Card does not support SDIO commands");
794 		return -ENOTSUP;
795 	}
796 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
797 	if (ret) {
798 		LOG_WRN("Could not get SD card mutex");
799 		return -EBUSY;
800 	}
801 	ret = sdio_io_rw_direct(func->card, SDIO_IO_READ, func->num, reg, 0, val);
802 	k_mutex_unlock(&func->card->lock);
803 	return ret;
804 }
805 
806 /**
807  * @brief Write byte to SDIO register
808  *
809  * Writes byte to SDIO register
810  * @param func: function to write to
811  * @param reg: register address to write to
812  * @param write_val: value to write to register
813  * @retval 0 write succeeded
814  * @retval -EBUSY: card is busy with another request
815  * @retval -ETIMEDOUT: card write timed out
816  * @retval -EIO: I/O error
817  */
sdio_write_byte(struct sdio_func * func,uint32_t reg,uint8_t write_val)818 int sdio_write_byte(struct sdio_func *func, uint32_t reg, uint8_t write_val)
819 {
820 	int ret;
821 
822 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
823 		LOG_WRN("Card does not support SDIO commands");
824 		return -ENOTSUP;
825 	}
826 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
827 	if (ret) {
828 		LOG_WRN("Could not get SD card mutex");
829 		return -EBUSY;
830 	}
831 	ret = sdio_io_rw_direct(func->card, SDIO_IO_WRITE, func->num, reg,
832 		write_val, NULL);
833 	k_mutex_unlock(&func->card->lock);
834 	return ret;
835 }
836 
837 /**
838  * @brief Write byte to SDIO register, and read result
839  *
840  * Writes byte to SDIO register, and reads the register after write
841  * @param func: function to write to
842  * @param reg: register address to write to
843  * @param write_val: value to write to register
844  * @param read_val: filled with value read from register
845  * @retval 0 write succeeded
846  * @retval -EBUSY: card is busy with another request
847  * @retval -ETIMEDOUT: card write timed out
848  * @retval -EIO: I/O error
849  */
sdio_rw_byte(struct sdio_func * func,uint32_t reg,uint8_t write_val,uint8_t * read_val)850 int sdio_rw_byte(struct sdio_func *func, uint32_t reg, uint8_t write_val,
851 		 uint8_t *read_val)
852 {
853 	int ret;
854 
855 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
856 		LOG_WRN("Card does not support SDIO commands");
857 		return -ENOTSUP;
858 	}
859 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
860 	if (ret) {
861 		LOG_WRN("Could not get SD card mutex");
862 		return -EBUSY;
863 	}
864 	ret = sdio_io_rw_direct(func->card, SDIO_IO_WRITE, func->num, reg,
865 		write_val, read_val);
866 	k_mutex_unlock(&func->card->lock);
867 	return ret;
868 }
869 
870 /**
871  * @brief Read bytes from SDIO fifo
872  *
873  * Reads bytes from SDIO register, treating it as a fifo. Reads will
874  * all be done from same address.
875  * @param func: function to read from
876  * @param reg: register address of fifo
877  * @param data: filled with data read from fifo
878  * @param len: length of data to read from card
879  * @retval 0 read succeeded
880  * @retval -EBUSY: card is busy with another request
881  * @retval -ETIMEDOUT: card read timed out
882  * @retval -EIO: I/O error
883  */
sdio_read_fifo(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t len)884 int sdio_read_fifo(struct sdio_func *func, uint32_t reg, uint8_t *data,
885 		   uint32_t len)
886 {
887 	int ret;
888 
889 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
890 		LOG_WRN("Card does not support SDIO commands");
891 		return -ENOTSUP;
892 	}
893 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
894 	if (ret) {
895 		LOG_WRN("Could not get SD card mutex");
896 		return -EBUSY;
897 	}
898 	ret = sdio_io_rw_extended_helper(func, SDIO_IO_READ, reg, false,
899 		data, len);
900 	k_mutex_unlock(&func->card->lock);
901 	return ret;
902 }
903 
904 /**
905  * @brief Write bytes to SDIO fifo
906  *
907  * Writes bytes to SDIO register, treating it as a fifo. Writes will
908  * all be done to same address.
909  * @param func: function to write to
910  * @param reg: register address of fifo
911  * @param data: data to write to fifo
912  * @param len: length of data to write to card
913  * @retval 0 write succeeded
914  * @retval -EBUSY: card is busy with another request
915  * @retval -ETIMEDOUT: card write timed out
916  * @retval -EIO: I/O error
917  */
sdio_write_fifo(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t len)918 int sdio_write_fifo(struct sdio_func *func, uint32_t reg, uint8_t *data,
919 		    uint32_t len)
920 {
921 	int ret;
922 
923 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
924 		LOG_WRN("Card does not support SDIO commands");
925 		return -ENOTSUP;
926 	}
927 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
928 	if (ret) {
929 		LOG_WRN("Could not get SD card mutex");
930 		return -EBUSY;
931 	}
932 	ret = sdio_io_rw_extended_helper(func, SDIO_IO_WRITE, reg, false,
933 		data, len);
934 	k_mutex_unlock(&func->card->lock);
935 	return ret;
936 }
937 
938 /**
939  * @brief Read blocks from SDIO fifo
940  *
941  * Reads blocks from SDIO register, treating it as a fifo. Reads will
942  * all be done from same address.
943  * @param func: function to read from
944  * @param reg: register address of fifo
945  * @param data: filled with data read from fifo
946  * @param blocks: number of blocks to read from fifo
947  * @retval 0 read succeeded
948  * @retval -EBUSY: card is busy with another request
949  * @retval -ETIMEDOUT: card read timed out
950  * @retval -EIO: I/O error
951  */
sdio_read_blocks_fifo(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t blocks)952 int sdio_read_blocks_fifo(struct sdio_func *func, uint32_t reg, uint8_t *data,
953 			  uint32_t blocks)
954 {
955 	int ret;
956 
957 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
958 		LOG_WRN("Card does not support SDIO commands");
959 		return -ENOTSUP;
960 	}
961 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
962 	if (ret) {
963 		LOG_WRN("Could not get SD card mutex");
964 		return -EBUSY;
965 	}
966 	ret = sdio_io_rw_extended(func->card, SDIO_IO_READ, func->num, reg,
967 		false, data, blocks, func->block_size);
968 	k_mutex_unlock(&func->card->lock);
969 	return ret;
970 }
971 
972 /**
973  * @brief Write blocks to SDIO fifo
974  *
975  * Writes blocks from SDIO register, treating it as a fifo. Writes will
976  * all be done to same address.
977  * @param func: function to write to
978  * @param reg: register address of fifo
979  * @param data: data to write to fifo
980  * @param blocks: number of blocks to write to fifo
981  * @retval 0 write succeeded
982  * @retval -EBUSY: card is busy with another request
983  * @retval -ETIMEDOUT: card write timed out
984  * @retval -EIO: I/O error
985  */
sdio_write_blocks_fifo(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t blocks)986 int sdio_write_blocks_fifo(struct sdio_func *func, uint32_t reg, uint8_t *data,
987 			   uint32_t blocks)
988 {
989 	int ret;
990 
991 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
992 		LOG_WRN("Card does not support SDIO commands");
993 		return -ENOTSUP;
994 	}
995 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
996 	if (ret) {
997 		LOG_WRN("Could not get SD card mutex");
998 		return -EBUSY;
999 	}
1000 	ret = sdio_io_rw_extended(func->card, SDIO_IO_WRITE, func->num, reg,
1001 		false, data, blocks, func->block_size);
1002 	k_mutex_unlock(&func->card->lock);
1003 	return ret;
1004 }
1005 
1006 /**
1007  * @brief Copy bytes from an SDIO card
1008  *
1009  * Copies bytes from an SDIO card, starting from provided address.
1010  * @param func: function to read from
1011  * @param reg: register address to start copy at
1012  * @param data: buffer to copy data into
1013  * @param len: length of data to read
1014  * @retval 0 read succeeded
1015  * @retval -EBUSY: card is busy with another request
1016  * @retval -ETIMEDOUT: card read timed out
1017  * @retval -EIO: I/O error
1018  */
sdio_read_addr(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t len)1019 int sdio_read_addr(struct sdio_func *func, uint32_t reg, uint8_t *data,
1020 		   uint32_t len)
1021 {
1022 	int ret;
1023 
1024 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
1025 		LOG_WRN("Card does not support SDIO commands");
1026 		return -ENOTSUP;
1027 	}
1028 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
1029 	if (ret) {
1030 		LOG_WRN("Could not get SD card mutex");
1031 		return -EBUSY;
1032 	}
1033 	ret = sdio_io_rw_extended_helper(func, SDIO_IO_READ, reg, true,
1034 		data, len);
1035 	k_mutex_unlock(&func->card->lock);
1036 	return ret;
1037 }
1038 
1039 /**
1040  * @brief Copy bytes to an SDIO card
1041  *
1042  * Copies bytes to an SDIO card, starting from provided address.
1043  *
1044  * @param func: function to write to
1045  * @param reg: register address to start copy at
1046  * @param data: buffer to copy data from
1047  * @param len: length of data to write
1048  * @retval 0 write succeeded
1049  * @retval -EBUSY: card is busy with another request
1050  * @retval -ETIMEDOUT: card write timed out
1051  * @retval -EIO: I/O error
1052  */
sdio_write_addr(struct sdio_func * func,uint32_t reg,uint8_t * data,uint32_t len)1053 int sdio_write_addr(struct sdio_func *func, uint32_t reg, uint8_t *data,
1054 		    uint32_t len)
1055 {
1056 	int ret;
1057 
1058 	if ((func->card->type != CARD_SDIO) && (func->card->type != CARD_COMBO)) {
1059 		LOG_WRN("Card does not support SDIO commands");
1060 		return -ENOTSUP;
1061 	}
1062 	ret = k_mutex_lock(&func->card->lock, K_MSEC(CONFIG_SD_DATA_TIMEOUT));
1063 	if (ret) {
1064 		LOG_WRN("Could not get SD card mutex");
1065 		return -EBUSY;
1066 	}
1067 	ret = sdio_io_rw_extended_helper(func, SDIO_IO_WRITE, reg, true,
1068 		data, len);
1069 	k_mutex_unlock(&func->card->lock);
1070 	return ret;
1071 }
1072