6073677a96745ddfbc69a37976e72e9c76a5edd2
[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    1
32
33 /* Spew SD tracing */
34 #define SDCARD_TRACE    0
35
36 /* Emit error and warning messages */
37 #define SDCARD_WARN     0
38
39 static uint8_t  initialized;
40 static uint8_t  present;
41 static uint8_t  mutex;
42 static enum ao_sdtype sdtype;
43
44 #define ao_sdcard_lock()        ao_mutex_get(&mutex)
45 #define ao_sdcard_unlock()      ao_mutex_put(&mutex)
46
47 #if SDCARD_TRACE
48 #define DBG(...) printf(__VA_ARGS__)
49 #else
50 #define DBG(...)
51 #endif
52
53 #if SDCARD_WARN
54 #define WARN(...) printf(__VA_ARGS__)
55 #else
56 #define WARN(...)
57 #endif
58
59 #define later(x,y)      ((int16_t) ((x) - (y)) >= 0)
60
61 /*
62  * Wait while the card is busy. The card will return a stream of 0xff
63  * when it is ready to accept a command
64  */
65
66 static uint8_t
67 ao_sdcard_wait_busy(void)
68 {
69         uint16_t        timeout = ao_time() + SDCARD_BUSY_TIMEOUT;
70         uint8_t         reply;
71         for (;;) {
72                 ao_sdcard_recv(&reply, 1);
73                 DBG("\t\twait busy %02x\n", reply);
74                 if (reply == 0xff)
75                         break;
76                 if (later(ao_time(), timeout)) {
77                         WARN("wait busy timeout\n");
78                         return 0;
79                 }
80         }
81         return 1;
82 }
83
84
85 /*
86  * Send an SD command and await the status reply
87  */
88
89 static uint8_t
90 ao_sdcard_send_cmd(uint8_t cmd, uint32_t arg)
91 {
92         uint8_t data[6];
93         uint8_t reply;
94         int i;
95         uint16_t timeout;
96
97         DBG ("\tsend_cmd %d arg %08x\n", cmd, arg);
98
99         /* Wait for the card to not be busy */
100         if (cmd != SDCARD_GO_IDLE_STATE) {
101                 if (!ao_sdcard_wait_busy())
102                         return SDCARD_STATUS_TIMEOUT;
103         }
104         
105         data[0] = cmd & 0x3f | 0x40;
106         data[1] = arg >> 24;
107         data[2] = arg >> 16;
108         data[3] = arg >> 8;
109         data[4] = arg;
110         if (cmd == SDCARD_GO_IDLE_STATE)
111                 data[5] = 0x95; /* Valid for 0 arg */
112         else if (cmd == SDCARD_SEND_IF_COND)
113                 data[5] = 0x87; /* Valid for 0x1aa arg */
114         else
115                 data[5] = 0xff; /* no CRC */
116         ao_sdcard_send(data, 6);
117
118         /* The first reply byte will be the status,
119          * which must have the high bit clear
120          */
121         timeout = ao_time() + SDCARD_CMD_TIMEOUT;
122         for (;;) {
123                 ao_sdcard_recv(&reply, 1);
124                 DBG ("\t\tgot byte %02x\n", reply);
125                 if ((reply & 0x80) == 0)
126                         break;
127                 if (later(ao_time(), timeout)) {
128                         WARN("send_cmd %02x timeout\n", cmd);
129                         return SDCARD_STATUS_TIMEOUT;
130                 }
131         }
132 #if SDCARD_WARN
133         if (reply != SDCARD_STATUS_READY_STATE && reply != SDCARD_STATUS_IDLE_STATE)
134                 WARN("send_cmd %d failed %02x\n", cmd, reply);
135 #endif
136         return reply;
137 }
138
139 /*
140  * Retrieve any reply, discarding the trailing CRC byte
141  */
142 static void
143 ao_sdcard_recv_reply(uint8_t *reply, int len)
144 {
145         uint8_t discard;
146
147         if (len)
148                 ao_sdcard_recv(reply, len);
149         /* trailing byte */
150         ao_sdcard_recv(&discard, 1);
151 }
152
153 /*
154  * Switch to 'idle' state. This is used to get the card into SPI mode
155  */
156 static uint8_t
157 ao_sdcard_go_idle_state(void)
158 {
159         uint8_t ret;
160
161         DBG ("go_idle_state\n");
162         ao_sdcard_select();
163         ret = ao_sdcard_send_cmd(SDCARD_GO_IDLE_STATE, 0);
164         ao_sdcard_recv_reply(NULL, 0);
165         ao_sdcard_deselect();
166         DBG ("\tgo_idle_state status %02x\n", ret);
167         return ret;
168 }
169
170 static uint8_t
171 ao_sdcard_send_op_cond(void)
172 {
173         uint8_t ret;
174
175         DBG ("send_op_cond\n");
176         ao_sdcard_select();
177         ret = ao_sdcard_send_cmd(SDCARD_SEND_OP_COND, 0);
178         ao_sdcard_recv_reply(NULL, 0);
179         ao_sdcard_deselect();
180         DBG ("\tsend_op_cond %02x\n", ret);
181         return ret;
182 }
183
184 static uint8_t
185 ao_sdcard_send_if_cond(uint32_t arg, uint8_t send_if_cond_response[4])
186 {
187         uint8_t ret;
188
189         DBG ("send_if_cond\n");
190         ao_sdcard_select();
191         ret = ao_sdcard_send_cmd(SDCARD_SEND_IF_COND, arg);
192         if (ret != SDCARD_STATUS_IDLE_STATE) {
193                 DBG ("\tsend_if_cond failed %02x\n", ret);
194                 return ret;
195         }
196         ao_sdcard_recv_reply(send_if_cond_response, 4);
197         DBG ("send_if_cond status %02x response %02x %02x %02x %02x\n",
198                 ret,
199                 send_if_cond_response[0],
200                 send_if_cond_response[1],
201                 send_if_cond_response[2],
202                 send_if_cond_response[3]);
203         ao_sdcard_deselect();
204         return ret;
205 }
206
207 /*
208  * _ao_sdcard_send_status
209  *
210  * Get the 2-byte status value.
211  *
212  * Called from other functions with CS held low already,
213  * hence prefixing the name with '_'
214  */
215 static uint16_t
216 _ao_sdcard_send_status(void)
217 {
218         uint8_t ret;
219         uint8_t extra;
220
221         DBG ("send_status\n");
222         ret = ao_sdcard_send_cmd(SDCARD_SEND_STATUS, 0);
223         ao_sdcard_recv_reply(&extra, 1);
224         if (ret != SDCARD_STATUS_READY_STATE)
225                 DBG ("\tsend_if_cond failed %02x\n", ret);
226         return ret | (extra << 8);
227 }
228
229 /*
230  * ao_sdcard_set_blocklen
231  *
232  * Set the block length for future read and write commands
233  */
234 static uint8_t
235 ao_sdcard_set_blocklen(uint32_t blocklen)
236 {
237         uint8_t ret;
238
239         DBG ("set_blocklen %d\n", blocklen);
240         ao_sdcard_select();
241         ret = ao_sdcard_send_cmd(SDCARD_SET_BLOCKLEN, blocklen);
242         ao_sdcard_recv_reply(NULL, 0);
243         ao_sdcard_deselect();
244         if (ret != SDCARD_STATUS_READY_STATE)
245                 DBG ("\tsend_if_cond failed %02x\n", ret);
246         return ret;
247 }
248
249 /*
250  * _ao_sdcard_app_cmd
251  *
252  * Send the app command prefix
253  *
254  * Called with the CS held low, hence
255  * the '_' prefix
256  */
257 static uint8_t
258 _ao_sdcard_app_cmd(void)
259 {
260         uint8_t ret;
261
262         DBG ("app_cmd\n");
263         ret = ao_sdcard_send_cmd(SDCARD_APP_CMD, 0);
264         ao_sdcard_recv_reply(NULL, 0);
265         DBG ("\tapp_cmd status %02x\n");
266         return ret;
267 }
268
269 static uint8_t
270 ao_sdcard_app_send_op_cond(uint32_t arg)
271 {
272         uint8_t ret;
273
274         DBG("send_op_comd\n");
275         ao_sdcard_select();
276         ret = _ao_sdcard_app_cmd();
277         if (ret != SDCARD_STATUS_IDLE_STATE)
278                 goto bail;
279         ret = ao_sdcard_send_cmd(SDCARD_APP_SEND_OP_COMD, arg);
280         ao_sdcard_recv_reply(NULL, 0);
281 bail:
282         ao_sdcard_deselect();
283         DBG ("\tapp_send_op_cond status %02x\n", ret);
284         return ret;
285 }
286
287 static uint8_t
288 ao_sdcard_read_ocr(uint8_t read_ocr_response[4])
289 {
290         uint8_t ret;
291
292         DBG ("read_ocr\n");
293         ao_sdcard_select();
294         ret = ao_sdcard_send_cmd(SDCARD_READ_OCR, 0);
295         if (ret != SDCARD_STATUS_READY_STATE)
296                 DBG ("\tread_ocr failed %02x\n", ret);
297         else {
298                 ao_sdcard_recv_reply(read_ocr_response, 4);
299                 DBG ("\tread_ocr status %02x response %02x %02x %02x %02x\n", ret,
300                         read_ocr_response[0], read_ocr_response[1],
301                         read_ocr_response[2], read_ocr_response[3]);
302         }
303         ao_sdcard_deselect();
304         return ret;
305 }
306
307 /*
308  * Follow the flow-chart defined by the SD group to
309  * initialize the card and figure out what kind it is
310  */
311 static void
312 ao_sdcard_setup(void)
313 {
314         int     i;
315         uint8_t ret;
316         uint8_t response[10];
317
318         DBG ("Testing sdcard\n");
319
320         ao_sdcard_get_slow();
321         /*
322          * min 74 clocks with CS high
323          */
324         ao_sdcard_send_fixed(0xff, 10);
325
326         /* Reset the card and get it into SPI mode */
327         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
328                 if (ao_sdcard_go_idle_state() == SDCARD_STATUS_IDLE_STATE)
329                         break;
330         }
331         if (i == SDCARD_IDLE_WAIT)
332                 goto bail;
333
334         /* Figure out what kind of card we have */
335         sdtype = ao_sdtype_unknown;
336
337         if (ao_sdcard_send_if_cond(0x1aa, response) == SDCARD_STATUS_IDLE_STATE) {
338                 uint32_t        arg = 0;
339                 uint8_t         sdver2 = 0;
340
341                 /* Check for SD version 2 */
342                 if ((response[2] & 0xf) == 1 && response[3] == 0xaa) {
343                         arg = 0x40000000;
344                         sdver2 = 1;
345                 }
346
347                 for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
348                         ret = ao_sdcard_app_send_op_cond(arg);
349                         if (ret != SDCARD_STATUS_IDLE_STATE)
350                                 break;
351                 }
352                 if (ret != SDCARD_STATUS_READY_STATE) {
353                         /* MMC */
354                         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
355                                 ret = ao_sdcard_send_op_cond();
356                                 if (ret != SDCARD_STATUS_IDLE_STATE)
357                                         break;
358                         }
359                         if (ret != SDCARD_STATUS_READY_STATE)
360                                 goto bail;
361                         sdtype = ao_sdtype_mmc3;
362                 } else {
363                         /* SD */
364                         if (sdver2 != 0) {
365                                 ret = ao_sdcard_read_ocr(response);
366                                 if (ret != SDCARD_STATUS_READY_STATE)
367                                         goto bail;
368                                 if ((response[0] & 0xc0) == 0xc0)
369                                         sdtype = ao_sdtype_sd2block;
370                                 else
371                                         sdtype = ao_sdtype_sd2byte;
372                         } else {
373                                 sdtype = ao_sdtype_sd1;
374                         }
375                 }
376
377                 /* For everything but SDHC cards, set the block length */
378                 if (sdtype != ao_sdtype_sd2block) {
379                         ret = ao_sdcard_set_blocklen(512);
380                         if (ret != SDCARD_STATUS_READY_STATE)
381                                 DBG ("set_blocklen failed, ignoring\n");
382                 }
383         }
384
385         DBG ("SD card detected, type %d\n", sdtype);
386 bail:
387         ao_sdcard_put();
388 }
389
390 static uint8_t
391 _ao_sdcard_reset(void)
392 {
393         int i;
394         uint8_t ret;
395         uint8_t response[10];
396
397         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
398                 if (ao_sdcard_go_idle_state() == SDCARD_STATUS_IDLE_STATE)
399                         break;
400         }
401         if (i == SDCARD_IDLE_WAIT) {
402                 ret = 0x3f;
403                 goto bail;
404         }
405
406         /* Follow the setup path to get the card out of idle state and
407          * up and running again
408          */
409         if (ao_sdcard_send_if_cond(0x1aa, response) == SDCARD_STATUS_IDLE_STATE) {
410                 uint32_t        arg = 0;
411                 uint8_t         sdver2 = 0;
412
413                 /* Check for SD version 2 */
414                 if ((response[2] & 0xf) == 1 && response[3] == 0xaa) {
415                         arg = 0x40000000;
416                         sdver2 = 1;
417                 }
418
419                 for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
420                         ret = ao_sdcard_app_send_op_cond(arg);
421                         if (ret != SDCARD_STATUS_IDLE_STATE)
422                                 break;
423                 }
424
425                 if (ret != SDCARD_STATUS_READY_STATE) {
426                         /* MMC */
427                         for (i = 0; i < SDCARD_IDLE_WAIT; i++) {
428                                 ret = ao_sdcard_send_op_cond();
429                                 if (ret != SDCARD_STATUS_IDLE_STATE)
430                                         break;
431                         }
432                         if (ret != SDCARD_STATUS_READY_STATE)
433                                 goto bail;
434                 }
435
436                 /* For everything but SDHC cards, set the block length */
437                 if (sdtype != ao_sdtype_sd2block) {
438                         ret = ao_sdcard_set_blocklen(512);
439                         if (ret != SDCARD_STATUS_READY_STATE)
440                                 DBG ("set_blocklen failed, ignoring\n");
441                 }
442         }
443 bail:
444         return ret;
445 }
446
447 /*
448  * The card will send 0xff until it is ready to send
449  * the data block at which point it will send the START_BLOCK
450  * marker followed by the data. This function waits while
451  * the card is sending 0xff
452  */
453 static uint8_t
454 ao_sdcard_wait_block_start(void)
455 {
456         uint8_t         v;
457         uint16_t        timeout = ao_time() + SDCARD_BLOCK_TIMEOUT;
458
459         DBG ("\twait_block_start\n");
460         for (;;) {
461                 ao_sdcard_recv(&v, 1);
462                 DBG("\t\trecv %02x\n", v);
463                 if (v != 0xff)
464                         break;
465                 if (later(ao_time(), timeout)) {
466                         printf ("wait block start timeout\n");
467                         return 0xff;
468                 }
469         }
470         return v;
471 }
472
473 /*
474  * Read a block of 512 bytes from the card
475  */
476 uint8_t
477 ao_sdcard_read_block(uint32_t block, uint8_t *data)
478 {
479         uint8_t ret;
480         uint8_t start_block;
481         uint8_t crc[2];
482         int tries;
483
484         ao_sdcard_lock();
485         if (!initialized) {
486                 ao_sdcard_setup();
487                 initialized = 1;
488                 if (sdtype != ao_sdtype_unknown)
489                         present = 1;
490         }
491         if (!present) {
492                 ao_sdcard_unlock();
493                 return 0;
494         }
495         DBG("read block %d\n", block);
496         if (sdtype != ao_sdtype_sd2block)
497                 block <<= 9;
498
499         ao_sdcard_get();
500         for (tries = 0; tries < 10; tries++) {
501                 ao_sdcard_select();
502
503                 ret = ao_sdcard_send_cmd(SDCARD_READ_BLOCK, block);
504                 ao_sdcard_recv_reply(NULL, 0);
505                 if (ret != SDCARD_STATUS_READY_STATE) {
506                         uint16_t        status;
507                         WARN ("read block command failed %d status %02x\n", block, ret);
508                         status = _ao_sdcard_send_status();
509                         WARN ("\tstatus now %04x\n", status);
510                         goto bail;
511                 }
512
513                 ao_sdcard_send_fixed(0xff, 1);
514
515                 /* Wait for the data start block marker */
516                 start_block = ao_sdcard_wait_block_start();
517                 if (start_block != SDCARD_DATA_START_BLOCK) {
518                         WARN ("wait block start failed %02x\n", start_block);
519                         ret = 0x3f;
520                         goto bail;
521                 }
522
523                 ao_sdcard_recv(data, 512);
524                 ao_sdcard_recv(crc, 2);
525         bail:
526                 ao_sdcard_deselect();
527                 if (ret == SDCARD_STATUS_READY_STATE)
528                         break;
529                 if (ret == SDCARD_STATUS_IDLE_STATE) {
530                         ret = _ao_sdcard_reset();
531                         if (ret != SDCARD_STATUS_READY_STATE)
532                                 break;
533                 }
534         }
535         ao_sdcard_put();
536         ao_sdcard_unlock();
537
538 #if SDCARD_WARN
539         if (ret != SDCARD_STATUS_READY_STATE)
540                 WARN("read failed\n");
541         else if (tries)
542                 WARN("took %d tries to read %d\n", tries + 1, block);
543 #endif
544
545         DBG("read %s\n", ret == SDCARD_STATUS_READY_STATE ? "success" : "failure");
546         return ret == SDCARD_STATUS_READY_STATE;
547 }
548
549 /*
550  * Write a block of 512 bytes to the card
551  */
552 uint8_t
553 ao_sdcard_write_block(uint32_t block, uint8_t *data)
554 {
555         uint8_t ret;
556         uint8_t response[1];
557         uint8_t start_block[8];
558         uint16_t status;
559         static uint8_t  check_data[512];
560         int     i;
561         int     tries;
562
563         ao_sdcard_lock();
564         if (!initialized) {
565                 ao_sdcard_setup();
566                 initialized = 1;
567                 if (sdtype != ao_sdtype_unknown)
568                         present = 1;
569         }
570         if (!present) {
571                 ao_sdcard_unlock();
572                 return 0;
573         }
574         DBG("write block %d\n", block);
575         if (sdtype != ao_sdtype_sd2block)
576                 block <<= 9;
577
578         ao_sdcard_get();
579
580         for (tries = 0; tries < 10; tries++) {
581                 ao_sdcard_select();
582
583                 ret = ao_sdcard_send_cmd(SDCARD_WRITE_BLOCK, block);
584                 ao_sdcard_recv_reply(NULL, 0);
585                 if (ret != SDCARD_STATUS_READY_STATE)
586                         goto bail;
587
588                 /* Write a pad byte followed by the data start block marker */
589                 start_block[0] = 0xff;
590                 start_block[1] = SDCARD_DATA_START_BLOCK;
591                 ao_sdcard_send(start_block, 2);
592
593                 /* Send the data */
594                 ao_sdcard_send(data, 512);
595
596                 /* Fake the CRC */
597                 ao_sdcard_send_fixed(0xff, 2);
598
599                 /* See if the card liked the data */
600                 ao_sdcard_recv(response, sizeof (response));
601                 if ((response[0] & SDCARD_DATA_RES_MASK) != SDCARD_DATA_RES_ACCEPTED) {
602                         int i;
603                         WARN("Data not accepted, response");
604                         for (i = 0; i < sizeof (response); i++)
605                                 WARN(" %02x", response[i]);
606                         WARN("\n");
607                         ret = 0x3f;
608                         goto bail;
609                 }
610                 
611                 /* Wait for the bus to go idle (should be done with an interrupt?) */
612                 if (!ao_sdcard_wait_busy()) {
613                         ret = 0x3f;
614                         goto bail;
615                 }
616
617                 /* Check the current status after the write completes */
618                 status = _ao_sdcard_send_status();
619                 if ((status & 0xff) != SDCARD_STATUS_READY_STATE) {
620                         WARN ("send status after write %04x\n", status);
621                         ret = status & 0xff;
622                         goto bail;
623                 }
624         bail:
625                 ao_sdcard_deselect();
626                 DBG("write %s\n", ret == SDCARD_STATUS_READY_STATE ? "success" : "failure");
627                 if (ret == SDCARD_STATUS_READY_STATE)
628                         break;
629         }
630         ao_sdcard_put();
631         ao_sdcard_unlock();
632         if (tries)
633                 WARN("took %d tries to write %d\n", tries + 1, block);
634
635         return ret == SDCARD_STATUS_READY_STATE;
636 }
637
638 #if SDCARD_DEBUG
639 static uint8_t  test_data[512];
640
641 static void
642 ao_sdcard_test_read(void)
643 {
644         int i;
645
646         ao_cmd_decimal();
647         if (ao_cmd_status != ao_cmd_success)
648                 return;
649         
650         for (i = 0; i < 100; i++) {
651                 printf ("."); flush();
652                 if (!ao_sdcard_read_block(ao_cmd_lex_u32+i, test_data)) {
653                         printf ("read error %d\n", i);
654                         return;
655                 }
656         }
657         printf ("data:");
658         for (i = 0; i < 18; i++)
659                 printf (" %02x", test_data[i]);
660         printf ("\n");
661 }
662
663 static void
664 ao_sdcard_test_write(void)
665 {
666         int     i;
667         printf ("data:");
668         for (i = 0; i < 16; i++) {
669                 test_data[i]++;
670                 printf (" %02x", test_data[i]);
671         }
672         printf ("\n");
673         if (!ao_sdcard_write_block(1, test_data)) {
674                 printf ("write error\n");
675                 return;
676         }
677 }
678
679 static const struct ao_cmds ao_sdcard_cmds[] = {
680         { ao_sdcard_test_read,  "x\0Test read" },
681         { ao_sdcard_test_write, "y\0Test read" },
682         { 0, NULL },
683 };
684 #endif
685
686 void
687 ao_sdcard_init(void)
688 {
689         ao_spi_init_cs(AO_SDCARD_SPI_CS_PORT, (1 << AO_SDCARD_SPI_CS_PIN));
690 #if SDCARD_DEBUG
691         ao_cmd_register(&ao_sdcard_cmds[0]);
692 #endif
693 }