1/* Driver for USB Mass Storage compliant devices
2 * SCSI layer glue code
3 *
4 * Current development and maintenance by:
5 *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
6 *
7 * Developed with the assistance of:
8 *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
9 *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
10 *
11 * Initial work by:
12 *   (c) 1999 Michael Gee (michael@linuxspecific.com)
13 *
14 * This driver is based on the 'USB Mass Storage Class' document. This
15 * describes in detail the protocol used to communicate with such
16 * devices.  Clearly, the designers had SCSI and ATAPI commands in
17 * mind when they created this document.  The commands are all very
18 * similar to commands in the SCSI-II and ATAPI specifications.
19 *
20 * It is important to note that in a number of cases this class
21 * exhibits class-specific exemptions from the USB specification.
22 * Notably the usage of NAK, STALL and ACK differs from the norm, in
23 * that they are used to communicate wait, failed and OK on commands.
24 *
25 * Also, for certain devices, the interrupt endpoint is used to convey
26 * status of a command.
27 *
28 * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
29 * information about this driver.
30 *
31 * This program is free software; you can redistribute it and/or modify it
32 * under the terms of the GNU General Public License as published by the
33 * Free Software Foundation; either version 2, or (at your option) any
34 * later version.
35 *
36 * This program is distributed in the hope that it will be useful, but
37 * WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
39 * General Public License for more details.
40 *
41 * You should have received a copy of the GNU General Public License along
42 * with this program; if not, write to the Free Software Foundation, Inc.,
43 * 675 Mass Ave, Cambridge, MA 02139, USA.
44 */
45
46#include <linux/module.h>
47#include <linux/mutex.h>
48
49#include <scsi/scsi.h>
50#include <scsi/scsi_cmnd.h>
51#include <scsi/scsi_devinfo.h>
52#include <scsi/scsi_device.h>
53#include <scsi/scsi_eh.h>
54
55#include "usb.h"
56#include "scsiglue.h"
57#include "debug.h"
58#include "transport.h"
59#include "protocol.h"
60
61/* Vendor IDs for companies that seem to include the READ CAPACITY bug
62 * in all their devices
63 */
64#define VENDOR_ID_NOKIA		0x0421
65#define VENDOR_ID_NIKON		0x04b0
66#define VENDOR_ID_PENTAX	0x0a17
67#define VENDOR_ID_MOTOROLA	0x22b8
68
69/***********************************************************************
70 * Host functions
71 ***********************************************************************/
72
73static const char* host_info(struct Scsi_Host *host)
74{
75	struct us_data *us = host_to_us(host);
76	return us->scsi_name;
77}
78
79static int slave_alloc (struct scsi_device *sdev)
80{
81	struct us_data *us = host_to_us(sdev->host);
82
83	/*
84	 * Set the INQUIRY transfer length to 36.  We don't use any of
85	 * the extra data and many devices choke if asked for more or
86	 * less than 36 bytes.
87	 */
88	sdev->inquiry_len = 36;
89
90	/* USB has unusual DMA-alignment requirements: Although the
91	 * starting address of each scatter-gather element doesn't matter,
92	 * the length of each element except the last must be divisible
93	 * by the Bulk maxpacket value.  There's currently no way to
94	 * express this by block-layer constraints, so we'll cop out
95	 * and simply require addresses to be aligned at 512-byte
96	 * boundaries.  This is okay since most block I/O involves
97	 * hardware sectors that are multiples of 512 bytes in length,
98	 * and since host controllers up through USB 2.0 have maxpacket
99	 * values no larger than 512.
100	 *
101	 * But it doesn't suffice for Wireless USB, where Bulk maxpacket
102	 * values can be as large as 2048.  To make that work properly
103	 * will require changes to the block layer.
104	 */
105	blk_queue_update_dma_alignment(sdev->request_queue, (512 - 1));
106
107	/* Tell the SCSI layer if we know there is more than one LUN */
108	if (us->protocol == USB_PR_BULK && us->max_lun > 0)
109		sdev->sdev_bflags |= BLIST_FORCELUN;
110
111	return 0;
112}
113
114static int slave_configure(struct scsi_device *sdev)
115{
116	struct us_data *us = host_to_us(sdev->host);
117
118	/* Many devices have trouble transferring more than 32KB at a time,
119	 * while others have trouble with more than 64K. At this time we
120	 * are limiting both to 32K (64 sectores).
121	 */
122	if (us->fflags & (US_FL_MAX_SECTORS_64 | US_FL_MAX_SECTORS_MIN)) {
123		unsigned int max_sectors = 64;
124
125		if (us->fflags & US_FL_MAX_SECTORS_MIN)
126			max_sectors = PAGE_CACHE_SIZE >> 9;
127		if (queue_max_hw_sectors(sdev->request_queue) > max_sectors)
128			blk_queue_max_hw_sectors(sdev->request_queue,
129					      max_sectors);
130	} else if (sdev->type == TYPE_TAPE) {
131		/* Tapes need much higher max_sector limits, so just
132		 * raise it to the maximum possible (4 GB / 512) and
133		 * let the queue segment size sort out the real limit.
134		 */
135		blk_queue_max_hw_sectors(sdev->request_queue, 0x7FFFFF);
136	}
137
138	/* Some USB host controllers can't do DMA; they have to use PIO.
139	 * They indicate this by setting their dma_mask to NULL.  For
140	 * such controllers we need to make sure the block layer sets
141	 * up bounce buffers in addressable memory.
142	 */
143	if (!us->pusb_dev->bus->controller->dma_mask)
144		blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_HIGH);
145
146	/* We can't put these settings in slave_alloc() because that gets
147	 * called before the device type is known.  Consequently these
148	 * settings can't be overridden via the scsi devinfo mechanism. */
149	if (sdev->type == TYPE_DISK) {
150
151		/* Some vendors seem to put the READ CAPACITY bug into
152		 * all their devices -- primarily makers of cell phones
153		 * and digital cameras.  Since these devices always use
154		 * flash media and can be expected to have an even number
155		 * of sectors, we will always enable the CAPACITY_HEURISTICS
156		 * flag unless told otherwise. */
157		switch (le16_to_cpu(us->pusb_dev->descriptor.idVendor)) {
158		case VENDOR_ID_NOKIA:
159		case VENDOR_ID_NIKON:
160		case VENDOR_ID_PENTAX:
161		case VENDOR_ID_MOTOROLA:
162			if (!(us->fflags & (US_FL_FIX_CAPACITY |
163					US_FL_CAPACITY_OK)))
164				us->fflags |= US_FL_CAPACITY_HEURISTICS;
165			break;
166		}
167
168		/* Disk-type devices use MODE SENSE(6) if the protocol
169		 * (SubClass) is Transparent SCSI, otherwise they use
170		 * MODE SENSE(10). */
171		if (us->subclass != USB_SC_SCSI && us->subclass != USB_SC_CYP_ATACB)
172			sdev->use_10_for_ms = 1;
173
174		/* Many disks only accept MODE SENSE transfer lengths of
175		 * 192 bytes (that's what Windows uses). */
176		sdev->use_192_bytes_for_3f = 1;
177
178		/* Some devices don't like MODE SENSE with page=0x3f,
179		 * which is the command used for checking if a device
180		 * is write-protected.  Now that we tell the sd driver
181		 * to do a 192-byte transfer with this command the
182		 * majority of devices work fine, but a few still can't
183		 * handle it.  The sd driver will simply assume those
184		 * devices are write-enabled. */
185		if (us->fflags & US_FL_NO_WP_DETECT)
186			sdev->skip_ms_page_3f = 1;
187
188		/* A number of devices have problems with MODE SENSE for
189		 * page x08, so we will skip it. */
190		sdev->skip_ms_page_8 = 1;
191
192		/* Some devices don't handle VPD pages correctly */
193		sdev->skip_vpd_pages = 1;
194
195		/* Do not attempt to use REPORT SUPPORTED OPERATION CODES */
196		sdev->no_report_opcodes = 1;
197
198		/* Do not attempt to use WRITE SAME */
199		sdev->no_write_same = 1;
200
201		/* Some disks return the total number of blocks in response
202		 * to READ CAPACITY rather than the highest block number.
203		 * If this device makes that mistake, tell the sd driver. */
204		if (us->fflags & US_FL_FIX_CAPACITY)
205			sdev->fix_capacity = 1;
206
207		/* A few disks have two indistinguishable version, one of
208		 * which reports the correct capacity and the other does not.
209		 * The sd driver has to guess which is the case. */
210		if (us->fflags & US_FL_CAPACITY_HEURISTICS)
211			sdev->guess_capacity = 1;
212
213		/* Some devices cannot handle READ_CAPACITY_16 */
214		if (us->fflags & US_FL_NO_READ_CAPACITY_16)
215			sdev->no_read_capacity_16 = 1;
216
217		/*
218		 * Many devices do not respond properly to READ_CAPACITY_16.
219		 * Tell the SCSI layer to try READ_CAPACITY_10 first.
220		 * However some USB 3.0 drive enclosures return capacity
221		 * modulo 2TB. Those must use READ_CAPACITY_16
222		 */
223		if (!(us->fflags & US_FL_NEEDS_CAP16))
224			sdev->try_rc_10_first = 1;
225
226		/* assume SPC3 or latter devices support sense size > 18 */
227		if (sdev->scsi_level > SCSI_SPC_2)
228			us->fflags |= US_FL_SANE_SENSE;
229
230		/* USB-IDE bridges tend to report SK = 0x04 (Non-recoverable
231		 * Hardware Error) when any low-level error occurs,
232		 * recoverable or not.  Setting this flag tells the SCSI
233		 * midlayer to retry such commands, which frequently will
234		 * succeed and fix the error.  The worst this can lead to
235		 * is an occasional series of retries that will all fail. */
236		sdev->retry_hwerror = 1;
237
238		/* USB disks should allow restart.  Some drives spin down
239		 * automatically, requiring a START-STOP UNIT command. */
240		sdev->allow_restart = 1;
241
242		/* Some USB cardreaders have trouble reading an sdcard's last
243		 * sector in a larger then 1 sector read, since the performance
244		 * impact is negligible we set this flag for all USB disks */
245		sdev->last_sector_bug = 1;
246
247		/* Enable last-sector hacks for single-target devices using
248		 * the Bulk-only transport, unless we already know the
249		 * capacity will be decremented or is correct. */
250		if (!(us->fflags & (US_FL_FIX_CAPACITY | US_FL_CAPACITY_OK |
251					US_FL_SCM_MULT_TARG)) &&
252				us->protocol == USB_PR_BULK)
253			us->use_last_sector_hacks = 1;
254
255		/* Check if write cache default on flag is set or not */
256		if (us->fflags & US_FL_WRITE_CACHE)
257			sdev->wce_default_on = 1;
258
259		/* A few buggy USB-ATA bridges don't understand FUA */
260		if (us->fflags & US_FL_BROKEN_FUA)
261			sdev->broken_fua = 1;
262
263	} else {
264
265		/* Non-disk-type devices don't need to blacklist any pages
266		 * or to force 192-byte transfer lengths for MODE SENSE.
267		 * But they do need to use MODE SENSE(10). */
268		sdev->use_10_for_ms = 1;
269
270		/* Some (fake) usb cdrom devices don't like READ_DISC_INFO */
271		if (us->fflags & US_FL_NO_READ_DISC_INFO)
272			sdev->no_read_disc_info = 1;
273	}
274
275	/* The CB and CBI transports have no way to pass LUN values
276	 * other than the bits in the second byte of a CDB.  But those
277	 * bits don't get set to the LUN value if the device reports
278	 * scsi_level == 0 (UNKNOWN).  Hence such devices must necessarily
279	 * be single-LUN.
280	 */
281	if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_CBI) &&
282			sdev->scsi_level == SCSI_UNKNOWN)
283		us->max_lun = 0;
284
285	/* Some devices choke when they receive a PREVENT-ALLOW MEDIUM
286	 * REMOVAL command, so suppress those commands. */
287	if (us->fflags & US_FL_NOT_LOCKABLE)
288		sdev->lockable = 0;
289
290	/* this is to satisfy the compiler, tho I don't think the
291	 * return code is ever checked anywhere. */
292	return 0;
293}
294
295static int target_alloc(struct scsi_target *starget)
296{
297	struct us_data *us = host_to_us(dev_to_shost(starget->dev.parent));
298
299	/*
300	 * Some USB drives don't support REPORT LUNS, even though they
301	 * report a SCSI revision level above 2.  Tell the SCSI layer
302	 * not to issue that command; it will perform a normal sequential
303	 * scan instead.
304	 */
305	starget->no_report_luns = 1;
306
307	/*
308	 * The UFI spec treats the Peripheral Qualifier bits in an
309	 * INQUIRY result as reserved and requires devices to set them
310	 * to 0.  However the SCSI spec requires these bits to be set
311	 * to 3 to indicate when a LUN is not present.
312	 *
313	 * Let the scanning code know if this target merely sets
314	 * Peripheral Device Type to 0x1f to indicate no LUN.
315	 */
316	if (us->subclass == USB_SC_UFI)
317		starget->pdt_1f_for_no_lun = 1;
318
319	return 0;
320}
321
322/* queue a command */
323/* This is always called with scsi_lock(host) held */
324static int queuecommand_lck(struct scsi_cmnd *srb,
325			void (*done)(struct scsi_cmnd *))
326{
327	struct us_data *us = host_to_us(srb->device->host);
328
329	/* check for state-transition errors */
330	if (us->srb != NULL) {
331		printk(KERN_ERR USB_STORAGE "Error in %s: us->srb = %p\n",
332			__func__, us->srb);
333		return SCSI_MLQUEUE_HOST_BUSY;
334	}
335
336	/* fail the command if we are disconnecting */
337	if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
338		usb_stor_dbg(us, "Fail command during disconnect\n");
339		srb->result = DID_NO_CONNECT << 16;
340		done(srb);
341		return 0;
342	}
343
344	/* enqueue the command and wake up the control thread */
345	srb->scsi_done = done;
346	us->srb = srb;
347	complete(&us->cmnd_ready);
348
349	return 0;
350}
351
352static DEF_SCSI_QCMD(queuecommand)
353
354/***********************************************************************
355 * Error handling functions
356 ***********************************************************************/
357
358/* Command timeout and abort */
359static int command_abort(struct scsi_cmnd *srb)
360{
361	struct us_data *us = host_to_us(srb->device->host);
362
363	usb_stor_dbg(us, "%s called\n", __func__);
364
365	/* us->srb together with the TIMED_OUT, RESETTING, and ABORTING
366	 * bits are protected by the host lock. */
367	scsi_lock(us_to_host(us));
368
369	/* Is this command still active? */
370	if (us->srb != srb) {
371		scsi_unlock(us_to_host(us));
372		usb_stor_dbg(us, "-- nothing to abort\n");
373		return FAILED;
374	}
375
376	/* Set the TIMED_OUT bit.  Also set the ABORTING bit, but only if
377	 * a device reset isn't already in progress (to avoid interfering
378	 * with the reset).  Note that we must retain the host lock while
379	 * calling usb_stor_stop_transport(); otherwise it might interfere
380	 * with an auto-reset that begins as soon as we release the lock. */
381	set_bit(US_FLIDX_TIMED_OUT, &us->dflags);
382	if (!test_bit(US_FLIDX_RESETTING, &us->dflags)) {
383		set_bit(US_FLIDX_ABORTING, &us->dflags);
384		usb_stor_stop_transport(us);
385	}
386	scsi_unlock(us_to_host(us));
387
388	/* Wait for the aborted command to finish */
389	wait_for_completion(&us->notify);
390	return SUCCESS;
391}
392
393/* This invokes the transport reset mechanism to reset the state of the
394 * device */
395static int device_reset(struct scsi_cmnd *srb)
396{
397	struct us_data *us = host_to_us(srb->device->host);
398	int result;
399
400	usb_stor_dbg(us, "%s called\n", __func__);
401
402	/* lock the device pointers and do the reset */
403	mutex_lock(&(us->dev_mutex));
404	result = us->transport_reset(us);
405	mutex_unlock(&us->dev_mutex);
406
407	return result < 0 ? FAILED : SUCCESS;
408}
409
410/* Simulate a SCSI bus reset by resetting the device's USB port. */
411static int bus_reset(struct scsi_cmnd *srb)
412{
413	struct us_data *us = host_to_us(srb->device->host);
414	int result;
415
416	usb_stor_dbg(us, "%s called\n", __func__);
417
418	result = usb_stor_port_reset(us);
419	return result < 0 ? FAILED : SUCCESS;
420}
421
422/* Report a driver-initiated device reset to the SCSI layer.
423 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
424 * The caller must own the SCSI host lock. */
425void usb_stor_report_device_reset(struct us_data *us)
426{
427	int i;
428	struct Scsi_Host *host = us_to_host(us);
429
430	scsi_report_device_reset(host, 0, 0);
431	if (us->fflags & US_FL_SCM_MULT_TARG) {
432		for (i = 1; i < host->max_id; ++i)
433			scsi_report_device_reset(host, 0, i);
434	}
435}
436
437/* Report a driver-initiated bus reset to the SCSI layer.
438 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
439 * The caller must not own the SCSI host lock. */
440void usb_stor_report_bus_reset(struct us_data *us)
441{
442	struct Scsi_Host *host = us_to_host(us);
443
444	scsi_lock(host);
445	scsi_report_bus_reset(host, 0);
446	scsi_unlock(host);
447}
448
449/***********************************************************************
450 * /proc/scsi/ functions
451 ***********************************************************************/
452
453static int write_info(struct Scsi_Host *host, char *buffer, int length)
454{
455	/* if someone is sending us data, just throw it away */
456	return length;
457}
458
459/* we use this macro to help us write into the buffer */
460#undef SPRINTF
461#define SPRINTF(args...) seq_printf(m, ## args)
462
463static int show_info (struct seq_file *m, struct Scsi_Host *host)
464{
465	struct us_data *us = host_to_us(host);
466	const char *string;
467
468	/* print the controller name */
469	SPRINTF("   Host scsi%d: usb-storage\n", host->host_no);
470
471	/* print product, vendor, and serial number strings */
472	if (us->pusb_dev->manufacturer)
473		string = us->pusb_dev->manufacturer;
474	else if (us->unusual_dev->vendorName)
475		string = us->unusual_dev->vendorName;
476	else
477		string = "Unknown";
478	SPRINTF("       Vendor: %s\n", string);
479	if (us->pusb_dev->product)
480		string = us->pusb_dev->product;
481	else if (us->unusual_dev->productName)
482		string = us->unusual_dev->productName;
483	else
484		string = "Unknown";
485	SPRINTF("      Product: %s\n", string);
486	if (us->pusb_dev->serial)
487		string = us->pusb_dev->serial;
488	else
489		string = "None";
490	SPRINTF("Serial Number: %s\n", string);
491
492	/* show the protocol and transport */
493	SPRINTF("     Protocol: %s\n", us->protocol_name);
494	SPRINTF("    Transport: %s\n", us->transport_name);
495
496	/* show the device flags */
497	SPRINTF("       Quirks:");
498
499#define US_FLAG(name, value) \
500	if (us->fflags & value) seq_printf(m, " " #name);
501US_DO_ALL_FLAGS
502#undef US_FLAG
503	seq_putc(m, '\n');
504	return 0;
505}
506
507/***********************************************************************
508 * Sysfs interface
509 ***********************************************************************/
510
511/* Output routine for the sysfs max_sectors file */
512static ssize_t max_sectors_show(struct device *dev, struct device_attribute *attr, char *buf)
513{
514	struct scsi_device *sdev = to_scsi_device(dev);
515
516	return sprintf(buf, "%u\n", queue_max_hw_sectors(sdev->request_queue));
517}
518
519/* Input routine for the sysfs max_sectors file */
520static ssize_t max_sectors_store(struct device *dev, struct device_attribute *attr, const char *buf,
521		size_t count)
522{
523	struct scsi_device *sdev = to_scsi_device(dev);
524	unsigned short ms;
525
526	if (sscanf(buf, "%hu", &ms) > 0) {
527		blk_queue_max_hw_sectors(sdev->request_queue, ms);
528		return count;
529	}
530	return -EINVAL;
531}
532static DEVICE_ATTR_RW(max_sectors);
533
534static struct device_attribute *sysfs_device_attr_list[] = {
535	&dev_attr_max_sectors,
536	NULL,
537};
538
539/*
540 * this defines our host template, with which we'll allocate hosts
541 */
542
543struct scsi_host_template usb_stor_host_template = {
544	/* basic userland interface stuff */
545	.name =				"usb-storage",
546	.proc_name =			"usb-storage",
547	.show_info =			show_info,
548	.write_info =			write_info,
549	.info =				host_info,
550
551	/* command interface -- queued only */
552	.queuecommand =			queuecommand,
553
554	/* error and abort handlers */
555	.eh_abort_handler =		command_abort,
556	.eh_device_reset_handler =	device_reset,
557	.eh_bus_reset_handler =		bus_reset,
558
559	/* queue commands only, only one command per LUN */
560	.can_queue =			1,
561	.cmd_per_lun =			1,
562
563	/* unknown initiator id */
564	.this_id =			-1,
565
566	.slave_alloc =			slave_alloc,
567	.slave_configure =		slave_configure,
568	.target_alloc =			target_alloc,
569
570	/* lots of sg segments can be handled */
571	.sg_tablesize =			SCSI_MAX_SG_CHAIN_SEGMENTS,
572
573	/* limit the total size of a transfer to 120 KB */
574	.max_sectors =                  240,
575
576	/* merge commands... this seems to help performance, but
577	 * periodically someone should test to see which setting is more
578	 * optimal.
579	 */
580	.use_clustering =		1,
581
582	/* emulated HBA */
583	.emulated =			1,
584
585	/* we do our own delay after a device or bus reset */
586	.skip_settle_delay =		1,
587
588	/* sysfs device attributes */
589	.sdev_attrs =			sysfs_device_attr_list,
590
591	/* module management */
592	.module =			THIS_MODULE
593};
594
595/* To Report "Illegal Request: Invalid Field in CDB */
596unsigned char usb_stor_sense_invalidCDB[18] = {
597	[0]	= 0x70,			    /* current error */
598	[2]	= ILLEGAL_REQUEST,	    /* Illegal Request = 0x05 */
599	[7]	= 0x0a,			    /* additional length */
600	[12]	= 0x24			    /* Invalid Field in CDB */
601};
602EXPORT_SYMBOL_GPL(usb_stor_sense_invalidCDB);
603