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