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