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