Add write block function.
[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 size_t sd_writeDirect(KBlock *b, block_idx_t idx, const void *buf, size_t offset, size_t size)
282 {
283         Sd *sd = SD_CAST(b);
284         KFile *fd = sd->ch;
285         ASSERT(offset == 0);
286         ASSERT(size == SD_DEFAULT_BLOCKLEN);
287
288         LOG_INFO("writing block %ld\n", idx);
289         if (sd->tranfer_len != SD_DEFAULT_BLOCKLEN)
290         {
291                 if ((sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN)))
292                 {
293                         LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
294                         return 0;
295                 }
296                 sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
297         }
298
299         SD_SELECT(sd);
300
301         sd->r1 = sd_sendCommand(sd, SD_WRITE_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN, 0);
302
303         if (sd->r1)
304         {
305                 LOG_ERR("write single block failed: %04X\n", sd->r1);
306                 sd_select(sd, false);
307                 return 0;
308         }
309
310         kfile_putc(SD_STARTTOKEN, fd);
311         kfile_write(fd, buf, SD_DEFAULT_BLOCKLEN);
312         /* send fake crc */
313         kfile_putc(0, fd);
314         kfile_putc(0, fd);
315
316         uint8_t dataresp = kfile_getc(fd);
317         sd_select(sd, false);
318
319         if ((dataresp & 0x1f) != SD_DATA_ACCEPTED)
320         {
321                 LOG_ERR("write block %ld failed: %02X\n", idx, dataresp);
322                 return EOF;
323         }
324
325         return SD_DEFAULT_BLOCKLEN;
326 }
327
328 void sd_writeTest(Sd *sd)
329 {
330         uint8_t buf[SD_DEFAULT_BLOCKLEN];
331         memset(buf, 0, sizeof(buf));
332
333         for (block_idx_t i = 0; i < sd->b.blk_cnt; i++)
334         {
335                 LOG_INFO("writing block %ld: %s\n", i, (sd_writeDirect(&sd->b, i, buf, 0, SD_DEFAULT_BLOCKLEN) == SD_DEFAULT_BLOCKLEN) ? "OK" : "FAIL");
336         }
337 }
338
339
340 bool sd_test(Sd *sd)
341 {
342         uint8_t buf[SD_DEFAULT_BLOCKLEN];
343
344         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
345                 return false;
346
347         kputchar('\n');
348         for (int i = 0; i < SD_DEFAULT_BLOCKLEN; i++)
349         {
350                 kprintf("%02X ", buf[i]);
351                 buf[i] = i;
352                 if (!((i+1) % 16))
353                         kputchar('\n');
354         }
355
356         if (sd_writeDirect(&sd->b, 0, buf, 0, SD_DEFAULT_BLOCKLEN) != SD_DEFAULT_BLOCKLEN)
357                 return false;
358
359         memset(buf, 0, sizeof(buf));
360         if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
361                 return false;
362
363         kputchar('\n');
364         for (block_idx_t i = 0; i < sd->b.blk_size; i++)
365         {
366                 kprintf("%02X ", buf[i]);
367                 buf[i] = i;
368                 if (!((i+1) % 16))
369                         kputchar('\n');
370         }
371
372         return true;
373 }
374
375 static int sd_error(KBlock *b)
376 {
377         Sd *sd = SD_CAST(b);
378         return sd->r1;
379 }
380
381 static void sd_clearerr(KBlock *b)
382 {
383         Sd *sd = SD_CAST(b);
384         sd->r1 = 0;
385 }
386
387 static const KBlockVTable sd_unbuffered_vt =
388 {
389         .readDirect = sd_readDirect,
390         .writeDirect = sd_writeDirect,
391
392         .error = sd_error,
393         .clearerr = sd_clearerr,
394 };
395
396 static const KBlockVTable sd_buffered_vt =
397 {
398         .readDirect = sd_readDirect,
399         .writeDirect = sd_writeDirect,
400
401         .readBuf = kblock_swReadBuf,
402         .writeBuf = kblock_swWriteBuf,
403         .load = kblock_swLoad,
404         .store = kblock_swStore,
405
406         .error = sd_error,
407         .clearerr = sd_clearerr,
408 };
409
410 #define SD_GO_IDLE_STATE     0x40
411 #define SD_GO_IDLE_STATE_CRC 0x95
412 #define SD_SEND_OP_COND      0x41
413 #define SD_SEND_OP_COND_CRC  0xF9
414
415 #define SD_START_DELAY  10
416 #define SD_INIT_TIMEOUT ms_to_ticks(2000)
417 #define SD_IDLE_RETRIES 4
418
419 static bool sd_blockInit(Sd *sd, KFile *ch)
420 {
421         ASSERT(sd);
422         ASSERT(ch);
423         memset(sd, 0, sizeof(*sd));
424         DB(sd->b.priv.type = KBT_SD);
425         sd->ch = ch;
426
427         SD_CS_INIT();
428         SD_CS_OFF();
429
430         /* Wait a few moments for supply voltage to stabilize */
431         timer_delay(SD_START_DELAY);
432
433         /* Give 80 clk pulses to wake up the card */
434         for (int i = 0; i < 10; i++)
435                 kfile_putc(0xff, ch);
436         kfile_flush(ch);
437
438         for (int i = 0; i < SD_IDLE_RETRIES; i++)
439         {
440                 SD_SELECT(sd);
441                 sd->r1 = sd_sendCommand(sd, SD_GO_IDLE_STATE, 0, SD_GO_IDLE_STATE_CRC);
442                 sd_select(sd, false);
443
444                 if (sd->r1 == SD_IN_IDLE)
445                         break;
446         }
447
448         if (sd->r1 != SD_IN_IDLE)
449         {
450                 LOG_ERR("go_idle_state failed: %04X\n", sd->r1);
451                 return false;
452         }
453
454         ticks_t start = timer_clock();
455
456         /* Wait for card to start */
457         do
458         {
459                 SD_SELECT(sd);
460                 sd->r1 = sd_sendCommand(sd, SD_SEND_OP_COND, 0, SD_SEND_OP_COND_CRC);
461                 sd_select(sd, false);
462                 cpu_relax();
463         }
464         while (sd->r1 != 0 && timer_clock() - start < SD_INIT_TIMEOUT);
465
466         if (sd->r1)
467         {
468                 LOG_ERR("send_op_cond failed: %04X\n", sd->r1);
469                 return false;
470         }
471
472         sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN);
473         sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
474
475         if (sd->r1)
476         {
477                 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
478                 return false;
479         }
480
481         /* Avoid warning for uninitialized csd use (gcc bug?) */
482         CardCSD csd = csd;
483
484         sd->r1 = sd_getCSD(sd, &csd);
485
486         if (sd->r1)
487         {
488                 LOG_ERR("getCSD failed: %04X\n", sd->r1);
489                 return false;
490         }
491
492         sd->b.blk_size = SD_DEFAULT_BLOCKLEN;
493         sd->b.blk_cnt = csd.block_num * (csd.block_len / SD_DEFAULT_BLOCKLEN);
494         LOG_INFO("blk_size %d, blk_cnt %ld\n", sd->b.blk_size, sd->b.blk_cnt);
495
496 #if CONFIG_SD_AUTOASSIGN_FAT
497         disk_assignDrive(&sd->b, 0);
498 #endif
499
500         return true;
501 }
502
503 #if CPU_CM3_SAM3X8
504
505 #include <drv/hsmci_sam3.h>
506
507 /* SD commands                           type  argument     response */
508   /* class 0 */
509 /* This is basically the same command as for MMC with some quirks. */
510 #define SD_SEND_RELATIVE_ADDR     3   /* bcr                     R6  */
511 #define SD_SEND_IF_COND           8   /* bcr  [11:0] See below   R7  */
512 #define SD_SWITCH_VOLTAGE         11  /* ac                      R1  */
513
514   /* class 10 */
515 #define SD_SWITCH                 6   /* adtc [31:0] See below   R1  */
516
517   /* class 5 */
518 #define SD_ERASE_WR_BLK_START    32   /* ac   [31:0] data addr   R1  */
519 #define SD_ERASE_WR_BLK_END      33   /* ac   [31:0] data addr   R1  */
520
521   /* Application commands */
522 #define SD_APP_SET_BUS_WIDTH      6   /* ac   [1:0] bus width    R1  */
523 #define SD_APP_SD_STATUS         13   /* adtc                    R1  */
524 #define SD_APP_SEND_NUM_WR_BLKS  22   /* adtc                    R1  */
525 #define SD_APP_OP_COND           41   /* bcr  [31:0] OCR         R3  */
526 #define SD_APP_SEND_SCR          51   /* adtc                    R1  */
527
528 /* OCR bit definitions */
529 #define SD_OCR_S18R     (1 << 24)    /* 1.8V switching request */
530 #define SD_ROCR_S18A        SD_OCR_S18R  /* 1.8V switching accepted by card */
531 #define SD_OCR_XPC      (1 << 28)    /* SDXC power control */
532
533 /*
534  * SD_SWITCH argument format:
535  *
536  *      [31] Check (0) or switch (1)
537  *      [30:24] Reserved (0)
538  *      [23:20] Function group 6
539  *      [19:16] Function group 5
540  *      [15:12] Function group 4
541  *      [11:8] Function group 3
542  *      [7:4] Function group 2
543  *      [3:0] Function group 1
544  */
545
546 /*
547  * SD_SEND_IF_COND argument format:
548  *
549  *  [31:12] Reserved (0)
550  *  [11:8] Host Voltage Supply Flags
551  *  [7:0] Check Pattern (0xAA)
552  */
553
554 /*
555  * SCR field definitions
556  */
557
558 #define SCR_SPEC_VER_0      0   /* Implements system specification 1.0 - 1.01 */
559 #define SCR_SPEC_VER_1      1   /* Implements system specification 1.10 */
560 #define SCR_SPEC_VER_2      2   /* Implements system specification 2.00-3.0X */
561
562 #define UNSTUFF_BITS(resp, start, size)                   \
563     ({                              \
564         const uint32_t __size = size;                \
565         const uint32_t __mask = (__size < 32 ? 1 << __size : 0) - 1; \
566         const uint32_t __off = 3 - ((start) / 32);           \
567         const uint32_t __shft = (start) & 31;            \
568         uint32_t __res;                      \
569                                     \
570         __res = resp[__off] >> __shft;              \
571         if (__size + __shft > 32)               \
572             __res |= resp[__off-1] << ((32 - __shft) % 32); \
573         __res & __mask;                     \
574     })
575
576
577 #define SD_ADDR_TO_RCA(addr)    (uint32_t)(((addr) << 16) & 0xFFFF0000)
578
579 #define BCD_TO_INT_32BIT(bcd)  ((uint32_t )((bcd) & 0xf) * 1 +  \
580                                                                 (((bcd) >> 4) & 0xf)  * 10 +      \
581                                                                 (((bcd) >> 8) & 0xf)  * 100 +     \
582                                                                 (((bcd) >> 12) & 0xf) * 1000 +   \
583                                                                 (((bcd) >> 16) & 0xf) * 10000 +   \
584                                                                 (((bcd) >> 20) & 0xf) * 100000 +  \
585                                                                 (((bcd) >> 24) & 0xf) * 1000000 + \
586                                                                 (((bcd) >> 28) & 0xf) * 10000000) \
587
588 LOG_INFOB(
589 static void dump(const char *label, uint32_t *r, size_t len)
590 {
591         ASSERT(r);
592         size_t i;
593         int j = 0;
594         kprintf("\n%s [\n", label);
595         for (i = 0; i < len; i++)
596         {
597                 if (j == 5)
598                 {
599                         kputs("\n");
600                         j = 0;
601                 }
602                 kprintf("%08lx", r[i]);
603                 j++;
604         }
605         kprintf("\n] len=%d\n\n", i);
606 }
607 )
608
609 static const uint32_t tran_exp[] = {
610     10000,      100000,     1000000,    10000000,
611     0,      0,      0,      0
612 };
613
614 static const uint8_t tran_mant[] = {
615     0,  10, 12, 13, 15, 20, 25, 30,
616     35, 40, 45, 50, 55, 60, 70, 80,
617 };
618
619 static int sd_decodeCsd(SDcsd *csd, uint32_t *resp, size_t len)
620 {
621         ASSERT(csd);
622         ASSERT(resp);
623         ASSERT(len >= 4);
624
625     csd->structure = UNSTUFF_BITS(resp, 126, 2);
626         csd->ccc = UNSTUFF_BITS(resp, 84, 12);
627
628     csd->max_data_rate  = tran_exp[UNSTUFF_BITS(resp, 96, 3)] * tran_mant[UNSTUFF_BITS(resp, 99, 4)];
629
630         /*
631          * CSD structure:
632          * - 0:
633          *              - Version 1.01-1.10
634          *              - Version 2.00/Standard Capacity
635          * - 1:
636          *              - Version 2.00/High Capacity
637          * - >1: not defined.
638          */
639
640     if (csd->structure == 0)
641         {
642                 // (C_size + 1) x 2^(C_SIZE_MUL+2)
643                 csd->blk_num = (1 + UNSTUFF_BITS(resp, 62, 12)) << (UNSTUFF_BITS(resp, 47, 3) + 2);
644
645                 csd->read_blk_bits = UNSTUFF_BITS(resp, 80, 4);
646                 csd->write_blk_bits = UNSTUFF_BITS(resp, 22, 4);
647
648                 csd->blk_len = 1 << csd->read_blk_bits;
649         csd->capacity  = csd->blk_num * csd->blk_len;
650
651         csd->read_partial = UNSTUFF_BITS(resp, 79, 1);
652         csd->read_misalign = UNSTUFF_BITS(resp, 77, 1);
653
654         csd->write_misalign = UNSTUFF_BITS(resp, 78, 1);
655         csd->write_partial = UNSTUFF_BITS(resp, 21, 1);
656
657         if (UNSTUFF_BITS(resp, 46, 1))
658                 {
659             csd->erase_size = 1;
660         }
661                 else if(csd->write_blk_bits >= 9)
662                 {
663             csd->erase_size = UNSTUFF_BITS(resp, 39, 7) + 1;
664             csd->erase_size <<= csd->write_blk_bits - 9;
665         }
666
667                 return 0;
668         }
669         else if (csd->structure == 1)
670         {
671                 kprintf("csize %ld\n", UNSTUFF_BITS(resp, 48, 22));
672         csd->capacity  = (1 + UNSTUFF_BITS(resp, 48, 22)) << 10;
673
674                 csd->write_blk_bits = 9;
675                 csd->write_partial = 0;
676         csd->write_misalign = 0;
677
678                 csd->read_blk_bits = 9;
679                 csd->read_partial = 0;
680         csd->read_misalign = 0;
681
682         csd->erase_size = 1;
683                 // the block size if fixed to 512kb
684                 csd->blk_len = (1 << csd->write_blk_bits) << 10;
685
686         return 0;
687         }
688     else
689         {
690         kprintf("Unrecognised CSD structure version %d\n", csd->structure);
691         return -1;
692     }
693
694     return 0;
695 }
696
697
698 void sd_dumpCsd(Sd *sd)
699 {
700         ASSERT(sd);
701
702         LOG_INFO("VERSION: %d.0\n", sd->csd.structure ? 2 : 1);
703     LOG_INFO("CARD COMMAND CLASS: %d\n", sd->csd.ccc);
704         LOG_INFO("MAX DATA RATE: %ld\n", sd->csd.max_data_rate);
705         LOG_INFO("WRITE BLK LEN BITS: %ld\n", sd->csd.write_blk_bits);
706         LOG_INFO("READ BLK LEN BITS: %ld\n", sd->csd.read_blk_bits);
707         LOG_INFO("ERASE SIZE: %ld\n", sd->csd.erase_size);
708         LOG_INFO("BLK NUM: %ld\n", sd->csd.blk_num);
709         LOG_INFO("BLK LEN: %ld\n", sd->csd.blk_len);
710         LOG_INFO("CAPACITY %ld\n", sd->csd.capacity);
711         LOG_INFO("FLAG Write: WP %d, W MISALIGN %d\n", sd->csd.write_partial, sd->csd.write_misalign);
712         LOG_INFO("FLAG Read: RP %d, R MISALIGN %d\n", sd->csd.read_partial, sd->csd.read_misalign);
713
714 }
715
716 void sd_dumpCid(Sd *sd)
717 {
718         ASSERT(sd);
719
720         LOG_INFO("MANFID: %d\n", sd->cid.manfid);
721     LOG_INFO("OEMID: %d\n", sd->cid.oemid);
722         LOG_INFO("SERIAL: %ld\n", sd->cid.serial);
723     LOG_INFO("PROD_NAME: %s\n", sd->cid.prod_name);
724     LOG_INFO("REV: %d.%d\n", sd->cid.m_rev, sd->cid.l_rev);
725     LOG_INFO("OFF,Y,M: %lx, %ld %ld\n", sd->cid.year_off, (BCD_TO_INT_32BIT(sd->cid.year_off) / 12) + 2000,
726                                                                                                 (BCD_TO_INT_32BIT(sd->cid.year_off) % 12));
727 }
728
729 void sd_dumpSsr(Sd *sd)
730 {
731         ASSERT(sd);
732
733         LOG_INFO("BUS_WIDTH: %d\n", sd->ssr.bus_width);
734     LOG_INFO("TYPE: %d\n", sd->ssr.card_type);
735         LOG_INFO("AU_TYPE: %d\n", sd->ssr.au_size);
736         LOG_INFO("ERASE_SIZE: %d\n", sd->ssr.erase_size);
737         LOG_INFO("SPEED_CLASS: %d\n", sd->ssr.speed_class);
738 }
739
740
741 void sd_sendInit(void)
742 {
743         hsmci_init(NULL); //TODO: REMOVE IT!
744
745         if (hsmci_sendCmd(0, 0, HSMCI_CMDR_SPCMD_INIT | HSMCI_CMDR_RSPTYP_NORESP))
746                 LOG_ERR("INIT: %lx\n", HSMCI_SR);
747 }
748
749
750 void sd_goIdle(void)
751 {
752         hsmci_setSpeed(HSMCI_INIT_SPEED, false);
753         if (hsmci_sendCmd(0, 0, HSMCI_CMDR_RSPTYP_NORESP))
754                 LOG_ERR("GO_IDLE: %lx\n", HSMCI_SR);
755 }
756
757 int sd_sendIfCond(void)
758 {
759         if (hsmci_sendCmd(8, CMD8_V_RANGE_27V_36V, HSMCI_CMDR_RSPTYP_48_BIT))
760         {
761                 LOG_ERR("IF_COND %lx\n", HSMCI_SR);
762                 return -1;
763         }
764         else
765         {
766                 uint32_t r = HSMCI_RSPR;
767                 if ((r & 0xFFF) == CMD8_V_RANGE_27V_36V)
768                 {
769                         LOG_INFO("IF_COND: %lx\n", r);
770                         return 0;
771                 }
772                 LOG_ERR("IF_COND: %lx\n", r);
773         }
774         return -1;
775 }
776
777 int sd_sendAppOpCond(void)
778 {
779         if (hsmci_sendCmd(55, 0, HSMCI_CMDR_RSPTYP_48_BIT))
780         {
781                 LOG_ERR("APP_CMD %lx\n", HSMCI_SR);
782                 return -1;
783         }
784         else
785         {
786                 LOG_INFO("APP_CMD %lx\n", HSMCI_RSPR);
787         }
788
789         if (hsmci_sendCmd(41, SD_HOST_VOLTAGE_RANGE | SD_OCR_CCS, HSMCI_CMDR_RSPTYP_48_BIT))// se cmd 8 va ok.
790         {
791                 LOG_ERR("APP_OP_COND %lx\n", HSMCI_SR);
792                 return -1;
793         }
794         else
795         {
796                 uint32_t status = HSMCI_RSPR;
797                 if (status & SD_OCR_BUSY)
798                 {
799                         LOG_INFO("SD power up! Hight Capability [%d]\n", (bool)(status & SD_OCR_CCS));
800                         return 0;
801                 }
802
803                 LOG_ERR("sd not ready.\n");
804         }
805
806         return -1;
807 }
808
809
810 int sd_getCid(Sd *sd, uint32_t addr, uint8_t flag)
811 {
812         ASSERT(sd);
813         memset(&(sd->cid), 0, sizeof(SDcid));
814
815         uint8_t idx = 9; // CMD9 get cid from gived sd address (RCA)
816         if (flag & SD_SEND_ALL_CID)
817                 idx = 2;
818
819
820         if (hsmci_sendCmd(idx, SD_ADDR_TO_RCA(addr), HSMCI_CMDR_RSPTYP_136_BIT))
821         {
822                 LOG_ERR("GET_CID %lx\n", HSMCI_SR);
823                 return -1;
824         }
825         else
826         {
827                 uint32_t resp[4];
828                 hsmci_readResp(resp, 4);
829                 LOG_INFOB(dump("CID", resp, 4););
830
831                 sd->cid.manfid        = UNSTUFF_BITS(resp, 120, 8);
832                 sd->cid.oemid         = UNSTUFF_BITS(resp, 104, 16);
833                 sd->cid.prod_name[0]      = UNSTUFF_BITS(resp, 96, 8);
834                 sd->cid.prod_name[1]      = UNSTUFF_BITS(resp, 88, 8);
835                 sd->cid.prod_name[2]      = UNSTUFF_BITS(resp, 80, 8);
836                 sd->cid.prod_name[3]      = UNSTUFF_BITS(resp, 72, 8);
837                 sd->cid.prod_name[4]      = UNSTUFF_BITS(resp, 64, 8);
838                 sd->cid.m_rev         = UNSTUFF_BITS(resp, 60, 4);
839                 sd->cid.l_rev         = UNSTUFF_BITS(resp, 56, 4);
840                 sd->cid.serial        = (uint32_t)UNSTUFF_BITS(resp, 24, 32);
841                 sd->cid.year_off      = UNSTUFF_BITS(resp, 8, 12);
842         }
843
844         return 0;
845 }
846
847 int sd_getCsd(Sd *sd)
848 {
849         ASSERT(sd);
850         memset(&(sd->csd), 0, sizeof(SDcsd));
851
852         LOG_INFO("Send to RCA: %lx\n", SD_ADDR_TO_RCA(sd->addr));
853         if (hsmci_sendCmd(9, SD_ADDR_TO_RCA(sd->addr), HSMCI_CMDR_RSPTYP_136_BIT))
854         {
855                 LOG_ERR("GET_CSD %lx\n", HSMCI_SR);
856                 return -1;
857         }
858         else
859         {
860                 uint32_t resp[4];
861                 hsmci_readResp(resp, 4);
862                 LOG_INFOB(dump("CSD", resp, 4););
863                 sd_decodeCsd(&(sd->csd), resp, 4);
864         }
865
866         return 0;
867 }
868
869 int sd_getRelativeAddr(Sd *sd)
870 {
871         ASSERT(sd);
872         if (hsmci_sendCmd(3, 0, HSMCI_CMDR_RSPTYP_48_BIT))
873         {
874                 LOG_ERR("RCA: %lx\n", HSMCI_SR);
875                 return -1;
876         }
877
878         hsmci_readResp(&sd->addr, 1);
879         sd->addr = sd->addr >> 16;
880
881         LOG_INFOB(dump("RCA", &sd->addr, 1););
882
883         return 0;
884 }
885
886 #define SD_STATUS_APP_CMD      BV(5)
887 #define SD_STATUS_READY        BV(8)
888 #define SD_STATUS_CURR_MASK    0x1E00
889 #define SD_STATUS_CURR_SHIFT   9
890
891 #define SD_GET_STATE(status)    (uint8_t)(((status) & SD_STATUS_CURR_MASK) >> SD_STATUS_CURR_SHIFT)
892
893 int sd_appStatus(Sd *sd)
894 {
895         ASSERT(sd);
896         LOG_INFO("Send to RCA: %lx\n", SD_ADDR_TO_RCA(sd->addr));
897         if (hsmci_sendCmd(13, SD_ADDR_TO_RCA(sd->addr), HSMCI_CMDR_RSPTYP_48_BIT))
898         {
899                 LOG_ERR("STATUS: %lx\n", HSMCI_SR);
900                 return -1;
901         }
902
903         hsmci_readResp(&(sd->status), 1);
904         LOG_INFOB(dump("STATUS", &(sd->status), 1););
905
906         LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
907
908         if (sd->status & SD_STATUS_READY)
909                 return 0;
910
911         return -1;
912 }
913
914
915 INLINE int sd_cardSelection(Sd *sd, size_t rca)
916 {
917         ASSERT(sd);
918         LOG_INFO("Select RCA: %lx\n", SD_ADDR_TO_RCA(sd->addr));
919         if (hsmci_sendCmd(7, rca, HSMCI_CMDR_RSPTYP_R1B))
920         {
921                 LOG_ERR("SELECT_SD: %lx\n", HSMCI_SR);
922                 return -1;
923         }
924
925         HSMCI_CHECK_BUSY();
926         hsmci_readResp(&(sd->status), 1);
927         LOG_INFOB(dump("SELECT_SD", &(sd->status), 1););
928
929         LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
930
931         if (sd->status & SD_STATUS_READY)
932                 return 0;
933
934         return -1;
935 }
936
937 int sd_selectCard(Sd *sd)
938 {
939         return sd_cardSelection(sd, SD_ADDR_TO_RCA(sd->addr));
940 }
941
942 int sd_deSelectCard(Sd *sd)
943 {
944         uint32_t rca = 0;
945         if (!sd->addr)
946                 rca = SD_ADDR_TO_RCA(sd->addr + 1);
947
948         return sd_cardSelection(sd, rca);
949 }
950
951
952 int sd_setBusWidth(Sd *sd, size_t len)
953 {
954         ASSERT(sd);
955
956         if (hsmci_sendCmd(55, SD_ADDR_TO_RCA(sd->addr), HSMCI_CMDR_RSPTYP_48_BIT))
957         {
958                 LOG_ERR("APP_CMD %lx\n", HSMCI_SR);
959                 return -1;
960         }
961
962         uint32_t status = HSMCI_RSPR;
963         if (status & (SD_STATUS_APP_CMD | SD_STATUS_READY))
964         {
965                 hsmci_setBusWidth(len);
966
967                 uint8_t arg = 0;
968                 if (len == 4)
969                         arg = 2;
970
971                 if (hsmci_sendCmd(6, arg, HSMCI_CMDR_RSPTYP_48_BIT))
972                 {
973                         LOG_ERR("SET_BUS_WIDTH CMD: %lx\n", HSMCI_SR);
974                         return -1;
975                 }
976
977                 hsmci_readResp(&(sd->status), 1);
978
979                 LOG_INFOB(dump("SET_BUS_WIDTH", &(sd->status), 1););
980                 LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
981
982                 if (sd->status & SD_STATUS_READY)
983                         return 0;
984         }
985
986         LOG_ERR("SET_BUS_WIDTH REP %lx\n", status);
987         return -1;
988 }
989
990
991 int sd_set_BlockLen(Sd *sd, size_t len)
992 {
993         ASSERT(sd);
994
995         if (hsmci_sendCmd(16, len, HSMCI_CMDR_RSPTYP_48_BIT))
996         {
997                 LOG_ERR("SET_BLK_LEN: %lx\n", HSMCI_SR);
998                 return -1;
999         }
1000
1001         hsmci_readResp(&(sd->status), 1);
1002
1003         LOG_INFOB(dump("SET_BLK_LEN", &(sd->status), 1););
1004         LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
1005
1006         sd->csd.blk_len = len;
1007
1008         if (sd->status & SD_STATUS_READY)
1009                 return 0;
1010
1011         return -1;
1012 }
1013
1014 int sd_getStatus(Sd *sd, uint32_t *buf, size_t words)
1015 {
1016         ASSERT(sd);
1017
1018         // Status reply with 512bit data, so the block size in byte is 64
1019         hsmci_prgRxDMA(buf, words, 64);
1020
1021         if (hsmci_sendCmd(55, SD_ADDR_TO_RCA(sd->addr), HSMCI_CMDR_RSPTYP_48_BIT))
1022         {
1023                 LOG_ERR("APP_CMD %lx\n", HSMCI_SR);
1024                 return -1;
1025         }
1026
1027         uint32_t status = HSMCI_RSPR;
1028         if (status & (SD_STATUS_APP_CMD | SD_STATUS_READY))
1029         {
1030                 if (hsmci_sendCmd(13, 0, HSMCI_CMDR_RSPTYP_48_BIT |
1031                                 BV(HSMCI_CMDR_TRDIR) | HSMCI_CMDR_TRCMD_START_DATA | HSMCI_CMDR_TRTYP_SINGLE))
1032                 {
1033                         LOG_ERR("STATUS CMD: %lx\n", HSMCI_SR);
1034                         return -1;
1035                 }
1036
1037                 hsmci_readResp(&(sd->status), 1);
1038                 LOG_INFOB(dump("STATUS", &(sd->status), 1););
1039                 LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
1040
1041                 if (sd->status & SD_STATUS_READY)
1042                 {
1043                         hsmci_waitTransfer();
1044
1045                         LOG_INFOB(dump("STATUS", buf, words););
1046                         memset(&(sd->ssr), 0, sizeof(SDssr));
1047
1048                         sd->ssr.bus_width  = UNSTUFF_BITS(buf, 510, 2);
1049                         sd->ssr.card_type  = UNSTUFF_BITS(buf, 480, 16);
1050                         sd->ssr.au_size  = UNSTUFF_BITS(buf, 432, 8);
1051                         sd->ssr.speed_class  = UNSTUFF_BITS(buf, 440, 8);
1052                         sd->ssr.erase_size = UNSTUFF_BITS(buf, 408, 24);
1053
1054                         return 0;
1055                 }
1056         }
1057
1058         return -1;
1059 }
1060
1061
1062
1063 int sd_readSingleBlock(Sd *sd, size_t index, uint32_t *buf, size_t words)
1064 {
1065         ASSERT(sd);
1066         ASSERT(buf);
1067
1068         hsmci_prgRxDMA(buf, words, sd->csd.blk_len);
1069
1070         if (hsmci_sendCmd(17, index * sd->csd.blk_len, HSMCI_CMDR_RSPTYP_48_BIT |
1071                         BV(HSMCI_CMDR_TRDIR) | HSMCI_CMDR_TRCMD_START_DATA | HSMCI_CMDR_TRTYP_SINGLE))
1072         {
1073                 LOG_ERR("SIGLE_BLK_READ: %lx\n", HSMCI_SR);
1074                 return -1;
1075         }
1076         hsmci_readResp(&(sd->status), 1);
1077
1078         LOG_INFOB(dump("SIGLE_BLK_READ", &(sd->status), 1););
1079         LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
1080
1081         if (sd->status & SD_STATUS_READY)
1082         {
1083                 hsmci_waitTransfer();
1084                 LOG_INFOB(dump("BLK", buf, words););
1085
1086                 return words;
1087         }
1088
1089         return -1;
1090 }
1091
1092
1093 int sd_writeSingleBlock(Sd *sd, size_t index, uint32_t *buf, size_t words)
1094 {
1095         ASSERT(sd);
1096         ASSERT(buf);
1097
1098         hsmci_prgTxDMA(buf, words, sd->csd.blk_len);
1099
1100         if (hsmci_sendCmd(24, index * sd->csd.blk_len, HSMCI_CMDR_RSPTYP_48_BIT |
1101                                                 HSMCI_CMDR_TRCMD_START_DATA | HSMCI_CMDR_TRTYP_SINGLE))
1102         {
1103                 LOG_ERR("SIGLE_BLK_WRITE: %lx\n", HSMCI_SR);
1104                 return -1;
1105         }
1106         hsmci_readResp(&(sd->status), 1);
1107
1108         LOG_INFOB(dump("SIGLE_BLK_WR", &(sd->status), 1););
1109         LOG_INFO("State[%d]\n", SD_GET_STATE(sd->status));
1110
1111         if (sd->status & SD_STATUS_READY)
1112         {
1113                 hsmci_waitTransfer();
1114                 LOG_INFOB(dump("BLK", buf, words););
1115
1116                 return words;
1117         }
1118
1119         return -1;
1120 }
1121
1122
1123
1124 void sd_setHightSpeed(Sd *sd)
1125 {
1126         (void)sd;
1127         hsmci_setSpeed(2100000, true);
1128 }
1129
1130
1131 #endif
1132
1133
1134 bool sd_initUnbuf(Sd *sd, KFile *ch)
1135 {
1136         if (sd_blockInit(sd, ch))
1137         {
1138                 sd->b.priv.vt = &sd_unbuffered_vt;
1139                 return true;
1140         }
1141         else
1142                 return false;
1143 }
1144
1145 static uint8_t sd_buf[SD_DEFAULT_BLOCKLEN];
1146
1147 bool sd_initBuf(Sd *sd, KFile *ch)
1148 {
1149         if (sd_blockInit(sd, ch))
1150         {
1151                 sd->b.priv.buf = sd_buf;
1152                 sd->b.priv.flags |= KB_BUFFERED | KB_PARTIAL_WRITE;
1153                 sd->b.priv.vt = &sd_buffered_vt;
1154                 sd->b.priv.vt->load(&sd->b, 0);
1155                 return true;
1156         }
1157         else
1158                 return false;
1159 }
1160
1161
1162