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