Update SD driver in order to use the new KBlock API.
[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   256
70
71 #define SD_DEFAULT_BLOCKLEN 512
72
73 #define SD_BUSY_TIMEOUT ms_to_ticks(200)
74
75 static bool sd_select(Sd *sd, bool state)
76 {
77         KFile *fd = sd->ch;
78
79         if (state)
80         {
81                 ticks_t start = timer_clock();
82                 do
83                 {
84                         SD_CS_ON();
85                         if (kfile_getc(fd) == 0xff)
86                                 return true;
87                         SD_CS_OFF();
88                         kfile_putc(0xff, fd);
89                         kfile_flush(fd);
90                         cpu_relax();
91                 }
92                 while (timer_clock() - start < SD_BUSY_TIMEOUT);
93
94                 LOG_ERR("sd_select timeout\n");
95                 return false;
96         }
97         else
98         {
99                 kfile_putc(0xff, fd);
100                 kfile_flush(fd);
101                 SD_CS_OFF();
102                 return true;
103         }
104 }
105
106 static int16_t sd_waitR1(Sd *sd)
107 {
108         uint8_t datain;
109
110         for (int i = 0; i < TIMEOUT_NAC; i++)
111         {
112           datain = kfile_getc(sd->ch);
113           if (datain != 0xff)
114                 return (int16_t)datain;
115         }
116         LOG_ERR("Timeout waiting R1\n");
117         return EOF;
118 }
119
120 static int16_t sd_sendCommand(Sd *sd, uint8_t cmd, uint32_t param, uint8_t crc)
121 {
122         KFile *fd = sd->ch;
123         /* The 7th bit of command must be a 1 */
124         kfile_putc(cmd | 0x40, fd);
125
126         /* send parameter */
127         kfile_putc((param >> 24) & 0xFF, fd);
128         kfile_putc((param >> 16) & 0xFF, fd);
129         kfile_putc((param >> 8) & 0xFF, fd);
130         kfile_putc((param) & 0xFF, fd);
131
132         kfile_putc(crc, fd);
133
134         return sd_waitR1(sd);
135 }
136
137
138 static bool sd_getBlock(Sd *sd, void *buf, size_t len)
139 {
140         uint8_t token;
141         uint16_t crc;
142
143         KFile *fd = sd->ch;
144
145         for (int i = 0; i < TIMEOUT_NAC; i++)
146         {
147                 token = kfile_getc(fd);
148                 if (token != 0xff)
149                 {
150                         if (token == SD_STARTTOKEN)
151                         {
152                                 if (kfile_read(fd, buf, len) == len)
153                                 {
154                                         if (kfile_read(fd, &crc, sizeof(crc)) == sizeof(crc))
155                                                 /* check CRC here if needed */
156                                                 return true;
157                                         else
158                                                 LOG_ERR("get_block error getting crc\n");
159                                 }
160                                 else
161                                         LOG_ERR("get_block len error: %d\n", (int)len);
162                         }
163                         else
164                                 LOG_ERR("get_block token error: %02X\n", token);
165
166                         return false;
167                 }
168         }
169
170         LOG_ERR("get_block timeout waiting token\n");
171         return false;
172 }
173
174 #define SD_SELECT(sd) \
175 do \
176 { \
177         if (!sd_select((sd), true)) \
178         { \
179                 LOG_ERR("%s failed, card busy\n", __func__); \
180                 return EOF; \
181         } \
182 } \
183 while (0)
184
185 #define SD_SETBLOCKLEN 0x50
186
187 static int16_t sd_setBlockLen(Sd *sd, uint32_t newlen)
188 {
189         SD_SELECT(sd);
190
191         sd->r1 = sd_sendCommand(sd, SD_SETBLOCKLEN, newlen, 0);
192
193         sd_select(sd, false);
194         return sd->r1;
195 }
196
197 #define SD_SEND_CSD 0x49
198
199 static int16_t sd_getCSD(Sd *sd, CardCSD *csd)
200 {
201         SD_SELECT(sd);
202
203         sd->r1 = sd_sendCommand(sd, SD_SEND_CSD, 0, 0);
204
205         if (sd->r1)
206         {
207                 LOG_ERR("send_csd failed: %04X\n", sd->r1);
208                 sd_select(sd, false);
209                 return sd->r1;
210         }
211
212         uint8_t buf[16];
213         bool res = sd_getBlock(sd, buf, sizeof(buf));
214         sd_select(sd, false);
215
216         if (res)
217         {
218                 #if LOG_LEVEL >= LOG_LVL_INFO
219                         LOG_INFO("CSD: [");
220                         for (int i = 0; i < 16; i++)
221                                 kprintf("%02X ", buf[i]);
222                         kprintf("]\n");
223                 #endif
224
225                 uint16_t mult = (1L << ((((buf[9] & 0x03) << 1) | ((buf[10] & 0x80) >> 7)) + 2));
226                 uint16_t c_size = (((uint16_t)(buf[6] & 0x03)) << 10) | (((uint16_t)buf[7]) << 2) |
227                                   (((uint16_t)(buf[8] & 0xC0)) >> 6);
228
229                 csd->block_len = (1L << (buf[5] & 0x0F));
230                 csd->block_num = (c_size + 1) * mult;
231                 csd->capacity = (csd->block_len * csd->block_num) >> 20; // in MB
232
233                 LOG_INFO("block_len %d bytes, block_num %ld, total capacity %dMB\n", csd->block_len, csd->block_num, csd->capacity);
234                 return 0;
235         }
236         else
237                 return EOF;
238 }
239
240
241 #define SD_READ_SINGLEBLOCK 0x51
242
243 static size_t sd_readDirect(struct KBlock *b, block_idx_t idx, void *buf, size_t offset, size_t size)
244 {
245         Sd *sd = SD_CAST(b);
246         LOG_INFO("reading from block %ld, offset %d, size %d\n", idx, offset, 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
254         SD_SELECT(sd);
255         sd->r1 = sd_sendCommand(sd, SD_READ_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN + offset, 0);
256
257         if (sd->r1)
258         {
259                 LOG_ERR("read single block failed: %04X\n", sd->r1);
260                 sd_select(sd, false);
261                 return 0;
262         }
263
264         bool res = sd_getBlock(sd, buf, size);
265         sd_select(sd, false);
266         if (!res)
267         {
268                 LOG_ERR("read single block failed reading data\n");
269                 return 0;
270         }
271         else
272                 return size;
273 }
274
275 #define SD_WRITE_SINGLEBLOCK 0x58
276 #define SD_DATA_ACCEPTED     0x05
277
278 static int sd_writeBlock(KBlock *b, block_idx_t idx, const void *buf)
279 {
280         Sd *sd = SD_CAST(b);
281         KFile *fd = sd->ch;
282
283         LOG_INFO("writing block %ld\n", idx);
284         if ((sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN)))
285         {
286                 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
287                 return sd->r1;
288         }
289
290         SD_SELECT(sd);
291
292         sd->r1 = sd_sendCommand(sd, SD_WRITE_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN, 0);
293
294         if (sd->r1)
295         {
296                 LOG_ERR("write single block failed: %04X\n", sd->r1);
297                 sd_select(sd, false);
298                 return sd->r1;
299         }
300
301         kfile_putc(SD_STARTTOKEN, fd);
302         kfile_write(fd, buf, SD_DEFAULT_BLOCKLEN);
303         /* send fake crc */
304         kfile_putc(0, fd);
305         kfile_putc(0, fd);
306         uint8_t dataresp = (kfile_getc(fd) & 0x1F);
307         sd_select(sd, false);
308
309         // FIXME: sometimes dataresp is 0, find out why.
310         if (dataresp != SD_DATA_ACCEPTED)
311         {
312                 LOG_ERR("write single block failed: %02X\n", dataresp);
313                 return EOF;
314         }
315         else
316                 return 0;
317 }
318
319
320 bool sd_test(Sd *sd)
321 {
322         uint8_t buf[SD_DEFAULT_BLOCKLEN];
323
324         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
325                 return false;
326
327         kputchar('\n');
328         for (int i = 0; i < SD_DEFAULT_BLOCKLEN; i++)
329         {
330                 kprintf("%02X ", buf[i]);
331                 buf[i] = i;
332                 if (!((i+1) % 16))
333                         kputchar('\n');
334         }
335
336         if (sd_writeBlock(&sd->b, 0, buf) != 0)
337                 return false;
338
339         memset(buf, 0, sizeof(buf));
340         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
341                 return false;
342
343         kputchar('\n');
344         for (block_idx_t i = 0; i < sd->b.blk_size; i++)
345         {
346                 kprintf("%02X ", buf[i]);
347                 buf[i] = i;
348                 if (!((i+1) % 16))
349                         kputchar('\n');
350         }
351
352         return true;
353 }
354
355 static int sd_error(KBlock *b)
356 {
357         Sd *sd = SD_CAST(b);
358         return sd->r1;
359 }
360
361 static int sd_clearerr(KBlock *b)
362 {
363         Sd *sd = SD_CAST(b);
364         sd->r1 = 0;
365         return 0;
366 }
367
368 static const KBlockVTable sd_unbuffered_vt =
369 {
370         .readDirect = sd_readDirect,
371         .writeBlock = sd_writeBlock,
372
373         .error = sd_error,
374         .clearerr = sd_clearerr,
375 };
376
377 static const KBlockVTable sd_buffered_vt =
378 {
379         .readDirect = sd_readDirect,
380         .writeBlock = sd_writeBlock,
381
382         .readBuf = kblock_swReadBuf,
383         .writeBuf = kblock_swWriteBuf,
384         .load = kblock_swLoad,
385         .store = kblock_swStore,
386
387         .error = sd_error,
388         .clearerr = sd_clearerr,
389 };
390
391 #define SD_GO_IDLE_STATE     0x40
392 #define SD_GO_IDLE_STATE_CRC 0x95
393 #define SD_SEND_OP_COND      0x41
394 #define SD_SEND_OP_COND_CRC  0xF9
395
396 #define SD_START_DELAY  ms_to_ticks(10)
397 #define SD_INIT_TIMEOUT ms_to_ticks(1000)
398 #define SD_IDLE_RETRIES 4
399
400 static bool sd_blockInit(Sd *sd, KFile *ch)
401 {
402         ASSERT(sd);
403         ASSERT(ch);
404         memset(sd, 0, sizeof(*sd));
405         DB(sd->b.priv.type = KBT_SD);
406         sd->ch = ch;
407
408         SD_CS_INIT();
409         SD_CS_OFF();
410
411         /* Wait a few moments for supply voltage to stabilize */
412         timer_delay(SD_START_DELAY);
413
414         /* Give 80 clk pulses to wake up the card */
415         for (int i = 0; i < 10; i++)
416                 kfile_putc(0xff, ch);
417         kfile_flush(ch);
418
419         for (int i = 0; i < SD_IDLE_RETRIES; i++)
420         {
421                 SD_SELECT(sd);
422                 sd->r1 = sd_sendCommand(sd, SD_GO_IDLE_STATE, 0, SD_GO_IDLE_STATE_CRC);
423                 sd_select(sd, false);
424
425                 if (sd->r1 == SD_IN_IDLE)
426                         break;
427         }
428
429         if (sd->r1 != SD_IN_IDLE)
430         {
431                 LOG_ERR("go_idle_state failed: %04X\n", sd->r1);
432                 return false;
433         }
434
435         ticks_t start = timer_clock();
436
437         /* Wait for card to start */
438         do
439         {
440                 SD_SELECT(sd);
441                 sd->r1 = sd_sendCommand(sd, SD_SEND_OP_COND, 0, SD_SEND_OP_COND_CRC);
442                 sd_select(sd, false);
443                 cpu_relax();
444         }
445         while (sd->r1 != 0 && timer_clock() - start < SD_INIT_TIMEOUT);
446
447         if (sd->r1)
448         {
449                 LOG_ERR("send_op_cond failed: %04X\n", sd->r1);
450                 return false;
451         }
452
453         sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN);
454
455         if (sd->r1)
456         {
457                 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
458                 return false;
459         }
460
461         CardCSD csd;
462         sd->r1 = sd_getCSD(sd, &csd);
463         if (sd->r1)
464         {
465                 LOG_ERR("getCSD failed: %04X\n", sd->r1);
466                 return false;
467         }
468
469         sd->b.blk_size = SD_DEFAULT_BLOCKLEN;
470         sd->b.blk_cnt = csd.block_num * (csd.block_len / SD_DEFAULT_BLOCKLEN);
471         LOG_INFO("blk_size %d, blk_cnt %ld\n", sd->b.blk_size, sd->b.blk_cnt);
472
473
474 #if CONFIG_SD_AUTOASSIGN_FAT
475         disk_assignDrive(&sd->b, 0);
476 #endif
477
478         return true;
479 }
480
481 bool sd_initUnbuf(Sd *sd, KFile *ch)
482 {
483         if (sd_blockInit(sd, ch))
484         {
485                 sd->b.priv.vt = &sd_unbuffered_vt;
486                 return true;
487         }
488         else
489                 return false;
490 }
491
492 static uint8_t sd_buf[SD_DEFAULT_BLOCKLEN];
493
494 bool sd_initBuf(Sd *sd, KFile *ch)
495 {
496         if (sd_blockInit(sd, ch))
497         {
498                 sd->b.priv.buf = sd_buf;
499                 sd->b.priv.flags |= KB_BUFFERED;
500                 sd->b.priv.vt = &sd_buffered_vt;
501                 sd->b.priv.vt->load(&sd->b, 0);
502                 return true;
503         }
504         else
505                 return false;
506 }
507