[PATCH] PATCH: usb-storage: move GetMaxLUN later in time
[firefly-linux-kernel-4.4.55.git] / drivers / usb / storage / usb.c
1 /* Driver for USB Mass Storage compliant devices
2  *
3  * $Id: usb.c,v 1.75 2002/04/22 03:39:43 mdharm Exp $
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 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  * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
33  * information about this driver.
34  *
35  * This program is free software; you can redistribute it and/or modify it
36  * under the terms of the GNU General Public License as published by the
37  * Free Software Foundation; either version 2, or (at your option) any
38  * later version.
39  *
40  * This program is distributed in the hope that it will be useful, but
41  * WITHOUT ANY WARRANTY; without even the implied warranty of
42  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
43  * General Public License for more details.
44  *
45  * You should have received a copy of the GNU General Public License along
46  * with this program; if not, write to the Free Software Foundation, Inc.,
47  * 675 Mass Ave, Cambridge, MA 02139, USA.
48  */
49
50 #include <linux/config.h>
51 #include <linux/sched.h>
52 #include <linux/errno.h>
53 #include <linux/suspend.h>
54 #include <linux/module.h>
55 #include <linux/init.h>
56 #include <linux/slab.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 #ifdef CONFIG_USB_STORAGE_USBAT
70 #include "shuttle_usbat.h"
71 #endif
72 #ifdef CONFIG_USB_STORAGE_SDDR09
73 #include "sddr09.h"
74 #endif
75 #ifdef CONFIG_USB_STORAGE_SDDR55
76 #include "sddr55.h"
77 #endif
78 #ifdef CONFIG_USB_STORAGE_DPCM
79 #include "dpcm.h"
80 #endif
81 #ifdef CONFIG_USB_STORAGE_FREECOM
82 #include "freecom.h"
83 #endif
84 #ifdef CONFIG_USB_STORAGE_ISD200
85 #include "isd200.h"
86 #endif
87 #ifdef CONFIG_USB_STORAGE_DATAFAB
88 #include "datafab.h"
89 #endif
90 #ifdef CONFIG_USB_STORAGE_JUMPSHOT
91 #include "jumpshot.h"
92 #endif
93 #ifdef CONFIG_USB_STORAGE_ONETOUCH
94 #include "onetouch.h"
95 #endif
96
97 /* Some informational data */
98 MODULE_AUTHOR("Matthew Dharm <mdharm-usb@one-eyed-alien.net>");
99 MODULE_DESCRIPTION("USB Mass Storage driver for Linux");
100 MODULE_LICENSE("GPL");
101
102 static unsigned int delay_use = 5;
103 module_param(delay_use, uint, S_IRUGO | S_IWUSR);
104 MODULE_PARM_DESC(delay_use, "seconds to delay before using a new device");
105
106
107 /* These are used to make sure the module doesn't unload before all the
108  * threads have exited.
109  */
110 static atomic_t total_threads = ATOMIC_INIT(0);
111 static DECLARE_COMPLETION(threads_gone);
112
113
114 static int storage_probe(struct usb_interface *iface,
115                          const struct usb_device_id *id);
116
117 static void storage_disconnect(struct usb_interface *iface);
118
119 /* The entries in this table, except for final ones here
120  * (USB_MASS_STORAGE_CLASS and the empty entry), correspond,
121  * line for line with the entries of us_unsuaul_dev_list[].
122  */
123
124 #define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
125                     vendorName, productName,useProtocol, useTransport, \
126                     initFunction, flags) \
127 { USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin,bcdDeviceMax) }
128
129 static struct usb_device_id storage_usb_ids [] = {
130
131 #       include "unusual_devs.h"
132 #undef UNUSUAL_DEV
133         /* Control/Bulk transport for all SubClass values */
134         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_CB) },
135         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_CB) },
136         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_CB) },
137         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_CB) },
138         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_CB) },
139         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_CB) },
140
141         /* Control/Bulk/Interrupt transport for all SubClass values */
142         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_CBI) },
143         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_CBI) },
144         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_CBI) },
145         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_CBI) },
146         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_CBI) },
147         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_CBI) },
148
149         /* Bulk-only transport for all SubClass values */
150         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_BULK) },
151         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_BULK) },
152         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_BULK) },
153         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_BULK) },
154         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_BULK) },
155         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
156
157         /* Terminating entry */
158         { }
159 };
160
161 MODULE_DEVICE_TABLE (usb, storage_usb_ids);
162
163 /* This is the list of devices we recognize, along with their flag data */
164
165 /* The vendor name should be kept at eight characters or less, and
166  * the product name should be kept at 16 characters or less. If a device
167  * has the US_FL_FIX_INQUIRY flag, then the vendor and product names
168  * normally generated by a device thorugh the INQUIRY response will be
169  * taken from this list, and this is the reason for the above size
170  * restriction. However, if the flag is not present, then you
171  * are free to use as many characters as you like.
172  */
173
174 #undef UNUSUAL_DEV
175 #define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
176                     vendor_name, product_name, use_protocol, use_transport, \
177                     init_function, Flags) \
178 { \
179         .vendorName = vendor_name,      \
180         .productName = product_name,    \
181         .useProtocol = use_protocol,    \
182         .useTransport = use_transport,  \
183         .initFunction = init_function,  \
184         .flags = Flags, \
185 }
186
187 static struct us_unusual_dev us_unusual_dev_list[] = {
188 #       include "unusual_devs.h" 
189 #       undef UNUSUAL_DEV
190         /* Control/Bulk transport for all SubClass values */
191         { .useProtocol = US_SC_RBC,
192           .useTransport = US_PR_CB},
193         { .useProtocol = US_SC_8020,
194           .useTransport = US_PR_CB},
195         { .useProtocol = US_SC_QIC,
196           .useTransport = US_PR_CB},
197         { .useProtocol = US_SC_UFI,
198           .useTransport = US_PR_CB},
199         { .useProtocol = US_SC_8070,
200           .useTransport = US_PR_CB},
201         { .useProtocol = US_SC_SCSI,
202           .useTransport = US_PR_CB},
203
204         /* Control/Bulk/Interrupt transport for all SubClass values */
205         { .useProtocol = US_SC_RBC,
206           .useTransport = US_PR_CBI},
207         { .useProtocol = US_SC_8020,
208           .useTransport = US_PR_CBI},
209         { .useProtocol = US_SC_QIC,
210           .useTransport = US_PR_CBI},
211         { .useProtocol = US_SC_UFI,
212           .useTransport = US_PR_CBI},
213         { .useProtocol = US_SC_8070,
214           .useTransport = US_PR_CBI},
215         { .useProtocol = US_SC_SCSI,
216           .useTransport = US_PR_CBI},
217
218         /* Bulk-only transport for all SubClass values */
219         { .useProtocol = US_SC_RBC,
220           .useTransport = US_PR_BULK},
221         { .useProtocol = US_SC_8020,
222           .useTransport = US_PR_BULK},
223         { .useProtocol = US_SC_QIC,
224           .useTransport = US_PR_BULK},
225         { .useProtocol = US_SC_UFI,
226           .useTransport = US_PR_BULK},
227         { .useProtocol = US_SC_8070,
228           .useTransport = US_PR_BULK},
229         { .useProtocol = US_SC_SCSI,
230           .useTransport = US_PR_BULK},
231
232         /* Terminating entry */
233         { NULL }
234 };
235
236 static struct usb_driver usb_storage_driver = {
237         .owner =        THIS_MODULE,
238         .name =         "usb-storage",
239         .probe =        storage_probe,
240         .disconnect =   storage_disconnect,
241         .id_table =     storage_usb_ids,
242 };
243
244 /*
245  * fill_inquiry_response takes an unsigned char array (which must
246  * be at least 36 characters) and populates the vendor name,
247  * product name, and revision fields. Then the array is copied
248  * into the SCSI command's response buffer (oddly enough
249  * called request_buffer). data_len contains the length of the
250  * data array, which again must be at least 36.
251  */
252
253 void fill_inquiry_response(struct us_data *us, unsigned char *data,
254                 unsigned int data_len)
255 {
256         if (data_len<36) // You lose.
257                 return;
258
259         if(data[0]&0x20) { /* USB device currently not connected. Return
260                               peripheral qualifier 001b ("...however, the
261                               physical device is not currently connected
262                               to this logical unit") and leave vendor and
263                               product identification empty. ("If the target
264                               does store some of the INQUIRY data on the
265                               device, it may return zeros or ASCII spaces 
266                               (20h) in those fields until the data is
267                               available from the device."). */
268                 memset(data+8,0,28);
269         } else {
270                 u16 bcdDevice = le16_to_cpu(us->pusb_dev->descriptor.bcdDevice);
271                 memcpy(data+8, us->unusual_dev->vendorName, 
272                         strlen(us->unusual_dev->vendorName) > 8 ? 8 :
273                         strlen(us->unusual_dev->vendorName));
274                 memcpy(data+16, us->unusual_dev->productName, 
275                         strlen(us->unusual_dev->productName) > 16 ? 16 :
276                         strlen(us->unusual_dev->productName));
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
286 static int usb_stor_control_thread(void * __us)
287 {
288         struct us_data *us = (struct us_data *)__us;
289         struct Scsi_Host *host = us_to_host(us);
290
291         lock_kernel();
292
293         /*
294          * This thread doesn't need any user-level access,
295          * so get rid of all our resources.
296          */
297         daemonize("usb-storage");
298         current->flags |= PF_NOFREEZE;
299         unlock_kernel();
300
301         /* acquire a reference to the host, so it won't be deallocated
302          * until we're ready to exit */
303         scsi_host_get(host);
304
305         /* signal that we've started the thread */
306         complete(&(us->notify));
307
308         for(;;) {
309                 US_DEBUGP("*** thread sleeping.\n");
310                 if(down_interruptible(&us->sema))
311                         break;
312                         
313                 US_DEBUGP("*** thread awakened.\n");
314
315                 /* lock the device pointers */
316                 down(&(us->dev_semaphore));
317
318                 /* if the device has disconnected, we are free to exit */
319                 if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
320                         US_DEBUGP("-- exiting\n");
321                         up(&(us->dev_semaphore));
322                         break;
323                 }
324
325                 /* lock access to the state */
326                 scsi_lock(host);
327
328                 /* has the command timed out *already* ? */
329                 if (test_bit(US_FLIDX_TIMED_OUT, &us->flags)) {
330                         us->srb->result = DID_ABORT << 16;
331                         goto SkipForAbort;
332                 }
333
334                 scsi_unlock(host);
335
336                 /* reject the command if the direction indicator 
337                  * is UNKNOWN
338                  */
339                 if (us->srb->sc_data_direction == DMA_BIDIRECTIONAL) {
340                         US_DEBUGP("UNKNOWN data direction\n");
341                         us->srb->result = DID_ERROR << 16;
342                 }
343
344                 /* reject if target != 0 or if LUN is higher than
345                  * the maximum known LUN
346                  */
347                 else if (us->srb->device->id && 
348                                 !(us->flags & US_FL_SCM_MULT_TARG)) {
349                         US_DEBUGP("Bad target number (%d:%d)\n",
350                                   us->srb->device->id, us->srb->device->lun);
351                         us->srb->result = DID_BAD_TARGET << 16;
352                 }
353
354                 else if (us->srb->device->lun > us->max_lun) {
355                         US_DEBUGP("Bad LUN (%d:%d)\n",
356                                   us->srb->device->id, us->srb->device->lun);
357                         us->srb->result = DID_BAD_TARGET << 16;
358                 }
359
360                 /* Handle those devices which need us to fake 
361                  * their inquiry data */
362                 else if ((us->srb->cmnd[0] == INQUIRY) &&
363                             (us->flags & US_FL_FIX_INQUIRY)) {
364                         unsigned char data_ptr[36] = {
365                             0x00, 0x80, 0x02, 0x02,
366                             0x1F, 0x00, 0x00, 0x00};
367
368                         US_DEBUGP("Faking INQUIRY command\n");
369                         fill_inquiry_response(us, data_ptr, 36);
370                         us->srb->result = SAM_STAT_GOOD;
371                 }
372
373                 /* we've got a command, let's do it! */
374                 else {
375                         US_DEBUG(usb_stor_show_command(us->srb));
376                         us->proto_handler(us->srb, us);
377                 }
378
379                 /* lock access to the state */
380                 scsi_lock(host);
381
382                 /* indicate that the command is done */
383                 if (us->srb->result != DID_ABORT << 16) {
384                         US_DEBUGP("scsi cmd done, result=0x%x\n", 
385                                    us->srb->result);
386                         us->srb->scsi_done(us->srb);
387                 } else {
388 SkipForAbort:
389                         US_DEBUGP("scsi command aborted\n");
390                 }
391
392                 /* If an abort request was received we need to signal that
393                  * the abort has finished.  The proper test for this is
394                  * the TIMED_OUT flag, not srb->result == DID_ABORT, because
395                  * the timeout might have occurred after the command had
396                  * already completed with a different result code. */
397                 if (test_bit(US_FLIDX_TIMED_OUT, &us->flags)) {
398                         complete(&(us->notify));
399
400                         /* Allow USB transfers to resume */
401                         clear_bit(US_FLIDX_ABORTING, &us->flags);
402                         clear_bit(US_FLIDX_TIMED_OUT, &us->flags);
403                 }
404
405                 /* finished working on this command */
406                 us->srb = NULL;
407                 scsi_unlock(host);
408
409                 /* unlock the device pointers */
410                 up(&(us->dev_semaphore));
411         } /* for (;;) */
412
413         scsi_host_put(host);
414
415         /* notify the exit routine that we're actually exiting now 
416          *
417          * complete()/wait_for_completion() is similar to up()/down(),
418          * except that complete() is safe in the case where the structure
419          * is getting deleted in a parallel mode of execution (i.e. just
420          * after the down() -- that's necessary for the thread-shutdown
421          * case.
422          *
423          * complete_and_exit() goes even further than this -- it is safe in
424          * the case that the thread of the caller is going away (not just
425          * the structure) -- this is necessary for the module-remove case.
426          * This is important in preemption kernels, which transfer the flow
427          * of execution immediately upon a complete().
428          */
429         complete_and_exit(&threads_gone, 0);
430 }       
431
432 /***********************************************************************
433  * Device probing and disconnecting
434  ***********************************************************************/
435
436 /* Associate our private data with the USB device */
437 static int associate_dev(struct us_data *us, struct usb_interface *intf)
438 {
439         US_DEBUGP("-- %s\n", __FUNCTION__);
440
441         /* Fill in the device-related fields */
442         us->pusb_dev = interface_to_usbdev(intf);
443         us->pusb_intf = intf;
444         us->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
445         US_DEBUGP("Vendor: 0x%04x, Product: 0x%04x, Revision: 0x%04x\n",
446                         le16_to_cpu(us->pusb_dev->descriptor.idVendor),
447                         le16_to_cpu(us->pusb_dev->descriptor.idProduct),
448                         le16_to_cpu(us->pusb_dev->descriptor.bcdDevice));
449         US_DEBUGP("Interface Subclass: 0x%02x, Protocol: 0x%02x\n",
450                         intf->cur_altsetting->desc.bInterfaceSubClass,
451                         intf->cur_altsetting->desc.bInterfaceProtocol);
452
453         /* Store our private data in the interface */
454         usb_set_intfdata(intf, us);
455
456         /* Allocate the device-related DMA-mapped buffers */
457         us->cr = usb_buffer_alloc(us->pusb_dev, sizeof(*us->cr),
458                         GFP_KERNEL, &us->cr_dma);
459         if (!us->cr) {
460                 US_DEBUGP("usb_ctrlrequest allocation failed\n");
461                 return -ENOMEM;
462         }
463
464         us->iobuf = usb_buffer_alloc(us->pusb_dev, US_IOBUF_SIZE,
465                         GFP_KERNEL, &us->iobuf_dma);
466         if (!us->iobuf) {
467                 US_DEBUGP("I/O buffer allocation failed\n");
468                 return -ENOMEM;
469         }
470         return 0;
471 }
472
473 /* Get the unusual_devs entries and the string descriptors */
474 static void get_device_info(struct us_data *us, int id_index)
475 {
476         struct usb_device *dev = us->pusb_dev;
477         struct usb_interface_descriptor *idesc =
478                 &us->pusb_intf->cur_altsetting->desc;
479         struct us_unusual_dev *unusual_dev = &us_unusual_dev_list[id_index];
480         struct usb_device_id *id = &storage_usb_ids[id_index];
481
482         /* Store the entries */
483         us->unusual_dev = unusual_dev;
484         us->subclass = (unusual_dev->useProtocol == US_SC_DEVICE) ?
485                         idesc->bInterfaceSubClass :
486                         unusual_dev->useProtocol;
487         us->protocol = (unusual_dev->useTransport == US_PR_DEVICE) ?
488                         idesc->bInterfaceProtocol :
489                         unusual_dev->useTransport;
490         us->flags = unusual_dev->flags;
491
492         /*
493          * This flag is only needed when we're in high-speed, so let's
494          * disable it if we're in full-speed
495          */
496         if (dev->speed != USB_SPEED_HIGH)
497                 us->flags &= ~US_FL_GO_SLOW;
498
499         /* Log a message if a non-generic unusual_dev entry contains an
500          * unnecessary subclass or protocol override.  This may stimulate
501          * reports from users that will help us remove unneeded entries
502          * from the unusual_devs.h table.
503          */
504         if (id->idVendor || id->idProduct) {
505                 static char *msgs[3] = {
506                         "an unneeded SubClass entry",
507                         "an unneeded Protocol entry",
508                         "unneeded SubClass and Protocol entries"};
509                 struct usb_device_descriptor *ddesc = &dev->descriptor;
510                 int msg = -1;
511
512                 if (unusual_dev->useProtocol != US_SC_DEVICE &&
513                         us->subclass == idesc->bInterfaceSubClass)
514                         msg += 1;
515                 if (unusual_dev->useTransport != US_PR_DEVICE &&
516                         us->protocol == idesc->bInterfaceProtocol)
517                         msg += 2;
518                 if (msg >= 0 && !(unusual_dev->flags & US_FL_NEED_OVERRIDE))
519                         printk(KERN_NOTICE USB_STORAGE "This device "
520                                 "(%04x,%04x,%04x S %02x P %02x)"
521                                 " has %s in unusual_devs.h\n"
522                                 "   Please send a copy of this message to "
523                                 "<linux-usb-devel@lists.sourceforge.net>\n",
524                                 le16_to_cpu(ddesc->idVendor),
525                                 le16_to_cpu(ddesc->idProduct),
526                                 le16_to_cpu(ddesc->bcdDevice),
527                                 idesc->bInterfaceSubClass,
528                                 idesc->bInterfaceProtocol,
529                                 msgs[msg]);
530         }
531 }
532
533 /* Get the transport settings */
534 static int get_transport(struct us_data *us)
535 {
536         switch (us->protocol) {
537         case US_PR_CB:
538                 us->transport_name = "Control/Bulk";
539                 us->transport = usb_stor_CB_transport;
540                 us->transport_reset = usb_stor_CB_reset;
541                 us->max_lun = 7;
542                 break;
543
544         case US_PR_CBI:
545                 us->transport_name = "Control/Bulk/Interrupt";
546                 us->transport = usb_stor_CBI_transport;
547                 us->transport_reset = usb_stor_CB_reset;
548                 us->max_lun = 7;
549                 break;
550
551         case US_PR_BULK:
552                 us->transport_name = "Bulk";
553                 us->transport = usb_stor_Bulk_transport;
554                 us->transport_reset = usb_stor_Bulk_reset;
555                 break;
556
557 #ifdef CONFIG_USB_STORAGE_USBAT
558         case US_PR_USBAT:
559                 us->transport_name = "Shuttle USBAT";
560                 us->transport = usbat_transport;
561                 us->transport_reset = usb_stor_CB_reset;
562                 us->max_lun = 1;
563                 break;
564 #endif
565
566 #ifdef CONFIG_USB_STORAGE_SDDR09
567         case US_PR_EUSB_SDDR09:
568                 us->transport_name = "EUSB/SDDR09";
569                 us->transport = sddr09_transport;
570                 us->transport_reset = usb_stor_CB_reset;
571                 us->max_lun = 0;
572                 break;
573 #endif
574
575 #ifdef CONFIG_USB_STORAGE_SDDR55
576         case US_PR_SDDR55:
577                 us->transport_name = "SDDR55";
578                 us->transport = sddr55_transport;
579                 us->transport_reset = sddr55_reset;
580                 us->max_lun = 0;
581                 break;
582 #endif
583
584 #ifdef CONFIG_USB_STORAGE_DPCM
585         case US_PR_DPCM_USB:
586                 us->transport_name = "Control/Bulk-EUSB/SDDR09";
587                 us->transport = dpcm_transport;
588                 us->transport_reset = usb_stor_CB_reset;
589                 us->max_lun = 1;
590                 break;
591 #endif
592
593 #ifdef CONFIG_USB_STORAGE_FREECOM
594         case US_PR_FREECOM:
595                 us->transport_name = "Freecom";
596                 us->transport = freecom_transport;
597                 us->transport_reset = usb_stor_freecom_reset;
598                 us->max_lun = 0;
599                 break;
600 #endif
601
602 #ifdef CONFIG_USB_STORAGE_DATAFAB
603         case US_PR_DATAFAB:
604                 us->transport_name  = "Datafab Bulk-Only";
605                 us->transport = datafab_transport;
606                 us->transport_reset = usb_stor_Bulk_reset;
607                 us->max_lun = 1;
608                 break;
609 #endif
610
611 #ifdef CONFIG_USB_STORAGE_JUMPSHOT
612         case US_PR_JUMPSHOT:
613                 us->transport_name  = "Lexar Jumpshot Control/Bulk";
614                 us->transport = jumpshot_transport;
615                 us->transport_reset = usb_stor_Bulk_reset;
616                 us->max_lun = 1;
617                 break;
618 #endif
619
620         default:
621                 return -EIO;
622         }
623         US_DEBUGP("Transport: %s\n", us->transport_name);
624
625         /* fix for single-lun devices */
626         if (us->flags & US_FL_SINGLE_LUN)
627                 us->max_lun = 0;
628         return 0;
629 }
630
631 /* Get the protocol settings */
632 static int get_protocol(struct us_data *us)
633 {
634         switch (us->subclass) {
635         case US_SC_RBC:
636                 us->protocol_name = "Reduced Block Commands (RBC)";
637                 us->proto_handler = usb_stor_transparent_scsi_command;
638                 break;
639
640         case US_SC_8020:
641                 us->protocol_name = "8020i";
642                 us->proto_handler = usb_stor_ATAPI_command;
643                 us->max_lun = 0;
644                 break;
645
646         case US_SC_QIC:
647                 us->protocol_name = "QIC-157";
648                 us->proto_handler = usb_stor_qic157_command;
649                 us->max_lun = 0;
650                 break;
651
652         case US_SC_8070:
653                 us->protocol_name = "8070i";
654                 us->proto_handler = usb_stor_ATAPI_command;
655                 us->max_lun = 0;
656                 break;
657
658         case US_SC_SCSI:
659                 us->protocol_name = "Transparent SCSI";
660                 us->proto_handler = usb_stor_transparent_scsi_command;
661                 break;
662
663         case US_SC_UFI:
664                 us->protocol_name = "Uniform Floppy Interface (UFI)";
665                 us->proto_handler = usb_stor_ufi_command;
666                 break;
667
668 #ifdef CONFIG_USB_STORAGE_ISD200
669         case US_SC_ISD200:
670                 us->protocol_name = "ISD200 ATA/ATAPI";
671                 us->proto_handler = isd200_ata_command;
672                 break;
673 #endif
674
675         default:
676                 return -EIO;
677         }
678         US_DEBUGP("Protocol: %s\n", us->protocol_name);
679         return 0;
680 }
681
682 /* Get the pipe settings */
683 static int get_pipes(struct us_data *us)
684 {
685         struct usb_host_interface *altsetting =
686                 us->pusb_intf->cur_altsetting;
687         int i;
688         struct usb_endpoint_descriptor *ep;
689         struct usb_endpoint_descriptor *ep_in = NULL;
690         struct usb_endpoint_descriptor *ep_out = NULL;
691         struct usb_endpoint_descriptor *ep_int = NULL;
692
693         /*
694          * Find the endpoints we need.
695          * We are expecting a minimum of 2 endpoints - in and out (bulk).
696          * An optional interrupt is OK (necessary for CBI protocol).
697          * We will ignore any others.
698          */
699         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
700                 ep = &altsetting->endpoint[i].desc;
701
702                 /* Is it a BULK endpoint? */
703                 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
704                                 == USB_ENDPOINT_XFER_BULK) {
705                         /* BULK in or out? */
706                         if (ep->bEndpointAddress & USB_DIR_IN)
707                                 ep_in = ep;
708                         else
709                                 ep_out = ep;
710                 }
711
712                 /* Is it an interrupt endpoint? */
713                 else if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
714                                 == USB_ENDPOINT_XFER_INT) {
715                         ep_int = ep;
716                 }
717         }
718
719         if (!ep_in || !ep_out || (us->protocol == US_PR_CBI && !ep_int)) {
720                 US_DEBUGP("Endpoint sanity check failed! Rejecting dev.\n");
721                 return -EIO;
722         }
723
724         /* Calculate and store the pipe values */
725         us->send_ctrl_pipe = usb_sndctrlpipe(us->pusb_dev, 0);
726         us->recv_ctrl_pipe = usb_rcvctrlpipe(us->pusb_dev, 0);
727         us->send_bulk_pipe = usb_sndbulkpipe(us->pusb_dev,
728                 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
729         us->recv_bulk_pipe = usb_rcvbulkpipe(us->pusb_dev, 
730                 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
731         if (ep_int) {
732                 us->recv_intr_pipe = usb_rcvintpipe(us->pusb_dev,
733                         ep_int->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
734                 us->ep_bInterval = ep_int->bInterval;
735         }
736         return 0;
737 }
738
739 /* Initialize all the dynamic resources we need */
740 static int usb_stor_acquire_resources(struct us_data *us)
741 {
742         int p;
743
744         us->current_urb = usb_alloc_urb(0, GFP_KERNEL);
745         if (!us->current_urb) {
746                 US_DEBUGP("URB allocation failed\n");
747                 return -ENOMEM;
748         }
749
750         /* Just before we start our control thread, initialize
751          * the device if it needs initialization */
752         if (us->unusual_dev->initFunction) {
753                 p = us->unusual_dev->initFunction(us);
754                 if (p)
755                         return p;
756         }
757
758         /* Start up our control thread */
759         p = kernel_thread(usb_stor_control_thread, us, CLONE_VM);
760         if (p < 0) {
761                 printk(KERN_WARNING USB_STORAGE 
762                        "Unable to start control thread\n");
763                 return p;
764         }
765         us->pid = p;
766         atomic_inc(&total_threads);
767
768         /* Wait for the thread to start */
769         wait_for_completion(&(us->notify));
770
771         return 0;
772 }
773
774 /* Release all our dynamic resources */
775 static void usb_stor_release_resources(struct us_data *us)
776 {
777         US_DEBUGP("-- %s\n", __FUNCTION__);
778
779         /* Tell the control thread to exit.  The SCSI host must
780          * already have been removed so it won't try to queue
781          * any more commands.
782          */
783         US_DEBUGP("-- sending exit command to thread\n");
784         set_bit(US_FLIDX_DISCONNECTING, &us->flags);
785         up(&us->sema);
786
787         /* Call the destructor routine, if it exists */
788         if (us->extra_destructor) {
789                 US_DEBUGP("-- calling extra_destructor()\n");
790                 us->extra_destructor(us->extra);
791         }
792
793         /* Free the extra data and the URB */
794         kfree(us->extra);
795         usb_free_urb(us->current_urb);
796 }
797
798 /* Dissociate from the USB device */
799 static void dissociate_dev(struct us_data *us)
800 {
801         US_DEBUGP("-- %s\n", __FUNCTION__);
802
803         /* Free the device-related DMA-mapped buffers */
804         if (us->cr)
805                 usb_buffer_free(us->pusb_dev, sizeof(*us->cr), us->cr,
806                                 us->cr_dma);
807         if (us->iobuf)
808                 usb_buffer_free(us->pusb_dev, US_IOBUF_SIZE, us->iobuf,
809                                 us->iobuf_dma);
810
811         /* Remove our private data from the interface */
812         usb_set_intfdata(us->pusb_intf, NULL);
813 }
814
815 /* First stage of disconnect processing: stop all commands and remove
816  * the host */
817 static void quiesce_and_remove_host(struct us_data *us)
818 {
819         /* Prevent new USB transfers, stop the current command, and
820          * interrupt a SCSI-scan or device-reset delay */
821         set_bit(US_FLIDX_DISCONNECTING, &us->flags);
822         usb_stor_stop_transport(us);
823         wake_up(&us->delay_wait);
824
825         /* It doesn't matter if the SCSI-scanning thread is still running.
826          * The thread will exit when it sees the DISCONNECTING flag. */
827
828         /* Wait for the current command to finish, then remove the host */
829         down(&us->dev_semaphore);
830         up(&us->dev_semaphore);
831
832         /* queuecommand won't accept any new commands and the control
833          * thread won't execute a previously-queued command.  If there
834          * is such a command pending, complete it with an error. */
835         if (us->srb) {
836                 us->srb->result = DID_NO_CONNECT << 16;
837                 scsi_lock(us_to_host(us));
838                 us->srb->scsi_done(us->srb);
839                 us->srb = NULL;
840                 scsi_unlock(us_to_host(us));
841         }
842
843         /* Now we own no commands so it's safe to remove the SCSI host */
844         scsi_remove_host(us_to_host(us));
845 }
846
847 /* Second stage of disconnect processing: deallocate all resources */
848 static void release_everything(struct us_data *us)
849 {
850         usb_stor_release_resources(us);
851         dissociate_dev(us);
852
853         /* Drop our reference to the host; the SCSI core will free it
854          * (and "us" along with it) when the refcount becomes 0. */
855         scsi_host_put(us_to_host(us));
856 }
857
858 /* Thread to carry out delayed SCSI-device scanning */
859 static int usb_stor_scan_thread(void * __us)
860 {
861         struct us_data *us = (struct us_data *)__us;
862
863         /*
864          * This thread doesn't need any user-level access,
865          * so get rid of all our resources.
866          */
867         lock_kernel();
868         daemonize("usb-stor-scan");
869         unlock_kernel();
870
871         /* Acquire a reference to the host, so it won't be deallocated
872          * until we're ready to exit */
873         scsi_host_get(us_to_host(us));
874
875         /* Signal that we've started the thread */
876         complete(&(us->notify));
877
878         printk(KERN_DEBUG
879                 "usb-storage: device found at %d\n", us->pusb_dev->devnum);
880
881         /* Wait for the timeout to expire or for a disconnect */
882         if (delay_use > 0) {
883                 printk(KERN_DEBUG "usb-storage: waiting for device "
884                                 "to settle before scanning\n");
885 retry:
886                 wait_event_interruptible_timeout(us->delay_wait,
887                                 test_bit(US_FLIDX_DISCONNECTING, &us->flags),
888                                 delay_use * HZ);
889                 if (try_to_freeze())
890                         goto retry;
891         }
892
893         /* If the device is still connected, perform the scanning */
894         if (!test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
895
896                 /* For bulk-only devices, determine the max LUN value */
897                 if (us->protocol == US_PR_BULK &&
898                                 !(us->flags & US_FL_SINGLE_LUN)) {
899                         down(&us->dev_semaphore);
900                         us->max_lun = usb_stor_Bulk_max_lun(us);
901                         up(&us->dev_semaphore);
902                 }
903                 scsi_scan_host(us_to_host(us));
904                 printk(KERN_DEBUG "usb-storage: device scan complete\n");
905
906                 /* Should we unbind if no devices were detected? */
907         }
908
909         scsi_host_put(us_to_host(us));
910         complete_and_exit(&threads_gone, 0);
911 }
912
913
914 /* Probe to see if we can drive a newly-connected USB device */
915 static int storage_probe(struct usb_interface *intf,
916                          const struct usb_device_id *id)
917 {
918         struct Scsi_Host *host;
919         struct us_data *us;
920         const int id_index = id - storage_usb_ids; 
921         int result;
922
923         US_DEBUGP("USB Mass Storage device detected\n");
924
925         /*
926          * Ask the SCSI layer to allocate a host structure, with extra
927          * space at the end for our private us_data structure.
928          */
929         host = scsi_host_alloc(&usb_stor_host_template, sizeof(*us));
930         if (!host) {
931                 printk(KERN_WARNING USB_STORAGE
932                         "Unable to allocate the scsi host\n");
933                 return -ENOMEM;
934         }
935
936         us = host_to_us(host);
937         memset(us, 0, sizeof(struct us_data));
938         init_MUTEX(&(us->dev_semaphore));
939         init_MUTEX_LOCKED(&(us->sema));
940         init_completion(&(us->notify));
941         init_waitqueue_head(&us->delay_wait);
942
943         /* Associate the us_data structure with the USB device */
944         result = associate_dev(us, intf);
945         if (result)
946                 goto BadDevice;
947
948         /*
949          * Get the unusual_devs entries and the descriptors
950          *
951          * id_index is calculated in the declaration to be the index number
952          * of the match from the usb_device_id table, so we can find the
953          * corresponding entry in the private table.
954          */
955         get_device_info(us, id_index);
956
957 #ifdef CONFIG_USB_STORAGE_SDDR09
958         if (us->protocol == US_PR_EUSB_SDDR09 ||
959                         us->protocol == US_PR_DPCM_USB) {
960                 /* set the configuration -- STALL is an acceptable response here */
961                 if (us->pusb_dev->actconfig->desc.bConfigurationValue != 1) {
962                         US_DEBUGP("active config #%d != 1 ??\n", us->pusb_dev
963                                 ->actconfig->desc.bConfigurationValue);
964                         goto BadDevice;
965                 }
966                 result = usb_reset_configuration(us->pusb_dev);
967
968                 US_DEBUGP("Result of usb_reset_configuration is %d\n", result);
969                 if (result == -EPIPE) {
970                         US_DEBUGP("-- stall on control interface\n");
971                 } else if (result != 0) {
972                         /* it's not a stall, but another error -- time to bail */
973                         US_DEBUGP("-- Unknown error.  Rejecting device\n");
974                         goto BadDevice;
975                 }
976         }
977 #endif
978
979         /* Get the transport, protocol, and pipe settings */
980         result = get_transport(us);
981         if (result)
982                 goto BadDevice;
983         result = get_protocol(us);
984         if (result)
985                 goto BadDevice;
986         result = get_pipes(us);
987         if (result)
988                 goto BadDevice;
989
990         /* Acquire all the other resources and add the host */
991         result = usb_stor_acquire_resources(us);
992         if (result)
993                 goto BadDevice;
994         result = scsi_add_host(host, &intf->dev);
995         if (result) {
996                 printk(KERN_WARNING USB_STORAGE
997                         "Unable to add the scsi host\n");
998                 goto BadDevice;
999         }
1000
1001         /* Start up the thread for delayed SCSI-device scanning */
1002         result = kernel_thread(usb_stor_scan_thread, us, CLONE_VM);
1003         if (result < 0) {
1004                 printk(KERN_WARNING USB_STORAGE 
1005                        "Unable to start the device-scanning thread\n");
1006                 quiesce_and_remove_host(us);
1007                 goto BadDevice;
1008         }
1009         atomic_inc(&total_threads);
1010
1011         /* Wait for the thread to start */
1012         wait_for_completion(&(us->notify));
1013
1014         return 0;
1015
1016         /* We come here if there are any problems */
1017 BadDevice:
1018         US_DEBUGP("storage_probe() failed\n");
1019         release_everything(us);
1020         return result;
1021 }
1022
1023 /* Handle a disconnect event from the USB core */
1024 static void storage_disconnect(struct usb_interface *intf)
1025 {
1026         struct us_data *us = usb_get_intfdata(intf);
1027
1028         US_DEBUGP("storage_disconnect() called\n");
1029         quiesce_and_remove_host(us);
1030         release_everything(us);
1031 }
1032
1033 /***********************************************************************
1034  * Initialization and registration
1035  ***********************************************************************/
1036
1037 static int __init usb_stor_init(void)
1038 {
1039         int retval;
1040         printk(KERN_INFO "Initializing USB Mass Storage driver...\n");
1041
1042         /* register the driver, return usb_register return code if error */
1043         retval = usb_register(&usb_storage_driver);
1044         if (retval == 0)
1045                 printk(KERN_INFO "USB Mass Storage support registered.\n");
1046
1047         return retval;
1048 }
1049
1050 static void __exit usb_stor_exit(void)
1051 {
1052         US_DEBUGP("usb_stor_exit() called\n");
1053
1054         /* Deregister the driver
1055          * This will cause disconnect() to be called for each
1056          * attached unit
1057          */
1058         US_DEBUGP("-- calling usb_deregister()\n");
1059         usb_deregister(&usb_storage_driver) ;
1060
1061         /* Don't return until all of our control and scanning threads
1062          * have exited.  Since each thread signals threads_gone as its
1063          * last act, we have to call wait_for_completion the right number
1064          * of times.
1065          */
1066         while (atomic_read(&total_threads) > 0) {
1067                 wait_for_completion(&threads_gone);
1068                 atomic_dec(&total_threads);
1069         }
1070 }
1071
1072 module_init(usb_stor_init);
1073 module_exit(usb_stor_exit);