ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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 & DONT_SUBMIT)
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 & DONT_SUBMIT) {
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 & DONT_SUBMIT)
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 & DONT_SUBMIT) {
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         return;
712
713         /* abort processing: the bulk-only transport requires a reset
714          * following an abort */
715         Handle_Abort:
716         srb->result = DID_ABORT << 16;
717         if (us->protocol == US_PR_BULK) {
718
719                 /* permit the reset transfer to take place */
720                 clear_bit(US_FLIDX_ABORTING, &us->flags);
721                 us->transport_reset(us);
722         }
723 }
724
725 /* Stop the current URB transfer */
726 void usb_stor_stop_transport(struct us_data *us)
727 {
728         US_DEBUGP("%s called\n", __FUNCTION__);
729
730         /* If the state machine is blocked waiting for an URB,
731          * let's wake it up.  The test_and_clear_bit() call
732          * guarantees that if a URB has just been submitted,
733          * it won't be cancelled more than once. */
734         if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->flags)) {
735                 US_DEBUGP("-- cancelling URB\n");
736                 usb_unlink_urb(us->current_urb);
737         }
738
739         /* If we are waiting for a scatter-gather operation, cancel it. */
740         if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->flags)) {
741                 US_DEBUGP("-- cancelling sg request\n");
742                 usb_sg_cancel(&us->current_sg);
743         }
744 }
745
746 /*
747  * Control/Bulk/Interrupt transport
748  */
749
750 int usb_stor_CBI_transport(Scsi_Cmnd *srb, struct us_data *us)
751 {
752         unsigned int transfer_length = srb->request_bufflen;
753         unsigned int pipe = 0;
754         int result;
755
756         /* COMMAND STAGE */
757         /* let's send the command via the control pipe */
758         result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
759                                       US_CBI_ADSC, 
760                                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
761                                       us->ifnum, srb->cmnd, srb->cmd_len);
762
763         /* check the return code for the command */
764         US_DEBUGP("Call to usb_stor_ctrl_transfer() returned %d\n", result);
765
766         /* if we stalled the command, it means command failed */
767         if (result == USB_STOR_XFER_STALLED) {
768                 return USB_STOR_TRANSPORT_FAILED;
769         }
770
771         /* Uh oh... serious problem here */
772         if (result != USB_STOR_XFER_GOOD) {
773                 return USB_STOR_TRANSPORT_ERROR;
774         }
775
776         /* DATA STAGE */
777         /* transfer the data payload for this command, if one exists*/
778         if (transfer_length) {
779                 pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
780                                 us->recv_bulk_pipe : us->send_bulk_pipe;
781                 result = usb_stor_bulk_transfer_sg(us, pipe,
782                                         srb->request_buffer, transfer_length,
783                                         srb->use_sg, &srb->resid);
784                 US_DEBUGP("CBI data stage result is 0x%x\n", result);
785
786                 /* if we stalled the data transfer it means command failed */
787                 if (result == USB_STOR_XFER_STALLED)
788                         return USB_STOR_TRANSPORT_FAILED;
789                 if (result > USB_STOR_XFER_STALLED)
790                         return USB_STOR_TRANSPORT_ERROR;
791         }
792
793         /* STATUS STAGE */
794         result = usb_stor_intr_transfer(us, us->iobuf, 2);
795         US_DEBUGP("Got interrupt data (0x%x, 0x%x)\n", 
796                         us->iobuf[0], us->iobuf[1]);
797         if (result != USB_STOR_XFER_GOOD)
798                 return USB_STOR_TRANSPORT_ERROR;
799
800         /* UFI gives us ASC and ASCQ, like a request sense
801          *
802          * REQUEST_SENSE and INQUIRY don't affect the sense data on UFI
803          * devices, so we ignore the information for those commands.  Note
804          * that this means we could be ignoring a real error on these
805          * commands, but that can't be helped.
806          */
807         if (us->subclass == US_SC_UFI) {
808                 if (srb->cmnd[0] == REQUEST_SENSE ||
809                     srb->cmnd[0] == INQUIRY)
810                         return USB_STOR_TRANSPORT_GOOD;
811                 if (us->iobuf[0])
812                         goto Failed;
813                 return USB_STOR_TRANSPORT_GOOD;
814         }
815
816         /* If not UFI, we interpret the data as a result code 
817          * The first byte should always be a 0x0.
818          *
819          * Some bogus devices don't follow that rule.  They stuff the ASC
820          * into the first byte -- so if it's non-zero, call it a failure.
821          */
822         if (us->iobuf[0]) {
823                 US_DEBUGP("CBI IRQ data showed reserved bType 0x%x\n",
824                                 us->iobuf[0]);
825                 goto Failed;
826
827         }
828
829         /* The second byte & 0x0F should be 0x0 for good, otherwise error */
830         switch (us->iobuf[1] & 0x0F) {
831                 case 0x00: 
832                         return USB_STOR_TRANSPORT_GOOD;
833                 case 0x01: 
834                         goto Failed;
835         }
836         return USB_STOR_TRANSPORT_ERROR;
837
838         /* the CBI spec requires that the bulk pipe must be cleared
839          * following any data-in/out command failure (section 2.4.3.1.3)
840          */
841   Failed:
842         if (pipe)
843                 usb_stor_clear_halt(us, pipe);
844         return USB_STOR_TRANSPORT_FAILED;
845 }
846
847 /*
848  * Control/Bulk transport
849  */
850 int usb_stor_CB_transport(Scsi_Cmnd *srb, struct us_data *us)
851 {
852         unsigned int transfer_length = srb->request_bufflen;
853         int result;
854
855         /* COMMAND STAGE */
856         /* let's send the command via the control pipe */
857         result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
858                                       US_CBI_ADSC, 
859                                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
860                                       us->ifnum, srb->cmnd, srb->cmd_len);
861
862         /* check the return code for the command */
863         US_DEBUGP("Call to usb_stor_ctrl_transfer() returned %d\n", result);
864
865         /* if we stalled the command, it means command failed */
866         if (result == USB_STOR_XFER_STALLED) {
867                 return USB_STOR_TRANSPORT_FAILED;
868         }
869
870         /* Uh oh... serious problem here */
871         if (result != USB_STOR_XFER_GOOD) {
872                 return USB_STOR_TRANSPORT_ERROR;
873         }
874
875         /* DATA STAGE */
876         /* transfer the data payload for this command, if one exists*/
877         if (transfer_length) {
878                 unsigned int pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
879                                 us->recv_bulk_pipe : us->send_bulk_pipe;
880                 result = usb_stor_bulk_transfer_sg(us, pipe,
881                                         srb->request_buffer, transfer_length,
882                                         srb->use_sg, &srb->resid);
883                 US_DEBUGP("CB data stage result is 0x%x\n", result);
884
885                 /* if we stalled the data transfer it means command failed */
886                 if (result == USB_STOR_XFER_STALLED)
887                         return USB_STOR_TRANSPORT_FAILED;
888                 if (result > USB_STOR_XFER_STALLED)
889                         return USB_STOR_TRANSPORT_ERROR;
890         }
891
892         /* STATUS STAGE */
893         /* NOTE: CB does not have a status stage.  Silly, I know.  So
894          * we have to catch this at a higher level.
895          */
896         return USB_STOR_TRANSPORT_GOOD;
897 }
898
899 /*
900  * Bulk only transport
901  */
902
903 /* Determine what the maximum LUN supported is */
904 int usb_stor_Bulk_max_lun(struct us_data *us)
905 {
906         int result;
907
908         /* issue the command */
909         result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
910                                  US_BULK_GET_MAX_LUN, 
911                                  USB_DIR_IN | USB_TYPE_CLASS | 
912                                  USB_RECIP_INTERFACE,
913                                  0, us->ifnum, us->iobuf, 1, HZ);
914
915         US_DEBUGP("GetMaxLUN command result is %d, data is %d\n", 
916                   result, us->iobuf[0]);
917
918         /* if we have a successful request, return the result */
919         if (result == 1)
920                 return us->iobuf[0];
921
922         /* return the default -- no LUNs */
923         return 0;
924 }
925
926 int usb_stor_Bulk_transport(Scsi_Cmnd *srb, struct us_data *us)
927 {
928         struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
929         struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
930         unsigned int transfer_length = srb->request_bufflen;
931         unsigned int residue;
932         int result;
933         int fake_sense = 0;
934         unsigned int cswlen;
935
936         /* set up the command wrapper */
937         bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
938         bcb->DataTransferLength = cpu_to_le32(transfer_length);
939         bcb->Flags = srb->sc_data_direction == SCSI_DATA_READ ? 1 << 7 : 0;
940         bcb->Tag = srb->serial_number;
941         bcb->Lun = srb->device->lun;
942         if (us->flags & US_FL_SCM_MULT_TARG)
943                 bcb->Lun |= srb->device->id << 4;
944         bcb->Length = srb->cmd_len;
945
946         /* copy the command payload */
947         memset(bcb->CDB, 0, sizeof(bcb->CDB));
948         memcpy(bcb->CDB, srb->cmnd, bcb->Length);
949
950         /* send it to out endpoint */
951         US_DEBUGP("Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
952                         le32_to_cpu(bcb->Signature), bcb->Tag,
953                         le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
954                         (bcb->Lun >> 4), (bcb->Lun & 0x0F), 
955                         bcb->Length);
956         result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
957                                 bcb, US_BULK_CB_WRAP_LEN, NULL);
958         US_DEBUGP("Bulk command transfer result=%d\n", result);
959         if (result != USB_STOR_XFER_GOOD)
960                 return USB_STOR_TRANSPORT_ERROR;
961
962         /* DATA STAGE */
963         /* send/receive data payload, if there is any */
964         if (transfer_length) {
965                 unsigned int pipe = srb->sc_data_direction == SCSI_DATA_READ ? 
966                                 us->recv_bulk_pipe : us->send_bulk_pipe;
967                 result = usb_stor_bulk_transfer_sg(us, pipe,
968                                         srb->request_buffer, transfer_length,
969                                         srb->use_sg, &srb->resid);
970                 US_DEBUGP("Bulk data transfer result 0x%x\n", result);
971                 if (result == USB_STOR_XFER_ERROR)
972                         return USB_STOR_TRANSPORT_ERROR;
973
974                 /* If the device tried to send back more data than the
975                  * amount requested, the spec requires us to transfer
976                  * the CSW anyway.  Since there's no point retrying the
977                  * the command, we'll return fake sense data indicating
978                  * Illegal Request, Invalid Field in CDB.
979                  */
980                 if (result == USB_STOR_XFER_LONG)
981                         fake_sense = 1;
982         }
983
984         /* See flow chart on pg 15 of the Bulk Only Transport spec for
985          * an explanation of how this code works.
986          */
987
988         /* get CSW for device status */
989         US_DEBUGP("Attempting to get CSW...\n");
990         result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
991                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
992
993         /* Some broken devices add unnecessary zero-length packets to the
994          * end of their data transfers.  Such packets show up as 0-length
995          * CSWs.  If we encounter such a thing, try to read the CSW again.
996          */
997         if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
998                 US_DEBUGP("Received 0-length CSW; retrying...\n");
999                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1000                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1001         }
1002
1003         /* did the attempt to read the CSW fail? */
1004         if (result == USB_STOR_XFER_STALLED) {
1005
1006                 /* get the status again */
1007                 US_DEBUGP("Attempting to get CSW (2nd try)...\n");
1008                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1009                                 bcs, US_BULK_CS_WRAP_LEN, NULL);
1010         }
1011
1012         /* if we still have a failure at this point, we're in trouble */
1013         US_DEBUGP("Bulk status result = %d\n", result);
1014         if (result != USB_STOR_XFER_GOOD)
1015                 return USB_STOR_TRANSPORT_ERROR;
1016
1017         /* check bulk status */
1018         residue = le32_to_cpu(bcs->Residue);
1019         US_DEBUGP("Bulk Status S 0x%x T 0x%x R %u Stat 0x%x\n",
1020                         le32_to_cpu(bcs->Signature), bcs->Tag, 
1021                         residue, bcs->Status);
1022         if ((bcs->Signature != cpu_to_le32(US_BULK_CS_SIGN) &&
1023                     bcs->Signature != cpu_to_le32(US_BULK_CS_OLYMPUS_SIGN)) ||
1024                         bcs->Tag != srb->serial_number || 
1025                         bcs->Status > US_BULK_STAT_PHASE) {
1026                 US_DEBUGP("Bulk logical error\n");
1027                 return USB_STOR_TRANSPORT_ERROR;
1028         }
1029
1030         /* try to compute the actual residue, based on how much data
1031          * was really transferred and what the device tells us */
1032         residue = min(residue, transfer_length);
1033         srb->resid = max(srb->resid, (int) residue);
1034
1035         /* based on the status code, we report good or bad */
1036         switch (bcs->Status) {
1037                 case US_BULK_STAT_OK:
1038                         /* device babbled -- return fake sense data */
1039                         if (fake_sense) {
1040                                 memcpy(srb->sense_buffer, 
1041                                        usb_stor_sense_invalidCDB, 
1042                                        sizeof(usb_stor_sense_invalidCDB));
1043                                 return USB_STOR_TRANSPORT_NO_SENSE;
1044                         }
1045
1046                         /* command good -- note that data could be short */
1047                         return USB_STOR_TRANSPORT_GOOD;
1048
1049                 case US_BULK_STAT_FAIL:
1050                         /* command failed */
1051                         return USB_STOR_TRANSPORT_FAILED;
1052
1053                 case US_BULK_STAT_PHASE:
1054                         /* phase error -- note that a transport reset will be
1055                          * invoked by the invoke_transport() function
1056                          */
1057                         return USB_STOR_TRANSPORT_ERROR;
1058         }
1059
1060         /* we should never get here, but if we do, we're in trouble */
1061         return USB_STOR_TRANSPORT_ERROR;
1062 }
1063
1064 /***********************************************************************
1065  * Reset routines
1066  ***********************************************************************/
1067
1068 /* This is the common part of the device reset code.
1069  *
1070  * It's handy that every transport mechanism uses the control endpoint for
1071  * resets.
1072  *
1073  * Basically, we send a reset with a 20-second timeout, so we don't get
1074  * jammed attempting to do the reset.
1075  */
1076 static int usb_stor_reset_common(struct us_data *us,
1077                 u8 request, u8 requesttype,
1078                 u16 value, u16 index, void *data, u16 size)
1079 {
1080         int result;
1081         int result2;
1082
1083         /* Let the SCSI layer know we are doing a reset */
1084         usb_stor_report_device_reset(us);
1085
1086         /* A 20-second timeout may seem rather long, but a LaCie
1087          *  StudioDrive USB2 device takes 16+ seconds to get going
1088          *  following a powerup or USB attach event. */
1089
1090         result = usb_stor_control_msg(us, us->send_ctrl_pipe,
1091                         request, requesttype, value, index, data, size,
1092                         20*HZ);
1093         if (result < 0) {
1094                 US_DEBUGP("Soft reset failed: %d\n", result);
1095                 return FAILED;
1096         }
1097
1098         /* long wait for reset, so unlock to allow disconnects */
1099         up(&us->dev_semaphore);
1100         set_current_state(TASK_UNINTERRUPTIBLE);
1101         schedule_timeout(HZ*6);
1102         down(&us->dev_semaphore);
1103         if (test_bit(US_FLIDX_DISCONNECTING, &us->flags)) {
1104                 US_DEBUGP("Reset interrupted by disconnect\n");
1105                 return FAILED;
1106         }
1107
1108         /* permit the clear-halt transfers to take place */
1109         clear_bit(US_FLIDX_ABORTING, &us->flags);
1110
1111         US_DEBUGP("Soft reset: clearing bulk-in endpoint halt\n");
1112         result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
1113
1114         US_DEBUGP("Soft reset: clearing bulk-out endpoint halt\n");
1115         result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
1116
1117         /* return a result code based on the result of the control message */
1118         if (result < 0 || result2 < 0) {
1119                 US_DEBUGP("Soft reset failed\n");
1120                 return FAILED;
1121         }
1122         US_DEBUGP("Soft reset done\n");
1123         return SUCCESS;
1124 }
1125
1126 /* This issues a CB[I] Reset to the device in question
1127  */
1128 #define CB_RESET_CMD_SIZE       12
1129
1130 int usb_stor_CB_reset(struct us_data *us)
1131 {
1132         US_DEBUGP("%s called\n", __FUNCTION__);
1133
1134         memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
1135         us->iobuf[0] = SEND_DIAGNOSTIC;
1136         us->iobuf[1] = 4;
1137         return usb_stor_reset_common(us, US_CBI_ADSC, 
1138                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1139                                  0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
1140 }
1141
1142 /* This issues a Bulk-only Reset to the device in question, including
1143  * clearing the subsequent endpoint halts that may occur.
1144  */
1145 int usb_stor_Bulk_reset(struct us_data *us)
1146 {
1147         US_DEBUGP("%s called\n", __FUNCTION__);
1148
1149         return usb_stor_reset_common(us, US_BULK_RESET_REQUEST, 
1150                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1151                                  0, us->ifnum, NULL, 0);
1152 }