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