Increase read/write performances; add some comments.
[bertos.git] / bertos / drv / sd.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
30  * -->
31  *
32  * \brief Function library for secure digital memory.
33  *
34  * \author Francesco Sacchi <batt@develer.com>
35  */
36
37
38 #include "sd.h"
39 #include "hw/hw_sd.h"
40 #include <io/kfile.h>
41 #include <io/kblock.h>
42 #include <drv/timer.h>
43
44 #include <fs/fat.h>
45
46 #include "cfg/cfg_sd.h"
47
48 #define LOG_LEVEL  SD_LOG_LEVEL
49 #define LOG_FORMAT SD_LOG_FORMAT
50 #include <cfg/log.h>
51 #include <cpu/power.h>
52
53 #include <string.h> /* memset */
54
55 /**
56  * Card Specific Data
57  * read directly from the card.
58  */
59 typedef struct CardCSD
60 {
61         uint16_t block_len;  ///< Length of a block
62         uint32_t block_num;  ///< Number of block on the card
63         uint16_t capacity;   ///< Card capacity in MB
64 } CardCSD;
65
66 #define SD_IN_IDLE    0x01
67 #define SD_STARTTOKEN 0xFE
68
69 #define TIMEOUT_NAC   16384
70 #define SD_DEFAULT_BLOCKLEN 512
71
72 #define SD_BUSY_TIMEOUT ms_to_ticks(200)
73
74 static bool sd_select(Sd *sd, bool state)
75 {
76         KFile *fd = sd->ch;
77
78         if (state)
79         {
80                 SD_CS_ON();
81
82                 ticks_t start = timer_clock();
83                 do
84                 {
85                         if (kfile_getc(fd) == 0xff)
86                                 return true;
87
88                         cpu_relax();
89                 }
90                 while (timer_clock() - start < SD_BUSY_TIMEOUT);
91
92                 SD_CS_OFF();
93                 LOG_ERR("sd_select timeout\n");
94                 return false;
95         }
96         else
97         {
98                 kfile_putc(0xff, fd);
99                 kfile_flush(fd);
100                 SD_CS_OFF();
101                 return true;
102         }
103 }
104
105 static int16_t sd_waitR1(Sd *sd)
106 {
107         uint8_t datain;
108
109         for (int i = 0; i < TIMEOUT_NAC; i++)
110         {
111                 datain = kfile_getc(sd->ch);
112                 if (datain != 0xff)
113                         return (int16_t)datain;
114         }
115         LOG_ERR("Timeout waiting R1\n");
116         return EOF;
117 }
118
119 static int16_t sd_sendCommand(Sd *sd, uint8_t cmd, uint32_t param, uint8_t crc)
120 {
121         KFile *fd = sd->ch;
122         /* The 7th bit of command must be a 1 */
123         kfile_putc(cmd | 0x40, fd);
124
125         /* send parameter */
126         kfile_putc((param >> 24) & 0xFF, fd);
127         kfile_putc((param >> 16) & 0xFF, fd);
128         kfile_putc((param >> 8) & 0xFF, fd);
129         kfile_putc((param) & 0xFF, fd);
130
131         kfile_putc(crc, fd);
132
133         return sd_waitR1(sd);
134 }
135
136 static bool sd_getBlock(Sd *sd, void *buf, size_t len)
137 {
138         uint8_t token;
139         uint16_t crc;
140
141         KFile *fd = sd->ch;
142
143         for (int i = 0; i < TIMEOUT_NAC; i++)
144         {
145                 token = kfile_getc(fd);
146                 if (token != 0xff)
147                 {
148                         if (token == SD_STARTTOKEN)
149                         {
150                                 if (kfile_read(fd, buf, len) == len)
151                                 {
152                                         if (kfile_read(fd, &crc, sizeof(crc)) == sizeof(crc))
153                                                 /* check CRC here if needed */
154                                                 return true;
155                                         else
156                                                 LOG_ERR("get_block error getting crc\n");
157                                 }
158                                 else
159                                         LOG_ERR("get_block len error: %d\n", (int)len);
160                         }
161                         else
162                                 LOG_ERR("get_block token error: %02X\n", token);
163
164                         return false;
165                 }
166         }
167
168         LOG_ERR("get_block timeout waiting token\n");
169         return false;
170 }
171
172 #define SD_SELECT(sd) \
173 do \
174 { \
175         if (!sd_select((sd), true)) \
176         { \
177                 LOG_ERR("%s failed, card busy\n", __func__); \
178                 return EOF; \
179         } \
180 } \
181 while (0)
182
183 #define SD_SETBLOCKLEN 0x50
184
185 static int16_t sd_setBlockLen(Sd *sd, uint32_t newlen)
186 {
187         SD_SELECT(sd);
188
189         sd->r1 = sd_sendCommand(sd, SD_SETBLOCKLEN, newlen, 0);
190
191         sd_select(sd, false);
192         return sd->r1;
193 }
194
195 #define SD_SEND_CSD 0x49
196
197 static int16_t sd_getCSD(Sd *sd, CardCSD *csd)
198 {
199         SD_SELECT(sd);
200
201         int16_t r1 = sd_sendCommand(sd, SD_SEND_CSD, 0, 0);
202
203         if (r1)
204         {
205                 LOG_ERR("send_csd failed: %04X\n", sd->r1);
206                 sd_select(sd, false);
207                 return r1;
208         }
209
210         uint8_t buf[16];
211         bool res = sd_getBlock(sd, buf, sizeof(buf));
212         sd_select(sd, false);
213
214         if (res)
215         {
216                 #if LOG_LEVEL >= LOG_LVL_INFO
217                         LOG_INFO("CSD: [");
218                         for (int i = 0; i < 16; i++)
219                                 kprintf("%02X ", buf[i]);
220                         kprintf("]\n");
221                 #endif
222
223                 uint16_t mult = (1L << ((((buf[9] & 0x03) << 1) | ((buf[10] & 0x80) >> 7)) + 2));
224                 uint16_t c_size = (((uint16_t)(buf[6] & 0x03)) << 10) | (((uint16_t)buf[7]) << 2) |
225                                   (((uint16_t)(buf[8] & 0xC0)) >> 6);
226
227                 csd->block_len = (1L << (buf[5] & 0x0F));
228                 csd->block_num = (c_size + 1) * mult;
229                 csd->capacity = (csd->block_len * csd->block_num) >> 20; // in MB
230
231                 LOG_INFO("block_len %d bytes, block_num %ld, total capacity %dMB\n", csd->block_len, csd->block_num, csd->capacity);
232                 return 0;
233         }
234         else
235                 return EOF;
236 }
237
238
239 #define SD_READ_SINGLEBLOCK 0x51
240
241 static size_t sd_readDirect(struct KBlock *b, block_idx_t idx, void *buf, size_t offset, size_t size)
242 {
243         Sd *sd = SD_CAST(b);
244         LOG_INFO("reading from block %ld, offset %d, size %d\n", idx, offset, size);
245
246         if (sd->tranfer_len != size)
247         {
248                 if ((sd->r1 = sd_setBlockLen(sd, size)))
249                 {
250                         LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
251                         return 0;
252                 }
253                 sd->tranfer_len = size;
254         }
255
256         SD_SELECT(sd);
257
258         sd->r1 = sd_sendCommand(sd, SD_READ_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN + offset, 0);
259
260         if (sd->r1)
261         {
262                 LOG_ERR("read single block failed: %04X\n", sd->r1);
263                 sd_select(sd, false);
264                 return 0;
265         }
266
267         bool res = sd_getBlock(sd, buf, size);
268         sd_select(sd, false);
269         if (!res)
270         {
271                 LOG_ERR("read single block failed reading data\n");
272                 return 0;
273         }
274         else
275                 return size;
276 }
277
278 #define SD_WRITE_SINGLEBLOCK 0x58
279 #define SD_DATA_ACCEPTED     0x05
280
281 static int sd_writeBlock(KBlock *b, block_idx_t idx, const void *buf)
282 {
283         Sd *sd = SD_CAST(b);
284         KFile *fd = sd->ch;
285
286         LOG_INFO("writing block %ld\n", idx);
287         if (sd->tranfer_len != SD_DEFAULT_BLOCKLEN)
288         {
289                 if ((sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN)))
290                 {
291                         LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
292                         return sd->r1;
293                 }
294                 sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
295         }
296
297         SD_SELECT(sd);
298
299         sd->r1 = sd_sendCommand(sd, SD_WRITE_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN, 0);
300
301         if (sd->r1)
302         {
303                 LOG_ERR("write single block failed: %04X\n", sd->r1);
304                 sd_select(sd, false);
305                 return sd->r1;
306         }
307
308         kfile_putc(SD_STARTTOKEN, fd);
309         kfile_write(fd, buf, SD_DEFAULT_BLOCKLEN);
310         /* send fake crc */
311         kfile_putc(0, fd);
312         kfile_putc(0, fd);
313
314         uint8_t dataresp = kfile_getc(fd);
315         sd_select(sd, false);
316
317         if ((dataresp & 0x1f) != SD_DATA_ACCEPTED)
318         {
319                 LOG_ERR("write block %ld failed: %02X\n", idx, dataresp);
320                 return EOF;
321         }
322
323         return 0;
324 }
325
326 void sd_writeTest(Sd *sd)
327 {
328         uint8_t buf[SD_DEFAULT_BLOCKLEN];
329         memset(buf, 0, sizeof(buf));
330
331         for (block_idx_t i = 0; i < sd->b.blk_cnt; i++)
332         {
333                 LOG_INFO("writing block %ld: %s\n", i, (sd_writeBlock(&sd->b, i, buf) == 0) ? "OK" : "FAIL");
334         }
335 }
336
337
338 bool sd_test(Sd *sd)
339 {
340         uint8_t buf[SD_DEFAULT_BLOCKLEN];
341
342         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
343                 return false;
344
345         kputchar('\n');
346         for (int i = 0; i < SD_DEFAULT_BLOCKLEN; i++)
347         {
348                 kprintf("%02X ", buf[i]);
349                 buf[i] = i;
350                 if (!((i+1) % 16))
351                         kputchar('\n');
352         }
353
354         if (sd_writeBlock(&sd->b, 0, buf) != 0)
355                 return false;
356
357         memset(buf, 0, sizeof(buf));
358         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
359                 return false;
360
361         kputchar('\n');
362         for (block_idx_t i = 0; i < sd->b.blk_size; i++)
363         {
364                 kprintf("%02X ", buf[i]);
365                 buf[i] = i;
366                 if (!((i+1) % 16))
367                         kputchar('\n');
368         }
369
370         return true;
371 }
372
373 static int sd_error(KBlock *b)
374 {
375         Sd *sd = SD_CAST(b);
376         return sd->r1;
377 }
378
379 static int sd_clearerr(KBlock *b)
380 {
381         Sd *sd = SD_CAST(b);
382         sd->r1 = 0;
383         return 0;
384 }
385
386 static const KBlockVTable sd_unbuffered_vt =
387 {
388         .readDirect = sd_readDirect,
389         .writeBlock = sd_writeBlock,
390
391         .error = sd_error,
392         .clearerr = sd_clearerr,
393 };
394
395 static const KBlockVTable sd_buffered_vt =
396 {
397         .readDirect = sd_readDirect,
398         .writeBlock = sd_writeBlock,
399
400         .readBuf = kblock_swReadBuf,
401         .writeBuf = kblock_swWriteBuf,
402         .load = kblock_swLoad,
403         .store = kblock_swStore,
404
405         .error = sd_error,
406         .clearerr = sd_clearerr,
407 };
408
409 #define SD_GO_IDLE_STATE     0x40
410 #define SD_GO_IDLE_STATE_CRC 0x95
411 #define SD_SEND_OP_COND      0x41
412 #define SD_SEND_OP_COND_CRC  0xF9
413
414 #define SD_START_DELAY  ms_to_ticks(10)
415 #define SD_INIT_TIMEOUT ms_to_ticks(1000)
416 #define SD_IDLE_RETRIES 4
417
418 static bool sd_blockInit(Sd *sd, KFile *ch)
419 {
420         ASSERT(sd);
421         ASSERT(ch);
422         memset(sd, 0, sizeof(*sd));
423         DB(sd->b.priv.type = KBT_SD);
424         sd->ch = ch;
425
426         SD_CS_INIT();
427         SD_CS_OFF();
428
429         /* Wait a few moments for supply voltage to stabilize */
430         timer_delay(SD_START_DELAY);
431
432         /* Give 80 clk pulses to wake up the card */
433         for (int i = 0; i < 10; i++)
434                 kfile_putc(0xff, ch);
435         kfile_flush(ch);
436
437         for (int i = 0; i < SD_IDLE_RETRIES; i++)
438         {
439                 SD_SELECT(sd);
440                 sd->r1 = sd_sendCommand(sd, SD_GO_IDLE_STATE, 0, SD_GO_IDLE_STATE_CRC);
441                 sd_select(sd, false);
442
443                 if (sd->r1 == SD_IN_IDLE)
444                         break;
445         }
446
447         if (sd->r1 != SD_IN_IDLE)
448         {
449                 LOG_ERR("go_idle_state failed: %04X\n", sd->r1);
450                 return false;
451         }
452
453         ticks_t start = timer_clock();
454
455         /* Wait for card to start */
456         do
457         {
458                 SD_SELECT(sd);
459                 sd->r1 = sd_sendCommand(sd, SD_SEND_OP_COND, 0, SD_SEND_OP_COND_CRC);
460                 sd_select(sd, false);
461                 cpu_relax();
462         }
463         while (sd->r1 != 0 && timer_clock() - start < SD_INIT_TIMEOUT);
464
465         if (sd->r1)
466         {
467                 LOG_ERR("send_op_cond failed: %04X\n", sd->r1);
468                 return false;
469         }
470
471         sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN);
472         sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
473
474         if (sd->r1)
475         {
476                 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
477                 return false;
478         }
479
480         /* Avoid warning for uninitialized csd use (gcc bug?) */
481         CardCSD csd = csd;
482
483         sd->r1 = sd_getCSD(sd, &csd);
484
485         if (sd->r1)
486         {
487                 LOG_ERR("getCSD failed: %04X\n", sd->r1);
488                 return false;
489         }
490
491         sd->b.blk_size = SD_DEFAULT_BLOCKLEN;
492         sd->b.blk_cnt = csd.block_num * (csd.block_len / SD_DEFAULT_BLOCKLEN);
493         LOG_INFO("blk_size %d, blk_cnt %ld\n", sd->b.blk_size, sd->b.blk_cnt);
494
495 #if CONFIG_SD_AUTOASSIGN_FAT
496         disk_assignDrive(&sd->b, 0);
497 #endif
498
499         return true;
500 }
501
502 bool sd_initUnbuf(Sd *sd, KFile *ch)
503 {
504         if (sd_blockInit(sd, ch))
505         {
506                 sd->b.priv.vt = &sd_unbuffered_vt;
507                 return true;
508         }
509         else
510                 return false;
511 }
512
513 static uint8_t sd_buf[SD_DEFAULT_BLOCKLEN];
514
515 bool sd_initBuf(Sd *sd, KFile *ch)
516 {
517         if (sd_blockInit(sd, ch))
518         {
519                 sd->b.priv.buf = sd_buf;
520                 sd->b.priv.flags |= KB_BUFFERED;
521                 sd->b.priv.vt = &sd_buffered_vt;
522                 sd->b.priv.vt->load(&sd->b, 0);
523                 return true;
524         }
525         else
526                 return false;
527 }
528