ub.c 61.6 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3 4 5 6 7 8 9 10
/*
 * The low performance USB storage driver (ub).
 *
 * Copyright (c) 1999, 2000 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
 * Copyright (C) 2004 Pete Zaitcev (zaitcev@yahoo.com)
 *
 * This work is a part of Linux kernel, is derived from it,
 * and is not licensed separately. See file COPYING for details.
 *
 * TODO (sorted by decreasing priority)
11
 *  -- Return sense now that rq allows it (we always auto-sense anyway).
Linus Torvalds's avatar
Linus Torvalds committed
12 13 14
 *  -- set readonly flag for CDs, set removable flag for CF readers
 *  -- do inquiry and verify we got a disk and not a tape (for LUN mismatch)
 *  -- verify the 13 conditions and do bulk resets
15
 *  -- highmem
Linus Torvalds's avatar
Linus Torvalds committed
16 17
 *  -- move top_sense and work_bcs into separate allocations (if they survive)
 *     for cache purists and esoteric architectures.
18
 *  -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
Linus Torvalds's avatar
Linus Torvalds committed
19 20
 *  -- prune comments, they are too volumnous
 *  -- Resove XXX's
Pete Zaitcev's avatar
Pete Zaitcev committed
21
 *  -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
Linus Torvalds's avatar
Linus Torvalds committed
22 23 24 25
 */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/usb.h>
26
#include <linux/usb_usual.h>
Linus Torvalds's avatar
Linus Torvalds committed
27 28
#include <linux/blkdev.h>
#include <linux/timer.h>
29
#include <linux/scatterlist.h>
Linus Torvalds's avatar
Linus Torvalds committed
30 31 32 33 34 35
#include <scsi/scsi.h>

#define DRV_NAME "ub"

#define UB_MAJOR 180

Pete Zaitcev's avatar
Pete Zaitcev committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
/*
 * The command state machine is the key model for understanding of this driver.
 *
 * The general rule is that all transitions are done towards the bottom
 * of the diagram, thus preventing any loops.
 *
 * An exception to that is how the STAT state is handled. A counter allows it
 * to be re-entered along the path marked with [C].
 *
 *       +--------+
 *       ! INIT   !
 *       +--------+
 *           !
 *        ub_scsi_cmd_start fails ->--------------------------------------\
 *           !                                                            !
 *           V                                                            !
 *       +--------+                                                       !
 *       ! CMD    !                                                       !
 *       +--------+                                                       !
 *           !                                            +--------+      !
 *         was -EPIPE -->-------------------------------->! CLEAR  !      !
 *           !                                            +--------+      !
 *           !                                                !           !
 *         was error -->------------------------------------- ! --------->\
 *           !                                                !           !
 *  /--<-- cmd->dir == NONE ?                                 !           !
 *  !        !                                                !           !
 *  !        V                                                !           !
 *  !    +--------+                                           !           !
 *  !    ! DATA   !                                           !           !
 *  !    +--------+                                           !           !
 *  !        !                           +---------+          !           !
 *  !      was -EPIPE -->--------------->! CLR2STS !          !           !
 *  !        !                           +---------+          !           !
 *  !        !                                !               !           !
 *  !        !                              was error -->---- ! --------->\
 *  !      was error -->--------------------- ! ------------- ! --------->\
 *  !        !                                !               !           !
 *  !        V                                !               !           !
 *  \--->+--------+                           !               !           !
 *       ! STAT   !<--------------------------/               !           !
 *  /--->+--------+                                           !           !
 *  !        !                                                !           !
 * [C]     was -EPIPE -->-----------\                         !           !
 *  !        !                      !                         !           !
 *  +<---- len == 0                 !                         !           !
 *  !        !                      !                         !           !
 *  !      was error -->--------------------------------------!---------->\
 *  !        !                      !                         !           !
 *  +<---- bad CSW                  !                         !           !
 *  +<---- bad tag                  !                         !           !
 *  !        !                      V                         !           !
 *  !        !                 +--------+                     !           !
 *  !        !                 ! CLRRS  !                     !           !
 *  !        !                 +--------+                     !           !
 *  !        !                      !                         !           !
 *  \------- ! --------------------[C]--------\               !           !
 *           !                                !               !           !
 *         cmd->error---\                +--------+           !           !
 *           !          +--------------->! SENSE  !<----------/           !
 *         STAT_FAIL----/                +--------+                       !
 *           !                                !                           V
 *           !                                V                      +--------+
 *           \--------------------------------\--------------------->! DONE   !
 *                                                                   +--------+
 */

Linus Torvalds's avatar
Linus Torvalds committed
103
/*
104 105
 * This many LUNs per USB device.
 * Every one of them takes a host, see UB_MAX_HOSTS.
Linus Torvalds's avatar
Linus Torvalds committed
106
 */
Pete Zaitcev's avatar
Pete Zaitcev committed
107
#define UB_MAX_LUNS   9
108 109 110 111

/*
 */

Pete Zaitcev's avatar
Pete Zaitcev committed
112
#define UB_PARTS_PER_LUN      8
Linus Torvalds's avatar
Linus Torvalds committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126

#define UB_MAX_CDB_SIZE      16		/* Corresponds to Bulk */

#define UB_SENSE_SIZE  18

/*
 */

/* command block wrapper */
struct bulk_cb_wrap {
	__le32	Signature;		/* contains 'USBC' */
	u32	Tag;			/* unique per command id */
	__le32	DataTransferLength;	/* size of data */
	u8	Flags;			/* direction in bit 0 */
127
	u8	Lun;			/* LUN */
Linus Torvalds's avatar
Linus Torvalds committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	u8	Length;			/* of of the CDB */
	u8	CDB[UB_MAX_CDB_SIZE];	/* max command */
};

#define US_BULK_CB_WRAP_LEN	31
#define US_BULK_CB_SIGN		0x43425355	/*spells out USBC */
#define US_BULK_FLAG_IN		1
#define US_BULK_FLAG_OUT	0

/* command status wrapper */
struct bulk_cs_wrap {
	__le32	Signature;		/* should = 'USBS' */
	u32	Tag;			/* same as original command */
	__le32	Residue;		/* amount not transferred */
	u8	Status;			/* see below */
};

