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