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