Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 /*
0003  * Driver for USB Mass Storage compliant devices
0004  *
0005  * Current development and maintenance by:
0006  *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
0007  *
0008  * Developed with the assistance of:
0009  *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
0010  *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
0011  *   (c) 2002 Alan Stern <stern@rowland.org>
0012  *
0013  * Initial work by:
0014  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
0015  *
0016  * This driver is based on the 'USB Mass Storage Class' document. This
0017  * describes in detail the protocol used to communicate with such
0018  * devices.  Clearly, the designers had SCSI and ATAPI commands in
0019  * mind when they created this document.  The commands are all very
0020  * similar to commands in the SCSI-II and ATAPI specifications.
0021  *
0022  * It is important to note that in a number of cases this class
0023  * exhibits class-specific exemptions from the USB specification.
0024  * Notably the usage of NAK, STALL and ACK differs from the norm, in
0025  * that they are used to communicate wait, failed and OK on commands.
0026  *
0027  * Also, for certain devices, the interrupt endpoint is used to convey
0028  * status of a command.
0029  */
0030 
0031 #include <linux/sched.h>
0032 #include <linux/gfp.h>
0033 #include <linux/errno.h>
0034 #include <linux/export.h>
0035 
0036 #include <linux/usb/quirks.h>
0037 
0038 #include <scsi/scsi.h>
0039 #include <scsi/scsi_eh.h>
0040 #include <scsi/scsi_device.h>
0041 
0042 #include "usb.h"
0043 #include "transport.h"
0044 #include "protocol.h"
0045 #include "scsiglue.h"
0046 #include "debug.h"
0047 
0048 #include <linux/blkdev.h>
0049 #include "../../scsi/sd.h"
0050 
0051 
0052 /***********************************************************************
0053  * Data transfer routines
0054  ***********************************************************************/
0055 
0056 /*
0057  * This is subtle, so pay attention:
0058  * ---------------------------------
0059  * We're very concerned about races with a command abort.  Hanging this code
0060  * is a sure fire way to hang the kernel.  (Note that this discussion applies
0061  * only to transactions resulting from a scsi queued-command, since only
0062  * these transactions are subject to a scsi abort.  Other transactions, such
0063  * as those occurring during device-specific initialization, must be handled
0064  * by a separate code path.)
0065  *
0066  * The abort function (usb_storage_command_abort() in scsiglue.c) first
0067  * sets the machine state and the ABORTING bit in us->dflags to prevent
0068  * new URBs from being submitted.  It then calls usb_stor_stop_transport()
0069  * below, which atomically tests-and-clears the URB_ACTIVE bit in us->dflags
0070  * to see if the current_urb needs to be stopped.  Likewise, the SG_ACTIVE
0071  * bit is tested to see if the current_sg scatter-gather request needs to be
0072  * stopped.  The timeout callback routine does much the same thing.
0073  *
0074  * When a disconnect occurs, the DISCONNECTING bit in us->dflags is set to
0075  * prevent new URBs from being submitted, and usb_stor_stop_transport() is
0076  * called to stop any ongoing requests.
0077  *
0078  * The submit function first verifies that the submitting is allowed
0079  * (neither ABORTING nor DISCONNECTING bits are set) and that the submit
0080  * completes without errors, and only then sets the URB_ACTIVE bit.  This
0081  * prevents the stop_transport() function from trying to cancel the URB
0082  * while the submit call is underway.  Next, the submit function must test
0083  * the flags to see if an abort or disconnect occurred during the submission
0084  * or before the URB_ACTIVE bit was set.  If so, it's essential to cancel
0085  * the URB if it hasn't been cancelled already (i.e., if the URB_ACTIVE bit
0086  * is still set).  Either way, the function must then wait for the URB to
0087  * finish.  Note that the URB can still be in progress even after a call to
0088  * usb_unlink_urb() returns.
0089  *
0090  * The idea is that (1) once the ABORTING or DISCONNECTING bit is set,
0091  * either the stop_transport() function or the submitting function
0092  * is guaranteed to call usb_unlink_urb() for an active URB,
0093  * and (2) test_and_clear_bit() prevents usb_unlink_urb() from being
0094  * called more than once or from being called during usb_submit_urb().
0095  */
0096 
0097 /*
0098  * This is the completion handler which will wake us up when an URB
0099  * completes.
0100  */
0101 static void usb_stor_blocking_completion(struct urb *urb)
0102 {
0103     struct completion *urb_done_ptr = urb->context;
0104 
0105     complete(urb_done_ptr);
0106 }
0107 
0108 /*
0109  * This is the common part of the URB message submission code
0110  *
0111  * All URBs from the usb-storage driver involved in handling a queued scsi
0112  * command _must_ pass through this function (or something like it) for the
0113  * abort mechanisms to work properly.
0114  */
0115 static int usb_stor_msg_common(struct us_data *us, int timeout)
0116 {
0117     struct completion urb_done;
0118     long timeleft;
0119     int status;
0120 
0121     /* don't submit URBs during abort processing */
0122     if (test_bit(US_FLIDX_ABORTING, &us->dflags))
0123         return -EIO;
0124 
0125     /* set up data structures for the wakeup system */
0126     init_completion(&urb_done);
0127 
0128     /* fill the common fields in the URB */
0129     us->current_urb->context = &urb_done;
0130     us->current_urb->transfer_flags = 0;
0131 
0132     /*
0133      * we assume that if transfer_buffer isn't us->iobuf then it
0134      * hasn't been mapped for DMA.  Yes, this is clunky, but it's
0135      * easier than always having the caller tell us whether the
0136      * transfer buffer has already been mapped.
0137      */
0138     if (us->current_urb->transfer_buffer == us->iobuf)
0139         us->current_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
0140     us->current_urb->transfer_dma = us->iobuf_dma;
0141 
0142     /* submit the URB */
0143     status = usb_submit_urb(us->current_urb, GFP_NOIO);
0144     if (status) {
0145         /* something went wrong */
0146         return status;
0147     }
0148 
0149     /*
0150      * since the URB has been submitted successfully, it's now okay
0151      * to cancel it
0152      */
0153     set_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
0154 
0155     /* did an abort occur during the submission? */
0156     if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
0157 
0158         /* cancel the URB, if it hasn't been cancelled already */
0159         if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
0160             usb_stor_dbg(us, "-- cancelling URB\n");
0161             usb_unlink_urb(us->current_urb);
0162         }
0163     }
0164  
0165     /* wait for the completion of the URB */
0166     timeleft = wait_for_completion_interruptible_timeout(
0167             &urb_done, timeout ? : MAX_SCHEDULE_TIMEOUT);
0168  
0169     clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
0170 
0171     if (timeleft <= 0) {
0172         usb_stor_dbg(us, "%s -- cancelling URB\n",
0173                  timeleft == 0 ? "Timeout" : "Signal");
0174         usb_kill_urb(us->current_urb);
0175     }
0176 
0177     /* return the URB status */
0178     return us->current_urb->status;
0179 }
0180 
0181 /*
0182  * Transfer one control message, with timeouts, and allowing early
0183  * termination.  Return codes are usual -Exxx, *not* USB_STOR_XFER_xxx.
0184  */
0185 int usb_stor_control_msg(struct us_data *us, unsigned int pipe,
0186          u8 request, u8 requesttype, u16 value, u16 index, 
0187          void *data, u16 size, int timeout)
0188 {
0189     int status;
0190 
0191     usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
0192              request, requesttype, value, index, size);
0193 
0194     /* fill in the devrequest structure */
0195     us->cr->bRequestType = requesttype;
0196     us->cr->bRequest = request;
0197     us->cr->wValue = cpu_to_le16(value);
0198     us->cr->wIndex = cpu_to_le16(index);
0199     us->cr->wLength = cpu_to_le16(size);
0200 
0201     /* fill and submit the URB */
0202     usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
0203              (unsigned char*) us->cr, data, size, 
0204              usb_stor_blocking_completion, NULL);
0205     status = usb_stor_msg_common(us, timeout);
0206 
0207     /* return the actual length of the data transferred if no error */
0208     if (status == 0)
0209         status = us->current_urb->actual_length;
0210     return status;
0211 }
0212 EXPORT_SYMBOL_GPL(usb_stor_control_msg);
0213 
0214 /*
0215  * This is a version of usb_clear_halt() that allows early termination and
0216  * doesn't read the status from the device -- this is because some devices
0217  * crash their internal firmware when the status is requested after a halt.
0218  *
0219  * A definitive list of these 'bad' devices is too difficult to maintain or
0220  * make complete enough to be useful.  This problem was first observed on the
0221  * Hagiwara FlashGate DUAL unit.  However, bus traces reveal that neither
0222  * MacOS nor Windows checks the status after clearing a halt.
0223  *
0224  * Since many vendors in this space limit their testing to interoperability
0225  * with these two OSes, specification violations like this one are common.
0226  */
0227 int usb_stor_clear_halt(struct us_data *us, unsigned int pipe)
0228 {
0229     int result;
0230     int endp = usb_pipeendpoint(pipe);
0231 
0232     if (usb_pipein (pipe))
0233         endp |= USB_DIR_IN;
0234 
0235     result = usb_stor_control_msg(us, us->send_ctrl_pipe,
0236         USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
0237         USB_ENDPOINT_HALT, endp,
0238         NULL, 0, 3*HZ);
0239 
0240     if (result >= 0)
0241         usb_reset_endpoint(us->pusb_dev, endp);
0242 
0243     usb_stor_dbg(us, "result = %d\n", result);
0244     return result;
0245 }
0246 EXPORT_SYMBOL_GPL(usb_stor_clear_halt);
0247 
0248 
0249 /*
0250  * Interpret the results of a URB transfer
0251  *
0252  * This function prints appropriate debugging messages, clears halts on
0253  * non-control endpoints, and translates the status to the corresponding
0254  * USB_STOR_XFER_xxx return code.
0255  */
0256 static int interpret_urb_result(struct us_data *us, unsigned int pipe,
0257         unsigned int length, int result, unsigned int partial)
0258 {
0259     usb_stor_dbg(us, "Status code %d; transferred %u/%u\n",
0260              result, partial, length);
0261     switch (result) {
0262 
0263     /* no error code; did we send all the data? */
0264     case 0:
0265         if (partial != length) {
0266             usb_stor_dbg(us, "-- short transfer\n");
0267             return USB_STOR_XFER_SHORT;
0268         }
0269 
0270         usb_stor_dbg(us, "-- transfer complete\n");
0271         return USB_STOR_XFER_GOOD;
0272 
0273     /* stalled */
0274     case -EPIPE:
0275         /*
0276          * for control endpoints, (used by CB[I]) a stall indicates
0277          * a failed command
0278          */
0279         if (usb_pipecontrol(pipe)) {
0280             usb_stor_dbg(us, "-- stall on control pipe\n");
0281             return USB_STOR_XFER_STALLED;
0282         }
0283 
0284         /* for other sorts of endpoint, clear the stall */
0285         usb_stor_dbg(us, "clearing endpoint halt for pipe 0x%x\n",
0286                  pipe);
0287         if (usb_stor_clear_halt(us, pipe) < 0)
0288             return USB_STOR_XFER_ERROR;
0289         return USB_STOR_XFER_STALLED;
0290 
0291     /* babble - the device tried to send more than we wanted to read */
0292     case -EOVERFLOW:
0293         usb_stor_dbg(us, "-- babble\n");
0294         return USB_STOR_XFER_LONG;
0295 
0296     /* the transfer was cancelled by abort, disconnect, or timeout */
0297     case -ECONNRESET:
0298         usb_stor_dbg(us, "-- transfer cancelled\n");
0299         return USB_STOR_XFER_ERROR;
0300 
0301     /* short scatter-gather read transfer */
0302     case -EREMOTEIO:
0303         usb_stor_dbg(us, "-- short read transfer\n");
0304         return USB_STOR_XFER_SHORT;
0305 
0306     /* abort or disconnect in progress */
0307     case -EIO:
0308         usb_stor_dbg(us, "-- abort or disconnect in progress\n");
0309         return USB_STOR_XFER_ERROR;
0310 
0311     /* the catch-all error case */
0312     default:
0313         usb_stor_dbg(us, "-- unknown error\n");
0314         return USB_STOR_XFER_ERROR;
0315     }
0316 }
0317 
0318 /*
0319  * Transfer one control message, without timeouts, but allowing early
0320  * termination.  Return codes are USB_STOR_XFER_xxx.
0321  */
0322 int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe,
0323         u8 request, u8 requesttype, u16 value, u16 index,
0324         void *data, u16 size)
0325 {
0326     int result;
0327 
0328     usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
0329              request, requesttype, value, index, size);
0330 
0331     /* fill in the devrequest structure */
0332     us->cr->bRequestType = requesttype;
0333     us->cr->bRequest = request;
0334     us->cr->wValue = cpu_to_le16(value);
0335     us->cr->wIndex = cpu_to_le16(index);
0336     us->cr->wLength = cpu_to_le16(size);
0337 
0338     /* fill and submit the URB */
0339     usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe, 
0340              (unsigned char*) us->cr, data, size, 
0341              usb_stor_blocking_completion, NULL);
0342     result = usb_stor_msg_common(us, 0);
0343 
0344     return interpret_urb_result(us, pipe, size, result,
0345             us->current_urb->actual_length);
0346 }
0347 EXPORT_SYMBOL_GPL(usb_stor_ctrl_transfer);
0348 
0349 /*
0350  * Receive one interrupt buffer, without timeouts, but allowing early
0351  * termination.  Return codes are USB_STOR_XFER_xxx.
0352  *
0353  * This routine always uses us->recv_intr_pipe as the pipe and
0354  * us->ep_bInterval as the interrupt interval.
0355  */
0356 static int usb_stor_intr_transfer(struct us_data *us, void *buf,
0357                   unsigned int length)
0358 {
0359     int result;
0360     unsigned int pipe = us->recv_intr_pipe;
0361     unsigned int maxp;
0362 
0363     usb_stor_dbg(us, "xfer %u bytes\n", length);
0364 
0365     /* calculate the max packet size */
0366     maxp = usb_maxpacket(us->pusb_dev, pipe);
0367     if (maxp > length)
0368         maxp = length;
0369 
0370     /* fill and submit the URB */
0371     usb_fill_int_urb(us->current_urb, us->pusb_dev, pipe, buf,
0372             maxp, usb_stor_blocking_completion, NULL,
0373             us->ep_bInterval);
0374     result = usb_stor_msg_common(us, 0);
0375 
0376     return interpret_urb_result(us, pipe, length, result,
0377             us->current_urb->actual_length);
0378 }
0379 
0380 /*
0381  * Transfer one buffer via bulk pipe, without timeouts, but allowing early
0382  * termination.  Return codes are USB_STOR_XFER_xxx.  If the bulk pipe
0383  * stalls during the transfer, the halt is automatically cleared.
0384  */
0385 int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe,
0386     void *buf, unsigned int length, unsigned int *act_len)
0387 {
0388     int result;
0389 
0390     usb_stor_dbg(us, "xfer %u bytes\n", length);
0391 
0392     /* fill and submit the URB */
0393     usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length,
0394               usb_stor_blocking_completion, NULL);
0395     result = usb_stor_msg_common(us, 0);
0396 
0397     /* store the actual length of the data transferred */
0398     if (act_len)
0399         *act_len = us->current_urb->actual_length;
0400     return interpret_urb_result(us, pipe, length, result, 
0401             us->current_urb->actual_length);
0402 }
0403 EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf);
0404 
0405 /*
0406  * Transfer a scatter-gather list via bulk transfer
0407  *
0408  * This function does basically the same thing as usb_stor_bulk_transfer_buf()
0409  * above, but it uses the usbcore scatter-gather library.
0410  */
0411 static int usb_stor_bulk_transfer_sglist(struct us_data *us, unsigned int pipe,
0412         struct scatterlist *sg, int num_sg, unsigned int length,
0413         unsigned int *act_len)
0414 {
0415     int result;
0416 
0417     /* don't submit s-g requests during abort processing */
0418     if (test_bit(US_FLIDX_ABORTING, &us->dflags))
0419         goto usb_stor_xfer_error;
0420 
0421     /* initialize the scatter-gather request block */
0422     usb_stor_dbg(us, "xfer %u bytes, %d entries\n", length, num_sg);
0423     result = usb_sg_init(&us->current_sg, us->pusb_dev, pipe, 0,
0424             sg, num_sg, length, GFP_NOIO);
0425     if (result) {
0426         usb_stor_dbg(us, "usb_sg_init returned %d\n", result);
0427         goto usb_stor_xfer_error;
0428     }
0429 
0430     /*
0431      * since the block has been initialized successfully, it's now
0432      * okay to cancel it
0433      */
0434     set_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
0435 
0436     /* did an abort occur during the submission? */
0437     if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
0438 
0439         /* cancel the request, if it hasn't been cancelled already */
0440         if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
0441             usb_stor_dbg(us, "-- cancelling sg request\n");
0442             usb_sg_cancel(&us->current_sg);
0443         }
0444     }
0445 
0446     /* wait for the completion of the transfer */
0447     usb_sg_wait(&us->current_sg);
0448     clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
0449 
0450     result = us->current_sg.status;
0451     if (act_len)
0452         *act_len = us->current_sg.bytes;
0453     return interpret_urb_result(us, pipe, length, result,
0454             us->current_sg.bytes);
0455 
0456 usb_stor_xfer_error:
0457     if (act_len)
0458         *act_len = 0;
0459     return USB_STOR_XFER_ERROR;
0460 }
0461 
0462 /*
0463  * Common used function. Transfer a complete command
0464  * via usb_stor_bulk_transfer_sglist() above. Set cmnd resid
0465  */
0466 int usb_stor_bulk_srb(struct us_data* us, unsigned int pipe,
0467               struct scsi_cmnd* srb)
0468 {
0469     unsigned int partial;
0470     int result = usb_stor_bulk_transfer_sglist(us, pipe, scsi_sglist(srb),
0471                       scsi_sg_count(srb), scsi_bufflen(srb),
0472                       &partial);
0473 
0474     scsi_set_resid(srb, scsi_bufflen(srb) - partial);
0475     return result;
0476 }
0477 EXPORT_SYMBOL_GPL(usb_stor_bulk_srb);
0478 
0479 /*
0480  * Transfer an entire SCSI command's worth of data payload over the bulk
0481  * pipe.
0482  *
0483  * Note that this uses usb_stor_bulk_transfer_buf() and
0484  * usb_stor_bulk_transfer_sglist() to achieve its goals --
0485  * this function simply determines whether we're going to use
0486  * scatter-gather or not, and acts appropriately.
0487  */
0488 int usb_stor_bulk_transfer_sg(struct us_data* us, unsigned int pipe,
0489         void *buf, unsigned int length_left, int use_sg, int *residual)
0490 {
0491     int result;
0492     unsigned int partial;
0493 
0494     /* are we scatter-gathering? */
0495     if (use_sg) {
0496         /* use the usb core scatter-gather primitives */
0497         result = usb_stor_bulk_transfer_sglist(us, pipe,
0498                 (struct scatterlist *) buf, use_sg,
0499                 length_left, &partial);
0500         length_left -= partial;
0501     } else {
0502         /* no scatter-gather, just make the request */
0503         result = usb_stor_bulk_transfer_buf(us, pipe, buf, 
0504                 length_left, &partial);
0505         length_left -= partial;
0506     }
0507 
0508     /* store the residual and return the error code */
0509     if (residual)
0510         *residual = length_left;
0511     return result;
0512 }
0513 EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_sg);
0514 
0515 /***********************************************************************
0516  * Transport routines
0517  ***********************************************************************/
0518 
0519 /*
0520  * There are so many devices that report the capacity incorrectly,
0521  * this routine was written to counteract some of the resulting
0522  * problems.
0523  */
0524 static void last_sector_hacks(struct us_data *us, struct scsi_cmnd *srb)
0525 {
0526     struct gendisk *disk;
0527     struct scsi_disk *sdkp;
0528     u32 sector;
0529 
0530     /* To Report "Medium Error: Record Not Found */
0531     static unsigned char record_not_found[18] = {
0532         [0] = 0x70,         /* current error */
0533         [2] = MEDIUM_ERROR,     /* = 0x03 */
0534         [7] = 0x0a,         /* additional length */
0535         [12]    = 0x14          /* Record Not Found */
0536     };
0537 
0538     /*
0539      * If last-sector problems can't occur, whether because the
0540      * capacity was already decremented or because the device is
0541      * known to report the correct capacity, then we don't need
0542      * to do anything.
0543      */
0544     if (!us->use_last_sector_hacks)
0545         return;
0546 
0547     /* Was this command a READ(10) or a WRITE(10)? */
0548     if (srb->cmnd[0] != READ_10 && srb->cmnd[0] != WRITE_10)
0549         goto done;
0550 
0551     /* Did this command access the last sector? */
0552     sector = (srb->cmnd[2] << 24) | (srb->cmnd[3] << 16) |
0553             (srb->cmnd[4] << 8) | (srb->cmnd[5]);
0554     disk = scsi_cmd_to_rq(srb)->q->disk;
0555     if (!disk)
0556         goto done;
0557     sdkp = scsi_disk(disk);
0558     if (!sdkp)
0559         goto done;
0560     if (sector + 1 != sdkp->capacity)
0561         goto done;
0562 
0563     if (srb->result == SAM_STAT_GOOD && scsi_get_resid(srb) == 0) {
0564 
0565         /*
0566          * The command succeeded.  We know this device doesn't
0567          * have the last-sector bug, so stop checking it.
0568          */
0569         us->use_last_sector_hacks = 0;
0570 
0571     } else {
0572         /*
0573          * The command failed.  Allow up to 3 retries in case this
0574          * is some normal sort of failure.  After that, assume the
0575          * capacity is wrong and we're trying to access the sector
0576          * beyond the end.  Replace the result code and sense data
0577          * with values that will cause the SCSI core to fail the
0578          * command immediately, instead of going into an infinite
0579          * (or even just a very long) retry loop.
0580          */
0581         if (++us->last_sector_retries < 3)
0582             return;
0583         srb->result = SAM_STAT_CHECK_CONDITION;
0584         memcpy(srb->sense_buffer, record_not_found,
0585                 sizeof(record_not_found));
0586     }
0587 
0588  done:
0589     /*
0590      * Don't reset the retry counter for TEST UNIT READY commands,
0591      * because they get issued after device resets which might be
0592      * caused by a failed last-sector access.
0593      */
0594     if (srb->cmnd[0] != TEST_UNIT_READY)
0595         us->last_sector_retries = 0;
0596 }
0597 
0598 /*
0599  * Invoke the transport and basic error-handling/recovery methods
0600  *
0601  * This is used by the protocol layers to actually send the message to
0602  * the device and receive the response.
0603  */
0604 void usb_stor_invoke_transport(struct scsi_cmnd *srb, struct us_data *us)
0605 {
0606     int need_auto_sense;
0607     int result;
0608 
0609     /* send the command to the transport layer */
0610     scsi_set_resid(srb, 0);
0611     result = us->transport(srb, us);
0612 
0613     /*
0614      * if the command gets aborted by the higher layers, we need to
0615      * short-circuit all other processing
0616      */
0617     if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
0618         usb_stor_dbg(us, "-- command was aborted\n");
0619         srb->result = DID_ABORT << 16;
0620         goto Handle_Errors;
0621     }
0622 
0623     /* if there is a transport error, reset and don't auto-sense */
0624     if (result == USB_STOR_TRANSPORT_ERROR) {
0625         usb_stor_dbg(us, "-- transport indicates error, resetting\n");
0626         srb->result = DID_ERROR << 16;
0627         goto Handle_Errors;
0628     }
0629 
0630     /* if the transport provided its own sense data, don't auto-sense */
0631     if (result == USB_STOR_TRANSPORT_NO_SENSE) {
0632         srb->result = SAM_STAT_CHECK_CONDITION;
0633         last_sector_hacks(us, srb);
0634         return;
0635     }
0636 
0637     srb->result = SAM_STAT_GOOD;
0638 
0639     /*
0640      * Determine if we need to auto-sense
0641      *
0642      * I normally don't use a flag like this, but it's almost impossible
0643      * to understand what's going on here if I don't.
0644      */
0645     need_auto_sense = 0;
0646 
0647     /*
0648      * If we're running the CB transport, which is incapable
0649      * of determining status on its own, we will auto-sense
0650      * unless the operation involved a data-in transfer.  Devices
0651      * can signal most data-in errors by stalling the bulk-in pipe.
0652      */
0653     if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_DPCM_USB) &&
0654             srb->sc_data_direction != DMA_FROM_DEVICE) {
0655         usb_stor_dbg(us, "-- CB transport device requiring auto-sense\n");
0656         need_auto_sense = 1;
0657     }
0658 
0659     /* Some devices (Kindle) require another command after SYNC CACHE */
0660     if ((us->fflags & US_FL_SENSE_AFTER_SYNC) &&
0661             srb->cmnd[0] == SYNCHRONIZE_CACHE) {
0662         usb_stor_dbg(us, "-- sense after SYNC CACHE\n");
0663         need_auto_sense = 1;
0664     }
0665 
0666     /*
0667      * If we have a failure, we're going to do a REQUEST_SENSE 
0668      * automatically.  Note that we differentiate between a command
0669      * "failure" and an "error" in the transport mechanism.
0670      */
0671     if (result == USB_STOR_TRANSPORT_FAILED) {
0672         usb_stor_dbg(us, "-- transport indicates command failure\n");
0673         need_auto_sense = 1;
0674     }
0675 
0676     /*
0677      * Determine if this device is SAT by seeing if the
0678      * command executed successfully.  Otherwise we'll have
0679      * to wait for at least one CHECK_CONDITION to determine
0680      * SANE_SENSE support
0681      */
0682     if (unlikely((srb->cmnd[0] == ATA_16 || srb->cmnd[0] == ATA_12) &&
0683         result == USB_STOR_TRANSPORT_GOOD &&
0684         !(us->fflags & US_FL_SANE_SENSE) &&
0685         !(us->fflags & US_FL_BAD_SENSE) &&
0686         !(srb->cmnd[2] & 0x20))) {
0687         usb_stor_dbg(us, "-- SAT supported, increasing auto-sense\n");
0688         us->fflags |= US_FL_SANE_SENSE;
0689     }
0690 
0691     /*
0692      * A short transfer on a command where we don't expect it
0693      * is unusual, but it doesn't mean we need to auto-sense.
0694      */
0695     if ((scsi_get_resid(srb) > 0) &&
0696         !((srb->cmnd[0] == REQUEST_SENSE) ||
0697           (srb->cmnd[0] == INQUIRY) ||
0698           (srb->cmnd[0] == MODE_SENSE) ||
0699           (srb->cmnd[0] == LOG_SENSE) ||
0700           (srb->cmnd[0] == MODE_SENSE_10))) {
0701         usb_stor_dbg(us, "-- unexpectedly short transfer\n");
0702     }
0703 
0704     /* Now, if we need to do the auto-sense, let's do it */
0705     if (need_auto_sense) {
0706         int temp_result;
0707         struct scsi_eh_save ses;
0708         int sense_size = US_SENSE_SIZE;
0709         struct scsi_sense_hdr sshdr;
0710         const u8 *scdd;
0711         u8 fm_ili;
0712 
0713         /* device supports and needs bigger sense buffer */
0714         if (us->fflags & US_FL_SANE_SENSE)
0715             sense_size = ~0;
0716 Retry_Sense:
0717         usb_stor_dbg(us, "Issuing auto-REQUEST_SENSE\n");
0718 
0719         scsi_eh_prep_cmnd(srb, &ses, NULL, 0, sense_size);
0720 
0721         /* FIXME: we must do the protocol translation here */
0722         if (us->subclass == USB_SC_RBC || us->subclass == USB_SC_SCSI ||
0723                 us->subclass == USB_SC_CYP_ATACB)
0724             srb->cmd_len = 6;
0725         else
0726             srb->cmd_len = 12;
0727 
0728         /* issue the auto-sense command */
0729         scsi_set_resid(srb, 0);
0730         temp_result = us->transport(us->srb, us);
0731 
0732         /* let's clean up right away */
0733         scsi_eh_restore_cmnd(srb, &ses);
0734 
0735         if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
0736             usb_stor_dbg(us, "-- auto-sense aborted\n");
0737             srb->result = DID_ABORT << 16;
0738 
0739             /* If SANE_SENSE caused this problem, disable it */
0740             if (sense_size != US_SENSE_SIZE) {
0741                 us->fflags &= ~US_FL_SANE_SENSE;
0742                 us->fflags |= US_FL_BAD_SENSE;
0743             }
0744             goto Handle_Errors;
0745         }
0746 
0747         /*
0748          * Some devices claim to support larger sense but fail when
0749          * trying to request it. When a transport failure happens
0750          * using US_FS_SANE_SENSE, we always retry with a standard
0751          * (small) sense request. This fixes some USB GSM modems
0752          */
0753         if (temp_result == USB_STOR_TRANSPORT_FAILED &&
0754                 sense_size != US_SENSE_SIZE) {
0755             usb_stor_dbg(us, "-- auto-sense failure, retry small sense\n");
0756             sense_size = US_SENSE_SIZE;
0757             us->fflags &= ~US_FL_SANE_SENSE;
0758             us->fflags |= US_FL_BAD_SENSE;
0759             goto Retry_Sense;
0760         }
0761 
0762         /* Other failures */
0763         if (temp_result != USB_STOR_TRANSPORT_GOOD) {
0764             usb_stor_dbg(us, "-- auto-sense failure\n");
0765 
0766             /*
0767              * we skip the reset if this happens to be a
0768              * multi-target device, since failure of an
0769              * auto-sense is perfectly valid
0770              */
0771             srb->result = DID_ERROR << 16;
0772             if (!(us->fflags & US_FL_SCM_MULT_TARG))
0773                 goto Handle_Errors;
0774             return;
0775         }
0776 
0777         /*
0778          * If the sense data returned is larger than 18-bytes then we
0779          * assume this device supports requesting more in the future.
0780          * The response code must be 70h through 73h inclusive.
0781          */
0782         if (srb->sense_buffer[7] > (US_SENSE_SIZE - 8) &&
0783             !(us->fflags & US_FL_SANE_SENSE) &&
0784             !(us->fflags & US_FL_BAD_SENSE) &&
0785             (srb->sense_buffer[0] & 0x7C) == 0x70) {
0786             usb_stor_dbg(us, "-- SANE_SENSE support enabled\n");
0787             us->fflags |= US_FL_SANE_SENSE;
0788 
0789             /*
0790              * Indicate to the user that we truncated their sense
0791              * because we didn't know it supported larger sense.
0792              */
0793             usb_stor_dbg(us, "-- Sense data truncated to %i from %i\n",
0794                      US_SENSE_SIZE,
0795                      srb->sense_buffer[7] + 8);
0796             srb->sense_buffer[7] = (US_SENSE_SIZE - 8);
0797         }
0798 
0799         scsi_normalize_sense(srb->sense_buffer, SCSI_SENSE_BUFFERSIZE,
0800                      &sshdr);
0801 
0802         usb_stor_dbg(us, "-- Result from auto-sense is %d\n",
0803                  temp_result);
0804         usb_stor_dbg(us, "-- code: 0x%x, key: 0x%x, ASC: 0x%x, ASCQ: 0x%x\n",
0805                  sshdr.response_code, sshdr.sense_key,
0806                  sshdr.asc, sshdr.ascq);
0807 #ifdef CONFIG_USB_STORAGE_DEBUG
0808         usb_stor_show_sense(us, sshdr.sense_key, sshdr.asc, sshdr.ascq);
0809 #endif
0810 
0811         /* set the result so the higher layers expect this data */
0812         srb->result = SAM_STAT_CHECK_CONDITION;
0813 
0814         scdd = scsi_sense_desc_find(srb->sense_buffer,
0815                         SCSI_SENSE_BUFFERSIZE, 4);
0816         fm_ili = (scdd ? scdd[3] : srb->sense_buffer[2]) & 0xA0;
0817 
0818         /*
0819          * We often get empty sense data.  This could indicate that
0820          * everything worked or that there was an unspecified
0821          * problem.  We have to decide which.
0822          */
0823         if (sshdr.sense_key == 0 && sshdr.asc == 0 && sshdr.ascq == 0 &&
0824             fm_ili == 0) {
0825             /*
0826              * If things are really okay, then let's show that.
0827              * Zero out the sense buffer so the higher layers
0828              * won't realize we did an unsolicited auto-sense.
0829              */
0830             if (result == USB_STOR_TRANSPORT_GOOD) {
0831                 srb->result = SAM_STAT_GOOD;
0832                 srb->sense_buffer[0] = 0x0;
0833             }
0834 
0835             /*
0836              * ATA-passthru commands use sense data to report
0837              * the command completion status, and often devices
0838              * return Check Condition status when nothing is
0839              * wrong.
0840              */
0841             else if (srb->cmnd[0] == ATA_16 ||
0842                     srb->cmnd[0] == ATA_12) {
0843                 /* leave the data alone */
0844             }
0845 
0846             /*
0847              * If there was a problem, report an unspecified
0848              * hardware error to prevent the higher layers from
0849              * entering an infinite retry loop.
0850              */
0851             else {
0852                 srb->result = DID_ERROR << 16;
0853                 if ((sshdr.response_code & 0x72) == 0x72)
0854                     srb->sense_buffer[1] = HARDWARE_ERROR;
0855                 else
0856                     srb->sense_buffer[2] = HARDWARE_ERROR;
0857             }
0858         }
0859     }
0860 
0861     /*
0862      * Some devices don't work or return incorrect data the first
0863      * time they get a READ(10) command, or for the first READ(10)
0864      * after a media change.  If the INITIAL_READ10 flag is set,
0865      * keep track of whether READ(10) commands succeed.  If the
0866      * previous one succeeded and this one failed, set the REDO_READ10
0867      * flag to force a retry.
0868      */
0869     if (unlikely((us->fflags & US_FL_INITIAL_READ10) &&
0870             srb->cmnd[0] == READ_10)) {
0871         if (srb->result == SAM_STAT_GOOD) {
0872             set_bit(US_FLIDX_READ10_WORKED, &us->dflags);
0873         } else if (test_bit(US_FLIDX_READ10_WORKED, &us->dflags)) {
0874             clear_bit(US_FLIDX_READ10_WORKED, &us->dflags);
0875             set_bit(US_FLIDX_REDO_READ10, &us->dflags);
0876         }
0877 
0878         /*
0879          * Next, if the REDO_READ10 flag is set, return a result
0880          * code that will cause the SCSI core to retry the READ(10)
0881          * command immediately.
0882          */
0883         if (test_bit(US_FLIDX_REDO_READ10, &us->dflags)) {
0884             clear_bit(US_FLIDX_REDO_READ10, &us->dflags);
0885             srb->result = DID_IMM_RETRY << 16;
0886             srb->sense_buffer[0] = 0;
0887         }
0888     }
0889 
0890     /* Did we transfer less than the minimum amount required? */
0891     if ((srb->result == SAM_STAT_GOOD || srb->sense_buffer[2] == 0) &&
0892             scsi_bufflen(srb) - scsi_get_resid(srb) < srb->underflow)
0893         srb->result = DID_ERROR << 16;
0894 
0895     last_sector_hacks(us, srb);
0896     return;
0897 
0898     /*
0899      * Error and abort processing: try to resynchronize with the device
0900      * by issuing a port reset.  If that fails, try a class-specific
0901      * device reset.
0902      */
0903   Handle_Errors:
0904 
0905     /*
0906      * Set the RESETTING bit, and clear the ABORTING bit so that
0907      * the reset may proceed.
0908      */
0909     scsi_lock(us_to_host(us));
0910     set_bit(US_FLIDX_RESETTING, &us->dflags);
0911     clear_bit(US_FLIDX_ABORTING, &us->dflags);
0912     scsi_unlock(us_to_host(us));
0913 
0914     /*
0915      * We must release the device lock because the pre_reset routine
0916      * will want to acquire it.
0917      */
0918     mutex_unlock(&us->dev_mutex);
0919     result = usb_stor_port_reset(us);
0920     mutex_lock(&us->dev_mutex);
0921 
0922     if (result < 0) {
0923         scsi_lock(us_to_host(us));
0924         usb_stor_report_device_reset(us);
0925         scsi_unlock(us_to_host(us));
0926         us->transport_reset(us);
0927     }
0928     clear_bit(US_FLIDX_RESETTING, &us->dflags);
0929     last_sector_hacks(us, srb);
0930 }
0931 
0932 /* Stop the current URB transfer */
0933 void usb_stor_stop_transport(struct us_data *us)
0934 {
0935     /*
0936      * If the state machine is blocked waiting for an URB,
0937      * let's wake it up.  The test_and_clear_bit() call
0938      * guarantees that if a URB has just been submitted,
0939      * it won't be cancelled more than once.
0940      */
0941     if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
0942         usb_stor_dbg(us, "-- cancelling URB\n");
0943         usb_unlink_urb(us->current_urb);
0944     }
0945 
0946     /* If we are waiting for a scatter-gather operation, cancel it. */
0947     if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
0948         usb_stor_dbg(us, "-- cancelling sg request\n");
0949         usb_sg_cancel(&us->current_sg);
0950     }
0951 }
0952 
0953 /*
0954  * Control/Bulk and Control/Bulk/Interrupt transport
0955  */
0956 
0957 int usb_stor_CB_transport(struct scsi_cmnd *srb, struct us_data *us)
0958 {
0959     unsigned int transfer_length = scsi_bufflen(srb);
0960     unsigned int pipe = 0;
0961     int result;
0962 
0963     /* COMMAND STAGE */
0964     /* let's send the command via the control pipe */
0965     /*
0966      * Command is sometime (f.e. after scsi_eh_prep_cmnd) on the stack.
0967      * Stack may be vmallocated.  So no DMA for us.  Make a copy.
0968      */
0969     memcpy(us->iobuf, srb->cmnd, srb->cmd_len);
0970     result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0971                       US_CBI_ADSC, 
0972                       USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 
0973                       us->ifnum, us->iobuf, srb->cmd_len);
0974 
0975     /* check the return code for the command */
0976     usb_stor_dbg(us, "Call to usb_stor_ctrl_transfer() returned %d\n",
0977              result);
0978 
0979     /* if we stalled the command, it means command failed */
0980     if (result == USB_STOR_XFER_STALLED) {
0981         return USB_STOR_TRANSPORT_FAILED;
0982     }
0983 
0984     /* Uh oh... serious problem here */
0985     if (result != USB_STOR_XFER_GOOD) {
0986         return USB_STOR_TRANSPORT_ERROR;
0987     }
0988 
0989     /* DATA STAGE */
0990     /* transfer the data payload for this command, if one exists*/
0991     if (transfer_length) {
0992         pipe = srb->sc_data_direction == DMA_FROM_DEVICE ? 
0993                 us->recv_bulk_pipe : us->send_bulk_pipe;
0994         result = usb_stor_bulk_srb(us, pipe, srb);
0995         usb_stor_dbg(us, "CBI data stage result is 0x%x\n", result);
0996 
0997         /* if we stalled the data transfer it means command failed */
0998         if (result == USB_STOR_XFER_STALLED)
0999             return USB_STOR_TRANSPORT_FAILED;
1000         if (result > USB_STOR_XFER_STALLED)
1001             return USB_STOR_TRANSPORT_ERROR;
1002     }
1003 
1004     /* STATUS STAGE */
1005 
1006     /*
1007      * NOTE: CB does not have a status stage.  Silly, I know.  So
1008      * we have to catch this at a higher level.
1009      */
1010     if (us->protocol != USB_PR_CBI)
1011         return USB_STOR_TRANSPORT_GOOD;
1012 
1013     result = usb_stor_intr_transfer(us, us->iobuf, 2);
1014     usb_stor_dbg(us, "Got interrupt data (0x%x, 0x%x)\n",
1015              us->iobuf[0], us->iobuf[1]);
1016     if (result != USB_STOR_XFER_GOOD)
1017         return USB_STOR_TRANSPORT_ERROR;
1018 
1019     /*
1020      * UFI gives us ASC and ASCQ, like a request sense
1021      *
1022      * REQUEST_SENSE and INQUIRY don't affect the sense data on UFI
1023      * devices, so we ignore the information for those commands.  Note
1024      * that this means we could be ignoring a real error on these
1025      * commands, but that can't be helped.
1026      */
1027     if (us->subclass == USB_SC_UFI) {
1028         if (srb->cmnd[0] == REQUEST_SENSE ||
1029             srb->cmnd[0] == INQUIRY)
1030             return USB_STOR_TRANSPORT_GOOD;
1031         if (us->iobuf[0])
1032             goto Failed;
1033         return USB_STOR_TRANSPORT_GOOD;
1034     }
1035 
1036     /*
1037      * If not UFI, we interpret the data as a result code 
1038      * The first byte should always be a 0x0.
1039      *
1040      * Some bogus devices don't follow that rule.  They stuff the ASC
1041      * into the first byte -- so if it's non-zero, call it a failure.
1042      */
1043     if (us->iobuf[0]) {
1044         usb_stor_dbg(us, "CBI IRQ data showed reserved bType 0x%x\n",
1045                  us->iobuf[0]);
1046         goto Failed;
1047 
1048     }
1049 
1050     /* The second byte & 0x0F should be 0x0 for good, otherwise error */
1051     switch (us->iobuf[1] & 0x0F) {
1052         case 0x00: 
1053             return USB_STOR_TRANSPORT_GOOD;
1054         case 0x01: 
1055             goto Failed;
1056     }
1057     return USB_STOR_TRANSPORT_ERROR;
1058 
1059     /*
1060      * the CBI spec requires that the bulk pipe must be cleared
1061      * following any data-in/out command failure (section 2.4.3.1.3)
1062      */
1063   Failed:
1064     if (pipe)
1065         usb_stor_clear_halt(us, pipe);
1066     return USB_STOR_TRANSPORT_FAILED;
1067 }
1068 EXPORT_SYMBOL_GPL(usb_stor_CB_transport);
1069 
1070 /*
1071  * Bulk only transport
1072  */
1073 
1074 /* Determine what the maximum LUN supported is */
1075 int usb_stor_Bulk_max_lun(struct us_data *us)
1076 {
1077     int result;
1078 
1079     /* issue the command */
1080     us->iobuf[0] = 0;
1081     result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
1082                  US_BULK_GET_MAX_LUN, 
1083                  USB_DIR_IN | USB_TYPE_CLASS | 
1084                  USB_RECIP_INTERFACE,
1085                  0, us->ifnum, us->iobuf, 1, 10*HZ);
1086 
1087     usb_stor_dbg(us, "GetMaxLUN command result is %d, data is %d\n",
1088              result, us->iobuf[0]);
1089 
1090     /*
1091      * If we have a successful request, return the result if valid. The
1092      * CBW LUN field is 4 bits wide, so the value reported by the device
1093      * should fit into that.
1094      */
1095     if (result > 0) {
1096         if (us->iobuf[0] < 16) {
1097             return us->iobuf[0];
1098         } else {
1099             dev_info(&us->pusb_intf->dev,
1100                  "Max LUN %d is not valid, using 0 instead",
1101                  us->iobuf[0]);
1102         }
1103     }
1104 
1105     /*
1106      * Some devices don't like GetMaxLUN.  They may STALL the control
1107      * pipe, they may return a zero-length result, they may do nothing at
1108      * all and timeout, or they may fail in even more bizarrely creative
1109      * ways.  In these cases the best approach is to use the default
1110      * value: only one LUN.
1111      */
1112     return 0;
1113 }
1114 
1115 int usb_stor_Bulk_transport(struct scsi_cmnd *srb, struct us_data *us)
1116 {
1117     struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
1118     struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
1119     unsigned int transfer_length = scsi_bufflen(srb);
1120     unsigned int residue;
1121     int result;
1122     int fake_sense = 0;
1123     unsigned int cswlen;
1124     unsigned int cbwlen = US_BULK_CB_WRAP_LEN;
1125 
1126     /* Take care of BULK32 devices; set extra byte to 0 */
1127     if (unlikely(us->fflags & US_FL_BULK32)) {
1128         cbwlen = 32;
1129         us->iobuf[31] = 0;
1130     }
1131 
1132     /* set up the command wrapper */
1133     bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1134     bcb->DataTransferLength = cpu_to_le32(transfer_length);
1135     bcb->Flags = srb->sc_data_direction == DMA_FROM_DEVICE ?
1136         US_BULK_FLAG_IN : 0;
1137     bcb->Tag = ++us->tag;
1138     bcb->Lun = srb->device->lun;
1139     if (us->fflags & US_FL_SCM_MULT_TARG)
1140         bcb->Lun |= srb->device->id << 4;
1141     bcb->Length = srb->cmd_len;
1142 
1143     /* copy the command payload */
1144     memset(bcb->CDB, 0, sizeof(bcb->CDB));
1145     memcpy(bcb->CDB, srb->cmnd, bcb->Length);
1146 
1147     /* send it to out endpoint */
1148     usb_stor_dbg(us, "Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
1149              le32_to_cpu(bcb->Signature), bcb->Tag,
1150              le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
1151              (bcb->Lun >> 4), (bcb->Lun & 0x0F),
1152              bcb->Length);
1153     result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
1154                 bcb, cbwlen, NULL);
1155     usb_stor_dbg(us, "Bulk command transfer result=%d\n", result);
1156     if (result != USB_STOR_XFER_GOOD)
1157         return USB_STOR_TRANSPORT_ERROR;
1158 
1159     /* DATA STAGE */
1160     /* send/receive data payload, if there is any */
1161 
1162     /*
1163      * Some USB-IDE converter chips need a 100us delay between the
1164      * command phase and the data phase.  Some devices need a little
1165      * more than that, probably because of clock rate inaccuracies.
1166      */
1167     if (unlikely(us->fflags & US_FL_GO_SLOW))
1168         usleep_range(125, 150);
1169 
1170     if (transfer_length) {
1171         unsigned int pipe = srb->sc_data_direction == DMA_FROM_DEVICE ? 
1172                 us->recv_bulk_pipe : us->send_bulk_pipe;
1173         result = usb_stor_bulk_srb(us, pipe, srb);
1174         usb_stor_dbg(us, "Bulk data transfer result 0x%x\n", result);
1175         if (result == USB_STOR_XFER_ERROR)
1176             return USB_STOR_TRANSPORT_ERROR;
1177 
1178         /*
1179          * If the device tried to send back more data than the
1180          * amount requested, the spec requires us to transfer
1181          * the CSW anyway.  Since there's no point retrying
1182          * the command, we'll return fake sense data indicating
1183          * Illegal Request, Invalid Field in CDB.
1184          */
1185         if (result == USB_STOR_XFER_LONG)
1186             fake_sense = 1;
1187 
1188         /*
1189          * Sometimes a device will mistakenly skip the data phase
1190          * and go directly to the status phase without sending a
1191          * zero-length packet.  If we get a 13-byte response here,
1192          * check whether it really is a CSW.
1193          */
1194         if (result == USB_STOR_XFER_SHORT &&
1195                 srb->sc_data_direction == DMA_FROM_DEVICE &&
1196                 transfer_length - scsi_get_resid(srb) ==
1197                     US_BULK_CS_WRAP_LEN) {
1198             struct scatterlist *sg = NULL;
1199             unsigned int offset = 0;
1200 
1201             if (usb_stor_access_xfer_buf((unsigned char *) bcs,
1202                     US_BULK_CS_WRAP_LEN, srb, &sg,
1203                     &offset, FROM_XFER_BUF) ==
1204                         US_BULK_CS_WRAP_LEN &&
1205                     bcs->Signature ==
1206                         cpu_to_le32(US_BULK_CS_SIGN)) {
1207                 usb_stor_dbg(us, "Device skipped data phase\n");
1208                 scsi_set_resid(srb, transfer_length);
1209                 goto skipped_data_phase;
1210             }
1211         }
1212     }
1213 
1214     /*
1215      * See flow chart on pg 15 of the Bulk Only Transport spec for
1216      * an explanation of how this code works.
1217      */
1218 
1219     /* get CSW for device status */
1220     usb_stor_dbg(us, "Attempting to get CSW...\n");
1221     result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1222                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1223 
1224     /*
1225      * Some broken devices add unnecessary zero-length packets to the
1226      * end of their data transfers.  Such packets show up as 0-length
1227      * CSWs.  If we encounter such a thing, try to read the CSW again.
1228      */
1229     if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
1230         usb_stor_dbg(us, "Received 0-length CSW; retrying...\n");
1231         result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1232                 bcs, US_BULK_CS_WRAP_LEN, &cswlen);
1233     }
1234 
1235     /* did the attempt to read the CSW fail? */
1236     if (result == USB_STOR_XFER_STALLED) {
1237 
1238         /* get the status again */
1239         usb_stor_dbg(us, "Attempting to get CSW (2nd try)...\n");
1240         result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
1241                 bcs, US_BULK_CS_WRAP_LEN, NULL);
1242     }
1243 
1244     /* if we still have a failure at this point, we're in trouble */
1245     usb_stor_dbg(us, "Bulk status result = %d\n", result);
1246     if (result != USB_STOR_XFER_GOOD)
1247         return USB_STOR_TRANSPORT_ERROR;
1248 
1249  skipped_data_phase:
1250     /* check bulk status */
1251     residue = le32_to_cpu(bcs->Residue);
1252     usb_stor_dbg(us, "Bulk Status S 0x%x T 0x%x R %u Stat 0x%x\n",
1253              le32_to_cpu(bcs->Signature), bcs->Tag,
1254              residue, bcs->Status);
1255     if (!(bcs->Tag == us->tag || (us->fflags & US_FL_BULK_IGNORE_TAG)) ||
1256         bcs->Status > US_BULK_STAT_PHASE) {
1257         usb_stor_dbg(us, "Bulk logical error\n");
1258         return USB_STOR_TRANSPORT_ERROR;
1259     }
1260 
1261     /*
1262      * Some broken devices report odd signatures, so we do not check them
1263      * for validity against the spec. We store the first one we see,
1264      * and check subsequent transfers for validity against this signature.
1265      */
1266     if (!us->bcs_signature) {
1267         us->bcs_signature = bcs->Signature;
1268         if (us->bcs_signature != cpu_to_le32(US_BULK_CS_SIGN))
1269             usb_stor_dbg(us, "Learnt BCS signature 0x%08X\n",
1270                      le32_to_cpu(us->bcs_signature));
1271     } else if (bcs->Signature != us->bcs_signature) {
1272         usb_stor_dbg(us, "Signature mismatch: got %08X, expecting %08X\n",
1273                  le32_to_cpu(bcs->Signature),
1274                  le32_to_cpu(us->bcs_signature));
1275         return USB_STOR_TRANSPORT_ERROR;
1276     }
1277 
1278     /*
1279      * try to compute the actual residue, based on how much data
1280      * was really transferred and what the device tells us
1281      */
1282     if (residue && !(us->fflags & US_FL_IGNORE_RESIDUE)) {
1283 
1284         /*
1285          * Heuristically detect devices that generate bogus residues
1286          * by seeing what happens with INQUIRY and READ CAPACITY
1287          * commands.
1288          */
1289         if (bcs->Status == US_BULK_STAT_OK &&
1290                 scsi_get_resid(srb) == 0 &&
1291                     ((srb->cmnd[0] == INQUIRY &&
1292                         transfer_length == 36) ||
1293                     (srb->cmnd[0] == READ_CAPACITY &&
1294                         transfer_length == 8))) {
1295             us->fflags |= US_FL_IGNORE_RESIDUE;
1296 
1297         } else {
1298             residue = min(residue, transfer_length);
1299             scsi_set_resid(srb, max(scsi_get_resid(srb), residue));
1300         }
1301     }
1302 
1303     /* based on the status code, we report good or bad */
1304     switch (bcs->Status) {
1305         case US_BULK_STAT_OK:
1306             /* device babbled -- return fake sense data */
1307             if (fake_sense) {
1308                 memcpy(srb->sense_buffer, 
1309                        usb_stor_sense_invalidCDB, 
1310                        sizeof(usb_stor_sense_invalidCDB));
1311                 return USB_STOR_TRANSPORT_NO_SENSE;
1312             }
1313 
1314             /* command good -- note that data could be short */
1315             return USB_STOR_TRANSPORT_GOOD;
1316 
1317         case US_BULK_STAT_FAIL:
1318             /* command failed */
1319             return USB_STOR_TRANSPORT_FAILED;
1320 
1321         case US_BULK_STAT_PHASE:
1322             /*
1323              * phase error -- note that a transport reset will be
1324              * invoked by the invoke_transport() function
1325              */
1326             return USB_STOR_TRANSPORT_ERROR;
1327     }
1328 
1329     /* we should never get here, but if we do, we're in trouble */
1330     return USB_STOR_TRANSPORT_ERROR;
1331 }
1332 EXPORT_SYMBOL_GPL(usb_stor_Bulk_transport);
1333 
1334 /***********************************************************************
1335  * Reset routines
1336  ***********************************************************************/
1337 
1338 /*
1339  * This is the common part of the device reset code.
1340  *
1341  * It's handy that every transport mechanism uses the control endpoint for
1342  * resets.
1343  *
1344  * Basically, we send a reset with a 5-second timeout, so we don't get
1345  * jammed attempting to do the reset.
1346  */
1347 static int usb_stor_reset_common(struct us_data *us,
1348         u8 request, u8 requesttype,
1349         u16 value, u16 index, void *data, u16 size)
1350 {
1351     int result;
1352     int result2;
1353 
1354     if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1355         usb_stor_dbg(us, "No reset during disconnect\n");
1356         return -EIO;
1357     }
1358 
1359     result = usb_stor_control_msg(us, us->send_ctrl_pipe,
1360             request, requesttype, value, index, data, size,
1361             5*HZ);
1362     if (result < 0) {
1363         usb_stor_dbg(us, "Soft reset failed: %d\n", result);
1364         return result;
1365     }
1366 
1367     /*
1368      * Give the device some time to recover from the reset,
1369      * but don't delay disconnect processing.
1370      */
1371     wait_event_interruptible_timeout(us->delay_wait,
1372             test_bit(US_FLIDX_DISCONNECTING, &us->dflags),
1373             HZ*6);
1374     if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1375         usb_stor_dbg(us, "Reset interrupted by disconnect\n");
1376         return -EIO;
1377     }
1378 
1379     usb_stor_dbg(us, "Soft reset: clearing bulk-in endpoint halt\n");
1380     result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
1381 
1382     usb_stor_dbg(us, "Soft reset: clearing bulk-out endpoint halt\n");
1383     result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
1384 
1385     /* return a result code based on the result of the clear-halts */
1386     if (result >= 0)
1387         result = result2;
1388     if (result < 0)
1389         usb_stor_dbg(us, "Soft reset failed\n");
1390     else
1391         usb_stor_dbg(us, "Soft reset done\n");
1392     return result;
1393 }
1394 
1395 /* This issues a CB[I] Reset to the device in question */
1396 #define CB_RESET_CMD_SIZE   12
1397 
1398 int usb_stor_CB_reset(struct us_data *us)
1399 {
1400     memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
1401     us->iobuf[0] = SEND_DIAGNOSTIC;
1402     us->iobuf[1] = 4;
1403     return usb_stor_reset_common(us, US_CBI_ADSC, 
1404                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1405                  0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
1406 }
1407 EXPORT_SYMBOL_GPL(usb_stor_CB_reset);
1408 
1409 /*
1410  * This issues a Bulk-only Reset to the device in question, including
1411  * clearing the subsequent endpoint halts that may occur.
1412  */
1413 int usb_stor_Bulk_reset(struct us_data *us)
1414 {
1415     return usb_stor_reset_common(us, US_BULK_RESET_REQUEST, 
1416                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1417                  0, us->ifnum, NULL, 0);
1418 }
1419 EXPORT_SYMBOL_GPL(usb_stor_Bulk_reset);
1420 
1421 /*
1422  * Issue a USB port reset to the device.  The caller must not hold
1423  * us->dev_mutex.
1424  */
1425 int usb_stor_port_reset(struct us_data *us)
1426 {
1427     int result;
1428 
1429     /*for these devices we must use the class specific method */
1430     if (us->pusb_dev->quirks & USB_QUIRK_RESET)
1431         return -EPERM;
1432 
1433     result = usb_lock_device_for_reset(us->pusb_dev, us->pusb_intf);
1434     if (result < 0)
1435         usb_stor_dbg(us, "unable to lock device for reset: %d\n",
1436                  result);
1437     else {
1438         /* Were we disconnected while waiting for the lock? */
1439         if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
1440             result = -EIO;
1441             usb_stor_dbg(us, "No reset during disconnect\n");
1442         } else {
1443             result = usb_reset_device(us->pusb_dev);
1444             usb_stor_dbg(us, "usb_reset_device returns %d\n",
1445                      result);
1446         }
1447         usb_unlock_device(us->pusb_dev);
1448     }
1449     return result;
1450 }