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