re-enabling serial
[clinton/Smoothieware.git] / gcc4mbed / samples / MSTest / USBMSD_SD / USBMSD_SD.cpp
1 /* mbed USBMSD_SD Library, for providing file access to SD cards
2 * Copyright (c) 2008-2010, sford
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
20 * THE SOFTWARE.
21 */
22
23 /* Introduction
24 * ------------
25 * SD and MMC cards support a number of interfaces, but common to them all
26 * is one based on SPI. This is the one I'm implmenting because it means
27 * it is much more portable even though not so performant, and we already
28 * have the mbed SPI Interface!
29 *
30 * The main reference I'm using is Chapter 7, "SPI Mode" of:
31 * http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
32 *
33 * SPI Startup
34 * -----------
35 * The SD card powers up in SD mode. The SPI interface mode is selected by
36 * asserting CS low and sending the reset command (CMD0). The card will
37 * respond with a (R1) response.
38 *
39 * CMD8 is optionally sent to determine the voltage range supported, and
40 * indirectly determine whether it is a version 1.x SD/non-SD card or
41 * version 2.x. I'll just ignore this for now.
42 *
43 * ACMD41 is repeatedly issued to initialise the card, until "in idle"
44 * (bit 0) of the R1 response goes to '0', indicating it is initialised.
45 *
46 * You should also indicate whether the host supports High Capicity cards,
47 * and check whether the card is high capacity - i'll also ignore this
48 *
49 * SPI Protocol
50 * ------------
51 * The SD SPI protocol is based on transactions made up of 8-bit words, with
52 * the host starting every bus transaction by asserting the CS signal low. The
53 * card always responds to commands, data blocks and errors.
54 *
55 * The protocol supports a CRC, but by default it is off (except for the
56 * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
57 * I'll leave the CRC off I think!
58 *
59 * Standard capacity cards have variable data block sizes, whereas High
60 * Capacity cards fix the size of data block to 512 bytes. I'll therefore
61 * just always use the Standard Capacity cards with a block size of 512 bytes.
62 * This is set with CMD16.
63 *
64 * You can read and write single blocks (CMD17, CMD25) or multiple blocks
65 * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
66 * the card gets a read command, it responds with a response token, and then
67 * a data token or an error.
68 *
69 * SPI Command Format
70 * ------------------
71 * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
72 *
73 * +---------------+------------+------------+-----------+----------+--------------+
74 * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
75 * +---------------+------------+------------+-----------+----------+--------------+
76 *
77 * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
78 *
79 * All Application Specific commands shall be preceded with APP_CMD (CMD55).
80 *
81 * SPI Response Format
82 * -------------------
83 * The main response format (R1) is a status byte (normally zero). Key flags:
84 * idle - 1 if the card is in an idle state/initialising
85 * cmd - 1 if an illegal command code was detected
86 *
87 * +-------------------------------------------------+
88 * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
89 * +-------------------------------------------------+
90 *
91 * R1b is the same, except it is followed by a busy signal (zeros) until
92 * the first non-zero byte when it is ready again.
93 *
94 * Data Response Token
95 * -------------------
96 * Every data block written to the card is acknowledged by a byte
97 * response token
98 *
99 * +----------------------+
100 * | xxx | 0 | status | 1 |
101 * +----------------------+
102 * 010 - OK!
103 * 101 - CRC Error
104 * 110 - Write Error
105 *
106 * Single Block Read and Write
107 * ---------------------------
108 *
109 * Block transfers have a byte header, followed by the data, followed
110 * by a 16-bit CRC. In our case, the data will always be 512 bytes.
111 *
112 * +------+---------+---------+- - - -+---------+-----------+----------+
113 * | 0xFE | data[0] | data[1] | | data[n] | crc[15:8] | crc[7:0] |
114 * +------+---------+---------+- - - -+---------+-----------+----------+
115 */
116
117 #include "USBMSD_SD.h"
118
119 #define SD_COMMAND_TIMEOUT 5000
120
121 USBMSD_SD::USBMSD_SD(PinName mosi, PinName miso, PinName sclk, PinName cs) :
122 _spi(mosi, miso, sclk), _cs(cs) {
123 _cs = 1;
124 //no init
125 _status = 0x01;
126 connect();
127 }
128
129 #define R1_IDLE_STATE (1 << 0)
130 #define R1_ERASE_RESET (1 << 1)
131 #define R1_ILLEGAL_COMMAND (1 << 2)
132 #define R1_COM_CRC_ERROR (1 << 3)
133 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
134 #define R1_ADDRESS_ERROR (1 << 5)
135 #define R1_PARAMETER_ERROR (1 << 6)
136
137 // Types
138 // - v1.x Standard Capacity
139 // - v2.x Standard Capacity
140 // - v2.x High Capacity
141 // - Not recognised as an SD Card
142
143 #define SDCARD_FAIL 0
144 #define SDCARD_V1 1
145 #define SDCARD_V2 2
146 #define SDCARD_V2HC 3
147
148 int USBMSD_SD::initialise_card() {
149 // Set to 100kHz for initialisation, and clock card with cs = 1
150 _spi.frequency(100000);
151 _cs = 1;
152 for(int i=0; i<16; i++) {
153 _spi.write(0xFF);
154 }
155
156 // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
157 if(_cmd(0, 0) != R1_IDLE_STATE) {
158 fprintf(stderr, "No disk, or could not put SD card in to SPI idle state\n");
159 return SDCARD_FAIL;
160 }
161
162 // send CMD8 to determine whther it is ver 2.x
163 int r = _cmd8();
164 if(r == R1_IDLE_STATE) {
165 return initialise_card_v2();
166 } else if(r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
167 return initialise_card_v1();
168 } else {
169 fprintf(stderr, "Not in idle state after sending CMD8 (not an SD card?)\n");
170 return SDCARD_FAIL;
171 }
172 }
173
174 int USBMSD_SD::initialise_card_v1() {
175 for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
176 _cmd(55, 0);
177 if(_cmd(41, 0) == 0) {
178 return SDCARD_V1;
179 }
180 }
181
182 fprintf(stderr, "Timeout waiting for v1.x card\n");
183 return SDCARD_FAIL;
184 }
185
186 int USBMSD_SD::initialise_card_v2() {
187
188 for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
189 _cmd(55, 0);
190 if(_cmd(41, 0) == 0) {
191 _cmd58();
192 return SDCARD_V2;
193 }
194 }
195
196 fprintf(stderr, "Timeout waiting for v2.x card\n");
197 return SDCARD_FAIL;
198 }
199
200 int USBMSD_SD::disk_initialize() {
201
202 int i = initialise_card();
203 // printf("init card = %d\n", i);
204 // printf("OK\n");
205
206 _sectors = _sd_sectors();
207
208 // Set block length to 512 (CMD16)
209 if(_cmd(16, 512) != 0) {
210 fprintf(stderr, "Set 512-byte block timed out\n");
211 return 1;
212 }
213
214 _spi.frequency(5000000); // Set to 5MHz for data transfer
215 // OK
216 _status = 0x00;
217 return 0;
218 }
219
220 int USBMSD_SD::disk_write(const char *buffer, int block_number) {
221 // set write address for single block (CMD24)
222 if(_cmd(24, block_number * 512) != 0) {
223 return 1;
224 }
225
226 // send the data block
227 _write(buffer, 512);
228 return 0;
229 }
230
231 int USBMSD_SD::disk_read(char *buffer, int block_number) {
232 // set read address for single block (CMD17)
233 if(_cmd(17, block_number * 512) != 0) {
234 return 1;
235 }
236
237 // receive the data
238 _read(buffer, 512);
239 return 0;
240 }
241
242 int USBMSD_SD::disk_status() { return _status; }
243 int USBMSD_SD::disk_sync() { return 0; }
244 int USBMSD_SD::disk_sectors() { return _sectors; }
245
246 // PRIVATE FUNCTIONS
247
248 int USBMSD_SD::_cmd(int cmd, int arg) {
249 _cs = 0;
250
251 // send a command
252 _spi.write(0x40 | cmd);
253 _spi.write(arg >> 24);
254 _spi.write(arg >> 16);
255 _spi.write(arg >> 8);
256 _spi.write(arg >> 0);
257 _spi.write(0x95);
258
259 // wait for the repsonse (response[7] == 0)
260 for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
261 int response = _spi.write(0xFF);
262 if(!(response & 0x80)) {
263 _cs = 1;
264 _spi.write(0xFF);
265 return response;
266 }
267 }
268 _cs = 1;
269 _spi.write(0xFF);
270 return -1; // timeout
271 }
272 int USBMSD_SD::_cmdx(int cmd, int arg) {
273 _cs = 0;
274
275 // send a command
276 _spi.write(0x40 | cmd);
277 _spi.write(arg >> 24);
278 _spi.write(arg >> 16);
279 _spi.write(arg >> 8);
280 _spi.write(arg >> 0);
281 _spi.write(0x95);
282
283 // wait for the repsonse (response[7] == 0)
284 for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
285 int response = _spi.write(0xFF);
286 if(!(response & 0x80)) {
287 return response;
288 }
289 }
290 _cs = 1;
291 _spi.write(0xFF);
292 return -1; // timeout
293 }
294
295
296 int USBMSD_SD::_cmd58() {
297 _cs = 0;
298 int arg = 0;
299
300 // send a command
301 _spi.write(0x40 | 58);
302 _spi.write(arg >> 24);
303 _spi.write(arg >> 16);
304 _spi.write(arg >> 8);
305 _spi.write(arg >> 0);
306 _spi.write(0x95);
307
308 // wait for the repsonse (response[7] == 0)
309 for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
310 int response = _spi.write(0xFF);
311 if(!(response & 0x80)) {
312 int ocr = _spi.write(0xFF) << 24;
313 ocr |= _spi.write(0xFF) << 16;
314 ocr |= _spi.write(0xFF) << 8;
315 ocr |= _spi.write(0xFF) << 0;
316 // printf("OCR = 0x%08X\n", ocr);
317 _cs = 1;
318 _spi.write(0xFF);
319 return response;
320 }
321 }
322 _cs = 1;
323 _spi.write(0xFF);
324 return -1; // timeout
325 }
326
327 int USBMSD_SD::_cmd8() {
328 _cs = 0;
329
330 // send a command
331 _spi.write(0x40 | 8); // CMD8
332 _spi.write(0x00); // reserved
333 _spi.write(0x00); // reserved
334 _spi.write(0x01); // 3.3v
335 _spi.write(0xAA); // check pattern
336 _spi.write(0x87); // crc
337
338 // wait for the repsonse (response[7] == 0)
339 for(int i=0; i<SD_COMMAND_TIMEOUT * 1000; i++) {
340 char response[5];
341 response[0] = _spi.write(0xFF);
342 if(!(response[0] & 0x80)) {
343 for(int j=1; j<5; j++) {
344 response[i] = _spi.write(0xFF);
345 }
346 _cs = 1;
347 _spi.write(0xFF);
348 return response[0];
349 }
350 }
351 _cs = 1;
352 _spi.write(0xFF);
353 return -1; // timeout
354 }
355
356 int USBMSD_SD::_read(char *buffer, int length) {
357 _cs = 0;
358
359 // read until start byte (0xFF)
360 while(_spi.write(0xFF) != 0xFE);
361
362 // read data
363 for(int i=0; i<length; i++) {
364 buffer[i] = _spi.write(0xFF);
365 }
366 _spi.write(0xFF); // checksum
367 _spi.write(0xFF);
368
369 _cs = 1;
370 _spi.write(0xFF);
371 return 0;
372 }
373
374 int USBMSD_SD::_write(const char *buffer, int length) {
375 _cs = 0;
376
377 // indicate start of block
378 _spi.write(0xFE);
379
380 // write the data
381 for(int i=0; i<length; i++) {
382 _spi.write(buffer[i]);
383 }
384
385 // write the checksum
386 _spi.write(0xFF);
387 _spi.write(0xFF);
388
389 // check the repsonse token
390 if((_spi.write(0xFF) & 0x1F) != 0x05) {
391 _cs = 1;
392 _spi.write(0xFF);
393 return 1;
394 }
395
396 // wait for write to finish
397 while(_spi.write(0xFF) == 0);
398
399 _cs = 1;
400 _spi.write(0xFF);
401 return 0;
402 }
403
404 static int ext_bits(char *data, int msb, int lsb) {
405 int bits = 0;
406 int size = 1 + msb - lsb;
407 for(int i=0; i<size; i++) {
408 int position = lsb + i;
409 int byte = 15 - (position >> 3);
410 int bit = position & 0x7;
411 int value = (data[byte] >> bit) & 1;
412 bits |= value << i;
413 }
414 return bits;
415 }
416
417 int USBMSD_SD::_sd_sectors() {
418
419 // CMD9, Response R2 (R1 byte + 16-byte block read)
420 if(_cmdx(9, 0) != 0) {
421 fprintf(stderr, "Didn't get a response from the disk\n");
422 return 0;
423 }
424
425 char csd[16];
426 if(_read(csd, 16) != 0) {
427 fprintf(stderr, "Couldn't read csd response from disk\n");
428 return 0;
429 }
430
431 // csd_structure : csd[127:126]
432 // c_size : csd[73:62]
433 // c_size_mult : csd[49:47]
434 // read_bl_len : csd[83:80] - the *maximum* read block length
435
436 int csd_structure = ext_bits(csd, 127, 126);
437 int c_size = ext_bits(csd, 73, 62);
438 int c_size_mult = ext_bits(csd, 49, 47);
439 int read_bl_len = ext_bits(csd, 83, 80);
440
441 // printf("CSD_STRUCT = %d\n", csd_structure);
442
443 if(csd_structure != 0) {
444 fprintf(stderr, "This disk tastes funny! I only know about type 0 CSD structures\n");
445 return 0;
446 }
447
448 // memory capacity = BLOCKNR * BLOCK_LEN
449 // where
450 // BLOCKNR = (C_SIZE+1) * MULT
451 // MULT = 2^(C_SIZE_MULT+2) (C_SIZE_MULT < 8)
452 // BLOCK_LEN = 2^READ_BL_LEN, (READ_BL_LEN < 12)
453
454 int block_len = 1 << read_bl_len;
455 int mult = 1 << (c_size_mult + 2);
456 int blocknr = (c_size + 1) * mult;
457 capacity = blocknr * block_len;
458
459 int blocks = capacity / 512;
460
461 return blocks;
462 }
463
464
465 int USBMSD_SD::disk_size() {
466 return capacity;
467 }