]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/fs/sd/SDFileSystem.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / fs / sd / SDFileSystem.cpp
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2012 ARM Limited
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22 /* Introduction
23  * ------------
24  * SD and MMC cards support a number of interfaces, but common to them all
25  * is one based on SPI. This is the one I'm implmenting because it means
26  * it is much more portable even though not so performant, and we already
27  * have the mbed SPI Interface!
28  *
29  * The main reference I'm using is Chapter 7, "SPI Mode" of:
30  *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
31  *
32  * SPI Startup
33  * -----------
34  * The SD card powers up in SD mode. The SPI interface mode is selected by
35  * asserting CS low and sending the reset command (CMD0). The card will
36  * respond with a (R1) response.
37  *
38  * CMD8 is optionally sent to determine the voltage range supported, and
39  * indirectly determine whether it is a version 1.x SD/non-SD card or
40  * version 2.x. I'll just ignore this for now.
41  *
42  * ACMD41 is repeatedly issued to initialise the card, until "in idle"
43  * (bit 0) of the R1 response goes to '0', indicating it is initialised.
44  *
45  * You should also indicate whether the host supports High Capicity cards,
46  * and check whether the card is high capacity - i'll also ignore this
47  *
48  * SPI Protocol
49  * ------------
50  * The SD SPI protocol is based on transactions made up of 8-bit words, with
51  * the host starting every bus transaction by asserting the CS signal low. The
52  * card always responds to commands, data blocks and errors.
53  *
54  * The protocol supports a CRC, but by default it is off (except for the
55  * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
56  * I'll leave the CRC off I think!
57  *
58  * Standard capacity cards have variable data block sizes, whereas High
59  * Capacity cards fix the size of data block to 512 bytes. I'll therefore
60  * just always use the Standard Capacity cards with a block size of 512 bytes.
61  * This is set with CMD16.
62  *
63  * You can read and write single blocks (CMD17, CMD25) or multiple blocks
64  * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
65  * the card gets a read command, it responds with a response token, and then
66  * a data token or an error.
67  *
68  * SPI Command Format
69  * ------------------
70  * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
71  *
72  * +---------------+------------+------------+-----------+----------+--------------+
73  * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
74  * +---------------+------------+------------+-----------+----------+--------------+
75  *
76  * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
77  *
78  * All Application Specific commands shall be preceded with APP_CMD (CMD55).
79  *
80  * SPI Response Format
81  * -------------------
82  * The main response format (R1) is a status byte (normally zero). Key flags:
83  *  idle - 1 if the card is in an idle state/initialising
84  *  cmd  - 1 if an illegal command code was detected
85  *
86  *    +-------------------------------------------------+
87  * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
88  *    +-------------------------------------------------+
89  *
90  * R1b is the same, except it is followed by a busy signal (zeros) until
91  * the first non-zero byte when it is ready again.
92  *
93  * Data Response Token
94  * -------------------
95  * Every data block written to the card is acknowledged by a byte
96  * response token
97  *
98  * +----------------------+
99  * | xxx | 0 | status | 1 |
100  * +----------------------+
101  *              010 - OK!
102  *              101 - CRC Error
103  *              110 - Write Error
104  *
105  * Single Block Read and Write
106  * ---------------------------
107  *
108  * Block transfers have a byte header, followed by the data, followed
109  * by a 16-bit CRC. In our case, the data will always be 512 bytes.
110  *
111  * +------+---------+---------+- -  - -+---------+-----------+----------+
112  * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
113  * +------+---------+---------+- -  - -+---------+-----------+----------+
114  */
115 #include "SDFileSystem.h"
116 #include "mbed_debug.h"
117
118 #define SD_COMMAND_TIMEOUT 5000
119
120 #define SD_DBG             0
121
122 SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :
123     FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs), _is_initialized(0) {
124     _cs = 1;
125
126     // Set default to 100kHz for initialisation and 1MHz for data transfer
127     _init_sck = 100000;
128     _transfer_sck = 1000000;
129 }
130
131 #define R1_IDLE_STATE           (1 << 0)
132 #define R1_ERASE_RESET          (1 << 1)
133 #define R1_ILLEGAL_COMMAND      (1 << 2)
134 #define R1_COM_CRC_ERROR        (1 << 3)
135 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
136 #define R1_ADDRESS_ERROR        (1 << 5)
137 #define R1_PARAMETER_ERROR      (1 << 6)
138
139 // Types
140 //  - v1.x Standard Capacity
141 //  - v2.x Standard Capacity
142 //  - v2.x High Capacity
143 //  - Not recognised as an SD Card
144 #define SDCARD_FAIL 0
145 #define SDCARD_V1   1
146 #define SDCARD_V2   2
147 #define SDCARD_V2HC 3
148
149 int SDFileSystem::initialise_card() {
150     // Set to SCK for initialisation, and clock card with cs = 1
151     _spi.frequency(_init_sck);
152     _cs = 1;
153     for (int i = 0; i < 16; i++) {
154         _spi.write(0xFF);
155     }
156
157     // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
158     if (_cmd(0, 0) != R1_IDLE_STATE) {
159         debug("No disk, or could not put SD card in to SPI idle state\n");
160         return SDCARD_FAIL;
161     }
162
163     // send CMD8 to determine whther it is ver 2.x
164     int r = _cmd8();
165     if (r == R1_IDLE_STATE) {
166         return initialise_card_v2();
167     } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
168         return initialise_card_v1();
169     } else {
170         debug("Not in idle state after sending CMD8 (not an SD card?)\n");
171         return SDCARD_FAIL;
172     }
173 }
174
175 int SDFileSystem::initialise_card_v1() {
176     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
177         _cmd(55, 0);
178         if (_cmd(41, 0) == 0) {
179             cdv = 512;
180             debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r");
181             return SDCARD_V1;
182         }
183     }
184
185     debug("Timeout waiting for v1.x card\n");
186     return SDCARD_FAIL;
187 }
188
189 int SDFileSystem::initialise_card_v2() {
190     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
191         wait_ms(50);
192         _cmd58();
193         _cmd(55, 0);
194         if (_cmd(41, 0x40000000) == 0) {
195             _cmd58();
196             debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r");
197             cdv = 1;
198             return SDCARD_V2;
199         }
200     }
201
202     debug("Timeout waiting for v2.x card\n");
203     return SDCARD_FAIL;
204 }
205
206 int SDFileSystem::disk_initialize() {
207     _is_initialized = initialise_card();
208     if (_is_initialized == 0) {
209         debug("Fail to initialize card\n");
210         return 1;
211     }
212     debug_if(SD_DBG, "init card = %d\n", _is_initialized);
213     _sectors = _sd_sectors();
214
215     // Set block length to 512 (CMD16)
216     if (_cmd(16, 512) != 0) {
217         debug("Set 512-byte block timed out\n");
218         return 1;
219     }
220
221     // Set SCK for data transfer
222     _spi.frequency(_transfer_sck);
223     return 0;
224 }
225
226 int SDFileSystem::disk_write(const uint8_t* buffer, uint64_t block_number, uint8_t count) {
227     if (!_is_initialized) {
228         return -1;
229     }
230     
231     for (uint64_t b = block_number; b < block_number + count; b++) {
232         // set write address for single block (CMD24)
233         if (_cmd(24, b * cdv) != 0) {
234             return 1;
235         }
236         
237         // send the data block
238         _write(buffer, 512);
239         buffer += 512;
240     }
241     
242     return 0;
243 }
244
245 int SDFileSystem::disk_read(uint8_t* buffer, uint64_t block_number, uint8_t count) {
246     if (!_is_initialized) {
247         return -1;
248     }
249     
250     for (uint64_t b = block_number; b < block_number + count; b++) {
251         // set read address for single block (CMD17)
252         if (_cmd(17, b * cdv) != 0) {
253             return 1;
254         }
255         
256         // receive the data
257         _read(buffer, 512);
258         buffer += 512;
259     }
260
261     return 0;
262 }
263
264 int SDFileSystem::disk_status() {
265     // FATFileSystem::disk_status() returns 0 when initialized
266     if (_is_initialized) {
267         return 0;
268     } else {
269         return 1;
270     }
271 }
272
273 int SDFileSystem::disk_sync() { return 0; }
274 uint64_t SDFileSystem::disk_sectors() { return _sectors; }
275
276
277 // PRIVATE FUNCTIONS
278 int SDFileSystem::_cmd(int cmd, int arg) {
279     _cs = 0;
280
281     // send a command
282     _spi.write(0x40 | cmd);
283     _spi.write(arg >> 24);
284     _spi.write(arg >> 16);
285     _spi.write(arg >> 8);
286     _spi.write(arg >> 0);
287     _spi.write(0x95);
288
289     // wait for the repsonse (response[7] == 0)
290     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
291         int response = _spi.write(0xFF);
292         if (!(response & 0x80)) {
293             _cs = 1;
294             _spi.write(0xFF);
295             return response;
296         }
297     }
298     _cs = 1;
299     _spi.write(0xFF);
300     return -1; // timeout
301 }
302 int SDFileSystem::_cmdx(int cmd, int arg) {
303     _cs = 0;
304
305     // send a command
306     _spi.write(0x40 | cmd);
307     _spi.write(arg >> 24);
308     _spi.write(arg >> 16);
309     _spi.write(arg >> 8);
310     _spi.write(arg >> 0);
311     _spi.write(0x95);
312
313     // wait for the repsonse (response[7] == 0)
314     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
315         int response = _spi.write(0xFF);
316         if (!(response & 0x80)) {
317             return response;
318         }
319     }
320     _cs = 1;
321     _spi.write(0xFF);
322     return -1; // timeout
323 }
324
325
326 int SDFileSystem::_cmd58() {
327     _cs = 0;
328     int arg = 0;
329
330     // send a command
331     _spi.write(0x40 | 58);
332     _spi.write(arg >> 24);
333     _spi.write(arg >> 16);
334     _spi.write(arg >> 8);
335     _spi.write(arg >> 0);
336     _spi.write(0x95);
337
338     // wait for the repsonse (response[7] == 0)
339     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
340         int response = _spi.write(0xFF);
341         if (!(response & 0x80)) {
342             int ocr = _spi.write(0xFF) << 24;
343             ocr |= _spi.write(0xFF) << 16;
344             ocr |= _spi.write(0xFF) << 8;
345             ocr |= _spi.write(0xFF) << 0;
346             _cs = 1;
347             _spi.write(0xFF);
348             return response;
349         }
350     }
351     _cs = 1;
352     _spi.write(0xFF);
353     return -1; // timeout
354 }
355
356 int SDFileSystem::_cmd8() {
357     _cs = 0;
358
359     // send a command
360     _spi.write(0x40 | 8); // CMD8
361     _spi.write(0x00);     // reserved
362     _spi.write(0x00);     // reserved
363     _spi.write(0x01);     // 3.3v
364     _spi.write(0xAA);     // check pattern
365     _spi.write(0x87);     // crc
366
367     // wait for the repsonse (response[7] == 0)
368     for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
369         char response[5];
370         response[0] = _spi.write(0xFF);
371         if (!(response[0] & 0x80)) {
372             for (int j = 1; j < 5; j++) {
373                 response[i] = _spi.write(0xFF);
374             }
375             _cs = 1;
376             _spi.write(0xFF);
377             return response[0];
378         }
379     }
380     _cs = 1;
381     _spi.write(0xFF);
382     return -1; // timeout
383 }
384
385 int SDFileSystem::_read(uint8_t *buffer, uint32_t length) {
386     _cs = 0;
387
388     // read until start byte (0xFF)
389     while (_spi.write(0xFF) != 0xFE);
390
391     // read data
392     for (uint32_t i = 0; i < length; i++) {
393         buffer[i] = _spi.write(0xFF);
394     }
395     _spi.write(0xFF); // checksum
396     _spi.write(0xFF);
397
398     _cs = 1;
399     _spi.write(0xFF);
400     return 0;
401 }
402
403 int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) {
404     _cs = 0;
405
406     // indicate start of block
407     _spi.write(0xFE);
408
409     // write the data
410     for (uint32_t i = 0; i < length; i++) {
411         _spi.write(buffer[i]);
412     }
413
414     // write the checksum
415     _spi.write(0xFF);
416     _spi.write(0xFF);
417
418     // check the response token
419     if ((_spi.write(0xFF) & 0x1F) != 0x05) {
420         _cs = 1;
421         _spi.write(0xFF);
422         return 1;
423     }
424
425     // wait for write to finish
426     while (_spi.write(0xFF) == 0);
427
428     _cs = 1;
429     _spi.write(0xFF);
430     return 0;
431 }
432
433 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
434     uint32_t bits = 0;
435     uint32_t size = 1 + msb - lsb;
436     for (uint32_t i = 0; i < size; i++) {
437         uint32_t position = lsb + i;
438         uint32_t byte = 15 - (position >> 3);
439         uint32_t bit = position & 0x7;
440         uint32_t value = (data[byte] >> bit) & 1;
441         bits |= value << i;
442     }
443     return bits;
444 }
445
446 uint64_t SDFileSystem::_sd_sectors() {
447     uint32_t c_size, c_size_mult, read_bl_len;
448     uint32_t block_len, mult, blocknr, capacity;
449     uint32_t hc_c_size;
450     uint64_t blocks;
451
452     // CMD9, Response R2 (R1 byte + 16-byte block read)
453     if (_cmdx(9, 0) != 0) {
454         debug("Didn't get a response from the disk\n");
455         return 0;
456     }
457
458     uint8_t csd[16];
459     if (_read(csd, 16) != 0) {
460         debug("Couldn't read csd response from disk\n");
461         return 0;
462     }
463
464     // csd_structure : csd[127:126]
465     // c_size        : csd[73:62]
466     // c_size_mult   : csd[49:47]
467     // read_bl_len   : csd[83:80] - the *maximum* read block length
468
469     int csd_structure = ext_bits(csd, 127, 126);
470
471     switch (csd_structure) {
472         case 0:
473             cdv = 512;
474             c_size = ext_bits(csd, 73, 62);
475             c_size_mult = ext_bits(csd, 49, 47);
476             read_bl_len = ext_bits(csd, 83, 80);
477
478             block_len = 1 << read_bl_len;
479             mult = 1 << (c_size_mult + 2);
480             blocknr = (c_size + 1) * mult;
481             capacity = blocknr * block_len;
482             blocks = capacity / 512;
483             debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks);
484             break;
485
486         case 1:
487             cdv = 1;
488             hc_c_size = ext_bits(csd, 63, 48);
489             blocks = (hc_c_size+1)*1024;
490             debug_if(SD_DBG, "\n\rSDHC Card \n\rhc_c_size: %d\n\rcapacity: %lld \n\rsectors: %lld\n\r", hc_c_size, blocks*512, blocks);
491             break;
492
493         default:
494             debug("CSD struct unsupported\r\n");
495             return 0;
496     };
497     return blocks;
498 }