v2.4.9.9 -> v2.4.9.10
[opensuse:kernel.git] / drivers / usb / storage / usb.c
1 /* Driver for USB Mass Storage compliant devices
2  *
3  * $Id: usb.c,v 1.67 2001/07/29 23:41:52 mdharm Exp $
4  *
5  * Current development and maintenance by:
6  *   (c) 1999, 2000 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  *
11  * Initial work by:
12  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
13  *
14  * usb_device_id support by Adam J. Richter (adam@yggdrasil.com):
15  *   (c) 2000 Yggdrasil Computing, Inc.
16  *
17  * This driver is based on the 'USB Mass Storage Class' document. This
18  * describes in detail the protocol used to communicate with such
19  * devices.  Clearly, the designers had SCSI and ATAPI commands in
20  * mind when they created this document.  The commands are all very
21  * similar to commands in the SCSI-II and ATAPI specifications.
22  *
23  * It is important to note that in a number of cases this class
24  * exhibits class-specific exemptions from the USB specification.
25  * Notably the usage of NAK, STALL and ACK differs from the norm, in
26  * that they are used to communicate wait, failed and OK on commands.
27  *
28  * Also, for certain devices, the interrupt endpoint is used to convey
29  * status of a command.
30  *
31  * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
32  * information about this driver.
33  *
34  * This program is free software; you can redistribute it and/or modify it
35  * under the terms of the GNU General Public License as published by the
36  * Free Software Foundation; either version 2, or (at your option) any
37  * later version.
38  *
39  * This program is distributed in the hope that it will be useful, but
40  * WITHOUT ANY WARRANTY; without even the implied warranty of
41  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
42  * General Public License for more details.
43  *
44  * You should have received a copy of the GNU General Public License along
45  * with this program; if not, write to the Free Software Foundation, Inc.,
46  * 675 Mass Ave, Cambridge, MA 02139, USA.
47  */
48
49 #include <linux/config.h>
50 #include "usb.h"
51 #include "scsiglue.h"
52 #include "transport.h"
53 #include "protocol.h"
54 #include "debug.h"
55 #include "initializers.h"
56
57 #ifdef CONFIG_USB_STORAGE_HP8200e
58 #include "shuttle_usbat.h"
59 #endif
60 #ifdef CONFIG_USB_STORAGE_SDDR09
61 #include "sddr09.h"
62 #endif
63 #ifdef CONFIG_USB_STORAGE_DPCM
64 #include "dpcm.h"
65 #endif
66 #ifdef CONFIG_USB_STORAGE_FREECOM
67 #include "freecom.h"
68 #endif
69 #ifdef CONFIG_USB_STORAGE_ISD200
70 #include "isd200.h"
71 #endif
72 #ifdef CONFIG_USB_STORAGE_DATAFAB
73 #include "datafab.h"
74 #endif
75 #ifdef CONFIG_USB_STORAGE_JUMPSHOT
76 #include "jumpshot.h"
77 #endif
78
79
80 #include <linux/module.h>
81 #include <linux/sched.h>
82 #include <linux/errno.h>
83 #include <linux/init.h>
84 #include <linux/slab.h>
85
86 /* Some informational data */
87 MODULE_AUTHOR("Matthew Dharm <mdharm-usb@one-eyed-alien.net>");
88 MODULE_DESCRIPTION("USB Mass Storage driver for Linux");
89 MODULE_LICENSE("GPL");
90
91 /*
92  * Per device data
93  */
94
95 static int my_host_number;
96
97 /*
98  * kernel thread actions
99  */
100
101 #define US_ACT_COMMAND          1
102 #define US_ACT_DEVICE_RESET     2
103 #define US_ACT_BUS_RESET        3
104 #define US_ACT_HOST_RESET       4
105 #define US_ACT_EXIT             5
106
107 /* The list of structures and the protective lock for them */
108 struct us_data *us_list;
109 struct semaphore us_list_semaphore;
110
111 static void * storage_probe(struct usb_device *dev, unsigned int ifnum,
112                             const struct usb_device_id *id);
113
114 static void storage_disconnect(struct usb_device *dev, void *ptr);
115
116 /* The entries in this table, except for final ones here
117  * (USB_MASS_STORAGE_CLASS and the empty entry), correspond,
118  * line for line with the entries of us_unsuaul_dev_list[].
119  * For now, we duplicate idVendor and idProduct in us_unsual_dev_list,
120  * just to avoid alignment bugs.
121  */
122
123 #define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
124                     vendorName, productName,useProtocol, useTransport, \
125                     initFunction, flags) \
126 { USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin,bcdDeviceMax) }
127
128 static struct usb_device_id storage_usb_ids [] = {
129
130 #       include "unusual_devs.h"
131 #undef UNUSUAL_DEV
132         /* Control/Bulk transport for all SubClass values */
133         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_CB) },
134         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_CB) },
135         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_CB) },
136         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_CB) },
137         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_CB) },
138         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_CB) },
139
140         /* Control/Bulk/Interrupt transport for all SubClass values */
141         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_CBI) },
142         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_CBI) },
143         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_CBI) },
144         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_CBI) },
145         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_CBI) },
146         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_CBI) },
147
148         /* Bulk-only transport for all SubClass values */
149         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_RBC, US_PR_BULK) },
150         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8020, US_PR_BULK) },
151         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_QIC, US_PR_BULK) },
152         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_UFI, US_PR_BULK) },
153         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_8070, US_PR_BULK) },
154         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
155
156         /* Terminating entry */
157         { }
158 };
159
160 MODULE_DEVICE_TABLE (usb, storage_usb_ids);
161
162 /* This is the list of devices we recognize, along with their flag data */
163
164 /* The vendor name should be kept at eight characters or less, and
165  * the product name should be kept at 16 characters or less. If a device
166  * has the US_FL_FIX_INQUIRY flag, then the vendor and product names
167  * normally generated by a device thorugh the INQUIRY response will be
168  * taken from this list, and this is the reason for the above size
169  * restriction. However, if the flag is not present, then you
170  * are free to use as many characters as you like.
171  */
172
173 #undef UNUSUAL_DEV
174 #define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
175                     vendor_name, product_name, use_protocol, use_transport, \
176                     init_function, Flags) \
177 { \
178         vendorName: vendor_name,        \
179         productName: product_name,      \
180         useProtocol: use_protocol,      \
181         useTransport: use_transport,    \
182         initFunction : init_function,   \
183         flags: Flags, \
184 }
185
186 static struct us_unusual_dev us_unusual_dev_list[] = {
187 #       include "unusual_devs.h" 
188 #       undef UNUSUAL_DEV
189         /* Control/Bulk transport for all SubClass values */
190         { useProtocol: US_SC_RBC,
191           useTransport: US_PR_CB},
192         { useProtocol: US_SC_8020,
193           useTransport: US_PR_CB},
194         { useProtocol: US_SC_QIC,
195           useTransport: US_PR_CB},
196         { useProtocol: US_SC_UFI,
197           useTransport: US_PR_CB},
198         { useProtocol: US_SC_8070,
199           useTransport: US_PR_CB},
200         { useProtocol: US_SC_SCSI,
201           useTransport: US_PR_CB},
202
203         /* Control/Bulk/Interrupt transport for all SubClass values */
204         { useProtocol: US_SC_RBC,
205           useTransport: US_PR_CBI},
206         { useProtocol: US_SC_8020,
207           useTransport: US_PR_CBI},
208         { useProtocol: US_SC_QIC,
209           useTransport: US_PR_CBI},
210         { useProtocol: US_SC_UFI,
211           useTransport: US_PR_CBI},
212         { useProtocol: US_SC_8070,
213           useTransport: US_PR_CBI},
214         { useProtocol: US_SC_SCSI,
215           useTransport: US_PR_CBI},
216
217         /* Bulk-only transport for all SubClass values */
218         { useProtocol: US_SC_RBC,
219           useTransport: US_PR_BULK},
220         { useProtocol: US_SC_8020,
221           useTransport: US_PR_BULK},
222         { useProtocol: US_SC_QIC,
223           useTransport: US_PR_BULK},
224         { useProtocol: US_SC_UFI,
225           useTransport: US_PR_BULK},
226         { useProtocol: US_SC_8070,
227           useTransport: US_PR_BULK},
228         { useProtocol: US_SC_SCSI,
229           useTransport: US_PR_BULK},
230
231         /* Terminating entry */
232         { 0 }
233 };
234
235 struct usb_driver usb_storage_driver = {
236         name:           "usb-storage",
237         probe:          storage_probe,
238         disconnect:     storage_disconnect,
239         id_table:       storage_usb_ids,
240 };
241
242 /*
243  * fill_inquiry_response takes an unsigned char array (which must
244  * be at least 36 characters) and populates the vendor name,
245  * product name, and revision fields. Then the array is copied
246  * into the SCSI command's response buffer (oddly enough
247  * called request_buffer). data_len contains the length of the
248  * data array, which again must be at least 36.
249  */
250
251 void fill_inquiry_response(struct us_data *us, unsigned char *data,
252                 unsigned int data_len) {
253
254         int i;
255         struct scatterlist *sg;
256         int len =
257                 us->srb->request_bufflen > data_len ? data_len :
258                 us->srb->request_bufflen;
259         int transferred;
260         int amt;
261
262         if (data_len<36) // You lose.
263                 return;
264
265         memcpy(data+8, us->unusual_dev->vendorName, 
266                 strlen(us->unusual_dev->vendorName) > 8 ? 8 :
267                 strlen(us->unusual_dev->vendorName));
268         memcpy(data+16, us->unusual_dev->productName, 
269                 strlen(us->unusual_dev->productName) > 16 ? 16 :
270                 strlen(us->unusual_dev->productName));
271         data[32] = 0x30 + ((us->pusb_dev->descriptor.bcdDevice>>12) & 0x0F);
272         data[33] = 0x30 + ((us->pusb_dev->descriptor.bcdDevice>>8) & 0x0F);
273         data[34] = 0x30 + ((us->pusb_dev->descriptor.bcdDevice>>4) & 0x0F);
274         data[35] = 0x30 + ((us->pusb_dev->descriptor.bcdDevice) & 0x0F);
275
276         if (us->srb->use_sg) {
277                 sg = (struct scatterlist *)us->srb->request_buffer;
278                 for (i=0; i<us->srb->use_sg; i++)
279                         memset(sg[i].address, 0, sg[i].length);
280                 for (i=0, transferred=0; 
281                                 i<us->srb->use_sg && transferred < len;
282                                 i++) {
283                         amt = sg[i].length > len-transferred ? 
284                                         len-transferred : sg[i].length;
285                         memcpy(sg[i].address, data+transferred, amt);
286                         transferred -= amt;
287                 }
288         } else {
289                 memset(us->srb->request_buffer, 0, us->srb->request_bufflen);
290                 memcpy(us->srb->request_buffer, data, len);
291         }
292 }
293
294 static int usb_stor_control_thread(void * __us)
295 {
296         struct us_data *us = (struct us_data *)__us;
297         int action;
298
299         lock_kernel();
300
301         /*
302          * This thread doesn't need any user-level access,
303          * so get rid of all our resources..
304          */
305         exit_files(current);
306         current->files = init_task.files;
307         atomic_inc(&current->files->count);
308         daemonize();
309
310         /* set our name for identification purposes */
311         sprintf(current->comm, "usb-storage-%d", us->host_number);
312
313         unlock_kernel();
314
315         /* set up for wakeups by new commands */
316         init_MUTEX_LOCKED(&us->sema);
317
318         /* signal that we've started the thread */
319         complete(&(us->notify));
320         set_current_state(TASK_INTERRUPTIBLE);
321
322         for(;;) {
323                 US_DEBUGP("*** thread sleeping.\n");
324                 if(down_interruptible(&us->sema))
325                         break;
326                         
327                 US_DEBUGP("*** thread awakened.\n");
328
329                 /* lock access to the queue element */
330                 down(&(us->queue_exclusion));
331
332                 /* take the command off the queue */
333                 action = us->action;
334                 us->action = 0;
335                 us->srb = us->queue_srb;
336
337                 /* release the queue lock as fast as possible */
338                 up(&(us->queue_exclusion));
339
340                 switch (action) {
341                 case US_ACT_COMMAND:
342                         /* reject the command if the direction indicator 
343                          * is UNKNOWN
344                          */
345                         if (us->srb->sc_data_direction == SCSI_DATA_UNKNOWN) {
346                                 US_DEBUGP("UNKNOWN data direction\n");
347                                 us->srb->result = DID_ERROR << 16;
348                                 set_current_state(TASK_INTERRUPTIBLE);
349                                 us->srb->scsi_done(us->srb);
350                                 us->srb = NULL;
351                                 break;
352                         }
353
354                         /* reject if target != 0 or if LUN is higher than
355                          * the maximum known LUN
356                          */
357                         if (us->srb->target && 
358                                         !(us->flags & US_FL_SCM_MULT_TARG)) {
359                                 US_DEBUGP("Bad target number (%d/%d)\n",
360                                           us->srb->target, us->srb->lun);
361                                 us->srb->result = DID_BAD_TARGET << 16;
362
363                                 set_current_state(TASK_INTERRUPTIBLE);
364                                 us->srb->scsi_done(us->srb);
365                                 us->srb = NULL;
366                                 break;
367                         }
368
369                         if (us->srb->lun > us->max_lun) {
370                                 US_DEBUGP("Bad LUN (%d/%d)\n",
371                                           us->srb->target, us->srb->lun);
372                                 us->srb->result = DID_BAD_TARGET << 16;
373
374                                 set_current_state(TASK_INTERRUPTIBLE);
375                                 us->srb->scsi_done(us->srb);
376                                 us->srb = NULL;
377                                 break;
378                         }
379
380                         /* handle those devices which can't do a START_STOP */
381                         if ((us->srb->cmnd[0] == START_STOP) &&
382                             (us->flags & US_FL_START_STOP)) {
383                                 US_DEBUGP("Skipping START_STOP command\n");
384                                 us->srb->result = GOOD << 1;
385
386                                 set_current_state(TASK_INTERRUPTIBLE);
387                                 us->srb->scsi_done(us->srb);
388                                 us->srb = NULL;
389                                 break;
390                         }
391
392                         /* Handle those devices which need us to fake their
393                          * inquiry data */
394                         if ((us->srb->cmnd[0] == INQUIRY) &&
395                             (us->flags & US_FL_FIX_INQUIRY)) {
396                                 unsigned char data_ptr[36] = {
397                                     0x00, 0x80, 0x02, 0x02,
398                                     0x1F, 0x00, 0x00, 0x00};
399
400                                 US_DEBUGP("Faking INQUIRY command\n");
401                                 fill_inquiry_response(us, data_ptr, 36);
402                                 us->srb->result = GOOD << 1;
403
404                                 set_current_state(TASK_INTERRUPTIBLE);
405                                 us->srb->scsi_done(us->srb);
406                                 us->srb = NULL;
407                                 break;
408                         }
409
410                         /* lock the device pointers */
411                         down(&(us->dev_semaphore));
412
413                         /* our device has gone - pretend not ready */
414                         if (!us->pusb_dev) {
415                                 US_DEBUGP("Request is for removed device\n");
416                                 /* For REQUEST_SENSE, it's the data.  But
417                                  * for anything else, it should look like
418                                  * we auto-sensed for it.
419                                  */
420                                 if (us->srb->cmnd[0] == REQUEST_SENSE) {
421                                         memcpy(us->srb->request_buffer, 
422                                                usb_stor_sense_notready, 
423                                                sizeof(usb_stor_sense_notready));
424                                         us->srb->result = GOOD << 1;
425                                 } else {
426                                         memcpy(us->srb->sense_buffer, 
427                                                usb_stor_sense_notready, 
428                                                sizeof(usb_stor_sense_notready));
429                                         us->srb->result = CHECK_CONDITION << 1;
430                                 }
431                         } else { /* !us->pusb_dev */
432                                 /* we've got a command, let's do it! */
433                                 US_DEBUG(usb_stor_show_command(us->srb));
434                                 us->proto_handler(us->srb, us);
435                         }
436
437                         /* unlock the device pointers */
438                         up(&(us->dev_semaphore));
439
440                         /* indicate that the command is done */
441                         if (us->srb->result != DID_ABORT << 16) {
442                                 US_DEBUGP("scsi cmd done, result=0x%x\n", 
443                                            us->srb->result);
444                                 set_current_state(TASK_INTERRUPTIBLE);
445                                 us->srb->scsi_done(us->srb);
446                         } else {
447                                 US_DEBUGP("scsi command aborted\n");
448                                 set_current_state(TASK_INTERRUPTIBLE);
449                                 complete(&(us->notify));
450                         }
451                         us->srb = NULL;
452                         break;
453
454                 case US_ACT_DEVICE_RESET:
455                         break;
456
457                 case US_ACT_BUS_RESET:
458                         break;
459
460                 case US_ACT_HOST_RESET:
461                         break;
462
463                 } /* end switch on action */
464
465                 /* exit if we get a signal to exit */
466                 if (action == US_ACT_EXIT) {
467                         US_DEBUGP("-- US_ACT_EXIT command received\n");
468                         break;
469                 }
470         } /* for (;;) */
471
472         /* clean up after ourselves */
473         set_current_state(TASK_INTERRUPTIBLE);
474
475         /* notify the exit routine that we're actually exiting now */
476         complete(&(us->notify));
477
478         return 0;
479 }       
480
481 /* Set up the IRQ pipe and handler
482  * Note that this function assumes that all the data in the us_data
483  * strucuture is current.  This includes the ep_int field, which gives us
484  * the endpoint for the interrupt.
485  * Returns non-zero on failure, zero on success
486  */ 
487 static int usb_stor_allocate_irq(struct us_data *ss)
488 {
489         unsigned int pipe;
490         int maxp;
491         int result;
492
493         US_DEBUGP("Allocating IRQ for CBI transport\n");
494
495         /* lock access to the data structure */
496         down(&(ss->irq_urb_sem));
497
498         /* allocate the URB */
499         ss->irq_urb = usb_alloc_urb(0);
500         if (!ss->irq_urb) {
501                 up(&(ss->irq_urb_sem));
502                 US_DEBUGP("couldn't allocate interrupt URB");
503                 return 1;
504         }
505
506         /* calculate the pipe and max packet size */
507         pipe = usb_rcvintpipe(ss->pusb_dev, ss->ep_int->bEndpointAddress & 
508                               USB_ENDPOINT_NUMBER_MASK);
509         maxp = usb_maxpacket(ss->pusb_dev, pipe, usb_pipeout(pipe));
510         if (maxp > sizeof(ss->irqbuf))
511                 maxp = sizeof(ss->irqbuf);
512
513         /* fill in the URB with our data */
514         FILL_INT_URB(ss->irq_urb, ss->pusb_dev, pipe, ss->irqbuf, maxp, 
515                      usb_stor_CBI_irq, ss, ss->ep_int->bInterval); 
516
517         /* submit the URB for processing */
518         result = usb_submit_urb(ss->irq_urb);
519         US_DEBUGP("usb_submit_urb() returns %d\n", result);
520         if (result) {
521                 usb_free_urb(ss->irq_urb);
522                 up(&(ss->irq_urb_sem));
523                 return 2;
524         }
525
526         /* unlock the data structure and return success */
527         up(&(ss->irq_urb_sem));
528         return 0;
529 }
530
531 /* Probe to see if a new device is actually a SCSI device */
532 static void * storage_probe(struct usb_device *dev, unsigned int ifnum,
533                             const struct usb_device_id *id)
534 {
535         int i;
536         const int id_index = id - storage_usb_ids; 
537         char mf[USB_STOR_STRING_LEN];                /* manufacturer */
538         char prod[USB_STOR_STRING_LEN];              /* product */
539         char serial[USB_STOR_STRING_LEN];            /* serial number */
540         GUID(guid);                        /* Global Unique Identifier */
541         unsigned int flags;
542         struct us_unusual_dev *unusual_dev;
543         struct us_data *ss = NULL;
544 #ifdef CONFIG_USB_STORAGE_SDDR09
545         int result;
546 #endif
547
548         /* these are temporary copies -- we test on these, then put them
549          * in the us-data structure 
550          */
551         struct usb_endpoint_descriptor *ep_in = NULL;
552         struct usb_endpoint_descriptor *ep_out = NULL;
553         struct usb_endpoint_descriptor *ep_int = NULL;
554         u8 subclass = 0;
555         u8 protocol = 0;
556
557         /* the altsettting on the interface we're probing that matched our
558          * usb_match_id table
559          */
560         struct usb_interface *intf = dev->actconfig->interface;
561         struct usb_interface_descriptor *altsetting =
562                 intf[ifnum].altsetting + intf[ifnum].act_altsetting;
563         US_DEBUGP("act_altsettting is %d\n", intf[ifnum].act_altsetting);
564
565         /* clear the temporary strings */
566         memset(mf, 0, sizeof(mf));
567         memset(prod, 0, sizeof(prod));
568         memset(serial, 0, sizeof(serial));
569
570         /* 
571          * Can we support this device, either because we know about it
572          * from our unusual device list, or because it advertises that it's
573          * compliant to the specification?
574          *
575          * id_index is calculated in the declaration to be the index number
576          * of the match from the usb_device_id table, so we can find the
577          * corresponding entry in the private table.
578          */
579         US_DEBUGP("id_index calculated to be: %d\n", id_index);
580         US_DEBUGP("Array length appears to be: %d\n", sizeof(us_unusual_dev_list) / sizeof(us_unusual_dev_list[0]));
581         if (id_index <
582             sizeof(us_unusual_dev_list) / sizeof(us_unusual_dev_list[0])) {
583                 unusual_dev = &us_unusual_dev_list[id_index];
584                 if (unusual_dev->vendorName)
585                         US_DEBUGP("Vendor: %s\n", unusual_dev->vendorName);
586                 if (unusual_dev->productName)
587                         US_DEBUGP("Product: %s\n", unusual_dev->productName);
588         } else
589                 /* no, we can't support it */
590                 return NULL;
591
592         /* At this point, we know we've got a live one */
593         US_DEBUGP("USB Mass Storage device detected\n");
594
595         /* Determine subclass and protocol, or copy from the interface */
596         subclass = unusual_dev->useProtocol;
597         protocol = unusual_dev->useTransport;
598         flags = unusual_dev->flags;
599
600         /*
601          * Find the endpoints we need
602          * We are expecting a minimum of 2 endpoints - in and out (bulk).
603          * An optional interrupt is OK (necessary for CBI protocol).
604          * We will ignore any others.
605          */
606         for (i = 0; i < altsetting->bNumEndpoints; i++) {
607                 /* is it an BULK endpoint? */
608                 if ((altsetting->endpoint[i].bmAttributes & 
609                      USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK) {
610                         /* BULK in or out? */
611                         if (altsetting->endpoint[i].bEndpointAddress & 
612                             USB_DIR_IN)
613                                 ep_in = &altsetting->endpoint[i];
614                         else
615                                 ep_out = &altsetting->endpoint[i];
616                 }
617
618                 /* is it an interrupt endpoint? */
619                 if ((altsetting->endpoint[i].bmAttributes & 
620                      USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) {
621                         ep_int = &altsetting->endpoint[i];
622                 }
623         }
624         US_DEBUGP("Endpoints: In: 0x%p Out: 0x%p Int: 0x%p (Period %d)\n",
625                   ep_in, ep_out, ep_int, ep_int ? ep_int->bInterval : 0);
626
627 #ifdef CONFIG_USB_STORAGE_SDDR09
628         if (protocol == US_PR_EUSB_SDDR09 || protocol == US_PR_DPCM_USB) {
629                 /* set the configuration -- STALL is an acceptable response here */
630                 result = usb_set_configuration(dev, 1);
631
632                 US_DEBUGP("Result from usb_set_configuration is %d\n", result);
633                 if (result == -EPIPE) {
634                         US_DEBUGP("-- clearing stall on control interface\n");
635                         usb_clear_halt(dev, usb_sndctrlpipe(dev, 0));
636                 } else if (result != 0) {
637                         /* it's not a stall, but another error -- time to bail */
638                         US_DEBUGP("-- Unknown error.  Rejecting device\n");
639                         return NULL;
640                 }
641         }
642 #endif
643
644         /* Do some basic sanity checks, and bail if we find a problem */
645         if (!ep_in || !ep_out || (protocol == US_PR_CBI && !ep_int)) {
646                 US_DEBUGP("Endpoint sanity check failed! Rejecting dev.\n");
647                 return NULL;
648         }
649
650         /* At this point, we're committed to using the device */
651         usb_inc_dev_use(dev);
652
653         /* clear the GUID and fetch the strings */
654         GUID_CLEAR(guid);
655         if (dev->descriptor.iManufacturer)
656                 usb_string(dev, dev->descriptor.iManufacturer, 
657                            mf, sizeof(mf));
658         if (dev->descriptor.iProduct)
659                 usb_string(dev, dev->descriptor.iProduct, 
660                            prod, sizeof(prod));
661         if (dev->descriptor.iSerialNumber && !(flags & US_FL_IGNORE_SER))
662                 usb_string(dev, dev->descriptor.iSerialNumber, 
663                            serial, sizeof(serial));
664
665         /* Create a GUID for this device */
666         if (dev->descriptor.iSerialNumber && serial[0]) {
667                 /* If we have a serial number, and it's a non-NULL string */
668                 make_guid(guid, dev->descriptor.idVendor, 
669                           dev->descriptor.idProduct, serial);
670         } else {
671                 /* We don't have a serial number, so we use 0 */
672                 make_guid(guid, dev->descriptor.idVendor, 
673                           dev->descriptor.idProduct, "0");
674         }
675
676         /*
677          * Now check if we have seen this GUID before
678          * We're looking for a device with a matching GUID that isn't
679          * already on the system
680          */
681         ss = us_list;
682         while ((ss != NULL) && 
683                ((ss->pusb_dev) || !GUID_EQUAL(guid, ss->guid)))
684                 ss = ss->next;
685
686         if (ss != NULL) {
687                 /* Existing device -- re-connect */
688                 US_DEBUGP("Found existing GUID " GUID_FORMAT "\n",
689                           GUID_ARGS(guid));
690
691                 /* lock the device pointers */
692                 down(&(ss->dev_semaphore));
693
694                 /* establish the connection to the new device upon reconnect */
695                 ss->ifnum = ifnum;
696                 ss->pusb_dev = dev;
697
698                 /* copy over the endpoint data */
699                 if (ep_in)
700                         ss->ep_in = ep_in->bEndpointAddress & 
701                                 USB_ENDPOINT_NUMBER_MASK;
702                 if (ep_out)
703                         ss->ep_out = ep_out->bEndpointAddress & 
704                                 USB_ENDPOINT_NUMBER_MASK;
705                 ss->ep_int = ep_int;
706
707                 /* allocate an IRQ callback if one is needed */
708                 if ((ss->protocol == US_PR_CBI) && usb_stor_allocate_irq(ss)) {
709                         usb_dec_dev_use(dev);
710                         return NULL;
711                 }
712
713                 /* allocate the URB we're going to use */
714                 ss->current_urb = usb_alloc_urb(0);
715                 if (!ss->current_urb) {
716                         usb_dec_dev_use(dev);
717                         return NULL;
718                 }
719
720                 /* Re-Initialize the device if it needs it */
721                 if (unusual_dev && unusual_dev->initFunction)
722                         (unusual_dev->initFunction)(ss);
723
724                 /* unlock the device pointers */
725                 up(&(ss->dev_semaphore));
726
727         } else { 
728                 /* New device -- allocate memory and initialize */
729                 US_DEBUGP("New GUID " GUID_FORMAT "\n", GUID_ARGS(guid));
730
731                 if ((ss = (struct us_data *)kmalloc(sizeof(struct us_data), 
732                                                     GFP_KERNEL)) == NULL) {
733                         printk(KERN_WARNING USB_STORAGE "Out of memory\n");
734                         usb_dec_dev_use(dev);
735                         return NULL;
736                 }
737                 memset(ss, 0, sizeof(struct us_data));
738
739                 /* allocate the URB we're going to use */
740                 ss->current_urb = usb_alloc_urb(0);
741                 if (!ss->current_urb) {
742                         kfree(ss);
743                         usb_dec_dev_use(dev);
744                         return NULL;
745                 }
746
747                 /* Initialize the mutexes only when the struct is new */
748                 init_completion(&(ss->notify));
749                 init_MUTEX_LOCKED(&(ss->ip_waitq));
750                 init_MUTEX(&(ss->queue_exclusion));
751                 init_MUTEX(&(ss->irq_urb_sem));
752                 init_MUTEX(&(ss->current_urb_sem));
753                 init_MUTEX(&(ss->dev_semaphore));
754
755                 /* copy over the subclass and protocol data */
756                 ss->subclass = subclass;
757                 ss->protocol = protocol;
758                 ss->flags = flags;
759                 ss->unusual_dev = unusual_dev;
760
761                 /* copy over the endpoint data */
762                 if (ep_in)
763                         ss->ep_in = ep_in->bEndpointAddress & 
764                                 USB_ENDPOINT_NUMBER_MASK;
765                 if (ep_out)
766                         ss->ep_out = ep_out->bEndpointAddress & 
767                                 USB_ENDPOINT_NUMBER_MASK;
768                 ss->ep_int = ep_int;
769
770                 /* establish the connection to the new device */
771                 ss->ifnum = ifnum;
772                 ss->pusb_dev = dev;
773
774                 /* copy over the identifiying strings */
775                 strncpy(ss->vendor, mf, USB_STOR_STRING_LEN);
776                 strncpy(ss->product, prod, USB_STOR_STRING_LEN);
777                 strncpy(ss->serial, serial, USB_STOR_STRING_LEN);
778                 if (strlen(ss->vendor) == 0) {
779                         if (unusual_dev->vendorName)
780                                 strncpy(ss->vendor, unusual_dev->vendorName,
781                                         USB_STOR_STRING_LEN);
782                         else
783                                 strncpy(ss->vendor, "Unknown",
784                                         USB_STOR_STRING_LEN);
785                 }
786                 if (strlen(ss->product) == 0) {
787                         if (unusual_dev->productName)
788                                 strncpy(ss->product, unusual_dev->productName,
789                                         USB_STOR_STRING_LEN);
790                         else
791                                 strncpy(ss->product, "Unknown",
792                                         USB_STOR_STRING_LEN);
793                 }
794                 if (strlen(ss->serial) == 0)
795                         strncpy(ss->serial, "None", USB_STOR_STRING_LEN);
796
797                 /* copy the GUID we created before */
798                 memcpy(ss->guid, guid, sizeof(guid));
799
800                 /* 
801                  * Set the handler pointers based on the protocol
802                  * Again, this data is persistant across reattachments
803                  */
804                 switch (ss->protocol) {
805                 case US_PR_CB:
806                         ss->transport_name = "Control/Bulk";
807                         ss->transport = usb_stor_CB_transport;
808                         ss->transport_reset = usb_stor_CB_reset;
809                         ss->max_lun = 7;
810                         break;
811
812                 case US_PR_CBI:
813                         ss->transport_name = "Control/Bulk/Interrupt";
814                         ss->transport = usb_stor_CBI_transport;
815                         ss->transport_reset = usb_stor_CB_reset;
816                         ss->max_lun = 7;
817                         break;
818
819                 case US_PR_BULK:
820                         ss->transport_name = "Bulk";
821                         ss->transport = usb_stor_Bulk_transport;
822                         ss->transport_reset = usb_stor_Bulk_reset;
823                         ss->max_lun = usb_stor_Bulk_max_lun(ss);
824                         break;
825
826 #ifdef CONFIG_USB_STORAGE_HP8200e
827                 case US_PR_SCM_ATAPI:
828                         ss->transport_name = "SCM/ATAPI";
829                         ss->transport = hp8200e_transport;
830                         ss->transport_reset = usb_stor_CB_reset;
831                         ss->max_lun = 1;
832                         break;
833 #endif
834
835 #ifdef CONFIG_USB_STORAGE_SDDR09
836                 case US_PR_EUSB_SDDR09:
837                         ss->transport_name = "EUSB/SDDR09";
838                         ss->transport = sddr09_transport;
839                         ss->transport_reset = usb_stor_CB_reset;
840                         ss->max_lun = 0;
841                         break;
842 #endif
843
844 #ifdef CONFIG_USB_STORAGE_DPCM
845                 case US_PR_DPCM_USB:
846                         ss->transport_name = "Control/Bulk-EUSB/SDDR09";
847                         ss->transport = dpcm_transport;
848                         ss->transport_reset = usb_stor_CB_reset;
849                         ss->max_lun = 1;
850                         break;
851 #endif
852
853 #ifdef CONFIG_USB_STORAGE_FREECOM
854                 case US_PR_FREECOM:
855                         ss->transport_name = "Freecom";
856                         ss->transport = freecom_transport;
857                         ss->transport_reset = usb_stor_freecom_reset;
858                         ss->max_lun = 0;
859                         break;
860 #endif
861
862 #ifdef CONFIG_USB_STORAGE_DATAFAB
863                 case US_PR_DATAFAB:
864                         ss->transport_name  = "Datafab Bulk-Only";
865                         ss->transport = datafab_transport;
866                         ss->transport_reset = usb_stor_Bulk_reset;
867                         ss->max_lun = 1;
868                         break;
869 #endif
870
871 #ifdef CONFIG_USB_STORAGE_JUMPSHOT
872                 case US_PR_JUMPSHOT:
873                         ss->transport_name  = "Lexar Jumpshot Control/Bulk";
874                         ss->transport = jumpshot_transport;
875                         ss->transport_reset = usb_stor_Bulk_reset;
876                         ss->max_lun = 1;
877                         break;
878 #endif
879
880                 default:
881                         ss->transport_name = "Unknown";
882                         kfree(ss->current_urb);
883                         kfree(ss);
884                         usb_dec_dev_use(dev);
885                         return NULL;
886                         break;
887                 }
888                 US_DEBUGP("Transport: %s\n", ss->transport_name);
889
890                 /* fix for single-lun devices */
891                 if (ss->flags & US_FL_SINGLE_LUN)
892                         ss->max_lun = 0;
893
894                 switch (ss->subclass) {
895                 case US_SC_RBC:
896                         ss->protocol_name = "Reduced Block Commands (RBC)";
897                         ss->proto_handler = usb_stor_transparent_scsi_command;
898                         break;
899
900                 case US_SC_8020:
901                         ss->protocol_name = "8020i";
902                         ss->proto_handler = usb_stor_ATAPI_command;
903                         ss->max_lun = 0;
904                         break;
905
906                 case US_SC_QIC:
907                         ss->protocol_name = "QIC-157";
908                         ss->proto_handler = usb_stor_qic157_command;
909                         ss->max_lun = 0;
910                         break;
911
912                 case US_SC_8070:
913                         ss->protocol_name = "8070i";
914                         ss->proto_handler = usb_stor_ATAPI_command;
915                         ss->max_lun = 0;
916                         break;
917
918                 case US_SC_SCSI:
919                         ss->protocol_name = "Transparent SCSI";
920                         ss->proto_handler = usb_stor_transparent_scsi_command;
921                         break;
922
923                 case US_SC_UFI:
924                         ss->protocol_name = "Uniform Floppy Interface (UFI)";
925                         ss->proto_handler = usb_stor_ufi_command;
926                         break;
927
928 #ifdef CONFIG_USB_STORAGE_ISD200
929                 case US_SC_ISD200:
930                         ss->protocol_name = "ISD200 ATA/ATAPI";
931                         ss->proto_handler = isd200_ata_command;
932                         break;
933 #endif
934
935                 default:
936                         ss->protocol_name = "Unknown";
937                         kfree(ss->current_urb);
938                         kfree(ss);
939                         return NULL;
940                         break;
941                 }
942                 US_DEBUGP("Protocol: %s\n", ss->protocol_name);
943
944                 /* allocate an IRQ callback if one is needed */
945                 if ((ss->protocol == US_PR_CBI) && usb_stor_allocate_irq(ss)) {
946                         usb_dec_dev_use(dev);
947                         return NULL;
948                 }
949
950                 /*
951                  * Since this is a new device, we need to generate a scsi 
952                  * host definition, and register with the higher SCSI layers
953                  */
954
955                 /* Initialize the host template based on the default one */
956                 memcpy(&(ss->htmplt), &usb_stor_host_template, 
957                        sizeof(usb_stor_host_template));
958
959                 /* Grab the next host number */
960                 ss->host_number = my_host_number++;
961
962                 /* We abuse this pointer so we can pass the ss pointer to 
963                  * the host controller thread in us_detect.  But how else are
964                  * we to do it?
965                  */
966                 (struct us_data *)ss->htmplt.proc_dir = ss; 
967
968                 /* Just before we start our control thread, initialize
969                  * the device if it needs initialization */
970                 if (unusual_dev && unusual_dev->initFunction)
971                         unusual_dev->initFunction(ss);
972
973                 /* start up our control thread */
974                 ss->pid = kernel_thread(usb_stor_control_thread, ss,
975                                         CLONE_VM);
976                 if (ss->pid < 0) {
977                         printk(KERN_WARNING USB_STORAGE 
978                                "Unable to start control thread\n");
979                         kfree(ss->current_urb);
980                         kfree(ss);
981                         usb_dec_dev_use(dev);
982                         return NULL;
983                 }
984
985                 /* wait for the thread to start */
986                 wait_for_completion(&(ss->notify));
987
988                 /* now register  - our detect function will be called */
989                 ss->htmplt.module = THIS_MODULE;
990                 scsi_register_module(MODULE_SCSI_HA, &(ss->htmplt));
991
992                 /* lock access to the data structures */
993                 down(&us_list_semaphore);
994
995                 /* put us in the list */
996                 ss->next = us_list;
997                 us_list = ss;
998
999                 /* release the data structure lock */
1000                 up(&us_list_semaphore);
1001         }
1002
1003         printk(KERN_DEBUG 
1004                "WARNING: USB Mass Storage data integrity not assured\n");
1005         printk(KERN_DEBUG 
1006                "USB Mass Storage device found at %d\n", dev->devnum);
1007
1008         /* return a pointer for the disconnect function */
1009         return ss;
1010 }
1011
1012 /* Handle a disconnect event from the USB core */
1013 static void storage_disconnect(struct usb_device *dev, void *ptr)
1014 {
1015         struct us_data *ss = ptr;
1016         int result;
1017
1018         US_DEBUGP("storage_disconnect() called\n");
1019
1020         /* this is the odd case -- we disconnected but weren't using it */
1021         if (!ss) {
1022                 US_DEBUGP("-- device was not in use\n");
1023                 return;
1024         }
1025
1026         /* lock access to the device data structure */
1027         down(&(ss->dev_semaphore));
1028
1029         /* release the IRQ, if we have one */
1030         down(&(ss->irq_urb_sem));
1031         if (ss->irq_urb) {
1032                 US_DEBUGP("-- releasing irq URB\n");
1033                 result = usb_unlink_urb(ss->irq_urb);
1034                 US_DEBUGP("-- usb_unlink_urb() returned %d\n", result);
1035                 usb_free_urb(ss->irq_urb);
1036                 ss->irq_urb = NULL;
1037         }
1038         up(&(ss->irq_urb_sem));
1039
1040         /* free up the main URB for this device */
1041         US_DEBUGP("-- releasing main URB\n");
1042         result = usb_unlink_urb(ss->current_urb);
1043         US_DEBUGP("-- usb_unlink_urb() returned %d\n", result);
1044         usb_free_urb(ss->current_urb);
1045         ss->current_urb = NULL;
1046
1047         /* mark the device as gone */
1048         usb_dec_dev_use(ss->pusb_dev);
1049         ss->pusb_dev = NULL;
1050
1051         /* unlock access to the device data structure */
1052         up(&(ss->dev_semaphore));
1053 }
1054
1055 /***********************************************************************
1056  * Initialization and registration
1057  ***********************************************************************/
1058
1059 int __init usb_stor_init(void)
1060 {
1061         printk(KERN_INFO "Initializing USB Mass Storage driver...\n");
1062
1063         /* initialize internal global data elements */
1064         us_list = NULL;
1065         init_MUTEX(&us_list_semaphore);
1066         my_host_number = 0;
1067
1068         /* register the driver, return -1 if error */
1069         if (usb_register(&usb_storage_driver) < 0)
1070                 return -1;
1071
1072         /* we're all set */
1073         printk(KERN_INFO "USB Mass Storage support registered.\n");
1074         return 0;
1075 }
1076
1077 void __exit usb_stor_exit(void)
1078 {
1079         struct us_data *next;
1080
1081         US_DEBUGP("usb_stor_exit() called\n");
1082
1083         /* Deregister the driver
1084          * This eliminates races with probes and disconnects 
1085          */
1086         US_DEBUGP("-- calling usb_deregister()\n");
1087         usb_deregister(&usb_storage_driver) ;
1088
1089         /* While there are still virtual hosts, unregister them
1090          * Note that it's important to do this completely before removing
1091          * the structures because of possible races with the /proc
1092          * interface
1093          */
1094         for (next = us_list; next; next = next->next) {
1095                 US_DEBUGP("-- calling scsi_unregister_module()\n");
1096                 scsi_unregister_module(MODULE_SCSI_HA, &(next->htmplt));
1097         }
1098
1099         /* While there are still structures, free them.  Note that we are
1100          * now race-free, since these structures can no longer be accessed
1101          * from either the SCSI command layer or the /proc interface
1102          */
1103         while (us_list) {
1104                 /* keep track of where the next one is */
1105                 next = us_list->next;
1106
1107                 /* If there's extra data in the us_data structure then
1108                  * free that first */
1109                 if (us_list->extra) {
1110                         /* call the destructor routine, if it exists */
1111                         if (us_list->extra_destructor) {
1112                                 US_DEBUGP("-- calling extra_destructor()\n");
1113                                 us_list->extra_destructor(us_list->extra);
1114                         }
1115
1116                         /* destroy the extra data */
1117                         US_DEBUGP("-- freeing the data structure\n");
1118                         kfree(us_list->extra);
1119                 }
1120
1121                 /* free the structure itself */
1122                 kfree (us_list);
1123
1124                 /* advance the list pointer */
1125                 us_list = next;
1126         }
1127 }
1128
1129 module_init(usb_stor_init);
1130 module_exit(usb_stor_exit);