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