1 /*
2  * Copyright 2022,2024 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT zephyr_sdhc_spi_slot
8 
9 
10 
11 #include <zephyr/drivers/sdhc.h>
12 #include <zephyr/drivers/gpio.h>
13 #include <zephyr/logging/log.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/drivers/spi.h>
16 #include <zephyr/sys/crc.h>
17 #include <zephyr/pm/device_runtime.h>
18 
19 LOG_MODULE_REGISTER(sdhc_spi, CONFIG_SDHC_LOG_LEVEL);
20 
21 #define MAX_CMD_READ 21
22 #define SPI_R1B_TIMEOUT_MS 3000
23 #define SD_SPI_SKIP_RETRIES 1000000
24 
25 #define _INST_REQUIRES_EXPLICIT_FF(inst) (SPI_MOSI_OVERRUN_DT(DT_INST_BUS(inst)) != 0xFF) ||
26 
27 /* The SD protocol requires sending ones while reading but the Zephyr
28  * SPI API defers the choice of default values to the drivers.
29  *
30  * For drivers that we know will send ones we can avoid allocating a
31  * 512 byte array of ones and remove the limit on the number of bytes
32  * that can be read in a single transaction.
33  */
34 #define ANY_INST_REQUIRES_EXPLICIT_FF DT_INST_FOREACH_STATUS_OKAY(_INST_REQUIRES_EXPLICIT_FF) 0
35 
36 #if ANY_INST_REQUIRES_EXPLICIT_FF
37 
38 static const uint8_t sdhc_ones[] = {
39 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
40 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
41 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
42 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
43 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
44 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
45 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
46 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
47 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
48 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
49 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
50 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
51 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
52 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
53 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
54 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
55 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
56 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
57 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
58 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
59 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
60 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
61 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
62 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
63 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
64 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
65 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
66 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
67 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
68 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
69 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
70 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
71 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
72 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
73 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
74 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
75 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
76 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
77 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
78 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
79 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
80 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
81 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
82 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
83 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
84 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
85 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
86 };
87 
88 BUILD_ASSERT(sizeof(sdhc_ones) == 512, "0xFF array for SDHC must be 512 bytes");
89 
90 #endif /* ANY_INST_REQUIRES_EXPLICIT_FF */
91 
92 struct sdhc_spi_config {
93 	const struct device *spi_dev;
94 	const struct gpio_dt_spec pwr_gpio;
95 	const uint32_t spi_max_freq;
96 	uint32_t power_delay_ms;
97 };
98 
99 struct sdhc_spi_data {
100 	enum sdhc_power power_mode;
101 	struct spi_config *spi_cfg;
102 	struct spi_config cfg_a;
103 	struct spi_config cfg_b;
104 	uint8_t scratch[MAX_CMD_READ];
105 };
106 
107 /* Receives a block of bytes */
sdhc_spi_rx(const struct device * spi_dev,struct spi_config * spi_cfg,uint8_t * buf,int len)108 static int sdhc_spi_rx(const struct device *spi_dev, struct spi_config *spi_cfg,
109 	uint8_t *buf, int len)
110 {
111 #if ANY_INST_REQUIRES_EXPLICIT_FF
112 	struct spi_buf tx_bufs[] = {
113 		{
114 			.buf = (uint8_t *)sdhc_ones,
115 			.len = len
116 		}
117 	};
118 
119 	const struct spi_buf_set tx = {
120 		.buffers = tx_bufs,
121 		.count = 1,
122 	};
123 	const struct spi_buf_set *tx_ptr = &tx;
124 #else
125 	const struct spi_buf_set *tx_ptr = NULL;
126 #endif /* ANY_INST_REQUIRES_EXPLICIT_FF */
127 
128 	struct spi_buf rx_bufs[] = {
129 		{
130 			.buf = buf,
131 			.len = len
132 		}
133 	};
134 
135 	const struct spi_buf_set rx = {
136 		.buffers = rx_bufs,
137 		.count = 1,
138 	};
139 
140 	return spi_transceive(spi_dev, spi_cfg, tx_ptr, &rx);
141 }
142 
sdhc_spi_init_card(const struct device * dev)143 static int sdhc_spi_init_card(const struct device *dev)
144 {
145 	/* SD spec requires at least 74 clocks be send to SD to start it.
146 	 * for SPI protocol, this will be performed by sending 10 0xff values
147 	 * to the card (this should result in 80 SCK cycles)
148 	 */
149 	const struct sdhc_spi_config *config = dev->config;
150 	struct sdhc_spi_data *data = dev->data;
151 	struct spi_config *spi_cfg = data->spi_cfg;
152 	int ret, ret2;
153 
154 	if (spi_cfg->frequency == 0) {
155 		/* Use default 400KHZ frequency */
156 		spi_cfg->frequency = SDMMC_CLOCK_400KHZ;
157 	}
158 
159 	/* Request SPI bus to be active */
160 	if (pm_device_runtime_get(config->spi_dev) < 0) {
161 		return -EIO;
162 	}
163 
164 	/* the initial 74 clocks must be sent while CS is high */
165 	spi_cfg->operation |= SPI_CS_ACTIVE_HIGH;
166 	ret = sdhc_spi_rx(config->spi_dev, spi_cfg, data->scratch, 10);
167 
168 	/* Release lock on SPI bus */
169 	ret2 = spi_release(config->spi_dev, spi_cfg);
170 	spi_cfg->operation &= ~SPI_CS_ACTIVE_HIGH;
171 
172 	/* Release request for SPI bus to be active */
173 	(void)pm_device_runtime_put(config->spi_dev);
174 
175 	return ret ? ret : ret2;
176 }
177 
178 /* Checks if SPI SD card is sending busy signal */
sdhc_spi_card_busy(const struct device * dev)179 static int sdhc_spi_card_busy(const struct device *dev)
180 {
181 	const struct sdhc_spi_config *config = dev->config;
182 	struct sdhc_spi_data *data = dev->data;
183 	int ret;
184 	uint8_t response;
185 
186 
187 	ret = sdhc_spi_rx(config->spi_dev, data->spi_cfg, &response, 1);
188 	if (ret) {
189 		return -EIO;
190 	}
191 
192 	if (response == 0xFF) {
193 		return 0;
194 	} else {
195 		return 1;
196 	}
197 }
198 
199 /* Waits for SPI SD card to stop sending busy signal */
sdhc_spi_wait_unbusy(const struct device * dev,int timeout_ms,int interval_ticks)200 static int sdhc_spi_wait_unbusy(const struct device *dev,
201 	int timeout_ms,
202 	int interval_ticks)
203 {
204 	const struct sdhc_spi_config *config = dev->config;
205 	struct sdhc_spi_data *data = dev->data;
206 	int ret;
207 	uint8_t response;
208 
209 	while (timeout_ms > 0) {
210 		ret = sdhc_spi_rx(config->spi_dev, data->spi_cfg, &response, 1);
211 		if (ret) {
212 			return ret;
213 		}
214 		if (response == 0xFF) {
215 			return 0;
216 		}
217 		k_msleep(k_ticks_to_ms_floor32(interval_ticks));
218 		timeout_ms -= k_ticks_to_ms_floor32(interval_ticks);
219 	}
220 	return -ETIMEDOUT;
221 }
222 
223 
224 /* Read SD command from SPI response */
sdhc_spi_response_get(const struct device * dev,struct sdhc_command * cmd,int rx_len)225 static int sdhc_spi_response_get(const struct device *dev, struct sdhc_command *cmd,
226 	int rx_len)
227 {
228 	const struct sdhc_spi_config *config = dev->config;
229 	struct sdhc_spi_data *dev_data = dev->data;
230 	uint8_t *response = dev_data->scratch;
231 	uint8_t *end = response + rx_len;
232 	int ret, timeout = cmd->timeout_ms;
233 	uint8_t value, i;
234 
235 	/* First step is finding the first valid byte of the response.
236 	 * All SPI responses start with R1, which will have MSB of zero.
237 	 * we know we can ignore the first 7 bytes, which hold the command and
238 	 * initial "card ready" byte.
239 	 */
240 	response += 8;
241 	while (response < end && ((*response & SD_SPI_START) == SD_SPI_START)) {
242 		response++;
243 	}
244 	if (response == end) {
245 		/* Some cards are slow, and need more time to respond. Continue
246 		 * with single byte reads until the card responds.
247 		 */
248 		response = dev_data->scratch;
249 		end = response + 1;
250 		while (timeout > 0) {
251 			ret = sdhc_spi_rx(config->spi_dev, dev_data->spi_cfg,
252 				response, 1);
253 			if (ret < 0) {
254 				return ret;
255 			}
256 			if (*response != 0xff) {
257 				break;
258 			}
259 			/* Delay for a bit, and poll the card again */
260 			k_msleep(10);
261 			timeout -= 10;
262 		}
263 		if (*response == 0xff) {
264 			return -ETIMEDOUT;
265 		}
266 	}
267 	/* Record R1 response */
268 	cmd->response[0] = *response++;
269 	/* Check response for error */
270 	if (cmd->response[0] != 0) {
271 		if (cmd->response[0] &	(SD_SPI_R1PARAMETER_ERR | SD_SPI_R1ADDRESS_ERR)) {
272 			return -EFAULT; /* Bad address */
273 		} else if (cmd->response[0] & (SD_SPI_R1ILLEGAL_CMD_ERR)) {
274 			return -EINVAL; /* Invalid command */
275 		} else if (cmd->response[0] & (SD_SPI_R1CMD_CRC_ERR)) {
276 			return -EILSEQ; /* Illegal byte sequence */
277 		} else if (cmd->response[0] & (SD_SPI_R1ERASE_SEQ_ERR | SD_SPI_R1ERASE_RESET)) {
278 			return -EIO;
279 		}
280 		/* else IDLE_STATE bit is set, which is not an error, card is just resetting */
281 	}
282 	switch ((cmd->response_type & SDHC_SPI_RESPONSE_TYPE_MASK)) {
283 	case SD_SPI_RSP_TYPE_R1:
284 		/* R1 response - one byte*/
285 		break;
286 	case SD_SPI_RSP_TYPE_R1b:
287 		/* R1b response - one byte plus busy signal */
288 		/* Read remaining bytes to see if card is still busy.
289 		 * card will be ready when it stops driving data out
290 		 * low.
291 		 */
292 		while (response < end && (*response == 0x0)) {
293 			response++;
294 		}
295 		if (response == end) {
296 			value = cmd->timeout_ms;
297 			response--;
298 			/* Periodically check busy line */
299 			ret = sdhc_spi_wait_unbusy(dev,
300 				SPI_R1B_TIMEOUT_MS, 1000);
301 		}
302 		break;
303 	case SD_SPI_RSP_TYPE_R2:
304 	case SD_SPI_RSP_TYPE_R5:
305 		/* R2/R5 response - R1 response + 1 byte*/
306 		if (response == end) {
307 			response = dev_data->scratch;
308 			end = response + 1;
309 			/* Read the next byte */
310 			ret = sdhc_spi_rx(config->spi_dev,
311 				dev_data->spi_cfg,
312 				response, 1);
313 			if (ret) {
314 				return ret;
315 			}
316 		}
317 		cmd->response[0] = (*response) << 8;
318 		break;
319 	case SD_SPI_RSP_TYPE_R3:
320 	case SD_SPI_RSP_TYPE_R4:
321 	case SD_SPI_RSP_TYPE_R7:
322 		/* R3/R4/R7 response - R1 response + 4 bytes */
323 		cmd->response[1] = 0;
324 		for (i = 0; i < 4; i++) {
325 			cmd->response[1] <<= 8;
326 			/* Read bytes of response */
327 			if (response == end) {
328 				response = dev_data->scratch;
329 				end = response + 1;
330 				/* Read the next byte */
331 				ret = sdhc_spi_rx(config->spi_dev,
332 					dev_data->spi_cfg,
333 					response, 1);
334 				if (ret) {
335 					return ret;
336 				}
337 			}
338 			cmd->response[1] |= *response++;
339 		}
340 		break;
341 	default:
342 		/* Other RSP types not supported */
343 		return -ENOTSUP;
344 	}
345 	return 0;
346 }
347 
348 /* Send SD command using SPI */
sdhc_spi_send_cmd(const struct device * dev,struct sdhc_command * cmd,bool data_present)349 static int sdhc_spi_send_cmd(const struct device *dev, struct sdhc_command *cmd,
350 	bool data_present)
351 {
352 	const struct sdhc_spi_config *config = dev->config;
353 	struct sdhc_spi_data *dev_data = dev->data;
354 	int err;
355 	uint8_t *cmd_buf;
356 	/* To reduce overhead, we will send entire command in one SPI
357 	 * transaction. The packet takes the following format:
358 	 * - all ones byte to ensure card is ready
359 	 * - opcode byte (which includes start and transmission bits)
360 	 * - 4 bytes for argument
361 	 * - crc7 byte (with end bit)
362 	 * The SD card can take up to 8 bytes worth of SCLK cycles to respond.
363 	 * therefore, we provide 8 bytes of all ones, to read data from the card.
364 	 * the maximum spi response length is 5 bytes, so we provide an
365 	 * additional 5 bytes of data, leaving us with 13 bytes of 0xff.
366 	 * Finally, we send a padding byte of all 0xff, to ensure that
367 	 * the card recives at least one 0xff byte before next command.
368 	 */
369 
370 	/* Note: we can discard CMD data as we send it,
371 	 * so resuse the TX buf as RX
372 	 */
373 	struct spi_buf bufs[] = {
374 		{
375 			.buf = dev_data->scratch,
376 			.len = sizeof(dev_data->scratch),
377 		},
378 	};
379 
380 	const struct spi_buf_set buf_set = {
381 		.buffers = bufs,
382 		.count = 1,
383 	};
384 
385 
386 	if (data_present) {
387 		/* We cannot send extra SCLK cycles with our command,
388 		 * since we'll miss the data the card responds with. We
389 		 * send one 0xff byte, six command bytes, two additional 0xff
390 		 * bytes, since the min value of NCR (see SD SPI timing
391 		 * diagrams) is one, and we know there will be an R1 response.
392 		 */
393 		bufs[0].len = SD_SPI_CMD_SIZE + 3;
394 	}
395 	memset(dev_data->scratch, 0xFF, sizeof(dev_data->scratch));
396 	cmd_buf = dev_data->scratch + 1;
397 
398 	/* Command packet holds the following bits:
399 	 * [47]: start bit, 0b0
400 	 * [46]: transmission bit, 0b1
401 	 * [45-40]: command index
402 	 * [39-8]: argument
403 	 * [7-1]: CRC
404 	 * [0]: end bit, 0b1
405 	 * Note that packets are sent MSB first.
406 	 */
407 	/* Add start bit, tx bit, and cmd opcode */
408 	cmd_buf[0] = (cmd->opcode & SD_SPI_CMD);
409 	cmd_buf[0] = ((cmd_buf[0] | SD_SPI_TX) & ~SD_SPI_START);
410 	/* Add argument */
411 	sys_put_be32(cmd->arg, &cmd_buf[1]);
412 	/* Add CRC, and set LSB as the end bit */
413 	cmd_buf[SD_SPI_CMD_BODY_SIZE] = crc7_be(0, cmd_buf, SD_SPI_CMD_BODY_SIZE) | 0x1;
414 	LOG_DBG("cmd%d arg 0x%x", cmd->opcode, cmd->arg);
415 	/* Set data, will lock SPI bus */
416 	err = spi_transceive(config->spi_dev, dev_data->spi_cfg, &buf_set, &buf_set);
417 	if (err != 0) {
418 		return err;
419 	}
420 	/* Read command response */
421 	return sdhc_spi_response_get(dev, cmd, bufs[0].len);
422 }
423 
424 /* Skips bytes in SDHC data stream. */
sdhc_skip(const struct device * dev,uint8_t skip_val)425 static int sdhc_skip(const struct device *dev, uint8_t skip_val)
426 {
427 	const struct sdhc_spi_config *config = dev->config;
428 	struct sdhc_spi_data *data = dev->data;
429 	uint8_t buf;
430 	int ret;
431 	uint32_t retries = SD_SPI_SKIP_RETRIES;
432 
433 	do {
434 		ret = sdhc_spi_rx(config->spi_dev, data->spi_cfg,
435 			&buf, sizeof(buf));
436 		if (ret) {
437 			return ret;
438 		}
439 	} while (buf == skip_val && retries--);
440 	if (retries == 0) {
441 		return -ETIMEDOUT;
442 	}
443 	/* Return first non-skipped value */
444 	return buf;
445 }
446 
447 /* Handles reading data from SD SPI device */
sdhc_spi_read_data(const struct device * dev,struct sdhc_data * data)448 static int sdhc_spi_read_data(const struct device *dev, struct sdhc_data *data)
449 {
450 	const struct sdhc_spi_config *config = dev->config;
451 	struct sdhc_spi_data *dev_data = dev->data;
452 	uint8_t *read_location = data->data;
453 	uint32_t remaining = data->blocks;
454 	int ret;
455 	uint8_t crc[SD_SPI_CRC16_SIZE + 1];
456 
457 #if ANY_INST_REQUIRES_EXPLICIT_FF
458 	/* If the driver requires explicit 0xFF bytes on receive, we
459 	 * are limited to receiving the size of the sdhc_ones buffer
460 	 */
461 	if (data->block_size > sizeof(sdhc_ones)) {
462 		return -ENOTSUP;
463 	}
464 
465 	const struct spi_buf tx_bufs[] = {
466 		{
467 			.buf = (uint8_t *)sdhc_ones,
468 			.len = data->block_size,
469 		},
470 	};
471 
472 	const struct spi_buf_set tx = {
473 		.buffers = tx_bufs,
474 		.count = 1,
475 	};
476 	const struct spi_buf_set *tx_ptr = &tx;
477 #else
478 	const struct spi_buf_set *tx_ptr = NULL;
479 #endif /* ANY_INST_REQUIRES_EXPLICIT_FF */
480 
481 	struct spi_buf rx_bufs[] = {
482 		{
483 			.buf = read_location,
484 			.len = data->block_size,
485 		}
486 	};
487 
488 	const struct spi_buf_set rx = {
489 		.buffers = rx_bufs,
490 		.count = 1,
491 	};
492 
493 
494 	/* Read bytes until data stream starts. SD will send 0xff until
495 	 * data is available
496 	 */
497 	ret = sdhc_skip(dev, 0xff);
498 	if (ret < 0) {
499 		return ret;
500 	}
501 	/* Check token */
502 	if (ret != SD_SPI_TOKEN_SINGLE)	{
503 		return -EIO;
504 	}
505 
506 	/* Read blocks until we are out of data */
507 	while (remaining--) {
508 		ret = spi_transceive(config->spi_dev,
509 			dev_data->spi_cfg, tx_ptr, &rx);
510 		if (ret) {
511 			LOG_ERR("Data write failed");
512 			return ret;
513 		}
514 		/* Read CRC16 plus one end byte */
515 		ret = sdhc_spi_rx(config->spi_dev, dev_data->spi_cfg,
516 			crc, sizeof(crc));
517 		if (crc16_itu_t(0, read_location, data->block_size) !=
518 			sys_get_be16(crc)) {
519 			/* Bad CRC */
520 			LOG_ERR("Bad data CRC");
521 			return -EILSEQ;
522 		}
523 		/* Advance read location */
524 		read_location += data->block_size;
525 		rx_bufs[0].buf = read_location;
526 		if (remaining) {
527 			/* Check next data token */
528 			ret = sdhc_skip(dev, 0xff);
529 			if (ret != SD_SPI_TOKEN_SINGLE) {
530 				LOG_ERR("Bad token");
531 				return -EIO;
532 			}
533 		}
534 	}
535 	return ret;
536 }
537 
538 /* Handles writing data to SD SPI device */
sdhc_spi_write_data(const struct device * dev,struct sdhc_data * data)539 static int sdhc_spi_write_data(const struct device *dev, struct sdhc_data *data)
540 {
541 	const struct sdhc_spi_config *config = dev->config;
542 	struct sdhc_spi_data *dev_data = dev->data;
543 	int ret;
544 	uint8_t token, resp;
545 	uint8_t *write_location = data->data, crc[SD_SPI_CRC16_SIZE];
546 	uint32_t remaining = data->blocks;
547 
548 	struct spi_buf tx_bufs[] = {
549 		{
550 			.buf = &token,
551 			.len = sizeof(uint8_t),
552 		},
553 		{
554 			.buf = write_location,
555 			.len = data->block_size,
556 		},
557 		{
558 			.buf = crc,
559 			.len = sizeof(crc),
560 		},
561 	};
562 
563 	struct spi_buf_set tx = {
564 		.buffers = tx_bufs,
565 		.count = 3,
566 	};
567 
568 	/* Set the token- single block reads use different token
569 	 * than multibock
570 	 */
571 	if (remaining > 1) {
572 		token = SD_SPI_TOKEN_MULTI_WRITE;
573 	} else {
574 		token = SD_SPI_TOKEN_SINGLE;
575 	}
576 
577 	while (remaining--) {
578 		/* Build the CRC for this data block */
579 		sys_put_be16(crc16_itu_t(0, write_location, data->block_size),
580 			crc);
581 		ret = spi_write(config->spi_dev, dev_data->spi_cfg, &tx);
582 		if (ret) {
583 			return ret;
584 		}
585 		/* Read back the data response token from the card */
586 		ret = sdhc_spi_rx(config->spi_dev, dev_data->spi_cfg,
587 			&resp, sizeof(resp));
588 		if (ret) {
589 			return ret;
590 		}
591 		/* Check response token */
592 		if ((resp & 0xF) != SD_SPI_RESPONSE_ACCEPTED) {
593 			if ((resp & 0xF) == SD_SPI_RESPONSE_CRC_ERR) {
594 				return -EILSEQ;
595 			} else if ((resp & 0xF) == SD_SPI_RESPONSE_WRITE_ERR) {
596 				return -EIO;
597 			}
598 			LOG_DBG("Unknown write response token 0x%x", resp);
599 			return -EIO;
600 		}
601 		/* Advance write location */
602 		write_location += data->block_size;
603 		tx_bufs[1].buf = write_location;
604 		/* Wait for card to stop being busy */
605 		ret = sdhc_spi_wait_unbusy(dev, data->timeout_ms, 0);
606 		if (ret) {
607 			return ret;
608 		}
609 	}
610 	if (data->blocks > 1) {
611 		/* Write stop transfer token to card */
612 		token = SD_SPI_TOKEN_STOP_TRAN;
613 		tx.count = 1;
614 		ret = spi_write(config->spi_dev, dev_data->spi_cfg, &tx);
615 		if (ret) {
616 			return ret;
617 		}
618 		/* Wait for card to stop being busy */
619 		ret = sdhc_spi_wait_unbusy(dev, data->timeout_ms, 0);
620 		if (ret) {
621 			return ret;
622 		}
623 	}
624 	return 0;
625 }
626 
sdhc_spi_request(const struct device * dev,struct sdhc_command * cmd,struct sdhc_data * data)627 static int sdhc_spi_request(const struct device *dev,
628 	struct sdhc_command *cmd,
629 	struct sdhc_data *data)
630 {
631 	const struct sdhc_spi_config *config = dev->config;
632 	struct sdhc_spi_data *dev_data = dev->data;
633 	int ret, ret2, stop_ret, retries = cmd->retries;
634 	const struct sdhc_command stop_cmd = {
635 		.opcode = SD_STOP_TRANSMISSION,
636 		.arg = 0,
637 		.response_type = SD_SPI_RSP_TYPE_R1b,
638 		.timeout_ms = 1000,
639 		.retries = 1,
640 	};
641 
642 	/* Request SPI bus to be active */
643 	if (pm_device_runtime_get(config->spi_dev) < 0) {
644 		return -EIO;
645 	}
646 
647 	if (data == NULL) {
648 		do {
649 			ret = sdhc_spi_send_cmd(dev, cmd, false);
650 		} while ((ret != 0) && (retries-- > 0));
651 	} else {
652 		do {
653 			retries--;
654 			ret = sdhc_spi_send_cmd(dev, cmd, true);
655 			if (ret) {
656 				continue;
657 			}
658 			if ((cmd->opcode == SD_WRITE_SINGLE_BLOCK) ||
659 				(cmd->opcode == SD_WRITE_MULTIPLE_BLOCK)) {
660 				ret = sdhc_spi_write_data(dev, data);
661 			} else {
662 				ret = sdhc_spi_read_data(dev, data);
663 			}
664 			if (ret || (cmd->opcode == SD_READ_MULTIPLE_BLOCK)) {
665 				int stop_retries = cmd->retries;
666 
667 				/* CMD12 is required after multiple read, or
668 				 * to retry failed transfer
669 				 */
670 				stop_ret = sdhc_spi_send_cmd(dev,
671 					(struct sdhc_command *)&stop_cmd,
672 					false);
673 				while ((stop_ret != 0) && (stop_retries > 0)) {
674 					/* Retry stop command */
675 					ret = stop_ret = sdhc_spi_send_cmd(dev,
676 						(struct sdhc_command *)&stop_cmd,
677 						false);
678 					stop_retries--;
679 				}
680 			}
681 		} while ((ret != 0) && (retries > 0));
682 	}
683 
684 	/* Release SPI bus */
685 	ret2 = spi_release(config->spi_dev, dev_data->spi_cfg);
686 
687 	/* Release request for SPI bus to be active */
688 	(void)pm_device_runtime_put(config->spi_dev);
689 
690 	return ret ? ret : ret2;
691 }
692 
sdhc_spi_set_io(const struct device * dev,struct sdhc_io * ios)693 static int sdhc_spi_set_io(const struct device *dev, struct sdhc_io *ios)
694 {
695 	const struct sdhc_spi_config *cfg = dev->config;
696 	struct sdhc_spi_data *data = dev->data;
697 
698 	if (ios->clock != data->spi_cfg->frequency) {
699 		if (ios->clock > cfg->spi_max_freq) {
700 			return -ENOTSUP;
701 		}
702 		/* Because pointer comparision is used, we have to
703 		 * swap to a new configuration structure to reconfigure SPI.
704 		 */
705 		if (ios->clock != 0) {
706 			if (data->spi_cfg == &data->cfg_a) {
707 				data->cfg_a.frequency = ios->clock;
708 				memcpy(&data->cfg_b, &data->cfg_a,
709 					sizeof(struct spi_config));
710 				data->spi_cfg = &data->cfg_b;
711 			} else {
712 				data->cfg_b.frequency = ios->clock;
713 				memcpy(&data->cfg_a, &data->cfg_b,
714 					sizeof(struct spi_config));
715 				data->spi_cfg = &data->cfg_a;
716 			}
717 		}
718 	}
719 	if (ios->bus_mode != SDHC_BUSMODE_PUSHPULL) {
720 		/* SPI mode supports push pull */
721 		return -ENOTSUP;
722 	}
723 	if (data->power_mode != ios->power_mode) {
724 		if (ios->power_mode == SDHC_POWER_ON) {
725 			if (cfg->pwr_gpio.port) {
726 				if (gpio_pin_set_dt(&cfg->pwr_gpio, 1)) {
727 					return -EIO;
728 				}
729 
730 				/* Wait until VDD is stable. Per the spec:
731 				 *   Maximum VDD rise time of 35ms.
732 				 *   Minimum 1ms VDD stable time.
733 				 */
734 				k_sleep(K_MSEC(36));
735 
736 				LOG_INF("Powered up");
737 			}
738 
739 			/* Send 74 clock cycles to start card */
740 			if (sdhc_spi_init_card(dev) != 0) {
741 				LOG_ERR("Card SCLK init sequence failed");
742 				return -EIO;
743 			}
744 		} else {
745 			if (cfg->pwr_gpio.port) {
746 				if (gpio_pin_set_dt(&cfg->pwr_gpio, 0)) {
747 					return -EIO;
748 				}
749 				LOG_INF("Powered down");
750 			}
751 		}
752 		data->power_mode = ios->power_mode;
753 	}
754 	if (ios->bus_width != SDHC_BUS_WIDTH1BIT) {
755 		/* SPI mode supports 1 bit bus */
756 		return -ENOTSUP;
757 	}
758 	if (ios->signal_voltage != SD_VOL_3_3_V) {
759 		/* SPI mode does not support UHS voltages */
760 		return -ENOTSUP;
761 	}
762 	return 0;
763 }
764 
sdhc_spi_get_card_present(const struct device * dev)765 static int sdhc_spi_get_card_present(const struct device *dev)
766 {
767 	/* SPI has no card presence method, assume card is in slot */
768 	return 1;
769 }
770 
sdhc_spi_get_host_props(const struct device * dev,struct sdhc_host_props * props)771 static int sdhc_spi_get_host_props(const struct device *dev,
772 	struct sdhc_host_props *props)
773 {
774 	const struct sdhc_spi_config *cfg = dev->config;
775 
776 	memset(props, 0, sizeof(struct sdhc_host_props));
777 
778 	props->f_min = SDMMC_CLOCK_400KHZ;
779 	props->f_max = cfg->spi_max_freq;
780 	props->power_delay = cfg->power_delay_ms;
781 	props->host_caps.vol_330_support = true;
782 	props->is_spi = true;
783 	return 0;
784 }
785 
sdhc_spi_reset(const struct device * dev)786 static int sdhc_spi_reset(const struct device *dev)
787 {
788 	struct sdhc_spi_data *data = dev->data;
789 
790 	/* Reset host I/O */
791 	data->spi_cfg->frequency = SDMMC_CLOCK_400KHZ;
792 	return 0;
793 }
794 
sdhc_spi_init(const struct device * dev)795 static int sdhc_spi_init(const struct device *dev)
796 {
797 	const struct sdhc_spi_config *cfg = dev->config;
798 	struct sdhc_spi_data *data = dev->data;
799 	int ret = 0;
800 
801 	if (!device_is_ready(cfg->spi_dev)) {
802 		return -ENODEV;
803 	}
804 	if (cfg->pwr_gpio.port) {
805 		if (!gpio_is_ready_dt(&cfg->pwr_gpio)) {
806 			return -ENODEV;
807 		}
808 		ret = gpio_pin_configure_dt(&cfg->pwr_gpio, GPIO_OUTPUT_INACTIVE);
809 		if (ret != 0) {
810 			LOG_ERR("Could not configure power gpio (%d)", ret);
811 			return ret;
812 		}
813 	}
814 	data->power_mode = SDHC_POWER_OFF;
815 	data->spi_cfg = &data->cfg_a;
816 	data->spi_cfg->frequency = 0;
817 	return ret;
818 }
819 
820 static DEVICE_API(sdhc, sdhc_spi_api) = {
821 	.request = sdhc_spi_request,
822 	.set_io = sdhc_spi_set_io,
823 	.get_host_props = sdhc_spi_get_host_props,
824 	.get_card_present = sdhc_spi_get_card_present,
825 	.reset = sdhc_spi_reset,
826 	.card_busy = sdhc_spi_card_busy,
827 };
828 
829 
830 #define SDHC_SPI_INIT(n)							\
831 	const struct sdhc_spi_config sdhc_spi_config_##n = {			\
832 		.spi_dev = DEVICE_DT_GET(DT_INST_PARENT(n)),			\
833 		.pwr_gpio = GPIO_DT_SPEC_INST_GET_OR(n, pwr_gpios, {0}),	\
834 		.spi_max_freq = DT_INST_PROP(n, spi_max_frequency),		\
835 		.power_delay_ms = DT_INST_PROP(n, power_delay_ms),		\
836 	};									\
837 										\
838 	struct sdhc_spi_data sdhc_spi_data_##n = {				\
839 		.cfg_a = SPI_CONFIG_DT_INST(n,					\
840 				(SPI_LOCK_ON | SPI_HOLD_ON_CS | SPI_WORD_SET(8) \
841 				 | (DT_INST_PROP(n, spi_clock_mode_cpol) ? SPI_MODE_CPOL : 0) \
842 				 | (DT_INST_PROP(n, spi_clock_mode_cpha) ? SPI_MODE_CPHA : 0) \
843 				),\
844 				0),						\
845 	};									\
846 										\
847 	DEVICE_DT_INST_DEFINE(n,						\
848 			&sdhc_spi_init,						\
849 			NULL,							\
850 			&sdhc_spi_data_##n,					\
851 			&sdhc_spi_config_##n,					\
852 			POST_KERNEL,						\
853 			CONFIG_SDHC_INIT_PRIORITY,				\
854 			&sdhc_spi_api);
855 
856 DT_INST_FOREACH_STATUS_OKAY(SDHC_SPI_INIT)
857