#define US_BULK_CS_WRAP_LEN	13
#define US_BULK_CS_SIGN		0x53425355	/* spells out 'USBS' */
#define US_BULK_STAT_OK		0
#define US_BULK_STAT_FAIL	1
#define US_BULK_STAT_PHASE	2

/* bulk-only class specific requests */
#define US_BULK_RESET_REQUEST	0xff
#define US_BULK_GET_MAX_LUN	0xfe

/*
 */
struct ub_dev;

Pete Zaitcev's avatar
Pete Zaitcev committed
159
#define UB_MAX_REQ_SG	9	/* cdrecord requires 32KB and maybe a header */
Linus Torvalds's avatar
Linus Torvalds committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
#define UB_MAX_SECTORS 64

/*
 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
 * even if a webcam hogs the bus, but some devices need time to spin up.
 */
#define UB_URB_TIMEOUT	(HZ*2)
#define UB_DATA_TIMEOUT	(HZ*5)	/* ZIP does spin-ups in the data phase */
#define UB_STAT_TIMEOUT	(HZ*5)	/* Same spinups and eject for a dataless cmd. */
#define UB_CTRL_TIMEOUT	(HZ/2)	/* 500ms ought to be enough to clear a stall */

/*
 * An instance of a SCSI command in transit.
 */
#define UB_DIR_NONE	0
#define UB_DIR_READ	1
#define UB_DIR_ILLEGAL2	2
#define UB_DIR_WRITE	3

#define UB_DIR_CHAR(c)  (((c)==UB_DIR_WRITE)? 'w': \
			 (((c)==UB_DIR_READ)? 'r': 'n'))

enum ub_scsi_cmd_state {
	UB_CMDST_INIT,			/* Initial state */
	UB_CMDST_CMD,			/* Command submitted */
	UB_CMDST_DATA,			/* Data phase */
	UB_CMDST_CLR2STS,		/* Clearing before requesting status */
	UB_CMDST_STAT,			/* Status phase */
	UB_CMDST_CLEAR,			/* Clearing a stall (halt, actually) */
Pete Zaitcev's avatar
Pete Zaitcev committed
189
	UB_CMDST_CLRRS,			/* Clearing before retrying status */
Linus Torvalds's avatar
Linus Torvalds committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
	UB_CMDST_SENSE,			/* Sending Request Sense */
	UB_CMDST_DONE			/* Final state */
};

struct ub_scsi_cmd {
	unsigned char cdb[UB_MAX_CDB_SIZE];
	unsigned char cdb_len;

	unsigned char dir;		/* 0 - none, 1 - read, 3 - write. */
	enum ub_scsi_cmd_state state;
	unsigned int tag;
	struct ub_scsi_cmd *next;

	int error;			/* Return code - valid upon done */
	unsigned int act_len;		/* Return size */
	unsigned char key, asc, ascq;	/* May be valid if error==-EIO */

	int stat_count;			/* Retries getting status. */
Pete Zaitcev's avatar
Pete Zaitcev committed
208
	unsigned int timeo;		/* jiffies until rq->timeout changes */
Linus Torvalds's avatar
Linus Torvalds committed
209 210

	unsigned int len;		/* Requested length */
211 212 213
	unsigned int current_sg;
	unsigned int nsg;		/* sgv[nsg] */
	struct scatterlist sgv[UB_MAX_REQ_SG];
Linus Torvalds's avatar
Linus Torvalds committed
214

215
	struct ub_lun *lun;
Linus Torvalds's avatar
Linus Torvalds committed
216 217 218 219
	void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
	void *back;
};

220 221 222 223 224 225 226
struct ub_request {
	struct request *rq;
	unsigned int current_try;
	unsigned int nsg;		/* sgv[nsg] */
	struct scatterlist sgv[UB_MAX_REQ_SG];
};

Linus Torvalds's avatar
Linus Torvalds committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
/*
 */
struct ub_capacity {
	unsigned long nsec;		/* Linux size - 512 byte sectors */
	unsigned int bsize;		/* Linux hardsect_size */
	unsigned int bshift;		/* Shift between 512 and hard sects */
};

/*
 * This is a direct take-off from linux/include/completion.h
 * The difference is that I do not wait on this thing, just poll.
 * When I want to wait (ub_probe), I just use the stock completion.
 *
 * Note that INIT_COMPLETION takes no lock. It is correct. But why
 * in the bloody hell that thing takes struct instead of pointer to struct
 * is quite beyond me. I just copied it from the stock completion.
 */
struct ub_completion {
	unsigned int done;
	spinlock_t lock;
};

static inline void ub_init_completion(struct ub_completion *x)
{
	x->done = 0;
	spin_lock_init(&x->lock);
}

#define UB_INIT_COMPLETION(x)	((x).done = 0)

static void ub_complete(struct ub_completion *x)
{
	unsigned long flags;

	spin_lock_irqsave(&x->lock, flags);
	x->done++;
	spin_unlock_irqrestore(&x->lock, flags);
}

static int ub_is_completed(struct ub_completion *x)
{
	unsigned long flags;
	int ret;

	spin_lock_irqsave(&x->lock, flags);
	ret = x->done;
	spin_unlock_irqrestore(&x->lock, flags);
	return ret;
}

/*
 */
struct ub_scsi_cmd_queue {
	int qlen, qmax;
	struct ub_scsi_cmd *head, *tail;
};

/*
285 286 287 288 289 290 291 292 293 294 295 296 297 298
 * The block device instance (one per LUN).
 */
struct ub_lun {
	struct ub_dev *udev;
	struct list_head link;
	struct gendisk *disk;
	int id;				/* Host index */
	int num;			/* LUN number */
	char name[16];

	int changed;			/* Media was changed */
	int removable;
	int readonly;

299 300
	struct ub_request urq;

301 302 303 304 305 306 307 308 309 310 311 312 313 314
	/* Use Ingo's mempool if or when we have more than one command. */
	/*
	 * Currently we never need more than one command for the whole device.
	 * However, giving every LUN a command is a cheap and automatic way
	 * to enforce fairness between them.
	 */
	int cmda[1];
	struct ub_scsi_cmd cmdv[1];

	struct ub_capacity capacity; 
};

