GNU Linux-libre 4.14.251-gnu1
[releases.git] / drivers / usb / storage / transport.c
1 /*
2  * Driver for USB Mass Storage compliant devices
3  *
4  * Current development and maintenance by:
5  *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
6  *
7  * Developed with the assistance of:
8  *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
9  *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
10  *   (c) 2002 Alan Stern <stern@rowland.org>
11  *
12  * Initial work by:
13  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
14  *
15  * This driver is based on the 'USB Mass Storage Class' document. This
16  * describes in detail the protocol used to communicate with such
17  * devices.  Clearly, the designers had SCSI and ATAPI commands in
18  * mind when they created this document.  The commands are all very
19  * similar to commands in the SCSI-II and ATAPI specifications.
20  *
21  * It is important to note that in a number of cases this class
22  * exhibits class-specific exemptions from the USB specification.
23  * Notably the usage of NAK, STALL and ACK differs from the norm, in
24  * that they are used to communicate wait, failed and OK on commands.
25  *
26  * Also, for certain devices, the interrupt endpoint is used to convey
27  * status of a command.
28  *
29  * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
30  * information about this driver.
31  *
32  * This program is free software; you can redistribute it and/or modify it
33  * under the terms of the GNU General Public License as published by the
34  * Free Software Foundation; either version 2, or (at your option) any
35  * later version.
36  *
37  * This program is distributed in the hope that it will be useful, but
38  * WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40  * General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License along
43  * with this program; if not, write to the Free Software Foundation, Inc.,
44  * 675 Mass Ave, Cambridge, MA 02139, USA.
45  */
46
47 #include <linux/sched.h>
48 #include <linux/gfp.h>
49 #include <linux/errno.h>
50 #include <linux/export.h>
51
52 #include <linux/usb/quirks.h>
53
54 #include <scsi/scsi.h>
55 #include <scsi/scsi_eh.h>
56 #include <scsi/scsi_device.h>
57
58 #include "usb.h"
59 #include "transport.h"
60 #include "protocol.h"
61 #include "scsiglue.h"
62 #include "debug.h"
63
64 #include <linux/blkdev.h>
65 #include "../../scsi/sd.h"
66
67
68 /***********************************************************************
69  * Data transfer routines
70  ***********************************************************************/
71
72 /*
73  * This is subtle, so pay attention:
74  * ---------------------------------
75  * We're very concerned about races with a command abort.  Hanging this code
76  * is a sure fire way to hang the kernel.  (Note that this discussion applies
77  * only to transactions resulting from a scsi queued-command, since only
78  * these transactions are subject to a scsi abort.  Other transactions, such
79  * as those occurring during device-specific initialization, must be handled
80  * by a separate code path.)
81  *
82  * The abort function (usb_storage_command_abort() in scsiglue.c) first
83  * sets the machine state and the ABORTING bit in us->dflags to prevent
84  * new URBs from being submitted.  It then calls usb_stor_stop_transport()
85  * below, which atomically tests-and-clears the URB_ACTIVE bit in us->dflags
86  * to see if the current_urb needs to be stopped.  Likewise, the SG_ACTIVE
87  * bit is tested to see if the current_sg scatter-gather request needs to be
88  * stopped.  The timeout callback routine does much the same thing.
89  *
90  * When a disconnect occurs, the DISCONNECTING bit in us->dflags is set to
91  * prevent new URBs from being submitted, and usb_stor_stop_transport() is
92  * called to stop any ongoing requests.
93  *
94  * The submit function first verifies that the submitting is allowed
95  * (neither ABORTING nor DISCONNECTING bits are set) and that the submit
96  * completes without errors, and only then sets the URB_ACTIVE bit.  This
97  * prevents the stop_transport() function from trying to cancel the URB
98  * while the submit call is underway.  Next, the submit function must test
99  * the flags to see if an abort or disconnect occurred during the submission
100  * or before the URB_ACTIVE bit was set.  If so, it's essential to cancel
101  * the URB if it hasn't been cancelled already (i.e., if the URB_ACTIVE bit
102  * is still set).  Either way, the function must then wait for the URB to
103  * finish.  Note that the URB can still be in progress even after a call to
104  * usb_unlink_urb() returns.
105  *
106  * The idea is that (1) once the ABORTING or DISCONNECTING bit is set,
107  * either the stop_transport() function or the submitting function
108  * is guaranteed to call usb_unlink_urb() for an active URB,
109  * and (2) test_and_clear_bit() prevents usb_unlink_urb() from being
110  * called more than once or from being called during usb_submit_urb().
111  */
112
113 /*
114  * This is the completion handler which will wake us up when an URB
115  * completes.
116  */
117 static void usb_stor_blocking_completion(struct urb *urb)
118 {
119         struct completion *urb_done_ptr = urb->context;
120
121         complete(urb_done_ptr);
122 }
123
124 /*
125  * This is the common part of the URB message submission code
126  *
127  * All URBs from the usb-storage driver involved in handling a queued scsi
128  * command _must_ pass through this function (or something like it) for the
129  * abort mechanisms to work properly.
130  */
131 static int usb_stor_msg_common(struct us_data *us, int timeout)
132 {
133         struct completion urb_done;
134         long timeleft;
135         int status;
136
137         /* don't submit URBs during abort processing */
138         if (test_bit(US_FLIDX_ABORTING, &us->dflags))
139                 return -EIO;
140
141         /* set up data structures for the wakeup system */
142         init_completion(&urb_done);
143
144         /* fill the common fields in the URB */
145         us->current_urb->context = &urb_done;
146         us->current_urb->transfer_flags = 0;
147
148         /*
149          * we assume that if transfer_buffer isn't us->iobuf then it
150          * hasn't been mapped for DMA.  Yes, this is clunky, but it's
151          * easier than always having the caller tell us whether the
152          * transfer buffer has already been mapped.
153          */
154         if (us->current_urb->transfer_buffer == us->iobuf)
155                 us->current_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
156         us->current_urb->transfer_dma = us->iobuf_dma;
157
158         /* submit the URB */
159         status = usb_submit_urb(us->current_urb, GFP_NOIO);
160         if (status) {
161                 /* something went wrong */
162                 return status;
163         }
164
165         /*
166          * since the URB has been submitted successfully, it's now okay
167          * to cancel it
168          */
169         set_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
170
171         /* did an abort occur during the submission? */
172         if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
173
174                 /* cancel the URB, if it hasn't been cancelled already */
175                 if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
176                         usb_stor_dbg(us, "-- cancelling URB\n");
177                         usb_unlink_urb(us->current_urb);
178                 }
179         }
180  
181         /* wait for the completion of the URB */
182         timeleft = wait_for_completion_interruptible_timeout(
183                         &urb_done, timeout ? : MAX_SCHEDULE_TIMEOUT);
184  
185         clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
186
187         if (timeleft <= 0) {
188                 usb_stor_dbg(us, "%s -- cancelling URB\n",
189                              timeleft == 0 ? "Timeout" : "Signal");
190                 usb_kill_urb(us->current_urb);
191         }
192
193         /* return the URB status */
194         return us->current_urb->status;
195 }
196
197 /*
198  * Transfer one control message, with timeouts, and allowing early
199  * termination.  Return codes are usual -Exxx, *not* USB_STOR_XFER_xxx.
200  */
201 int usb_stor_control_msg(struct us_data *us, unsigned int pipe,
202                  u8 request, u8 requesttype, u16 value, u16 index, 
203                  void *data, u16 size, int timeout)
204 {
205         int status;
206
207         usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
208                      request, requesttype, value, index, size);
209
210         /* fill in the devrequest structure */
211         us->cr->bRequestType = requesttype;
212         us->cr->bRequest = request;
213         us->cr->wValue = cpu_to_le16(value);
214         us->cr->wIndex = cpu_to_le16(index);
215         us->cr->wLength = cpu_to_le16(size);
216
217         /* fill and submit the URB */
218         usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
219                          (unsigned char*) us->cr, data, size, 
220                          usb_stor_blocking_completion, NULL);
221         status = usb_stor_msg_common(us, timeout);
222
223         /* return the actual length of the data transferred if no error */
224         if (status == 0)
225                 status = us->current_urb->actual_length;
226         return status;
227 }
228 EXPORT_SYMBOL_GPL(usb_stor_control_msg);
229
230 /*
231  * This is a version of usb_clear_halt() that allows early termination and
232  * doesn't read the status from the device -- this is because some devices
233  * crash their internal firmware when the status is requested after a halt.
234  *
235  * A definitive list of these 'bad' devices is too difficult to maintain or
236  * make complete enough to be useful.  This problem was first observed on the
237  * Hagiwara FlashGate DUAL unit.  However, bus traces reveal that neither
238  * MacOS nor Windows checks the status after clearing a halt.
239  *
240  * Since many vendors in this space limit their testing to interoperability
241  * with these two OSes, specification violations like this one are common.
242  */
243 int usb_stor_clear_halt(struct us_data *us, unsigned int pipe)
244 {
245         int result;
246         int endp = usb_pipeendpoint(pipe);
247
248         if (usb_pipein (pipe))
249                 endp |= USB_DIR_IN;
250
251         result = usb_stor_control_msg(us, us->send_ctrl_pipe,
252                 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
253                 USB_ENDPOINT_HALT, endp,
254                 NULL, 0, 3*HZ);
255
256         if (result >= 0)
257                 usb_reset_endpoint(us->pusb_dev, endp);
258
259         usb_stor_dbg(us, "result = %d\n", result);
260         return result;
261 }
262 EXPORT_SYMBOL_GPL(usb_stor_clear_halt);
263
264
265 /*
266  * Interpret the results of a URB transfer
267  *
268  * This function prints appropriate debugging messages, clears halts on
269  * non-control endpoints, and translates the status to the corresponding
270  * USB_STOR_XFER_xxx return code.
271  */
272 static int interpret_urb_result(struct us_data *us, unsigned int pipe,
273                 unsigned int length, int result, unsigned int partial)
274 {
275         usb_stor_dbg(us, "Status code %d; transferred %u/%u\n",
276                      result, partial, length);
277         switch (result) {
278
279         /* no error code; did we send all the data? */
280         case 0:
281                 if (partial != length) {
282                         usb_stor_dbg(us, "-- short transfer\n");
283                         return USB_STOR_XFER_SHORT;
284                 }
285
286                 usb_stor_dbg(us, "-- transfer complete\n");
287                 return USB_STOR_XFER_GOOD;
288
289         /* stalled */
290         case -EPIPE:
291                 /*
292                  * for control endpoints, (used by CB[I]) a stall indicates
293                  * a failed command
294                  */
295                 if (usb_pipecontrol(pipe)) {
296                         usb_stor_dbg(us, "-- stall on control pipe\n");
297                         return USB_STOR_XFER_STALLED;
298                 }
299
300                 /* for other sorts of endpoint, clear the stall */
301                 usb_stor_dbg(us, "clearing endpoint halt for pipe 0x%x\n",
302                              pipe);
303                 if (usb_stor_clear_halt(us, pipe) < 0)
304                         return USB_STOR_XFER_ERROR;
305                 return USB_STOR_XFER_STALLED;
306
307         /* babble - the device tried to send more than we wanted to read */
308         case -EOVERFLOW:
309                 usb_stor_dbg(us, "-- babble\n");
310                 return USB_STOR_XFER_LONG;
311
312         /* the transfer was cancelled by abort, disconnect, or timeout */
313         case -ECONNRESET:
314                 usb_stor_dbg(us, "-- transfer cancelled\n");
315                 return USB_STOR_XFER_ERROR;
316
317         /* short scatter-gather read transfer */
318         case -EREMOTEIO:
319                 usb_stor_dbg(us, "-- short read transfer\n");
320                 return USB_STOR_XFER_SHORT;
321
322         /* abort or disconnect in progress */
323         case -EIO:
324                 usb_stor_dbg(us, "-- abort or disconnect in progress\n");
325                 return USB_STOR_XFER_ERROR;
326
327         /* the catch-all error case */
328         default:
329                 usb_stor_dbg(us, "-- unknown error\n");
330                 return USB_STOR_XFER_ERROR;
331         }
332 }
333
334 /*
335  * Transfer one control message, without timeouts, but allowing early
336  * termination.  Return codes are USB_STOR_XFER_xxx.
337  */
338 int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe,
339                 u8 request, u8 requesttype, u16 value, u16 index,
340                 void *data, u16 size)
341 {
342         int result;
343
344         usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
345                      request, requesttype, value, index, size);
346
347         /* fill in the devrequest structure */
348         us->cr->bRequestType = requesttype;
349         us->cr->bRequest = request;
350         us->cr->wValue = cpu_to_le16(value);
351         us->cr->wIndex = cpu_to_le16(index);
352         us->cr->wLength = cpu_to_le16(size);
353
354         /* fill and submit the URB */
355         usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
356                          (unsigned char*) us->cr, data, size, 
357                          usb_stor_blocking_completion, NULL);
358         result = usb_stor_msg_common(us, 0);
359
360         return interpret_urb_result(us, pipe, size, result,
361                         us->current_urb->actual_length);
362 }
363 EXPORT_SYMBOL_GPL(usb_stor_ctrl_transfer);
364
365 /*
366  * Receive one interrupt buffer, without timeouts, but allowing early
367  * termination.  Return codes are USB_STOR_XFER_xxx.
368  *
369  * This routine always uses us->recv_intr_pipe as the pipe and
370  * us->ep_bInterval as the interrupt interval.
371  */
372 static int usb_stor_intr_transfer(struct us_data *us, void *buf,
373                                   unsigned int length)
374 {
375         int result;
376         unsigned int pipe = us->recv_intr_pipe;
377         unsigned int maxp;
378
379         usb_stor_dbg(us, "xfer %u bytes\n", length);
380
381         /* calculate the max packet size */
382         maxp = usb_maxpacket(us->pusb_dev, pipe, usb_pipeout(pipe));
383         if (maxp > length)
384                 maxp = length;
385
386         /* fill and submit the URB */
387         usb_fill_int_urb(us->current_urb, us->pusb_dev, pipe, buf,
388                         maxp, usb_stor_blocking_completion, NULL,
389                         us->ep_bInterval);
390         result = usb_stor_msg_common(us, 0);
391
392         return interpret_urb_result(us, pipe, length, result,
393                         us->current_urb->actual_length);
394 }
395
396 /*
397  * Transfer one buffer via bulk pipe, without timeouts, but allowing early
398  * termination.  Return codes are USB_STOR_XFER_xxx.  If the bulk pipe
399  * stalls during the transfer, the halt is automatically cleared.
400  */
401 int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe,
402         void *buf, unsigned int length, unsigned int *act_len)
403 {
404         int result;
405
406         usb_stor_dbg(us, "xfer %u bytes\n", length);
407
408         /* fill and submit the URB */
409         usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length,
410                       usb_stor_blocking_completion, NULL);
411         result = usb_stor_msg_common(us, 0);
412
413         /* store the actual length of the data transferred */
414         if (act_len)
415                 *act_len = us->current_urb->actual_length;
416         return interpret_urb_result(us, pipe, length, result, 
417                         us->current_urb->actual_length);
418 }
419 EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf);
420
421 /*
422  * Transfer a scatter-gather list via bulk transfer
423  *
424  * This function does basically the same thing as usb_stor_bulk_transfer_buf()
425  * above, but it uses the usbcore scatter-gather library.
426  */
427 static int usb_stor_bulk_transfer_sglist(struct us_data *us, unsigned int pipe,
428                 struct scatterlist *sg, int num_sg, unsigned int length,
429                 unsigned int *act_len)
430 {
431         int result;
432
433         /* don't submit s-g requests during abort processing */
434         if (test_bit(US_FLIDX_ABORTING, &us->dflags))
435                 return USB_STOR_XFER_ERROR;
436
437         /* initialize the scatter-gather request block */
438         usb_stor_dbg(us, "xfer %u bytes, %d entries\n", length, num_sg);
439         result = usb_sg_init(&us->current_sg, us->pusb_dev, pipe, 0,
440                         sg, num_sg, length, GFP_NOIO);
441         if (result) {
442                 usb_stor_dbg(us, "usb_sg_init returned %d\n", result);
443                 return USB_STOR_XFER_ERROR;
444         }
445
446         /*
447          * since the block has been initialized successfully, it's now
448          * okay to cancel it
449          */
450         set_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
451
452         /* did an abort occur during the submission? */
453         if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
454
455                 /* cancel the request, if it hasn't been cancelled already */
456                 if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
457                         usb_stor_dbg(us, "-- cancelling sg request\n");
458                         usb_sg_cancel(&us->current_sg);
459                 }
460         }
461
462         /* wait for the completion of the transfer */
463         usb_sg_wait(&us->current_sg);
464         clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
465
466         result = us->current_sg.status;
467         if (act_len)
468                 *act_len = us->current_sg.bytes;
469         return interpret_urb_result(us, pipe, length, result,
470                         us->current_sg.bytes);
471 }
472
473 /*
474  * Common used function. Transfer a complete command
475  * via usb_stor_bulk_transfer_sglist() above. Set cmnd resid
476  */
477 int usb_stor_bulk_srb(struct us_data* us, unsigned int pipe,
478                       struct scsi_cmnd* srb)
479 {
480         unsigned int partial;
481         int result = usb_stor_bulk_transfer_sglist(us, pipe, scsi_sglist(srb),
482                                       scsi_sg_count(srb), scsi_bufflen(srb),
483                                       &partial);
484
485         scsi_set_resid(srb, scsi_bufflen(srb) - partial);
486         return result;
487 }
488 EXPORT_SYMBOL_GPL(usb_stor_bulk_srb);
489
490 /*
491  * Transfer an entire SCSI command's worth of data payload over the bulk
492  * pipe.
493  *
494  * Note that this uses usb_stor_bulk_transfer_buf() and
495  * usb_stor_bulk_transfer_sglist() to achieve its goals --
496  * this function simply determines whether we're going to use
497  * scatter-gather or not, and acts appropriately.
498  */
499 int usb_stor_bulk_transfer_sg(struct us_data* us, unsigned int pipe,
500                 void *buf, unsigned int length_left, int use_sg, int *residual)
501 {
502         int result;
503         unsigned int partial;
504
505         /* are we scatter-gathering? */
506         if (use_sg) {
507                 /* use the usb core scatter-gather primitives */
508                 result = usb_stor_bulk_transfer_sglist(us, pipe,
509                                 (struct scatterlist *) buf, use_sg,
510                                 length_left, &partial);
511                 length_left -= partial;
512         } else {
513                 /* no scatter-gather, just make the request */
514                 result = usb_stor_bulk_transfer_buf(us, pipe, buf, 
515                                 length_left, &partial);
516                 length_left -= partial;
517         }
518
519         /* store the residual and return the error code */
520         if (residual)
521                 *residual = length_left;
522         return result;
523 }
524 EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_sg);
525
526 /***********************************************************************
527  * Transport routines
528  ***********************************************************************/
529
530 /*
531  * There are so many devices that report the capacity incorrectly,
532  * this routine was written to counteract some of the resulting
533  * problems.
534  */
535 static void last_sector_hacks(struct us_data *us, struct scsi_cmnd *srb)
536 {
537         struct gendisk *disk;
538         struct scsi_disk *sdkp;
539         u32 sector;
540
541         /* To Report "Medium Error: Record Not Found */
542         static unsigned char record_not_found[18] = {
543                 [0]     = 0x70,                 /* current error */
544                 [2]     = MEDIUM_ERROR,         /* = 0x03 */
545                 [7]     = 0x0a,                 /* additional length */
546                 [12]    = 0x14                  /* Record Not Found */
547         };
548
549         /*
550          * If last-sector problems can't occur, whether because the
551          * capacity was already decremented or because the device is
552          * known to report the correct capacity, then we don't need
553          * to do anything.
554          */
555         if (!us->use_last_sector_hacks)
556                 return;
557
558         /* Was this command a READ(10) or a WRITE(10)? */
559         if (srb->cmnd[0] != READ_10 && srb->cmnd[0] != WRITE_10)
560                 goto done;
561
562         /* Did this command access the last sector? */
563         sector = (srb->cmnd[2] << 24) | (srb->cmnd[3] << 16) |
564                         (srb->cmnd[4] << 8) | (srb->cmnd[5]);
565         disk = srb->request->rq_disk;
566         if (!disk)
567                 goto done;
568         sdkp = scsi_disk(disk);
569         if (!sdkp)
570                 goto done;
571         if (sector + 1 != sdkp->capacity)
572                 goto done;
573
574         if (srb->result == SAM_STAT_GOOD && scsi_get_resid(srb) == 0) {
575
576                 /*
577                  * The command succeeded.  We know this device doesn't
578                  * have the last-sector bug, so stop checking it.
579                  */
580                 us->use_last_sector_hacks = 0;
581
582         } else {
583                 /*
584                  * The command failed.  Allow up to 3 retries in case this
585                  * is some normal sort of failure.  After that, assume the
586                  * capacity is wrong and we're trying to access the sector
587                  * beyond the end.  Replace the result code and sense data
588                  * with values that will cause the SCSI core to fail the
589                  * command immediately, instead of going into an infinite
590                  * (or even just a very long) retry loop.
591                  */
592                 if (++us->last_sector_retries < 3)
593                         return;
594                 srb->result = SAM_STAT_CHECK_CONDITION;
595                 memcpy(srb->sense_buffer, record_not_found,
596                                 sizeof(record_not_found));
597         }
598
599  done:
600         /*
601          * Don't reset the retry counter for TEST UNIT READY commands,
602          * because they get issued after device resets which might be
603          * caused by a failed last-sector access.
604          */
605         if (srb->cmnd[0] != TEST_UNIT_READY)
606                 us->last_sector_retries = 0;
607 }
608
609 /*
610  * Invoke the transport and basic error-handling/recovery methods
611  *
612  * This is used by the protocol layers to actually send the message to
613  * the device and receive the response.
614  */
615 void usb_stor_invoke_transport(struct scsi_cmnd *srb, struct us_data *us)
616 {
617         int need_auto_sense;
618         int result;
619
620         /* send the command to the transport layer */
621         scsi_set_resid(srb, 0);
622         result = us->transport(srb, us);
623
624         /*
625          * if the command gets aborted by the higher layers, we need to
626          * short-circuit all other processing
627          */
628         if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
629                 usb_stor_dbg(us, "-- command was aborted\n");
630                 srb->result = DID_ABORT << 16;
631                 goto Handle_Errors;
632         }
633
634         /* if there is a transport error, reset and don't auto-sense */
635         if (result == USB_STOR_TRANSPORT_ERROR) {
636                 usb_stor_dbg(us, "-- transport indicates error, resetting\n");
637                 srb->result = DID_ERROR << 16;
638                 goto Handle_Errors;
639         }
640
641         /* if the transport provided its own sense data, don't auto-sense */
642         if (result == USB_STOR_TRANSPORT_NO_SENSE) {
643                 srb->result = SAM_STAT_CHECK_CONDITION;
644                 last_sector_hacks(us, srb);
645                 return;
646         }
647
648         srb->result = SAM_STAT_GOOD;
649
650         /*
651          * Determine if we need to auto-sense
652          *
653          * I normally don't use a flag like this, but it's almost impossible
654          * to understand what's going on here if I don't.
655          */
656         need_auto_sense = 0;
657
658         /*
659          * If we're running the CB transport, which is incapable
660          * of determining status on its own, we will auto-sense
661          * unless the operation involved a data-in transfer.  Devices
662          * can signal most data-in errors by stalling the bulk-in pipe.
663          */
664         if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_DPCM_USB) &&
665                         srb->sc_data_direction != DMA_FROM_DEVICE) {
666                 usb_stor_dbg(us, "-- CB transport device requiring auto-sense\n");
667                 need_auto_sense = 1;
668         }
669
670         /* Some devices (Kindle) require another command after SYNC CACHE */
671         if ((us->fflags & US_FL_SENSE_AFTER_SYNC) &&
672                         srb->cmnd[0] == SYNCHRONIZE_CACHE) {
673                 usb_stor_dbg(us, "-- sense after SYNC CACHE\n");
674                 need_auto_sense = 1;
675         }
676
677         /*
678          * If we have a failure, we're going to do a REQUEST_SENSE 
679          * automatically.  Note that we differentiate between a command
680          * "failure" and an "error" in the transport mechanism.
681          */
682         if (result == USB_STOR_TRANSPORT_FAILED) {
683                 usb_stor_dbg(us, "-- transport indicates command failure\n");
684                 need_auto_sense = 1;
685         }
686
687         /*
688          * Determine if this device is SAT by seeing if the
689          * command executed successfully.  Otherwise we'll have
690          * to wait for at least one CHECK_CONDITION to determine
691          * SANE_SENSE support
692          */
693         if (unlikely((srb->cmnd[0] == ATA_16 || srb->cmnd[0] == ATA_12) &&
694             result == USB_STOR_TRANSPORT_GOOD &&
695             !(us->fflags & US_FL_SANE_SENSE) &&
696             !(us->fflags & US_FL_BAD_SENSE) &&
697             !(srb->cmnd[2] & 0x20))) {
698                 usb_stor_dbg(us, "-- SAT supported, increasing auto-sense\n");
699                 us->fflags |= US_FL_SANE_SENSE;
700         }
701
702         /*
703          * A short transfer on a command where we don't expect it
704          * is unusual, but it doesn't mean we need to auto-sense.
705          */
706         if ((scsi_get_resid(srb) > 0) &&
707             !((srb->cmnd[0] == REQUEST_SENSE) ||
708               (srb->cmnd[0] == INQUIRY) ||
709               (srb->cmnd[0] == MODE_SENSE) ||
710               (srb->cmnd[0] == LOG_SENSE) ||
711               (srb->cmnd[0] == MODE_SENSE_10))) {
712                 usb_stor_dbg(us, "-- unexpectedly short transfer\n");
713         }
714
715         /* Now, if we need to do the auto-sense, let's do it */
716         if (need_auto_sense) {
717                 int temp_result;
718                 struct scsi_eh_save ses;
719                 int sense_size = US_SENSE_SIZE;
720                 struct scsi_sense_hdr sshdr;
721                 const u8 *scdd;
722                 u8 fm_ili;
723
724                 /* device supports and needs bigger sense buffer */
725                 if (us->fflags & US_FL_SANE_SENSE)
726                         sense_size = ~0;
727 Retry_Sense:
728                 usb_stor_dbg(us, "Issuing auto-REQUEST_SENSE\n");
729
730                 scsi_eh_prep_cmnd(srb, &ses, NULL, 0, sense_size);
731
732                 /* FIXME: we must do the protocol translation here */
733                 if (us->subclass == USB_SC_RBC || us->subclass == USB_SC_SCSI ||
734                                 us->subclass == USB_SC_CYP_ATACB)
735                         srb->cmd_len = 6;
736                 else
737                         srb->cmd_len = 12;
738
739                 /* issue the auto-sense command */
740                 scsi_set_resid(srb, 0);
741                 temp_result = us->transport(us->srb, us);
742
743                 /* let's clean up right away */
744                 scsi_eh_restore_cmnd(srb, &ses);
745
746                 if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
747                         usb_stor_dbg(us, "-- auto-sense aborted\n");
748                         srb->result = DID_ABORT << 16;
749
750                         /* If SANE_SENSE caused this problem, disable it */
751                         if (sense_size != US_SENSE_SIZE) {
752                                 us->fflags &= ~US_FL_SANE_SENSE;
753                                 us->fflags |= US_FL_BAD_SENSE;
754                         }
755                         goto Handle_Errors;
756                 }
757
758                 /*
759                  * Some devices claim to support larger sense but fail when
760                  * trying to request it. When a transport failure happens
761                  * using US_FS_SANE_SENSE, we always retry with a standard
762                  * (small) sense request. This fixes some USB GSM modems
763                  */
764                 if (temp_result == USB_STOR_TRANSPORT_FAILED &&
765                                 sense_size != US_SENSE_SIZE) {
766                         usb_stor_dbg(us, "-- auto-sense failure, retry small sense\n");
767                         sense_size = US_SENSE_SIZE;
768                         us->fflags &= ~US_FL_SANE_SENSE;
769                         us->fflags |= US_FL_BAD_SENSE;
770                         goto Retry_Sense;
771                 }
772
773                 /* Other failures */
774                 if (temp_result != USB_STOR_TRANSPORT_GOOD) {
775                         usb_stor_dbg(us, "-- auto-sense failure\n");
776
777                         /*
778                          * we skip the reset if this happens to be a
779                          * multi-target device, since failure of an
780                          * auto-sense is perfectly valid
781                          */
782                         srb->result = DID_ERROR << 16;
783                         if (!(us->fflags & US_FL_SCM_MULT_TARG))
784                                 goto Handle_Errors;
785                         return;
786                 }
787
788                 /*
789                  * If the sense data returned is larger than 18-bytes then we
790                  * assume this device supports requesting more in the future.
791                  * The response code must be 70h through 73h inclusive.
792                  */
793                 if (srb->sense_buffer[7] > (US_SENSE_SIZE - 8) &&
794                     !(us->fflags & US_FL_SANE_SENSE) &&
795                     !(us->fflags & US_FL_BAD_SENSE) &&
796                     (srb->sense_buffer[0] & 0x7C) == 0x70) {
797                         usb_stor_dbg(us, "-- SANE_SENSE support enabled\n");
798                         us->fflags |= US_FL_SANE_SENSE;
799
800                         /*
801                          * Indicate to the user that we truncated their sense
802                          * because we didn't know it supported larger sense.
803                          */
804                         usb_stor_dbg(us, "-- Sense data truncated to %i from %i\n",
805                                      US_SENSE_SIZE,
806                                      srb->sense_buffer[7] + 8);
807                         srb->sense_buffer[7] = (US_SENSE_SIZE - 8);
808                 }
809
810                 scsi_normalize_sense(srb->sense_buffer, SCSI_SENSE_BUFFERSIZE,
811                                      &sshdr);
812
813                 usb_stor_dbg(us, "-- Result from auto-sense is %d\n",
814                              temp_result);
815                 usb_stor_dbg(us, "-- code: 0x%x, key: 0x%x, ASC: 0x%x, ASCQ: 0x%x\n",
816                              sshdr.response_code, sshdr.sense_key,
817                              sshdr.asc, sshdr.ascq);
818 #ifdef CONFIG_USB_STORAGE_DEBUG
819                 usb_stor_show_sense(us, sshdr.sense_key, sshdr.asc, sshdr.ascq);
820 #endif
821
822                 /* set the result so the higher layers expect this data */
823                 srb->result = SAM_STAT_CHECK_CONDITION;
824
825                 scdd = scsi_sense_desc_find(srb->sense_buffer,
826                                             SCSI_SENSE_BUFFERSIZE, 4);
827                 fm_ili = (scdd ? scdd[3] : srb->sense_buffer[2]) & 0xA0;
828
829                 /*
830                  * We often get empty sense data.  This could indicate that
831                  * everything worked or that there was an unspecified
832                  * problem.  We have to decide which.
833                  */
834                 if (sshdr.sense_key == 0 && sshdr.asc == 0 && sshdr.ascq == 0 &&
835                     fm_ili == 0) {
836                         /*
837                          * If things are really okay, then let's show that.
838                          * Zero out the sense buffer so the higher layers
839                          * won't realize we did an unsolicited auto-sense.
840                          */
841                         if (result == USB_STOR_TRANSPORT_GOOD) {
842                                 srb->result = SAM_STAT_GOOD;
843                                 srb->sense_buffer[0] = 0x0;
844                         }
845
846                         /*
847                          * ATA-passthru commands use sense data to report
848                          * the command completion status, and often devices
849                          * return Check Condition status when nothing is
850                          * wrong.
851                          */
852                         else if (srb->cmnd[0] == ATA_16 ||
853                                         srb->cmnd[0] == ATA_12) {
854                                 /* leave the data alone */
855                         }
856
857                         /*
858                          * If there was a problem, report an unspecified
859                          * hardware error to prevent the higher layers from
860                          * entering an infinite retry loop.
861                          */
862                         else {
863                                 srb->result = DID_ERROR << 16;
864                                 if ((sshdr.response_code & 0x72) == 0x72)
865                                         srb->sense_buffer[1] = HARDWARE_ERROR;
866                                 else
867                                         srb->sense_buffer[2] = HARDWARE_ERROR;
868                         }
869                 }
870         }
871
872         /*
873          * Some devices don't work or return incorrect data the first
874          * time they get a READ(10) command, or for the first READ(10)
875          * after a media change.  If the INITIAL_READ10 flag is set,
876          * keep track of whether READ(10) commands succeed.  If the
877          * previous one succeeded and this one failed, set the REDO_READ10
878          * flag to force a retry.
879          */
880         if (unlikely((us->fflags & US_FL_INITIAL_READ10) &&
881                         srb->cmnd[0] == READ_10)) {
882                 if (srb->result == SAM_STAT_GOOD) {
883                         set_bit(US_FLIDX_READ10_WORKED, &us->dflags);
884                 } else if (test_bit(US_FLIDX_READ10_WORKED, &us->dflags)) {
885                         clear_bit(US_FLIDX_READ10_WORKED, &us->dflags);
886                         set_bit(US_FLIDX_REDO_READ10, &us->dflags);
887                 }
888
889                 /*
890                  * Next, if the REDO_READ10 flag is set, return a result
891                  * code that will cause the SCSI core to retry the READ(10)
892                  * command immediately.
893                  */
894                 if (test_bit(US_FLIDX_REDO_READ10, &us->dflags)) {
895                         clear_bit(US_FLIDX_REDO_READ10, &us->dflags);
896                         srb->result = DID_IMM_RETRY << 16;
897                         srb->sense_buffer[0] = 0;
898                 }
899         }
900
901         /* Did we transfer less than the minimum amount required? */
902         if ((srb->result == SAM_STAT_GOOD || srb->sense_buffer[2] == 0) &&
903                         scsi_bufflen(srb) - scsi_get_resid(srb) < srb->underflow)
904                 srb->result = DID_ERROR << 16;
905
906         last_sector_hacks(us, srb);
907         return;
908
909         /*
910          * Error and abort processing: try to resynchronize with the device
911          * by issuing a port reset.  If that fails, try a class-specific
912          * device reset.
913          */
914   Handle_Errors:
915
916         /*
917          * Set the RESETTING bit, and clear the ABORTING bit so that
918          * the reset may proceed.
919          */
920         scsi_lock(us_to_host(us));
921         set_bit(US_FLIDX_RESETTING, &us->dflags);
922         clear_bit(US_FLIDX_ABORTING, &us->dflags);
923         scsi_unlock(us_to_host(us));
924
925         /*
926          * We must release the device lock because the pre_reset routine
927          * will want to acquire it.
928          */
929         mutex_unlock(&us->dev_mutex);
930         result = usb_stor_port_reset(us);
931         mutex_lock(&us->dev_mutex);
932
933         if (result < 0) {
934                 scsi_lock(us_to_host(us));
935                 usb_stor_report_device_reset(us);
936                 scsi_unlock(us_to_host(us));
937                 us->transport_reset(us);
938         }
939         clear_bit(US_FLIDX_RESETTING, &us->dflags);
940         last_sector_hacks(us, srb);
941 }
942
943 /* Stop the current URB transfer */
944 void usb_stor_stop_transport(struct us_data *us)
945 {
946         /*
947          * If the state machine is blocked waiting for an URB,
948          * let's wake it up.  The test_and_clear_bit() call
949          * guarantees that if a URB has just been submitted,
950          * it won't be cancelled more than once.
951          */
952         if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
953                 usb_stor_dbg(us, "-- cancelling URB\n");
954                 usb_unlink_urb(us->current_urb);
955         }
956
957         /* If we are waiting for a scatter-gather operation, cancel it. */
958         if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
959                 usb_stor_dbg(us, "-- cancelling sg request\n");
960                 usb_sg_cancel(&us->current_sg);
961         }
962 }
963
964 /*
965  * Control/Bulk and Control/Bulk/Interrupt transport
966  */
967
968 int usb_stor_CB_transport(struct scsi_cmnd *srb, struct us_data *us)
969 {
970         unsigned int transfer_length = scsi_bufflen(srb);
971         unsigned int pipe = 0;
972         int result;
973
974         /* COMMAND STAGE */
975         /* let's send the command via the control pipe */
976         /*
977          * Command is sometime (f.e. after scsi_eh_prep_cmnd) on the stack.
978          * Stack may be vmallocated.  So no DMA for us.  Make a copy.
979          */
980         memcpy(us->iobuf, srb->cmnd, srb->cmd_len);
981         result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
982                                       US_CBI_ADSC, 
983                                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
984                                       us->ifnum, us->iobuf, srb->cmd_len);
985
986         /* check the return code for the command */
987         usb_stor_dbg(us, "Call to usb_stor_ctrl_transfer() returned %d\n",
988                      result);
989
990         /* if we stalled the command, it means command failed */
991         if (result == USB_STOR_XFER_STALLED) {
992                 return USB_STOR_TRANSPORT_FAILED;
993         }
994
995         /* Uh oh... serious problem here */
996         if (result != USB_STOR_XFER_GOOD) {
997                 return USB_STOR_TRANSPORT_ERROR;
998         }
999
1000         /* DATA STAGE */
1001         /* transfer the data payload for this command, if one exists*/
1002         if (transfer_length) {
1003                 pipe = srb->sc_data_direction == DMA_FROM_DEVICE ? 
1004                                 us->recv_bulk_pipe : us->send_bulk_pipe;
1005                 result = usb_stor_bulk_srb(us, pipe, srb);
1006                 usb_stor_dbg(us, "CBI data stage result is 0x%x\n", result);
1007
1008                 /* if we stalled the data transfer it means command failed */
1009                 if (result == USB_STOR_XFER_STALLED)
1010                         return USB_STOR_TRANSPORT_FAILED;
1011                 if (result > USB_STOR_XFER_STALLED)
1012                         return USB_STOR_TRANSPORT_ERROR;
1013         }
1014
1015         /* STATUS STAGE */
1016
1017         /*
1018          * NOTE: CB does not have a status stage.  Silly, I know.  So
1019          * we have to catch this at a higher level.
1020          */
1021         if (us->protocol != USB_PR_CBI)
1022                 return USB_STOR_TRANSPORT_GOOD;
1023
1024         result = usb_stor_intr_transfer(us, us->iobuf, 2);
1025         usb_stor_dbg(us, "Got interrupt data (0x%x, 0x%x)\n",
1026                      us->iobuf[0], us->iobuf[1]);
1027         if (result != USB_STOR_XFER_GOOD)
1028                 return USB_STOR_TRANSPORT_ERROR;
1029
1030         /*
1031          * UFI gives us ASC and ASCQ, like a request sense
1032          *
1033          * REQUEST_SENSE and INQUIRY don't affect the sense data on UFI
1034          * devices, so we ignore the information for those commands.  Note
1035          * that this means we could be ignoring a real error on these
1036          * commands, but that can't be helped.
1037          */
1038         if (us->subclass == USB_SC_UFI) {
1039                 if (srb->cmnd[0] == REQUEST_SENSE ||
1040                     srb->cmnd[0] == INQUIRY)
1041                         return USB_STOR_TRANSPORT_GOOD;
1042                 if (us->iobuf[0])
1043                         goto Failed;
1044                 return USB_STOR_TRANSPORT_GOOD;
1045         }
1046
1047         /*
1048          * If not UFI, we interpret the data as a result code 
1049          * The first byte should always be a 0x0.
1050          *
1051          * Some bogus devices don't follow that rule.  They stuff the ASC
1052          * into the first byte -- so if it's non-zero, call it a failure.
1053          */
1054         if (us->iobuf[0]) {
1055                 usb_stor_dbg(us, "CBI IRQ data showed reserved bType 0x%x\n",
1056                              us->iobuf[0]);
1057                 goto Failed;
1058
1059         }
1060
1061         /* The second byte & 0x0F should be 0x0 for good, otherwise error */
1062         switch (us->iobuf[1] & 0x0F) {
1063                 case 0x00: 
1064                         return USB_STOR_TRANSPORT_GOOD;
1065                 case 0x01: 
1066                         goto Failed;
1067         }
1068         return USB_STOR_TRANSPORT_ERROR;
1069
1070         /*
1071          * the CBI spec requires that the bulk pipe must be cleared
1072          * following any data-in/out command failure (section 2.4.3.1.3)
1073          */
1074   Failed:
1075         if (pipe)
1076                 usb_stor_clear_halt(us, pipe);
1077         return USB_STOR_TRANSPORT_FAILED;
1078 }
1079 EXPORT_SYMBOL_GPL(usb_stor_CB_transport);
1080
1081 /*
1082  * Bulk only transport
1083  */
1084
1085 /* Determine what the maximum LUN supported is */
1086 int usb_stor_Bulk_max_lun(struct us_data *us)
1087 {
1088         int result;
1089
1090         /* issue the command */
1091         us->iobuf[0] = 0;
1092         result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
1093                                  US_BULK_GET_MAX_LUN, 
1094                                  USB_DIR_IN | USB_TYPE_CLASS | 
1095                                  USB_RECIP_INTERFACE,
1096                                  0, us->ifnum, us->iobuf, 1, 10*HZ);
1097
1098         usb_stor_dbg(us, "GetMaxLUN command result is %d, data is %d\n",
1099                      result, us->iobuf[0]);
1100
1101         /*
1102          * If we have a successful request, return the result if valid. The
1103          * CBW LUN field is 4 bits wide, so the value reported by the device
1104          * should fit into that.
1105          */
1106         if (result > 0) {
1107                 if (us->iobuf[0] < 16) {
1108                         return us->iobuf[0];
1109                 } else {
1110                         dev_info(&us->pusb_intf->dev,
1111                                  "Max LUN %d is not valid, using 0 instead",
1112                                  us->iobuf[0]);
1113                 }
1114         }
1115
1116         /*
1117          * Some devices don't like GetMaxLUN.  They may STALL the control
1118          * pipe, they may return a zero-length result, they may do nothing at
1119          * all and timeout, or they may fail in even more bizarrely creative
1120          * ways.  In these cases the best approach is to use the default
1121          * value: only one LUN.
1122          */
1123         return 0;
1124 }
1125
1126 int usb_stor_Bulk_transport(struct scsi_cmnd *srb, struct us_data *us)
1127 {
1128         struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
1129         struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
1130         unsigned int transfer_length = scsi_bufflen(srb);
1131         unsigned int residue;
1132         int result;
1133         int fake_sense = 0;
1134         unsigned int cswlen;
1135         unsigned int cbwlen = US_BULK_CB_WRAP_LEN;
1136
1137         /* Take care of BULK32 devices; set extra byte to 0 */
1138         if (unlikely(us->fflags & US_FL_BULK32)) {
1139                 cbwlen = 32;
1140                 us->iobuf[31] = 0;
1141         }
1142
1143         /* set up the command wrapper */
1144         bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1145         bcb->DataTransferLength = cpu_to_le32(transfer_length);
1146         bcb->Flags = srb->sc_data_direction == DMA_FROM_DEVICE ?
1147                 US_BULK_FLAG_IN : 0;
1148         bcb->Tag = ++us->tag;
1149         bcb->Lun = srb->device->lun;
1150         if (us->fflags & US_FL_SCM_MULT_TARG)
1151                 bcb->Lun |= srb->device->id << 4;
1152         bcb->Length = srb->cmd_len;
1153
1154         /* copy the command payload */
1155         memset(bcb->CDB, 0, sizeof(bcb->CDB));
1156         memcpy(bcb->CDB, srb->cmnd, bcb->Length);
1157
1158         /* send it to out endpoint */
1159         usb_stor_dbg(us, "Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
1160                      le32_to_cpu(bcb->Signature), bcb->Tag,
1161                      le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
1162                      (bcb->Lun >> 4), (bcb->Lun & 0x0F),
1163                      bcb->Length);
1164         result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
1165                                 bcb, cbwlen, NULL);
1166         usb_stor_dbg(us, "Bulk command transfer result=%d\n", result);
1167         if (result != USB_STOR_XFER_GOOD)
1168                 return USB_STOR_TRANSPORT_ERROR;
1169
1170         /* DATA STAGE */
1171         /* send/receive data payload, if there is any */
1172
1173         /*
1174          * Some USB-IDE converter chips need a 100us delay between the
1175          * command phase and the data phase.  Some devices need a little
1176          * more than that, probably because of clock rate inaccuracies.
1177          */
1178         if (unlikely(us->fflags & US_FL_GO_SLOW))
1179                 usleep_range(125, 150);
1180
1181         if (transfer_length) {
1182                 unsigned int pipe = srb->sc_data_direction == DMA_FROM_DEVICE ? 
1183                                 us->recv_bulk_pipe : us->send_bulk_pipe;
1184                 result = usb_stor_bulk_srb(us, pipe, srb);
1185                 usb_stor_dbg(us, "Bulk data transfer result 0x%x\n", result);
1186                 if (result == USB_STOR_XFER_ERROR)
1187                         return USB_STOR_TRANSPORT_ERROR;
1188
1189                 /*
1190                  * If the device tried to send back more data than the
1191                  * amount requested, the spec requires us to transfer
1192                  * the CSW anyway.  Since there's no point retrying the
1193                  * the command, we'll return fake sense data indicating
1194                  * Illegal Request, Invalid Field in CDB.
1195                  */
1196                 if (result == USB_STOR_XFER_LONG)
1197                         fake_sense = 1;
1198
1199                 /*
1200                  * Sometimes a device will mistakenly skip the data phase
1201                  * and go directly to the status phase without sending a
1202                  * zero-length packet.  If we get a 13-byte response here,
1203                  * check whether it really is a CSW.
1204                  */
1205                 if (result == USB_STOR_XFER_SHORT &&
1206                                 srb->sc_data_direction == DMA_FROM_DEVICE &&
1207                                 transfer_length - scsi_get_resid(srb) ==
1208                                         US_BULK_CS_WRAP_LEN) {
1209                         struct scatterlist *sg = NULL;
1210                         unsigned int offset = 0;
1211
1212                         if (usb_stor_access_xfer_buf((unsigned char *) bcs,
1213                                         US_BULK_CS_WRAP_LEN, srb, &sg,
1214                                         &offset, FROM_XFER_BUF) ==
1215                                                 US_BULK_CS_WRAP_LEN &&
1216                                         bcs->Signature ==
1217                                                 cpu_to_le32(US_BULK_CS_SIGN)) {
1218                                 usb_stor_dbg(us, "Device skipped data phase\n");
1219                                 scsi_set_resid(srb, transfer_length);
1220                                 goto skipped_data_phase;
1221                         }
1222                 }
1223         }
1224
1225         /*
1226          * See flow chart on pg 15 of the Bulk Only Transport spec for
1227          * an explanation of how this code works.
1228          */
1229
1230         /* get CSW for device status */
1231         usb_stor_dbg(us, "Attempting to get CSW...\n");
1232         result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1233                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1234
1235         /*
1236          * Some broken devices add unnecessary zero-length packets to the
1237          * end of their data transfers.  Such packets show up as 0-length
1238          * CSWs.  If we encounter such a thing, try to read the CSW again.
1239          */
1240         if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
1241                 usb_stor_dbg(us, "Received 0-length CSW; retrying...\n");
1242                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1243                                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1244         }
1245
1246         /* did the attempt to read the CSW fail? */
1247         if (result == USB_STOR_XFER_STALLED) {
1248
1249                 /* get the status again */
1250                 usb_stor_dbg(us, "Attempting to get CSW (2nd try)...\n");
1251                 result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1252                                 bcs, US_BULK_CS_WRAP_LEN, NULL);
1253         }
1254
1255         /* if we still have a failure at this point, we're in trouble */
1256         usb_stor_dbg(us, "Bulk status result = %d\n", result);
1257         if (result != USB_STOR_XFER_GOOD)
1258                 return USB_STOR_TRANSPORT_ERROR;
1259
1260  skipped_data_phase:
1261         /* check bulk status */
1262         residue = le32_to_cpu(bcs->Residue);
1263         usb_stor_dbg(us, "Bulk Status S 0x%x T 0x%x R %u Stat 0x%x\n",
1264                      le32_to_cpu(bcs->Signature), bcs->Tag,
1265                      residue, bcs->Status);
1266         if (!(bcs->Tag == us->tag || (us->fflags & US_FL_BULK_IGNORE_TAG)) ||
1267                 bcs->Status > US_BULK_STAT_PHASE) {
1268                 usb_stor_dbg(us, "Bulk logical error\n");
1269                 return USB_STOR_TRANSPORT_ERROR;
1270         }
1271
1272         /*
1273          * Some broken devices report odd signatures, so we do not check them
1274          * for validity against the spec. We store the first one we see,
1275          * and check subsequent transfers for validity against this signature.
1276          */
1277         if (!us->bcs_signature) {
1278                 us->bcs_signature = bcs->Signature;
1279                 if (us->bcs_signature != cpu_to_le32(US_BULK_CS_SIGN))
1280                         usb_stor_dbg(us, "Learnt BCS signature 0x%08X\n",
1281                                      le32_to_cpu(us->bcs_signature));
1282         } else if (bcs->Signature != us->bcs_signature) {
1283                 usb_stor_dbg(us, "Signature mismatch: got %08X, expecting %08X\n",
1284                              le32_to_cpu(bcs->Signature),
1285                              le32_to_cpu(us->bcs_signature));
1286                 return USB_STOR_TRANSPORT_ERROR;
1287         }
1288
1289         /*
1290          * try to compute the actual residue, based on how much data
1291          * was really transferred and what the device tells us
1292          */
1293         if (residue && !(us->fflags & US_FL_IGNORE_RESIDUE)) {
1294
1295                 /*
1296                  * Heuristically detect devices that generate bogus residues
1297                  * by seeing what happens with INQUIRY and READ CAPACITY
1298                  * commands.
1299                  */
1300                 if (bcs->Status == US_BULK_STAT_OK &&
1301                                 scsi_get_resid(srb) == 0 &&
1302                                         ((srb->cmnd[0] == INQUIRY &&
1303                                                 transfer_length == 36) ||
1304                                         (srb->cmnd[0] == READ_CAPACITY &&
1305                                                 transfer_length == 8))) {
1306                         us->fflags |= US_FL_IGNORE_RESIDUE;
1307
1308                 } else {
1309                         residue = min(residue, transfer_length);
1310                         scsi_set_resid(srb, max(scsi_get_resid(srb),
1311                                                                (int) residue));
1312                 }
1313         }
1314
1315         /* based on the status code, we report good or bad */
1316         switch (bcs->Status) {
1317                 case US_BULK_STAT_OK:
1318                         /* device babbled -- return fake sense data */
1319                         if (fake_sense) {
1320                                 memcpy(srb->sense_buffer, 
1321                                        usb_stor_sense_invalidCDB, 
1322                                        sizeof(usb_stor_sense_invalidCDB));
1323                                 return USB_STOR_TRANSPORT_NO_SENSE;
1324                         }
1325
1326                         /* command good -- note that data could be short */
1327                         return USB_STOR_TRANSPORT_GOOD;
1328
1329                 case US_BULK_STAT_FAIL:
1330                         /* command failed */
1331                         return USB_STOR_TRANSPORT_FAILED;
1332
1333                 case US_BULK_STAT_PHASE:
1334                         /*
1335                          * phase error -- note that a transport reset will be
1336                          * invoked by the invoke_transport() function
1337                          */
1338                         return USB_STOR_TRANSPORT_ERROR;
1339         }
1340
1341         /* we should never get here, but if we do, we're in trouble */
1342         return USB_STOR_TRANSPORT_ERROR;
1343 }
1344 EXPORT_SYMBOL_GPL(usb_stor_Bulk_transport);
1345
1346 /***********************************************************************
1347  * Reset routines
1348  ***********************************************************************/
1349
1350 /*
1351  * This is the common part of the device reset code.
1352  *
1353  * It's handy that every transport mechanism uses the control endpoint for
1354  * resets.
1355  *
1356  * Basically, we send a reset with a 5-second timeout, so we don't get
1357  * jammed attempting to do the reset.
1358  */
1359 static int usb_stor_reset_common(struct us_data *us,
1360                 u8 request, u8 requesttype,
1361                 u16 value, u16 index, void *data, u16 size)
1362 {
1363         int result;
1364         int result2;
1365
1366         if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1367                 usb_stor_dbg(us, "No reset during disconnect\n");
1368                 return -EIO;
1369         }
1370
1371         result = usb_stor_control_msg(us, us->send_ctrl_pipe,
1372                         request, requesttype, value, index, data, size,
1373                         5*HZ);
1374         if (result < 0) {
1375                 usb_stor_dbg(us, "Soft reset failed: %d\n", result);
1376                 return result;
1377         }
1378
1379         /*
1380          * Give the device some time to recover from the reset,
1381          * but don't delay disconnect processing.
1382          */
1383         wait_event_interruptible_timeout(us->delay_wait,
1384                         test_bit(US_FLIDX_DISCONNECTING, &us->dflags),
1385                         HZ*6);
1386         if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1387                 usb_stor_dbg(us, "Reset interrupted by disconnect\n");
1388                 return -EIO;
1389         }
1390
1391         usb_stor_dbg(us, "Soft reset: clearing bulk-in endpoint halt\n");
1392         result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
1393
1394         usb_stor_dbg(us, "Soft reset: clearing bulk-out endpoint halt\n");
1395         result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
1396
1397         /* return a result code based on the result of the clear-halts */
1398         if (result >= 0)
1399                 result = result2;
1400         if (result < 0)
1401                 usb_stor_dbg(us, "Soft reset failed\n");
1402         else
1403                 usb_stor_dbg(us, "Soft reset done\n");
1404         return result;
1405 }
1406
1407 /* This issues a CB[I] Reset to the device in question */
1408 #define CB_RESET_CMD_SIZE       12
1409
1410 int usb_stor_CB_reset(struct us_data *us)
1411 {
1412         memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
1413         us->iobuf[0] = SEND_DIAGNOSTIC;
1414         us->iobuf[1] = 4;
1415         return usb_stor_reset_common(us, US_CBI_ADSC, 
1416                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1417                                  0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
1418 }
1419 EXPORT_SYMBOL_GPL(usb_stor_CB_reset);
1420
1421 /*
1422  * This issues a Bulk-only Reset to the device in question, including
1423  * clearing the subsequent endpoint halts that may occur.
1424  */
1425 int usb_stor_Bulk_reset(struct us_data *us)
1426 {
1427         return usb_stor_reset_common(us, US_BULK_RESET_REQUEST, 
1428                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1429                                  0, us->ifnum, NULL, 0);
1430 }
1431 EXPORT_SYMBOL_GPL(usb_stor_Bulk_reset);
1432
1433 /*
1434  * Issue a USB port reset to the device.  The caller must not hold
1435  * us->dev_mutex.
1436  */
1437 int usb_stor_port_reset(struct us_data *us)
1438 {
1439         int result;
1440
1441         /*for these devices we must use the class specific method */
1442         if (us->pusb_dev->quirks & USB_QUIRK_RESET)
1443                 return -EPERM;
1444
1445         result = usb_lock_device_for_reset(us->pusb_dev, us->pusb_intf);
1446         if (result < 0)
1447                 usb_stor_dbg(us, "unable to lock device for reset: %d\n",
1448                              result);
1449         else {
1450                 /* Were we disconnected while waiting for the lock? */
1451                 if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1452                         result = -EIO;
1453                         usb_stor_dbg(us, "No reset during disconnect\n");
1454                 } else {
1455                         result = usb_reset_device(us->pusb_dev);
1456                         usb_stor_dbg(us, "usb_reset_device returns %d\n",
1457                                      result);
1458                 }
1459                 usb_unlock_device(us->pusb_dev);
1460         }
1461         return result;
1462 }