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