/*
 * The USB device instance.
Linus Torvalds's avatar
Linus Torvalds committed
315 316
 */
struct ub_dev {
317
	spinlock_t *lock;
Linus Torvalds's avatar
Linus Torvalds committed
318 319 320
	atomic_t poison;		/* The USB device is disconnected */
	int openc;			/* protected by ub_lock! */
					/* kref is too implicit for our taste */
321
	int reset;			/* Reset is running */
Pete Zaitcev's avatar
Pete Zaitcev committed
322
	int bad_resid;
Linus Torvalds's avatar
Linus Torvalds committed
323
	unsigned int tagcnt;
324
	char name[12];
Linus Torvalds's avatar
Linus Torvalds committed
325 326 327
	struct usb_device *dev;
	struct usb_interface *intf;

328
	struct list_head luns;
Linus Torvalds's avatar
Linus Torvalds committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

	unsigned int send_bulk_pipe;	/* cached pipe values */
	unsigned int recv_bulk_pipe;
	unsigned int send_ctrl_pipe;
	unsigned int recv_ctrl_pipe;

	struct tasklet_struct tasklet;

	struct ub_scsi_cmd_queue cmd_queue;
	struct ub_scsi_cmd top_rqs_cmd;	/* REQUEST SENSE */
	unsigned char top_sense[UB_SENSE_SIZE];

	struct ub_completion work_done;
	struct urb work_urb;
	struct timer_list work_timer;
	int last_pipe;			/* What might need clearing */
Pete Zaitcev's avatar
Pete Zaitcev committed
345
	__le32 signature;		/* Learned signature */
Linus Torvalds's avatar
Linus Torvalds committed
346 347 348 349
	struct bulk_cb_wrap work_bcb;
	struct bulk_cs_wrap work_bcs;
	struct usb_ctrlrequest work_cr;

350 351
	struct work_struct reset_work;
	wait_queue_head_t reset_wait;
Linus Torvalds's avatar
Linus Torvalds committed
352 353 354 355 356
};

/*
 */
static void ub_cleanup(struct ub_dev *sc);
357
static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
358 359 360 361
static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq);
static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq);
Linus Torvalds's avatar
Linus Torvalds committed
362
static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
Tejun Heo's avatar
Tejun Heo committed
363
static void ub_end_rq(struct request *rq, unsigned int status);
364 365
static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_request *urq, struct ub_scsi_cmd *cmd);
Linus Torvalds's avatar
Linus Torvalds committed
366
static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
367
static void ub_urb_complete(struct urb *urb);
Linus Torvalds's avatar
Linus Torvalds committed
368 369 370
static void ub_scsi_action(unsigned long _dev);
static void ub_scsi_dispatch(struct ub_dev *sc);
static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
371
static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
Linus Torvalds's avatar
Linus Torvalds committed
372
static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
Pete Zaitcev's avatar
Pete Zaitcev committed
373
static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
Linus Torvalds's avatar
Linus Torvalds committed
374
static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
Pete Zaitcev's avatar
Pete Zaitcev committed
375
static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
Linus Torvalds's avatar
Linus Torvalds committed
376 377 378 379
static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
    int stalled_pipe);
static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
Pete Zaitcev's avatar
Pete Zaitcev committed
380
static void ub_reset_enter(struct ub_dev *sc, int try);
David Howells's avatar
David Howells committed
381
static void ub_reset_task(struct work_struct *work);
382 383 384
static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_capacity *ret);
Pete Zaitcev's avatar
Pete Zaitcev committed
385 386
static int ub_sync_reset(struct ub_dev *sc);
static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
387
static int ub_probe_lun(struct ub_dev *sc, int lnum);
Linus Torvalds's avatar
Linus Torvalds committed
388 389 390

/*
 */
391 392
#ifdef CONFIG_USB_LIBUSUAL

393
#define ub_usb_ids  usb_storage_usb_ids
394 395
#else

