VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / drivers / usb / storage / transport.c
1 /* Driver for USB Mass Storage compliant devices
2  *
3  * $Id: transport.c,v 1.47 2002/04/22 03:39:43 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  *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
11  *   (c) 2002 Alan Stern <stern@rowland.org>
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
48 #include <linux/config.h>
49 #include "transport.h"
50 #include "protocol.h"
51 #include "scsiglue.h"
52 #include "usb.h"
53 #include "debug.h"
54
55 #include <linux/sched.h>
56 #include <linux/errno.h>
57 #include <linux/slab.h>
58
59 /***********************************************************************
60  * Data transfer routines
61  ***********************************************************************/
62
63 /*
64  * This is subtle, so pay attention:
65  * ---------------------------------
66  * We're very concerned about races with a command abort.  Hanging this code
67  * is a sure fire way to hang the kernel.  (Note that this discussion applies
68  * only to transactions resulting from a scsi queued-command, since only
69  * these transactions are subject to a scsi abort.  Other transactions, such
70  * as those occurring during device-specific initialization, must be handled
71  * by a separate code path.)
72  *
73  * The abort function (usb_storage_command_abort() in scsiglue.c) first
74  * sets the machine state and the ABORTING bit in us->flags to prevent
75  * new URBs from being submitted.  It then calls usb_stor_stop_transport()
76  * below, which atomically tests-and-clears the URB_ACTIVE bit in us->flags
77  * to see if the current_urb needs to be stopped.  Likewise, the SG_ACTIVE
78  * bit is tested to see if the current_sg scatter-gather request needs to be
79  * stopped.  The timeout callback routine does much the same thing.
80  *
81  * When a disconnect occurs, the DISCONNECTING bit in us->flags is set to
82  * prevent new URBs from being submitted, and usb_stor_stop_transport() is
83  * called to stop any ongoing requests.
84  *
85  * The submit function first verifies that the submitting is allowed
86  * (neither ABORTING nor DISCONNECTING bits are set) and that the submit
87  * completes without errors, and only then sets the URB_ACTIVE bit.  This
88  * prevents the stop_transport() function from trying to cancel the URB
89  * while the submit call is underway.  Next, the submit function must test
90  * the flags to see if an abort or disconnect occurred during the submission
91  * or before the URB_ACTIVE bit was set.  If so, it's essential to cancel
92  * the URB if it hasn't been cancelled already (i.e., if the URB_ACTIVE bit
93  * is still set).  Either way, the function must then wait for the URB to
94  * finish.  Note that because the URB_ASYNC_UNLINK flag is set, the URB can
95  * still be in progress even after a call to usb_unlink_urb() returns.
96  *
97  * The idea is that (1) once the ABORTING or DISCONNECTING bit is set,
98  * either the stop_transport() function or the submitting function
99  * is guaranteed to call usb_unlink_urb() for an active URB,
100  * and (2) test_and_clear_bit() prevents usb_unlink_urb() from being
101  * called more than once or from being called during usb_submit_urb().
102  */
103
104 /* This is the completion handler which will wake us up when an URB
105  * completes.
106  */
107 static void usb_stor_blocking_completion(struct urb *urb, struct pt_regs *regs)
108 {
109         struct completion *urb_done_ptr = (struct completion *)urb->context;
110
111         complete(urb_done_ptr);
112 }
113  
114 /* This is the timeout handler which will cancel an URB when its timeout
115  * expires.
116  */
117 static void timeout_handler(unsigned long us_)
118 {
119         struct us_data *us = (struct us_data *) us_;
120
121         if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->flags)) {
122                 US_DEBUGP("Timeout -- cancelling URB\n");
123                 usb_unlink_urb(us->current_urb);
124         }
125 }
126
127 /* This is the common part of the URB message submission code
128  *
129  * All URBs from the usb-storage driver involved in handling a queued scsi
130  * command _must_ pass through this function (or something like it) for the
131  * abort mechanisms to work properly.
132  */
133 static int usb_stor_msg_common(struct us_data *us, int timeout)
134 {
135         struct completion urb_done;
136         struct timer_list to_timer;
137         int status;
138
139         /* don't submit URBs during abort/disconnect processing */
140         if (us->flags & ABORTING_OR_DISCONNECTING)
141                 return -EIO;
142
143         /* set up data structures for the wakeup system */
144         init_completion(&urb_done);
145
146         /* fill the common fields in the URB */
147         us->current_urb->context = &urb_done;
148         us->current_urb->actual_length = 0;
149         us->current_urb->error_count = 0;
150         us->current_urb->status = 0;
151
152         /* we assume that if transfer_buffer isn't us->iobuf then it
153          * hasn't been mapped for DMA.  Yes, this is clunky, but it's
154          * easier than always having the caller tell us whether the
155          * transfer buffer has already been mapped. */
156         us->current_urb->transfer_flags =
157                         URB_ASYNC_UNLINK | URB_NO_SETUP_DMA_MAP;
158         if (us->current_urb->transfer_buffer == us->iobuf)
159                 us->current_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
160         us->current_urb->transfer_dma = us->iobuf_dma;
161         us->current_urb->setup_dma = us->cr_dma;
162
163         /* submit the URB */
164         status = usb_submit_urb(us->current_urb, GFP_NOIO);
165         if (status) {
166                 /* something went wrong */
167                 return status;
168         }
169
170         /* since the URB has been submitted successfully, it's now okay
171          * to cancel it */
172         set_bit(US_FLIDX_URB_ACTIVE, &us->flags);
173
174         /* did an abort/disconnect occur during the submission? */
175         if (us->flags & ABORTING_OR_DISCONNECTING) {
176
177                 /* cancel the URB, if it hasn't been cancelled already */
178                 if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->flags)) {
179                         US_DEBUGP("-- cancelling URB\n");
180                         usb_unlink_urb(us->current_urb);
181                 }
182         }
183  
184         /* submit the timeout timer, if a timeout was requested */
185         if (timeout > 0) {
186                 init_timer(&to_timer);
187                 to_timer.expires = jiffies + timeout;
188                 to_timer.function = timeout_handler;
189                 to_timer.data = (unsigned long) us;
190                 add_timer(&to_timer);
191         }
192
193         /* wait for the completion of the URB */
194         wait_for_completion(&urb_done);
195         clear_bit(US_FLIDX_URB_ACTIVE, &us->flags);
196  
197         /* clean up the timeout timer */
198         if (timeout > 0)
199                 del_timer_sync(&to_timer);
200
201         /* return the URB status */
202         return us->current_urb->status;
203 }
204
205 /*
206  * Transfer one control message, with timeouts, and allowing early
207  * termination.  Return codes are usual -Exxx, *not* USB_STOR_XFER_xxx.
208  */
209 int usb_stor_control_msg(struct us_data *us, unsigned int pipe,
210                  u8 request, u8 requesttype, u16 value, u16 index, 
211                  void *data, u16 size, int timeout)
212 {
213         int status;
214
215         US_DEBUGP("%s: rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
216                         __FUNCTION__, request, requesttype,
217                         value, index, size);
218
219         /* fill in the devrequest structure */
220         us->cr->bRequestType = requesttype;
221         us->cr->bRequest = request;
222         us->cr->wValue = cpu_to_le16(value);
223         us->cr->wIndex = cpu_to_le16(index);
224         us->cr->wLength = cpu_to_le16(size);
225
226         /* fill and submit the URB */
227         usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
228                          (unsigned char*) us->cr, data, size, 
229                          usb_stor_blocking_completion, NULL);
230         status = usb_stor_msg_common(us, timeout);
231
232         /* return the actual length of the data transferred if no error */
233         if (status == 0)
234                 status = us->current_urb->actual_length;
235         return status;
236 }
237
238 /* This is a version of usb_clear_halt() that allows early termination and
239  * doesn't read the status from the device -- this is because some devices
240  * crash their internal firmware when the status is requested after a halt.
241  *
242  * A definitive list of these 'bad' devices is too difficult to maintain or
243  * make complete enough to be useful.  This problem was first observed on the
244  * Hagiwara FlashGate DUAL unit.  However, bus traces reveal that neither
245  * MacOS nor Windows checks the status after clearing a halt.
246  *
247  * Since many vendors in this space limit their testing to interoperability
248  * with these two OSes, specification violations like this one are common.
249  */
250 int usb_stor_clear_halt(struct us_data *us, unsigned int pipe)
251 {
252         int result;
253         int endp = usb_pipeendpoint(pipe);
254
255         if (usb_pipein (pipe))
256                 endp |= USB_DIR_IN;
257
258         result = usb_stor_control_msg(us, us->send_ctrl_pipe,
259                 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
260                 USB_ENDPOINT_HALT, endp,
261                 NULL, 0, 3*HZ);
262
263         /* reset the toggles and endpoint flags */
264         usb_endpoint_running(us->pusb_dev, usb_pipeendpoint(pipe),
265                 usb_pipeout(pipe));
266         usb_settoggle(us->pusb_dev, usb_pipeendpoint(pipe),
267                 usb_pipeout(pipe), 0);
268
269         US_DEBUGP("%s: result = %d\n", __FUNCTION__, result);
270         return result;
271 }
272
273
274 /*
275  * Interpret the results of a URB transfer
276  *
277  * This function prints appropriate debugging messages, clears halts on
278  * non-control endpoints, and translates the status to the corresponding
279  * USB_STOR_XFER_xxx return code.
280  */
281 static int interpret_urb_result(struct us_data *us, unsigned int pipe,
282                 unsigned int length, int result, unsigned int partial)
283 {
284         US_DEBUGP("Status code %d; transferred %u/%u\n",
285                         result, partial, length);
286         switch (result) {
287
288         /* no error code; did we send all the data? */
289         case 0:
290                 if (partial != length) {
291                         US_DEBUGP("-- short transfer\n");
292                         return USB_STOR_XFER_SHORT;
293                 }
294
295                 US_DEBUGP("-- transfer complete\n");
296                 return USB_STOR_XFER_GOOD;
297
298         /* stalled */
299         case -EPIPE:
300                 /* for control endpoints, (used by CB[I]) a stall indicates
301                  * a failed command */
302                 if (usb_pipecontrol(pipe)) {
303                         US_DEBUGP("-- stall on control pipe\n");
304                         return USB_STOR_XFER_STALLED;
305                 }
306
307                 /* for other sorts of endpoint, clear the stall */
308                 US_DEBUGP("clearing endpoint halt for pipe 0x%x\n", pipe);
309                 if (usb_stor_clear_halt(us, pipe) < 0)
310                         return USB_STOR_XFER_ERROR;
311                 return USB_STOR_XFER_STALLED;
312
313         /* timeout or excessively long NAK */
314         case -ETIMEDOUT:
315                 US_DEBUGP("-- timeout or NAK\n");
316                 return USB_STOR_XFER_ERROR;
317
318         /* babble - the device tried to send more than we wanted to read */
319         case -EOVERFLOW:
320                 US_DEBUGP("-- babble\n");
321                 return USB_STOR_XFER_LONG;
322
323         /* the transfer was cancelled by abort, disconnect, or timeout */
324         case -ECONNRESET:
325                 US_DEBUGP("-- transfer cancelled\n");
326                 return USB_STOR_XFER_ERROR;
327
328         /* short scatter-gather read transfer */
329         case -EREMOTEIO:
330                 US_DEBUGP("-- short read transfer\n");
331                 return USB_STOR_XFER_SHORT;
332
333         /* abort or disconnect in progress */
334         case -EIO:
335                 US_DEBUGP("-- abort or disconnect in progress\n");
336                 return USB_STOR_XFER_ERROR;
337
338         /* the catch-all error case */
339         default:
340                 US_DEBUGP("-- unknown error\n");
341                 return USB_STOR_XFER_ERROR;
342         }
343 }
344
345 /*
346  * Transfer one control message, without timeouts, but allowing early
347  * termination.  Return codes are USB_STOR_XFER_xxx.
348  */
349 int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe,
350                 u8 request, u8 requesttype, u16 value, u16 index,
351                 void *data, u16 size)
352 {
353         int result;
354
355         US_DEBUGP("%s: rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
356                         __FUNCTION__, request, requesttype,
357                         value, index, size);
358
359         /* fill in the devrequest structure */
360         us->cr->bRequestType = requesttype;
361         us->cr->bRequest = request;
362         us->cr->wValue = cpu_to_le16(value);
363         us->cr->wIndex = cpu_to_le16(index);
364         us->cr->wLength = cpu_to_le16(size);
365
366         /* fill and submit the URB */
367         usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
368                          (unsigned char*) us->cr, data, size, 
369                          usb_stor_blocking_completion, NULL);
370         result = usb_stor_msg_common(us, 0);
371
372         return interpret_urb_result(us, pipe, size, result,
373                         us->current_urb->actual_length);
374 }
375
376 /*
377  * Receive one interrupt buffer, without timeouts, but allowing early
378  * termination.  Return codes are USB_STOR_XFER_xxx.
379  *
380  * This routine always uses us->recv_intr_pipe as the pipe and
381  * us->ep_bInterval as the interrupt interval.
382  */
383 int usb_stor_intr_transfer(struct us_data *us, void *buf, unsigned int length)
384 {
385         int result;
386         unsigned int pipe = us->recv_intr_pipe;
387         unsigned int maxp;
388
389         US_DEBUGP("%s: xfer %u bytes\n", __FUNCTION__, length);
390
391         /* calculate the max packet size */
392         maxp = usb_maxpacket(us->pusb_dev, pipe, usb_pipeout(pipe));
393         if (maxp > length)
394                 maxp = length;
395
396         /* fill and submit the URB */
397         usb_fill_int_urb(us->current_urb, us->pusb_dev, pipe, buf,
398                         maxp, usb_stor_blocking_completion, NULL,
399                         us->ep_bInterval);
400         result = usb_stor_msg_common(us, 0);
401
402         return interpret_urb_result(us, pipe, length, result,
403                         us->current_urb->actual_length);
404 }
405
406 /*
407  * Transfer one buffer via bulk pipe, without timeouts, but allowing early
408  * termination.  Return codes are USB_STOR_XFER_xxx.  If the bulk pipe
409  * stalls during the transfer, the halt is automatically cleared.
410  */
411 int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe,
412         void *buf, unsigned int length, unsigned int *act_len)
413 {
414         int result;
415
416         US_DEBUGP("%s: xfer %u bytes\n", __FUNCTION__, length);
417
418         /* fill and submit the URB */
419         usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length,
420                       usb_stor_blocking_completion, NULL);
421         result = usb_stor_msg_common(us, 0);
422
423         /* store the actual length of the data transferred */
424         if (act_len)
425                 *act_len = us->current_urb->actual_length;
426         return interpret_urb_result(us, pipe, length, result, 
427                         us->current_urb->actual_length);
428 }
429
430 /*
431  * Transfer a scatter-gather list via bulk transfer
432  *
433  * This function does basically the same thing as usb_stor_bulk_transfer_buf()
434  * above, but it uses the usbcore scatter-gather library.
435  */
436 int usb_stor_bulk_transfer_sglist(struct us_data *us, unsigned int pipe,
437                 struct scatterlist *sg, int num_sg, unsigned int length,
438                 unsigned int *act_len)
439 {
440         int result;
441
442         /* don't submit s-g requests during abort/disconnect processing */
443         if (us->flags & ABORTING_OR_DISCONNECTING)
444                 return USB_STOR_XFER_ERROR;
445
446         /* initialize the scatter-gather request block */
447         US_DEBUGP("%s: xfer %u bytes, %d entries\n", __FUNCTION__,
448                         length, num_sg);
449         result = usb_sg_init(&us->current_sg, us->pusb_dev, pipe, 0,
450                         sg, num_sg, length, SLAB_NOIO);
451         if (result) {
452                 US_DEBUGP("usb_sg_init returned %d\n", result);
453                 return USB_STOR_XFER_ERROR;
454         }
455
456         /* since the block has been initialized successfully, it's now
457          * okay to cancel it */
458         set_bit(US_FLIDX_SG_ACTIVE, &us->flags);
459
460         /* did an abort/disconnect occur during the submission? */
461         if (us->flags & ABORTING_OR_DISCONNECTING) {
462
463                 /* cancel the request, if it hasn't been cancelled already */
464                 if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->flags)) {
465                         US_DEBUGP("-- cancelling sg request\n");
466                         usb_sg_cancel(&us->current_sg);
467                 }
468         }
469
470         /* wait for the completion of the transfer */
471         usb_sg_wait(&us->current_sg);
472         clear_bit(US_FLIDX_SG_ACTIVE, &us->flags);
473
474         result = us->current_sg.status;
475         if (act_len)
476                 *act_len = us->current_sg.bytes;
477         return interpret_urb_result(us, pipe, length, result,
478                         us->current_sg.bytes);
479 }
480
481 /*
482  * Transfer an entire SCSI command's worth of data payload over the bulk
483  * pipe.
484  *
485  * Note that this uses usb_stor_bulk_transfer_buf() and
486  * usb_stor_bulk_transfer_sglist() to achieve its goals --
487  * this function simply determines whether we're going to use
488  * scatter-gather or not, and acts appropriately.
489  */
490 int usb_stor_bulk_transfer_sg(struct us_data* us, unsigned int pipe,
491                 void *buf, unsigned int length_left, int use_sg, int *residual)
492 {
493         int result;
494         unsigned int partial;
495
496         /* are we scatter-gathering? */
497         if (use_sg) {
498                 /* use the usb core scatter-gather primitives */
499                 result = usb_stor_bulk_transfer_sglist(us, pipe,
500                                 (struct scatterlist *) buf, use_sg,
501                                 length_left, &partial);
502                 length_left -= partial;
503         } else {
504                 /* no scatter-gather, just make the request */
505                 result = usb_stor_bulk_transfer_buf(us, pipe, buf, 
506                                 length_left, &partial);
507                 length_left -= partial;
508         }
509
510         /* store the residual and return the error code */
511         if (residual)
512                 *residual = length_left;
513         return result;
514 }
515
516 /***********************************************************************
517  * Transport routines
518  ***********************************************************************/
519
520 /* Invoke the transport and basic error-handling/recovery methods
521  *
522  * This is used by the protocol layers to actually send the message to
523  * the device and receive the response.
524  */
525 void usb_stor_invoke_transport(Scsi_Cmnd *srb, struct us_data *us)
526 {
527         int need_auto_sense;
528         int result;
529
530         /* send the command to the transport layer */
531         srb->resid = 0;
532         result = us->transport(srb, us);
533
534         /* if the command gets aborted by the higher layers, we need to
535          * short-circuit all other processing
536          */
537         if (us->sm_state == US_STATE_ABORTING) {
538                 US_DEBUGP("-- command was aborted\n");
539                 goto Handle_Abort;
540         }
541
542         /* if there is a transport error, reset and don't auto-sense */
543         if (result == USB_STOR_TRANSPORT_ERROR) {
544                 US_DEBUGP("-- transport indicates error, resetting\n");
545                 us->transport_reset(us);
546                 srb->result = DID_ERROR << 16;
547                 return;
548         }
549
550         /* if the transport provided its own sense data, don't auto-sense */
551         if (result == USB_STOR_TRANSPORT_NO_SENSE) {
552                 srb->result = SAM_STAT_CHECK_CONDITION;
553                 return;
554         }
555
556         srb->result = SAM_STAT_GOOD;
557
558         /* Determine if we need to auto-sense
559          *
560          * I normally don't use a flag like this, but it's almost impossible
561          * to understand what's going on here if I don't.
562          */
563         need_auto_sense = 0;
564
565         /*
566          * If we're running the CB transport, which is incapable
567          * of determining status on its own, we will auto-sense
568          * unless the operation involved a data-in transfer.  Devices
569          * can signal most data-in errors by stalling the bulk-in pipe.
570          */
571         if ((us->protocol == US_PR_CB || us->protocol == US_PR_DPCM_USB) &&
572                         srb->sc_data_direction != SCSI_DATA_READ) {
573                 US_DEBUGP("-- CB transport device requiring auto-sense\n");
574                 need_auto_sense = 1;
575         }
576
577         /*
578          * If we have a failure, we're going to do a REQUEST_SENSE 
579          * automatically.  Note that we differentiate between a command
580          * "failure" and an "error" in the transport mechanism.
581          */
582         if (result == USB_STOR_TRANSPORT_FAILED) {
583                 US_DEBUGP("-- transport indicates command failure\n");
584                 need_auto_sense = 1;
585         }
586
587         /*
588          * A short transfer on a command where we don't expect it
589          * is unusual, but it doesn't mean we need to auto-sense.
590          */
591         if ((srb->resid > 0) &&
592             !((srb->cmnd[0] == REQUEST_SENSE) ||
593               (srb->cmnd[0] == INQUIRY) ||
594               (srb->cmnd[0] == MODE_SENSE) ||
595               (srb->cmnd[0] == LOG_SENSE) ||
596               (srb->cmnd[0] == MODE_SENSE_10))) {
597                 US_DEBUGP("-- unexpectedly short transfer\n");
598         }
599
600         /* Now, if we need to do the auto-sense, let's do it */
601         if (need_auto_sense) {
602                 int temp_result;
603                 void* old_request_buffer;
604                 unsigned short old_sg;
605                 unsigned old_request_bufflen;
606                 unsigned char old_sc_data_direction;
607                 unsigned char old_cmd_len;
608                 unsigned char old_cmnd[MAX_COMMAND_SIZE];
609                 unsigned long old_serial_number;
610                 int old_resid;
611
612                 US_DEBUGP("Issuing auto-REQUEST_SENSE\n");
613
614                 /* save the old command */
615                 memcpy(old_cmnd, srb->cmnd, MAX_COMMAND_SIZE);
616                 old_cmd_len = srb->cmd_len;
617
618                 /* set the command and the LUN */
619                 memset(srb->cmnd, 0, MAX_COMMAND_SIZE);
620                 srb->cmnd[0] = REQUEST_SENSE;
621                 srb->cmnd[1] = old_cmnd[1] & 0xE0;
622                 srb->cmnd[4] = 18;
623
624                 /* FIXME: we must do the protocol translation here */
625                 if (us->subclass == US_SC_RBC || us->subclass == US_SC_SCSI)
626                         srb->cmd_len = 6;
627                 else
628                         srb->cmd_len = 12;
629
630                 /* set the transfer direction */
631                 old_sc_data_direction = srb->sc_data_direction;
632                 srb->sc_data_direction = SCSI_DATA_READ;
633
634                 /* use the new buffer we have */
635                 old_request_buffer = srb->request_buffer;
636                 srb->request_buffer = srb->sense_buffer;
637
638                 /* set the buffer length for transfer */
639                 old_request_bufflen = srb->request_bufflen;
640                 srb->request_bufflen = 18;
641
642                 /* set up for no scatter-gather use */
643                 old_sg = srb->use_sg;
644                 srb->use_sg = 0;
645
646                 /* change the serial number -- toggle the high bit*/
647                 old_serial_number = srb->serial_number;
648                 srb->serial_number ^= 0x80000000;
649
650                 /* issue the auto-sense command */
651                 old_resid = srb->resid;
652                 srb->resid = 0;
653                 temp_result = us->transport(us->srb, us);
654
655                 /* let's clean up right away */
656                 srb->resid = old_resid;
657                 srb->request_buffer = old_request_buffer;
658                 srb->request_bufflen = old_request_bufflen;
659                 srb->use_sg = old_sg;
660                 srb->serial_number = old_serial_number;
661                 srb->sc_data_direction = old_sc_data_direction;
662                 srb->cmd_len = old_cmd_len;
663                 memcpy(srb->cmnd, old_cmnd, MAX_COMMAND_SIZE);
664
665                 if (us->sm_state == US_STATE_ABORTING) {
666                         US_DEBUGP("-- auto-sense aborted\n");
667                         goto Handle_Abort;
668                 }
669                 if (temp_result != USB_STOR_TRANSPORT_GOOD) {
670                         US_DEBUGP("-- auto-sense failure\n");
671
672                         /* we skip the reset if this happens to be a
673                          * multi-target device, since failure of an
674                          * auto-sense is perfectly valid
675                          */
676                         if (!(us->flags & US_FL_SCM_MULT_TARG))
677                                 us->transport_reset(us);
678                         srb->result = DID_ERROR << 16;
679                         return;
680                 }
681
682                 US_DEBUGP("-- Result from auto-sense is %d\n", temp_result);
683                 US_DEBUGP("-- code: 0x%x, key: 0x%x, ASC: 0x%x, ASCQ: 0x%x\n",
684                           srb->sense_buffer[0],
685                           srb->sense_buffer[2] & 0xf,
686                           srb->sense_buffer[12], 
687                           srb->sense_buffer[13]);
688 #ifdef CONFIG_USB_STORAGE_DEBUG
689                 usb_stor_show_sense(
690                           srb->sense_buffer[2] & 0xf,
691                           srb->sense_buffer[12], 
692                           srb->sense_buffer[13]);
693 #endif
694
695                 /* set the result so the higher layers expect this data */
696                 srb->result = SAM_STAT_CHECK_CONDITION;
697
698                 /* If things are really okay, then let's show that.  Zero
699                  * out the sense buffer so the higher layers won't realize
700                  * we did an unsolicited auto-sense. */
701                 if (result == USB_STOR_TRANSPORT_GOOD &&
702                         /* Filemark 0, ignore EOM, ILI 0, no sense */
703                                 (srb->sense_buffer[2] & 0xaf) == 0 &&
704                         /* No ASC or ASCQ */
705                                 srb->sense_buffer[12] == 0 &&
706                                 srb->sense_buffer[13] == 0) {
707                         srb->result = SAM_STAT_GOOD;
708                         srb->sense_buffer[0] = 0x0;
709                 }
710         }
711
712         /* Did we transfer less than the minimum amount required? */
713         if (srb->result == SAM_STAT_GOOD &&
714                         srb->request_bufflen - srb->resid < srb->underflow)
715                 srb->result = (DID_ERROR << 16) | (SUGGEST_RETRY << 24);
716
717         return;
718
719         /* abort processing: the bulk-only transport requires a reset
720          * following an abort */
721   Handle_Abort:
722         srb->result = DID_ABORT << 16;
723         if (us->protocol == US_PR_BULK)
724                 us->transport_reset(us);
725 }
726
727 /* Stop the current URB transfer */
728 void usb_stor_stop_transport(struct us_data *us)
729 {
730         US_DEBUGP("%s called\n", __FUNCTION__);
731
732         /* If the state machine is blocked waiting for an URB,
733          * let's wake it up.  The test_and_clear_bit() call
734          * guarantees that if a URB has just been submitted,
735          * it won't be cancelled more than once. */
736         if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->flags)) {
737                 US_DEBUGP("-- cancelling URB\n");
738                 usb_unlink_urb(us->current_urb);
739         }
740
741         /* If we are waiting for a scatter-gather operation, cancel it. */
742         if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->flags)) {
743                 US_DEBUGP("-- cancelling sg request\n");
744                 usb_sg_cancel(&us->current_sg);
745         }
746 }
747
748 /*
749  * Control/Bulk/Interrupt transport
750  */
751
752 int usb_stor_CBI_transport(Scsi_Cmnd *srb, struct us_data *us)
753 {
754         unsigned int transfer_length = srb->request_bufflen;
755         unsigned int pipe = 0;
756         int result;
757
758         /* COMMAND STAGE */
759         /* let's send the command via the control pipe */
760         result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
761                                       US_CBI_ADSC, 
762                                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
763                                       us->ifnum, srb->cmnd, srb->cmd_len);
764
765         /* check the return code for the command */
766         US_DEBUGP("Call to usb_stor_ctrl_transfer() returned %d\n", result);
767
768         /* if we stalled the command, it means command failed */
769         if (result == USB_STOR_XFER_STALLED) {
770                 return USB_STOR_TRANSPORT_FAILED;
771         }
772
773         /* Uh oh... serious problem here */
774         if (result != USB_STOR_XFER_GOOD) {
775                 return USB_STOR_TRANSPORT_ERROR;
776         }
777
778         /* DATA STAGE */
779         /* transfer the data payload for this command, if one exists*/
780         if (transfer_length) {
781                 pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
782                                 us->recv_bulk_pipe : us->send_bulk_pipe;
783                 result = usb_stor_bulk_transfer_sg(us, pipe,
784                                         srb->request_buffer, transfer_length,
785                                         srb->use_sg, &srb->resid);
786                 US_DEBUGP("CBI data stage result is 0x%x\n", result);
787
788                 /* if we stalled the data transfer it means command failed */
789                 if (result == USB_STOR_XFER_STALLED)
790                         return USB_STOR_TRANSPORT_FAILED;
791                 if (result > USB_STOR_XFER_STALLED)
792                         return USB_STOR_TRANSPORT_ERROR;
793         }
794
795         /* STATUS STAGE */
796         result = usb_stor_intr_transfer(us, us->iobuf, 2);
797         US_DEBUGP("Got interrupt data (0x%x, 0x%x)\n", 
798                         us->iobuf[0], us->iobuf[1]);
799         if (result != USB_STOR_XFER_GOOD)
800                 return USB_STOR_TRANSPORT_ERROR;
801
802         /* UFI gives us ASC and ASCQ, like a request sense
803          *
804          * REQUEST_SENSE and INQUIRY don't affect the sense data on UFI
805          * devices, so we ignore the information for those commands.  Note
806          * that this means we could be ignoring a real error on these
807          * commands, but that can't be helped.
808          */
809         if (us->subclass == US_SC_UFI) {
810                 if (srb->cmnd[0] == REQUEST_SENSE ||
811                     srb->cmnd[0] == INQUIRY)
812                         return USB_STOR_TRANSPORT_GOOD;
813                 if (us->iobuf[0])
814                         goto Failed;
815                 return USB_STOR_TRANSPORT_GOOD;
816         }
817
818         /* If not UFI, we interpret the data as a result code 
819          * The first byte should always be a 0x0.
820          *
821          * Some bogus devices don't follow that rule.  They stuff the ASC
822          * into the first byte -- so if it's non-zero, call it a failure.
823          */
824         if (us->iobuf[0]) {
825                 US_DEBUGP("CBI IRQ data showed reserved bType 0x%x\n",
826                                 us->iobuf[0]);
827                 goto Failed;
828
829         }
830
831         /* The second byte & 0x0F should be 0x0 for good, otherwise error */
832         switch (us->iobuf[1] & 0x0F) {
833                 case 0x00: 
834                         return USB_STOR_TRANSPORT_GOOD;
835                 case 0x01: 
836                         goto Failed;
837         }
838         return USB_STOR_TRANSPORT_ERROR;
839
840         /* the CBI spec requires that the bulk pipe must be cleared
841          * following any data-in/out command failure (section 2.4.3.1.3)
842          */
843   Failed:
844         if (pipe)
845                 usb_stor_clear_halt(us, pipe);
846         return USB_STOR_TRANSPORT_FAILED;
847 }
848
849 /*
850  * Control/Bulk transport
851  */
852 int usb_stor_CB_transport(Scsi_Cmnd *srb, struct us_data *us)
853 {
854         unsigned int transfer_length = srb->request_bufflen;
855         int result;
856
857         /* COMMAND STAGE */
858         /* let's send the command via the control pipe */
859         result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
860                                       US_CBI_ADSC, 
861                                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
862                                       us->ifnum, srb->cmnd, srb->cmd_len);
863
864         /* check the return code for the command */
865         US_DEBUGP("Call to usb_stor_ctrl_transfer() returned %d\n", result);
866
867         /* if we stalled the command, it means command failed */
868         if (result == USB_STOR_XFER_STALLED) {
869                 return USB_STOR_TRANSPORT_FAILED;
870         }
871
872         /* Uh oh... serious problem here */
873         if (result != USB_STOR_XFER_GOOD) {
874                 return USB_STOR_TRANSPORT_ERROR;
875         }
876
877         /* DATA STAGE */
878         /* transfer the data payload for this command, if one exists*/
879         if (transfer_length) {
880                 unsigned int pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
881                                 us->recv_bulk_pipe : us->send_bulk_pipe;
882                 result = usb_stor_bulk_transfer_sg(us, pipe,
883                                         srb->request_buffer, transfer_length,
884                                         srb->use_sg, &srb->resid);
885                 US_DEBUGP("CB data stage result is 0x%x\n", result);
886
887                 /* if we stalled the data transfer it means command failed */
888                 if (result == USB_STOR_XFER_STALLED)
889                         return USB_STOR_TRANSPORT_FAILED;
890                 if (result > USB_STOR_XFER_STALLED)
891                         return USB_STOR_TRANSPORT_ERROR;
892         }
893
894         /* STATUS STAGE */
895         /* NOTE: CB does not have a status stage.  Silly, I know.  So
896          * we have to catch this at a higher level.
897          */
898         return USB_STOR_TRANSPORT_GOOD;
899 }
900
901 /*
902  * Bulk only transport
903  */
904
905 /* Determine what the maximum LUN supported is */
906 int usb_stor_Bulk_max_lun(struct us_data *us)
907 {
908         int result;
909
910         /* issue the command */
911         result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
912                                  US_BULK_GET_MAX_LUN, 
913                                  USB_DIR_IN | USB_TYPE_CLASS | 
914                                  USB_RECIP_INTERFACE,
915                                  0, us->ifnum, us->iobuf, 1, HZ);
916
917         US_DEBUGP("GetMaxLUN command result is %d, data is %d\n", 
918                   result, us->iobuf[0]);
919
920         /* if we have a successful request, return the result */
921         if (result == 1)
922                 return us->iobuf[0];
923
924         /* 
925          * Some devices (i.e. Iomega Zip100) need this -- apparently
926          * the bulk pipes get STALLed when the GetMaxLUN request is
927          * processed.   This is, in theory, harmless to all other devices
928          * (regardless of if they stall or not).
929          */
930         if (result == -EPIPE) {
931                 usb_stor_clear_halt(us, us->recv_bulk_pipe);
932                 usb_stor_clear_halt(us, us->send_bulk_pipe);
933                 /* return the default -- no LUNs */
934                 return 0;
935         }
936
937         /* An answer or a STALL are the only valid responses.  If we get
938          * something else, return an indication of error */
939         return -1;
940 }
941
942 int usb_stor_Bulk_transport(Scsi_Cmnd *srb, struct us_data *us)
943 {
944         struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
945         struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
946         unsigned int transfer_length = srb->request_bufflen;
947         unsigned int residue;
948         int result;
949         int fake_sense = 0;
950         unsigned int cswlen;
951
952         /* set up the command wrapper */
953         bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
954         bcb->DataTransferLength = cpu_to_le32(transfer_length);
955         bcb->Flags = srb->sc_data_direction == SCSI_DATA_READ ? 1 << 7 : 0;
956         bcb->Tag = srb->serial_number;
957         bcb->Lun = srb->device->lun;
958         if (us->flags & US_FL_SCM_MULT_TARG)
959                 bcb->Lun |= srb->device->id << 4;
960         bcb->Length = srb->cmd_len;
961
962         /* copy the command payload */
963         memset(bcb->CDB, 0, sizeof(bcb->CDB));
964         memcpy(bcb->CDB, srb->cmnd, bcb->Length);
965
966         /* send it to out endpoint */
967         US_DEBUGP("Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
968                         le32_to_cpu(bcb->Signature), bcb->Tag,
969                         le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
970                         (bcb->Lun >> 4), (bcb->Lun & 0x0F), 
971                         bcb->Length);
972         result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
973                                 bcb, US_BULK_CB_WRAP_LEN, NULL);
974         US_DEBUGP("Bulk command transfer result=%d\n", result);
975         if (result != USB_STOR_XFER_GOOD)
976                 return USB_STOR_TRANSPORT_ERROR;
977
978         /* DATA STAGE */
979         /* send/receive data payload, if there is any */
980         if (transfer_length) {
981                 unsigned int pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
982                                 us->recv_bulk_pipe : us->send_bulk_pipe;
983                 result = usb_stor_bulk_transfer_sg(us, pipe,
984                                         srb->request_buffer, transfer_length,
985                                         srb->use_sg, &srb->resid);
986                 US_DEBUGP("Bulk data transfer result 0x%x\n", result);
987                 if (result == USB_STOR_XFER_ERROR)
988                         return USB_STOR_TRANSPORT_ERROR;
989
990                 /* If the device tried to send back more data than the
991                  * amount requested, the spec requires us to transfer
992                  * the CSW anyway.  Since there's no point retrying the
993                  * the command, we'll return fake sense data indicating
994                  * Illegal Request, Invalid Field in CDB.
995                  */
996                 if (result == USB_STOR_XFER_LONG)
997                         fake_sense = 1;
998         }
999
1000         /* See flow chart on pg 15 of the Bulk Only Transport spec for
1001          * an explanation of how this code works.
1002          */
1003
1004         /* get CSW for device status */
1005         US_DEBUGP("Attempting to get CSW...\n");
1006         result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1007                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1008
1009         /* Some broken devices add unnecessary zero-length packets to the
1010          * end of their data transfers.  Such packets show up as 0-length
1011          * CSWs.  If we encounter such a thing, try to read the CSW again.
1012          */
1013         if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
1014                 US_DEBUGP("Received 0-length CSW; retrying...\n");
1015                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1016                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1017         }
1018
1019         /* did the attempt to read the CSW fail? */
1020         if (result == USB_STOR_XFER_STALLED) {
1021
1022                 /* get the status again */
1023                 US_DEBUGP("Attempting to get CSW (2nd try)...\n");
1024                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1025                                 bcs, US_BULK_CS_WRAP_LEN, NULL);
1026         }
1027
1028         /* if we still have a failure at this point, we're in trouble */
1029         US_DEBUGP("Bulk status result = %d\n", result);
1030         if (result != USB_STOR_XFER_GOOD)
1031                 return USB_STOR_TRANSPORT_ERROR;
1032
1033         /* check bulk status */
1034         residue = le32_to_cpu(bcs->Residue);
1035         US_DEBUGP("Bulk Status S 0x%x T 0x%x R %u Stat 0x%x\n",
1036                         le32_to_cpu(bcs->Signature), bcs->Tag, 
1037                         residue, bcs->Status);
1038         if ((bcs->Signature != cpu_to_le32(US_BULK_CS_SIGN) &&
1039                     bcs->Signature != cpu_to_le32(US_BULK_CS_OLYMPUS_SIGN)) ||
1040                         bcs->Tag != srb->serial_number || 
1041                         bcs->Status > US_BULK_STAT_PHASE) {
1042                 US_DEBUGP("Bulk logical error\n");
1043                 return USB_STOR_TRANSPORT_ERROR;
1044         }
1045
1046         /* try to compute the actual residue, based on how much data
1047          * was really transferred and what the device tells us */
1048         residue = min(residue, transfer_length);
1049         srb->resid = max(srb->resid, (int) residue);
1050
1051         /* based on the status code, we report good or bad */
1052         switch (bcs->Status) {
1053                 case US_BULK_STAT_OK:
1054                         /* device babbled -- return fake sense data */
1055                         if (fake_sense) {
1056                                 memcpy(srb->sense_buffer, 
1057                                        usb_stor_sense_invalidCDB, 
1058                                        sizeof(usb_stor_sense_invalidCDB));
1059                                 return USB_STOR_TRANSPORT_NO_SENSE;
1060                         }
1061
1062                         /* command good -- note that data could be short */
1063                         return USB_STOR_TRANSPORT_GOOD;
1064
1065                 case US_BULK_STAT_FAIL:
1066                         /* command failed */
1067                         return USB_STOR_TRANSPORT_FAILED;
1068
1069                 case US_BULK_STAT_PHASE:
1070                         /* phase error -- note that a transport reset will be
1071                          * invoked by the invoke_transport() function
1072                          */
1073                         return USB_STOR_TRANSPORT_ERROR;
1074         }
1075
1076         /* we should never get here, but if we do, we're in trouble */
1077         return USB_STOR_TRANSPORT_ERROR;
1078 }
1079
1080 /***********************************************************************
1081  * Reset routines
1082  ***********************************************************************/
1083
1084 /* This is the common part of the device reset code.
1085  *
1086  * It's handy that every transport mechanism uses the control endpoint for
1087  * resets.
1088  *
1089  * Basically, we send a reset with a 20-second timeout, so we don't get
1090  * jammed attempting to do the reset.
1091  */
1092 static int usb_stor_reset_common(struct us_data *us,
1093                 u8 request, u8 requesttype,
1094                 u16 value, u16 index, void *data, u16 size)
1095 {
1096         int result;
1097         int result2;
1098         int rc = FAILED;
1099
1100         /* Let the SCSI layer know we are doing a reset, set the
1101          * RESETTING bit, and clear the ABORTING bit so that the reset
1102          * may proceed.
1103          */
1104         scsi_lock(us->host);
1105         usb_stor_report_device_reset(us);
1106         set_bit(US_FLIDX_RESETTING, &us->flags);
1107         clear_bit(US_FLIDX_ABORTING, &us->flags);
1108         scsi_unlock(us->host);
1109
1110         /* A 20-second timeout may seem rather long, but a LaCie
1111          * StudioDrive USB2 device takes 16+ seconds to get going
1112          * following a powerup or USB attach event.
1113          */
1114         result = usb_stor_control_msg(us, us->send_ctrl_pipe,
1115                         request, requesttype, value, index, data, size,
1116                         20*HZ);
1117         if (result < 0) {
1118                 US_DEBUGP("Soft reset failed: %d\n", result);
1119                 goto Done;
1120         }
1121
1122         /* Give the device some time to recover from the reset,
1123          * but don't delay disconnect processing. */
1124         wait_event_interruptible_timeout(us->dev_reset_wait,
1125                         test_bit(US_FLIDX_DISCONNECTING, &us->flags),
1126                         HZ*6);
1127         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
1128                 US_DEBUGP("Reset interrupted by disconnect\n");
1129                 goto Done;
1130         }
1131
1132         US_DEBUGP("Soft reset: clearing bulk-in endpoint halt\n");
1133         result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
1134
1135         US_DEBUGP("Soft reset: clearing bulk-out endpoint halt\n");
1136         result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
1137
1138         /* return a result code based on the result of the control message */
1139         if (result < 0 || result2 < 0) {
1140                 US_DEBUGP("Soft reset failed\n");
1141                 goto Done;
1142         }
1143         US_DEBUGP("Soft reset done\n");
1144         rc = SUCCESS;
1145
1146   Done:
1147         clear_bit(US_FLIDX_RESETTING, &us->flags);
1148         return rc;
1149 }
1150
1151 /* This issues a CB[I] Reset to the device in question
1152  */
1153 #define CB_RESET_CMD_SIZE       12
1154
1155 int usb_stor_CB_reset(struct us_data *us)
1156 {
1157         US_DEBUGP("%s called\n", __FUNCTION__);
1158
1159         memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
1160         us->iobuf[0] = SEND_DIAGNOSTIC;
1161         us->iobuf[1] = 4;
1162         return usb_stor_reset_common(us, US_CBI_ADSC, 
1163                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1164                                  0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
1165 }
1166
1167 /* This issues a Bulk-only Reset to the device in question, including
1168  * clearing the subsequent endpoint halts that may occur.
1169  */
1170 int usb_stor_Bulk_reset(struct us_data *us)
1171 {
1172         US_DEBUGP("%s called\n", __FUNCTION__);
1173
1174         return usb_stor_reset_common(us, US_BULK_RESET_REQUEST, 
1175                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1176                                  0, us->ifnum, NULL, 0);
1177 }