patch-2_6_7-vs1_9_1_12
[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 and set the ABORTING bit, but only if
163          * a device reset isn't already in progress (to avoid interfering
164          * with the reset).  To prevent races with auto-reset, we must
165          * stop any ongoing USB transfers while still holding the host
166          * lock. */
167         us->sm_state = US_STATE_ABORTING;
168         if (!test_bit(US_FLIDX_RESETTING, &us->flags)) {
169                 set_bit(US_FLIDX_ABORTING, &us->flags);
170                 usb_stor_stop_transport(us);
171         }
172         scsi_unlock(host);
173
174         /* Wait for the aborted command to finish */
175         wait_for_completion(&us->notify);
176
177         /* Reacquire the lock and allow USB transfers to resume */
178         scsi_lock(host);
179         clear_bit(US_FLIDX_ABORTING, &us->flags);
180         return SUCCESS;
181 }
182
183 /* This invokes the transport reset mechanism to reset the state of the
184  * device */
185 /* This is always called with scsi_lock(srb->host) held */
186 static int device_reset( Scsi_Cmnd *srb )
187 {
188         struct us_data *us = (struct us_data *)srb->device->host->hostdata[0];
189         int result;
190
191         US_DEBUGP("%s called\n", __FUNCTION__);
192         if (us->sm_state != US_STATE_IDLE) {
193                 printk(KERN_ERR USB_STORAGE "Error in %s: "
194                         "invalid state %d\n", __FUNCTION__, us->sm_state);
195                 return FAILED;
196         }
197
198         /* set the state and release the lock */
199         us->sm_state = US_STATE_RESETTING;
200         scsi_unlock(srb->device->host);
201
202         /* lock the device pointers and do the reset */
203         down(&(us->dev_semaphore));
204         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
205                 result = FAILED;
206                 US_DEBUGP("No reset during disconnect\n");
207         } else
208                 result = us->transport_reset(us);
209         up(&(us->dev_semaphore));
210
211         /* lock access to the state and clear it */
212         scsi_lock(srb->device->host);
213         us->sm_state = US_STATE_IDLE;
214         return result;
215 }
216
217 /* This resets the device's USB port. */
218 /* It refuses to work if there's more than one interface in
219  * the device, so that other users are not affected. */
220 /* This is always called with scsi_lock(srb->host) held */
221 static int bus_reset( Scsi_Cmnd *srb )
222 {
223         struct us_data *us = (struct us_data *)srb->device->host->hostdata[0];
224         int result;
225
226         US_DEBUGP("%s called\n", __FUNCTION__);
227         if (us->sm_state != US_STATE_IDLE) {
228                 printk(KERN_ERR USB_STORAGE "Error in %s: "
229                         "invalid state %d\n", __FUNCTION__, us->sm_state);
230                 return FAILED;
231         }
232
233         /* set the state and release the lock */
234         us->sm_state = US_STATE_RESETTING;
235         scsi_unlock(srb->device->host);
236
237         /* The USB subsystem doesn't handle synchronisation between
238          * a device's several drivers. Therefore we reset only devices
239          * with just one interface, which we of course own. */
240
241         down(&(us->dev_semaphore));
242         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
243                 result = -EIO;
244                 US_DEBUGP("No reset during disconnect\n");
245         } else if (us->pusb_dev->actconfig->desc.bNumInterfaces != 1) {
246                 result = -EBUSY;
247                 US_DEBUGP("Refusing to reset a multi-interface device\n");
248         } else {
249                 result = usb_reset_device(us->pusb_dev);
250                 US_DEBUGP("usb_reset_device returns %d\n", result);
251         }
252         up(&(us->dev_semaphore));
253
254         /* lock access to the state and clear it */
255         scsi_lock(srb->device->host);
256         us->sm_state = US_STATE_IDLE;
257         return result < 0 ? FAILED : SUCCESS;
258 }
259
260 /* Report a driver-initiated device reset to the SCSI layer.
261  * Calling this for a SCSI-initiated reset is unnecessary but harmless.
262  * The caller must own the SCSI host lock. */
263 void usb_stor_report_device_reset(struct us_data *us)
264 {
265         int i;
266
267         scsi_report_device_reset(us->host, 0, 0);
268         if (us->flags & US_FL_SCM_MULT_TARG) {
269                 for (i = 1; i < us->host->max_id; ++i)
270                         scsi_report_device_reset(us->host, 0, i);
271         }
272 }
273
274 /***********************************************************************
275  * /proc/scsi/ functions
276  ***********************************************************************/
277
278 /* we use this macro to help us write into the buffer */
279 #undef SPRINTF
280 #define SPRINTF(args...) \
281         do { if (pos < buffer+length) pos += sprintf(pos, ## args); } while (0)
282 #define DO_FLAG(a) \
283         do { if (us->flags & US_FL_##a) pos += sprintf(pos, " " #a); } while(0)
284
285 static int proc_info (struct Scsi_Host *hostptr, char *buffer, char **start, off_t offset,
286                 int length, int inout)
287 {
288         struct us_data *us;
289         char *pos = buffer;
290
291         /* if someone is sending us data, just throw it away */
292         if (inout)
293                 return length;
294
295         us = (struct us_data*)hostptr->hostdata[0];
296
297         /* print the controller name */
298         SPRINTF("   Host scsi%d: usb-storage\n", hostptr->host_no);
299
300         /* print product, vendor, and serial number strings */
301         SPRINTF("       Vendor: %s\n", us->vendor);
302         SPRINTF("      Product: %s\n", us->product);
303         SPRINTF("Serial Number: %s\n", us->serial);
304
305         /* show the protocol and transport */
306         SPRINTF("     Protocol: %s\n", us->protocol_name);
307         SPRINTF("    Transport: %s\n", us->transport_name);
308
309         /* show the device flags */
310         if (pos < buffer + length) {
311                 pos += sprintf(pos, "       Quirks:");
312
313                 DO_FLAG(SINGLE_LUN);
314                 DO_FLAG(SCM_MULT_TARG);
315                 DO_FLAG(FIX_INQUIRY);
316                 DO_FLAG(FIX_CAPACITY);
317
318                 *(pos++) = '\n';
319         }
320
321         /*
322          * Calculate start of next buffer, and return value.
323          */
324         *start = buffer + offset;
325
326         if ((pos - buffer) < offset)
327                 return (0);
328         else if ((pos - buffer - offset) < length)
329                 return (pos - buffer - offset);
330         else
331                 return (length);
332 }
333
334 /***********************************************************************
335  * Sysfs interface
336  ***********************************************************************/
337
338 /* Output routine for the sysfs max_sectors file */
339 static ssize_t show_max_sectors(struct device *dev, char *buf)
340 {
341         struct scsi_device *sdev = to_scsi_device(dev);
342
343         return sprintf(buf, "%u\n", sdev->request_queue->max_sectors);
344 }
345
346 /* Input routine for the sysfs max_sectors file */
347 static ssize_t store_max_sectors(struct device *dev, const char *buf,
348                 size_t count)
349 {
350         struct scsi_device *sdev = to_scsi_device(dev);
351         unsigned short ms;
352
353         if (sscanf(buf, "%hu", &ms) > 0 && ms <= SCSI_DEFAULT_MAX_SECTORS) {
354                 blk_queue_max_sectors(sdev->request_queue, ms);
355                 return strlen(buf);
356         }
357         return -EINVAL; 
358 }
359
360 static DEVICE_ATTR(max_sectors, S_IRUGO | S_IWUSR, show_max_sectors,
361                 store_max_sectors);
362
363 static struct device_attribute *sysfs_device_attr_list[] = {
364                 &dev_attr_max_sectors,
365                 NULL,
366                 };
367
368 /*
369  * this defines our host template, with which we'll allocate hosts
370  */
371
372 struct scsi_host_template usb_stor_host_template = {
373         /* basic userland interface stuff */
374         .name =                         "usb-storage",
375         .proc_name =                    "usb-storage",
376         .proc_info =                    proc_info,
377         .info =                         host_info,
378
379         /* command interface -- queued only */
380         .queuecommand =                 queuecommand,
381
382         /* error and abort handlers */
383         .eh_abort_handler =             command_abort,
384         .eh_device_reset_handler =      device_reset,
385         .eh_bus_reset_handler =         bus_reset,
386
387         /* queue commands only, only one command per LUN */
388         .can_queue =                    1,
389         .cmd_per_lun =                  1,
390
391         /* unknown initiator id */
392         .this_id =                      -1,
393
394         .slave_alloc =                  slave_alloc,
395         .slave_configure =              slave_configure,
396
397         /* lots of sg segments can be handled */
398         .sg_tablesize =                 SG_ALL,
399
400         /* limit the total size of a transfer to 120 KB */
401         .max_sectors =                  240,
402
403         /* merge commands... this seems to help performance, but
404          * periodically someone should test to see which setting is more
405          * optimal.
406          */
407         .use_clustering =               TRUE,
408
409         /* emulated HBA */
410         .emulated =                     TRUE,
411
412         /* sysfs device attributes */
413         .sdev_attrs =                   sysfs_device_attr_list,
414
415         /* module management */
416         .module =                       THIS_MODULE
417 };
418
419 /* For a device that is "Not Ready" */
420 unsigned char usb_stor_sense_notready[18] = {
421         [0]     = 0x70,                     /* current error */
422         [2]     = 0x02,                     /* not ready */
423         [7]     = 0x0a,                     /* additional length */
424         [12]    = 0x04,                     /* not ready */
425         [13]    = 0x03                      /* manual intervention */
426 };
427
428 /* To Report "Illegal Request: Invalid Field in CDB */
429 unsigned char usb_stor_sense_invalidCDB[18] = {
430         [0]     = 0x70,                     /* current error */
431         [2]     = ILLEGAL_REQUEST,          /* Illegal Request = 0x05 */
432         [7]     = 0x0a,                     /* additional length */
433         [12]    = 0x24                      /* Invalid Field in CDB */
434 };
435