Linus Torvalds's avatar
Linus Torvalds committed
396 397 398 399 400 401
static struct usb_device_id ub_usb_ids[] = {
	{ USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
	{ }
};

MODULE_DEVICE_TABLE(usb, ub_usb_ids);
402
#endif /* CONFIG_USB_LIBUSUAL */
Linus Torvalds's avatar
Linus Torvalds committed
403 404 405 406 407 408 409 410 411 412

/*
 * Find me a way to identify "next free minor" for add_disk(),
 * and the array disappears the next day. However, the number of
 * hosts has something to do with the naming and /proc/partitions.
 * This has to be thought out in detail before changing.
 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
 */
#define UB_MAX_HOSTS  26
static char ub_hostv[UB_MAX_HOSTS];
413

414 415 416 417
#define UB_QLOCK_NUM 5
static spinlock_t ub_qlockv[UB_QLOCK_NUM];
static int ub_qlock_next = 0;

Linus Torvalds's avatar
Linus Torvalds committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
static DEFINE_SPINLOCK(ub_lock);	/* Locks globals and ->openc */

/*
 * The id allocator.
 *
 * This also stores the host for indexing by minor, which is somewhat dirty.
 */
static int ub_id_get(void)
{
	unsigned long flags;
	int i;

	spin_lock_irqsave(&ub_lock, flags);
	for (i = 0; i < UB_MAX_HOSTS; i++) {
		if (ub_hostv[i] == 0) {
			ub_hostv[i] = 1;
			spin_unlock_irqrestore(&ub_lock, flags);
			return i;
		}
	}
	spin_unlock_irqrestore(&ub_lock, flags);
	return -1;
}

static void ub_id_put(int id)
{
	unsigned long flags;

	if (id < 0 || id >= UB_MAX_HOSTS) {
		printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
		return;
	}

	spin_lock_irqsave(&ub_lock, flags);
	if (ub_hostv[id] == 0) {
		spin_unlock_irqrestore(&ub_lock, flags);
		printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
		return;
	}
	ub_hostv[id] = 0;
	spin_unlock_irqrestore(&ub_lock, flags);
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
/*
 * This is necessitated by the fact that blk_cleanup_queue does not
 * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
 * Since our blk_init_queue() passes a spinlock common with ub_dev,
 * we have life time issues when ub_cleanup frees ub_dev.
 */
static spinlock_t *ub_next_lock(void)
{
	unsigned long flags;
	spinlock_t *ret;

	spin_lock_irqsave(&ub_lock, flags);
	ret = &ub_qlockv[ub_qlock_next];
	ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
	spin_unlock_irqrestore(&ub_lock, flags);
	return ret;
}

Linus Torvalds's avatar
Linus Torvalds committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
/*
 * Downcount for deallocation. This rides on two assumptions:
 *  - once something is poisoned, its refcount cannot grow
 *  - opens cannot happen at this time (del_gendisk was done)
 * If the above is true, we can drop the lock, which we need for
 * blk_cleanup_queue(): the silly thing may attempt to sleep.
 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
 */
static void ub_put(struct ub_dev *sc)
{
	unsigned long flags;

	spin_lock_irqsave(&ub_lock, flags);
	--sc->openc;
	if (sc->openc == 0 && atomic_read(&sc->poison)) {
		spin_unlock_irqrestore(&ub_lock, flags);
		ub_cleanup(sc);
	} else {
		spin_unlock_irqrestore(&ub_lock, flags);
	}
}

/*
 * Final cleanup and deallocation.
 */
static void ub_cleanup(struct ub_dev *sc)
{
506 507
	struct list_head *p;
	struct ub_lun *lun;
508
	struct request_queue *q;
Linus Torvalds's avatar
Linus Torvalds committed
509

510 511 512 513
	while (!list_empty(&sc->luns)) {
		p = sc->luns.next;
		lun = list_entry(p, struct ub_lun, link);
		list_del(p);
Linus Torvalds's avatar
Linus Torvalds committed
514

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		/* I don't think queue can be NULL. But... Stolen from sx8.c */
		if ((q = lun->disk->queue) != NULL)
			blk_cleanup_queue(q);
		/*
		 * If we zero disk->private_data BEFORE put_disk, we have
		 * to check for NULL all over the place in open, release,
		 * check_media and revalidate, because the block level
		 * semaphore is well inside the put_disk.
		 * But we cannot zero after the call, because *disk is gone.
		 * The sd.c is blatantly racy in this area.
		 */
		/* disk->private_data = NULL; */
		put_disk(lun->disk);
		lun->disk = NULL;

		ub_id_put(lun->id);
		kfree(lun);
	}
Linus Torvalds's avatar
Linus Torvalds committed
533

534 535 536
	usb_set_intfdata(sc->intf, NULL);
	usb_put_intf(sc->intf);
	usb_put_dev(sc->dev);
Linus Torvalds's avatar
Linus Torvalds committed
537 538 539 540 541 542
	kfree(sc);
}

/*
 * The "command allocator".
 */
543
static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
Linus Torvalds's avatar
Linus Torvalds committed
544 545 546
{
	struct ub_scsi_cmd *ret;

547
	if (lun->cmda[0])
Linus Torvalds's avatar
Linus Torvalds committed
548
		return NULL;
549 550
	ret = &lun->cmdv[0];
	lun->cmda[0] = 1;
Linus Torvalds's avatar
Linus Torvalds committed
551 552 553
	return ret;
}

554
static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
Linus Torvalds's avatar
Linus Torvalds committed
555
{
556
	if (cmd != &lun->cmdv[0]) {
Linus Torvalds's avatar
Linus Torvalds committed
557
		printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
558
		    lun->name, cmd);
Linus Torvalds's avatar
Linus Torvalds committed
559 560
		return;
	}
561 562
	if (!lun->cmda[0]) {
		printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
Linus Torvalds's avatar
Linus Torvalds committed
563 564
		return;
	}
565
	lun->cmda[0] = 0;
Linus Torvalds's avatar
Linus Torvalds committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
}

/*
 * The command queue.
 */
static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct ub_scsi_cmd_queue *t = &sc->cmd_queue;

	if (t->qlen++ == 0) {
		t->head = cmd;
		t->tail = cmd;
	} else {
		t->tail->next = cmd;
		t->tail = cmd;
	}

	if (t->qlen > t->qmax)
		t->qmax = t->qlen;
}

static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct ub_scsi_cmd_queue *t = &sc->cmd_queue;

	if (t->qlen++ == 0) {
		t->head = cmd;
		t->tail = cmd;
	} else {
		cmd->next = t->head;
		t->head = cmd;
	}

	if (t->qlen > t->qmax)
		t->qmax = t->qlen;
}

static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
{
	struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
	struct ub_scsi_cmd *cmd;

	if (t->qlen == 0)
		return NULL;
	if (--t->qlen == 0)
		t->tail = NULL;
	cmd = t->head;
	t->head = cmd->next;
	cmd->next = NULL;
	return cmd;
}

#define ub_cmdq_peek(sc)  ((sc)->cmd_queue.head)

/*
 * The request function is our main entry point
 */

624
static void ub_request_fn(struct request_queue *q)
Linus Torvalds's avatar
Linus Torvalds committed
625
{
626
	struct ub_lun *lun = q->queuedata;
Linus Torvalds's avatar
Linus Torvalds committed
627 628
	struct request *rq;

629
	while ((rq = blk_peek_request(q)) != NULL) {
630
		if (ub_request_fn_1(lun, rq) != 0) {
Linus Torvalds's avatar
Linus Torvalds committed
631 632 633 634 635 636
			blk_stop_queue(q);
			break;
		}
	}
}

