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