import of upstream 2.4.34.4 from kernel.org
[linux-2.4.git] / drivers / usb / storage / sddr09.c
1 /* Driver for SanDisk SDDR-09 SmartMedia reader
2  *
3  *   (c) 2000, 2001 Robert Baruch (autophile@starband.net)
4  *   (c) 2002 Andries Brouwer (aeb@cwi.nl)
5  *
6  * The SanDisk SDDR-09 SmartMedia reader uses the Shuttle EUSB-01 chip.
7  * This chip is a programmable USB controller. In the SDDR-09, it has
8  * been programmed to obey a certain limited set of SCSI commands.
9  * This driver translates the "real" SCSI commands to the SDDR-09 SCSI
10  * commands.
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2, or (at your option) any
15  * later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include "transport.h"
28 #include "protocol.h"
29 #include "usb.h"
30 #include "debug.h"
31 #include "sddr09.h"
32
33 #include <linux/sched.h>
34 #include <linux/errno.h>
35 #include <linux/slab.h>
36
37 #define short_pack(lsb,msb) ( ((u16)(lsb)) | ( ((u16)(msb))<<8 ) )
38 #define LSB_of(s) ((s)&0xFF)
39 #define MSB_of(s) ((s)>>8)
40
41 /* #define US_DEBUGP printk */
42
43 /*
44  * First some stuff that does not belong here:
45  * data on SmartMedia and other cards, completely
46  * unrelated to this driver.
47  * Similar stuff occurs in <linux/mtd/nand_ids.h>.
48  */
49
50 struct nand_flash_dev {
51         int model_id;
52         int chipshift;          /* 1<<cs bytes total capacity */
53         char pageshift;         /* 1<<ps bytes in a page */
54         char blockshift;        /* 1<<bs pages in an erase block */
55         char zoneshift;         /* 1<<zs blocks in a zone */
56                                 /* # of logical blocks is 125/128 of this */
57         char pageadrlen;        /* length of an address in bytes - 1 */
58 };
59
60 /*
61  * NAND Flash Manufacturer ID Codes
62  */
63 #define NAND_MFR_AMD            0x01
64 #define NAND_MFR_TOSHIBA        0x98
65 #define NAND_MFR_SAMSUNG        0xec
66
67 static inline char *nand_flash_manufacturer(int manuf_id) {
68         switch(manuf_id) {
69         case NAND_MFR_AMD:
70                 return "AMD";
71         case NAND_MFR_TOSHIBA:
72                 return "Toshiba";
73         case NAND_MFR_SAMSUNG:
74                 return "Samsung";
75         default:
76                 return "unknown";
77         }
78 }
79
80 /*
81  * It looks like it is unnecessary to attach manufacturer to the
82  * remaining data: SSFDC prescribes manufacturer-independent id codes.
83  */
84
85 static struct nand_flash_dev nand_flash_ids[] = {
86         /* NAND flash - these I verified */
87         { 0x6e, 20, 8, 4, 8, 2},        /* 1 MB */
88         { 0xe8, 20, 8, 4, 8, 2},        /* 1 MB */
89         { 0xec, 20, 8, 4, 8, 2},        /* 1 MB */
90         { 0x64, 21, 8, 4, 9, 2},        /* 2 MB */
91         { 0xea, 21, 8, 4, 9, 2},        /* 2 MB */
92         { 0x6b, 22, 9, 4, 9, 2},        /* 4 MB */
93         { 0xe3, 22, 9, 4, 9, 2},        /* 4 MB */
94         { 0xe5, 22, 9, 4, 9, 2},        /* 4 MB */
95         { 0xe6, 23, 9, 4, 10, 2},       /* 8 MB */
96         { 0x73, 24, 9, 5, 10, 2},       /* 16 MB */
97         { 0x75, 25, 9, 5, 10, 2},       /* 32 MB */
98         { 0x76, 26, 9, 5, 10, 3},       /* 64 MB */
99         { 0x79, 27, 9, 5, 10, 3},       /* 128 MB */
100         /* MASK ROM - from unknown source */
101         { 0x5d, 21, 9, 4, 8, 2},        /* 2 MB */
102         { 0xd5, 22, 9, 4, 9, 2},        /* 4 MB */
103         { 0xd6, 23, 9, 4, 10, 2},       /* 8 MB */
104         { 0,}
105 };
106
107 #define SIZE(a) (sizeof(a)/sizeof((a)[0]))
108
109 static struct nand_flash_dev *
110 nand_find_id(unsigned char id) {
111         int i;
112
113         for (i = 0; i < SIZE(nand_flash_ids); i++)
114                 if (nand_flash_ids[i].model_id == id)
115                         return &(nand_flash_ids[i]);
116         return NULL;
117 }
118
119 /*
120  * ECC computation.
121  */
122 static unsigned char parity[256];
123 static unsigned char ecc2[256];
124
125 static void nand_init_ecc(void) {
126         int i, j, a;
127
128         parity[0] = 0;
129         for (i = 1; i < 256; i++)
130                 parity[i] = (parity[i&(i-1)] ^ 1);
131
132         for (i = 0; i < 256; i++) {
133                 a = 0;
134                 for (j = 0; j < 8; j++) {
135                         if (i & (1<<j)) {
136                                 if ((j & 1) == 0)
137                                         a ^= 0x04;
138                                 if ((j & 2) == 0)
139                                         a ^= 0x10;
140                                 if ((j & 4) == 0)
141                                         a ^= 0x40;
142                         }
143                 }
144                 ecc2[i] = ~(a ^ (a<<1) ^ (parity[i] ? 0xa8 : 0));
145         }
146 }
147
148 /* compute 3-byte ecc on 256 bytes */
149 static void nand_compute_ecc(unsigned char *data, unsigned char *ecc) {
150         int i, j, a;
151         unsigned char par, bit, bits[8];
152
153         par = 0;
154         for (j = 0; j < 8; j++)
155                 bits[j] = 0;
156
157         /* collect 16 checksum bits */
158         for (i = 0; i < 256; i++) {
159                 par ^= data[i];
160                 bit = parity[data[i]];
161                 for (j = 0; j < 8; j++)
162                         if ((i & (1<<j)) == 0)
163                                 bits[j] ^= bit;
164         }
165
166         /* put 4+4+4 = 12 bits in the ecc */
167         a = (bits[3] << 6) + (bits[2] << 4) + (bits[1] << 2) + bits[0];
168         ecc[0] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
169
170         a = (bits[7] << 6) + (bits[6] << 4) + (bits[5] << 2) + bits[4];
171         ecc[1] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
172
173         ecc[2] = ecc2[par];
174 }
175
176 static int nand_compare_ecc(unsigned char *data, unsigned char *ecc) {
177         return (data[0] == ecc[0] && data[1] == ecc[1] && data[2] == ecc[2]);
178 }
179
180 static void nand_store_ecc(unsigned char *data, unsigned char *ecc) {
181         memcpy(data, ecc, 3);
182 }
183
184 /*
185  * The actual driver starts here.
186  */
187
188 /*
189  * On my 16MB card, control blocks have size 64 (16 real control bytes,
190  * and 48 junk bytes). In reality of course the card uses 16 control bytes,
191  * so the reader makes up the remaining 48. Don't know whether these numbers
192  * depend on the card. For now a constant.
193  */
194 #define CONTROL_SHIFT 6
195
196 /*
197  * LBA and PBA are unsigned ints. Special values.
198  */
199 #define UNDEF    0xffffffff
200 #define SPARE    0xfffffffe
201 #define UNUSABLE 0xfffffffd
202
203 /*
204  * Send a control message and wait for the response.
205  *
206  * us - the pointer to the us_data structure for the device to use
207  *
208  * request - the URB Setup Packet's first 6 bytes. The first byte always
209  *  corresponds to the request type, and the second byte always corresponds
210  *  to the request.  The other 4 bytes do not correspond to value and index,
211  *  since they are used in a custom way by the SCM protocol.
212  *
213  * xfer_data - a buffer from which to get, or to which to store, any data
214  *  that gets send or received, respectively, with the URB. Even though
215  *  it looks like we allocate a buffer in this code for the data, xfer_data
216  *  must contain enough allocated space.
217  *
218  * xfer_len - the number of bytes to send or receive with the URB.
219  *
220  */
221
222 static int
223 sddr09_send_control(struct us_data *us,
224                     int pipe,
225                     unsigned char request,
226                     unsigned char requesttype,
227                     unsigned int value,
228                     unsigned int index,
229                     unsigned char *xfer_data,
230                     unsigned int xfer_len) {
231
232         int result;
233
234         // Send the URB to the device and wait for a response.
235
236         /* Why are request and request type reversed in this call? */
237
238         result = usb_stor_control_msg(us, pipe,
239                         request, requesttype, value, index,
240                         xfer_data, xfer_len);
241
242
243         // Check the return code for the command.
244
245         if (result < 0) {
246                 /* if the command was aborted, indicate that */
247                 if (result == -ECONNRESET)
248                         return USB_STOR_TRANSPORT_ABORTED;
249
250                 /* a stall is a fatal condition from the device */
251                 if (result == -EPIPE) {
252                         US_DEBUGP("-- Stall on control pipe. Clearing\n");
253                         result = usb_clear_halt(us->pusb_dev, pipe);
254                         US_DEBUGP("-- usb_clear_halt() returns %d\n", result);
255                         return USB_STOR_TRANSPORT_FAILED;
256                 }
257
258                 return USB_STOR_TRANSPORT_ERROR;
259         }
260
261         return USB_STOR_TRANSPORT_GOOD;
262 }
263
264 /* send vendor interface command (0x41) */
265 /* called for requests 0, 1, 8 */
266 static int
267 sddr09_send_command(struct us_data *us,
268                     unsigned char request,
269                     unsigned char direction,
270                     unsigned char *xfer_data,
271                     unsigned int xfer_len) {
272         int pipe;
273         unsigned char requesttype = (0x41 | direction);
274
275         // Get the receive or send control pipe number
276
277         if (direction == USB_DIR_IN)
278                 pipe = usb_rcvctrlpipe(us->pusb_dev,0);
279         else
280                 pipe = usb_sndctrlpipe(us->pusb_dev,0);
281
282         return sddr09_send_control(us, pipe, request, requesttype,
283                                    0, 0, xfer_data, xfer_len);
284 }
285
286 static int
287 sddr09_send_scsi_command(struct us_data *us,
288                          unsigned char *command,
289                          unsigned int command_len) {
290         return sddr09_send_command(us, 0, USB_DIR_OUT, command, command_len);
291 }
292
293 static int
294 sddr09_raw_bulk(struct us_data *us, int direction,
295                 unsigned char *data, unsigned int len) {
296
297         int result;
298         int act_len;
299         int pipe;
300
301         if (direction == SCSI_DATA_READ)
302                 pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
303         else
304                 pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
305
306         result = usb_stor_bulk_msg(us, data, pipe, len, &act_len);
307
308         /* if we stall, we need to clear it before we go on */
309         if (result == -EPIPE) {
310                 US_DEBUGP("EPIPE: clearing endpoint halt for"
311                           " pipe 0x%x, stalled at %d bytes\n",
312                           pipe, act_len);
313                 usb_clear_halt(us->pusb_dev, pipe);
314         }
315
316         if (result) {
317                 /* -ECONNRESET -- we canceled this transfer */
318                 if (result == -ECONNRESET) {
319                         US_DEBUGP("usbat_raw_bulk(): transfer aborted\n");
320                         return US_BULK_TRANSFER_ABORTED;
321                 }
322
323                 /* NAK - that means we've retried a few times already */
324                 if (result == -ETIMEDOUT)
325                         US_DEBUGP("usbat_raw_bulk(): device NAKed\n");
326                 else if (result == -EOVERFLOW)
327                         US_DEBUGP("us_transfer_partial(): babble/overflow\n");
328                 else if (result != -EPIPE)
329                         US_DEBUGP("us_transfer_partial(): unknown error %d\n",
330                                   result);
331
332                 return US_BULK_TRANSFER_FAILED;
333         }
334
335         if (act_len != len) {
336                 US_DEBUGP("Warning: Transferred only %d of %d bytes\n",
337                           act_len, len);
338                 return US_BULK_TRANSFER_SHORT;
339         }
340
341         return US_BULK_TRANSFER_GOOD;
342 }
343
344 static int
345 sddr09_bulk_transport(struct us_data *us, int direction,
346                       unsigned char *data, unsigned int len,
347                       int use_sg) {
348
349         int result = USB_STOR_TRANSPORT_GOOD;
350         int transferred = 0;
351         int i;
352         struct scatterlist *sg;
353         char string[64];
354
355 #define DEBUG_PRCT 12
356
357         if (len == 0)
358                 return USB_STOR_TRANSPORT_GOOD;
359
360         if (direction == SCSI_DATA_WRITE && !use_sg) {
361
362                 /* Debug-print the first N bytes of the write transfer */
363
364                 strcpy(string, "wr: ");
365                 for (i=0; i<len && i<DEBUG_PRCT; i++) {
366                         sprintf(string+strlen(string), "%02X ",
367                                 data[i]);
368                         if ((i%16) == 15) {
369                                 US_DEBUGP("%s\n", string);
370                                 strcpy(string, "wr: ");
371                         }
372                 }
373                 if ((i%16)!=0)
374                         US_DEBUGP("%s\n", string);
375         }
376
377         US_DEBUGP("SCM data %s transfer %d sg buffers %d\n",
378                   (direction == SCSI_DATA_READ) ? "in" : "out",
379                   len, use_sg);
380
381         if (!use_sg)
382                 result = sddr09_raw_bulk(us, direction, data, len);
383         else {
384                 sg = (struct scatterlist *)data;
385
386                 for (i=0; i<use_sg && transferred<len; i++) {
387                         unsigned char *buf;
388                         unsigned int length;
389
390                         buf = sg[i].address;
391                         length = len-transferred;
392                         if (length > sg[i].length)
393                                 length = sg[i].length;
394
395                         result = sddr09_raw_bulk(us, direction, buf, length);
396                         if (result != US_BULK_TRANSFER_GOOD)
397                                 break;
398                         transferred += sg[i].length;
399                 }
400         }
401
402         if (direction == SCSI_DATA_READ && !use_sg) {
403
404                 /* Debug-print the first N bytes of the read transfer */
405
406                 strcpy(string, "rd: ");
407                 for (i=0; i<len && i<DEBUG_PRCT; i++) {
408                         sprintf(string+strlen(string), "%02X ",
409                                 data[i]);
410                         if ((i%16) == 15) {
411                                 US_DEBUGP("%s\n", string);
412                                 strcpy(string, "rd: ");
413                         }
414                 }
415                 if ((i%16)!=0)
416                         US_DEBUGP("%s\n", string);
417         }
418
419         return result;
420 }
421
422 #if 0
423 /*
424  * Test Unit Ready Command: 12 bytes.
425  * byte 0: opcode: 00
426  */
427 static int
428 sddr09_test_unit_ready(struct us_data *us) {
429         unsigned char command[6] = {
430                 0, 0x20, 0, 0, 0, 0
431         };
432         int result;
433
434         result = sddr09_send_scsi_command(us, command, sizeof(command));
435
436         US_DEBUGP("sddr09_test_unit_ready returns %d\n", result);
437
438         return result;
439 }
440 #endif
441
442 /*
443  * Request Sense Command: 12 bytes.
444  * byte 0: opcode: 03
445  * byte 4: data length
446  */
447 #if 0
448 static int
449 sddr09_request_sense(struct us_data *us, unsigned char *sensebuf, int buflen) {
450         unsigned char command[12] = {
451                 0x03, 0x20, 0, 0, buflen, 0, 0, 0, 0, 0, 0, 0
452         };
453         int result;
454
455         result = sddr09_send_scsi_command(us, command, sizeof(command));
456         if (result != USB_STOR_TRANSPORT_GOOD) {
457                 US_DEBUGP("request sense failed\n");
458                 return result;
459         }
460
461         result = sddr09_raw_bulk(us, SCSI_DATA_READ, sensebuf, buflen);
462         if (result != USB_STOR_TRANSPORT_GOOD)
463                 US_DEBUGP("request sense bulk in failed\n");
464         else
465                 US_DEBUGP("request sense worked\n");
466
467         return result;
468 }
469 #endif
470 /*
471  * Read Command: 12 bytes.
472  * byte 0: opcode: E8
473  * byte 1: last two bits: 00: read data, 01: read blockwise control,
474  *                        10: read both, 11: read pagewise control.
475  *         It turns out we need values 20, 21, 22, 23 here (LUN 1).
476  * bytes 2-5: address (interpretation depends on byte 1, see below)
477  * bytes 10-11: count (idem)
478  *
479  * A page has 512 data bytes and 64 control bytes (16 control and 48 junk).
480  * A read data command gets data in 512-byte pages.
481  * A read control command gets control in 64-byte chunks.
482  * A read both command gets data+control in 576-byte chunks.
483  *
484  * Blocks are groups of 32 pages, and read blockwise control jumps to the
485  * next block, while read pagewise control jumps to the next page after
486  * reading a group of 64 control bytes.
487  * [Here 512 = 1<<pageshift, 32 = 1<<blockshift, 64 is constant?]
488  *
489  * (1 MB and 2 MB cards are a bit different, but I have only a 16 MB card.)
490  */
491
492 static int
493 sddr09_readX(struct us_data *us, int x, unsigned long fromaddress,
494              int nr_of_pages, int bulklen, unsigned char *buf,
495              int use_sg) {
496
497         unsigned char command[12] = {
498                 0xe8, 0x20 | x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
499         };
500         int result;
501
502         command[2] = MSB_of(fromaddress>>16);
503         command[3] = LSB_of(fromaddress>>16); 
504         command[4] = MSB_of(fromaddress & 0xFFFF);
505         command[5] = LSB_of(fromaddress & 0xFFFF); 
506
507         command[10] = MSB_of(nr_of_pages);
508         command[11] = LSB_of(nr_of_pages);
509
510         result = sddr09_send_scsi_command(us, command, sizeof(command));
511
512         if (result != USB_STOR_TRANSPORT_GOOD) {
513                 US_DEBUGP("Result for send_control in sddr09_read2%d %d\n",
514                           x, result);
515                 return result;
516         }
517
518         result = sddr09_bulk_transport(us, SCSI_DATA_READ,
519                                        buf, bulklen, use_sg);
520
521         if (result != USB_STOR_TRANSPORT_GOOD)
522                 US_DEBUGP("Result for bulk_transport in sddr09_read2%d %d\n",
523                           x, result);
524
525         return result;
526 }
527
528 /*
529  * Read Data
530  *
531  * fromaddress counts data shorts:
532  * increasing it by 256 shifts the bytestream by 512 bytes;
533  * the last 8 bits are ignored.
534  *
535  * nr_of_pages counts pages of size (1 << pageshift).
536  */
537 static int
538 sddr09_read20(struct us_data *us, unsigned long fromaddress,
539               int nr_of_pages, int pageshift, unsigned char *buf, int use_sg) {
540         int bulklen = nr_of_pages << pageshift;
541
542         /* The last 8 bits of fromaddress are ignored. */
543         return sddr09_readX(us, 0, fromaddress, nr_of_pages, bulklen,
544                             buf, use_sg);
545 }
546
547 /*
548  * Read Blockwise Control
549  *
550  * fromaddress gives the starting position (as in read data;
551  * the last 8 bits are ignored); increasing it by 32*256 shifts
552  * the output stream by 64 bytes.
553  *
554  * count counts control groups of size (1 << controlshift).
555  * For me, controlshift = 6. Is this constant?
556  *
557  * After getting one control group, jump to the next block
558  * (fromaddress += 8192).
559  */
560 static int
561 sddr09_read21(struct us_data *us, unsigned long fromaddress,
562               int count, int controlshift, unsigned char *buf, int use_sg) {
563
564         int bulklen = (count << controlshift);
565         return sddr09_readX(us, 1, fromaddress, count, bulklen,
566                             buf, use_sg);
567 }
568
569 /*
570  * Read both Data and Control
571  *
572  * fromaddress counts data shorts, ignoring control:
573  * increasing it by 256 shifts the bytestream by 576 = 512+64 bytes;
574  * the last 8 bits are ignored.
575  *
576  * nr_of_pages counts pages of size (1 << pageshift) + (1 << controlshift).
577  */
578 static int
579 sddr09_read22(struct us_data *us, unsigned long fromaddress,
580               int nr_of_pages, int pageshift, unsigned char *buf, int use_sg) {
581
582         int bulklen = (nr_of_pages << pageshift) + (nr_of_pages << CONTROL_SHIFT);
583         US_DEBUGP("sddr09_read22: reading %d pages, %d bytes\n",
584                   nr_of_pages, bulklen);
585         return sddr09_readX(us, 2, fromaddress, nr_of_pages, bulklen,
586                             buf, use_sg);
587 }
588
589 #if 0
590 /*
591  * Read Pagewise Control
592  *
593  * fromaddress gives the starting position (as in read data;
594  * the last 8 bits are ignored); increasing it by 256 shifts
595  * the output stream by 64 bytes.
596  *
597  * count counts control groups of size (1 << controlshift).
598  * For me, controlshift = 6. Is this constant?
599  *
600  * After getting one control group, jump to the next page
601  * (fromaddress += 256).
602  */
603 static int
604 sddr09_read23(struct us_data *us, unsigned long fromaddress,
605               int count, int controlshift, unsigned char *buf, int use_sg) {
606
607         int bulklen = (count << controlshift);
608         return sddr09_readX(us, 3, fromaddress, count, bulklen,
609                             buf, use_sg);
610 }
611 #endif
612
613 #if 0
614 /*
615  * Erase Command: 12 bytes.
616  * byte 0: opcode: EA
617  * bytes 6-9: erase address (big-endian, counting shorts, sector aligned).
618  * 
619  * Always precisely one block is erased; bytes 2-5 and 10-11 are ignored.
620  * The byte address being erased is 2*Eaddress.
621  */
622 static int
623 sddr09_erase(struct us_data *us, unsigned long Eaddress) {
624         unsigned char command[12] = {
625                 0xea, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
626         };
627         int result;
628
629         command[6] = MSB_of(Eaddress>>16);
630         command[7] = LSB_of(Eaddress>>16);
631         command[8] = MSB_of(Eaddress & 0xFFFF);
632         command[9] = LSB_of(Eaddress & 0xFFFF);
633
634         result = sddr09_send_scsi_command(us, command, sizeof(command));
635
636         if (result != USB_STOR_TRANSPORT_GOOD)
637                 US_DEBUGP("Result for send_control in sddr09_erase %d\n",
638                           result);
639
640         return result;
641 }
642 #endif
643
644 /*
645  * Write Command: 12 bytes.
646  * byte 0: opcode: E9
647  * bytes 2-5: write address (big-endian, counting shorts, sector aligned).
648  * bytes 6-9: erase address (big-endian, counting shorts, sector aligned).
649  * bytes 10-11: sector count (big-endian, in 512-byte sectors).
650  *
651  * If write address equals erase address, the erase is done first,
652  * otherwise the write is done first. When erase address equals zero
653  * no erase is done?
654  */
655 static int
656 sddr09_writeX(struct us_data *us,
657               unsigned long Waddress, unsigned long Eaddress,
658               int nr_of_pages, int bulklen, unsigned char *buf, int use_sg) {
659
660         unsigned char command[12] = {
661                 0xe9, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
662         };
663         int result;
664
665         command[2] = MSB_of(Waddress>>16);
666         command[3] = LSB_of(Waddress>>16);
667         command[4] = MSB_of(Waddress & 0xFFFF);
668         command[5] = LSB_of(Waddress & 0xFFFF);
669
670         command[6] = MSB_of(Eaddress>>16);
671         command[7] = LSB_of(Eaddress>>16);
672         command[8] = MSB_of(Eaddress & 0xFFFF);
673         command[9] = LSB_of(Eaddress & 0xFFFF);
674
675         command[10] = MSB_of(nr_of_pages);
676         command[11] = LSB_of(nr_of_pages);
677
678         result = sddr09_send_scsi_command(us, command, sizeof(command));
679
680         if (result != USB_STOR_TRANSPORT_GOOD) {
681                 US_DEBUGP("Result for send_control in sddr09_writeX %d\n",
682                           result);
683                 return result;
684         }
685
686         result = sddr09_bulk_transport(us, SCSI_DATA_WRITE,
687                                        buf, bulklen, use_sg);
688
689         if (result != USB_STOR_TRANSPORT_GOOD)
690                 US_DEBUGP("Result for bulk_transport in sddr09_writeX %d\n",
691                           result);
692
693         return result;
694 }
695
696 /* erase address, write same address */
697 static int
698 sddr09_write_inplace(struct us_data *us, unsigned long address,
699                      int nr_of_pages, int pageshift, unsigned char *buf,
700                      int use_sg) {
701         int bulklen = (nr_of_pages << pageshift) + (nr_of_pages << CONTROL_SHIFT);
702         return sddr09_writeX(us, address, address, nr_of_pages, bulklen,
703                              buf, use_sg);
704 }
705
706 #if 0
707 /*
708  * Read Scatter Gather Command: 3+4n bytes.
709  * byte 0: opcode E7
710  * byte 2: n
711  * bytes 4i-1,4i,4i+1: page address
712  * byte 4i+2: page count
713  * (i=1..n)
714  *
715  * This reads several pages from the card to a single memory buffer.
716  */
717 static int
718 sddr09_read_sg_test_only(struct us_data *us) {
719         unsigned char command[15] = {
720                 0xe7, 0x20, 0
721         };
722         int result, bulklen, nsg, ct;
723         unsigned char *buf;
724         unsigned long address;
725
726         nsg = bulklen = 0;
727
728         address = 040000; ct = 1;
729         nsg++;
730         bulklen += (ct << 9);
731         command[4*nsg+2] = ct;
732         command[4*nsg+1] = ((address >> 9) & 0xFF);
733         command[4*nsg+0] = ((address >> 17) & 0xFF);
734         command[4*nsg-1] = ((address >> 25) & 0xFF);
735
736         address = 0340000; ct = 1;
737         nsg++;
738         bulklen += (ct << 9);
739         command[4*nsg+2] = ct;
740         command[4*nsg+1] = ((address >> 9) & 0xFF);
741         command[4*nsg+0] = ((address >> 17) & 0xFF);
742         command[4*nsg-1] = ((address >> 25) & 0xFF);
743
744         address = 01000000; ct = 2;
745         nsg++;
746         bulklen += (ct << 9);
747         command[4*nsg+2] = ct;
748         command[4*nsg+1] = ((address >> 9) & 0xFF);
749         command[4*nsg+0] = ((address >> 17) & 0xFF);
750         command[4*nsg-1] = ((address >> 25) & 0xFF);
751
752         command[2] = nsg;
753
754         result = sddr09_send_scsi_command(us, command, 4*nsg+3);
755
756         if (result != USB_STOR_TRANSPORT_GOOD) {
757                 US_DEBUGP("Result for send_control in sddr09_read_sg %d\n",
758                           result);
759                 return result;
760         }
761
762         buf = (unsigned char *) kmalloc(bulklen, GFP_NOIO);
763         if (!buf)
764                 return USB_STOR_TRANSPORT_ERROR;
765
766         result = sddr09_bulk_transport(us, SCSI_DATA_READ,
767                                        buf, bulklen, 0);
768         if (result != USB_STOR_TRANSPORT_GOOD)
769                 US_DEBUGP("Result for bulk_transport in sddr09_read_sg %d\n",
770                           result);
771
772         kfree(buf);
773
774         return result;
775 }
776 #endif
777
778 /*
779  * Read Status Command: 12 bytes.
780  * byte 0: opcode: EC
781  *
782  * Returns 64 bytes, all zero except for the first.
783  * bit 0: 1: Error
784  * bit 5: 1: Suspended
785  * bit 6: 1: Ready
786  * bit 7: 1: Not write-protected
787  */
788
789 static int
790 sddr09_read_status(struct us_data *us, unsigned char *status) {
791
792         unsigned char command[12] = {
793                 0xec, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
794         };
795         unsigned char data[64];
796         int result;
797
798         US_DEBUGP("Reading status...\n");
799
800         result = sddr09_send_scsi_command(us, command, sizeof(command));
801         if (result != USB_STOR_TRANSPORT_GOOD)
802                 return result;
803
804         result = sddr09_bulk_transport(us, SCSI_DATA_READ,
805                                        data, sizeof(data), 0);
806         *status = data[0];
807         return result;
808 }
809
810 static int
811 sddr09_read_data(struct us_data *us,
812                  unsigned long address,
813                  unsigned int sectors,
814                  unsigned char *content,
815                  int use_sg) {
816
817         struct sddr09_card_info *info = (struct sddr09_card_info *) us->extra;
818         unsigned int lba, maxlba, pba;
819         unsigned int page, pages;
820         unsigned char *buffer = NULL;
821         unsigned char *ptr;
822         struct scatterlist *sg = NULL;
823         int result, i, len;
824
825         // If we're using scatter-gather, we have to create a new
826         // buffer to read all of the data in first, since a
827         // scatter-gather buffer could in theory start in the middle
828         // of a page, which would be bad. A developer who wants a
829         // challenge might want to write a limited-buffer
830         // version of this code.
831
832         len = sectors*info->pagesize;
833
834         if (use_sg) {
835                 sg = (struct scatterlist *)content;
836                 buffer = kmalloc(len, GFP_NOIO);
837                 if (buffer == NULL)
838                         return USB_STOR_TRANSPORT_ERROR;
839                 ptr = buffer;
840         } else
841                 ptr = content;
842
843         // Figure out the initial LBA and page
844         lba = address >> info->blockshift;
845         page = (address & info->blockmask);
846         maxlba = info->capacity >> (info->pageshift + info->blockshift);
847
848         // This could be made much more efficient by checking for
849         // contiguous LBA's. Another exercise left to the student.
850
851         result = USB_STOR_TRANSPORT_GOOD;
852
853         while (sectors > 0) {
854
855                 /* Find number of pages we can read in this block */
856                 pages = info->blocksize - page;
857                 if (pages > sectors)
858                         pages = sectors;
859
860                 /* Not overflowing capacity? */
861                 if (lba >= maxlba) {
862                         US_DEBUGP("Error: Requested lba %u exceeds "
863                                   "maximum %u\n", lba, maxlba);
864                         result = USB_STOR_TRANSPORT_ERROR;
865                         break;
866                 }
867
868                 /* Find where this lba lives on disk */
869                 pba = info->lba_to_pba[lba];
870
871                 if (pba == UNDEF) {     /* this lba was never written */
872
873                         US_DEBUGP("Read %d zero pages (LBA %d) page %d\n",
874                                   pages, lba, page);
875
876                         /* This is not really an error. It just means
877                            that the block has never been written.
878                            Instead of returning USB_STOR_TRANSPORT_ERROR
879                            it is better to return all zero data. */
880
881                         memset(ptr, 0, pages << info->pageshift);
882
883                 } else {
884                         US_DEBUGP("Read %d pages, from PBA %d"
885                                   " (LBA %d) page %d\n",
886                                   pages, pba, lba, page);
887
888                         address = ((pba << info->blockshift) + page) << 
889                                 info->pageshift;
890
891                         result = sddr09_read20(us, address>>1,
892                                                pages, info->pageshift, ptr, 0);
893                         if (result != USB_STOR_TRANSPORT_GOOD)
894                                 break;
895                 }
896
897                 page = 0;
898                 lba++;
899                 sectors -= pages;
900                 ptr += (pages << info->pageshift);
901         }
902
903         if (use_sg && result == USB_STOR_TRANSPORT_GOOD) {
904                 int transferred = 0;
905
906                 for (i=0; i<use_sg && transferred<len; i++) {
907                         unsigned char *buf = sg[i].address;
908                         unsigned int length;
909
910                         length = len-transferred;
911                         if (length > sg[i].length)
912                                 length = sg[i].length;
913
914                         memcpy(buf, buffer+transferred, length);
915                         transferred += sg[i].length;
916                 }
917         }
918
919         if (use_sg)
920                 kfree(buffer);
921
922         return result;
923 }
924
925 /* we never free blocks, so lastpba can only increase */
926 static unsigned int
927 sddr09_find_unused_pba(struct sddr09_card_info *info) {
928         static unsigned int lastpba = 1;
929         int numblocks = info->capacity >> (info->blockshift + info->pageshift);
930         int i;
931
932         for (i = lastpba+1; i < numblocks; i++) {
933                 if (info->pba_to_lba[i] == UNDEF) {
934                         lastpba = i;
935                         return i;
936                 }
937         }
938         return 0;
939 }
940
941 static int
942 sddr09_write_lba(struct us_data *us, unsigned int lba,
943                  unsigned int page, unsigned int pages,
944                  unsigned char *ptr) {
945
946         struct sddr09_card_info *info = (struct sddr09_card_info *) us->extra;
947         unsigned long address;
948         unsigned int pba, lbap;
949         unsigned int pagelen, blocklen;
950         unsigned char *blockbuffer, *bptr, *cptr, *xptr;
951         unsigned char ecc[3];
952         int i, result;
953
954         lbap = ((lba & 0x3ff) << 1) | 0x1000;
955         if (parity[MSB_of(lbap) ^ LSB_of(lbap)])
956                 lbap ^= 1;
957         pba = info->lba_to_pba[lba];
958
959         if (pba == UNDEF) {
960                 pba = sddr09_find_unused_pba(info);
961                 if (!pba) {
962                         printk("sddr09_write_lba: Out of unused blocks\n");
963                         return USB_STOR_TRANSPORT_ERROR;
964                 }
965                 info->pba_to_lba[pba] = lba;
966                 info->lba_to_pba[lba] = pba;
967         }
968
969         if (pba == 1) {
970                 /* Maybe it is impossible to write to PBA 1.
971                    Fake success, but don't do anything. */
972                 printk("sddr09: avoid writing to pba 1\n");
973                 return USB_STOR_TRANSPORT_GOOD;
974         }
975
976         pagelen = (1 << info->pageshift) + (1 << CONTROL_SHIFT);
977         blocklen = (pagelen << info->blockshift);
978         blockbuffer = kmalloc(blocklen, GFP_NOIO);
979         if (!blockbuffer) {
980                 printk("sddr09_write_lba: Out of memory\n");
981                 return USB_STOR_TRANSPORT_ERROR;
982         }
983
984         /* read old contents */
985         address = (pba << (info->pageshift + info->blockshift));
986         result = sddr09_read22(us, address>>1, info->blocksize,
987                                info->pageshift, blockbuffer, 0);
988         if (result != USB_STOR_TRANSPORT_GOOD)
989                 goto err;
990
991         /* check old contents */
992         for (i = 0; i < info->blockshift; i++) {
993                 bptr = blockbuffer + i*pagelen;
994                 cptr = bptr + info->pagesize;
995                 nand_compute_ecc(bptr, ecc);
996                 if (!nand_compare_ecc(cptr+13, ecc)) {
997                         US_DEBUGP("Warning: bad ecc in page %d- of pba %d\n",
998                                   i, pba);
999                         nand_store_ecc(cptr+13, ecc);
1000                 }
1001                 nand_compute_ecc(bptr+(info->pagesize / 2), ecc);
1002                 if (!nand_compare_ecc(cptr+8, ecc)) {
1003                         US_DEBUGP("Warning: bad ecc in page %d+ of pba %d\n",
1004                                   i, pba);
1005                         nand_store_ecc(cptr+8, ecc);
1006                 }
1007         }
1008
1009         /* copy in new stuff and compute ECC */
1010         xptr = ptr;
1011         for (i = page; i < page+pages; i++) {
1012                 bptr = blockbuffer + i*pagelen;
1013                 cptr = bptr + info->pagesize;
1014                 memcpy(bptr, xptr, info->pagesize);
1015                 xptr += info->pagesize;
1016                 nand_compute_ecc(bptr, ecc);
1017                 nand_store_ecc(cptr+13, ecc);
1018                 nand_compute_ecc(bptr+(info->pagesize / 2), ecc);
1019                 nand_store_ecc(cptr+8, ecc);
1020                 cptr[6] = cptr[11] = MSB_of(lbap);
1021                 cptr[7] = cptr[12] = LSB_of(lbap);
1022         }
1023
1024         US_DEBUGP("Rewrite PBA %d (LBA %d)\n", pba, lba);
1025
1026         result = sddr09_write_inplace(us, address>>1, info->blocksize,
1027                                       info->pageshift, blockbuffer, 0);
1028
1029         US_DEBUGP("sddr09_write_inplace returns %d\n", result);
1030
1031 #if 0
1032         {
1033             unsigned char status = 0;
1034             int result2 = sddr09_read_status(us, &status);
1035             if (result2 != USB_STOR_TRANSPORT_GOOD)
1036                 US_DEBUGP("sddr09_write_inplace: cannot read status\n");
1037             else if (status != 0xc0)
1038                 US_DEBUGP("sddr09_write_inplace: status after write: 0x%x\n",
1039                           status);
1040         }
1041 #endif
1042
1043 #if 0
1044         {
1045             int result2 = sddr09_test_unit_ready(us);
1046         }
1047 #endif
1048  err:
1049         kfree(blockbuffer);
1050
1051         /* TODO: instead of doing kmalloc/kfree for each block,
1052            add a bufferpointer to the info structure */
1053
1054         return result;
1055 }
1056
1057 static int
1058 sddr09_write_data(struct us_data *us,
1059                   unsigned long address,
1060                   unsigned int sectors,
1061                   unsigned char *content,
1062                   int use_sg) {
1063
1064         struct sddr09_card_info *info = (struct sddr09_card_info *) us->extra;
1065         unsigned int lba, page, pages;
1066         unsigned char *buffer = NULL;
1067         unsigned char *ptr;
1068         struct scatterlist *sg = NULL;
1069         int result, i, len;
1070
1071         // If we're using scatter-gather, we have to create a new
1072         // buffer to write all of the data in first, since a
1073         // scatter-gather buffer could in theory start in the middle
1074         // of a page, which would be bad. A developer who wants a
1075         // challenge might want to write a limited-buffer
1076         // version of this code.
1077
1078         len = sectors*info->pagesize;
1079
1080         if (use_sg) {
1081                 int transferred = 0;
1082
1083                 sg = (struct scatterlist *)content;
1084                 buffer = kmalloc(len, GFP_NOIO);
1085                 if (buffer == NULL)
1086                         return USB_STOR_TRANSPORT_ERROR;
1087
1088                 for (i=0; i<use_sg && transferred<len; i++) {
1089                         memcpy(buffer+transferred,
1090                                sg[i].address,
1091                                len-transferred > sg[i].length ?
1092                                 sg[i].length : len-transferred);
1093                         transferred += sg[i].length;
1094                 }
1095                 ptr = buffer;
1096         } else
1097                 ptr = content;
1098
1099         // Figure out the initial LBA and page
1100         lba = address >> info->blockshift;
1101         page = (address & info->blockmask);
1102
1103         // This could be made much more efficient by checking for
1104         // contiguous LBA's. Another exercise left to the student.
1105
1106         result = USB_STOR_TRANSPORT_GOOD;
1107
1108         while (sectors > 0) {
1109
1110                 // Write as many sectors as possible in this block
1111
1112                 pages = info->blocksize - page;
1113                 if (pages > sectors)
1114                         pages = sectors;
1115
1116                 result = sddr09_write_lba(us, lba, page, pages, ptr);
1117                 if (result != USB_STOR_TRANSPORT_GOOD)
1118                         break;
1119
1120                 page = 0;
1121                 lba++;
1122                 sectors -= pages;
1123                 ptr += (pages << info->pageshift);
1124         }
1125
1126         if (use_sg)
1127                 kfree(buffer);
1128
1129         return result;
1130 }
1131
1132 int sddr09_read_control(struct us_data *us,
1133                 unsigned long address,
1134                 unsigned int blocks,
1135                 unsigned char *content,
1136                 int use_sg) {
1137
1138         US_DEBUGP("Read control address %08lX blocks %04X\n",
1139                 address, blocks);
1140
1141         return sddr09_read21(us, address, blocks, CONTROL_SHIFT, content, use_sg);
1142 }
1143
1144 static int
1145 sddr09_read_deviceID(struct us_data *us, unsigned char *deviceID) {
1146 /*
1147  * Read Device ID Command: 12 bytes.
1148  * byte 0: opcode: ED
1149  *
1150  * Returns 2 bytes: Manufacturer ID and Device ID.
1151  * On more recent cards 3 bytes: the third byte is an option code A5
1152  * signifying that the secret command to read an 128-bit ID is available.
1153  * On still more recent cards 4 bytes: the fourth byte C0 means that
1154  * a second read ID cmd is available.
1155  */
1156
1157         unsigned char command[12] = {
1158                 0xed, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1159         };
1160         unsigned char content[64];
1161         int result, i;
1162
1163         result = sddr09_send_scsi_command(us, command, sizeof(command));
1164         if (result != USB_STOR_TRANSPORT_GOOD)
1165                 return result;
1166
1167         result = sddr09_bulk_transport(us, SCSI_DATA_READ, content, 64, 0);
1168
1169         for (i = 0; i < 4; i++)
1170                 deviceID[i] = content[i];
1171
1172         return result;
1173 }
1174
1175 static int
1176 sddr09_get_wp(struct us_data *us, struct sddr09_card_info *info) {
1177         int result;
1178         unsigned char status;
1179
1180         result = sddr09_read_status(us, &status);
1181         if (result != USB_STOR_TRANSPORT_GOOD) {
1182                 US_DEBUGP("sddr09_get_wp: read_status fails\n");
1183                 return result;
1184         }
1185         US_DEBUGP("sddr09_get_wp: status %02X", status);
1186         if ((status & 0x80) == 0) {
1187                 info->flags |= SDDR09_WP;       /* write protected */
1188                 US_DEBUGP(" WP");
1189         }
1190         if (status & 0x40)
1191                 US_DEBUGP(" Ready");
1192         if (status & 0x20)
1193                 US_DEBUGP(" Suspended");
1194         if (status & 0x1)
1195                 US_DEBUGP(" Error");
1196         US_DEBUGP("\n");
1197         return USB_STOR_TRANSPORT_GOOD;
1198 }
1199
1200 #if 0
1201 /*
1202  * Reset Command: 12 bytes.
1203  * byte 0: opcode: EB
1204  */
1205 static int
1206 sddr09_reset(struct us_data *us) {
1207
1208         unsigned char command[12] = {
1209                 0xeb, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1210         };
1211
1212         return sddr09_send_scsi_command(us, command, sizeof(command));
1213 }
1214 #endif
1215
1216 static struct nand_flash_dev *
1217 sddr09_get_cardinfo(struct us_data *us, unsigned char flags) {
1218         struct nand_flash_dev *cardinfo;
1219         unsigned char deviceID[4];
1220         char blurbtxt[256];
1221         int result;
1222
1223         US_DEBUGP("Reading capacity...\n");
1224
1225         result = sddr09_read_deviceID(us, deviceID);
1226
1227         if (result != USB_STOR_TRANSPORT_GOOD) {
1228                 US_DEBUGP("Result of read_deviceID is %d\n", result);
1229                 printk("sddr09: could not read card info\n");
1230                 return 0;
1231         }
1232
1233         sprintf(blurbtxt, "sddr09: Found Flash card, ID = %02X %02X %02X %02X",
1234                 deviceID[0], deviceID[1], deviceID[2], deviceID[3]);
1235
1236         /* Byte 0 is the manufacturer */
1237         sprintf(blurbtxt + strlen(blurbtxt),
1238                 ": Manuf. %s",
1239                 nand_flash_manufacturer(deviceID[0]));
1240
1241         /* Byte 1 is the device type */
1242         cardinfo = nand_find_id(deviceID[1]);
1243         if (cardinfo) {
1244                 /* MB or MiB? It is neither. A 16 MB card has
1245                    17301504 raw bytes, of which 16384000 are
1246                    usable for user data. */
1247                 sprintf(blurbtxt + strlen(blurbtxt),
1248                         ", %d MB", 1<<(cardinfo->chipshift - 20));
1249         } else {
1250                 sprintf(blurbtxt + strlen(blurbtxt),
1251                         ", type unrecognized");
1252         }
1253
1254         /* Byte 2 is code to signal availability of 128-bit ID */
1255         if (deviceID[2] == 0xa5) {
1256                 sprintf(blurbtxt + strlen(blurbtxt),
1257                         ", 128-bit ID");
1258         }
1259
1260         /* Byte 3 announces the availability of another read ID command */
1261         if (deviceID[3] == 0xc0) {
1262                 sprintf(blurbtxt + strlen(blurbtxt),
1263                         ", extra cmd");
1264         }
1265
1266         if (flags & SDDR09_WP)
1267                 sprintf(blurbtxt + strlen(blurbtxt),
1268                         ", WP");
1269
1270         printk("%s\n", blurbtxt);
1271
1272         return cardinfo;
1273 }
1274
1275 static int
1276 sddr09_read_map(struct us_data *us) {
1277
1278         struct scatterlist *sg;
1279         struct sddr09_card_info *info = (struct sddr09_card_info *) us->extra;
1280         int numblocks, alloc_len, alloc_blocks;
1281         int i, j, result;
1282         unsigned char *ptr;
1283         unsigned int lba, lbact;
1284
1285         if (!info->capacity)
1286                 return -1;
1287
1288         // read 64 (1<<6) bytes for every block 
1289         // ( 1 << ( blockshift + pageshift ) bytes)
1290         //       of capacity:
1291         // (1<<6)*capacity/(1<<(b+p)) =
1292         // ((1<<6)*capacity)>>(b+p) =
1293         // capacity>>(b+p-6)
1294
1295         alloc_len = info->capacity >> 
1296                 (info->blockshift + info->pageshift - CONTROL_SHIFT);
1297
1298         // Allocate a number of scatterlist structures according to
1299         // the number of 128k blocks in the alloc_len. Adding 128k-1
1300         // and then dividing by 128k gives the correct number of blocks.
1301         // 128k = 1<<17
1302
1303         alloc_blocks = (alloc_len + (1<<17) - 1) >> 17;
1304         sg = kmalloc(alloc_blocks*sizeof(struct scatterlist),
1305                      GFP_NOIO);
1306         if (sg == NULL)
1307                 return 0;
1308
1309         for (i=0; i<alloc_blocks; i++) {
1310                 if (i<alloc_blocks-1) {
1311                         sg[i].address = kmalloc( (1<<17), GFP_NOIO );
1312                         sg[i].page = NULL;
1313                         sg[i].length = (1<<17);
1314                 } else {
1315                         sg[i].address = kmalloc(alloc_len, GFP_NOIO);
1316                         sg[i].page = NULL;
1317                         sg[i].length = alloc_len;
1318                 }
1319                 alloc_len -= sg[i].length;
1320         }
1321         for (i=0; i<alloc_blocks; i++)
1322                 if (sg[i].address == NULL) {
1323                         for (i=0; i<alloc_blocks; i++)
1324                                 if (sg[i].address != NULL)
1325                                         kfree(sg[i].address);
1326                         kfree(sg);
1327                         return 0;
1328                 }
1329
1330         numblocks = info->capacity >> (info->blockshift + info->pageshift);
1331
1332         result = sddr09_read_control(us, 0, numblocks,
1333                                      (unsigned char *)sg, alloc_blocks);
1334         if (result != USB_STOR_TRANSPORT_GOOD) {
1335                 for (i=0; i<alloc_blocks; i++)
1336                         kfree(sg[i].address);
1337                 kfree(sg);
1338                 return -1;
1339         }
1340
1341         kfree(info->lba_to_pba);
1342         kfree(info->pba_to_lba);
1343         info->lba_to_pba = kmalloc(numblocks*sizeof(int), GFP_NOIO);
1344         info->pba_to_lba = kmalloc(numblocks*sizeof(int), GFP_NOIO);
1345
1346         if (info->lba_to_pba == NULL || info->pba_to_lba == NULL) {
1347                 kfree(info->lba_to_pba);
1348                 kfree(info->pba_to_lba);
1349                 info->lba_to_pba = NULL;
1350                 info->pba_to_lba = NULL;
1351                 for (i=0; i<alloc_blocks; i++)
1352                         kfree(sg[i].address);
1353                 kfree(sg);
1354                 return 0;
1355         }
1356
1357         for (i = 0; i < numblocks; i++)
1358                 info->lba_to_pba[i] = info->pba_to_lba[i] = UNDEF;
1359
1360         ptr = sg[0].address;
1361
1362         /*
1363          * Define lba-pba translation table
1364          */
1365         // Each block is 64 bytes of control data, so block i is located in
1366         // scatterlist block i*64/128k = i*(2^6)*(2^-17) = i*(2^-11)
1367
1368 #if 0
1369         /* No translation */
1370         for (i=0; i<numblocks; i++) {
1371                 lba = i;
1372                 info->pba_to_lba[i] = lba;
1373                 info->lba_to_pba[lba] = i;
1374         }
1375         printk("sddr09: no translation today\n");
1376 #else
1377         for (i=0; i<numblocks; i++) {
1378                 ptr = sg[i>>11].address + ((i&0x7ff)<<6);
1379
1380                 if (i == 0 || i == 1) {
1381                         info->pba_to_lba[i] = UNUSABLE;
1382                         continue;
1383                 }
1384
1385                 /* special PBAs have control field 0^16 */
1386                 for (j = 0; j < 16; j++)
1387                         if (ptr[j] != 0)
1388                                 goto nonz;
1389                 info->pba_to_lba[i] = UNUSABLE;
1390                 printk("sddr09: PBA %04X has no logical mapping\n", i);
1391                 continue;
1392
1393         nonz:
1394                 /* unwritten PBAs have control field FF^16 */
1395                 for (j = 0; j < 16; j++)
1396                         if (ptr[j] != 0xff)
1397                                 goto nonff;
1398                 continue;
1399
1400         nonff:
1401                 /* normal PBAs start with six FFs */
1402                 if (j < 6) {
1403                         printk("sddr09: PBA %04X has no logical mapping: "
1404                                "reserved area = %02X%02X%02X%02X "
1405                                "data status %02X block status %02X\n",
1406                                i, ptr[0], ptr[1], ptr[2], ptr[3],
1407                                ptr[4], ptr[5]);
1408                         info->pba_to_lba[i] = UNUSABLE;
1409                         continue;
1410                 }
1411
1412                 if ((ptr[6] >> 4) != 0x01) {
1413                         printk("sddr09: PBA %04X has invalid address field "
1414                                "%02X%02X/%02X%02X\n",
1415                                i, ptr[6], ptr[7], ptr[11], ptr[12]);
1416                         info->pba_to_lba[i] = UNUSABLE;
1417                         continue;
1418                 }
1419
1420                 /* check even parity */
1421                 if (parity[ptr[6] ^ ptr[7]]) {
1422                         printk("sddr09: Bad parity in LBA for block %04X"
1423                                " (%02X %02X)\n", i, ptr[6], ptr[7]);
1424                         info->pba_to_lba[i] = UNUSABLE;
1425                         continue;
1426                 }
1427
1428                 lba = short_pack(ptr[7], ptr[6]);
1429                 lba = (lba & 0x07FF) >> 1;
1430
1431                 /*
1432                  * Every 1024 physical blocks ("zone"), the LBA numbers
1433                  * go back to zero, but are within a higher block of LBA's.
1434                  * Also, there is a maximum of 1000 LBA's per zone.
1435                  * In other words, in PBA 1024-2047 you will find LBA 0-999
1436                  * which are really LBA 1000-1999. This allows for 24 bad
1437                  * or special physical blocks per zone.
1438                  */
1439
1440                 if (lba >= 1000) {
1441                         printk("sddr09: Bad LBA %04X for block %04X\n",
1442                                lba, i);
1443                         info->pba_to_lba[i] = UNDEF /* UNUSABLE */;
1444                         continue;
1445                 }
1446
1447                 lba += 1000*(i/0x400);
1448
1449                 if (lba<0x10 || (lba >= 0x3E0 && lba < 0x3EF))
1450                         US_DEBUGP("LBA %04X <-> PBA %04X\n", lba, i);
1451
1452                 info->pba_to_lba[i] = lba;
1453                 info->lba_to_pba[lba] = i;
1454         }
1455 #endif
1456
1457         /*
1458          * Approximate capacity. This is not entirely correct yet,
1459          * since a zone with less than 1000 usable pages leads to
1460          * missing LBAs. Especially if it is the last zone, some
1461          * LBAs can be past capacity.
1462          */
1463         lbact = 0;
1464         for (i = 0; i < numblocks; i += 1024) {
1465                 int ct = 0;
1466
1467                 for (j = 0; j < 1024 && i+j < numblocks; j++) {
1468                         if (info->pba_to_lba[i+j] != UNUSABLE) {
1469                                 if (ct >= 1000)
1470                                         info->pba_to_lba[i+j] = SPARE;
1471                                 else
1472                                         ct++;
1473                         }
1474                 }
1475                 lbact += ct;
1476         }
1477         info->lbact = lbact;
1478         US_DEBUGP("Found %d LBA's\n", lbact);
1479
1480         for (i=0; i<alloc_blocks; i++)
1481                 kfree(sg[i].address);
1482         kfree(sg);
1483         return 0;
1484 }
1485
1486 static void
1487 sddr09_card_info_destructor(void *extra) {
1488         struct sddr09_card_info *info = (struct sddr09_card_info *)extra;
1489
1490         if (!info)
1491                 return;
1492
1493         kfree(info->lba_to_pba);
1494         kfree(info->pba_to_lba);
1495 }
1496
1497 static void
1498 sddr09_init_card_info(struct us_data *us) {
1499         if (!us->extra) {
1500                 us->extra = kmalloc(sizeof(struct sddr09_card_info), GFP_NOIO);
1501                 if (us->extra) {
1502                         memset(us->extra, 0, sizeof(struct sddr09_card_info));
1503                         us->extra_destructor = sddr09_card_info_destructor;
1504                 }
1505         }
1506 }
1507
1508 /*
1509  * It is unclear whether this does anything.
1510  * However, the request sense succeeds only after a reboot,
1511  * not if we do this a second time.
1512  */
1513 int
1514 sddr09_init(struct us_data *us) {
1515 #if 0
1516         int result;
1517         unsigned char data[2];
1518
1519         printk("sddr09_init\n");
1520
1521         nand_init_ecc();
1522
1523         result = sddr09_send_command(us, 0x01, USB_DIR_IN, data, 2);
1524         if (result != USB_STOR_TRANSPORT_GOOD) {
1525                 US_DEBUGP("sddr09_init: send_command fails\n");
1526                 return result;
1527         }
1528
1529         US_DEBUGP("SDDR09init: %02X %02X\n", data[0], data[1]);
1530         // get 07 02
1531
1532         result = sddr09_send_command(us, 0x08, USB_DIR_IN, data, 2);
1533         if (result != USB_STOR_TRANSPORT_GOOD) {
1534                 US_DEBUGP("sddr09_init: 2nd send_command fails\n");
1535                 return result;
1536         }
1537
1538         US_DEBUGP("SDDR09init: %02X %02X\n", data[0], data[1]);
1539         // get 07 00
1540
1541 #if 1
1542         result = sddr09_request_sense(us, data, sizeof(data));
1543         if (result == USB_STOR_TRANSPORT_GOOD && data[2] != 0) {
1544                 int j;
1545                 for (j=0; j<sizeof(data); j++)
1546                         printk(" %02X", data[j]);
1547                 printk("\n");
1548                 // get 70 00 00 00 00 00 00 * 00 00 00 00 00 00
1549                 // 70: current command
1550                 // sense key 0, sense code 0, extd sense code 0
1551                 // additional transfer length * = sizeof(data) - 7
1552         }
1553 #endif
1554 #endif
1555         return USB_STOR_TRANSPORT_GOOD;         /* not result */
1556 }
1557
1558 /*
1559  * Transport for the Sandisk SDDR-09
1560  */
1561 int sddr09_transport(Scsi_Cmnd *srb, struct us_data *us)
1562 {
1563         static unsigned char sense = 0;
1564         static unsigned char havefakesense = 0;
1565         int result, i;
1566         unsigned char *ptr;
1567         unsigned long capacity;
1568         unsigned int page, pages;
1569         char string[64];
1570
1571         struct sddr09_card_info *info;
1572
1573         unsigned char inquiry_response[36] = {
1574                 0x00, 0x80, 0x00, 0x02, 0x1F, 0x00, 0x00, 0x00
1575         };
1576
1577         unsigned char mode_page_01[16] = {
1578                 0x0F, 0x00, 0, 0x00,
1579                 0x01, 0x0A,
1580                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
1581         };
1582
1583         info = (struct sddr09_card_info *)us->extra;
1584         if (!info) {
1585                 nand_init_ecc();
1586                 sddr09_init_card_info(us);
1587                 info = (struct sddr09_card_info *)us->extra;
1588                 if (!info)
1589                         return USB_STOR_TRANSPORT_ERROR;
1590         }
1591
1592         ptr = (unsigned char *)srb->request_buffer;
1593
1594         if (srb->cmnd[0] == REQUEST_SENSE && havefakesense) {
1595                 /* for a faked command, we have to follow with a faked sense */
1596                 memset(ptr, 0, srb->request_bufflen);
1597                 if (srb->request_bufflen > 7) {
1598                         ptr[0] = 0x70;
1599                         ptr[2] = sense;
1600                         ptr[7] = srb->request_bufflen - 7;
1601                 }
1602                 sense = havefakesense = 0;
1603                 return USB_STOR_TRANSPORT_GOOD;
1604         }
1605
1606         sense = 0;
1607         havefakesense = 1;
1608
1609         /* Dummy up a response for INQUIRY since SDDR09 doesn't
1610            respond to INQUIRY commands */
1611
1612         if (srb->cmnd[0] == INQUIRY) {
1613                 memset(inquiry_response+8, 0, 28);
1614                 fill_inquiry_response(us, inquiry_response, 36);
1615                 return USB_STOR_TRANSPORT_GOOD;
1616         }
1617
1618         if (srb->cmnd[0] == READ_CAPACITY) {
1619                 struct nand_flash_dev *cardinfo;
1620
1621                 sddr09_get_wp(us, info);        /* read WP bit */
1622
1623                 cardinfo = sddr09_get_cardinfo(us, info->flags);
1624                 if (!cardinfo)
1625                         return USB_STOR_TRANSPORT_FAILED;
1626
1627                 info->capacity = (1 << cardinfo->chipshift);
1628                 info->pageshift = cardinfo->pageshift;
1629                 info->pagesize = (1 << info->pageshift);
1630                 info->blockshift = cardinfo->blockshift;
1631                 info->blocksize = (1 << info->blockshift);
1632                 info->blockmask = info->blocksize - 1;
1633
1634                 // map initialization, must follow get_cardinfo()
1635                 sddr09_read_map(us);
1636
1637                 // Report capacity
1638
1639                 capacity = (info->lbact << info->blockshift) - 1;
1640
1641                 ptr[0] = MSB_of(capacity>>16);
1642                 ptr[1] = LSB_of(capacity>>16);
1643                 ptr[2] = MSB_of(capacity&0xFFFF);
1644                 ptr[3] = LSB_of(capacity&0xFFFF);
1645
1646                 // Report page size
1647
1648                 ptr[4] = MSB_of(info->pagesize>>16);
1649                 ptr[5] = LSB_of(info->pagesize>>16);
1650                 ptr[6] = MSB_of(info->pagesize&0xFFFF);
1651                 ptr[7] = LSB_of(info->pagesize&0xFFFF);
1652
1653                 return USB_STOR_TRANSPORT_GOOD;
1654         }
1655
1656         if (srb->cmnd[0] == MODE_SENSE) {
1657
1658                 // Read-write error recovery page: there needs to
1659                 // be a check for write-protect here
1660
1661                 if ( (srb->cmnd[2] & 0x3F) == 0x01 ) {
1662
1663                         US_DEBUGP(
1664                                 "SDDR09: Dummy up request for mode page 1\n");
1665
1666                         if (ptr == NULL || 
1667                             srb->request_bufflen<sizeof(mode_page_01))
1668                                 return USB_STOR_TRANSPORT_ERROR;
1669
1670                         mode_page_01[0] = sizeof(mode_page_01) - 1;
1671                         mode_page_01[2] = (info->flags & SDDR09_WP) ? 0x80 : 0;
1672                         memcpy(ptr, mode_page_01, sizeof(mode_page_01));
1673                         return USB_STOR_TRANSPORT_GOOD;
1674
1675                 } else if ( (srb->cmnd[2] & 0x3F) == 0x3F ) {
1676
1677                         US_DEBUGP("SDDR09: Dummy up request for "
1678                                   "all mode pages\n");
1679
1680                         if (ptr == NULL || 
1681                             srb->request_bufflen<sizeof(mode_page_01))
1682                                 return USB_STOR_TRANSPORT_ERROR;
1683
1684                         memcpy(ptr, mode_page_01, sizeof(mode_page_01));
1685                         return USB_STOR_TRANSPORT_GOOD;
1686
1687                 }
1688
1689                 return USB_STOR_TRANSPORT_ERROR;
1690         }
1691
1692         if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) {
1693
1694                 US_DEBUGP(
1695                         "SDDR09: %s medium removal. Not that I can do"
1696                         " anything about it...\n",
1697                         (srb->cmnd[4]&0x03) ? "Prevent" : "Allow");
1698
1699                 return USB_STOR_TRANSPORT_GOOD;
1700
1701         }
1702
1703         havefakesense = 0;
1704
1705         if (srb->cmnd[0] == READ_10) {
1706
1707                 page = short_pack(srb->cmnd[3], srb->cmnd[2]);
1708                 page <<= 16;
1709                 page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
1710                 pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
1711
1712                 US_DEBUGP("READ_10: read page %d pagect %d\n",
1713                           page, pages);
1714
1715                 return sddr09_read_data(us, page, pages, ptr, srb->use_sg);
1716         }
1717
1718         if (srb->cmnd[0] == WRITE_10) {
1719
1720                 page = short_pack(srb->cmnd[3], srb->cmnd[2]);
1721                 page <<= 16;
1722                 page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
1723                 pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
1724
1725                 US_DEBUGP("WRITE_10: write page %d pagect %d\n",
1726                           page, pages);
1727
1728                 return sddr09_write_data(us, page, pages, ptr, srb->use_sg);
1729         }
1730
1731         // Pass TEST_UNIT_READY and REQUEST_SENSE through
1732
1733         if (srb->cmnd[0] != TEST_UNIT_READY &&
1734             srb->cmnd[0] != REQUEST_SENSE) {
1735                 havefakesense = 1;
1736                 return USB_STOR_TRANSPORT_ERROR;
1737         }
1738
1739         for (; srb->cmd_len<12; srb->cmd_len++)
1740                 srb->cmnd[srb->cmd_len] = 0;
1741
1742         srb->cmnd[1] = 0x20;
1743
1744         string[0] = 0;
1745         for (i=0; i<12; i++)
1746                 sprintf(string+strlen(string), "%02X ", srb->cmnd[i]);
1747
1748         US_DEBUGP("SDDR09: Send control for command %s\n",
1749                   string);
1750
1751         result = sddr09_send_scsi_command(us, srb->cmnd, 12);
1752         if (result != USB_STOR_TRANSPORT_GOOD) {
1753                 US_DEBUGP("sddr09_transport: sddr09_send_scsi_command "
1754                           "returns %d\n", result);
1755                 return result;
1756         }
1757
1758         if (srb->request_bufflen == 0)
1759                 return USB_STOR_TRANSPORT_GOOD;
1760
1761         if (srb->sc_data_direction == SCSI_DATA_WRITE ||
1762             srb->sc_data_direction == SCSI_DATA_READ) {
1763
1764                 US_DEBUGP("SDDR09: %s %d bytes\n",
1765                           (srb->sc_data_direction == SCSI_DATA_WRITE) ?
1766                           "sending" : "receiving",
1767                           srb->request_bufflen);
1768
1769                 result = sddr09_bulk_transport(us,
1770                                                srb->sc_data_direction,
1771                                                srb->request_buffer, 
1772                                                srb->request_bufflen,
1773                                                srb->use_sg);
1774
1775                 return result;
1776         } 
1777
1778         return USB_STOR_TRANSPORT_GOOD;
1779 }
1780