637
static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
Linus Torvalds's avatar
Linus Torvalds committed
638
{
639
	struct ub_dev *sc = lun->udev;
Linus Torvalds's avatar
Linus Torvalds committed
640
	struct ub_scsi_cmd *cmd;
641 642
	struct ub_request *urq;
	int n_elem;
Linus Torvalds's avatar
Linus Torvalds committed
643

644
	if (atomic_read(&sc->poison)) {
645
		blk_start_request(rq);
Tejun Heo's avatar
Tejun Heo committed
646
		ub_end_rq(rq, DID_NO_CONNECT << 16);
647 648 649 650
		return 0;
	}

	if (lun->changed && !blk_pc_request(rq)) {
651
		blk_start_request(rq);
Tejun Heo's avatar
Tejun Heo committed
652
		ub_end_rq(rq, SAM_STAT_CHECK_CONDITION);
Linus Torvalds's avatar
Linus Torvalds committed
653 654 655
		return 0;
	}

656 657
	if (lun->urq.rq != NULL)
		return -1;
658
	if ((cmd = ub_get_cmd(lun)) == NULL)
Linus Torvalds's avatar
Linus Torvalds committed
659 660 661
		return -1;
	memset(cmd, 0, sizeof(struct ub_scsi_cmd));

662
	blk_start_request(rq);
663 664 665 666 667 668 669 670

	urq = &lun->urq;
	memset(urq, 0, sizeof(struct ub_request));
	urq->rq = rq;

	/*
	 * get scatterlist from block layer
	 */
671
	sg_init_table(&urq->sgv[0], UB_MAX_REQ_SG);
672 673
	n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
	if (n_elem < 0) {
Pete Zaitcev's avatar
Pete Zaitcev committed
674
		/* Impossible, because blk_rq_map_sg should not hit ENOMEM. */
675
		printk(KERN_INFO "%s: failed request map (%d)\n",
Pete Zaitcev's avatar
Pete Zaitcev committed
676
		    lun->name, n_elem);
677 678 679 680 681 682 683 684 685
		goto drop;
	}
	if (n_elem > UB_MAX_REQ_SG) {	/* Paranoia */
		printk(KERN_WARNING "%s: request with %d segments\n",
		    lun->name, n_elem);
		goto drop;
	}
	urq->nsg = n_elem;

Linus Torvalds's avatar
Linus Torvalds committed
686
	if (blk_pc_request(rq)) {
687
		ub_cmd_build_packet(sc, lun, cmd, urq);
Linus Torvalds's avatar
Linus Torvalds committed
688
	} else {
689
		ub_cmd_build_block(sc, lun, cmd, urq);
Linus Torvalds's avatar
Linus Torvalds committed
690 691
	}
	cmd->state = UB_CMDST_INIT;
692
	cmd->lun = lun;
Linus Torvalds's avatar
Linus Torvalds committed
693
	cmd->done = ub_rw_cmd_done;
694
	cmd->back = urq;
Linus Torvalds's avatar
Linus Torvalds committed
695 696

	cmd->tag = sc->tagcnt++;
697 698 699 700
	if (ub_submit_scsi(sc, cmd) != 0)
		goto drop;

	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
701

702 703
drop:
	ub_put_cmd(lun, cmd);
Tejun Heo's avatar
Tejun Heo committed
704
	ub_end_rq(rq, DID_ERROR << 16);
Linus Torvalds's avatar
Linus Torvalds committed
705 706 707
	return 0;
}

708 709
static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq)
Linus Torvalds's avatar
Linus Torvalds committed
710
{
711
	struct request *rq = urq->rq;
712
	unsigned int block, nblks;
Linus Torvalds's avatar
Linus Torvalds committed
713 714

	if (rq_data_dir(rq) == WRITE)
715
		cmd->dir = UB_DIR_WRITE;
Linus Torvalds's avatar
Linus Torvalds committed
716
	else
717
		cmd->dir = UB_DIR_READ;
Linus Torvalds's avatar
Linus Torvalds committed
718

719 720
	cmd->nsg = urq->nsg;
	memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
Linus Torvalds's avatar
Linus Torvalds committed
721 722 723 724

	/*
	 * build the command
	 *
725
	 * The call to blk_queue_logical_block_size() guarantees that request
Linus Torvalds's avatar
Linus Torvalds committed
726 727
	 * is aligned, but it is given in terms of 512 byte units, always.
	 */
728 729
	block = blk_rq_pos(rq) >> lun->capacity.bshift;
	nblks = blk_rq_sectors(rq) >> lun->capacity.bshift;
730

731
	cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
Linus Torvalds's avatar
Linus Torvalds committed
732 733 734 735 736 737 738 739 740
	/* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
	cmd->cdb[2] = block >> 24;
	cmd->cdb[3] = block >> 16;
	cmd->cdb[4] = block >> 8;
	cmd->cdb[5] = block;
	cmd->cdb[7] = nblks >> 8;
	cmd->cdb[8] = nblks;
	cmd->cdb_len = 10;

741
	cmd->len = blk_rq_bytes(rq);
Linus Torvalds's avatar
Linus Torvalds committed
742 743
}

744 745
static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq)
Linus Torvalds's avatar
Linus Torvalds committed
746
{
747
	struct request *rq = urq->rq;
Linus Torvalds's avatar
Linus Torvalds committed
748

Tejun Heo's avatar
Tejun Heo committed
749
	if (blk_rq_bytes(rq) == 0) {
Linus Torvalds's avatar
Linus Torvalds committed
750 751 752 753 754 755 756
		cmd->dir = UB_DIR_NONE;
	} else {
		if (rq_data_dir(rq) == WRITE)
			cmd->dir = UB_DIR_WRITE;
		else
			cmd->dir = UB_DIR_READ;
	}
757

758 759
	cmd->nsg = urq->nsg;
	memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
760 761 762 763

	memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
	cmd->cdb_len = rq->cmd_len;

Tejun Heo's avatar
Tejun Heo committed
764
	cmd->len = blk_rq_bytes(rq);
Pete Zaitcev's avatar
Pete Zaitcev committed
765 766 767 768 769 770

	/*
	 * To reapply this to every URB is not as incorrect as it looks.
	 * In return, we avoid any complicated tracking calculations.
	 */
	cmd->timeo = rq->timeout;
Linus Torvalds's avatar
Linus Torvalds committed
771 772 773 774
}

static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
775
	struct ub_lun *lun = cmd->lun;
776 777
	struct ub_request *urq = cmd->back;
	struct request *rq;
778
	unsigned int scsi_status;
Linus Torvalds's avatar
Linus Torvalds committed
779

780 781
	rq = urq->rq;

