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