xref: /linux/drivers/usb/storage/usb.c (revision c5288cda69ee2d8607f5026bd599a5cebf0ee783)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Driver for USB Mass Storage compliant devices
4  *
5  * Current development and maintenance by:
6  *   (c) 1999-2003 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
7  *
8  * Developed with the assistance of:
9  *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
10  *   (c) 2003-2009 Alan Stern (stern@rowland.harvard.edu)
11  *
12  * Initial work by:
13  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
14  *
15  * usb_device_id support by Adam J. Richter (adam@yggdrasil.com):
16  *   (c) 2000 Yggdrasil Computing, Inc.
17  *
18  * This driver is based on the 'USB Mass Storage Class' document. This
19  * describes in detail the protocol used to communicate with such
20  * devices.  Clearly, the designers had SCSI and ATAPI commands in
21  * mind when they created this document.  The commands are all very
22  * similar to commands in the SCSI-II and ATAPI specifications.
23  *
24  * It is important to note that in a number of cases this class
25  * exhibits class-specific exemptions from the USB specification.
26  * Notably the usage of NAK, STALL and ACK differs from the norm, in
27  * that they are used to communicate wait, failed and OK on commands.
28  *
29  * Also, for certain devices, the interrupt endpoint is used to convey
30  * status of a command.
31  */
32 
33 #ifdef CONFIG_USB_STORAGE_DEBUG
34 #define DEBUG
35 #endif
36 
37 #include <linux/sched.h>
38 #include <linux/errno.h>
39 #include <linux/module.h>
40 #include <linux/slab.h>
41 #include <linux/kthread.h>
42 #include <linux/mutex.h>
43 #include <linux/utsname.h>
44 
45 #include <scsi/scsi.h>
46 #include <scsi/scsi_cmnd.h>
47 #include <scsi/scsi_device.h>
48 
49 #include "usb.h"
50 #include <linux/usb/hcd.h>
51 #include "scsiglue.h"
52 #include "transport.h"
53 #include "protocol.h"
54 #include "debug.h"
55 #include "initializers.h"
56 
57 #include "sierra_ms.h"
58 #include "option_ms.h"
59 
60 #if IS_ENABLED(CONFIG_USB_UAS)
61 #include "uas-detect.h"
62 #endif
63 
64 #define DRV_NAME "usb-storage"
65 
66 /* Some informational data */
67 MODULE_AUTHOR("Matthew Dharm <mdharm-usb@one-eyed-alien.net>");
68 MODULE_DESCRIPTION("USB Mass Storage driver for Linux");
69 MODULE_LICENSE("GPL");
70 
71 static unsigned int delay_use = 1;
72 module_param(delay_use, uint, S_IRUGO | S_IWUSR);
73 MODULE_PARM_DESC(delay_use, "seconds to delay before using a new device");
74 
75 static char quirks[128];
76 module_param_string(quirks, quirks, sizeof(quirks), S_IRUGO | S_IWUSR);
77 MODULE_PARM_DESC(quirks, "supplemental list of device IDs and their quirks");
78 
79 
80 /*
81  * The entries in this table correspond, line for line,
82  * with the entries in usb_storage_usb_ids[], defined in usual-tables.c.
83  */
84 
85 /*
86  *The vendor name should be kept at eight characters or less, and
87  * the product name should be kept at 16 characters or less. If a device
88  * has the US_FL_FIX_INQUIRY flag, then the vendor and product names
89  * normally generated by a device through the INQUIRY response will be
90  * taken from this list, and this is the reason for the above size
91  * restriction. However, if the flag is not present, then you
92  * are free to use as many characters as you like.
93  */
94 
95 #define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
96 		    vendor_name, product_name, use_protocol, use_transport, \
97 		    init_function, Flags) \
98 { \
99 	.vendorName = vendor_name,	\
100 	.productName = product_name,	\
101 	.useProtocol = use_protocol,	\
102 	.useTransport = use_transport,	\
103 	.initFunction = init_function,	\
104 }
105 
106 #define COMPLIANT_DEV	UNUSUAL_DEV
107 
108 #define USUAL_DEV(use_protocol, use_transport) \
109 { \
110 	.useProtocol = use_protocol,	\
111 	.useTransport = use_transport,	\
112 }
113 
114 static const struct us_unusual_dev us_unusual_dev_list[] = {
115 #	include "unusual_devs.h"
116 	{ }		/* Terminating entry */
117 };
118 
119 static const struct us_unusual_dev for_dynamic_ids =
120 		USUAL_DEV(USB_SC_SCSI, USB_PR_BULK);
121 
122 #undef UNUSUAL_DEV
123 #undef COMPLIANT_DEV
124 #undef USUAL_DEV
125 
126 #ifdef CONFIG_LOCKDEP
127 
128 static struct lock_class_key us_interface_key[USB_MAXINTERFACES];
129 
130 static void us_set_lock_class(struct mutex *mutex,
131 		struct usb_interface *intf)
132 {
133 	struct usb_device *udev = interface_to_usbdev(intf);
134 	struct usb_host_config *config = udev->actconfig;
135 	int i;
136 
137 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
138 		if (config->interface[i] == intf)
139 			break;
140 	}
141 
142 	BUG_ON(i == config->desc.bNumInterfaces);
143 
144 	lockdep_set_class(mutex, &us_interface_key[i]);
145 }
146 
147 #else
148 
149 static void us_set_lock_class(struct mutex *mutex,
150 		struct usb_interface *intf)
151 {
152 }
153 
154 #endif
155 
156 #ifdef CONFIG_PM	/* Minimal support for suspend and resume */
157 
158 int usb_stor_suspend(struct usb_interface *iface, pm_message_t message)
159 {
160 	struct us_data *us = usb_get_intfdata(iface);
161 
162 	/* Wait until no command is running */
163 	mutex_lock(&us->dev_mutex);
164 
165 	if (us->suspend_resume_hook)
166 		(us->suspend_resume_hook)(us, US_SUSPEND);
167 
168 	/*
169 	 * When runtime PM is working, we'll set a flag to indicate
170 	 * whether we should autoresume when a SCSI request arrives.
171 	 */
172 
173 	mutex_unlock(&us->dev_mutex);
174 	return 0;
175 }
176 EXPORT_SYMBOL_GPL(usb_stor_suspend);
177 
178 int usb_stor_resume(struct usb_interface *iface)
179 {
180 	struct us_data *us = usb_get_intfdata(iface);
181 
182 	mutex_lock(&us->dev_mutex);
183 
184 	if (us->suspend_resume_hook)
185 		(us->suspend_resume_hook)(us, US_RESUME);
186 
187 	mutex_unlock(&us->dev_mutex);
188 	return 0;
189 }
190 EXPORT_SYMBOL_GPL(usb_stor_resume);
191 
192 int usb_stor_reset_resume(struct usb_interface *iface)
193 {
194 	struct us_data *us = usb_get_intfdata(iface);
195 
196 	/* Report the reset to the SCSI core */
197 	usb_stor_report_bus_reset(us);
198 
199 	/*
200 	 * If any of the subdrivers implemented a reinitialization scheme,
201 	 * this is where the callback would be invoked.
202 	 */
203 	return 0;
204 }
205 EXPORT_SYMBOL_GPL(usb_stor_reset_resume);
206 
207 #endif /* CONFIG_PM */
208 
209 /*
210  * The next two routines get called just before and just after
211  * a USB port reset, whether from this driver or a different one.
212  */
213 
214 int usb_stor_pre_reset(struct usb_interface *iface)
215 {
216 	struct us_data *us = usb_get_intfdata(iface);
217 
218 	/* Make sure no command runs during the reset */
219 	mutex_lock(&us->dev_mutex);
220 	return 0;
221 }
222 EXPORT_SYMBOL_GPL(usb_stor_pre_reset);
223 
224 int usb_stor_post_reset(struct usb_interface *iface)
225 {
226 	struct us_data *us = usb_get_intfdata(iface);
227 
228 	/* Report the reset to the SCSI core */
229 	usb_stor_report_bus_reset(us);
230 
231 	/*
232 	 * If any of the subdrivers implemented a reinitialization scheme,
233 	 * this is where the callback would be invoked.
234 	 */
235 
236 	mutex_unlock(&us->dev_mutex);
237 	return 0;
238 }
239 EXPORT_SYMBOL_GPL(usb_stor_post_reset);
240 
241 /*
242  * fill_inquiry_response takes an unsigned char array (which must
243  * be at least 36 characters) and populates the vendor name,
244  * product name, and revision fields. Then the array is copied
245  * into the SCSI command's response buffer (oddly enough
246  * called request_buffer). data_len contains the length of the
247  * data array, which again must be at least 36.
248  */
249 
250 void fill_inquiry_response(struct us_data *us, unsigned char *data,
251 		unsigned int data_len)
252 {
253 	if (data_len < 36) /* You lose. */
254 		return;
255 
256 	memset(data+8, ' ', 28);
257 	if (data[0]&0x20) { /*
258 			     * USB device currently not connected. Return
259 			     * peripheral qualifier 001b ("...however, the
260 			     * physical device is not currently connected
261 			     * to this logical unit") and leave vendor and
262 			     * product identification empty. ("If the target
263 			     * does store some of the INQUIRY data on the
264 			     * device, it may return zeros or ASCII spaces
265 			     * (20h) in those fields until the data is
266 			     * available from the device.").
267 			     */
268 	} else {
269 		u16 bcdDevice = le16_to_cpu(us->pusb_dev->descriptor.bcdDevice);
270 		int n;
271 
272 		n = strlen(us->unusual_dev->vendorName);
273 		memcpy(data+8, us->unusual_dev->vendorName, min(8, n));
274 		n = strlen(us->unusual_dev->productName);
275 		memcpy(data+16, us->unusual_dev->productName, min(16, n));
276 
277 		data[32] = 0x30 + ((bcdDevice>>12) & 0x0F);
278 		data[33] = 0x30 + ((bcdDevice>>8) & 0x0F);
279 		data[34] = 0x30 + ((bcdDevice>>4) & 0x0F);
280 		data[35] = 0x30 + ((bcdDevice) & 0x0F);
281 	}
282 
283 	usb_stor_set_xfer_buf(data, data_len, us->srb);
284 }
285 EXPORT_SYMBOL_GPL(fill_inquiry_response);
286 
287 static int usb_stor_control_thread(void * __us)
288 {
289 	struct us_data *us = (struct us_data *)__us;
290 	struct Scsi_Host *host = us_to_host(us);
291 	struct scsi_cmnd *srb;
292 
293 	for (;;) {
294 		usb_stor_dbg(us, "*** thread sleeping\n");
295 		if (wait_for_completion_interruptible(&us->cmnd_ready))
296 			break;
297 
298 		usb_stor_dbg(us, "*** thread awakened\n");
299 
300 		/* lock the device pointers */
301 		mutex_lock(&(us->dev_mutex));
302 
303 		/* lock access to the state */
304 		scsi_lock(host);
305 
306 		/* When we are called with no command pending, we're done */
307 		srb = us->srb;
308 		if (srb == NULL) {
309 			scsi_unlock(host);
310 			mutex_unlock(&us->dev_mutex);
311 			usb_stor_dbg(us, "-- exiting\n");
312 			break;
313 		}
314 
315 		/* has the command timed out *already* ? */
316 		if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
317 			srb->result = DID_ABORT << 16;
318 			goto SkipForAbort;
319 		}
320 
321 		scsi_unlock(host);
322 
323 		/*
324 		 * reject the command if the direction indicator
325 		 * is UNKNOWN
326 		 */
327 		if (srb->sc_data_direction == DMA_BIDIRECTIONAL) {
328 			usb_stor_dbg(us, "UNKNOWN data direction\n");
329 			srb->result = DID_ERROR << 16;
330 		}
331 
332 		/*
333 		 * reject if target != 0 or if LUN is higher than
334 		 * the maximum known LUN
335 		 */
336 		else if (srb->device->id &&
337 				!(us->fflags & US_FL_SCM_MULT_TARG)) {
338 			usb_stor_dbg(us, "Bad target number (%d:%llu)\n",
339 				     srb->device->id,
340 				     srb->device->lun);
341 			srb->result = DID_BAD_TARGET << 16;
342 		}
343 
344 		else if (srb->device->lun > us->max_lun) {
345 			usb_stor_dbg(us, "Bad LUN (%d:%llu)\n",
346 				     srb->device->id,
347 				     srb->device->lun);
348 			srb->result = DID_BAD_TARGET << 16;
349 		}
350 
351 		/*
352 		 * Handle those devices which need us to fake
353 		 * their inquiry data
354 		 */
355 		else if ((srb->cmnd[0] == INQUIRY) &&
356 			    (us->fflags & US_FL_FIX_INQUIRY)) {
357 			unsigned char data_ptr[36] = {
358 			    0x00, 0x80, 0x02, 0x02,
359 			    0x1F, 0x00, 0x00, 0x00};
360 
361 			usb_stor_dbg(us, "Faking INQUIRY command\n");
362 			fill_inquiry_response(us, data_ptr, 36);
363 			srb->result = SAM_STAT_GOOD;
364 		}
365 
366 		/* we've got a command, let's do it! */
367 		else {
368 			US_DEBUG(usb_stor_show_command(us, srb));
369 			us->proto_handler(srb, us);
370 			usb_mark_last_busy(us->pusb_dev);
371 		}
372 
373 		/* lock access to the state */
374 		scsi_lock(host);
375 
376 		/* was the command aborted? */
377 		if (srb->result == DID_ABORT << 16) {
378 SkipForAbort:
379 			usb_stor_dbg(us, "scsi command aborted\n");
380 			srb = NULL;	/* Don't call scsi_done() */
381 		}
382 
383 		/*
384 		 * If an abort request was received we need to signal that
385 		 * the abort has finished.  The proper test for this is
386 		 * the TIMED_OUT flag, not srb->result == DID_ABORT, because
387 		 * the timeout might have occurred after the command had
388 		 * already completed with a different result code.
389 		 */
390 		if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
391 			complete(&(us->notify));
392 
393 			/* Allow USB transfers to resume */
394 			clear_bit(US_FLIDX_ABORTING, &us->dflags);
395 			clear_bit(US_FLIDX_TIMED_OUT, &us->dflags);
396 		}
397 
398 		/* finished working on this command */
399 		us->srb = NULL;
400 		scsi_unlock(host);
401 
402 		/* unlock the device pointers */
403 		mutex_unlock(&us->dev_mutex);
404 
405 		/* now that the locks are released, notify the SCSI core */
406 		if (srb) {
407 			usb_stor_dbg(us, "scsi cmd done, result=0x%x\n",
408 					srb->result);
409 			scsi_done_direct(srb);
410 		}
411 	} /* for (;;) */
412 
413 	/* Wait until we are told to stop */
414 	for (;;) {
415 		set_current_state(TASK_INTERRUPTIBLE);
416 		if (kthread_should_stop())
417 			break;
418 		schedule();
419 	}
420 	__set_current_state(TASK_RUNNING);
421 	return 0;
422 }
423 
424 /***********************************************************************
425  * Device probing and disconnecting
426  ***********************************************************************/
427 
428 /* Associate our private data with the USB device */
429 static int associate_dev(struct us_data *us, struct usb_interface *intf)
430 {
431 	/* Fill in the device-related fields */
432 	us->pusb_dev = interface_to_usbdev(intf);
433 	us->pusb_intf = intf;
434 	us->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
435 	usb_stor_dbg(us, "Vendor: 0x%04x, Product: 0x%04x, Revision: 0x%04x\n",
436 		     le16_to_cpu(us->pusb_dev->descriptor.idVendor),
437 		     le16_to_cpu(us->pusb_dev->descriptor.idProduct),
438 		     le16_to_cpu(us->pusb_dev->descriptor.bcdDevice));
439 	usb_stor_dbg(us, "Interface Subclass: 0x%02x, Protocol: 0x%02x\n",
440 		     intf->cur_altsetting->desc.bInterfaceSubClass,
441 		     intf->cur_altsetting->desc.bInterfaceProtocol);
442 
443 	/* Store our private data in the interface */
444 	usb_set_intfdata(intf, us);
445 
446 	/* Allocate the control/setup and DMA-mapped buffers */
447 	us->cr = kmalloc(sizeof(*us->cr), GFP_KERNEL);
448 	if (!us->cr)
449 		return -ENOMEM;
450 
451 	us->iobuf = usb_alloc_coherent(us->pusb_dev, US_IOBUF_SIZE,
452 			GFP_KERNEL, &us->iobuf_dma);
453 	if (!us->iobuf) {
454 		usb_stor_dbg(us, "I/O buffer allocation failed\n");
455 		return -ENOMEM;
456 	}
457 	return 0;
458 }
459 
460 /* Works only for digits and letters, but small and fast */
461 #define TOLOWER(x) ((x) | 0x20)
462 
463 /* Adjust device flags based on the "quirks=" module parameter */
464 void usb_stor_adjust_quirks(struct usb_device *udev, u64 *fflags)
465 {
466 	char *p;
467 	u16 vid = le16_to_cpu(udev->descriptor.idVendor);
468 	u16 pid = le16_to_cpu(udev->descriptor.idProduct);
469 	u64 f = 0;
470 	u64 mask = (US_FL_SANE_SENSE | US_FL_BAD_SENSE |
471 			US_FL_FIX_CAPACITY | US_FL_IGNORE_UAS |
472 			US_FL_CAPACITY_HEURISTICS | US_FL_IGNORE_DEVICE |
473 			US_FL_NOT_LOCKABLE | US_FL_MAX_SECTORS_64 |
474 			US_FL_CAPACITY_OK | US_FL_IGNORE_RESIDUE |
475 			US_FL_SINGLE_LUN | US_FL_NO_WP_DETECT |
476 			US_FL_NO_READ_DISC_INFO | US_FL_NO_READ_CAPACITY_16 |
477 			US_FL_INITIAL_READ10 | US_FL_WRITE_CACHE |
478 			US_FL_NO_ATA_1X | US_FL_NO_REPORT_OPCODES |
479 			US_FL_MAX_SECTORS_240 | US_FL_NO_REPORT_LUNS |
480 			US_FL_ALWAYS_SYNC);
481 
482 	p = quirks;
483 	while (*p) {
484 		/* Each entry consists of VID:PID:flags */
485 		if (vid == simple_strtoul(p, &p, 16) &&
486 				*p == ':' &&
487 				pid == simple_strtoul(p+1, &p, 16) &&
488 				*p == ':')
489 			break;
490 
491 		/* Move forward to the next entry */
492 		while (*p) {
493 			if (*p++ == ',')
494 				break;
495 		}
496 	}
497 	if (!*p)	/* No match */
498 		return;
499 
500 	/* Collect the flags */
501 	while (*++p && *p != ',') {
502 		switch (TOLOWER(*p)) {
503 		case 'a':
504 			f |= US_FL_SANE_SENSE;
505 			break;
506 		case 'b':
507 			f |= US_FL_BAD_SENSE;
508 			break;
509 		case 'c':
510 			f |= US_FL_FIX_CAPACITY;
511 			break;
512 		case 'd':
513 			f |= US_FL_NO_READ_DISC_INFO;
514 			break;
515 		case 'e':
516 			f |= US_FL_NO_READ_CAPACITY_16;
517 			break;
518 		case 'f':
519 			f |= US_FL_NO_REPORT_OPCODES;
520 			break;
521 		case 'g':
522 			f |= US_FL_MAX_SECTORS_240;
523 			break;
524 		case 'h':
525 			f |= US_FL_CAPACITY_HEURISTICS;
526 			break;
527 		case 'i':
528 			f |= US_FL_IGNORE_DEVICE;
529 			break;
530 		case 'j':
531 			f |= US_FL_NO_REPORT_LUNS;
532 			break;
533 		case 'k':
534 			f |= US_FL_NO_SAME;
535 			break;
536 		case 'l':
537 			f |= US_FL_NOT_LOCKABLE;
538 			break;
539 		case 'm':
540 			f |= US_FL_MAX_SECTORS_64;
541 			break;
542 		case 'n':
543 			f |= US_FL_INITIAL_READ10;
544 			break;
545 		case 'o':
546 			f |= US_FL_CAPACITY_OK;
547 			break;
548 		case 'p':
549 			f |= US_FL_WRITE_CACHE;
550 			break;
551 		case 'r':
552 			f |= US_FL_IGNORE_RESIDUE;
553 			break;
554 		case 's':
555 			f |= US_FL_SINGLE_LUN;
556 			break;
557 		case 't':
558 			f |= US_FL_NO_ATA_1X;
559 			break;
560 		case 'u':
561 			f |= US_FL_IGNORE_UAS;
562 			break;
563 		case 'w':
564 			f |= US_FL_NO_WP_DETECT;
565 			break;
566 		case 'y':
567 			f |= US_FL_ALWAYS_SYNC;
568 			break;
569 		/* Ignore unrecognized flag characters */
570 		}
571 	}
572 	*fflags = (*fflags & ~mask) | f;
573 }
574 EXPORT_SYMBOL_GPL(usb_stor_adjust_quirks);
575 
576 /* Get the unusual_devs entries and the string descriptors */
577 static int get_device_info(struct us_data *us, const struct usb_device_id *id,
578 		const struct us_unusual_dev *unusual_dev)
579 {
580 	struct usb_device *dev = us->pusb_dev;
581 	struct usb_interface_descriptor *idesc =
582 		&us->pusb_intf->cur_altsetting->desc;
583 	struct device *pdev = &us->pusb_intf->dev;
584 
585 	/* Store the entries */
586 	us->unusual_dev = unusual_dev;
587 	us->subclass = (unusual_dev->useProtocol == USB_SC_DEVICE) ?
588 			idesc->bInterfaceSubClass :
589 			unusual_dev->useProtocol;
590 	us->protocol = (unusual_dev->useTransport == USB_PR_DEVICE) ?
591 			idesc->bInterfaceProtocol :
592 			unusual_dev->useTransport;
593 	us->fflags = id->driver_info;
594 	usb_stor_adjust_quirks(us->pusb_dev, &us->fflags);
595 
596 	if (us->fflags & US_FL_IGNORE_DEVICE) {
597 		dev_info(pdev, "device ignored\n");
598 		return -ENODEV;
599 	}
600 
601 	/*
602 	 * This flag is only needed when we're in high-speed, so let's
603 	 * disable it if we're in full-speed
604 	 */
605 	if (dev->speed != USB_SPEED_HIGH)
606 		us->fflags &= ~US_FL_GO_SLOW;
607 
608 	if (us->fflags)
609 		dev_info(pdev, "Quirks match for vid %04x pid %04x: %llx\n",
610 				le16_to_cpu(dev->descriptor.idVendor),
611 				le16_to_cpu(dev->descriptor.idProduct),
612 				us->fflags);
613 
614 	/*
615 	 * Log a message if a non-generic unusual_dev entry contains an
616 	 * unnecessary subclass or protocol override.  This may stimulate
617 	 * reports from users that will help us remove unneeded entries
618 	 * from the unusual_devs.h table.
619 	 */
620 	if (id->idVendor || id->idProduct) {
621 		static const char *msgs[3] = {
622 			"an unneeded SubClass entry",
623 			"an unneeded Protocol entry",
624 			"unneeded SubClass and Protocol entries"};
625 		struct usb_device_descriptor *ddesc = &dev->descriptor;
626 		int msg = -1;
627 
628 		if (unusual_dev->useProtocol != USB_SC_DEVICE &&
629 			us->subclass == idesc->bInterfaceSubClass)
630 			msg += 1;
631 		if (unusual_dev->useTransport != USB_PR_DEVICE &&
632 			us->protocol == idesc->bInterfaceProtocol)
633 			msg += 2;
634 		if (msg >= 0 && !(us->fflags & US_FL_NEED_OVERRIDE))
635 			dev_notice(pdev, "This device "
636 					"(%04x,%04x,%04x S %02x P %02x)"
637 					" has %s in unusual_devs.h (kernel"
638 					" %s)\n"
639 					"   Please send a copy of this message to "
640 					"<linux-usb@vger.kernel.org> and "
641 					"<usb-storage@lists.one-eyed-alien.net>\n",
642 					le16_to_cpu(ddesc->idVendor),
643 					le16_to_cpu(ddesc->idProduct),
644 					le16_to_cpu(ddesc->bcdDevice),
645 					idesc->bInterfaceSubClass,
646 					idesc->bInterfaceProtocol,
647 					msgs[msg],
648 					utsname()->release);
649 	}
650 
651 	return 0;
652 }
653 
654 /* Get the transport settings */
655 static void get_transport(struct us_data *us)
656 {
657 	switch (us->protocol) {
658 	case USB_PR_CB:
659 		us->transport_name = "Control/Bulk";
660 		us->transport = usb_stor_CB_transport;
661 		us->transport_reset = usb_stor_CB_reset;
662 		us->max_lun = 7;
663 		break;
664 
665 	case USB_PR_CBI:
666 		us->transport_name = "Control/Bulk/Interrupt";
667 		us->transport = usb_stor_CB_transport;
668 		us->transport_reset = usb_stor_CB_reset;
669 		us->max_lun = 7;
670 		break;
671 
672 	case USB_PR_BULK:
673 		us->transport_name = "Bulk";
674 		us->transport = usb_stor_Bulk_transport;
675 		us->transport_reset = usb_stor_Bulk_reset;
676 		break;
677 	}
678 }
679 
680 /* Get the protocol settings */
681 static void get_protocol(struct us_data *us)
682 {
683 	switch (us->subclass) {
684 	case USB_SC_RBC:
685 		us->protocol_name = "Reduced Block Commands (RBC)";
686 		us->proto_handler = usb_stor_transparent_scsi_command;
687 		break;
688 
689 	case USB_SC_8020:
690 		us->protocol_name = "8020i";
691 		us->proto_handler = usb_stor_pad12_command;
692 		us->max_lun = 0;
693 		break;
694 
695 	case USB_SC_QIC:
696 		us->protocol_name = "QIC-157";
697 		us->proto_handler = usb_stor_pad12_command;
698 		us->max_lun = 0;
699 		break;
700 
701 	case USB_SC_8070:
702 		us->protocol_name = "8070i";
703 		us->proto_handler = usb_stor_pad12_command;
704 		us->max_lun = 0;
705 		break;
706 
707 	case USB_SC_SCSI:
708 		us->protocol_name = "Transparent SCSI";
709 		us->proto_handler = usb_stor_transparent_scsi_command;
710 		break;
711 
712 	case USB_SC_UFI:
713 		us->protocol_name = "Uniform Floppy Interface (UFI)";
714 		us->proto_handler = usb_stor_ufi_command;
715 		break;
716 	}
717 }
718 
719 /* Get the pipe settings */
720 static int get_pipes(struct us_data *us)
721 {
722 	struct usb_host_interface *alt = us->pusb_intf->cur_altsetting;
723 	struct usb_endpoint_descriptor *ep_in;
724 	struct usb_endpoint_descriptor *ep_out;
725 	struct usb_endpoint_descriptor *ep_int;
726 	int res;
727 
728 	/*
729 	 * Find the first endpoint of each type we need.
730 	 * We are expecting a minimum of 2 endpoints - in and out (bulk).
731 	 * An optional interrupt-in is OK (necessary for CBI protocol).
732 	 * We will ignore any others.
733 	 */
734 	res = usb_find_common_endpoints(alt, &ep_in, &ep_out, NULL, NULL);
735 	if (res) {
736 		usb_stor_dbg(us, "bulk endpoints not found\n");
737 		return res;
738 	}
739 
740 	res = usb_find_int_in_endpoint(alt, &ep_int);
741 	if (res && us->protocol == USB_PR_CBI) {
742 		usb_stor_dbg(us, "interrupt endpoint not found\n");
743 		return res;
744 	}
745 
746 	/* Calculate and store the pipe values */
747 	us->send_ctrl_pipe = usb_sndctrlpipe(us->pusb_dev, 0);
748 	us->recv_ctrl_pipe = usb_rcvctrlpipe(us->pusb_dev, 0);
749 	us->send_bulk_pipe = usb_sndbulkpipe(us->pusb_dev,
750 		usb_endpoint_num(ep_out));
751 	us->recv_bulk_pipe = usb_rcvbulkpipe(us->pusb_dev,
752 		usb_endpoint_num(ep_in));
753 	if (ep_int) {
754 		us->recv_intr_pipe = usb_rcvintpipe(us->pusb_dev,
755 			usb_endpoint_num(ep_int));
756 		us->ep_bInterval = ep_int->bInterval;
757 	}
758 	return 0;
759 }
760 
761 /* Initialize all the dynamic resources we need */
762 static int usb_stor_acquire_resources(struct us_data *us)
763 {
764 	int p;
765 	struct task_struct *th;
766 
767 	us->current_urb = usb_alloc_urb(0, GFP_KERNEL);
768 	if (!us->current_urb)
769 		return -ENOMEM;
770 
771 	/*
772 	 * Just before we start our control thread, initialize
773 	 * the device if it needs initialization
774 	 */
775 	if (us->unusual_dev->initFunction) {
776 		p = us->unusual_dev->initFunction(us);
777 		if (p)
778 			return p;
779 	}
780 
781 	/* Start up our control thread */
782 	th = kthread_run(usb_stor_control_thread, us, "usb-storage");
783 	if (IS_ERR(th)) {
784 		dev_warn(&us->pusb_intf->dev,
785 				"Unable to start control thread\n");
786 		return PTR_ERR(th);
787 	}
788 	us->ctl_thread = th;
789 
790 	return 0;
791 }
792 
793 /* Release all our dynamic resources */
794 static void usb_stor_release_resources(struct us_data *us)
795 {
796 	/*
797 	 * Tell the control thread to exit.  The SCSI host must
798 	 * already have been removed and the DISCONNECTING flag set
799 	 * so that we won't accept any more commands.
800 	 */
801 	usb_stor_dbg(us, "-- sending exit command to thread\n");
802 	complete(&us->cmnd_ready);
803 	if (us->ctl_thread)
804 		kthread_stop(us->ctl_thread);
805 
806 	/* Call the destructor routine, if it exists */
807 	if (us->extra_destructor) {
808 		usb_stor_dbg(us, "-- calling extra_destructor()\n");
809 		us->extra_destructor(us->extra);
810 	}
811 
812 	/* Free the extra data and the URB */
813 	kfree(us->extra);
814 	usb_free_urb(us->current_urb);
815 }
816 
817 /* Dissociate from the USB device */
818 static void dissociate_dev(struct us_data *us)
819 {
820 	/* Free the buffers */
821 	kfree(us->cr);
822 	usb_free_coherent(us->pusb_dev, US_IOBUF_SIZE, us->iobuf, us->iobuf_dma);
823 
824 	/* Remove our private data from the interface */
825 	usb_set_intfdata(us->pusb_intf, NULL);
826 }
827 
828 /*
829  * First stage of disconnect processing: stop SCSI scanning,
830  * remove the host, and stop accepting new commands
831  */
832 static void quiesce_and_remove_host(struct us_data *us)
833 {
834 	struct Scsi_Host *host = us_to_host(us);
835 
836 	/* If the device is really gone, cut short reset delays */
837 	if (us->pusb_dev->state == USB_STATE_NOTATTACHED) {
838 		set_bit(US_FLIDX_DISCONNECTING, &us->dflags);
839 		wake_up(&us->delay_wait);
840 	}
841 
842 	/*
843 	 * Prevent SCSI scanning (if it hasn't started yet)
844 	 * or wait for the SCSI-scanning routine to stop.
845 	 */
846 	cancel_delayed_work_sync(&us->scan_dwork);
847 
848 	/* Balance autopm calls if scanning was cancelled */
849 	if (test_bit(US_FLIDX_SCAN_PENDING, &us->dflags))
850 		usb_autopm_put_interface_no_suspend(us->pusb_intf);
851 
852 	/*
853 	 * Removing the host will perform an orderly shutdown: caches
854 	 * synchronized, disks spun down, etc.
855 	 */
856 	scsi_remove_host(host);
857 
858 	/*
859 	 * Prevent any new commands from being accepted and cut short
860 	 * reset delays.
861 	 */
862 	scsi_lock(host);
863 	set_bit(US_FLIDX_DISCONNECTING, &us->dflags);
864 	scsi_unlock(host);
865 	wake_up(&us->delay_wait);
866 }
867 
868 /* Second stage of disconnect processing: deallocate all resources */
869 static void release_everything(struct us_data *us)
870 {
871 	usb_stor_release_resources(us);
872 	dissociate_dev(us);
873 
874 	/*
875 	 * Drop our reference to the host; the SCSI core will free it
876 	 * (and "us" along with it) when the refcount becomes 0.
877 	 */
878 	scsi_host_put(us_to_host(us));
879 }
880 
881 /* Delayed-work routine to carry out SCSI-device scanning */
882 static void usb_stor_scan_dwork(struct work_struct *work)
883 {
884 	struct us_data *us = container_of(work, struct us_data,
885 			scan_dwork.work);
886 	struct device *dev = &us->pusb_intf->dev;
887 
888 	dev_dbg(dev, "starting scan\n");
889 
890 	/* For bulk-only devices, determine the max LUN value */
891 	if (us->protocol == USB_PR_BULK &&
892 	    !(us->fflags & US_FL_SINGLE_LUN) &&
893 	    !(us->fflags & US_FL_SCM_MULT_TARG)) {
894 		mutex_lock(&us->dev_mutex);
895 		us->max_lun = usb_stor_Bulk_max_lun(us);
896 		/*
897 		 * Allow proper scanning of devices that present more than 8 LUNs
898 		 * While not affecting other devices that may need the previous
899 		 * behavior
900 		 */
901 		if (us->max_lun >= 8)
902 			us_to_host(us)->max_lun = us->max_lun+1;
903 		mutex_unlock(&us->dev_mutex);
904 	}
905 	scsi_scan_host(us_to_host(us));
906 	dev_dbg(dev, "scan complete\n");
907 
908 	/* Should we unbind if no devices were detected? */
909 
910 	usb_autopm_put_interface(us->pusb_intf);
911 	clear_bit(US_FLIDX_SCAN_PENDING, &us->dflags);
912 }
913 
914 static unsigned int usb_stor_sg_tablesize(struct usb_interface *intf)
915 {
916 	struct usb_device *usb_dev = interface_to_usbdev(intf);
917 
918 	if (usb_dev->bus->sg_tablesize) {
919 		return usb_dev->bus->sg_tablesize;
920 	}
921 	return SG_ALL;
922 }
923 
924 /* First part of general USB mass-storage probing */
925 int usb_stor_probe1(struct us_data **pus,
926 		struct usb_interface *intf,
927 		const struct usb_device_id *id,
928 		const struct us_unusual_dev *unusual_dev,
929 		const struct scsi_host_template *sht)
930 {
931 	struct Scsi_Host *host;
932 	struct us_data *us;
933 	int result;
934 
935 	dev_info(&intf->dev, "USB Mass Storage device detected\n");
936 
937 	/*
938 	 * Ask the SCSI layer to allocate a host structure, with extra
939 	 * space at the end for our private us_data structure.
940 	 */
941 	host = scsi_host_alloc(sht, sizeof(*us));
942 	if (!host) {
943 		dev_warn(&intf->dev, "Unable to allocate the scsi host\n");
944 		return -ENOMEM;
945 	}
946 
947 	/*
948 	 * Allow 16-byte CDBs and thus > 2TB
949 	 */
950 	host->max_cmd_len = 16;
951 	host->sg_tablesize = usb_stor_sg_tablesize(intf);
952 	*pus = us = host_to_us(host);
953 	mutex_init(&(us->dev_mutex));
954 	us_set_lock_class(&us->dev_mutex, intf);
955 	init_completion(&us->cmnd_ready);
956 	init_completion(&(us->notify));
957 	init_waitqueue_head(&us->delay_wait);
958 	INIT_DELAYED_WORK(&us->scan_dwork, usb_stor_scan_dwork);
959 
960 	/* Associate the us_data structure with the USB device */
961 	result = associate_dev(us, intf);
962 	if (result)
963 		goto BadDevice;
964 
965 	/*
966 	 * Some USB host controllers can't do DMA; they have to use PIO.
967 	 * For such controllers we need to make sure the block layer sets
968 	 * up bounce buffers in addressable memory.
969 	 */
970 	if (!hcd_uses_dma(bus_to_hcd(us->pusb_dev->bus)) ||
971 	    bus_to_hcd(us->pusb_dev->bus)->localmem_pool)
972 		host->no_highmem = true;
973 
974 	/* Get the unusual_devs entries and the descriptors */
975 	result = get_device_info(us, id, unusual_dev);
976 	if (result)
977 		goto BadDevice;
978 
979 	/* Get standard transport and protocol settings */
980 	get_transport(us);
981 	get_protocol(us);
982 
983 	/*
984 	 * Give the caller a chance to fill in specialized transport
985 	 * or protocol settings.
986 	 */
987 	return 0;
988 
989 BadDevice:
990 	usb_stor_dbg(us, "storage_probe() failed\n");
991 	release_everything(us);
992 	return result;
993 }
994 EXPORT_SYMBOL_GPL(usb_stor_probe1);
995 
996 /* Second part of general USB mass-storage probing */
997 int usb_stor_probe2(struct us_data *us)
998 {
999 	int result;
1000 	struct device *dev = &us->pusb_intf->dev;
1001 
1002 	/* Make sure the transport and protocol have both been set */
1003 	if (!us->transport || !us->proto_handler) {
1004 		result = -ENXIO;
1005 		goto BadDevice;
1006 	}
1007 	usb_stor_dbg(us, "Transport: %s\n", us->transport_name);
1008 	usb_stor_dbg(us, "Protocol: %s\n", us->protocol_name);
1009 
1010 	if (us->fflags & US_FL_SCM_MULT_TARG) {
1011 		/*
1012 		 * SCM eUSCSI bridge devices can have different numbers
1013 		 * of LUNs on different targets; allow all to be probed.
1014 		 */
1015 		us->max_lun = 7;
1016 		/* The eUSCSI itself has ID 7, so avoid scanning that */
1017 		us_to_host(us)->this_id = 7;
1018 		/* max_id is 8 initially, so no need to set it here */
1019 	} else {
1020 		/* In the normal case there is only a single target */
1021 		us_to_host(us)->max_id = 1;
1022 		/*
1023 		 * Like Windows, we won't store the LUN bits in CDB[1] for
1024 		 * SCSI-2 devices using the Bulk-Only transport (even though
1025 		 * this violates the SCSI spec).
1026 		 */
1027 		if (us->transport == usb_stor_Bulk_transport)
1028 			us_to_host(us)->no_scsi2_lun_in_cdb = 1;
1029 	}
1030 
1031 	/* fix for single-lun devices */
1032 	if (us->fflags & US_FL_SINGLE_LUN)
1033 		us->max_lun = 0;
1034 
1035 	/* Find the endpoints and calculate pipe values */
1036 	result = get_pipes(us);
1037 	if (result)
1038 		goto BadDevice;
1039 
1040 	/*
1041 	 * If the device returns invalid data for the first READ(10)
1042 	 * command, indicate the command should be retried.
1043 	 */
1044 	if (us->fflags & US_FL_INITIAL_READ10)
1045 		set_bit(US_FLIDX_REDO_READ10, &us->dflags);
1046 
1047 	/* Acquire all the other resources and add the host */
1048 	result = usb_stor_acquire_resources(us);
1049 	if (result)
1050 		goto BadDevice;
1051 	usb_autopm_get_interface_no_resume(us->pusb_intf);
1052 	snprintf(us->scsi_name, sizeof(us->scsi_name), "usb-storage %s",
1053 					dev_name(&us->pusb_intf->dev));
1054 	result = scsi_add_host(us_to_host(us), dev);
1055 	if (result) {
1056 		dev_warn(dev,
1057 				"Unable to add the scsi host\n");
1058 		goto HostAddErr;
1059 	}
1060 
1061 	/* Submit the delayed_work for SCSI-device scanning */
1062 	set_bit(US_FLIDX_SCAN_PENDING, &us->dflags);
1063 
1064 	if (delay_use > 0)
1065 		dev_dbg(dev, "waiting for device to settle before scanning\n");
1066 	queue_delayed_work(system_freezable_wq, &us->scan_dwork,
1067 			delay_use * HZ);
1068 	return 0;
1069 
1070 	/* We come here if there are any problems */
1071 HostAddErr:
1072 	usb_autopm_put_interface_no_suspend(us->pusb_intf);
1073 BadDevice:
1074 	usb_stor_dbg(us, "storage_probe() failed\n");
1075 	release_everything(us);
1076 	return result;
1077 }
1078 EXPORT_SYMBOL_GPL(usb_stor_probe2);
1079 
1080 /* Handle a USB mass-storage disconnect */
1081 void usb_stor_disconnect(struct usb_interface *intf)
1082 {
1083 	struct us_data *us = usb_get_intfdata(intf);
1084 
1085 	quiesce_and_remove_host(us);
1086 	release_everything(us);
1087 }
1088 EXPORT_SYMBOL_GPL(usb_stor_disconnect);
1089 
1090 static struct scsi_host_template usb_stor_host_template;
1091 
1092 /* The main probe routine for standard devices */
1093 static int storage_probe(struct usb_interface *intf,
1094 			 const struct usb_device_id *id)
1095 {
1096 	const struct us_unusual_dev *unusual_dev;
1097 	struct us_data *us;
1098 	int result;
1099 	int size;
1100 
1101 	/* If uas is enabled and this device can do uas then ignore it. */
1102 #if IS_ENABLED(CONFIG_USB_UAS)
1103 	if (uas_use_uas_driver(intf, id, NULL))
1104 		return -ENXIO;
1105 #endif
1106 
1107 	/*
1108 	 * If the device isn't standard (is handled by a subdriver
1109 	 * module) then don't accept it.
1110 	 */
1111 	if (usb_usual_ignore_device(intf))
1112 		return -ENXIO;
1113 
1114 	/*
1115 	 * Call the general probe procedures.
1116 	 *
1117 	 * The unusual_dev_list array is parallel to the usb_storage_usb_ids
1118 	 * table, so we use the index of the id entry to find the
1119 	 * corresponding unusual_devs entry.
1120 	 */
1121 
1122 	size = ARRAY_SIZE(us_unusual_dev_list);
1123 	if (id >= usb_storage_usb_ids && id < usb_storage_usb_ids + size) {
1124 		unusual_dev = (id - usb_storage_usb_ids) + us_unusual_dev_list;
1125 	} else {
1126 		unusual_dev = &for_dynamic_ids;
1127 
1128 		dev_dbg(&intf->dev, "Use Bulk-Only transport with the Transparent SCSI protocol for dynamic id: 0x%04x 0x%04x\n",
1129 			id->idVendor, id->idProduct);
1130 	}
1131 
1132 	result = usb_stor_probe1(&us, intf, id, unusual_dev,
1133 				 &usb_stor_host_template);
1134 	if (result)
1135 		return result;
1136 
1137 	/* No special transport or protocol settings in the main module */
1138 
1139 	result = usb_stor_probe2(us);
1140 	return result;
1141 }
1142 
1143 static struct usb_driver usb_storage_driver = {
1144 	.name =		DRV_NAME,
1145 	.probe =	storage_probe,
1146 	.disconnect =	usb_stor_disconnect,
1147 	.suspend =	usb_stor_suspend,
1148 	.resume =	usb_stor_resume,
1149 	.reset_resume =	usb_stor_reset_resume,
1150 	.pre_reset =	usb_stor_pre_reset,
1151 	.post_reset =	usb_stor_post_reset,
1152 	.id_table =	usb_storage_usb_ids,
1153 	.supports_autosuspend = 1,
1154 	.soft_unbind =	1,
1155 };
1156 
1157 module_usb_stor_driver(usb_storage_driver, usb_stor_host_template, DRV_NAME);
1158