782 783
	if (cmd->error == 0) {
		if (blk_pc_request(rq)) {
784 785 786 787
			if (cmd->act_len >= rq->resid_len)
				rq->resid_len = 0;
			else
				rq->resid_len -= cmd->act_len;
788 789 790 791 792 793 794
			scsi_status = 0;
		} else {
			if (cmd->act_len != cmd->len) {
				scsi_status = SAM_STAT_CHECK_CONDITION;
			} else {
				scsi_status = 0;
			}
795
		}
796 797 798 799 800 801
	} else {
		if (blk_pc_request(rq)) {
			/* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
			memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
			rq->sense_len = UB_SENSE_SIZE;
			if (sc->top_sense[0] != 0)
802
				scsi_status = SAM_STAT_CHECK_CONDITION;
803
			else
804
				scsi_status = DID_ERROR << 16;
805
		} else {
Pete Zaitcev's avatar
Pete Zaitcev committed
806 807 808 809
			if (cmd->error == -EIO &&
			    (cmd->key == 0 ||
			     cmd->key == MEDIUM_ERROR ||
			     cmd->key == UNIT_ATTENTION)) {
810 811 812
				if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
					return;
			}
813
			scsi_status = SAM_STAT_CHECK_CONDITION;
814 815
		}
	}
816

817 818
	urq->rq = NULL;

819
	ub_put_cmd(lun, cmd);
Tejun Heo's avatar
Tejun Heo committed
820
	ub_end_rq(rq, scsi_status);
821
	blk_start_queue(lun->disk->queue);
Linus Torvalds's avatar
Linus Torvalds committed
822 823
}

Tejun Heo's avatar
Tejun Heo committed
824
static void ub_end_rq(struct request *rq, unsigned int scsi_status)
Linus Torvalds's avatar
Linus Torvalds committed
825
{
826
	int error;
827 828

	if (scsi_status == 0) {
829
		error = 0;
830
	} else {
831
		error = -EIO;
832 833
		rq->errors = scsi_status;
	}
Tejun Heo's avatar
Tejun Heo committed
834
	__blk_end_request_all(rq, error);
Linus Torvalds's avatar
Linus Torvalds committed
835 836
}

837 838 839 840 841 842 843
static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_request *urq, struct ub_scsi_cmd *cmd)
{

	if (atomic_read(&sc->poison))
		return -ENXIO;

Pete Zaitcev's avatar
Pete Zaitcev committed
844
	ub_reset_enter(sc, urq->current_try);
845 846 847 848

	if (urq->current_try >= 3)
		return -EIO;
	urq->current_try++;
Pete Zaitcev's avatar
Pete Zaitcev committed
849 850 851

	/* Remove this if anyone complains of flooding. */
	printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
	    "[sense %x %02x %02x] retry %d\n",
	    sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
	    cmd->key, cmd->asc, cmd->ascq, urq->current_try);

	memset(cmd, 0, sizeof(struct ub_scsi_cmd));
	ub_cmd_build_block(sc, lun, cmd, urq);

	cmd->state = UB_CMDST_INIT;
	cmd->lun = lun;
	cmd->done = ub_rw_cmd_done;
	cmd->back = urq;

	cmd->tag = sc->tagcnt++;

#if 0 /* Wasteful */
	return ub_submit_scsi(sc, cmd);
#else
	ub_cmdq_add(sc, cmd);
	return 0;
#endif
}

Linus Torvalds's avatar
Linus Torvalds committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
/*
 * Submit a regular SCSI operation (not an auto-sense).
 *
 * The Iron Law of Good Submit Routine is:
 * Zero return - callback is done, Nonzero return - callback is not done.
 * No exceptions.
 *
 * Host is assumed locked.
 */
static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{

	if (cmd->state != UB_CMDST_INIT ||
	    (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
		return -EINVAL;
	}

	ub_cmdq_add(sc, cmd);
	/*
	 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
	 * safer to jump to a tasklet, in case upper layers do something silly.
	 */
	tasklet_schedule(&sc->tasklet);
	return 0;
}

/*
 * Submit the first URB for the queued command.
 * This function does not deal with queueing in any way.
 */
static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct bulk_cb_wrap *bcb;
	int rc;

	bcb = &sc->work_bcb;

	/*
	 * ``If the allocation length is eighteen or greater, and a device
	 * server returns less than eithteen bytes of data, the application
	 * client should assume that the bytes not transferred would have been
	 * zeroes had the device server returned those bytes.''
	 *
	 * We zero sense for all commands so that when a packet request
	 * fails it does not return a stale sense.
	 */
	memset(&sc->top_sense, 0, UB_SENSE_SIZE);

	/* set up the command wrapper */
	bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
	bcb->Tag = cmd->tag;		/* Endianness is not important */
	bcb->DataTransferLength = cpu_to_le32(cmd->len);
	bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
927
	bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
Linus Torvalds's avatar
Linus Torvalds committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
	bcb->Length = cmd->cdb_len;

	/* copy the command payload */
	memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);

	UB_INIT_COMPLETION(sc->work_done);

	sc->last_pipe = sc->send_bulk_pipe;
	usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
	    bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);

	if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
		/* XXX Clear stalls */
		ub_complete(&sc->work_done);
		return rc;
	}

	sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
	add_timer(&sc->work_timer);

	cmd->state = UB_CMDST_CMD;
	return 0;
}

/*
 * Timeout handler.
 */
