i2cm: fix configuration for this hardware
[protos/imu.git] / sd_raw.c
1
2 /*
3  * Copyright (c) 2006-2012 by Roland Riegel <feedback@roland-riegel.de>
4  *
5  * This file is free software; you can redistribute it and/or modify
6  * it under the terms of either the GNU General Public License version 2
7  * or the GNU Lesser General Public License version 2.1, both as
8  * published by the Free Software Foundation.
9  */
10
11 #include <string.h>
12 #include <avr/pgmspace.h>
13 #include <avr/io.h>
14 #include "sd_raw.h"
15
16 #include <uart.h>
17
18 /**
19  * \addtogroup sd_raw MMC/SD/SDHC card raw access
20  *
21  * This module implements read and write access to MMC, SD
22  * and SDHC cards. It serves as a low-level driver for the
23  * higher level modules such as partition and file system
24  * access.
25  *
26  * @{
27  */
28 /**
29  * \file
30  * MMC/SD/SDHC raw access implementation (license: GPLv2 or LGPLv2.1)
31  *
32  * \author Roland Riegel
33  */
34
35 /**
36  * \addtogroup sd_raw_config MMC/SD configuration
37  * Preprocessor defines to configure the MMC/SD support.
38  */
39
40 /**
41  * @}
42  */
43
44 /* commands available in SPI mode */
45
46 /* CMD0: response R1 */
47 #define CMD_GO_IDLE_STATE 0x00
48 /* CMD1: response R1 */
49 #define CMD_SEND_OP_COND 0x01
50 /* CMD8: response R7 */
51 #define CMD_SEND_IF_COND 0x08
52 /* CMD9: response R1 */
53 #define CMD_SEND_CSD 0x09
54 /* CMD10: response R1 */
55 #define CMD_SEND_CID 0x0a
56 /* CMD12: response R1 */
57 #define CMD_STOP_TRANSMISSION 0x0c
58 /* CMD13: response R2 */
59 #define CMD_SEND_STATUS 0x0d
60 /* CMD16: arg0[31:0]: block length, response R1 */
61 #define CMD_SET_BLOCKLEN 0x10
62 /* CMD17: arg0[31:0]: data address, response R1 */
63 #define CMD_READ_SINGLE_BLOCK 0x11
64 /* CMD18: arg0[31:0]: data address, response R1 */
65 #define CMD_READ_MULTIPLE_BLOCK 0x12
66 /* CMD24: arg0[31:0]: data address, response R1 */
67 #define CMD_WRITE_SINGLE_BLOCK 0x18
68 /* CMD25: arg0[31:0]: data address, response R1 */
69 #define CMD_WRITE_MULTIPLE_BLOCK 0x19
70 /* CMD27: response R1 */
71 #define CMD_PROGRAM_CSD 0x1b
72 /* CMD28: arg0[31:0]: data address, response R1b */
73 #define CMD_SET_WRITE_PROT 0x1c
74 /* CMD29: arg0[31:0]: data address, response R1b */
75 #define CMD_CLR_WRITE_PROT 0x1d
76 /* CMD30: arg0[31:0]: write protect data address, response R1 */
77 #define CMD_SEND_WRITE_PROT 0x1e
78 /* CMD32: arg0[31:0]: data address, response R1 */
79 #define CMD_TAG_SECTOR_START 0x20
80 /* CMD33: arg0[31:0]: data address, response R1 */
81 #define CMD_TAG_SECTOR_END 0x21
82 /* CMD34: arg0[31:0]: data address, response R1 */
83 #define CMD_UNTAG_SECTOR 0x22
84 /* CMD35: arg0[31:0]: data address, response R1 */
85 #define CMD_TAG_ERASE_GROUP_START 0x23
86 /* CMD36: arg0[31:0]: data address, response R1 */
87 #define CMD_TAG_ERASE_GROUP_END 0x24
88 /* CMD37: arg0[31:0]: data address, response R1 */
89 #define CMD_UNTAG_ERASE_GROUP 0x25
90 /* CMD38: arg0[31:0]: stuff bits, response R1b */
91 #define CMD_ERASE 0x26
92 /* ACMD41: arg0[31:0]: OCR contents, response R1 */
93 #define CMD_SD_SEND_OP_COND 0x29
94 /* CMD42: arg0[31:0]: stuff bits, response R1b */
95 #define CMD_LOCK_UNLOCK 0x2a
96 /* CMD55: arg0[31:0]: stuff bits, response R1 */
97 #define CMD_APP 0x37
98 /* CMD58: arg0[31:0]: stuff bits, response R3 */
99 #define CMD_READ_OCR 0x3a
100 /* CMD59: arg0[31:1]: stuff bits, arg0[0:0]: crc option, response R1 */
101 #define CMD_CRC_ON_OFF 0x3b
102
103 /* command responses */
104 /* R1: size 1 byte */
105 #define R1_IDLE_STATE 0
106 #define R1_ERASE_RESET 1
107 #define R1_ILL_COMMAND 2
108 #define R1_COM_CRC_ERR 3
109 #define R1_ERASE_SEQ_ERR 4
110 #define R1_ADDR_ERR 5
111 #define R1_PARAM_ERR 6
112 /* R1b: equals R1, additional busy bytes */
113 /* R2: size 2 bytes */
114 #define R2_CARD_LOCKED 0
115 #define R2_WP_ERASE_SKIP 1
116 #define R2_ERR 2
117 #define R2_CARD_ERR 3
118 #define R2_CARD_ECC_FAIL 4
119 #define R2_WP_VIOLATION 5
120 #define R2_INVAL_ERASE 6
121 #define R2_OUT_OF_RANGE 7
122 #define R2_CSD_OVERWRITE 7
123 #define R2_IDLE_STATE (R1_IDLE_STATE + 8)
124 #define R2_ERASE_RESET (R1_ERASE_RESET + 8)
125 #define R2_ILL_COMMAND (R1_ILL_COMMAND + 8)
126 #define R2_COM_CRC_ERR (R1_COM_CRC_ERR + 8)
127 #define R2_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 8)
128 #define R2_ADDR_ERR (R1_ADDR_ERR + 8)
129 #define R2_PARAM_ERR (R1_PARAM_ERR + 8)
130 /* R3: size 5 bytes */
131 #define R3_OCR_MASK (0xffffffffUL)
132 #define R3_IDLE_STATE (R1_IDLE_STATE + 32)
133 #define R3_ERASE_RESET (R1_ERASE_RESET + 32)
134 #define R3_ILL_COMMAND (R1_ILL_COMMAND + 32)
135 #define R3_COM_CRC_ERR (R1_COM_CRC_ERR + 32)
136 #define R3_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 32)
137 #define R3_ADDR_ERR (R1_ADDR_ERR + 32)
138 #define R3_PARAM_ERR (R1_PARAM_ERR + 32)
139 /* Data Response: size 1 byte */
140 #define DR_STATUS_MASK 0x0e
141 #define DR_STATUS_ACCEPTED 0x05
142 #define DR_STATUS_CRC_ERR 0x0a
143 #define DR_STATUS_WRITE_ERR 0x0c
144
145 /* status bits for card types */
146 #define SD_RAW_SPEC_1 0
147 #define SD_RAW_SPEC_2 1
148 #define SD_RAW_SPEC_SDHC 2
149
150 #if !SD_RAW_SAVE_RAM
151 /* static data buffer for acceleration */
152 static uint8_t raw_block[512];
153 /* offset where the data within raw_block lies on the card */
154 static offset_t raw_block_address;
155 #if SD_RAW_WRITE_BUFFERING
156 /* flag to remember if raw_block was written to the card */
157 static uint8_t raw_block_written;
158 #endif
159 #endif
160
161 /* card type state */
162 static uint8_t sd_raw_card_type;
163
164 /* private helper functions */
165 static void sd_raw_send_byte(uint8_t b);
166 static uint8_t sd_raw_rec_byte(void);
167 static uint8_t sd_raw_send_command(uint8_t command, uint32_t arg);
168
169 /**
170  * \ingroup sd_raw
171  * Initializes memory card communication.
172  *
173  * \returns 0 on failure, 1 on success.
174  */
175 uint8_t sd_raw_init(void)
176 {
177     /* enable inputs for reading card status */
178     configure_pin_available();
179     configure_pin_locked();
180
181     /* enable outputs for MOSI, SCK, SS, input for MISO */
182     configure_pin_mosi();
183     configure_pin_sck();
184     configure_pin_ss();
185     configure_pin_miso();
186
187     unselect_card();
188
189     /* initialize SPI with lowest frequency; max. 400kHz during identification mode of card */
190     SPCR = (0 << SPIE) | /* SPI Interrupt Enable */
191            (1 << SPE)  | /* SPI Enable */
192            (0 << DORD) | /* Data Order: MSB first */
193            (1 << MSTR) | /* Master mode */
194            (0 << CPOL) | /* Clock Polarity: SCK low when idle */
195            (0 << CPHA) | /* Clock Phase: sample on rising SCK edge */
196            (1 << SPR1) | /* Clock Frequency: f_OSC / 128 */
197            (1 << SPR0);
198     SPSR &= ~(1 << SPI2X); /* No doubled clock frequency */
199
200     /* initialization procedure */
201     sd_raw_card_type = 0;
202
203     if(!sd_raw_available())
204         return 0;
205
206     /* card needs 74 cycles minimum to start up */
207     for(uint8_t i = 0; i < 10; ++i)
208     {
209         /* wait 8 clock cycles */
210         sd_raw_rec_byte();
211     }
212
213     /* address card */
214     select_card();
215
216     /* reset card */
217     uint8_t response;
218     for(uint16_t i = 0; ; ++i)
219     {
220         response = sd_raw_send_command(CMD_GO_IDLE_STATE, 0);
221         if(response == (1 << R1_IDLE_STATE))
222             break;
223
224         if(i == 0x1ff)
225         {
226             unselect_card();
227             return 0;
228         }
229     }
230
231 #if SD_RAW_SDHC
232     /* check for version of SD card specification */
233     response = sd_raw_send_command(CMD_SEND_IF_COND, 0x100 /* 2.7V - 3.6V */ | 0xaa /* test pattern */);
234     if((response & (1 << R1_ILL_COMMAND)) == 0)
235     {
236         sd_raw_rec_byte();
237         sd_raw_rec_byte();
238         if((sd_raw_rec_byte() & 0x01) == 0)
239             return 0; /* card operation voltage range doesn't match */
240         if(sd_raw_rec_byte() != 0xaa)
241             return 0; /* wrong test pattern */
242
243         /* card conforms to SD 2 card specification */
244         sd_raw_card_type |= (1 << SD_RAW_SPEC_2);
245     }
246     else
247 #endif
248     {
249         /* determine SD/MMC card type */
250         sd_raw_send_command(CMD_APP, 0);
251         response = sd_raw_send_command(CMD_SD_SEND_OP_COND, 0);
252         if((response & (1 << R1_ILL_COMMAND)) == 0)
253         {
254             /* card conforms to SD 1 card specification */
255             sd_raw_card_type |= (1 << SD_RAW_SPEC_1);
256         }
257         else
258         {
259             /* MMC card */
260         }
261     }
262
263     /* wait for card to get ready */
264     for(uint16_t i = 0; ; ++i)
265     {
266         if(sd_raw_card_type & ((1 << SD_RAW_SPEC_1) | (1 << SD_RAW_SPEC_2)))
267         {
268             uint32_t arg = 0;
269 #if SD_RAW_SDHC
270             if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
271                 arg = 0x40000000;
272 #endif
273             sd_raw_send_command(CMD_APP, 0);
274             response = sd_raw_send_command(CMD_SD_SEND_OP_COND, arg);
275         }
276         else
277         {
278             response = sd_raw_send_command(CMD_SEND_OP_COND, 0);
279         }
280
281         if((response & (1 << R1_IDLE_STATE)) == 0)
282             break;
283
284         if(i == 0x7fff)
285         {
286             unselect_card();
287             return 0;
288         }
289     }
290
291 #if SD_RAW_SDHC
292     if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
293     {
294         if(sd_raw_send_command(CMD_READ_OCR, 0))
295         {
296             unselect_card();
297             return 0;
298         }
299
300         if(sd_raw_rec_byte() & 0x40)
301             sd_raw_card_type |= (1 << SD_RAW_SPEC_SDHC);
302
303         sd_raw_rec_byte();
304         sd_raw_rec_byte();
305         sd_raw_rec_byte();
306     }
307 #endif
308
309     /* set block size to 512 bytes */
310     if(sd_raw_send_command(CMD_SET_BLOCKLEN, 512))
311     {
312         unselect_card();
313         return 0;
314     }
315
316     /* deaddress card */
317     unselect_card();
318
319     /* switch to highest SPI frequency possible */
320     SPCR &= ~((1 << SPR1) | (1 << SPR0)); /* Clock Frequency: f_OSC / 4 */
321     SPSR |= (1 << SPI2X); /* Doubled Clock Frequency: f_OSC / 2 */
322
323 #if !SD_RAW_SAVE_RAM
324     /* the first block is likely to be accessed first, so precache it here */
325     raw_block_address = (offset_t) -1;
326 #if SD_RAW_WRITE_BUFFERING
327     raw_block_written = 1;
328 #endif
329     if(!sd_raw_read(0, raw_block, sizeof(raw_block)))
330         return 0;
331 #endif
332
333     return 1;
334 }
335
336 /**
337  * \ingroup sd_raw
338  * Checks wether a memory card is located in the slot.
339  *
340  * \returns 1 if the card is available, 0 if it is not.
341  */
342 uint8_t sd_raw_available()
343 {
344     return get_pin_available() == 0x00;
345 }
346
347 /**
348  * \ingroup sd_raw
349  * Checks wether the memory card is locked for write access.
350  *
351  * \returns 1 if the card is locked, 0 if it is not.
352  */
353 uint8_t sd_raw_locked()
354 {
355     return get_pin_locked() == 0x00;
356 }
357
358 /**
359  * \ingroup sd_raw
360  * Sends a raw byte to the memory card.
361  *
362  * \param[in] b The byte to sent.
363  * \see sd_raw_rec_byte
364  */
365 void sd_raw_send_byte(uint8_t b)
366 {
367     SPDR = b;
368     /* wait for byte to be shifted out */
369     while(!(SPSR & (1 << SPIF)));
370     SPSR &= ~(1 << SPIF);
371 }
372
373 /**
374  * \ingroup sd_raw
375  * Receives a raw byte from the memory card.
376  *
377  * \returns The byte which should be read.
378  * \see sd_raw_send_byte
379  */
380 uint8_t sd_raw_rec_byte()
381 {
382     /* send dummy data for receiving some */
383     SPDR = 0xff;
384     while(!(SPSR & (1 << SPIF)));
385     SPSR &= ~(1 << SPIF);
386
387     return SPDR;
388 }
389
390 /**
391  * \ingroup sd_raw
392  * Send a command to the memory card which responses with a R1 response (and possibly others).
393  *
394  * \param[in] command The command to send.
395  * \param[in] arg The argument for command.
396  * \returns The command answer.
397  */
398 uint8_t sd_raw_send_command(uint8_t command, uint32_t arg)
399 {
400     uint8_t response;
401
402     /* wait some clock cycles */
403     sd_raw_rec_byte();
404
405     /* send command via SPI */
406     sd_raw_send_byte(0x40 | command);
407     sd_raw_send_byte((arg >> 24) & 0xff);
408     sd_raw_send_byte((arg >> 16) & 0xff);
409     sd_raw_send_byte((arg >> 8) & 0xff);
410     sd_raw_send_byte((arg >> 0) & 0xff);
411     switch(command)
412     {
413         case CMD_GO_IDLE_STATE:
414            sd_raw_send_byte(0x95);
415            break;
416         case CMD_SEND_IF_COND:
417            sd_raw_send_byte(0x87);
418            break;
419         default:
420            sd_raw_send_byte(0xff);
421            break;
422     }
423
424     /* receive response */
425     for(uint8_t i = 0; i < 10; ++i)
426     {
427         response = sd_raw_rec_byte();
428         if(response != 0xff)
429             break;
430     }
431
432     return response;
433 }
434
435 /**
436  * \ingroup sd_raw
437  * Reads raw data from the card.
438  *
439  * \param[in] offset The offset from which to read.
440  * \param[out] buffer The buffer into which to write the data.
441  * \param[in] length The number of bytes to read.
442  * \returns 0 on failure, 1 on success.
443  * \see sd_raw_read_interval, sd_raw_write, sd_raw_write_interval
444  */
445 uint8_t sd_raw_read(offset_t offset, uint8_t* buffer, uintptr_t length)
446 {
447     offset_t block_address;
448     uint16_t block_offset;
449     uint16_t read_length;
450     while(length > 0)
451     {
452         /* determine byte count to read at once */
453         block_offset = offset & 0x01ff;
454         block_address = offset - block_offset;
455         read_length = 512 - block_offset; /* read up to block border */
456         if(read_length > length)
457             read_length = length;
458
459 #if !SD_RAW_SAVE_RAM
460         /* check if the requested data is cached */
461         if(block_address != raw_block_address)
462 #endif
463         {
464 #if SD_RAW_WRITE_BUFFERING
465             if(!sd_raw_sync())
466                 return 0;
467 #endif
468
469             /* address card */
470             select_card();
471
472             /* send single block request */
473 #if SD_RAW_SDHC
474             if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
475 #else
476             if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, block_address))
477 #endif
478             {
479                 unselect_card();
480                 return 0;
481             }
482
483             /* wait for data block (start byte 0xfe) */
484             while(sd_raw_rec_byte() != 0xfe);
485
486 #if SD_RAW_SAVE_RAM
487             /* read byte block */
488             uint16_t read_to = block_offset + read_length;
489             for(uint16_t i = 0; i < 512; ++i)
490             {
491                 uint8_t b = sd_raw_rec_byte();
492                 if(i >= block_offset && i < read_to)
493                     *buffer++ = b;
494             }
495 #else
496             /* read byte block */
497             uint8_t* cache = raw_block;
498             for(uint16_t i = 0; i < 512; ++i)
499                 *cache++ = sd_raw_rec_byte();
500             raw_block_address = block_address;
501
502             memcpy(buffer, raw_block + block_offset, read_length);
503             buffer += read_length;
504 #endif
505
506             /* read crc16 */
507             sd_raw_rec_byte();
508             sd_raw_rec_byte();
509
510             /* deaddress card */
511             unselect_card();
512
513             /* let card some time to finish */
514             sd_raw_rec_byte();
515         }
516 #if !SD_RAW_SAVE_RAM
517         else
518         {
519             /* use cached data */
520             memcpy(buffer, raw_block + block_offset, read_length);
521             buffer += read_length;
522         }
523 #endif
524
525         length -= read_length;
526         offset += read_length;
527     }
528
529     return 1;
530 }
531
532 /**
533  * \ingroup sd_raw
534  * Continuously reads units of \c interval bytes and calls a callback function.
535  *
536  * This function starts reading at the specified offset. Every \c interval bytes,
537  * it calls the callback function with the associated data buffer.
538  *
539  * By returning zero, the callback may stop reading.
540  *
541  * \note Within the callback function, you can not start another read or
542  *       write operation.
543  * \note This function only works if the following conditions are met:
544  *       - (offset - (offset % 512)) % interval == 0
545  *       - length % interval == 0
546  *
547  * \param[in] offset Offset from which to start reading.
548  * \param[in] buffer Pointer to a buffer which is at least interval bytes in size.
549  * \param[in] interval Number of bytes to read before calling the callback function.
550  * \param[in] length Number of bytes to read altogether.
551  * \param[in] callback The function to call every interval bytes.
552  * \param[in] p An opaque pointer directly passed to the callback function.
553  * \returns 0 on failure, 1 on success
554  * \see sd_raw_write_interval, sd_raw_read, sd_raw_write
555  */
556 uint8_t sd_raw_read_interval(offset_t offset, uint8_t* buffer, uintptr_t interval, uintptr_t length, sd_raw_read_interval_handler_t callback, void* p)
557 {
558     if(!buffer || interval == 0 || length < interval || !callback)
559         return 0;
560
561 #if !SD_RAW_SAVE_RAM
562     while(length >= interval)
563     {
564         /* as reading is now buffered, we directly
565          * hand over the request to sd_raw_read()
566          */
567         if(!sd_raw_read(offset, buffer, interval))
568             return 0;
569         if(!callback(buffer, offset, p))
570             break;
571         offset += interval;
572         length -= interval;
573     }
574
575     return 1;
576 #else
577     /* address card */
578     select_card();
579
580     uint16_t block_offset;
581     uint16_t read_length;
582     uint8_t* buffer_cur;
583     uint8_t finished = 0;
584     do
585     {
586         /* determine byte count to read at once */
587         block_offset = offset & 0x01ff;
588         read_length = 512 - block_offset;
589
590         /* send single block request */
591 #if SD_RAW_SDHC
592         if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? offset / 512 : offset - block_offset)))
593 #else
594         if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, offset - block_offset))
595 #endif
596         {
597             unselect_card();
598             return 0;
599         }
600
601         /* wait for data block (start byte 0xfe) */
602         while(sd_raw_rec_byte() != 0xfe);
603
604         /* read up to the data of interest */
605         for(uint16_t i = 0; i < block_offset; ++i)
606             sd_raw_rec_byte();
607
608         /* read interval bytes of data and execute the callback */
609         do
610         {
611             if(read_length < interval || length < interval)
612                 break;
613
614             buffer_cur = buffer;
615             for(uint16_t i = 0; i < interval; ++i)
616                 *buffer_cur++ = sd_raw_rec_byte();
617
618             if(!callback(buffer, offset + (512 - read_length), p))
619             {
620                 finished = 1;
621                 break;
622             }
623
624             read_length -= interval;
625             length -= interval;
626
627         } while(read_length > 0 && length > 0);
628
629         /* read rest of data block */
630         while(read_length-- > 0)
631             sd_raw_rec_byte();
632
633         /* read crc16 */
634         sd_raw_rec_byte();
635         sd_raw_rec_byte();
636
637         if(length < interval)
638             break;
639
640         offset = offset - block_offset + 512;
641
642     } while(!finished);
643
644     /* deaddress card */
645     unselect_card();
646
647     /* let card some time to finish */
648     sd_raw_rec_byte();
649
650     return 1;
651 #endif
652 }
653
654 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
655 /**
656  * \ingroup sd_raw
657  * Writes raw data to the card.
658  *
659  * \note If write buffering is enabled, you might have to
660  *       call sd_raw_sync() before disconnecting the card
661  *       to ensure all remaining data has been written.
662  *
663  * \param[in] offset The offset where to start writing.
664  * \param[in] buffer The buffer containing the data to be written.
665  * \param[in] length The number of bytes to write.
666  * \returns 0 on failure, 1 on success.
667  * \see sd_raw_write_interval, sd_raw_read, sd_raw_read_interval
668  */
669 uint8_t sd_raw_write(offset_t offset, const uint8_t* buffer, uintptr_t length)
670 {
671     if(sd_raw_locked())
672         return 0;
673
674     offset_t block_address;
675     uint16_t block_offset;
676     uint16_t write_length;
677     while(length > 0)
678     {
679         /* determine byte count to write at once */
680         block_offset = offset & 0x01ff;
681         block_address = offset - block_offset;
682         write_length = 512 - block_offset; /* write up to block border */
683         if(write_length > length)
684             write_length = length;
685
686         /* Merge the data to write with the content of the block.
687          * Use the cached block if available.
688          */
689         if(block_address != raw_block_address)
690         {
691 #if SD_RAW_WRITE_BUFFERING
692             if(!sd_raw_sync())
693                 return 0;
694 #endif
695
696             if(block_offset || write_length < 512)
697             {
698                 if(!sd_raw_read(block_address, raw_block, sizeof(raw_block)))
699                     return 0;
700             }
701             raw_block_address = block_address;
702         }
703
704         if(buffer != raw_block)
705         {
706             memcpy(raw_block + block_offset, buffer, write_length);
707
708 #if SD_RAW_WRITE_BUFFERING
709             raw_block_written = 0;
710
711             if(length == write_length)
712                 return 1;
713 #endif
714         }
715
716         /* address card */
717         select_card();
718
719         /* send single block request */
720 #if SD_RAW_SDHC
721         if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
722 #else
723         if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, block_address))
724 #endif
725         {
726             unselect_card();
727             return 0;
728         }
729
730         /* send start byte */
731         sd_raw_send_byte(0xfe);
732
733         /* write byte block */
734         uint8_t* cache = raw_block;
735         for(uint16_t i = 0; i < 512; ++i)
736             sd_raw_send_byte(*cache++);
737
738         /* write dummy crc16 */
739         sd_raw_send_byte(0xff);
740         sd_raw_send_byte(0xff);
741
742         /* wait while card is busy */
743         while(sd_raw_rec_byte() != 0xff);
744         sd_raw_rec_byte();
745
746         /* deaddress card */
747         unselect_card();
748
749         buffer += write_length;
750         offset += write_length;
751         length -= write_length;
752
753 #if SD_RAW_WRITE_BUFFERING
754         raw_block_written = 1;
755 #endif
756     }
757
758     return 1;
759 }
760 #endif
761
762 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
763 /**
764  * \ingroup sd_raw
765  * Writes a continuous data stream obtained from a callback function.
766  *
767  * This function starts writing at the specified offset. To obtain the
768  * next bytes to write, it calls the callback function. The callback fills the
769  * provided data buffer and returns the number of bytes it has put into the buffer.
770  *
771  * By returning zero, the callback may stop writing.
772  *
773  * \param[in] offset Offset where to start writing.
774  * \param[in] buffer Pointer to a buffer which is used for the callback function.
775  * \param[in] length Number of bytes to write in total. May be zero for endless writes.
776  * \param[in] callback The function used to obtain the bytes to write.
777  * \param[in] p An opaque pointer directly passed to the callback function.
778  * \returns 0 on failure, 1 on success
779  * \see sd_raw_read_interval, sd_raw_write, sd_raw_read
780  */
781 uint8_t sd_raw_write_interval(offset_t offset, uint8_t* buffer, uintptr_t length, sd_raw_write_interval_handler_t callback, void* p)
782 {
783 #if SD_RAW_SAVE_RAM
784     #error "SD_RAW_WRITE_SUPPORT is not supported together with SD_RAW_SAVE_RAM"
785 #endif
786
787     if(!buffer || !callback)
788         return 0;
789
790     uint8_t endless = (length == 0);
791     while(endless || length > 0)
792     {
793         uint16_t bytes_to_write = callback(buffer, offset, p);
794         if(!bytes_to_write)
795             break;
796         if(!endless && bytes_to_write > length)
797             return 0;
798
799         /* as writing is always buffered, we directly
800          * hand over the request to sd_raw_write()
801          */
802         if(!sd_raw_write(offset, buffer, bytes_to_write))
803             return 0;
804
805         offset += bytes_to_write;
806         length -= bytes_to_write;
807     }
808
809     return 1;
810 }
811 #endif
812
813 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
814 /**
815  * \ingroup sd_raw
816  * Writes the write buffer's content to the card.
817  *
818  * \note When write buffering is enabled, you should
819  *       call this function before disconnecting the
820  *       card to ensure all remaining data has been
821  *       written.
822  *
823  * \returns 0 on failure, 1 on success.
824  * \see sd_raw_write
825  */
826 uint8_t sd_raw_sync()
827 {
828 #if SD_RAW_WRITE_BUFFERING
829     if(raw_block_written)
830         return 1;
831     if(!sd_raw_write(raw_block_address, raw_block, sizeof(raw_block)))
832         return 0;
833     raw_block_written = 1;
834 #endif
835     return 1;
836 }
837 #endif
838
839 /**
840  * \ingroup sd_raw
841  * Reads informational data from the card.
842  *
843  * This function reads and returns the card's registers
844  * containing manufacturing and status information.
845  *
846  * \note: The information retrieved by this function is
847  *        not required in any way to operate on the card,
848  *        but it might be nice to display some of the data
849  *        to the user.
850  *
851  * \param[in] info A pointer to the structure into which to save the information.
852  * \returns 0 on failure, 1 on success.
853  */
854 uint8_t sd_raw_get_info(struct sd_raw_info* info)
855 {
856     if(!info || !sd_raw_available())
857         return 0;
858
859     memset(info, 0, sizeof(*info));
860
861     select_card();
862
863     /* read cid register */
864     if(sd_raw_send_command(CMD_SEND_CID, 0))
865     {
866         unselect_card();
867         return 0;
868     }
869     while(sd_raw_rec_byte() != 0xfe);
870     for(uint8_t i = 0; i < 18; ++i)
871     {
872         uint8_t b = sd_raw_rec_byte();
873
874         switch(i)
875         {
876             case 0:
877                 info->manufacturer = b;
878                 break;
879             case 1:
880             case 2:
881                 info->oem[i - 1] = b;
882                 break;
883             case 3:
884             case 4:
885             case 5:
886             case 6:
887             case 7:
888                 info->product[i - 3] = b;
889                 break;
890             case 8:
891                 info->revision = b;
892                 break;
893             case 9:
894             case 10:
895             case 11:
896             case 12:
897                 info->serial |= (uint32_t) b << ((12 - i) * 8);
898                 break;
899             case 13:
900                 info->manufacturing_year = b << 4;
901                 break;
902             case 14:
903                 info->manufacturing_year |= b >> 4;
904                 info->manufacturing_month = b & 0x0f;
905                 break;
906         }
907     }
908
909     /* read csd register */
910     uint8_t csd_read_bl_len = 0;
911     uint8_t csd_c_size_mult = 0;
912 #if SD_RAW_SDHC
913     uint16_t csd_c_size = 0;
914 #else
915     uint32_t csd_c_size = 0;
916 #endif
917     uint8_t csd_structure = 0;
918     if(sd_raw_send_command(CMD_SEND_CSD, 0))
919     {
920         unselect_card();
921         return 0;
922     }
923     while(sd_raw_rec_byte() != 0xfe);
924     for(uint8_t i = 0; i < 18; ++i)
925     {
926         uint8_t b = sd_raw_rec_byte();
927
928         if(i == 0)
929         {
930             csd_structure = b >> 6;
931             (void)csd_structure;
932         }
933         else if(i == 14)
934         {
935             if(b & 0x40)
936                 info->flag_copy = 1;
937             if(b & 0x20)
938                 info->flag_write_protect = 1;
939             if(b & 0x10)
940                 info->flag_write_protect_temp = 1;
941             info->format = (b & 0x0c) >> 2;
942         }
943         else
944         {
945 #if SD_RAW_SDHC
946             if(csd_structure == 0x01)
947             {
948                 switch(i)
949                 {
950                     case 7:
951                         b &= 0x3f;
952                     case 8:
953                     case 9:
954                         csd_c_size <<= 8;
955                         csd_c_size |= b;
956                         break;
957                 }
958                 if(i == 9)
959                 {
960                     ++csd_c_size;
961                     info->capacity = (offset_t) csd_c_size * 512 * 1024;
962                 }
963             }
964             else if(csd_structure == 0x00)
965 #endif
966             {
967                 switch(i)
968                 {
969                     case 5:
970                         csd_read_bl_len = b & 0x0f;
971                         break;
972                     case 6:
973                         csd_c_size = b & 0x03;
974                         csd_c_size <<= 8;
975                         break;
976                     case 7:
977                         csd_c_size |= b;
978                         csd_c_size <<= 2;
979                         break;
980                     case 8:
981                         csd_c_size |= b >> 6;
982                         ++csd_c_size;
983                         break;
984                     case 9:
985                         csd_c_size_mult = b & 0x03;
986                         csd_c_size_mult <<= 1;
987                         break;
988                     case 10:
989                         csd_c_size_mult |= b >> 7;
990
991                         info->capacity = (uint32_t) csd_c_size << (csd_c_size_mult + csd_read_bl_len + 2);
992                         break;
993                 }
994             }
995         }
996     }
997
998     unselect_card();
999
1000     return 1;
1001 }
1002