1/*
2 * Driver for Alauda-based card readers
3 *
4 * Current development and maintenance by:
5 *   (c) 2005 Daniel Drake <dsd@gentoo.org>
6 *
7 * The 'Alauda' is a chip manufacturered by RATOC for OEM use.
8 *
9 * Alauda implements a vendor-specific command set to access two media reader
10 * ports (XD, SmartMedia). This driver converts SCSI commands to the commands
11 * which are accepted by these devices.
12 *
13 * The driver was developed through reverse-engineering, with the help of the
14 * sddr09 driver which has many similarities, and with some help from the
15 * (very old) vendor-supplied GPL sma03 driver.
16 *
17 * For protocol info, see http://alauda.sourceforge.net
18 *
19 * This program is free software; you can redistribute it and/or modify it
20 * under the terms of the GNU General Public License as published by the
21 * Free Software Foundation; either version 2, or (at your option) any
22 * later version.
23 *
24 * This program is distributed in the hope that it will be useful, but
25 * WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27 * General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License along
30 * with this program; if not, write to the Free Software Foundation, Inc.,
31 * 675 Mass Ave, Cambridge, MA 02139, USA.
32 */
33
34#include <linux/module.h>
35#include <linux/slab.h>
36
37#include <scsi/scsi.h>
38#include <scsi/scsi_cmnd.h>
39#include <scsi/scsi_device.h>
40
41#include "usb.h"
42#include "transport.h"
43#include "protocol.h"
44#include "debug.h"
45
46MODULE_DESCRIPTION("Driver for Alauda-based card readers");
47MODULE_AUTHOR("Daniel Drake <dsd@gentoo.org>");
48MODULE_LICENSE("GPL");
49
50/*
51 * Status bytes
52 */
53#define ALAUDA_STATUS_ERROR		0x01
54#define ALAUDA_STATUS_READY		0x40
55
56/*
57 * Control opcodes (for request field)
58 */
59#define ALAUDA_GET_XD_MEDIA_STATUS	0x08
60#define ALAUDA_GET_SM_MEDIA_STATUS	0x98
61#define ALAUDA_ACK_XD_MEDIA_CHANGE	0x0a
62#define ALAUDA_ACK_SM_MEDIA_CHANGE	0x9a
63#define ALAUDA_GET_XD_MEDIA_SIG		0x86
64#define ALAUDA_GET_SM_MEDIA_SIG		0x96
65
66/*
67 * Bulk command identity (byte 0)
68 */
69#define ALAUDA_BULK_CMD			0x40
70
71/*
72 * Bulk opcodes (byte 1)
73 */
74#define ALAUDA_BULK_GET_REDU_DATA	0x85
75#define ALAUDA_BULK_READ_BLOCK		0x94
76#define ALAUDA_BULK_ERASE_BLOCK		0xa3
77#define ALAUDA_BULK_WRITE_BLOCK		0xb4
78#define ALAUDA_BULK_GET_STATUS2		0xb7
79#define ALAUDA_BULK_RESET_MEDIA		0xe0
80
81/*
82 * Port to operate on (byte 8)
83 */
84#define ALAUDA_PORT_XD			0x00
85#define ALAUDA_PORT_SM			0x01
86
87/*
88 * LBA and PBA are unsigned ints. Special values.
89 */
90#define UNDEF    0xffff
91#define SPARE    0xfffe
92#define UNUSABLE 0xfffd
93
94struct alauda_media_info {
95	unsigned long capacity;		/* total media size in bytes */
96	unsigned int pagesize;		/* page size in bytes */
97	unsigned int blocksize;		/* number of pages per block */
98	unsigned int uzonesize;		/* number of usable blocks per zone */
99	unsigned int zonesize;		/* number of blocks per zone */
100	unsigned int blockmask;		/* mask to get page from address */
101
102	unsigned char pageshift;
103	unsigned char blockshift;
104	unsigned char zoneshift;
105
106	u16 **lba_to_pba;		/* logical to physical block map */
107	u16 **pba_to_lba;		/* physical to logical block map */
108};
109
110struct alauda_info {
111	struct alauda_media_info port[2];
112	int wr_ep;			/* endpoint to write data out of */
113
114	unsigned char sense_key;
115	unsigned long sense_asc;	/* additional sense code */
116	unsigned long sense_ascq;	/* additional sense code qualifier */
117};
118
119#define short_pack(lsb,msb) ( ((u16)(lsb)) | ( ((u16)(msb))<<8 ) )
120#define LSB_of(s) ((s)&0xFF)
121#define MSB_of(s) ((s)>>8)
122
123#define MEDIA_PORT(us) us->srb->device->lun
124#define MEDIA_INFO(us) ((struct alauda_info *)us->extra)->port[MEDIA_PORT(us)]
125
126#define PBA_LO(pba) ((pba & 0xF) << 5)
127#define PBA_HI(pba) (pba >> 3)
128#define PBA_ZONE(pba) (pba >> 11)
129
130static int init_alauda(struct us_data *us);
131
132
133/*
134 * The table of devices
135 */
136#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
137		    vendorName, productName, useProtocol, useTransport, \
138		    initFunction, flags) \
139{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
140  .driver_info = (flags) }
141
142static struct usb_device_id alauda_usb_ids[] = {
143#	include "unusual_alauda.h"
144	{ }		/* Terminating entry */
145};
146MODULE_DEVICE_TABLE(usb, alauda_usb_ids);
147
148#undef UNUSUAL_DEV
149
150/*
151 * The flags table
152 */
153#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
154		    vendor_name, product_name, use_protocol, use_transport, \
155		    init_function, Flags) \
156{ \
157	.vendorName = vendor_name,	\
158	.productName = product_name,	\
159	.useProtocol = use_protocol,	\
160	.useTransport = use_transport,	\
161	.initFunction = init_function,	\
162}
163
164static struct us_unusual_dev alauda_unusual_dev_list[] = {
165#	include "unusual_alauda.h"
166	{ }		/* Terminating entry */
167};
168
169#undef UNUSUAL_DEV
170
171
172/*
173 * Media handling
174 */
175
176struct alauda_card_info {
177	unsigned char id;		/* id byte */
178	unsigned char chipshift;	/* 1<<cs bytes total capacity */
179	unsigned char pageshift;	/* 1<<ps bytes in a page */
180	unsigned char blockshift;	/* 1<<bs pages per block */
181	unsigned char zoneshift;	/* 1<<zs blocks per zone */
182};
183
184static struct alauda_card_info alauda_card_ids[] = {
185	/* NAND flash */
186	{ 0x6e, 20, 8, 4, 8},	/* 1 MB */
187	{ 0xe8, 20, 8, 4, 8},	/* 1 MB */
188	{ 0xec, 20, 8, 4, 8},	/* 1 MB */
189	{ 0x64, 21, 8, 4, 9}, 	/* 2 MB */
190	{ 0xea, 21, 8, 4, 9},	/* 2 MB */
191	{ 0x6b, 22, 9, 4, 9},	/* 4 MB */
192	{ 0xe3, 22, 9, 4, 9},	/* 4 MB */
193	{ 0xe5, 22, 9, 4, 9},	/* 4 MB */
194	{ 0xe6, 23, 9, 4, 10},	/* 8 MB */
195	{ 0x73, 24, 9, 5, 10},	/* 16 MB */
196	{ 0x75, 25, 9, 5, 10},	/* 32 MB */
197	{ 0x76, 26, 9, 5, 10},	/* 64 MB */
198	{ 0x79, 27, 9, 5, 10},	/* 128 MB */
199	{ 0x71, 28, 9, 5, 10},	/* 256 MB */
200
201	/* MASK ROM */
202	{ 0x5d, 21, 9, 4, 8},	/* 2 MB */
203	{ 0xd5, 22, 9, 4, 9},	/* 4 MB */
204	{ 0xd6, 23, 9, 4, 10},	/* 8 MB */
205	{ 0x57, 24, 9, 4, 11},	/* 16 MB */
206	{ 0x58, 25, 9, 4, 12},	/* 32 MB */
207	{ 0,}
208};
209
210static struct alauda_card_info *alauda_card_find_id(unsigned char id)
211{
212	int i;
213
214	for (i = 0; alauda_card_ids[i].id != 0; i++)
215		if (alauda_card_ids[i].id == id)
216			return &(alauda_card_ids[i]);
217	return NULL;
218}
219
220/*
221 * ECC computation.
222 */
223
224static unsigned char parity[256];
225static unsigned char ecc2[256];
226
227static void nand_init_ecc(void)
228{
229	int i, j, a;
230
231	parity[0] = 0;
232	for (i = 1; i < 256; i++)
233		parity[i] = (parity[i&(i-1)] ^ 1);
234
235	for (i = 0; i < 256; i++) {
236		a = 0;
237		for (j = 0; j < 8; j++) {
238			if (i & (1<<j)) {
239				if ((j & 1) == 0)
240					a ^= 0x04;
241				if ((j & 2) == 0)
242					a ^= 0x10;
243				if ((j & 4) == 0)
244					a ^= 0x40;
245			}
246		}
247		ecc2[i] = ~(a ^ (a<<1) ^ (parity[i] ? 0xa8 : 0));
248	}
249}
250
251/* compute 3-byte ecc on 256 bytes */
252static void nand_compute_ecc(unsigned char *data, unsigned char *ecc)
253{
254	int i, j, a;
255	unsigned char par = 0, bit, bits[8] = {0};
256
257	/* collect 16 checksum bits */
258	for (i = 0; i < 256; i++) {
259		par ^= data[i];
260		bit = parity[data[i]];
261		for (j = 0; j < 8; j++)
262			if ((i & (1<<j)) == 0)
263				bits[j] ^= bit;
264	}
265
266	/* put 4+4+4 = 12 bits in the ecc */
267	a = (bits[3] << 6) + (bits[2] << 4) + (bits[1] << 2) + bits[0];
268	ecc[0] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
269
270	a = (bits[7] << 6) + (bits[6] << 4) + (bits[5] << 2) + bits[4];
271	ecc[1] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
272
273	ecc[2] = ecc2[par];
274}
275
276static int nand_compare_ecc(unsigned char *data, unsigned char *ecc)
277{
278	return (data[0] == ecc[0] && data[1] == ecc[1] && data[2] == ecc[2]);
279}
280
281static void nand_store_ecc(unsigned char *data, unsigned char *ecc)
282{
283	memcpy(data, ecc, 3);
284}
285
286/*
287 * Alauda driver
288 */
289
290/*
291 * Forget our PBA <---> LBA mappings for a particular port
292 */
293static void alauda_free_maps (struct alauda_media_info *media_info)
294{
295	unsigned int shift = media_info->zoneshift
296		+ media_info->blockshift + media_info->pageshift;
297	unsigned int num_zones = media_info->capacity >> shift;
298	unsigned int i;
299
300	if (media_info->lba_to_pba != NULL)
301		for (i = 0; i < num_zones; i++) {
302			kfree(media_info->lba_to_pba[i]);
303			media_info->lba_to_pba[i] = NULL;
304		}
305
306	if (media_info->pba_to_lba != NULL)
307		for (i = 0; i < num_zones; i++) {
308			kfree(media_info->pba_to_lba[i]);
309			media_info->pba_to_lba[i] = NULL;
310		}
311}
312
313/*
314 * Returns 2 bytes of status data
315 * The first byte describes media status, and second byte describes door status
316 */
317static int alauda_get_media_status(struct us_data *us, unsigned char *data)
318{
319	int rc;
320	unsigned char command;
321
322	if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
323		command = ALAUDA_GET_XD_MEDIA_STATUS;
324	else
325		command = ALAUDA_GET_SM_MEDIA_STATUS;
326
327	rc = usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
328		command, 0xc0, 0, 1, data, 2);
329
330	usb_stor_dbg(us, "Media status %02X %02X\n", data[0], data[1]);
331
332	return rc;
333}
334
335/*
336 * Clears the "media was changed" bit so that we know when it changes again
337 * in the future.
338 */
339static int alauda_ack_media(struct us_data *us)
340{
341	unsigned char command;
342
343	if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
344		command = ALAUDA_ACK_XD_MEDIA_CHANGE;
345	else
346		command = ALAUDA_ACK_SM_MEDIA_CHANGE;
347
348	return usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
349		command, 0x40, 0, 1, NULL, 0);
350}
351
352/*
353 * Retrieves a 4-byte media signature, which indicates manufacturer, capacity,
354 * and some other details.
355 */
356static int alauda_get_media_signature(struct us_data *us, unsigned char *data)
357{
358	unsigned char command;
359
360	if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
361		command = ALAUDA_GET_XD_MEDIA_SIG;
362	else
363		command = ALAUDA_GET_SM_MEDIA_SIG;
364
365	return usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
366		command, 0xc0, 0, 0, data, 4);
367}
368
369/*
370 * Resets the media status (but not the whole device?)
371 */
372static int alauda_reset_media(struct us_data *us)
373{
374	unsigned char *command = us->iobuf;
375
376	memset(command, 0, 9);
377	command[0] = ALAUDA_BULK_CMD;
378	command[1] = ALAUDA_BULK_RESET_MEDIA;
379	command[8] = MEDIA_PORT(us);
380
381	return usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
382		command, 9, NULL);
383}
384
385/*
386 * Examines the media and deduces capacity, etc.
387 */
388static int alauda_init_media(struct us_data *us)
389{
390	unsigned char *data = us->iobuf;
391	int ready = 0;
392	struct alauda_card_info *media_info;
393	unsigned int num_zones;
394
395	while (ready == 0) {
396		msleep(20);
397
398		if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD)
399			return USB_STOR_TRANSPORT_ERROR;
400
401		if (data[0] & 0x10)
402			ready = 1;
403	}
404
405	usb_stor_dbg(us, "We are ready for action!\n");
406
407	if (alauda_ack_media(us) != USB_STOR_XFER_GOOD)
408		return USB_STOR_TRANSPORT_ERROR;
409
410	msleep(10);
411
412	if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD)
413		return USB_STOR_TRANSPORT_ERROR;
414
415	if (data[0] != 0x14) {
416		usb_stor_dbg(us, "Media not ready after ack\n");
417		return USB_STOR_TRANSPORT_ERROR;
418	}
419
420	if (alauda_get_media_signature(us, data) != USB_STOR_XFER_GOOD)
421		return USB_STOR_TRANSPORT_ERROR;
422
423	usb_stor_dbg(us, "Media signature: %4ph\n", data);
424	media_info = alauda_card_find_id(data[1]);
425	if (media_info == NULL) {
426		pr_warn("alauda_init_media: Unrecognised media signature: %4ph\n",
427			data);
428		return USB_STOR_TRANSPORT_ERROR;
429	}
430
431	MEDIA_INFO(us).capacity = 1 << media_info->chipshift;
432	usb_stor_dbg(us, "Found media with capacity: %ldMB\n",
433		     MEDIA_INFO(us).capacity >> 20);
434
435	MEDIA_INFO(us).pageshift = media_info->pageshift;
436	MEDIA_INFO(us).blockshift = media_info->blockshift;
437	MEDIA_INFO(us).zoneshift = media_info->zoneshift;
438
439	MEDIA_INFO(us).pagesize = 1 << media_info->pageshift;
440	MEDIA_INFO(us).blocksize = 1 << media_info->blockshift;
441	MEDIA_INFO(us).zonesize = 1 << media_info->zoneshift;
442
443	MEDIA_INFO(us).uzonesize = ((1 << media_info->zoneshift) / 128) * 125;
444	MEDIA_INFO(us).blockmask = MEDIA_INFO(us).blocksize - 1;
445
446	num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift
447		+ MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift);
448	MEDIA_INFO(us).pba_to_lba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO);
449	MEDIA_INFO(us).lba_to_pba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO);
450
451	if (alauda_reset_media(us) != USB_STOR_XFER_GOOD)
452		return USB_STOR_TRANSPORT_ERROR;
453
454	return USB_STOR_TRANSPORT_GOOD;
455}
456
457/*
458 * Examines the media status and does the right thing when the media has gone,
459 * appeared, or changed.
460 */
461static int alauda_check_media(struct us_data *us)
462{
463	struct alauda_info *info = (struct alauda_info *) us->extra;
464	unsigned char status[2];
465	int rc;
466
467	rc = alauda_get_media_status(us, status);
468
469	/* Check for no media or door open */
470	if ((status[0] & 0x80) || ((status[0] & 0x1F) == 0x10)
471		|| ((status[1] & 0x01) == 0)) {
472		usb_stor_dbg(us, "No media, or door open\n");
473		alauda_free_maps(&MEDIA_INFO(us));
474		info->sense_key = 0x02;
475		info->sense_asc = 0x3A;
476		info->sense_ascq = 0x00;
477		return USB_STOR_TRANSPORT_FAILED;
478	}
479
480	/* Check for media change */
481	if (status[0] & 0x08) {
482		usb_stor_dbg(us, "Media change detected\n");
483		alauda_free_maps(&MEDIA_INFO(us));
484		alauda_init_media(us);
485
486		info->sense_key = UNIT_ATTENTION;
487		info->sense_asc = 0x28;
488		info->sense_ascq = 0x00;
489		return USB_STOR_TRANSPORT_FAILED;
490	}
491
492	return USB_STOR_TRANSPORT_GOOD;
493}
494
495/*
496 * Checks the status from the 2nd status register
497 * Returns 3 bytes of status data, only the first is known
498 */
499static int alauda_check_status2(struct us_data *us)
500{
501	int rc;
502	unsigned char command[] = {
503		ALAUDA_BULK_CMD, ALAUDA_BULK_GET_STATUS2,
504		0, 0, 0, 0, 3, 0, MEDIA_PORT(us)
505	};
506	unsigned char data[3];
507
508	rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
509		command, 9, NULL);
510	if (rc != USB_STOR_XFER_GOOD)
511		return rc;
512
513	rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
514		data, 3, NULL);
515	if (rc != USB_STOR_XFER_GOOD)
516		return rc;
517
518	usb_stor_dbg(us, "%3ph\n", data);
519	if (data[0] & ALAUDA_STATUS_ERROR)
520		return USB_STOR_XFER_ERROR;
521
522	return USB_STOR_XFER_GOOD;
523}
524
525/*
526 * Gets the redundancy data for the first page of a PBA
527 * Returns 16 bytes.
528 */
529static int alauda_get_redu_data(struct us_data *us, u16 pba, unsigned char *data)
530{
531	int rc;
532	unsigned char command[] = {
533		ALAUDA_BULK_CMD, ALAUDA_BULK_GET_REDU_DATA,
534		PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 0, 0, MEDIA_PORT(us)
535	};
536
537	rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
538		command, 9, NULL);
539	if (rc != USB_STOR_XFER_GOOD)
540		return rc;
541
542	return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
543		data, 16, NULL);
544}
545
546/*
547 * Finds the first unused PBA in a zone
548 * Returns the absolute PBA of an unused PBA, or 0 if none found.
549 */
550static u16 alauda_find_unused_pba(struct alauda_media_info *info,
551	unsigned int zone)
552{
553	u16 *pba_to_lba = info->pba_to_lba[zone];
554	unsigned int i;
555
556	for (i = 0; i < info->zonesize; i++)
557		if (pba_to_lba[i] == UNDEF)
558			return (zone << info->zoneshift) + i;
559
560	return 0;
561}
562
563/*
564 * Reads the redundancy data for all PBA's in a zone
565 * Produces lba <--> pba mappings
566 */
567static int alauda_read_map(struct us_data *us, unsigned int zone)
568{
569	unsigned char *data = us->iobuf;
570	int result;
571	int i, j;
572	unsigned int zonesize = MEDIA_INFO(us).zonesize;
573	unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
574	unsigned int lba_offset, lba_real, blocknum;
575	unsigned int zone_base_lba = zone * uzonesize;
576	unsigned int zone_base_pba = zone * zonesize;
577	u16 *lba_to_pba = kcalloc(zonesize, sizeof(u16), GFP_NOIO);
578	u16 *pba_to_lba = kcalloc(zonesize, sizeof(u16), GFP_NOIO);
579	if (lba_to_pba == NULL || pba_to_lba == NULL) {
580		result = USB_STOR_TRANSPORT_ERROR;
581		goto error;
582	}
583
584	usb_stor_dbg(us, "Mapping blocks for zone %d\n", zone);
585
586	/* 1024 PBA's per zone */
587	for (i = 0; i < zonesize; i++)
588		lba_to_pba[i] = pba_to_lba[i] = UNDEF;
589
590	for (i = 0; i < zonesize; i++) {
591		blocknum = zone_base_pba + i;
592
593		result = alauda_get_redu_data(us, blocknum, data);
594		if (result != USB_STOR_XFER_GOOD) {
595			result = USB_STOR_TRANSPORT_ERROR;
596			goto error;
597		}
598
599		/* special PBAs have control field 0^16 */
600		for (j = 0; j < 16; j++)
601			if (data[j] != 0)
602				goto nonz;
603		pba_to_lba[i] = UNUSABLE;
604		usb_stor_dbg(us, "PBA %d has no logical mapping\n", blocknum);
605		continue;
606
607	nonz:
608		/* unwritten PBAs have control field FF^16 */
609		for (j = 0; j < 16; j++)
610			if (data[j] != 0xff)
611				goto nonff;
612		continue;
613
614	nonff:
615		/* normal PBAs start with six FFs */
616		if (j < 6) {
617			usb_stor_dbg(us, "PBA %d has no logical mapping: reserved area = %02X%02X%02X%02X data status %02X block status %02X\n",
618				     blocknum,
619				     data[0], data[1], data[2], data[3],
620				     data[4], data[5]);
621			pba_to_lba[i] = UNUSABLE;
622			continue;
623		}
624
625		if ((data[6] >> 4) != 0x01) {
626			usb_stor_dbg(us, "PBA %d has invalid address field %02X%02X/%02X%02X\n",
627				     blocknum, data[6], data[7],
628				     data[11], data[12]);
629			pba_to_lba[i] = UNUSABLE;
630			continue;
631		}
632
633		/* check even parity */
634		if (parity[data[6] ^ data[7]]) {
635			printk(KERN_WARNING
636			       "alauda_read_map: Bad parity in LBA for block %d"
637			       " (%02X %02X)\n", i, data[6], data[7]);
638			pba_to_lba[i] = UNUSABLE;
639			continue;
640		}
641
642		lba_offset = short_pack(data[7], data[6]);
643		lba_offset = (lba_offset & 0x07FF) >> 1;
644		lba_real = lba_offset + zone_base_lba;
645
646		/*
647		 * Every 1024 physical blocks ("zone"), the LBA numbers
648		 * go back to zero, but are within a higher block of LBA's.
649		 * Also, there is a maximum of 1000 LBA's per zone.
650		 * In other words, in PBA 1024-2047 you will find LBA 0-999
651		 * which are really LBA 1000-1999. This allows for 24 bad
652		 * or special physical blocks per zone.
653		 */
654
655		if (lba_offset >= uzonesize) {
656			printk(KERN_WARNING
657			       "alauda_read_map: Bad low LBA %d for block %d\n",
658			       lba_real, blocknum);
659			continue;
660		}
661
662		if (lba_to_pba[lba_offset] != UNDEF) {
663			printk(KERN_WARNING
664			       "alauda_read_map: "
665			       "LBA %d seen for PBA %d and %d\n",
666			       lba_real, lba_to_pba[lba_offset], blocknum);
667			continue;
668		}
669
670		pba_to_lba[i] = lba_real;
671		lba_to_pba[lba_offset] = blocknum;
672		continue;
673	}
674
675	MEDIA_INFO(us).lba_to_pba[zone] = lba_to_pba;
676	MEDIA_INFO(us).pba_to_lba[zone] = pba_to_lba;
677	result = 0;
678	goto out;
679
680error:
681	kfree(lba_to_pba);
682	kfree(pba_to_lba);
683out:
684	return result;
685}
686
687/*
688 * Checks to see whether we have already mapped a certain zone
689 * If we haven't, the map is generated
690 */
691static void alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone)
692{
693	if (MEDIA_INFO(us).lba_to_pba[zone] == NULL
694		|| MEDIA_INFO(us).pba_to_lba[zone] == NULL)
695		alauda_read_map(us, zone);
696}
697
698/*
699 * Erases an entire block
700 */
701static int alauda_erase_block(struct us_data *us, u16 pba)
702{
703	int rc;
704	unsigned char command[] = {
705		ALAUDA_BULK_CMD, ALAUDA_BULK_ERASE_BLOCK, PBA_HI(pba),
706		PBA_ZONE(pba), 0, PBA_LO(pba), 0x02, 0, MEDIA_PORT(us)
707	};
708	unsigned char buf[2];
709
710	usb_stor_dbg(us, "Erasing PBA %d\n", pba);
711
712	rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
713		command, 9, NULL);
714	if (rc != USB_STOR_XFER_GOOD)
715		return rc;
716
717	rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
718		buf, 2, NULL);
719	if (rc != USB_STOR_XFER_GOOD)
720		return rc;
721
722	usb_stor_dbg(us, "Erase result: %02X %02X\n", buf[0], buf[1]);
723	return rc;
724}
725
726/*
727 * Reads data from a certain offset page inside a PBA, including interleaved
728 * redundancy data. Returns (pagesize+64)*pages bytes in data.
729 */
730static int alauda_read_block_raw(struct us_data *us, u16 pba,
731		unsigned int page, unsigned int pages, unsigned char *data)
732{
733	int rc;
734	unsigned char command[] = {
735		ALAUDA_BULK_CMD, ALAUDA_BULK_READ_BLOCK, PBA_HI(pba),
736		PBA_ZONE(pba), 0, PBA_LO(pba) + page, pages, 0, MEDIA_PORT(us)
737	};
738
739	usb_stor_dbg(us, "pba %d page %d count %d\n", pba, page, pages);
740
741	rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
742		command, 9, NULL);
743	if (rc != USB_STOR_XFER_GOOD)
744		return rc;
745
746	return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
747		data, (MEDIA_INFO(us).pagesize + 64) * pages, NULL);
748}
749
750/*
751 * Reads data from a certain offset page inside a PBA, excluding redundancy
752 * data. Returns pagesize*pages bytes in data. Note that data must be big enough
753 * to hold (pagesize+64)*pages bytes of data, but you can ignore those 'extra'
754 * trailing bytes outside this function.
755 */
756static int alauda_read_block(struct us_data *us, u16 pba,
757		unsigned int page, unsigned int pages, unsigned char *data)
758{
759	int i, rc;
760	unsigned int pagesize = MEDIA_INFO(us).pagesize;
761
762	rc = alauda_read_block_raw(us, pba, page, pages, data);
763	if (rc != USB_STOR_XFER_GOOD)
764		return rc;
765
766	/* Cut out the redundancy data */
767	for (i = 0; i < pages; i++) {
768		int dest_offset = i * pagesize;
769		int src_offset = i * (pagesize + 64);
770		memmove(data + dest_offset, data + src_offset, pagesize);
771	}
772
773	return rc;
774}
775
776/*
777 * Writes an entire block of data and checks status after write.
778 * Redundancy data must be already included in data. Data should be
779 * (pagesize+64)*blocksize bytes in length.
780 */
781static int alauda_write_block(struct us_data *us, u16 pba, unsigned char *data)
782{
783	int rc;
784	struct alauda_info *info = (struct alauda_info *) us->extra;
785	unsigned char command[] = {
786		ALAUDA_BULK_CMD, ALAUDA_BULK_WRITE_BLOCK, PBA_HI(pba),
787		PBA_ZONE(pba), 0, PBA_LO(pba), 32, 0, MEDIA_PORT(us)
788	};
789
790	usb_stor_dbg(us, "pba %d\n", pba);
791
792	rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
793		command, 9, NULL);
794	if (rc != USB_STOR_XFER_GOOD)
795		return rc;
796
797	rc = usb_stor_bulk_transfer_buf(us, info->wr_ep, data,
798		(MEDIA_INFO(us).pagesize + 64) * MEDIA_INFO(us).blocksize,
799		NULL);
800	if (rc != USB_STOR_XFER_GOOD)
801		return rc;
802
803	return alauda_check_status2(us);
804}
805
806/*
807 * Write some data to a specific LBA.
808 */
809static int alauda_write_lba(struct us_data *us, u16 lba,
810		 unsigned int page, unsigned int pages,
811		 unsigned char *ptr, unsigned char *blockbuffer)
812{
813	u16 pba, lbap, new_pba;
814	unsigned char *bptr, *cptr, *xptr;
815	unsigned char ecc[3];
816	int i, result;
817	unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
818	unsigned int zonesize = MEDIA_INFO(us).zonesize;
819	unsigned int pagesize = MEDIA_INFO(us).pagesize;
820	unsigned int blocksize = MEDIA_INFO(us).blocksize;
821	unsigned int lba_offset = lba % uzonesize;
822	unsigned int new_pba_offset;
823	unsigned int zone = lba / uzonesize;
824
825	alauda_ensure_map_for_zone(us, zone);
826
827	pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset];
828	if (pba == 1) {
829		/* Maybe it is impossible to write to PBA 1.
830		   Fake success, but don't do anything. */
831		printk(KERN_WARNING
832		       "alauda_write_lba: avoid writing to pba 1\n");
833		return USB_STOR_TRANSPORT_GOOD;
834	}
835
836	new_pba = alauda_find_unused_pba(&MEDIA_INFO(us), zone);
837	if (!new_pba) {
838		printk(KERN_WARNING
839		       "alauda_write_lba: Out of unused blocks\n");
840		return USB_STOR_TRANSPORT_ERROR;
841	}
842
843	/* read old contents */
844	if (pba != UNDEF) {
845		result = alauda_read_block_raw(us, pba, 0,
846			blocksize, blockbuffer);
847		if (result != USB_STOR_XFER_GOOD)
848			return result;
849	} else {
850		memset(blockbuffer, 0, blocksize * (pagesize + 64));
851	}
852
853	lbap = (lba_offset << 1) | 0x1000;
854	if (parity[MSB_of(lbap) ^ LSB_of(lbap)])
855		lbap ^= 1;
856
857	/* check old contents and fill lba */
858	for (i = 0; i < blocksize; i++) {
859		bptr = blockbuffer + (i * (pagesize + 64));
860		cptr = bptr + pagesize;
861		nand_compute_ecc(bptr, ecc);
862		if (!nand_compare_ecc(cptr+13, ecc)) {
863			usb_stor_dbg(us, "Warning: bad ecc in page %d- of pba %d\n",
864				     i, pba);
865			nand_store_ecc(cptr+13, ecc);
866		}
867		nand_compute_ecc(bptr + (pagesize / 2), ecc);
868		if (!nand_compare_ecc(cptr+8, ecc)) {
869			usb_stor_dbg(us, "Warning: bad ecc in page %d+ of pba %d\n",
870				     i, pba);
871			nand_store_ecc(cptr+8, ecc);
872		}
873		cptr[6] = cptr[11] = MSB_of(lbap);
874		cptr[7] = cptr[12] = LSB_of(lbap);
875	}
876
877	/* copy in new stuff and compute ECC */
878	xptr = ptr;
879	for (i = page; i < page+pages; i++) {
880		bptr = blockbuffer + (i * (pagesize + 64));
881		cptr = bptr + pagesize;
882		memcpy(bptr, xptr, pagesize);
883		xptr += pagesize;
884		nand_compute_ecc(bptr, ecc);
885		nand_store_ecc(cptr+13, ecc);
886		nand_compute_ecc(bptr + (pagesize / 2), ecc);
887		nand_store_ecc(cptr+8, ecc);
888	}
889
890	result = alauda_write_block(us, new_pba, blockbuffer);
891	if (result != USB_STOR_XFER_GOOD)
892		return result;
893
894	new_pba_offset = new_pba - (zone * zonesize);
895	MEDIA_INFO(us).pba_to_lba[zone][new_pba_offset] = lba;
896	MEDIA_INFO(us).lba_to_pba[zone][lba_offset] = new_pba;
897	usb_stor_dbg(us, "Remapped LBA %d to PBA %d\n", lba, new_pba);
898
899	if (pba != UNDEF) {
900		unsigned int pba_offset = pba - (zone * zonesize);
901		result = alauda_erase_block(us, pba);
902		if (result != USB_STOR_XFER_GOOD)
903			return result;
904		MEDIA_INFO(us).pba_to_lba[zone][pba_offset] = UNDEF;
905	}
906
907	return USB_STOR_TRANSPORT_GOOD;
908}
909
910/*
911 * Read data from a specific sector address
912 */
913static int alauda_read_data(struct us_data *us, unsigned long address,
914		unsigned int sectors)
915{
916	unsigned char *buffer;
917	u16 lba, max_lba;
918	unsigned int page, len, offset;
919	unsigned int blockshift = MEDIA_INFO(us).blockshift;
920	unsigned int pageshift = MEDIA_INFO(us).pageshift;
921	unsigned int blocksize = MEDIA_INFO(us).blocksize;
922	unsigned int pagesize = MEDIA_INFO(us).pagesize;
923	unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
924	struct scatterlist *sg;
925	int result;
926
927	/*
928	 * Since we only read in one block at a time, we have to create
929	 * a bounce buffer and move the data a piece at a time between the
930	 * bounce buffer and the actual transfer buffer.
931	 * We make this buffer big enough to hold temporary redundancy data,
932	 * which we use when reading the data blocks.
933	 */
934
935	len = min(sectors, blocksize) * (pagesize + 64);
936	buffer = kmalloc(len, GFP_NOIO);
937	if (buffer == NULL) {
938		printk(KERN_WARNING "alauda_read_data: Out of memory\n");
939		return USB_STOR_TRANSPORT_ERROR;
940	}
941
942	/* Figure out the initial LBA and page */
943	lba = address >> blockshift;
944	page = (address & MEDIA_INFO(us).blockmask);
945	max_lba = MEDIA_INFO(us).capacity >> (blockshift + pageshift);
946
947	result = USB_STOR_TRANSPORT_GOOD;
948	offset = 0;
949	sg = NULL;
950
951	while (sectors > 0) {
952		unsigned int zone = lba / uzonesize; /* integer division */
953		unsigned int lba_offset = lba - (zone * uzonesize);
954		unsigned int pages;
955		u16 pba;
956		alauda_ensure_map_for_zone(us, zone);
957
958		/* Not overflowing capacity? */
959		if (lba >= max_lba) {
960			usb_stor_dbg(us, "Error: Requested lba %u exceeds maximum %u\n",
961				     lba, max_lba);
962			result = USB_STOR_TRANSPORT_ERROR;
963			break;
964		}
965
966		/* Find number of pages we can read in this block */
967		pages = min(sectors, blocksize - page);
968		len = pages << pageshift;
969
970		/* Find where this lba lives on disk */
971		pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset];
972
973		if (pba == UNDEF) {	/* this lba was never written */
974			usb_stor_dbg(us, "Read %d zero pages (LBA %d) page %d\n",
975				     pages, lba, page);
976
977			/* This is not really an error. It just means
978			   that the block has never been written.
979			   Instead of returning USB_STOR_TRANSPORT_ERROR
980			   it is better to return all zero data. */
981
982			memset(buffer, 0, len);
983		} else {
984			usb_stor_dbg(us, "Read %d pages, from PBA %d (LBA %d) page %d\n",
985				     pages, pba, lba, page);
986
987			result = alauda_read_block(us, pba, page, pages, buffer);
988			if (result != USB_STOR_TRANSPORT_GOOD)
989				break;
990		}
991
992		/* Store the data in the transfer buffer */
993		usb_stor_access_xfer_buf(buffer, len, us->srb,
994				&sg, &offset, TO_XFER_BUF);
995
996		page = 0;
997		lba++;
998		sectors -= pages;
999	}
1000
1001	kfree(buffer);
1002	return result;
1003}
1004
1005/*
1006 * Write data to a specific sector address
1007 */
1008static int alauda_write_data(struct us_data *us, unsigned long address,
1009		unsigned int sectors)
1010{
1011	unsigned char *buffer, *blockbuffer;
1012	unsigned int page, len, offset;
1013	unsigned int blockshift = MEDIA_INFO(us).blockshift;
1014	unsigned int pageshift = MEDIA_INFO(us).pageshift;
1015	unsigned int blocksize = MEDIA_INFO(us).blocksize;
1016	unsigned int pagesize = MEDIA_INFO(us).pagesize;
1017	struct scatterlist *sg;
1018	u16 lba, max_lba;
1019	int result;
1020
1021	/*
1022	 * Since we don't write the user data directly to the device,
1023	 * we have to create a bounce buffer and move the data a piece
1024	 * at a time between the bounce buffer and the actual transfer buffer.
1025	 */
1026
1027	len = min(sectors, blocksize) * pagesize;
1028	buffer = kmalloc(len, GFP_NOIO);
1029	if (buffer == NULL) {
1030		printk(KERN_WARNING "alauda_write_data: Out of memory\n");
1031		return USB_STOR_TRANSPORT_ERROR;
1032	}
1033
1034	/*
1035	 * We also need a temporary block buffer, where we read in the old data,
1036	 * overwrite parts with the new data, and manipulate the redundancy data
1037	 */
1038	blockbuffer = kmalloc((pagesize + 64) * blocksize, GFP_NOIO);
1039	if (blockbuffer == NULL) {
1040		printk(KERN_WARNING "alauda_write_data: Out of memory\n");
1041		kfree(buffer);
1042		return USB_STOR_TRANSPORT_ERROR;
1043	}
1044
1045	/* Figure out the initial LBA and page */
1046	lba = address >> blockshift;
1047	page = (address & MEDIA_INFO(us).blockmask);
1048	max_lba = MEDIA_INFO(us).capacity >> (pageshift + blockshift);
1049
1050	result = USB_STOR_TRANSPORT_GOOD;
1051	offset = 0;
1052	sg = NULL;
1053
1054	while (sectors > 0) {
1055		/* Write as many sectors as possible in this block */
1056		unsigned int pages = min(sectors, blocksize - page);
1057		len = pages << pageshift;
1058
1059		/* Not overflowing capacity? */
1060		if (lba >= max_lba) {
1061			usb_stor_dbg(us, "Requested lba %u exceeds maximum %u\n",
1062				     lba, max_lba);
1063			result = USB_STOR_TRANSPORT_ERROR;
1064			break;
1065		}
1066
1067		/* Get the data from the transfer buffer */
1068		usb_stor_access_xfer_buf(buffer, len, us->srb,
1069				&sg, &offset, FROM_XFER_BUF);
1070
1071		result = alauda_write_lba(us, lba, page, pages, buffer,
1072			blockbuffer);
1073		if (result != USB_STOR_TRANSPORT_GOOD)
1074			break;
1075
1076		page = 0;
1077		lba++;
1078		sectors -= pages;
1079	}
1080
1081	kfree(buffer);
1082	kfree(blockbuffer);
1083	return result;
1084}
1085
1086/*
1087 * Our interface with the rest of the world
1088 */
1089
1090static void alauda_info_destructor(void *extra)
1091{
1092	struct alauda_info *info = (struct alauda_info *) extra;
1093	int port;
1094
1095	if (!info)
1096		return;
1097
1098	for (port = 0; port < 2; port++) {
1099		struct alauda_media_info *media_info = &info->port[port];
1100
1101		alauda_free_maps(media_info);
1102		kfree(media_info->lba_to_pba);
1103		kfree(media_info->pba_to_lba);
1104	}
1105}
1106
1107/*
1108 * Initialize alauda_info struct and find the data-write endpoint
1109 */
1110static int init_alauda(struct us_data *us)
1111{
1112	struct alauda_info *info;
1113	struct usb_host_interface *altsetting = us->pusb_intf->cur_altsetting;
1114	nand_init_ecc();
1115
1116	us->extra = kzalloc(sizeof(struct alauda_info), GFP_NOIO);
1117	if (!us->extra)
1118		return USB_STOR_TRANSPORT_ERROR;
1119
1120	info = (struct alauda_info *) us->extra;
1121	us->extra_destructor = alauda_info_destructor;
1122
1123	info->wr_ep = usb_sndbulkpipe(us->pusb_dev,
1124		altsetting->endpoint[0].desc.bEndpointAddress
1125		& USB_ENDPOINT_NUMBER_MASK);
1126
1127	return USB_STOR_TRANSPORT_GOOD;
1128}
1129
1130static int alauda_transport(struct scsi_cmnd *srb, struct us_data *us)
1131{
1132	int rc;
1133	struct alauda_info *info = (struct alauda_info *) us->extra;
1134	unsigned char *ptr = us->iobuf;
1135	static unsigned char inquiry_response[36] = {
1136		0x00, 0x80, 0x00, 0x01, 0x1F, 0x00, 0x00, 0x00
1137	};
1138
1139	if (srb->cmnd[0] == INQUIRY) {
1140		usb_stor_dbg(us, "INQUIRY - Returning bogus response\n");
1141		memcpy(ptr, inquiry_response, sizeof(inquiry_response));
1142		fill_inquiry_response(us, ptr, 36);
1143		return USB_STOR_TRANSPORT_GOOD;
1144	}
1145
1146	if (srb->cmnd[0] == TEST_UNIT_READY) {
1147		usb_stor_dbg(us, "TEST_UNIT_READY\n");
1148		return alauda_check_media(us);
1149	}
1150
1151	if (srb->cmnd[0] == READ_CAPACITY) {
1152		unsigned int num_zones;
1153		unsigned long capacity;
1154
1155		rc = alauda_check_media(us);
1156		if (rc != USB_STOR_TRANSPORT_GOOD)
1157			return rc;
1158
1159		num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift
1160			+ MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift);
1161
1162		capacity = num_zones * MEDIA_INFO(us).uzonesize
1163			* MEDIA_INFO(us).blocksize;
1164
1165		/* Report capacity and page size */
1166		((__be32 *) ptr)[0] = cpu_to_be32(capacity - 1);
1167		((__be32 *) ptr)[1] = cpu_to_be32(512);
1168
1169		usb_stor_set_xfer_buf(ptr, 8, srb);
1170		return USB_STOR_TRANSPORT_GOOD;
1171	}
1172
1173	if (srb->cmnd[0] == READ_10) {
1174		unsigned int page, pages;
1175
1176		rc = alauda_check_media(us);
1177		if (rc != USB_STOR_TRANSPORT_GOOD)
1178			return rc;
1179
1180		page = short_pack(srb->cmnd[3], srb->cmnd[2]);
1181		page <<= 16;
1182		page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
1183		pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
1184
1185		usb_stor_dbg(us, "READ_10: page %d pagect %d\n", page, pages);
1186
1187		return alauda_read_data(us, page, pages);
1188	}
1189
1190	if (srb->cmnd[0] == WRITE_10) {
1191		unsigned int page, pages;
1192
1193		rc = alauda_check_media(us);
1194		if (rc != USB_STOR_TRANSPORT_GOOD)
1195			return rc;
1196
1197		page = short_pack(srb->cmnd[3], srb->cmnd[2]);
1198		page <<= 16;
1199		page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
1200		pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
1201
1202		usb_stor_dbg(us, "WRITE_10: page %d pagect %d\n", page, pages);
1203
1204		return alauda_write_data(us, page, pages);
1205	}
1206
1207	if (srb->cmnd[0] == REQUEST_SENSE) {
1208		usb_stor_dbg(us, "REQUEST_SENSE\n");
1209
1210		memset(ptr, 0, 18);
1211		ptr[0] = 0xF0;
1212		ptr[2] = info->sense_key;
1213		ptr[7] = 11;
1214		ptr[12] = info->sense_asc;
1215		ptr[13] = info->sense_ascq;
1216		usb_stor_set_xfer_buf(ptr, 18, srb);
1217
1218		return USB_STOR_TRANSPORT_GOOD;
1219	}
1220
1221	if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) {
1222		/* sure.  whatever.  not like we can stop the user from popping
1223		   the media out of the device (no locking doors, etc) */
1224		return USB_STOR_TRANSPORT_GOOD;
1225	}
1226
1227	usb_stor_dbg(us, "Gah! Unknown command: %d (0x%x)\n",
1228		     srb->cmnd[0], srb->cmnd[0]);
1229	info->sense_key = 0x05;
1230	info->sense_asc = 0x20;
1231	info->sense_ascq = 0x00;
1232	return USB_STOR_TRANSPORT_FAILED;
1233}
1234
1235static int alauda_probe(struct usb_interface *intf,
1236			 const struct usb_device_id *id)
1237{
1238	struct us_data *us;
1239	int result;
1240
1241	result = usb_stor_probe1(&us, intf, id,
1242			(id - alauda_usb_ids) + alauda_unusual_dev_list);
1243	if (result)
1244		return result;
1245
1246	us->transport_name  = "Alauda Control/Bulk";
1247	us->transport = alauda_transport;
1248	us->transport_reset = usb_stor_Bulk_reset;
1249	us->max_lun = 1;
1250
1251	result = usb_stor_probe2(us);
1252	return result;
1253}
1254
1255static struct usb_driver alauda_driver = {
1256	.name =		"ums-alauda",
1257	.probe =	alauda_probe,
1258	.disconnect =	usb_stor_disconnect,
1259	.suspend =	usb_stor_suspend,
1260	.resume =	usb_stor_resume,
1261	.reset_resume =	usb_stor_reset_resume,
1262	.pre_reset =	usb_stor_pre_reset,
1263	.post_reset =	usb_stor_post_reset,
1264	.id_table =	alauda_usb_ids,
1265	.soft_unbind =	1,
1266	.no_dynamic_id = 1,
1267};
1268
1269module_usb_driver(alauda_driver);
1270