ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / storage / scsiglue.c
1 /* Driver for USB Mass Storage compliant devices
2  * SCSI layer glue code
3  *
4  * $Id: scsiglue.c,v 1.26 2002/04/22 03:39:43 mdharm Exp $
5  *
6  * Current development and maintenance by:
7  *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
8  *
9  * Developed with the assistance of:
10  *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
11  *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
12  *
13  * Initial work by:
14  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
15  *
16  * This driver is based on the 'USB Mass Storage Class' document. This
17  * describes in detail the protocol used to communicate with such
18  * devices.  Clearly, the designers had SCSI and ATAPI commands in
19  * mind when they created this document.  The commands are all very
20  * similar to commands in the SCSI-II and ATAPI specifications.
21  *
22  * It is important to note that in a number of cases this class
23  * exhibits class-specific exemptions from the USB specification.
24  * Notably the usage of NAK, STALL and ACK differs from the norm, in
25  * that they are used to communicate wait, failed and OK on commands.
26  *
27  * Also, for certain devices, the interrupt endpoint is used to convey
28  * status of a command.
29  *
30  * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
31  * information about this driver.
32  *
33  * This program is free software; you can redistribute it and/or modify it
34  * under the terms of the GNU General Public License as published by the
35  * Free Software Foundation; either version 2, or (at your option) any
36  * later version.
37  *
38  * This program is distributed in the hope that it will be useful, but
39  * WITHOUT ANY WARRANTY; without even the implied warranty of
40  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41  * General Public License for more details.
42  *
43  * You should have received a copy of the GNU General Public License along
44  * with this program; if not, write to the Free Software Foundation, Inc.,
45  * 675 Mass Ave, Cambridge, MA 02139, USA.
46  */
47 #include "scsiglue.h"
48 #include "usb.h"
49 #include "debug.h"
50 #include "transport.h"
51
52 #include <linux/slab.h>
53 #include <linux/module.h>
54 #include <scsi/scsi_devinfo.h>
55 #include <scsi/scsi_host.h>
56
57
58 /***********************************************************************
59  * Host functions 
60  ***********************************************************************/
61
62 static const char* host_info(struct Scsi_Host *host)
63 {
64         return "SCSI emulation for USB Mass Storage devices";
65 }
66
67 static int slave_alloc (struct scsi_device *sdev)
68 {
69         /*
70          * Set default bflags. These can be overridden for individual
71          * models and vendors via the scsi devinfo mechanism.
72          */
73         sdev->sdev_bflags = (BLIST_MS_SKIP_PAGE_08 | BLIST_MS_SKIP_PAGE_3F |
74                              BLIST_USE_10_BYTE_MS);
75         return 0;
76 }
77
78 static int slave_configure(struct scsi_device *sdev)
79 {
80         struct us_data *us = (struct us_data *) sdev->host->hostdata[0];
81
82         /* Scatter-gather buffers (all but the last) must have a length
83          * divisible by the bulk maxpacket size.  Otherwise a data packet
84          * would end up being short, causing a premature end to the data
85          * transfer.  Since high-speed bulk pipes have a maxpacket size
86          * of 512, we'll use that as the scsi device queue's DMA alignment
87          * mask.  Guaranteeing proper alignment of the first buffer will
88          * have the desired effect because, except at the beginning and
89          * the end, scatter-gather buffers follow page boundaries. */
90         blk_queue_dma_alignment(sdev->request_queue, (512 - 1));
91
92         /* Devices using Genesys Logic chips cause a lot of trouble for
93          * high-speed transfers; they die unpredictably when given more
94          * than 64 KB of data at a time.  If we detect such a device,
95          * reduce the maximum transfer size to 64 KB = 128 sectors. */
96
97 #define USB_VENDOR_ID_GENESYS   0x05e3          // Needs a standard location
98         if (us->pusb_dev->descriptor.idVendor == USB_VENDOR_ID_GENESYS &&
99                         us->pusb_dev->speed == USB_SPEED_HIGH)
100                 blk_queue_max_sectors(sdev->request_queue, 128);
101
102         /* this is to satisify the compiler, tho I don't think the 
103          * return code is ever checked anywhere. */
104         return 0;
105 }
106
107 /* queue a command */
108 /* This is always called with scsi_lock(srb->host) held */
109 static int queuecommand( Scsi_Cmnd *srb , void (*done)(Scsi_Cmnd *))
110 {
111         struct us_data *us = (struct us_data *)srb->device->host->hostdata[0];
112
113         US_DEBUGP("%s called\n", __FUNCTION__);
114         srb->host_scribble = (unsigned char *)us;
115
116         /* enqueue the command */
117         if (us->sm_state != US_STATE_IDLE || us->srb != NULL) {
118                 printk(KERN_ERR USB_STORAGE "Error in %s: " 
119                         "state = %d, us->srb = %p\n",
120                         __FUNCTION__, us->sm_state, us->srb);
121                 return SCSI_MLQUEUE_HOST_BUSY;
122         }
123
124         srb->scsi_done = done;
125         us->srb = srb;
126
127         /* wake up the process task */
128         up(&(us->sema));
129
130         return 0;
131 }
132
133 /***********************************************************************
134  * Error handling functions
135  ***********************************************************************/
136
137 /* Command abort */
138 /* This is always called with scsi_lock(srb->host) held */
139 static int command_abort( Scsi_Cmnd *srb )
140 {
141         struct Scsi_Host *host = srb->device->host;
142         struct us_data *us = (struct us_data *) host->hostdata[0];
143
144         US_DEBUGP("%s called\n", __FUNCTION__);
145
146         /* Is this command still active? */
147         if (us->srb != srb) {
148                 US_DEBUGP ("-- nothing to abort\n");
149                 return FAILED;
150         }
151
152         /* Normally the current state is RUNNING.  If the control thread
153          * hasn't even started processing this command, the state will be
154          * IDLE.  Anything else is a bug. */
155         if (us->sm_state != US_STATE_RUNNING
156                                 && us->sm_state != US_STATE_IDLE) {
157                 printk(KERN_ERR USB_STORAGE "Error in %s: "
158                         "invalid state %d\n", __FUNCTION__, us->sm_state);
159                 return FAILED;
160         }
161
162         /* Set state to ABORTING, set the ABORTING bit, and release the lock */
163         us->sm_state = US_STATE_ABORTING;
164         set_bit(US_FLIDX_ABORTING, &us->flags);
165         scsi_unlock(host);
166
167         /* Stop an ongoing USB transfer */
168         usb_stor_stop_transport(us);
169
170         /* Wait for the aborted command to finish */
171         wait_for_completion(&us->notify);
172
173         /* Reacquire the lock and allow USB transfers to resume */
174         scsi_lock(host);
175         clear_bit(US_FLIDX_ABORTING, &us->flags);
176         return SUCCESS;
177 }
178
179 /* This invokes the transport reset mechanism to reset the state of the
180  * device */
181 /* This is always called with scsi_lock(srb->host) held */
182 static int device_reset( Scsi_Cmnd *srb )
183 {
184         struct us_data *us = (struct us_data *)srb->device->host->hostdata[0];
185         int result;
186
187         US_DEBUGP("%s called\n", __FUNCTION__);
188         if (us->sm_state != US_STATE_IDLE) {
189                 printk(KERN_ERR USB_STORAGE "Error in %s: "
190                         "invalid state %d\n", __FUNCTION__, us->sm_state);
191                 return FAILED;
192         }
193
194         /* set the state and release the lock */
195         us->sm_state = US_STATE_RESETTING;
196         scsi_unlock(srb->device->host);
197
198         /* lock the device pointers and do the reset */
199         down(&(us->dev_semaphore));
200         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
201                 result = FAILED;
202                 US_DEBUGP("No reset during disconnect\n");
203         } else
204                 result = us->transport_reset(us);
205         up(&(us->dev_semaphore));
206
207         /* lock access to the state and clear it */
208         scsi_lock(srb->device->host);
209         us->sm_state = US_STATE_IDLE;
210         return result;
211 }
212
213 /* This resets the device's USB port. */
214 /* It refuses to work if there's more than one interface in
215  * the device, so that other users are not affected. */
216 /* This is always called with scsi_lock(srb->host) held */
217 static int bus_reset( Scsi_Cmnd *srb )
218 {
219         struct us_data *us = (struct us_data *)srb->device->host->hostdata[0];
220         int result;
221
222         US_DEBUGP("%s called\n", __FUNCTION__);
223         if (us->sm_state != US_STATE_IDLE) {
224                 printk(KERN_ERR USB_STORAGE "Error in %s: "
225                         "invalid state %d\n", __FUNCTION__, us->sm_state);
226                 return FAILED;
227         }
228
229         /* set the state and release the lock */
230         us->sm_state = US_STATE_RESETTING;
231         scsi_unlock(srb->device->host);
232
233         /* The USB subsystem doesn't handle synchronisation between
234          * a device's several drivers. Therefore we reset only devices
235          * with just one interface, which we of course own. */
236
237         down(&(us->dev_semaphore));
238         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
239                 result = -EIO;
240                 US_DEBUGP("No reset during disconnect\n");
241         } else if (us->pusb_dev->actconfig->desc.bNumInterfaces != 1) {
242                 result = -EBUSY;
243                 US_DEBUGP("Refusing to reset a multi-interface device\n");
244         } else {
245                 result = usb_reset_device(us->pusb_dev);
246                 US_DEBUGP("usb_reset_device returns %d\n", result);
247         }
248         up(&(us->dev_semaphore));
249
250         /* lock access to the state and clear it */
251         scsi_lock(srb->device->host);
252         us->sm_state = US_STATE_IDLE;
253         return result < 0 ? FAILED : SUCCESS;
254 }
255
256 /* Report a driver-initiated device reset to the SCSI layer.
257  * Calling this for a SCSI-initiated reset is unnecessary but harmless. */
258 void usb_stor_report_device_reset(struct us_data *us)
259 {
260         int i;
261
262         scsi_lock(us->host);
263         scsi_report_device_reset(us->host, 0, 0);
264         if (us->flags & US_FL_SCM_MULT_TARG) {
265                 for (i = 1; i < us->host->max_id; ++i)
266                         scsi_report_device_reset(us->host, 0, i);
267         }
268         scsi_unlock(us->host);
269 }
270
271 /***********************************************************************
272  * /proc/scsi/ functions
273  ***********************************************************************/
274
275 /* we use this macro to help us write into the buffer */
276 #undef SPRINTF
277 #define SPRINTF(args...) \
278         do { if (pos < buffer+length) pos += sprintf(pos, ## args); } while (0)
279 #define DO_FLAG(a) \
280         do { if (us->flags & US_FL_##a) pos += sprintf(pos, " " #a); } while(0)
281
282 static int proc_info (struct Scsi_Host *hostptr, char *buffer, char **start, off_t offset,
283                 int length, int inout)
284 {
285         struct us_data *us;
286         char *pos = buffer;
287
288         /* if someone is sending us data, just throw it away */
289         if (inout)
290                 return length;
291
292         us = (struct us_data*)hostptr->hostdata[0];
293
294         /* print the controller name */
295         SPRINTF("   Host scsi%d: usb-storage\n", hostptr->host_no);
296
297         /* print product, vendor, and serial number strings */
298         SPRINTF("       Vendor: %s\n", us->vendor);
299         SPRINTF("      Product: %s\n", us->product);
300         SPRINTF("Serial Number: %s\n", us->serial);
301
302         /* show the protocol and transport */
303         SPRINTF("     Protocol: %s\n", us->protocol_name);
304         SPRINTF("    Transport: %s\n", us->transport_name);
305
306         /* show the device flags */
307         if (pos < buffer + length) {
308                 pos += sprintf(pos, "       Quirks:");
309
310                 DO_FLAG(SINGLE_LUN);
311                 DO_FLAG(SCM_MULT_TARG);
312                 DO_FLAG(FIX_INQUIRY);
313                 DO_FLAG(FIX_CAPACITY);
314
315                 *(pos++) = '\n';
316         }
317
318         /*
319          * Calculate start of next buffer, and return value.
320          */
321         *start = buffer + offset;
322
323         if ((pos - buffer) < offset)
324                 return (0);
325         else if ((pos - buffer - offset) < length)
326                 return (pos - buffer - offset);
327         else
328                 return (length);
329 }
330
331 /***********************************************************************
332  * Sysfs interface
333  ***********************************************************************/
334
335 /* Output routine for the sysfs max_sectors file */
336 static ssize_t show_max_sectors(struct device *dev, char *buf)
337 {
338         struct scsi_device *sdev = to_scsi_device(dev);
339
340         return sprintf(buf, "%u\n", sdev->request_queue->max_sectors);
341 }
342
343 /* Input routine for the sysfs max_sectors file */
344 static ssize_t store_max_sectors(struct device *dev, const char *buf,
345                 size_t count)
346 {
347         struct scsi_device *sdev = to_scsi_device(dev);
348         unsigned short ms;
349
350         if (sscanf(buf, "%hu", &ms) > 0 && ms <= SCSI_DEFAULT_MAX_SECTORS) {
351                 blk_queue_max_sectors(sdev->request_queue, ms);
352                 return strlen(buf);
353         }
354         return -EINVAL; 
355 }
356
357 static DEVICE_ATTR(max_sectors, S_IRUGO | S_IWUSR, show_max_sectors,
358                 store_max_sectors);
359
360 static struct device_attribute *sysfs_device_attr_list[] = {
361                 &dev_attr_max_sectors,
362                 NULL,
363                 };
364
365 /*
366  * this defines our host template, with which we'll allocate hosts
367  */
368
369 struct scsi_host_template usb_stor_host_template = {
370         /* basic userland interface stuff */
371         .name =                         "usb-storage",
372         .proc_name =                    "usb-storage",
373         .proc_info =                    proc_info,
374         .info =                         host_info,
375
376         /* command interface -- queued only */
377         .queuecommand =                 queuecommand,
378
379         /* error and abort handlers */
380         .eh_abort_handler =             command_abort,
381         .eh_device_reset_handler =      device_reset,
382         .eh_bus_reset_handler =         bus_reset,
383
384         /* queue commands only, only one command per LUN */
385         .can_queue =                    1,
386         .cmd_per_lun =                  1,
387
388         /* unknown initiator id */
389         .this_id =                      -1,
390
391         .slave_alloc =                  slave_alloc,
392         .slave_configure =              slave_configure,
393
394         /* lots of sg segments can be handled */
395         .sg_tablesize =                 SG_ALL,
396
397         /* limit the total size of a transfer to 120 KB */
398         .max_sectors =                  240,
399
400         /* merge commands... this seems to help performance, but
401          * periodically someone should test to see which setting is more
402          * optimal.
403          */
404         .use_clustering =               TRUE,
405
406         /* emulated HBA */
407         .emulated =                     TRUE,
408
409         /* sysfs device attributes */
410         .sdev_attrs =                   sysfs_device_attr_list,
411
412         /* module management */
413         .module =                       THIS_MODULE
414 };
415
416 /* For a device that is "Not Ready" */
417 unsigned char usb_stor_sense_notready[18] = {
418         [0]     = 0x70,                     /* current error */
419         [2]     = 0x02,                     /* not ready */
420         [7]     = 0x0a,                     /* additional length */
421         [12]    = 0x04,                     /* not ready */
422         [13]    = 0x03                      /* manual intervention */
423 };
424
425 /* To Report "Illegal Request: Invalid Field in CDB */
426 unsigned char usb_stor_sense_invalidCDB[18] = {
427         [0]     = 0x70,                     /* current error */
428         [2]     = ILLEGAL_REQUEST,          /* Illegal Request = 0x05 */
429         [7]     = 0x0a,                     /* additional length */
430         [12]    = 0x24                      /* Invalid Field in CDB */
431 };
432