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