]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/devs/disk/generic/mmc/v2_0/src/mmc_spi.c
Initial revision
[karo-tx-redboot.git] / packages / devs / disk / generic / mmc / v2_0 / src / mmc_spi.c
1 //==========================================================================
2 //
3 //      mmc_spi.c
4 //
5 //      Provide a disk device driver for MMC cards over SPI
6 //
7 //==========================================================================
8 //####ECOSGPLCOPYRIGHTBEGIN####
9 // -------------------------------------------
10 // This file is part of eCos, the Embedded Configurable Operating System.
11 // Copyright (C) 2004, 2006 eCosCentric Limited
12 //
13 // eCos is free software; you can redistribute it and/or modify it under
14 // the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 2 or (at your option) any later version.
16 //
17 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
18 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 // for more details.
21 //
22 // You should have received a copy of the GNU General Public License along
23 // with eCos; if not, write to the Free Software Foundation, Inc.,
24 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25 //
26 // As a special exception, if other files instantiate templates or use macros
27 // or inline functions from this file, or you compile this file and link it
28 // with other works to produce a work based on this file, this file does not
29 // by itself cause the resulting work to be covered by the GNU General Public
30 // License. However the source code for this file must still be made available
31 // in accordance with section (3) of the GNU General Public License.
32 //
33 // This exception does not invalidate any other reasons why a work based on
34 // this file might be covered by the GNU General Public License.
35 //
36 // -------------------------------------------
37 //####ECOSGPLCOPYRIGHTEND####
38 //==========================================================================
39 //#####DESCRIPTIONBEGIN####
40 //
41 // Author:       bartv
42 // Date:         2004-04-25
43 //
44 //####DESCRIPTIONEND####
45 //==========================================================================
46
47 #include <pkgconf/system.h>
48 #include <pkgconf/devs_disk_mmc.h>
49 #include <cyg/infra/cyg_type.h>
50 #include <cyg/infra/cyg_ass.h>
51 #include <cyg/infra/diag.h>
52 #include <cyg/hal/hal_arch.h>
53 #include <cyg/hal/hal_if.h>             // delays
54 #include <cyg/hal/hal_intr.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <cyg/io/io.h>
58 #include <cyg/io/spi.h>
59 #include <cyg/io/devtab.h>
60 #include <cyg/io/disk.h>
61 #include <cyg/io/mmc_protocol.h>
62
63 // Communication parameters. First some debug support
64 #define DEBUG   0
65 #if DEBUG > 0
66 # define DEBUG1(format, ...)    diag_printf(format, ## __VA_ARGS__)
67 #else
68 # define DEBUG1(format, ...)
69 #endif
70 #if DEBUG > 1
71 # define DEBUG2(format, ...)    diag_printf(format, ## __VA_ARGS__)
72 #else
73 # define DEBUG2(format, ...)
74 #endif
75
76 // Should the SPI operations run in polled or interrupt-driven mode?
77 // The default value is determined by CDL, but can be overridden at
78 // run-time if necessary. For example if configured for
79 // interrupt-driven I/O then it will be impossible to perform disk
80 // operations during system initialization, e.g. from a static
81 // constructor, unless this flag is changed for the duration.
82 #ifdef CYGIMP_DEVS_DISK_MMC_SPI_POLLED
83 cyg_bool    cyg_mmc_spi_polled = true;
84 #else
85 cyg_bool    cyg_mmc_spi_polled = false;
86 #endif
87
88 // Should write operations be allowed to complete in the background,
89 // or must the operation complete in the foreground. The latter
90 // requires polling for potentially a long time, up to some 100's of
91 // milliseconds, but the former appears unreliable if there are other
92 // devices on the SPI bus. In theory the MMC card should detect that
93 // the chip select line is dropped and tristate the output line, but
94 // in practice this does not always happen.
95 #undef MMC_SPI_BACKGROUND_WRITES
96
97 // The size of each disk block
98 #define MMC_SPI_BLOCK_SIZE      512
99 // The number of retries during a mount operation when switching to
100 // IDLE mode.
101 #define MMC_SPI_GO_IDLE_RETRIES 16
102 // The number of retries during a mount operation when switching from
103 // idle to operational
104 #define MMC_SPI_OP_COND_RETRIES 128
105 // The number of retries when waiting for a response to any command
106 #define MMC_SPI_COMMAND_RETRIES 32
107 // Retries when waiting for a data response token during a read
108 #define MMC_SPI_READ_DATA_TOKEN_RETRIES 32768
109 // Retries during a write while waiting for completion
110 #define MMC_SPI_WRITE_BUSY_RETRIES 32768
111
112 // ----------------------------------------------------------------------------
113 // SPI-specific parts of the MMC protocol.
114 //
115 // The main response byte. 0 indicates success, other bits
116 // indicate various error conditions.
117 #define MMC_REPLY_SUCCESS                   0x00
118 #define MMC_REPLY_PARAMETER_ERROR           (0x01 << 6)
119 #define MMC_REPLY_ADDRESS_ERROR             (0x01 << 5)
120 #define MMC_REPLY_ERASE_SEQUENCE_ERROR      (0x01 << 4)
121 #define MMC_REPLY_COM_CRC_ERROR             (0x01 << 3)
122 #define MMC_REPLY_ILLEGAL_COMMAND           (0x01 << 2)
123 #define MMC_REPLY_ERASE_RESET               (0x01 << 1)
124 #define MMC_REPLY_IN_IDLE_STATE             (0x01 << 0)
125
126 // A send-status command generates a second response byte
127 #define MMC_REPLY2_OUT_OF_RANGE             (0x01 << 7)
128 #define MMC_REPLY2_ERASE_PARAM              (0x01 << 6)
129 #define MMC_REPLY2_WP_VIOLATION             (0x01 << 5)
130 #define MMC_REPLY2_CARD_ECC_FAILED          (0x01 << 4)
131 #define MMC_REPLY2_CC_ERROR                 (0x01 << 3)
132 #define MMC_REPLY2_ERROR                    (0x01 << 2)
133 #define MMC_REPLY2_WP_ERASE_SKIP            (0x01 << 1)
134 // Alias for the above
135 #define MMC_REPLY2_LOCK_UNLOCK_FAILED       (0x01 << 1)
136 #define MMC_REPLY2_CARD_LOCKED              (0x01 << 0)
137
138 // The data error token byte which may get sent if a read
139 // operation fails. The top 3 bits will be 0. A successful
140 // response will have these bits 1.
141 #define MMC_DATA_TOKEN_SUCCESS                  (0x00FE)
142 #define MMC_DATA_ERROR_TOKEN_CARD_LOCKED        (0x01 << 4)
143 #define MMC_DATA_ERROR_TOKEN_OUT_OF_RANGE       (0x01 << 3)
144 #define MMC_DATA_ERROR_TOKEN_CARD_ECC_FAILED    (0x01 << 2)
145 #define MMC_DATA_ERROR_TOKEN_CC_ERROR           (0x01 << 1)
146 #define MMC_DATA_ERROR_TOKEN_ERROR              (0x01 << 0)
147
148 // ----------------------------------------------------------------------------
149 // Structures and statics.
150 //
151 // There should be an SPI device cyg_spi_mmc_dev0, probably provided by
152 // the HAL, possibly by the application. Because of the latter we cannot
153 // assume the variable will be defined in a header.
154 extern cyg_spi_device   cyg_spi_mmc_dev0;
155
156 // When retrieving data it is necessary to send an 0xff byte stream,
157 // which the card will not confuse with further commands. The largest
158 // transfer is 512 bytes, too large a buffer to place on the stack.
159 static cyg_uint8        mmc_spi_ff_data[512];
160 #define MMC_SPI_INIT_FF_DATA()              \
161     CYG_MACRO_START                         \
162     memset(mmc_spi_ff_data, 0x00FF, 512);   \
163     CYG_MACRO_END
164
165 // Details of a specific MMC card
166 typedef struct cyg_mmc_spi_disk_info_t {
167     cyg_spi_device*     mmc_spi_dev;
168     cyg_uint32          mmc_saved_baudrate;
169     cyg_uint32          mmc_block_count;
170 #ifdef MMC_SPI_BACKGROUND_WRITES    
171     cyg_bool            mmc_writing;
172 #endif    
173     cyg_bool            mmc_read_only;
174     cyg_bool            mmc_connected;
175     cyg_uint32          mmc_heads_per_cylinder;
176     cyg_uint32          mmc_sectors_per_head;
177     cyg_uint32          mmc_read_block_length;
178     cyg_uint32          mmc_write_block_length;
179     mmc_cid_register    mmc_id;
180 } cyg_mmc_spi_disk_info_t;
181
182 // There is no need for a hardware-specific disk controller structure.
183 // The closest equivalent is probably an SPI bus, i.e. if there were
184 // MMC connectors attached to different SPI buses then these would
185 // have separate controllers with independent locking. However that
186 // can be handled without a cyg_mmc_spi_controller_info_t structure.
187
188 // ----------------------------------------------------------------------------
189 // The low-level MMC operations
190
191 // After power-on an MMC card is in idle state and needs at least 74
192 // clock cycles before any communication. These might be supplied
193 // courtesy of another SPI device, but no guarantees, so generate some
194 // ticks.
195 static void
196 mmc_spi_send_init(cyg_mmc_spi_disk_info_t* disk)
197 {
198     cyg_spi_bus     *bus;
199     cyg_spi_device  *dev;
200
201     DEBUG2("mmc_spi_send_init(): dev pointer 0x%p, %d\n", disk->mmc_spi_dev, cyg_mmc_spi_polled );
202     dev = disk->mmc_spi_dev;
203     bus = dev->spi_bus;
204     DEBUG2("                   : begin pointer %p\n", bus->spi_transaction_begin );
205     cyg_spi_tick(disk->mmc_spi_dev, cyg_mmc_spi_polled, 10);
206 }
207
208 // Send the first part of a command sequence. This consists of the
209 // command itself, an argument, a CRC, and then waiting for a
210 // reply byte from the card.
211 static cyg_uint32
212 mmc_spi_send_command_start(cyg_mmc_spi_disk_info_t* disk, cyg_uint32 command, cyg_uint32 arg)
213 {
214     cyg_spi_device* dev = disk->mmc_spi_dev;
215     cyg_uint8       request[7];
216     cyg_uint8       response[7];
217     cyg_uint8       reply;
218     int             i;
219
220 #ifdef MMC_SPI_BACKGROUND_WRITES    
221     // If the last operation was a block write, those can take a while
222     // to complete. Rather than wait at the end of the write(), do so
223     // at the beginning of the next operation i.e. here. This also
224     // allows the chip select to be dropped while the write comples,
225     // so communication is possible with other devices. The polling is
226     // done as a sequence of transactions rather than in a single
227     // transaction, again to let other threads in to communicate with
228     // other devices.
229     //
230     // The card will send a stream of 0x00 bytes while the write
231     // completes. Some cards have been observed to send a byte 0x03 at
232     // the end, Either way, when the card sends a byte 0xff it should
233     // be ready for the next command.
234     if (disk->mmc_writing) {
235         DEBUG2("mmc_spi_send_command_start(): polling for completion of previous write\n");
236         disk->mmc_writing   = 0;
237         response[0]    = 0x00;
238         for (i = 0; (i < MMC_SPI_WRITE_BUSY_RETRIES) && (0x00FF != response[0]); i++) {
239             cyg_spi_transfer(dev, cyg_mmc_spi_polled, 1, mmc_spi_ff_data, response);
240         }
241     }
242 #endif    
243     
244     request[0]  = command | 0x0040;
245     request[1]  = (arg >> 24) & 0x00FF;
246     request[2]  = (arg >> 16) & 0x00FF;
247     request[3]  = (arg >>  8) & 0x00FF;
248     request[4]  = arg         & 0x00FF;
249     // A CRC is needed for the go-idle-state command, because that
250     // command switches the device from MMC to SPI mode. That CRC is
251     // well-known. Once in SPI mode the card will not use CRCs by
252     // default.
253     request[5]  = (command == 0x00) ? 0x0095 : 0x00ff;
254     // There will need to be at least one extra byte transfer to get
255     // the card's response, so send that straightaway. Extra
256     // outgoing data like this should be 0xff so that the card
257     // does not confuse it with a new incoming command.
258     request[6]  = 0x00ff;
259
260     // Lock the SPI bus. It remains locked until a subsequent call to
261     // mmc_spi_end_command().
262     cyg_spi_transaction_begin(dev);
263     
264     // Transfer the whole command, and try to read the response back
265     // immediately.
266     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 7, request, response, 0);
267     DEBUG2("Sent command %02x %d: reply bytes %02x %02x %02x %02x %02x %02x %02x\n", command, arg, \
268                 response[0], response[1], response[2], response[3], response[4], response[5], response[6]);
269     
270     // The response will be a single byte with the top bit clear.
271     // The remaining bits are error/status flags. If the command
272     // involves an additional response then that will be handled
273     // by the calling code.
274     reply       = response[6];
275     for (i = 0; (i < MMC_SPI_COMMAND_RETRIES) && (0 != (reply & 0x0080)); i++) {
276         cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 1, mmc_spi_ff_data, response, 0);
277         reply = response[0];
278         DEBUG2("  loop %d, additional reply %02x\n", i, reply);
279     }
280
281     // Leave the interpretation of the reply code to the caller
282     return (cyg_uint32) reply;
283 }
284
285 // At the end of each command the card needs eight clocks to finish
286 // its processing. A tick() call takes care of that, and will have
287 // the side effect of dropping the chip select. Ending the transaction
288 // unlocks the bus for other SPI I/O operations
289 static void
290 mmc_spi_end_command(cyg_mmc_spi_disk_info_t* disk)
291 {
292     cyg_spi_device* dev = disk->mmc_spi_dev;
293     cyg_spi_transaction_tick(dev, cyg_mmc_spi_polled, 1);
294     cyg_spi_transaction_end(dev);
295 }
296
297 // A utility combination of the above two for simple commands which do
298 // not involve any other data.
299 static cyg_uint32
300 mmc_spi_send_command(cyg_mmc_spi_disk_info_t* disk, cyg_uint32 command, cyg_uint32 arg)
301 {
302     cyg_uint32  reply;
303     reply = mmc_spi_send_command_start(disk, command, arg);
304     mmc_spi_end_command(disk);
305     return reply;
306 }
307
308 // The card will return a data block when reading a disk block, or
309 // for certain other commands like reading card registers. Each
310 // data block consists of:
311 //   1) some number of padding bytes 0xff while the card is still
312 //      processing the command and preparing the data
313 //   2) a data token byte, usually 0xFE for success
314 //   3) n bytes of data
315 //   4) two bytes of crc, which can be ignored.
316 //
317 // The data token byte is the only indication of success or failure,
318 // so that gets returned.
319 //
320 // When mounting certain types of card an extra delay may be needed
321 // before reading the first data block. This is handled by the
322 // extra_delay argument.
323 static cyg_uint32
324 mmc_spi_read_data(cyg_mmc_spi_disk_info_t* disk, cyg_uint8* buf, cyg_uint32 count, cyg_bool extra_delay)
325 {
326     cyg_spi_device* dev = disk->mmc_spi_dev;
327     int             i;
328     cyg_uint8       response[2];
329     cyg_uint32      retries;
330
331     if (extra_delay) {
332         retries = MMC_SPI_READ_DATA_TOKEN_RETRIES * 100;
333     } else {
334         retries = MMC_SPI_READ_DATA_TOKEN_RETRIES;
335     }
336
337     response[0] = 0x00FF;
338     for (i = 0; (i < retries) && (0x00FF == response[0]); i++) {
339         cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 1, mmc_spi_ff_data, response, 0);
340     }
341     
342     if (MMC_DATA_TOKEN_SUCCESS != response[0]) {
343         DEBUG1("mmc_spi_read_data(): got error response %02x after %d iterations\n", response[0], i);
344         return response[0];
345     }
346
347     // Now for the actual data. There is no way of detecting a failure from
348     // this point on.
349     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, count, mmc_spi_ff_data, buf, 0);
350     // And the CRC, which can be ignored
351     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 2, mmc_spi_ff_data, response, 0);
352     DEBUG2("mmc_spi_read_data(): got data and CRC %02x %02x\n", response[0], response[1]);
353     
354     return MMC_DATA_TOKEN_SUCCESS;
355 }
356
357 // Read one of the card registers, e.g. CSD or CID
358 static Cyg_ErrNo
359 mmc_spi_read_register(cyg_mmc_spi_disk_info_t* disk, cyg_uint32 command, cyg_uint8* buf, cyg_uint32 count)
360 {
361     cyg_uint32      reply;
362     
363     reply = mmc_spi_send_command_start(disk, command, 0);
364     if (MMC_REPLY_SUCCESS != reply) {
365         DEBUG1("mmc_spi_read_register(): unexpected response to command %02x, reply code %02x\n", command, reply);
366         mmc_spi_end_command(disk);
367         return (0x00FF == reply) ? -ENODEV : -EIO;
368     }
369     reply = mmc_spi_read_data(disk, buf, count, false);
370     mmc_spi_end_command(disk);
371     if (MMC_DATA_TOKEN_SUCCESS != reply) {
372         DEBUG1("mmc_spi_read_register(): unexpected response to command %02x, expected 0x00FE data token, got %02x\n", command, reply);
373         return -EIO;
374     }
375     return ENOERR;
376 }
377
378 // Reading a disk block is just a combination of the above utilities.
379 // This code is also responsible for translating error codes, since
380 // higher-level code does not get to see the initial response vs. the
381 // data token byte.
382 static Cyg_ErrNo
383 mmc_spi_read_disk_block(cyg_mmc_spi_disk_info_t* disk, cyg_uint8* buf, cyg_uint32 block, cyg_bool extra_delay)
384 {
385     cyg_uint32 reply;
386     
387     // First the command itself.
388     DEBUG2("mmc_spi_read_disk_block(%d): sending command\n", block);
389     reply = mmc_spi_send_command_start(disk, MMC_REQUEST_READ_SINGLE_BLOCK, block * MMC_SPI_BLOCK_SIZE);
390     if (MMC_REPLY_SUCCESS != reply) {
391         DEBUG1("mmc_spi_read_disk_block(%d): unexpected response to READ_SINGLE_BLOCK command, code %02x\n", block, reply);
392         mmc_spi_end_command(disk);
393         // A byte 0xFF indicates the card has been removed.
394         if (0x00FF == reply) {
395             return -ENODEV;
396         }
397         // Parameter or address error should not occur, higher-level
398         // code should have checked the block to ensure that it is
399         // in range.
400         if (0 != (reply & (MMC_REPLY_PARAMETER_ERROR | MMC_REPLY_ADDRESS_ERROR))) {
401             return -EINVAL;
402         }
403         // The disk should not be in idle state or in an erase sequence. The
404         // command is definitely legal and CRCs should be disabled. So everything
405         // else is an I/O error.
406         return -EIO;
407     }
408     
409     // Now read back the data block. That code can be shared with other read
410     // operations, e.g. for retrieving registers.
411     DEBUG2("mmc_spi_read_disk_block(%d): reading data token/data/crc\n", block);
412     reply = mmc_spi_read_data(disk, buf, MMC_SPI_BLOCK_SIZE, extra_delay);
413     mmc_spi_end_command(disk);
414     if (MMC_DATA_TOKEN_SUCCESS != reply) {
415         DEBUG1("mmc_spi_read_disk_block(%d): failed to retrieve data, error token %02x\n", block, reply);
416         
417         // Possibilities are password-locked, range error, ECC failure
418         // if the raw data is corrupt, CC error for an internal card
419         // error, or some other error. A byte 0xFF indicates the card
420         // has been removed.
421         if (0x00FF == reply) {
422             return -ENODEV;
423         } else if (0 != (MMC_DATA_ERROR_TOKEN_CARD_LOCKED & reply)) {
424             // This should have been caught by a mount operation.
425             return -EPERM;
426         } else if (0 != (MMC_DATA_ERROR_TOKEN_OUT_OF_RANGE & reply)) {
427             return -EINVAL;
428         } else {
429             return -EIO;
430         }
431     }
432     return ENOERR;
433 }
434
435 // Writing a block involves a bit more work. Some of this could be
436 // moved into a utility routine if necessary, shared with code for
437 // e.g. updating the CSD register, but for now that other functionality
438 // is not needed.
439 static Cyg_ErrNo
440 mmc_spi_write_disk_block(cyg_mmc_spi_disk_info_t* disk, const cyg_uint8* buf, cyg_uint32 block)
441 {
442     cyg_spi_device* dev = disk->mmc_spi_dev;
443     cyg_uint32      reply;
444     cyg_uint8       extra[4];
445     int             i;
446    
447     // First, send the command itself and get the initial response
448     DEBUG2("mmc_spi_write_disk_block(), sending command\n");
449     reply = mmc_spi_send_command_start(disk, MMC_REQUEST_WRITE_BLOCK, block * MMC_SPI_BLOCK_SIZE);
450     if (MMC_REPLY_SUCCESS != reply) {
451         DEBUG1("mmc_spi_write_disk_block(): unexpected response to WRITE_BLOCK command, code %02x\n", reply);
452         mmc_spi_end_command(disk);
453         if (0x00FF == reply) {
454             return -ENODEV;
455         }
456         // Parameter or address error should not occur, higher-level
457         // code should have checked the block to ensure that it is
458         // in range.
459         if (0 != (reply & (MMC_REPLY_PARAMETER_ERROR | MMC_REPLY_ADDRESS_ERROR))) {
460             return -EINVAL;
461         }
462         // The disk should not be in idle state or in an erase sequence. The
463         // command is definitely legal and CRCs should be disabled. So everything
464         // else is an I/O error.
465         return -EIO;
466     }
467
468     // The card is now expecting a data block. This consists of a single byte
469     // 0x00FE, then the data itself, and a dummy CRC. The reply from the card
470     // does not contain any useful information.
471     DEBUG2("mmc_spi_write_disk_block(): sending data token/data/crc\n");
472     extra[0]    = 0x00FE;
473     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 1, extra, (cyg_uint8*)0, 0);
474     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, MMC_SPI_BLOCK_SIZE, buf, (cyg_uint8*)0, 0);
475     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 2, mmc_spi_ff_data, (cyg_uint8*)0, 0);
476
477     // The card should respond immediately with a data response token.
478     cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 1, mmc_spi_ff_data, extra, 0);
479     DEBUG2("mmc_spi_write_disk_block(): got data response token %02x\n", extra[0]);
480
481     // The bottom five bits contain the response. 00101 indicates success,
482     // anything else is a CRC error. Everything else will have been checked
483     // before the data got transferred.
484     if (0x05 != (extra[0] & 0x1F)) {
485         DEBUG1("mmc_spi_write_disk_block(): invalid data response token %02x\n", extra[0]);
486         mmc_spi_end_command(disk);
487         if (0x00FF == extra[0]) {
488             return -ENODEV;
489         }
490         return -EIO;
491     }
492
493 #ifdef MMC_SPI_BACKGROUND_WRITES    
494     // Mark the card as writing. The next operation will poll for completion.
495     disk->mmc_writing   = true;
496 #else
497     // The card is now busy doing the write and will output a stream of 0's
498     // while busy. The timeout should really be calculated using the CSD
499     // register settings.
500     //
501     // It should be legal to drop the chip select here, i.e. to end
502     // the current transaction and start a new one for each poll
503     // operation. That would allow other SPI devices to be accessed.
504     // However it appears that this does not work with all MMC cards.
505     extra[0]    = 0x00;
506     for (i = 0; (i < MMC_SPI_WRITE_BUSY_RETRIES) && (0x00 == extra[0]); i++) {
507         cyg_spi_transaction_transfer(dev, cyg_mmc_spi_polled, 1, mmc_spi_ff_data, extra, 0);
508         DEBUG2("mmc_spi_write_disk_block(), polling for ! busy, got response %02x\n", extra[0]);
509     }
510 #endif
511     
512     // Assume that the loop did in fact terminate.
513     mmc_spi_end_command(disk);
514     return ENOERR;
515 }
516
517 // MMC sockets will default to a slow clockrate. During a successful mount
518 // the SPI device settings will be changed to the fastest supported by the
519 // card, as per the CSD register. This will need to be undone during an
520 // unmount, or if the final stages of a mount are unsuccessful.
521 static void
522 mmc_spi_restore_baud(cyg_mmc_spi_disk_info_t* disk)
523 {
524     cyg_uint32  len = sizeof(cyg_uint32);
525     (void) cyg_spi_set_config(disk->mmc_spi_dev, CYG_IO_SET_CONFIG_SPI_CLOCKRATE, (void*) &(disk->mmc_saved_baudrate), &len);
526 }
527
528 // check_for_disk() tries to communicate with an MMC card that is not
529 // currently mounted. It performs the appropriate initialization so
530 // that read and write operations are possible, checks the disk format,
531 // distinguishes between read-only and read-write cards, calculates the
532 // card size, stores the unique id, etc.
533 //
534 // The main error conditions are ENODEV (no card), EIO (card not
535 // responding sensibly to requests), ENOTDIR (wrong format), or EPERM
536 // (card is password-locked).
537 static Cyg_ErrNo
538 mmc_spi_check_for_disk(cyg_mmc_spi_disk_info_t* disk)
539 {
540     cyg_spi_device*     dev = disk->mmc_spi_dev;
541     int                 i;
542     cyg_uint32          reply;
543     Cyg_ErrNo           code;
544     mmc_csd_register    csd;
545
546 #ifdef MMC_SPI_BACKGROUND_WRITES    
547     // If we have unmounted a disk and are remounting it, assume that
548     // any writes have completed.
549     disk->mmc_writing   = false;
550 #endif    
551     reply               = 0x00ff;
552     
553     for (i = 0; (i < MMC_SPI_GO_IDLE_RETRIES) && (0x01 != reply); i++) {
554         // Allow platform HALs to provide additional initialization,
555         // if the hardware needs it.
556 #ifdef HAL_MMC_SPI_INIT
557         HAL_MMC_SPI_INIT(dev, reply);
558         if (! reply) {
559             return -ENODEV;
560         }
561 #endif
562         // MMC cards generic initialization. The card may have just
563         // been plugged in so there is no guarantee that any previous
564         // init() calls or other traffic will have affected this card.
565         mmc_spi_send_init(disk);
566     
567         // Now set the card to idle state. This involves the GO_IDLE_STATE
568         // command which will be accepted irrespective of whether the card is
569         // currently in MMC or SPI mode, and will leave the card in SPI mode.
570         reply = mmc_spi_send_command(disk, MMC_REQUEST_GO_IDLE_STATE, 0);
571
572         // The card should reply with 0x01. FF suggests that there is
573         // no card. Any other response indicates some synchronization
574         // problem. For example the card might still be responding to
575         // some request from a previous session which aborted at an
576         // inconvenient moment. Some dummy traffic is generated in the
577         // hope that this gets things back in sync.
578         if (0x01 != reply) {
579             DEBUG1("mmc_spi_check_for_disk(): loop %d, card did not enter idle state, code %02x\n", i, reply);
580             if (0x0ff != reply) {
581                 cyg_spi_transfer(dev, cyg_mmc_spi_polled, 128, mmc_spi_ff_data, (cyg_uint8*) 0);
582             }
583         }
584     }
585     if (0x0ff == reply) {
586         DEBUG1("mmc_spi_check_for_disk(): unable to get a response from the MMC card: code %02x\n", reply);
587         // A working card should be returning some data
588         return -ENODEV;
589     }
590     if (0x01 != reply) {
591         DEBUG1("mmc_spi_check_for_disk(): card did not enter idle state, code %02x\n", reply);
592         return -EIO;
593     }
594     
595     // Next, wait for the card to initialize. This involves repeatedly
596     // trying the SEND_OP_COND command until we get a reply that is
597     // not idle
598     reply = 0x00ff;
599     for (i = 0; (i < MMC_SPI_OP_COND_RETRIES) && ((0x00ff == reply) || (0 != (MMC_REPLY_IN_IDLE_STATE & reply))); i++) {
600 #ifdef CYGPKG_DEVS_DISK_MMC_SPI_IDLE_RETRIES_WAIT
601         CYGACC_CALL_IF_DELAY_US(CYGPKG_DEVS_DISK_MMC_SPI_IDLE_RETRIES_WAIT);
602 #endif
603         reply = mmc_spi_send_command(disk, MMC_REQUEST_SEND_OP_COND, 0);
604     }
605     if (MMC_REPLY_SUCCESS != reply) {
606         DEBUG1("mmc_spi_check_for_disk(): card has not entered operational state: reply code %02x\n", reply);
607         return (0x00FF == reply) ? -ENODEV : -EIO;
608     }
609
610     // The card has now generated sufficient responses that we don't need to
611     // worry about a missing card anymore.
612     // Get hold of the card's unique ID and store it, to allow disk changes
613     // to be detected.
614     code = mmc_spi_read_register(disk, MMC_REQUEST_SEND_CID, (cyg_uint8*) &(disk->mmc_id), 16);
615     if (code) {
616         mmc_spi_end_command(disk);
617         return code;
618     }
619     DEBUG2("CID data: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",               \
620            disk->mmc_id.cid_data[ 0], disk->mmc_id.cid_data[ 1], disk->mmc_id.cid_data[ 2], disk->mmc_id.cid_data[ 3],  \
621            disk->mmc_id.cid_data[ 4], disk->mmc_id.cid_data[ 5], disk->mmc_id.cid_data[ 6], disk->mmc_id.cid_data[ 7],  \
622            disk->mmc_id.cid_data[ 8], disk->mmc_id.cid_data[ 9], disk->mmc_id.cid_data[10], disk->mmc_id.cid_data[11],  \
623            disk->mmc_id.cid_data[12], disk->mmc_id.cid_data[13], disk->mmc_id.cid_data[14], disk->mmc_id.cid_data[15]);
624 #if DEBUG > 0
625     DEBUG1("CID data: register\n");
626     DEBUG1("        : Manufacturer ID       : MID = 0x%02x\n", MMC_CID_REGISTER_MID(&(disk->mmc_id)) & 0xff);
627     DEBUG1("        : OEM/Application ID    : OID = 0x%04x\n", MMC_CID_REGISTER_OID(&(disk->mmc_id)) & 0xffff);
628     DEBUG1("        : Product name          : PNM = 0x%02x%02x%02x%02x%02x%02x\n",
629                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[0] & 0xff,
630                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[1] & 0xff,
631                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[2] & 0xff,
632                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[3] & 0xff,
633                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[4] & 0xff,
634                                                                MMC_CID_REGISTER_PNM(&(disk->mmc_id))[5] & 0xff);
635     DEBUG1("        : Product revision      : PRV = 0x%02x\n", MMC_CID_REGISTER_PRV(&(disk->mmc_id)) & 0xff);
636     DEBUG1("        : Product serial number : PSN = 0x%08x\n", MMC_CID_REGISTER_PSN(&(disk->mmc_id)) & 0xffffffff);
637     DEBUG1("        : Manufacturing date    : MDT = 0x%02x\n", MMC_CID_REGISTER_MDT(&(disk->mmc_id)) & 0xff);
638     DEBUG1("        : 7-bit CRC checksum    : CRC = 0x%02x\n", MMC_CID_REGISTER_CRC(&(disk->mmc_id)) & 0xff);
639 #endif
640
641     // And retrieve the card's configuration data.
642     code = mmc_spi_read_register(disk, MMC_REQUEST_SEND_CSD, (cyg_uint8*) &csd, 16);
643     if (code) {
644         mmc_spi_end_command(disk);
645         return code;
646     }
647     DEBUG2("CSD data: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",   \
648            csd.csd_data[ 0], csd.csd_data[ 1], csd.csd_data[ 2], csd.csd_data[3],                           \
649            csd.csd_data[ 4], csd.csd_data[ 5], csd.csd_data[ 6], csd.csd_data[7],                           \
650            csd.csd_data[ 8], csd.csd_data[ 9], csd.csd_data[10], csd.csd_data[11],                          \
651            csd.csd_data[12], csd.csd_data[13], csd.csd_data[14], csd.csd_data[15]);
652     
653     // Optionally dump the whole CSD register. This takes a lot of
654     // code but gives a lot of info about the card. If the info looks
655     // correct then we really are interacting properly with an MMC card.
656 #if DEBUG > 0
657     DEBUG1("CSD data: structure 0x%02x, version 0x%02x\n", MMC_CSD_REGISTER_CSD_STRUCTURE(&csd), MMC_CSD_REGISTER_SPEC_VERS(&csd));
658     if (0 != MMC_CSD_REGISTER_FILE_FORMAT_GROUP(&csd)) {
659         DEBUG1("        : Reserved (unknown), FILE_FORMAT_GROUP %d, FILE_FORMAT %d\n", \
660                     MMC_CSD_REGISTER_FILE_FORMAT_GROUP(&csd), MMC_CSD_REGISTER_FILE_FORMAT(&csd));
661     } else if (0 == MMC_CSD_REGISTER_FILE_FORMAT(&csd)) {
662         DEBUG1("        : Partioned disk, FILE_FORMAT_GROUP 0, FILE_FORMAT 0\n");
663     } else if (1 == MMC_CSD_REGISTER_FILE_FORMAT(&csd)) {
664         DEBUG1("        : FAT disk, FILE_FORMAT_GROUP 0, FILE_FORMAT 1\n");
665     } else if (2 == MMC_CSD_REGISTER_FILE_FORMAT(&csd)) {
666         DEBUG1("        : Universal File format, FILE_FORMAT_GROUP 0, FILE_FORMAT 2\n");
667     } else {
668         DEBUG1("        : Others/Unknown disk, FILE_FORMAT_GROUP 0, FILE_FORMAT 3\n");
669     }
670     {
671         static const cyg_uint32 mantissa_speeds_x10[16]   = { 0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80 };
672         static const cyg_uint32 exponent_speeds_div10[8]  = { 10000, 100000, 1000000, 10000000, 0, 0, 0, 0 };
673         cyg_uint32 speed = mantissa_speeds_x10[MMC_CSD_REGISTER_TRAN_SPEED_MANTISSA(&csd)] *
674             exponent_speeds_div10[MMC_CSD_REGISTER_TRAN_SPEED_EXPONENT(&csd)];
675         speed /= 1000;
676         DEBUG1("        : TRAN_SPEED %d %d -> %d kbit/s\n", \
677                MMC_CSD_REGISTER_TRAN_SPEED_MANTISSA(&csd), MMC_CSD_REGISTER_TRAN_SPEED_EXPONENT(&csd), speed);
678     }        
679     DEBUG1("        : READ_BL_LEN block length 2^%d (%d)\n", MMC_CSD_REGISTER_READ_BL_LEN(&csd), \
680                 0x01 << MMC_CSD_REGISTER_READ_BL_LEN(&csd));
681     DEBUG1("        : C_SIZE %d, C_SIZE_MULT %d\n", MMC_CSD_REGISTER_C_SIZE(&csd), MMC_CSD_REGISTER_C_SIZE_MULT(&csd));
682     {
683         cyg_uint32 block_len = 0x01 << MMC_CSD_REGISTER_READ_BL_LEN(&csd);
684         cyg_uint32 mult      = 0x01 << (MMC_CSD_REGISTER_C_SIZE_MULT(&csd) + 2);
685         cyg_uint32 size      = block_len * mult * (MMC_CSD_REGISTER_C_SIZE(&csd) + 1);
686         cyg_uint32 sizeK     = (cyg_uint32) (size / 1024);
687         cyg_uint32 sizeM     =  sizeK / 1024;
688         sizeK  -= (sizeM * 1024);
689         DEBUG1("        : total card size %dM%dK\n", sizeM, sizeK);
690     }
691     DEBUG1("        : WR_BL_LEN block length 2^%d (%d)\n", \
692            MMC_CSD_REGISTER_WRITE_BL_LEN(&csd), 0x01 << MMC_CSD_REGISTER_WRITE_BL_LEN(&csd));
693     {
694         static cyg_uint32 taac_mantissa_speeds_x10[16]   = { 0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80 };
695         static cyg_uint32 taac_exponent_speeds_div10[8]  = { 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
696         cyg_uint32 taac_speed = taac_mantissa_speeds_x10[MMC_CSD_REGISTER_TAAC_MANTISSA(&csd)] *
697             taac_exponent_speeds_div10[MMC_CSD_REGISTER_TAAC_EXPONENT(&csd)];
698         taac_speed /= 100;
699         DEBUG1("        : asynchronous read access time TAAC %d %d -> %d ns\n", \
700                MMC_CSD_REGISTER_TAAC_MANTISSA(&csd), MMC_CSD_REGISTER_TAAC_EXPONENT(&csd), taac_speed);
701     }
702     DEBUG1("        : synchronous read access time NSAC %d * 100 cycles\n", \
703            MMC_CSD_REGISTER_NSAC(&csd));
704     DEBUG1("        : typical write program time %d * read time\n", MMC_CSD_REGISTER_R2W_FACTOR(&csd));
705     DEBUG1("        : CCC command classes 0x%04x\n", MMC_CSD_REGISTER_CCC(&csd));
706     DEBUG1("        : READ_BL_PARTIAL %d, WRITE_BLK_MISALIGN %d, READ_BLK_MISALIGN %d, DSR_IMP %d\n",   \
707            MMC_CSD_REGISTER_READ_BL_PARTIAL(&csd), MMC_CSD_REGISTER_WRITE_BLK_MISALIGN(&csd),           \
708            MMC_CSD_REGISTER_READ_BLK_MISALIGN(&csd), MMC_CSD_REGISTER_DSR_IMP(&csd));
709     DEBUG1("        : WR_BL_PARTIAL %d\n", MMC_CSD_REGISTER_WR_BL_PARTIAL(&csd));
710     {
711         static cyg_uint8    min_currents[8] = { 1, 1, 5, 10, 25, 35, 60, 100 };
712         static cyg_uint8    max_currents[8] = { 1, 5, 10, 25, 35, 45, 80, 200 };
713         DEBUG1("        : read current min %dmA, max %dmA\n",               \
714                     min_currents[MMC_CSD_REGISTER_VDD_R_CURR_MIN(&csd)],    \
715                     max_currents[MMC_CSD_REGISTER_VDD_R_CURR_MAX(&csd)]);
716         DEBUG1("        : write current min %dmA, max %dmA\n",              \
717                     min_currents[MMC_CSD_REGISTER_VDD_W_CURR_MIN(&csd)],    \
718                     max_currents[MMC_CSD_REGISTER_VDD_W_CURR_MAX(&csd)]);
719     }
720     DEBUG1("        : erase sector size %d, erase group size %d\n", \
721            MMC_CSD_REGISTER_SECTOR_SIZE(&csd) + 1, MMC_CSD_REGISTER_ERASE_GRP_SIZE(&csd) + 1);
722     DEBUG1("        : write group enable %d, write group size %d\n", \
723            MMC_CSD_REGISTER_WR_GRP_ENABLE(&csd), MMC_CSD_REGISTER_WR_GRP_SIZE(&csd) + 1);
724     DEBUG1("        : copy bit %d\n", MMC_CSD_REGISTER_COPY(&csd));
725     DEBUG1("        : permanent write protect %d, temporary write protect %d\n", \
726            MMC_CSD_REGISTER_PERM_WRITE_PROTECT(&csd), MMC_CSD_REGISTER_TMP_WRITE_PROTECT(&csd));
727     DEBUG1("        : ecc %d, default ecc %d\n", MMC_CSD_REGISTER_ECC(&csd), MMC_CSD_REGISTER_DEFAULT_ECC(&csd));
728     DEBUG1("        : crc 0x%08x\n", MMC_CSD_REGISTER_CRC(&csd));
729 #endif                
730
731     // There is information available about the file format, e.g.
732     // partitioned vs. simple FAT. With the current version of the
733     // generic disk code this needs to be known statically, via
734     // the mbr field of the disk channel structure. If the card
735     // is inappropriately formatted, reject the mount request.
736     if ((0 != MMC_CSD_REGISTER_FILE_FORMAT_GROUP(&csd)) ||
737         (0 != MMC_CSD_REGISTER_FILE_FORMAT(&csd))) {
738         return -ENOTDIR;
739     }
740
741     // Look for a write-protect bit (permanent or temporary), and set
742     // the disk as read-only or read-write as appropriate. The
743     // temporary write-protect could be cleared by rewriting the CSD
744     // register (including recalculating the CRC) but the effort
745     // involves does not seem worth-while.
746     if ((0 != MMC_CSD_REGISTER_PERM_WRITE_PROTECT(&csd)) || (0 != MMC_CSD_REGISTER_TMP_WRITE_PROTECT(&csd))) {
747         disk->mmc_read_only   = true;
748     } else {
749         disk->mmc_read_only   = false;
750     }
751     DEBUG1("Disk read-only flag %d\n", disk->mmc_read_only);
752     
753     // Calculate the disk size, primarily for assertion purposes.
754     // By design MMC cards are limited to 4GB, which still doesn't
755     // quite fit into 32 bits.
756     disk->mmc_block_count = (((cyg_uint64)(0x01 << MMC_CSD_REGISTER_READ_BL_LEN(&csd))) *
757                              ((cyg_uint64)(0x01 << (MMC_CSD_REGISTER_C_SIZE_MULT(&csd) + 2))) *
758                              ((cyg_uint64)(MMC_CSD_REGISTER_C_SIZE(&csd) + 1))) / (cyg_uint64)MMC_SPI_BLOCK_SIZE;
759     DEBUG1("Disk blockcount %d (0x%08x)\n", disk->mmc_block_count, disk->mmc_block_count);
760     
761     // Assume for now that the block length is 512 bytes. This is
762     // probably a safe assumption since we have just got the card
763     // initialized out of idle state. If it ever proves to be a problem
764     // the SET_BLOCK_LEN command can be used.
765     // Nevertheless store the underlying block sizes
766     disk->mmc_read_block_length  = 0x01 << MMC_CSD_REGISTER_READ_BL_LEN(&csd);
767     disk->mmc_write_block_length = 0x01 << MMC_CSD_REGISTER_WRITE_BL_LEN(&csd);
768
769     // The CSD contains the maximum supported transfer speed. Adjust
770     // the SPI device to match, saving the old value for an unmount
771     // operation. It is assumed that the SPI bus driver will munge
772     // the supplied speed to something appropriate.
773     {
774         static const cyg_uint32 mantissa_speeds_x10[16]   = { 0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80 };
775         static const cyg_uint32 exponent_speeds_div10[8]  = { 10000, 100000, 1000000, 10000000, 0, 0, 0, 0 };
776         cyg_uint32 speed, len;
777         
778         len = sizeof(cyg_uint32);
779         if (cyg_spi_get_config(dev, CYG_IO_GET_CONFIG_SPI_CLOCKRATE, (void*) &disk->mmc_saved_baudrate, &len)) {
780             DEBUG1("Failed to retrieve current SPI device clockrate\n");
781             return -EIO;
782         }
783         speed = mantissa_speeds_x10[MMC_CSD_REGISTER_TRAN_SPEED_MANTISSA(&csd)] * exponent_speeds_div10[MMC_CSD_REGISTER_TRAN_SPEED_EXPONENT(&csd)];
784         if (speed > disk->mmc_saved_baudrate) {
785             DEBUG1("Old SPI speed %d, switching to %d\n", disk->mmc_saved_baudrate, speed);
786             cyg_spi_set_config(dev, CYG_IO_SET_CONFIG_SPI_CLOCKRATE, (void*) &speed, &len);
787         } else {
788             DEBUG1("Old SPI speed %d already greater than max speed %d, leaving it alone\n",
789                    disk->mmc_saved_baudrate, speed);
790         }
791     }
792
793     // Read the partition table off the card. This is a way of
794     // checking that the card is not password-locked. It also
795     // provides information about the "disk geometry" which is
796     // needed by higher-level code.
797     // FIXME: the higher-level code should be made to use LBA
798     // addressing instead.
799     {
800         cyg_uint8   data[MMC_SPI_BLOCK_SIZE];
801         cyg_uint8*  partition;
802         cyg_uint32  lba_first, lba_size, lba_end, head, cylinder, sector;
803         
804         code = mmc_spi_read_disk_block(disk, data, 0, true);
805         if (code) {
806             mmc_spi_restore_baud(disk);
807             return code;
808         }
809 #if DEBUG > 1
810         {
811             cyg_uint8 *ptr_data;
812
813             DEBUG2("MBR dump\n");
814             for (i = 0; i < MMC_SPI_BLOCK_SIZE; i += 16) {
815                 ptr_data = &data[i];
816                 DEBUG2(" %04x: %02x %02x %02x %02x  %02x %02x %02x %02x  %02x %02x %02x %02x  %02x %02x %02x %02x\n",
817                     i,
818                     ptr_data[ 0], ptr_data[ 1], ptr_data[ 2], ptr_data[ 3],
819                     ptr_data[ 4], ptr_data[ 5], ptr_data[ 6], ptr_data[ 7],
820                     ptr_data[ 8], ptr_data[ 9], ptr_data[10], ptr_data[11],
821                     ptr_data[12], ptr_data[13], ptr_data[14], ptr_data[15]);
822             }
823         }
824 #endif
825 #if DEBUG > 0
826         DEBUG1("Read block 0 (partition table)\n");
827         DEBUG1("Signature 0x%02x 0x%02x, should be 0x55 0xaa\n", data[0x1fe], data[0x1ff]);
828         // There should be four 16-byte partition table entries at offsets
829         // 0x1be, 0x1ce, 0x1de and 0x1ee. The numbers are stored little-endian
830         for (i = 0; i < 4; i++) {
831             partition = &(data[0x1be + (0x10 * i)]);
832             DEBUG1("Partition %d: boot %02x, first sector %02x %02x %02x, file system %02x, last sector %02x %02x %02x\n", i,   \
833                    partition[0], partition[1], partition[2], partition[3], partition[4], \
834                    partition[5], partition[6], partition[7]);
835             DEBUG1("           : first sector (linear) %02x %02x %02x %02x, sector count %02x %02x %02x %02x\n", \
836                    partition[11], partition[10], partition[9], partition[8], \
837                    partition[15], partition[14], partition[13], partition[12]);
838         }
839 #endif        
840         if ((0x0055 != data[0x1fe]) || (0x00aa != data[0x1ff])) {
841             mmc_spi_restore_baud(disk);
842             return -ENOTDIR;
843         }
844         partition   = &(data[0x1be]);
845         lba_first   = (partition[11] << 24) | (partition[10] << 16) | (partition[9] << 8) | partition[8];
846         lba_size    = (partition[15] << 24) | (partition[14] << 16) | (partition[13] << 8) | partition[12];
847         lba_end     = lba_first + lba_size - 1;
848
849         // First sector in c/h/s format
850         cylinder    = ((partition[2] & 0xC0) << 2) | partition[3];
851         head        = partition[1];
852         sector      = partition[2] & 0x3F;
853
854         // lba_start == (((cylinder * Nh) + head) * Ns) + sector - 1, where (Nh == heads/cylinder) and (Ns == sectors/head)
855         // Strictly speaking we should be solving some simultaneous
856         // equations here for lba_start/lba_end, but that gets messy.
857         // The first partition is at the start of the card so cylinder will be 0,
858         // and we can ignore Nh.
859         CYG_ASSERT(0 == cylinder, "Driver assumption - partition 0 is at start of card\n");
860         CYG_ASSERT(0 != head,     "Driver assumption - partition table is sensible\n");
861         disk->mmc_sectors_per_head = ((lba_first + 1) - sector) / head;
862
863         // Now for lba_end.
864         cylinder    = ((partition[6] & 0xC0) << 2) | partition[7];
865         head        = partition[5];
866         sector      = partition[6] & 0x3F;
867         disk->mmc_heads_per_cylinder = ((((lba_end + 1) - sector) / disk->mmc_sectors_per_head) - head) / cylinder;
868     }
869     
870     return ENOERR;
871 }
872
873 // Check that the current card is the one that was previously
874 // accessed. This may fail if the card has been removed and the
875 // slot is empty, or if the card has been removed and a different
876 // one inserted. It may pass incorrectly if a card is removed,
877 // modified elsewhere, and reinserted without eCos noticing.
878 // There is no way around that without some way of detecting
879 // disk removal in hardware.
880 //
881 // Re-reading the cid may actually be overkill. If a new card
882 // has been plugged in then it will not have been initialized so
883 // it will respond with 0xff anyway. It is very unlikely that
884 // an init sequence will have happened by accident.
885 static cyg_bool
886 mmc_spi_disk_changed(cyg_mmc_spi_disk_info_t* disk)
887 {
888     mmc_cid_register    cid;
889     Cyg_ErrNo           code;
890
891     code = mmc_spi_read_register(disk, MMC_REQUEST_SEND_CID, (cyg_uint8*) &cid, 16);
892     if (-ENODEV == code) {
893         return true;
894     }
895
896     if (0 != memcmp(&cid, &(disk->mmc_id), sizeof(mmc_cid_register))) {
897         return true;
898     }
899     return false;
900 }
901
902 // ----------------------------------------------------------------------------
903
904 // No hardware initialization is performed here. Even if a card is
905 // currently plugged in it may get removed before it gets mounted, so
906 // there is no point looking at the card here. It is still necessary
907 // to invoke the callback init function so that higher-level code gets
908 // a chance to do its bit.
909 static cyg_bool
910 mmc_spi_disk_init(struct cyg_devtab_entry* tab)
911 {
912     disk_channel*   chan    = (disk_channel*) tab->priv;
913     MMC_SPI_INIT_FF_DATA();
914     return (*chan->callbacks->disk_init)(tab);
915 }
916
917 // lookup() is called during a mount() operation, so this is the right
918 // place to check whether or not there is a card.
919
920 static char*
921 mmc_spi_disk_lookup_itoa(cyg_uint32 num, char* where)
922 {
923     if (0 == num) {
924         *where++ = '0';
925     } else {
926         char local[10];  // 2^32 just fits into 10 places
927         int  index = 9;
928         while (num > 0) {
929             local[index--] = (num % 10) + '0';
930             num /= 10;
931         }
932         for (index += 1; index < 10; index++) {
933             *where++ = local[index];
934         }
935     }
936     return where;
937 }
938
939 static Cyg_ErrNo
940 mmc_spi_disk_lookup(struct cyg_devtab_entry** tab, struct cyg_devtab_entry *sub_tab, const char* name)
941 {
942     disk_channel*               chan    = (disk_channel*) (*tab)->priv;
943     cyg_mmc_spi_disk_info_t*    disk    = (cyg_mmc_spi_disk_info_t*) chan->dev_priv;
944     Cyg_ErrNo                   result;
945
946     DEBUG2("mmc_spi_disk_lookup(): target name=%s\n", name );
947     DEBUG2("                     : device name=%s dep_name=%s\n", tab[0]->name, tab[0]->dep_name );
948     DEBUG2("                     : sub    name=%s dep_name=%s\n", sub_tab->name, sub_tab->dep_name );
949
950     if (disk->mmc_connected) {
951         // There was a card plugged in last time we looked. Is it still there?
952         if (mmc_spi_disk_changed(disk)) {
953             // The old card is gone. Either there is no card plugged in, or
954             // it has been replaced with a different one. If the latter the
955             // existing mounts must be removed before anything sensible
956             // can be done.
957             disk->mmc_connected = false;
958             (*chan->callbacks->disk_disconnected)(chan);
959             if (0 != chan->info->mounts) {
960                 return -ENODEV;
961             }
962         }
963     }
964
965     if ((0 != chan->info->mounts) && !disk->mmc_connected) {
966         // There are still mount points to an old card. We cannot accept
967         // new mount requests until those have been cleaned out.
968         return -ENODEV;
969     }
970
971     if (!disk->mmc_connected) {
972         cyg_disk_identify_t ident;
973         cyg_uint32          id_data;
974         char*               where;
975         int                 i;
976         
977         // The world is consistent and the higher-level code does not
978         // know anything about the current card, if any. Is there a
979         // card?
980         result = mmc_spi_check_for_disk(disk);
981         if (ENOERR != result) {
982             return result;
983         }
984         // A card has been found. Tell the higher-level code about it.
985         // This requires an identify structure, although it is not
986         // entirely clear what purpose that serves.
987         disk->mmc_connected = true;
988         // Serial number, up to 20 characters; The CID register contains
989         // various fields which can be used for this.
990         where   = &(ident.serial[0]);
991         id_data = disk->mmc_id.cid_data[0];   // 1-byte manufacturer id -> 3 chars, 17 left
992         where   = mmc_spi_disk_lookup_itoa(id_data, where);
993         id_data = (disk->mmc_id.cid_data[1] << 8) + disk->mmc_id.cid_data[2]; // 2-byte OEM ID, 5 chars, 12 left
994         where   = mmc_spi_disk_lookup_itoa(id_data, where);
995         id_data = (disk->mmc_id.cid_data[10] << 24) + (disk->mmc_id.cid_data[11] << 16) +
996             (disk->mmc_id.cid_data[12] << 8) + disk->mmc_id.cid_data[13];
997         where   = mmc_spi_disk_lookup_itoa(id_data, where); // 4-byte OEM ID, 10 chars, 2 left
998         // And terminate the string with a couple of places to spare.
999         *where = '\0';
1000
1001         // Firmware revision number. There is a one-byte product
1002         // revision number in the CID, BCD-encoded
1003         id_data = disk->mmc_id.cid_data[9] >> 4;
1004         if (id_data <= 9) {
1005             ident.firmware_rev[0] = id_data + '0';
1006         } else {
1007             ident.firmware_rev[0] = id_data - 10 + 'A';
1008         }
1009         id_data = disk->mmc_id.cid_data[9] & 0x0F;
1010         if (id_data <= 9) {
1011             ident.firmware_rev[1] = id_data + '0';
1012         } else {
1013             ident.firmware_rev[1] = id_data - 10 + 'A';
1014         }
1015         ident.firmware_rev[2]   = '\0';
1016         
1017         // Model number. There is a six-byte product name in the CID.
1018         for (i = 0; i < 6; i++) {
1019             if ((disk->mmc_id.cid_data[i + 3] >= 0x20) && (disk->mmc_id.cid_data[i+3] <= 0x7E)) {
1020                 ident.model_num[i] = disk->mmc_id.cid_data[i + 3];
1021             } else {
1022                 break;
1023             }
1024         }
1025         ident.model_num[i] = '\0';
1026
1027         // We don't have no cylinders, heads, or sectors, but
1028         // higher-level code may interpret partition data using C/H/S
1029         // addressing rather than LBA. Hence values for some of these
1030         // settings were calculated above.
1031         ident.cylinders_num     = 1;
1032         ident.heads_num         = disk->mmc_heads_per_cylinder;
1033         ident.sectors_num       = disk->mmc_sectors_per_head;
1034         ident.lba_sectors_num   = disk->mmc_block_count;
1035         ident.phys_block_size   = disk->mmc_write_block_length/512;
1036         ident.max_transfer      = disk->mmc_write_block_length;
1037
1038         DEBUG1("Calling disk_connected(): serial %s, firmware %s, model %s, heads %d, sectors %d, lba_sectors_num %d, phys_block_size %d\n", \
1039                ident.serial, ident.firmware_rev, ident.model_num, ident.heads_num, ident.sectors_num,
1040                ident.lba_sectors_num, ident.phys_block_size);
1041         (*chan->callbacks->disk_connected)(*tab, &ident);
1042
1043         // We now have a valid card and higher-level code knows about it. Fall through.
1044     }
1045
1046     // And leave it to higher-level code to finish the lookup, taking
1047     // into accounts partitions etc.
1048     return (*chan->callbacks->disk_lookup)(tab, sub_tab, name);
1049 }
1050
1051 static Cyg_ErrNo
1052 mmc_spi_disk_read(disk_channel* chan, void* buf_arg, cyg_uint32 blocks, cyg_uint32 first_block)
1053 {
1054     cyg_mmc_spi_disk_info_t*    disk    = (cyg_mmc_spi_disk_info_t*) chan->dev_priv;
1055     cyg_uint32                  i;
1056     cyg_uint8*                  buf = (cyg_uint8*) buf_arg;
1057     Cyg_ErrNo                   code = ENOERR;
1058     
1059     DEBUG1("mmc_spi_disk_read(): first block %d, buf %p, len %lu blocks (%lu bytes)\n",
1060            first_block, buf, (unsigned long)blocks, (unsigned long)blocks*512);
1061
1062     if (! disk->mmc_connected) {
1063         return -ENODEV;
1064     }
1065     if ((first_block + blocks) >= disk->mmc_block_count) {
1066         return -EINVAL;
1067     }
1068
1069     for (i = 0; (i < blocks) && (ENOERR == code); i++) {
1070         code = mmc_spi_read_disk_block(disk, buf, first_block + i, false);
1071         buf += MMC_SPI_BLOCK_SIZE;
1072     }
1073     return code;
1074 }
1075
1076 static Cyg_ErrNo
1077 mmc_spi_disk_write(disk_channel* chan, const void* buf_arg, cyg_uint32 blocks, cyg_uint32 first_block)
1078 {
1079     cyg_mmc_spi_disk_info_t*    disk    = (cyg_mmc_spi_disk_info_t*) chan->dev_priv;
1080     cyg_uint32                  i;
1081     const cyg_uint8*            buf = (cyg_uint8*) buf_arg;
1082     Cyg_ErrNo                   code = ENOERR;
1083
1084     DEBUG1("mmc_spi_disk_write(): first block %d, buf %p, len %lu blocks (%lu bytes)\n",
1085            first_block, buf, (unsigned long)blocks, (unsigned long)blocks*512);
1086
1087     if (! disk->mmc_connected) {
1088         return -ENODEV;
1089     }
1090     if (disk->mmc_read_only) {
1091         return -EROFS;
1092     }
1093     if ((first_block + blocks) >= disk->mmc_block_count) {
1094         return -EINVAL;
1095     }
1096
1097     for (i = 0; (i < blocks) && (ENOERR == code); i++) {
1098         code = mmc_spi_write_disk_block(disk, buf, first_block + i);
1099         buf += MMC_SPI_BLOCK_SIZE;
1100     }
1101     return code;
1102 }
1103
1104 // get_config() and set_config(). There are no supported get_config() operations
1105 // at this time.
1106 static Cyg_ErrNo
1107 mmc_spi_disk_get_config(disk_channel* chan, cyg_uint32 key, const void* buf, cyg_uint32* len)
1108 {
1109     CYG_UNUSED_PARAM(disk_channel*, chan);
1110     CYG_UNUSED_PARAM(cyg_uint32, key);
1111     CYG_UNUSED_PARAM(const void*, buf);
1112     CYG_UNUSED_PARAM(cyg_uint32*, len);
1113     
1114     return -EINVAL;
1115 }
1116
1117 static Cyg_ErrNo
1118 mmc_spi_disk_set_config(disk_channel* chan, cyg_uint32 key, const void* buf, cyg_uint32* len)
1119 {
1120     Cyg_ErrNo                   result  = ENOERR;
1121     cyg_mmc_spi_disk_info_t*    disk    = (cyg_mmc_spi_disk_info_t*) chan->dev_priv;
1122
1123     switch(key) {
1124       case CYG_IO_SET_CONFIG_DISK_MOUNT:
1125         // There will have been a successful lookup(), so there's
1126         // little point in checking the disk again.
1127         break;
1128
1129       case CYG_IO_SET_CONFIG_DISK_UMOUNT:
1130         if (0 == chan->info->mounts) {
1131             // If this is the last unmount of the card, mark it as
1132             // disconnected. If the user then removes the card and
1133             // plugs in a new one everything works cleanly. Also
1134             // reset the SPI device's clockrate.
1135             disk->mmc_connected = false;
1136             mmc_spi_restore_baud(disk);
1137             result = (chan->callbacks->disk_disconnected)(chan);
1138         }
1139         break;
1140     }
1141
1142     return result;
1143 }
1144
1145 // ----------------------------------------------------------------------------
1146 // And finally the data structures that define this disk. Some of this
1147 // should be moved into an exported header file so that applications can
1148 // define additional disks.
1149 //
1150 // It is not obvious why there are quite so many structures. Apart
1151 // from the devtab entries there are no tables involved, so there is
1152 // no need to keep everything the same size. The cyg_disk_info_t could
1153 // be the common part of a h/w info_t. The channel structure is
1154 // redundant and its fields could be merged into the cyg_disk_info_t
1155 // structure. That would leave a devtab entry, a disk info structure
1156 // (h/w specific but with a common base), and a disk controller
1157 // structure (ditto).
1158
1159 DISK_FUNS(cyg_mmc_spi_disk_funs,
1160           mmc_spi_disk_read,
1161           mmc_spi_disk_write,
1162           mmc_spi_disk_get_config,
1163           mmc_spi_disk_set_config
1164           );
1165
1166 static cyg_mmc_spi_disk_info_t cyg_mmc_spi_disk0_hwinfo = {
1167     .mmc_spi_dev        = &cyg_spi_mmc_dev0,
1168 #ifdef MMC_SPI_BACKGROUND_WRITES    
1169     .mmc_writing        = 0,
1170 #endif    
1171     .mmc_connected      = 0
1172 };
1173
1174 // No h/w controller structure is needed, but the address of the
1175 // second argument is taken anyway.
1176 DISK_CONTROLLER(cyg_mmc_spi_disk_controller_0, cyg_mmc_spi_disk0_hwinfo);
1177
1178 DISK_CHANNEL(cyg_mmc_spi_disk0_channel,
1179              cyg_mmc_spi_disk_funs,
1180              cyg_mmc_spi_disk0_hwinfo,
1181              cyg_mmc_spi_disk_controller_0,
1182              true,                            /* MBR support */
1183              1                                /* Number of partitions supported */
1184              );
1185              
1186 BLOCK_DEVTAB_ENTRY(cyg_mmc_spi_disk0_devtab_entry,
1187                    CYGDAT_DEVS_DISK_MMC_SPI_DISK0_NAME,
1188                    0,
1189                    &cyg_io_disk_devio,
1190                    &mmc_spi_disk_init,
1191                    &mmc_spi_disk_lookup,
1192                    &cyg_mmc_spi_disk0_channel);
1193
1194 // EOF mmc_spi.c