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