1 // SPDX-License-Identifier: GPL-2.0+
3 * Driver for USB Mass Storage compliant devices
6 * Current development and maintenance by:
9 * Developed with the assistance of:
16 * This driver is based on the 'USB Mass Storage Class' document. This
17 * describes in detail the protocol used to communicate with such
18 * devices. Clearly, the designers had SCSI and ATAPI commands in
19 * mind when they created this document. The commands are all very
20 * similar to commands in the SCSI-II and ATAPI specifications.
22 * It is important to note that in a number of cases this class
23 * exhibits class-specific exemptions from the USB specification.
24 * Notably the usage of NAK, STALL and ACK differs from the norm, in
25 * that they are used to communicate wait, failed and OK on commands.
27 * Also, for certain devices, the interrupt endpoint is used to convey
28 * status of a command.
30 * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
31 * information about this driver.
34 #include <linux/module.h>
35 #include <linux/mutex.h>
37 #include <scsi/scsi.h>
38 #include <scsi/scsi_cmnd.h>
39 #include <scsi/scsi_devinfo.h>
40 #include <scsi/scsi_device.h>
41 #include <scsi/scsi_eh.h>
46 #include "transport.h"
50 * Vendor IDs for companies that seem to include the READ CAPACITY bug
51 * in all their devices
53 #define VENDOR_ID_NOKIA 0x0421
54 #define VENDOR_ID_NIKON 0x04b0
55 #define VENDOR_ID_PENTAX 0x0a17
56 #define VENDOR_ID_MOTOROLA 0x22b8
58 /***********************************************************************
60 ***********************************************************************/
62 static const char* host_info(struct Scsi_Host *host)
64 struct us_data *us = host_to_us(host);
68 static int slave_alloc (struct scsi_device *sdev)
70 struct us_data *us = host_to_us(sdev->host);
73 * Set the INQUIRY transfer length to 36. We don't use any of
74 * the extra data and many devices choke if asked for more or
77 sdev->inquiry_len = 36;
80 * USB has unusual DMA-alignment requirements: Although the
81 * starting address of each scatter-gather element doesn't matter,
82 * the length of each element except the last must be divisible
83 * by the Bulk maxpacket value. There's currently no way to
84 * express this by block-layer constraints, so we'll cop out
85 * and simply require addresses to be aligned at 512-byte
86 * boundaries. This is okay since most block I/O involves
87 * hardware sectors that are multiples of 512 bytes in length,
88 * and since host controllers up through USB 2.0 have maxpacket
89 * values no larger than 512.
91 * But it doesn't suffice for Wireless USB, where Bulk maxpacket
92 * values can be as large as 2048. To make that work properly
93 * will require changes to the block layer.
95 blk_queue_update_dma_alignment(sdev->request_queue, (512 - 1));
97 /* Tell the SCSI layer if we know there is more than one LUN */
98 if (us->protocol == USB_PR_BULK && us->max_lun > 0)
99 sdev->sdev_bflags |= BLIST_FORCELUN;
104 static int slave_configure(struct scsi_device *sdev)
106 struct us_data *us = host_to_us(sdev->host);
109 * Many devices have trouble transferring more than 32KB at a time,
110 * while others have trouble with more than 64K. At this time we
111 * are limiting both to 32K (64 sectores).
113 if (us->fflags & (US_FL_MAX_SECTORS_64 | US_FL_MAX_SECTORS_MIN)) {
114 unsigned int max_sectors = 64;
116 if (us->fflags & US_FL_MAX_SECTORS_MIN)
117 max_sectors = PAGE_SIZE >> 9;
118 if (queue_max_hw_sectors(sdev->request_queue) > max_sectors)
119 blk_queue_max_hw_sectors(sdev->request_queue,
121 } else if (sdev->type == TYPE_TAPE) {
123 * Tapes need much higher max_sector limits, so just
124 * raise it to the maximum possible (4 GB / 512) and
125 * let the queue segment size sort out the real limit.
127 blk_queue_max_hw_sectors(sdev->request_queue, 0x7FFFFF);
128 } else if (us->pusb_dev->speed >= USB_SPEED_SUPER) {
130 * USB3 devices will be limited to 2048 sectors. This gives us
131 * better throughput on most devices.
133 blk_queue_max_hw_sectors(sdev->request_queue, 2048);
137 * Some USB host controllers can't do DMA; they have to use PIO.
138 * They indicate this by setting their dma_mask to NULL. For
139 * such controllers we need to make sure the block layer sets
140 * up bounce buffers in addressable memory.
142 if (!us->pusb_dev->bus->controller->dma_mask)
143 blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_HIGH);
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.
150 if (sdev->type == TYPE_DISK) {
153 * Some vendors seem to put the READ CAPACITY bug into
154 * all their devices -- primarily makers of cell phones
155 * and digital cameras. Since these devices always use
156 * flash media and can be expected to have an even number
157 * of sectors, we will always enable the CAPACITY_HEURISTICS
158 * flag unless told otherwise.
160 switch (le16_to_cpu(us->pusb_dev->descriptor.idVendor)) {
161 case VENDOR_ID_NOKIA:
162 case VENDOR_ID_NIKON:
163 case VENDOR_ID_PENTAX:
164 case VENDOR_ID_MOTOROLA:
165 if (!(us->fflags & (US_FL_FIX_CAPACITY |
167 us->fflags |= US_FL_CAPACITY_HEURISTICS;
172 * Disk-type devices use MODE SENSE(6) if the protocol
173 * (SubClass) is Transparent SCSI, otherwise they use
176 if (us->subclass != USB_SC_SCSI && us->subclass != USB_SC_CYP_ATACB)
177 sdev->use_10_for_ms = 1;
180 *Many disks only accept MODE SENSE transfer lengths of
181 * 192 bytes (that's what Windows uses).
183 sdev->use_192_bytes_for_3f = 1;
186 * Some devices don't like MODE SENSE with page=0x3f,
187 * which is the command used for checking if a device
188 * is write-protected. Now that we tell the sd driver
189 * to do a 192-byte transfer with this command the
190 * majority of devices work fine, but a few still can't
191 * handle it. The sd driver will simply assume those
192 * devices are write-enabled.
194 if (us->fflags & US_FL_NO_WP_DETECT)
195 sdev->skip_ms_page_3f = 1;
198 * A number of devices have problems with MODE SENSE for
199 * page x08, so we will skip it.
201 sdev->skip_ms_page_8 = 1;
203 /* Some devices don't handle VPD pages correctly */
204 sdev->skip_vpd_pages = 1;
206 /* Do not attempt to use REPORT SUPPORTED OPERATION CODES */
207 sdev->no_report_opcodes = 1;
209 /* Do not attempt to use WRITE SAME */
210 sdev->no_write_same = 1;
213 * Some disks return the total number of blocks in response
214 * to READ CAPACITY rather than the highest block number.
215 * If this device makes that mistake, tell the sd driver.
217 if (us->fflags & US_FL_FIX_CAPACITY)
218 sdev->fix_capacity = 1;
221 * A few disks have two indistinguishable version, one of
222 * which reports the correct capacity and the other does not.
223 * The sd driver has to guess which is the case.
225 if (us->fflags & US_FL_CAPACITY_HEURISTICS)
226 sdev->guess_capacity = 1;
228 /* Some devices cannot handle READ_CAPACITY_16 */
229 if (us->fflags & US_FL_NO_READ_CAPACITY_16)
230 sdev->no_read_capacity_16 = 1;
233 * Many devices do not respond properly to READ_CAPACITY_16.
234 * Tell the SCSI layer to try READ_CAPACITY_10 first.
235 * However some USB 3.0 drive enclosures return capacity
236 * modulo 2TB. Those must use READ_CAPACITY_16
238 if (!(us->fflags & US_FL_NEEDS_CAP16))
239 sdev->try_rc_10_first = 1;
241 /* assume SPC3 or latter devices support sense size > 18 */
242 if (sdev->scsi_level > SCSI_SPC_2)
243 us->fflags |= US_FL_SANE_SENSE;
246 * USB-IDE bridges tend to report SK = 0x04 (Non-recoverable
247 * Hardware Error) when any low-level error occurs,
248 * recoverable or not. Setting this flag tells the SCSI
249 * midlayer to retry such commands, which frequently will
250 * succeed and fix the error. The worst this can lead to
251 * is an occasional series of retries that will all fail.
253 sdev->retry_hwerror = 1;
256 * USB disks should allow restart. Some drives spin down
257 * automatically, requiring a START-STOP UNIT command.
259 sdev->allow_restart = 1;
262 * Some USB cardreaders have trouble reading an sdcard's last
263 * sector in a larger then 1 sector read, since the performance
264 * impact is negligible we set this flag for all USB disks
266 sdev->last_sector_bug = 1;
269 * Enable last-sector hacks for single-target devices using
270 * the Bulk-only transport, unless we already know the
271 * capacity will be decremented or is correct.
273 if (!(us->fflags & (US_FL_FIX_CAPACITY | US_FL_CAPACITY_OK |
274 US_FL_SCM_MULT_TARG)) &&
275 us->protocol == USB_PR_BULK)
276 us->use_last_sector_hacks = 1;
278 /* Check if write cache default on flag is set or not */
279 if (us->fflags & US_FL_WRITE_CACHE)
280 sdev->wce_default_on = 1;
282 /* A few buggy USB-ATA bridges don't understand FUA */
283 if (us->fflags & US_FL_BROKEN_FUA)
284 sdev->broken_fua = 1;
286 /* Some even totally fail to indicate a cache */
287 if (us->fflags & US_FL_ALWAYS_SYNC) {
288 /* don't read caching information */
289 sdev->skip_ms_page_8 = 1;
290 sdev->skip_ms_page_3f = 1;
291 /* assume sync is needed */
292 sdev->wce_default_on = 1;
297 * Non-disk-type devices don't need to blacklist any pages
298 * or to force 192-byte transfer lengths for MODE SENSE.
299 * But they do need to use MODE SENSE(10).
301 sdev->use_10_for_ms = 1;
303 /* Some (fake) usb cdrom devices don't like READ_DISC_INFO */
304 if (us->fflags & US_FL_NO_READ_DISC_INFO)
305 sdev->no_read_disc_info = 1;
309 * The CB and CBI transports have no way to pass LUN values
310 * other than the bits in the second byte of a CDB. But those
311 * bits don't get set to the LUN value if the device reports
312 * scsi_level == 0 (UNKNOWN). Hence such devices must necessarily
315 if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_CBI) &&
316 sdev->scsi_level == SCSI_UNKNOWN)
320 * Some devices choke when they receive a PREVENT-ALLOW MEDIUM
321 * REMOVAL command, so suppress those commands.
323 if (us->fflags & US_FL_NOT_LOCKABLE)
327 * this is to satisfy the compiler, tho I don't think the
328 * return code is ever checked anywhere.
333 static int target_alloc(struct scsi_target *starget)
335 struct us_data *us = host_to_us(dev_to_shost(starget->dev.parent));
338 * Some USB drives don't support REPORT LUNS, even though they
339 * report a SCSI revision level above 2. Tell the SCSI layer
340 * not to issue that command; it will perform a normal sequential
343 starget->no_report_luns = 1;
346 * The UFI spec treats the Peripheral Qualifier bits in an
347 * INQUIRY result as reserved and requires devices to set them
348 * to 0. However the SCSI spec requires these bits to be set
349 * to 3 to indicate when a LUN is not present.
351 * Let the scanning code know if this target merely sets
352 * Peripheral Device Type to 0x1f to indicate no LUN.
354 if (us->subclass == USB_SC_UFI)
355 starget->pdt_1f_for_no_lun = 1;
360 /* queue a command */
361 /* This is always called with scsi_lock(host) held */
362 static int queuecommand_lck(struct scsi_cmnd *srb,
363 void (*done)(struct scsi_cmnd *))
365 struct us_data *us = host_to_us(srb->device->host);
367 /* check for state-transition errors */
368 if (us->srb != NULL) {
369 printk(KERN_ERR USB_STORAGE "Error in %s: us->srb = %p\n",
371 return SCSI_MLQUEUE_HOST_BUSY;
374 /* fail the command if we are disconnecting */
375 if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
376 usb_stor_dbg(us, "Fail command during disconnect\n");
377 srb->result = DID_NO_CONNECT << 16;
382 /* enqueue the command and wake up the control thread */
383 srb->scsi_done = done;
385 complete(&us->cmnd_ready);
390 static DEF_SCSI_QCMD(queuecommand)
392 /***********************************************************************
393 * Error handling functions
394 ***********************************************************************/
396 /* Command timeout and abort */
397 static int command_abort(struct scsi_cmnd *srb)
399 struct us_data *us = host_to_us(srb->device->host);
401 usb_stor_dbg(us, "%s called\n", __func__);
404 * us->srb together with the TIMED_OUT, RESETTING, and ABORTING
405 * bits are protected by the host lock.
407 scsi_lock(us_to_host(us));
409 /* Is this command still active? */
410 if (us->srb != srb) {
411 scsi_unlock(us_to_host(us));
412 usb_stor_dbg(us, "-- nothing to abort\n");
417 * Set the TIMED_OUT bit. Also set the ABORTING bit, but only if
418 * a device reset isn't already in progress (to avoid interfering
419 * with the reset). Note that we must retain the host lock while
420 * calling usb_stor_stop_transport(); otherwise it might interfere
421 * with an auto-reset that begins as soon as we release the lock.
423 set_bit(US_FLIDX_TIMED_OUT, &us->dflags);
424 if (!test_bit(US_FLIDX_RESETTING, &us->dflags)) {
425 set_bit(US_FLIDX_ABORTING, &us->dflags);
426 usb_stor_stop_transport(us);
428 scsi_unlock(us_to_host(us));
430 /* Wait for the aborted command to finish */
431 wait_for_completion(&us->notify);
436 * This invokes the transport reset mechanism to reset the state of the
439 static int device_reset(struct scsi_cmnd *srb)
441 struct us_data *us = host_to_us(srb->device->host);
444 usb_stor_dbg(us, "%s called\n", __func__);
446 /* lock the device pointers and do the reset */
447 mutex_lock(&(us->dev_mutex));
448 result = us->transport_reset(us);
449 mutex_unlock(&us->dev_mutex);
451 return result < 0 ? FAILED : SUCCESS;
454 /* Simulate a SCSI bus reset by resetting the device's USB port. */
455 static int bus_reset(struct scsi_cmnd *srb)
457 struct us_data *us = host_to_us(srb->device->host);
460 usb_stor_dbg(us, "%s called\n", __func__);
462 result = usb_stor_port_reset(us);
463 return result < 0 ? FAILED : SUCCESS;
467 * Report a driver-initiated device reset to the SCSI layer.
468 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
469 * The caller must own the SCSI host lock.
471 void usb_stor_report_device_reset(struct us_data *us)
474 struct Scsi_Host *host = us_to_host(us);
476 scsi_report_device_reset(host, 0, 0);
477 if (us->fflags & US_FL_SCM_MULT_TARG) {
478 for (i = 1; i < host->max_id; ++i)
479 scsi_report_device_reset(host, 0, i);
484 * Report a driver-initiated bus reset to the SCSI layer.
485 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
486 * The caller must not own the SCSI host lock.
488 void usb_stor_report_bus_reset(struct us_data *us)
490 struct Scsi_Host *host = us_to_host(us);
493 scsi_report_bus_reset(host, 0);
497 /***********************************************************************
498 * /proc/scsi/ functions
499 ***********************************************************************/
501 static int write_info(struct Scsi_Host *host, char *buffer, int length)
503 /* if someone is sending us data, just throw it away */
507 static int show_info (struct seq_file *m, struct Scsi_Host *host)
509 struct us_data *us = host_to_us(host);
512 /* print the controller name */
513 seq_printf(m, " Host scsi%d: usb-storage\n", host->host_no);
515 /* print product, vendor, and serial number strings */
516 if (us->pusb_dev->manufacturer)
517 string = us->pusb_dev->manufacturer;
518 else if (us->unusual_dev->vendorName)
519 string = us->unusual_dev->vendorName;
522 seq_printf(m, " Vendor: %s\n", string);
523 if (us->pusb_dev->product)
524 string = us->pusb_dev->product;
525 else if (us->unusual_dev->productName)
526 string = us->unusual_dev->productName;
529 seq_printf(m, " Product: %s\n", string);
530 if (us->pusb_dev->serial)
531 string = us->pusb_dev->serial;
534 seq_printf(m, "Serial Number: %s\n", string);
536 /* show the protocol and transport */
537 seq_printf(m, " Protocol: %s\n", us->protocol_name);
538 seq_printf(m, " Transport: %s\n", us->transport_name);
540 /* show the device flags */
541 seq_printf(m, " Quirks:");
543 #define US_FLAG(name, value) \
544 if (us->fflags & value) seq_printf(m, " " #name);
551 /***********************************************************************
553 ***********************************************************************/
555 /* Output routine for the sysfs max_sectors file */
556 static ssize_t max_sectors_show(struct device *dev, struct device_attribute *attr, char *buf)
558 struct scsi_device *sdev = to_scsi_device(dev);
560 return sprintf(buf, "%u\n", queue_max_hw_sectors(sdev->request_queue));
563 /* Input routine for the sysfs max_sectors file */
564 static ssize_t max_sectors_store(struct device *dev, struct device_attribute *attr, const char *buf,
567 struct scsi_device *sdev = to_scsi_device(dev);
570 if (sscanf(buf, "%hu", &ms) > 0) {
571 blk_queue_max_hw_sectors(sdev->request_queue, ms);
576 static DEVICE_ATTR_RW(max_sectors);
578 static struct device_attribute *sysfs_device_attr_list[] = {
579 &dev_attr_max_sectors,
584 * this defines our host template, with which we'll allocate hosts
587 static const struct scsi_host_template usb_stor_host_template = {
588 /* basic userland interface stuff */
589 .name = "usb-storage",
590 .proc_name = "usb-storage",
591 .show_info = show_info,
592 .write_info = write_info,
595 /* command interface -- queued only */
596 .queuecommand = queuecommand,
598 /* error and abort handlers */
599 .eh_abort_handler = command_abort,
600 .eh_device_reset_handler = device_reset,
601 .eh_bus_reset_handler = bus_reset,
603 /* queue commands only, only one command per LUN */
606 /* unknown initiator id */
609 .slave_alloc = slave_alloc,
610 .slave_configure = slave_configure,
611 .target_alloc = target_alloc,
613 /* lots of sg segments can be handled */
614 .sg_tablesize = SG_MAX_SEGMENTS,
618 * Limit the total size of a transfer to 120 KB.
620 * Some devices are known to choke with anything larger. It seems like
621 * the problem stems from the fact that original IDE controllers had
622 * only an 8-bit register to hold the number of sectors in one transfer
623 * and even those couldn't handle a full 256 sectors.
625 * Because we want to make sure we interoperate with as many devices as
626 * possible, we will maintain a 240 sector transfer size limit for USB
627 * Mass Storage devices.
629 * Tests show that other operating have similar limits with Microsoft
630 * Windows 7 limiting transfers to 128 sectors for both USB2 and USB3
631 * and Apple Mac OS X 10.11 limiting transfers to 256 sectors for USB2
632 * and 2048 for USB3 devices.
637 * merge commands... this seems to help performance, but
638 * periodically someone should test to see which setting is more
646 /* we do our own delay after a device or bus reset */
647 .skip_settle_delay = 1,
649 /* sysfs device attributes */
650 .sdev_attrs = sysfs_device_attr_list,
652 /* module management */
653 .module = THIS_MODULE
656 void usb_stor_host_template_init(struct scsi_host_template *sht,
657 const char *name, struct module *owner)
659 *sht = usb_stor_host_template;
661 sht->proc_name = name;
664 EXPORT_SYMBOL_GPL(usb_stor_host_template_init);
666 /* To Report "Illegal Request: Invalid Field in CDB */
667 unsigned char usb_stor_sense_invalidCDB[18] = {
668 [0] = 0x70, /* current error */
669 [2] = ILLEGAL_REQUEST, /* Illegal Request = 0x05 */
670 [7] = 0x0a, /* additional length */
671 [12] = 0x24 /* Invalid Field in CDB */
673 EXPORT_SYMBOL_GPL(usb_stor_sense_invalidCDB);