altos: Fix command-line FAT filename parsing
[fw/altos] / src / drivers / ao_sdcard.c
1 /*
2  * Copyright © 2013 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19 #include "ao_sdcard.h"
20
21 #define ao_sdcard_get_slow()            ao_spi_get(AO_SDCARD_SPI_BUS, AO_SPI_SPEED_250kHz)
22 #define ao_sdcard_get()                 ao_spi_get(AO_SDCARD_SPI_BUS, AO_SPI_SPEED_FAST)
23 #define ao_sdcard_put()                 ao_spi_put(AO_SDCARD_SPI_BUS)
24 #define ao_sdcard_send_fixed(d,l)       ao_spi_send_fixed((d), (l), AO_SDCARD_SPI_BUS)
25 #define ao_sdcard_send(d,l)             ao_spi_send((d), (l), AO_SDCARD_SPI_BUS)
26 #define ao_sdcard_recv(d,l)             ao_spi_recv((d), (l), AO_SDCARD_SPI_BUS)
27 #define ao_sdcard_select()              ao_gpio_set(AO_SDCARD_SPI_CS_PORT,AO_SDCARD_SPI_CS_PIN,AO_SDCARD_SPI_CS,0)
28 #define ao_sdcard_deselect()            ao_gpio_set(AO_SDCARD_SPI_CS_PORT,AO_SDCARD_SPI_CS_PIN,AO_SDCARD_SPI_CS,1)
29
30 /* Include SD card commands */
31 #define SDCARD_DEBUG    0
32
33 /* Spew SD tracing */
34 #define SDCARD_TRACE    0
35
36 static uint8_t  initialized;
37 static uint8_t  present;
38 static uint8_t  mutex;
39 static enum ao_sdtype sdtype;
40
41 #define ao_sdcard_lock()        ao_mutex_get(&mutex)
42 #define ao_sdcard_unlock()      ao_mutex_put(&mutex)
43
44 #if SDCARD_TRACE
45 #define DBG(...) printf(__VA_ARGS__)
46 #else
47 #define DBG(...)
48 #endif
49
50 /*
51  * Send an SD command and await the status reply
52  */
53
54 static uint8_t
55 ao_sdcard_send_cmd(uint8_t cmd, uint32_t arg)
56 {
57         uint8_t data[6];
58         uint8_t reply;
59         int i;
60
61         DBG ("\tsend_cmd %d arg %08x\n", cmd, arg);
62         if (cmd != SDCARD_GO_IDLE_STATE) {
63                 for (i = 0; i < SDCARD_CMD_TIMEOUT; i++) {
64                         ao_sdcard_recv(&reply, 1);
65                         if (reply == 0xff)
66                                 break;
67                 }
68                 if (i == SDCARD_CMD_TIMEOUT)
69                         return SDCARD_STATUS_TIMEOUT;
70         }
71         
72         data[0] = cmd & 0x3f | 0x40;
73         data[1] = arg >> 24;
74         data[2] = arg >> 16;
75         data[3] = arg >> 8;
76         data[4] = arg;
77         if (cmd == SDCARD_GO_IDLE_STATE)
78                 data[5] = 0x95; /* Valid for 0 arg */
79         else if (cmd == SDCARD_SEND_IF_COND)
80                 data[5] = 0x87; /* Valid for 0x1aa arg */
81         else
82                 data[5] = 0xff; /* no CRC */
83         ao_sdcard_send(data, 6);
84
85         /* The first reply byte will be the status,
86          * which must have the high bit clear
87          */
88         for (i = 0; i < SDCARD_CMD_TIMEOUT; i++) {
89                 ao_sdcard_recv(&reply, 1);
90                 DBG ("\t\tgot byte %02x\n", reply);
91                 if ((reply & 0x80) == 0)
92                         return reply;
93         }
94         return SDCARD_STATUS_TIMEOUT;
95 }
96
97 /*
98  * Retrieve any reply, discarding the trailing CRC byte
99  */
100 static void
101 ao_sdcard_recv_reply(uint8_t *reply, int len)
102 {
103         uint8_t discard;
104
105         if (len)
106                 ao_sdcard_recv(reply, len);
107         /* trailing byte */
108         ao_sdcard_recv(&discard, 1);
109 }
110
111 /*
112  * Wait while the card is busy. The
113  * card will return a stream of 0xff
114  * until it isn't busy anymore
115  */
116 static void
117 ao_sdcard_wait_busy(void)
118 {
119         uint8_t v;
120
121         do {
122                 ao_sdcard_recv(&v, 1);
123         } while (v != 0xff);
124         ao_sdcard_send_fixed(0xff, 1);
125 }
126
127 static uint8_t
128 ao_sdcard_go_idle_state(void)
129 {
130         uint8_t ret;
131
132         DBG ("go_idle_state\n");
133         ao_sdcard_select();
134         ret = ao_sdcard_send_cmd(SDCARD_GO_IDLE_STATE, 0);
135         ao_sdcard_recv_reply(NULL, 0);
136         ao_sdcard_deselect();
137         DBG ("\tgo_idle_state status %02x\n", ret);
138         return ret;
139 }
140
141 static uint8_t
142 ao_sdcard_send_op_cond(void)
143 {
144         uint8_t ret;
145
146         DBG ("send_op_cond\n");
147         ao_sdcard_select();
148         ret = ao_sdcard_send_cmd(SDCARD_SEND_OP_COND, 0);
149         ao_sdcard_recv_reply(NULL, 0);
150         ao_sdcard_deselect();
151         DBG ("\tsend_op_cond %02x\n", ret);
152         return ret;
153 }
154
155 static uint8_t
156 ao_sdcard_send_if_cond(uint32_t arg, uint8_t send_if_cond_response[4])
157 {
158         uint8_t ret;
159
160         DBG ("send_if_cond\n");
161         ao_sdcard_select();
162         ret = ao_sdcard_send_cmd(SDCARD_SEND_IF_COND, arg);
163         if (ret != SDCARD_STATUS_IDLE_STATE) {
164                 DBG ("\tsend_if_cond failed %02x\n", ret);
165                 return ret;
166         }
167         ao_sdcard_recv_reply(send_if_cond_response, 4);
168         DBG ("send_if_cond status %02x response %02x %02x %02x %02x\n",
169                 ret,
170                 send_if_cond_response[0],
171                 send_if_cond_response[1],
172                 send_if_cond_response[2],
173                 send_if_cond_response[3]);
174         ao_sdcard_deselect();
175         return ret;
176 }
177
178 static uint8_t
179 ao_sdcard_send_status(void)
180 {
181         uint8_t ret;
182
183         DBG ("send_status\n");
184         ao_sdcard_select();
185         ret = ao_sdcard_send_cmd(SDCARD_SEND_STATUS, 0);
186         ao_sdcard_recv_reply(NULL, 0);
187         if (ret != SDCARD_STATUS_READY_STATE)
188                 DBG ("\tsend_if_cond failed %02x\n", ret);
189         return ret;
190 }
191
192 static uint8_t
193 ao_sdcard_set_blocklen(uint32_t blocklen)
194 {
195         uint8_t ret;
196
197         DBG ("set_blocklen %d\n", blocklen);
198         ao_sdcard_select();
199         ret = ao_sdcard_send_cmd(SDCARD_SET_BLOCKLEN, blocklen);
200         ao_sdcard_recv_reply(NULL, 0);
201         if (ret != SDCARD_STATUS_READY_STATE)
202                 DBG ("\tsend_if_cond failed %02x\n", ret);
203         return ret;
204 }
205
206 static uint8_t
207 ao_sdcard_app_cmd(void)
208 {
209         uint8_t ret;
210
211         DBG ("app_cmd\n");
212         ao_sdcard_select();
213         ret = ao_sdcard_send_cmd(SDCARD_APP_CMD, 0);
214         ao_sdcard_recv_reply(NULL, 0);
215         ao_sdcard_deselect();
216         DBG ("\tapp_cmd status %02x\n");
217         return ret;
218 }
219
220 static uint8_t
221 ao_sdcard_app_send_op_cond(uint32_t arg)
222 {
223         uint8_t ret;
224
225         ret = ao_sdcard_app_cmd();
226         if (ret != SDCARD_STATUS_IDLE_STATE)
227                 return ret;
228         DBG("send_op_comd\n");
229         ao_sdcard_select();
230         ret = ao_sdcard_send_cmd(SDCARD_APP_SEND_OP_COMD, arg);
231         ao_sdcard_recv_reply(NULL, 0);
232         ao_sdcard_deselect();
233         DBG ("\tapp_send_op_cond status %02x\n", ret);
234         return ret;
235 }
236
237 static uint8_t
238 ao_sdcard_read_ocr(uint8_t read_ocr_response[4])
239 {
240         uint8_t ret;
241
242         DBG ("read_ocr\n");
243         ao_sdcard_select();
244         ret = ao_sdcard_send_cmd(SDCARD_READ_OCR, 0);
245         if (ret != SDCARD_STATUS_READY_STATE)
246                 DBG ("\tread_ocr failed %02x\n", ret);
247         else {
248                 ao_sdcard_recv_reply(read_ocr_response, 4);
249                 DBG ("\tread_ocr status %02x response %02x %02x %02x %02x\n", ret,
250                         read_ocr_response[0], read_ocr_response[1],
251                         read_ocr_response[2], read_ocr_response[3]);
252         }
253         ao_sdcard_deselect();
254         return ret;
255 }
256
257 static void
258 ao_sdcard_setup(void)
259 {
260         int     i;
261         uint8_t ret;
262         uint8_t response[10];
263
264         DBG ("Testing sdcard\n");
265
266         ao_sdcard_get_slow();
267         /*
268          * min 74 clocks with CS high
269          */
270         ao_sdcard_send_fixed(0xff, 10);
271
272         ao_delay(AO_MS_TO_TICKS(10));
273
274         /* Reset the card and get it into SPI mode */
275
276         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
277                 if (ao_sdcard_go_idle_state() == SDCARD_STATUS_IDLE_STATE)
278                         break;
279         }
280         if (i == SDCARD_IDLE_WAIT)
281                 goto bail;
282
283         /* Figure out what kind of card we have */
284
285         sdtype = ao_sdtype_unknown;
286
287         if (ao_sdcard_send_if_cond(0x1aa, response) == SDCARD_STATUS_IDLE_STATE) {
288                 uint32_t        arg = 0;
289                 uint8_t         sdver2 = 0;
290
291                 /* Check for SD version 2 */
292                 if ((response[2] & 0xf) == 1 && response[3] == 0xaa) {
293                         arg = 0x40000000;
294                         sdver2 = 1;
295                 }
296
297                 for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
298                         ret = ao_sdcard_app_send_op_cond(arg);
299                         if (ret != SDCARD_STATUS_IDLE_STATE)
300                                 break;
301                 }
302                 if (ret != SDCARD_STATUS_READY_STATE) {
303                         /* MMC */
304                         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
305                                 ret = ao_sdcard_send_op_cond();
306                                 if (ret != SDCARD_STATUS_IDLE_STATE)
307                                         break;
308                         }
309                         if (ret != SDCARD_STATUS_READY_STATE)
310                                 goto bail;
311                         sdtype = ao_sdtype_mmc3;
312                 } else {
313                         /* SD */
314                         if (sdver2 != 0) {
315                                 ret = ao_sdcard_read_ocr(response);
316                                 if (ret != SDCARD_STATUS_READY_STATE)
317                                         goto bail;
318                                 if ((response[0] & 0xc0) == 0xc0)
319                                         sdtype = ao_sdtype_sd2block;
320                                 else
321                                         sdtype = ao_sdtype_sd2byte;
322                         } else {
323                                 sdtype = ao_sdtype_sd1;
324                         }
325                 }
326
327                 /* For everything but SDHC cards, set the block length */
328                 if (sdtype != ao_sdtype_sd2block) {
329                         ret = ao_sdcard_set_blocklen(512);
330                         if (ret != SDCARD_STATUS_READY_STATE)
331                                 DBG ("set_blocklen failed, ignoring\n");
332                 }
333         }
334
335         DBG ("SD card detected, type %d\n", sdtype);
336 bail:
337         ao_sdcard_put();
338 }
339
340 static uint8_t
341 ao_sdcard_wait_block_start(void)
342 {
343         int     i;
344         uint8_t v;
345
346         DBG ("\twait_block_start\n");
347         for (i = 0; i < SDCARD_BLOCK_TIMEOUT; i++) {
348                 ao_sdcard_recv(&v, 1);
349                 DBG("\t\trecv %02x\n", v);
350                 if (v != 0xff)
351                         break;
352         }
353         return v;
354 }
355
356 /*
357  * Read a block of 512 bytes from the card
358  */
359 uint8_t
360 ao_sdcard_read_block(uint32_t block, uint8_t *data)
361 {
362         uint8_t ret;
363         uint8_t crc[2];
364
365         ao_sdcard_lock();
366         if (!initialized) {
367                 ao_sdcard_setup();
368                 initialized = 1;
369                 if (sdtype != ao_sdtype_unknown)
370                         present = 1;
371         }
372         if (!present) {
373                 ao_sdcard_unlock();
374                 return 0;
375         }
376         DBG("read block %d\n", block);
377         if (sdtype != ao_sdtype_sd2block)
378                 block <<= 9;
379         ao_sdcard_get();
380         ao_sdcard_select();
381         ret = ao_sdcard_send_cmd(SDCARD_READ_BLOCK, block);
382         ao_sdcard_recv_reply(NULL, 0);
383         if (ret != SDCARD_STATUS_READY_STATE)
384                 goto bail;
385
386         /* Wait for the data start block marker */
387         if (ao_sdcard_wait_block_start() != SDCARD_DATA_START_BLOCK) {
388                 ret = 0x3f;
389                 goto bail;
390         }
391
392         ao_sdcard_recv(data, 512);
393         ao_sdcard_recv(crc, 2);
394 bail:
395         ao_sdcard_deselect();
396         ao_sdcard_put();
397         ao_sdcard_unlock();
398         DBG("read %s\n", ret == SDCARD_STATUS_READY_STATE ? "success" : "failure");
399         return ret == SDCARD_STATUS_READY_STATE;
400 }
401
402 /*
403  * Write a block of 512 bytes to the card
404  */
405 uint8_t
406 ao_sdcard_write_block(uint32_t block, uint8_t *data)
407 {
408         uint8_t ret;
409         uint8_t response;
410         uint8_t start_block[2];
411         int     i;
412
413         ao_sdcard_lock();
414         if (!initialized) {
415                 ao_sdcard_setup();
416                 initialized = 1;
417                 if (sdtype != ao_sdtype_unknown)
418                         present = 1;
419         }
420         if (!present) {
421                 ao_sdcard_unlock();
422                 return 0;
423         }
424         DBG("write block %d\n", block);
425         if (sdtype != ao_sdtype_sd2block)
426                 block <<= 9;
427         ao_sdcard_get();
428         ao_sdcard_select();
429
430         ret = ao_sdcard_send_cmd(SDCARD_WRITE_BLOCK, block);
431         ao_sdcard_recv_reply(NULL, 0);
432         if (ret != SDCARD_STATUS_READY_STATE)
433                 goto bail;
434
435         /* Write a pad byte followed by the data start block marker */
436         start_block[0] = 0xff;
437         start_block[1] = SDCARD_DATA_START_BLOCK;
438         ao_sdcard_send(start_block, 2);
439
440         /* Send the data */
441         ao_sdcard_send(data, 512);
442
443         /* Fake the CRC */
444         ao_sdcard_send_fixed(0xff, 2);
445
446         /* See if the card liked the data */
447         ao_sdcard_recv(&response, 1);
448         if ((response & SDCARD_DATA_RES_MASK) != SDCARD_DATA_RES_ACCEPTED) {
449                 ret = 0x3f;
450                 goto bail;
451         }
452                 
453         /* Wait for the bus to go idle (should be done with an interrupt) */
454         for (i = 0; i < SDCARD_IDLE_TIMEOUT; i++) {
455                 ao_sdcard_recv(&response, 1);
456                 if (response == 0xff)
457                         break;
458         }
459         if (i == SDCARD_IDLE_TIMEOUT)
460                 ret = 0x3f;
461 bail:
462         ao_sdcard_deselect();
463         ao_sdcard_put();
464         ao_sdcard_unlock();
465         DBG("write %s\n", ret == SDCARD_STATUS_READY_STATE ? "success" : "failure");
466         return ret == SDCARD_STATUS_READY_STATE;
467 }
468
469 #if SDCARD_DEBUG
470 static uint8_t  test_data[512];
471
472 static void
473 ao_sdcard_test_read(void)
474 {
475         int i;
476         if (!ao_sdcard_read_block(1, test_data)) {
477                 printf ("read error\n");
478                 return;
479         }
480         printf ("data:");
481         for (i = 0; i < 18; i++)
482                 printf (" %02x", test_data[i]);
483         printf ("\n");
484 }
485
486 static void
487 ao_sdcard_test_write(void)
488 {
489         int     i;
490         printf ("data:");
491         for (i = 0; i < 16; i++) {
492                 test_data[i]++;
493                 printf (" %02x", test_data[i]);
494         }
495         printf ("\n");
496         if (!ao_sdcard_write_block(1, test_data)) {
497                 printf ("write error\n");
498                 return;
499         }
500 }
501
502 static const struct ao_cmds ao_sdcard_cmds[] = {
503         { ao_sdcard_test_read,  "x\0Test read" },
504         { ao_sdcard_test_write, "y\0Test read" },
505         { 0, NULL },
506 };
507 #endif
508
509 void
510 ao_sdcard_init(void)
511 {
512         ao_spi_init_cs(AO_SDCARD_SPI_CS_PORT, (1 << AO_SDCARD_SPI_CS_PIN));
513 #if SDCARD_DEBUG
514         ao_cmd_register(&ao_sdcard_cmds[0]);
515 #endif
516 }