static void ub_urb_timeout(unsigned long arg)
{
	struct ub_dev *sc = (struct ub_dev *) arg;
	unsigned long flags;

960
	spin_lock_irqsave(sc->lock, flags);
961 962
	if (!ub_is_completed(&sc->work_done))
		usb_unlink_urb(&sc->work_urb);
963
	spin_unlock_irqrestore(sc->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
964 965 966 967 968 969 970 971 972
}

/*
 * Completion routine for the work URB.
 *
 * This can be called directly from usb_submit_urb (while we have
 * the sc->lock taken) and from an interrupt (while we do NOT have
 * the sc->lock taken). Therefore, bounce this off to a tasklet.
 */
973
static void ub_urb_complete(struct urb *urb)
Linus Torvalds's avatar
Linus Torvalds committed
974 975 976 977 978 979 980 981 982 983 984 985
{
	struct ub_dev *sc = urb->context;

	ub_complete(&sc->work_done);
	tasklet_schedule(&sc->tasklet);
}

static void ub_scsi_action(unsigned long _dev)
{
	struct ub_dev *sc = (struct ub_dev *) _dev;
	unsigned long flags;

986
	spin_lock_irqsave(sc->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
987
	ub_scsi_dispatch(sc);
988
	spin_unlock_irqrestore(sc->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
989 990 991 992 993 994 995
}

static void ub_scsi_dispatch(struct ub_dev *sc)
{
	struct ub_scsi_cmd *cmd;
	int rc;

996
	while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
Linus Torvalds's avatar
Linus Torvalds committed
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
		if (cmd->state == UB_CMDST_DONE) {
			ub_cmdq_pop(sc);
			(*cmd->done)(sc, cmd);
		} else if (cmd->state == UB_CMDST_INIT) {
			if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
				break;
			cmd->error = rc;
			cmd->state = UB_CMDST_DONE;
		} else {
			if (!ub_is_completed(&sc->work_done))
				break;
1008
			del_timer(&sc->work_timer);
Linus Torvalds's avatar
Linus Torvalds committed
1009 1010 1011 1012 1013 1014 1015 1016 1017
			ub_scsi_urb_compl(sc, cmd);
		}
	}
}

static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct urb *urb = &sc->work_urb;
	struct bulk_cs_wrap *bcs;
1018
	int endp;
1019
	int len;
Linus Torvalds's avatar
Linus Torvalds committed
1020 1021 1022
	int rc;

	if (atomic_read(&sc->poison)) {
1023 1024
		ub_state_done(sc, cmd, -ENODEV);
		return;
Linus Torvalds's avatar
Linus Torvalds committed
1025 1026
	}

1027 1028 1029 1030
	endp = usb_pipeendpoint(sc->last_pipe);
	if (usb_pipein(sc->last_pipe))
		endp |= USB_DIR_IN;

Linus Torvalds's avatar
Linus Torvalds committed
1031 1032 1033 1034 1035 1036
	if (cmd->state == UB_CMDST_CLEAR) {
		if (urb->status == -EPIPE) {
			/*
			 * STALL while clearning STALL.
			 * The control pipe clears itself - nothing to do.
			 */
1037 1038
			printk(KERN_NOTICE "%s: stall on control pipe\n",
			    sc->name);
Linus Torvalds's avatar
Linus Torvalds committed
1039 1040 1041 1042 1043 1044 1045
			goto Bad_End;
		}

		/*
		 * We ignore the result for the halt clear.
		 */

1046
		usb_reset_endpoint(sc->dev, endp);
Linus Torvalds's avatar
Linus Torvalds committed
1047 1048 1049 1050 1051

		ub_state_sense(sc, cmd);

	} else if (cmd->state == UB_CMDST_CLR2STS) {
		if (urb->status == -EPIPE) {
1052 1053
			printk(KERN_NOTICE "%s: stall on control pipe\n",
			    sc->name);
Linus Torvalds's avatar
Linus Torvalds committed
1054 1055 1056 1057 1058 1059 1060
			goto Bad_End;
		}

		/*
		 * We ignore the result for the halt clear.
		 */

1061
		usb_reset_endpoint(sc->dev, endp);
Linus Torvalds's avatar
Linus Torvalds committed
1062 1063 1064

		ub_state_stat(sc, cmd);

Pete Zaitcev's avatar
Pete Zaitcev committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	} else if (cmd->state == UB_CMDST_CLRRS) {
		if (urb->status == -EPIPE) {
			printk(KERN_NOTICE "%s: stall on control pipe\n",
			    sc->name);
			goto Bad_End;
		}

		/*
		 * We ignore the result for the halt clear.
		 */

1076
		usb_reset_endpoint(sc->dev, endp);
Pete Zaitcev's avatar
Pete Zaitcev committed
1077 1078 1079

		ub_state_stat_counted(sc, cmd);

Linus Torvalds's avatar
Linus Torvalds committed
1080
	} else if (cmd->state == UB_CMDST_CMD) {
1081 1082 1083 1084 1085 1086
		switch (urb->status) {
		case 0:
			break;
		case -EOVERFLOW:
			goto Bad_End;
		case -EPIPE:
Linus Torvalds's avatar
Linus Torvalds committed
1087 1088 1089
			rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
			if (rc != 0) {
				printk(KERN_NOTICE "%s: "
1090 1091
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
Linus Torvalds's avatar
Linus Torvalds committed
1092 1093 1094 1095
				/*
				 * This is typically ENOMEM or some other such shit.
				 * Retrying is pointless. Just do Bad End on it...
				 */
1096 1097
				ub_state_done(sc, cmd, rc);
				return;
Linus Torvalds's avatar
Linus Torvalds committed
1098 1099 1100
			}
			cmd->state = UB_CMDST_CLEAR;
			return;
1101 1102 1103 1104 1105
		case -ESHUTDOWN:	/* unplug */
		case -EILSEQ:		/* unplug timeout on uhci */
			ub_state_done(sc, cmd, -ENODEV);
			return;
		default:
Linus Torvalds's avatar
Linus Torvalds committed
1106 1107 1108 1109 1110 1111
			goto Bad_End;
		}
		if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
			goto Bad_End;
		}

1112
		if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
Linus Torvalds's avatar
Linus Torvalds committed
1113 1114 1115 1116
			ub_state_stat(sc, cmd);
			return;
		}

1117 1118
		// udelay(125);		// usb-storage has this
		ub_data_start(sc, cmd);
Linus Torvalds's avatar
Linus Torvalds committed
1119 1120 1121 1122 1123 1124

	} else if (cmd->state == UB_CMDST_DATA) {
		if (urb->status == -EPIPE) {
			rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
			if (rc != 0) {
				printk(KERN_NOTICE "%s: "
1125 1126
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
1127 1128
				ub_state_done(sc, cmd, rc);
				return;
Linus Torvalds's avatar
Linus Torvalds committed
1129 1130 1131 1132 1133 1134 1135 1136 1137
			}
			cmd->state = UB_CMDST_CLR2STS;
			return;
		}
		if (urb->status == -EOVERFLOW) {
			/*
			 * A babble? Failure, but we must transfer CSW now.
			 */
			cmd->error = -EOVERFLOW;	/* A cheap trick... */
1138 1139
			ub_state_stat(sc, cmd);
			return;
Linus Torvalds's avatar
Linus Torvalds committed
1140
		}
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

		if (cmd->dir == UB_DIR_WRITE) {
			/*
			 * Do not continue writes in case of a failure.
			 * Doing so would cause sectors to be mixed up,
			 * which is worse than sectors lost.
			 *
			 * We must try to read the CSW, or many devices
			 * get confused.
			 */
			len = urb->actual_length;
			if (urb->status != 0 ||
			    len != cmd->sgv[cmd->current_sg].length) {
				cmd->act_len += len;

				cmd->error = -EIO;
				ub_state_stat(sc, cmd);
				return;
			}

		} else {
			/*
			 * If an error occurs on read, we record it, and
			 * continue to fetch data in order to avoid bubble.
			 *
			 * As a small shortcut, we stop if we detect that
			 * a CSW mixed into data.
			 */
			if (urb->status != 0)
				cmd->error = -EIO;

			len = urb->actual_length;
			if (urb->status != 0 ||
			    len != cmd->sgv[cmd->current_sg].length) {
				if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
					goto Bad_End;
			}
		}
Linus Torvalds's avatar
Linus Torvalds committed
1179

1180
		cmd->act_len += urb->actual_length;
Linus Torvalds's avatar
Linus Torvalds committed
1181

1182 1183 1184 1185
		if (++cmd->current_sg < cmd->nsg) {
			ub_data_start(sc, cmd);
			return;
		}
Linus Torvalds's avatar
Linus Torvalds committed
1186 1187 1188 1189 1190 1191 1192
		ub_state_stat(sc, cmd);

	} else if (cmd->state == UB_CMDST_STAT) {
		if (urb->status == -EPIPE) {
			rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
			if (rc != 0) {
				printk(KERN_NOTICE "%s: "
1193 1194
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
1195 1196
				ub_state_done(sc, cmd, rc);
				return;
Linus Torvalds's avatar
Linus Torvalds committed
1197
			}
Pete Zaitcev's avatar
Pete Zaitcev committed
1198 1199 1200 1201 1202 1203 1204 1205

			/*
			 * Having a stall when getting CSW is an error, so
			 * make sure uppper levels are not oblivious to it.
			 */
			cmd->error = -EIO;		/* A cheap trick... */

			cmd->state = UB_CMDST_CLRRS;
Linus Torvalds's avatar
Linus Torvalds committed
1206 1207
			return;
		}
1208 1209

		/* Catch everything, including -EOVERFLOW and other nasties. */
Linus Torvalds's avatar
Linus Torvalds committed
1210 1211 1212 1213
		if (urb->status != 0)
			goto Bad_End;

		if (urb->actual_length == 0) {
Pete Zaitcev's avatar
Pete Zaitcev committed
1214
			ub_state_stat_counted(sc, cmd);
Linus Torvalds's avatar
Linus Torvalds committed
1215 1216 1217 1218 1219
			return;
		}

		/*
		 * Check the returned Bulk protocol status.
Pete Zaitcev's avatar
Pete Zaitcev committed
1220
		 * The status block has to be validated first.
Linus Torvalds's avatar
Linus Torvalds committed
1221 1222 1223
		 */

		bcs = &sc->work_bcs;
Pete Zaitcev's avatar
Pete Zaitcev committed
1224 1225

		if (sc->signature == cpu_to_le32(0)) {
Linus Torvalds's avatar
Linus Torvalds committed
1226
			/*
Pete Zaitcev's avatar
Pete Zaitcev committed
1227 1228 1229
			 * This is the first reply, so do not perform the check.
			 * Instead, remember the signature the device uses
			 * for future checks. But do not allow a nul.
Linus Torvalds's avatar
Linus Torvalds committed
1230
			 */
Pete Zaitcev's avatar
Pete Zaitcev committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
			sc->signature = bcs->Signature;
			if (sc->signature == cpu_to_le32(0)) {
				ub_state_stat_counted(sc, cmd);
				return;
			}
		} else {
			if (bcs->Signature != sc->signature) {
				ub_state_stat_counted(sc, cmd);
				return;
			}
Linus Torvalds's avatar
Linus Torvalds committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
		}

		if (bcs->Tag != cmd->tag) {
			/*
			 * This usually happens when we disagree with the
			 * device's microcode about something. For instance,
			 * a few of them throw this after timeouts. They buffer
			 * commands and reply at commands we timed out before.
			 * Without flushing these replies we loop forever.
			 */
Pete Zaitcev's avatar
Pete Zaitcev committed
1251
			ub_state_stat_counted(sc, cmd);
Linus Torvalds's avatar
Linus Torvalds committed
1252 1253 1254
			return;
		}

Pete Zaitcev's avatar
Pete Zaitcev committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
		if (!sc->bad_resid) {
			len = le32_to_cpu(bcs->Residue);
			if (len != cmd->len - cmd->act_len) {
				/*
				 * Only start ignoring if this cmd ended well.
				 */
				if (cmd->len == cmd->act_len) {
					printk(KERN_NOTICE "%s: "
					    "bad residual %d of %d, ignoring\n",
					    sc->name, len, cmd->len);
					sc->bad_resid = 1;
				}
			}
Pete Zaitcev's avatar
Pete Zaitcev committed
1268 1269
		}

Linus Torvalds's avatar
Linus Torvalds committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
		switch (bcs->Status) {
		case US_BULK_STAT_OK:
			break;
		case US_BULK_STAT_FAIL:
			ub_state_sense(sc, cmd);
			return;
		case US_BULK_STAT_PHASE:
			goto Bad_End;
		default:
			printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
			    sc->name, bcs->Status);
1281 1282
			ub_state_done(sc, cmd, -EINVAL);
			return;
Linus Torvalds's avatar
Linus Torvalds committed
1283 1284 1285
		}

		/* Not zeroing error to preserve a babble indicator */
Pete Zaitcev's avatar
Pete Zaitcev committed
1286 1287 1288 1289
		if (cmd->error != 0) {
			ub_state_sense(sc, cmd);
			return;
		}
Linus Torvalds's avatar
Linus Torvalds committed
1290 1291 1292 1293 1294 1295 1296 1297
		cmd->state = UB_CMDST_DONE;
		ub_cmdq_pop(sc);
		(*cmd->done)(sc, cmd);

	} else if (cmd->state == UB_CMDST_SENSE) {
		ub_state_done(sc, cmd, -EIO);

	} else {