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