ub.c 61.2 KB
Newer Older
L
Linus Torvalds 已提交
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).
L
Linus Torvalds 已提交
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
L
Linus Torvalds 已提交
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. ?
L
Linus Torvalds 已提交
19 20
 *  -- prune comments, they are too volumnous
 *  -- Resove XXX's
P
Pete Zaitcev 已提交
21
 *  -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
L
Linus Torvalds 已提交
22 23 24 25
 */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/usb.h>
26
#include <linux/usb_usual.h>
L
Linus Torvalds 已提交
27 28
#include <linux/blkdev.h>
#include <linux/timer.h>
J
Jens Axboe 已提交
29
#include <linux/scatterlist.h>
30
#include <linux/slab.h>
31
#include <linux/mutex.h>
L
Linus Torvalds 已提交
32 33 34 35 36 37
#include <scsi/scsi.h>

#define DRV_NAME "ub"

#define UB_MAJOR 180

P
Pete Zaitcev 已提交
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 103 104
/*
 * 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   !
 *                                                                   +--------+
 */

L
Linus Torvalds 已提交
105
/*
106 107
 * This many LUNs per USB device.
 * Every one of them takes a host, see UB_MAX_HOSTS.
L
Linus Torvalds 已提交
108
 */
P
Pete Zaitcev 已提交
109
#define UB_MAX_LUNS   9
110 111 112 113

/*
 */

P
Pete Zaitcev 已提交
114
#define UB_PARTS_PER_LUN      8
L
Linus Torvalds 已提交
115 116 117 118 119 120 121 122 123

#define UB_MAX_CDB_SIZE      16		/* Corresponds to Bulk */

#define UB_SENSE_SIZE  18

/*
 */
struct ub_dev;

P
Pete Zaitcev 已提交
124
#define UB_MAX_REQ_SG	9	/* cdrecord requires 32KB and maybe a header */
L
Linus Torvalds 已提交
125 126 127 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
#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) */
P
Pete Zaitcev 已提交
154
	UB_CMDST_CLRRS,			/* Clearing before retrying status */
L
Linus Torvalds 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
	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. */
P
Pete Zaitcev 已提交
173
	unsigned int timeo;		/* jiffies until rq->timeout changes */
L
Linus Torvalds 已提交
174 175

	unsigned int len;		/* Requested length */
176 177 178
	unsigned int current_sg;
	unsigned int nsg;		/* sgv[nsg] */
	struct scatterlist sgv[UB_MAX_REQ_SG];
L
Linus Torvalds 已提交
179

180
	struct ub_lun *lun;
L
Linus Torvalds 已提交
181 182 183 184
	void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
	void *back;
};

185 186 187 188 189 190 191
struct ub_request {
	struct request *rq;
	unsigned int current_try;
	unsigned int nsg;		/* sgv[nsg] */
	struct scatterlist sgv[UB_MAX_REQ_SG];
};

L
Linus Torvalds 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
/*
 */
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;
};

214
static DEFINE_MUTEX(ub_mutex);
L
Linus Torvalds 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
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;
};

/*
251 252 253 254 255 256 257 258 259 260 261 262 263 264
 * 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;

265 266
	struct ub_request urq;

267 268 269 270 271 272 273 274 275 276 277 278 279 280
	/* 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.
L
Linus Torvalds 已提交
281 282
 */
struct ub_dev {
P
Pete Zaitcev 已提交
283
	spinlock_t *lock;
L
Linus Torvalds 已提交
284 285 286
	atomic_t poison;		/* The USB device is disconnected */
	int openc;			/* protected by ub_lock! */
					/* kref is too implicit for our taste */
287
	int reset;			/* Reset is running */
P
Pete Zaitcev 已提交
288
	int bad_resid;
L
Linus Torvalds 已提交
289
	unsigned int tagcnt;
290
	char name[12];
L
Linus Torvalds 已提交
291 292 293
	struct usb_device *dev;
	struct usb_interface *intf;

294
	struct list_head luns;
L
Linus Torvalds 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

	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 */
P
Pete Zaitcev 已提交
311
	__le32 signature;		/* Learned signature */
L
Linus Torvalds 已提交
312 313 314 315
	struct bulk_cb_wrap work_bcb;
	struct bulk_cs_wrap work_bcs;
	struct usb_ctrlrequest work_cr;

316 317
	struct work_struct reset_work;
	wait_queue_head_t reset_wait;
L
Linus Torvalds 已提交
318 319 320 321 322
};

/*
 */
static void ub_cleanup(struct ub_dev *sc);
323
static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
324 325 326 327
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);
L
Linus Torvalds 已提交
328
static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
T
Tejun Heo 已提交
329
static void ub_end_rq(struct request *rq, unsigned int status);
330 331
static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_request *urq, struct ub_scsi_cmd *cmd);
L
Linus Torvalds 已提交
332
static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
333
static void ub_urb_complete(struct urb *urb);
L
Linus Torvalds 已提交
334 335 336
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);
337
static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
L
Linus Torvalds 已提交
338
static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
P
Pete Zaitcev 已提交
339
static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
L
Linus Torvalds 已提交
340
static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
P
Pete Zaitcev 已提交
341
static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
L
Linus Torvalds 已提交
342 343 344 345
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);
P
Pete Zaitcev 已提交
346
static void ub_reset_enter(struct ub_dev *sc, int try);
D
David Howells 已提交
347
static void ub_reset_task(struct work_struct *work);
348 349 350
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);
P
Pete Zaitcev 已提交
351 352
static int ub_sync_reset(struct ub_dev *sc);
static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
353
static int ub_probe_lun(struct ub_dev *sc, int lnum);
L
Linus Torvalds 已提交
354 355 356

/*
 */
357 358
#ifdef CONFIG_USB_LIBUSUAL

359
#define ub_usb_ids  usb_storage_usb_ids
360 361
#else

362
static const struct usb_device_id ub_usb_ids[] = {
363
	{ USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, USB_SC_SCSI, USB_PR_BULK) },
L
Linus Torvalds 已提交
364 365 366 367
	{ }
};

MODULE_DEVICE_TABLE(usb, ub_usb_ids);
368
#endif /* CONFIG_USB_LIBUSUAL */
L
Linus Torvalds 已提交
369 370 371 372 373 374 375 376 377 378

/*
 * 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];
379

P
Pete Zaitcev 已提交
380 381 382 383
#define UB_QLOCK_NUM 5
static spinlock_t ub_qlockv[UB_QLOCK_NUM];
static int ub_qlock_next = 0;

L
Linus Torvalds 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
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);
}

P
Pete Zaitcev 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/*
 * 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;
}

L
Linus Torvalds 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
/*
 * 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)
{
472 473
	struct list_head *p;
	struct ub_lun *lun;
474
	struct request_queue *q;
L
Linus Torvalds 已提交
475

476 477 478 479
	while (!list_empty(&sc->luns)) {
		p = sc->luns.next;
		lun = list_entry(p, struct ub_lun, link);
		list_del(p);
L
Linus Torvalds 已提交
480

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
		/* 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);
	}
L
Linus Torvalds 已提交
499

500 501 502
	usb_set_intfdata(sc->intf, NULL);
	usb_put_intf(sc->intf);
	usb_put_dev(sc->dev);
L
Linus Torvalds 已提交
503 504 505 506 507 508
	kfree(sc);
}

/*
 * The "command allocator".
 */
509
static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
L
Linus Torvalds 已提交
510 511 512
{
	struct ub_scsi_cmd *ret;

513
	if (lun->cmda[0])
L
Linus Torvalds 已提交
514
		return NULL;
515 516
	ret = &lun->cmdv[0];
	lun->cmda[0] = 1;
L
Linus Torvalds 已提交
517 518 519
	return ret;
}

520
static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
L
Linus Torvalds 已提交
521
{
522
	if (cmd != &lun->cmdv[0]) {
L
Linus Torvalds 已提交
523
		printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
524
		    lun->name, cmd);
L
Linus Torvalds 已提交
525 526
		return;
	}
527 528
	if (!lun->cmda[0]) {
		printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
L
Linus Torvalds 已提交
529 530
		return;
	}
531
	lun->cmda[0] = 0;
L
Linus Torvalds 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
}

/*
 * 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
 */

590
static void ub_request_fn(struct request_queue *q)
L
Linus Torvalds 已提交
591
{
592
	struct ub_lun *lun = q->queuedata;
L
Linus Torvalds 已提交
593 594
	struct request *rq;

595
	while ((rq = blk_peek_request(q)) != NULL) {
596
		if (ub_request_fn_1(lun, rq) != 0) {
L
Linus Torvalds 已提交
597 598 599 600 601 602
			blk_stop_queue(q);
			break;
		}
	}
}

603
static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
L
Linus Torvalds 已提交
604
{
605
	struct ub_dev *sc = lun->udev;
L
Linus Torvalds 已提交
606
	struct ub_scsi_cmd *cmd;
607 608
	struct ub_request *urq;
	int n_elem;
L
Linus Torvalds 已提交
609

610
	if (atomic_read(&sc->poison)) {
611
		blk_start_request(rq);
T
Tejun Heo 已提交
612
		ub_end_rq(rq, DID_NO_CONNECT << 16);
613 614 615
		return 0;
	}

616
	if (lun->changed && rq->cmd_type != REQ_TYPE_BLOCK_PC) {
617
		blk_start_request(rq);
T
Tejun Heo 已提交
618
		ub_end_rq(rq, SAM_STAT_CHECK_CONDITION);
L
Linus Torvalds 已提交
619 620 621
		return 0;
	}

622 623
	if (lun->urq.rq != NULL)
		return -1;
624
	if ((cmd = ub_get_cmd(lun)) == NULL)
L
Linus Torvalds 已提交
625 626 627
		return -1;
	memset(cmd, 0, sizeof(struct ub_scsi_cmd));

628
	blk_start_request(rq);
629 630 631 632 633 634 635 636

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

	/*
	 * get scatterlist from block layer
	 */
637
	sg_init_table(&urq->sgv[0], UB_MAX_REQ_SG);
638 639
	n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
	if (n_elem < 0) {
P
Pete Zaitcev 已提交
640
		/* Impossible, because blk_rq_map_sg should not hit ENOMEM. */
641
		printk(KERN_INFO "%s: failed request map (%d)\n",
P
Pete Zaitcev 已提交
642
		    lun->name, n_elem);
643 644 645 646 647 648 649 650 651
		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;

652
	if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
653
		ub_cmd_build_packet(sc, lun, cmd, urq);
L
Linus Torvalds 已提交
654
	} else {
655
		ub_cmd_build_block(sc, lun, cmd, urq);
L
Linus Torvalds 已提交
656 657
	}
	cmd->state = UB_CMDST_INIT;
658
	cmd->lun = lun;
L
Linus Torvalds 已提交
659
	cmd->done = ub_rw_cmd_done;
660
	cmd->back = urq;
L
Linus Torvalds 已提交
661 662

	cmd->tag = sc->tagcnt++;
663 664 665 666
	if (ub_submit_scsi(sc, cmd) != 0)
		goto drop;

	return 0;
L
Linus Torvalds 已提交
667

668 669
drop:
	ub_put_cmd(lun, cmd);
T
Tejun Heo 已提交
670
	ub_end_rq(rq, DID_ERROR << 16);
L
Linus Torvalds 已提交
671 672 673
	return 0;
}

674 675
static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq)
L
Linus Torvalds 已提交
676
{
677
	struct request *rq = urq->rq;
678
	unsigned int block, nblks;
L
Linus Torvalds 已提交
679 680

	if (rq_data_dir(rq) == WRITE)
681
		cmd->dir = UB_DIR_WRITE;
L
Linus Torvalds 已提交
682
	else
683
		cmd->dir = UB_DIR_READ;
L
Linus Torvalds 已提交
684

685 686
	cmd->nsg = urq->nsg;
	memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
L
Linus Torvalds 已提交
687 688 689 690

	/*
	 * build the command
	 *
691
	 * The call to blk_queue_logical_block_size() guarantees that request
L
Linus Torvalds 已提交
692 693
	 * is aligned, but it is given in terms of 512 byte units, always.
	 */
694 695
	block = blk_rq_pos(rq) >> lun->capacity.bshift;
	nblks = blk_rq_sectors(rq) >> lun->capacity.bshift;
696

697
	cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
L
Linus Torvalds 已提交
698 699 700 701 702 703 704 705 706
	/* 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;

707
	cmd->len = blk_rq_bytes(rq);
L
Linus Torvalds 已提交
708 709
}

710 711
static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_scsi_cmd *cmd, struct ub_request *urq)
L
Linus Torvalds 已提交
712
{
713
	struct request *rq = urq->rq;
L
Linus Torvalds 已提交
714

T
Tejun Heo 已提交
715
	if (blk_rq_bytes(rq) == 0) {
L
Linus Torvalds 已提交
716 717 718 719 720 721 722
		cmd->dir = UB_DIR_NONE;
	} else {
		if (rq_data_dir(rq) == WRITE)
			cmd->dir = UB_DIR_WRITE;
		else
			cmd->dir = UB_DIR_READ;
	}
723

724 725
	cmd->nsg = urq->nsg;
	memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
726 727 728 729

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

T
Tejun Heo 已提交
730
	cmd->len = blk_rq_bytes(rq);
P
Pete Zaitcev 已提交
731 732 733 734 735 736

	/*
	 * 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;
L
Linus Torvalds 已提交
737 738 739 740
}

static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
741
	struct ub_lun *lun = cmd->lun;
742 743
	struct ub_request *urq = cmd->back;
	struct request *rq;
744
	unsigned int scsi_status;
L
Linus Torvalds 已提交
745

746 747
	rq = urq->rq;

748
	if (cmd->error == 0) {
749
		if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
750 751 752 753
			if (cmd->act_len >= rq->resid_len)
				rq->resid_len = 0;
			else
				rq->resid_len -= cmd->act_len;
754 755 756 757 758 759 760
			scsi_status = 0;
		} else {
			if (cmd->act_len != cmd->len) {
				scsi_status = SAM_STAT_CHECK_CONDITION;
			} else {
				scsi_status = 0;
			}
761
		}
762
	} else {
763
		if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
764 765 766 767
			/* 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)
768
				scsi_status = SAM_STAT_CHECK_CONDITION;
769
			else
770
				scsi_status = DID_ERROR << 16;
771
		} else {
P
Pete Zaitcev 已提交
772 773 774 775
			if (cmd->error == -EIO &&
			    (cmd->key == 0 ||
			     cmd->key == MEDIUM_ERROR ||
			     cmd->key == UNIT_ATTENTION)) {
776 777 778
				if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
					return;
			}
779
			scsi_status = SAM_STAT_CHECK_CONDITION;
780 781
		}
	}
782

783 784
	urq->rq = NULL;

785
	ub_put_cmd(lun, cmd);
T
Tejun Heo 已提交
786
	ub_end_rq(rq, scsi_status);
787
	blk_start_queue(lun->disk->queue);
L
Linus Torvalds 已提交
788 789
}

T
Tejun Heo 已提交
790
static void ub_end_rq(struct request *rq, unsigned int scsi_status)
L
Linus Torvalds 已提交
791
{
792
	int error;
793 794

	if (scsi_status == 0) {
795
		error = 0;
796
	} else {
797
		error = -EIO;
798 799
		rq->errors = scsi_status;
	}
T
Tejun Heo 已提交
800
	__blk_end_request_all(rq, error);
L
Linus Torvalds 已提交
801 802
}

803 804 805 806 807 808 809
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;

P
Pete Zaitcev 已提交
810
	ub_reset_enter(sc, urq->current_try);
811 812 813 814

	if (urq->current_try >= 3)
		return -EIO;
	urq->current_try++;
P
Pete Zaitcev 已提交
815 816 817

	/* Remove this if anyone complains of flooding. */
	printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
	    "[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
}

L
Linus Torvalds 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
/*
 * 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;
893
	bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
L
Linus Torvalds 已提交
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
	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;

P
Pete Zaitcev 已提交
926
	spin_lock_irqsave(sc->lock, flags);
927 928
	if (!ub_is_completed(&sc->work_done))
		usb_unlink_urb(&sc->work_urb);
P
Pete Zaitcev 已提交
929
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
930 931 932 933 934 935 936 937 938
}

/*
 * 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.
 */
939
static void ub_urb_complete(struct urb *urb)
L
Linus Torvalds 已提交
940 941 942 943 944 945 946 947 948 949 950 951
{
	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;

P
Pete Zaitcev 已提交
952
	spin_lock_irqsave(sc->lock, flags);
L
Linus Torvalds 已提交
953
	ub_scsi_dispatch(sc);
P
Pete Zaitcev 已提交
954
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
955 956 957 958 959 960 961
}

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

962
	while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
L
Linus Torvalds 已提交
963 964 965 966 967 968 969 970 971 972 973
		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;
974
			del_timer(&sc->work_timer);
L
Linus Torvalds 已提交
975 976 977 978 979 980 981 982 983
			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;
984
	int endp;
985
	int len;
L
Linus Torvalds 已提交
986 987 988
	int rc;

	if (atomic_read(&sc->poison)) {
989 990
		ub_state_done(sc, cmd, -ENODEV);
		return;
L
Linus Torvalds 已提交
991 992
	}

993 994 995 996
	endp = usb_pipeendpoint(sc->last_pipe);
	if (usb_pipein(sc->last_pipe))
		endp |= USB_DIR_IN;

L
Linus Torvalds 已提交
997 998 999 1000 1001 1002
	if (cmd->state == UB_CMDST_CLEAR) {
		if (urb->status == -EPIPE) {
			/*
			 * STALL while clearning STALL.
			 * The control pipe clears itself - nothing to do.
			 */
1003 1004
			printk(KERN_NOTICE "%s: stall on control pipe\n",
			    sc->name);
L
Linus Torvalds 已提交
1005 1006 1007 1008 1009 1010 1011
			goto Bad_End;
		}

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

1012
		usb_reset_endpoint(sc->dev, endp);
L
Linus Torvalds 已提交
1013 1014 1015 1016 1017

		ub_state_sense(sc, cmd);

	} else if (cmd->state == UB_CMDST_CLR2STS) {
		if (urb->status == -EPIPE) {
1018 1019
			printk(KERN_NOTICE "%s: stall on control pipe\n",
			    sc->name);
L
Linus Torvalds 已提交
1020 1021 1022 1023 1024 1025 1026
			goto Bad_End;
		}

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

1027
		usb_reset_endpoint(sc->dev, endp);
L
Linus Torvalds 已提交
1028 1029 1030

		ub_state_stat(sc, cmd);

P
Pete Zaitcev 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	} 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.
		 */

1042
		usb_reset_endpoint(sc->dev, endp);
P
Pete Zaitcev 已提交
1043 1044 1045

		ub_state_stat_counted(sc, cmd);

L
Linus Torvalds 已提交
1046
	} else if (cmd->state == UB_CMDST_CMD) {
1047 1048 1049 1050 1051 1052
		switch (urb->status) {
		case 0:
			break;
		case -EOVERFLOW:
			goto Bad_End;
		case -EPIPE:
L
Linus Torvalds 已提交
1053 1054 1055
			rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
			if (rc != 0) {
				printk(KERN_NOTICE "%s: "
1056 1057
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
L
Linus Torvalds 已提交
1058 1059 1060 1061
				/*
				 * This is typically ENOMEM or some other such shit.
				 * Retrying is pointless. Just do Bad End on it...
				 */
1062 1063
				ub_state_done(sc, cmd, rc);
				return;
L
Linus Torvalds 已提交
1064 1065 1066
			}
			cmd->state = UB_CMDST_CLEAR;
			return;
1067 1068 1069 1070 1071
		case -ESHUTDOWN:	/* unplug */
		case -EILSEQ:		/* unplug timeout on uhci */
			ub_state_done(sc, cmd, -ENODEV);
			return;
		default:
L
Linus Torvalds 已提交
1072 1073 1074 1075 1076 1077
			goto Bad_End;
		}
		if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
			goto Bad_End;
		}

1078
		if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
L
Linus Torvalds 已提交
1079 1080 1081 1082
			ub_state_stat(sc, cmd);
			return;
		}

1083 1084
		// udelay(125);		// usb-storage has this
		ub_data_start(sc, cmd);
L
Linus Torvalds 已提交
1085 1086 1087 1088 1089 1090

	} 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: "
1091 1092
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
1093 1094
				ub_state_done(sc, cmd, rc);
				return;
L
Linus Torvalds 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103
			}
			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... */
1104 1105
			ub_state_stat(sc, cmd);
			return;
L
Linus Torvalds 已提交
1106
		}
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

		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;
			}
		}
L
Linus Torvalds 已提交
1145

1146
		cmd->act_len += urb->actual_length;
L
Linus Torvalds 已提交
1147

1148 1149 1150 1151
		if (++cmd->current_sg < cmd->nsg) {
			ub_data_start(sc, cmd);
			return;
		}
L
Linus Torvalds 已提交
1152 1153 1154 1155 1156 1157 1158
		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: "
1159 1160
				    "unable to submit clear (%d)\n",
				    sc->name, rc);
1161 1162
				ub_state_done(sc, cmd, rc);
				return;
L
Linus Torvalds 已提交
1163
			}
P
Pete Zaitcev 已提交
1164 1165 1166 1167 1168 1169 1170 1171

			/*
			 * 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;
L
Linus Torvalds 已提交
1172 1173
			return;
		}
1174 1175

		/* Catch everything, including -EOVERFLOW and other nasties. */
L
Linus Torvalds 已提交
1176 1177 1178 1179
		if (urb->status != 0)
			goto Bad_End;

		if (urb->actual_length == 0) {
P
Pete Zaitcev 已提交
1180
			ub_state_stat_counted(sc, cmd);
L
Linus Torvalds 已提交
1181 1182 1183 1184 1185
			return;
		}

		/*
		 * Check the returned Bulk protocol status.
P
Pete Zaitcev 已提交
1186
		 * The status block has to be validated first.
L
Linus Torvalds 已提交
1187 1188 1189
		 */

		bcs = &sc->work_bcs;
P
Pete Zaitcev 已提交
1190 1191

		if (sc->signature == cpu_to_le32(0)) {
L
Linus Torvalds 已提交
1192
			/*
P
Pete Zaitcev 已提交
1193 1194 1195
			 * 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.
L
Linus Torvalds 已提交
1196
			 */
P
Pete Zaitcev 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
			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;
			}
L
Linus Torvalds 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		}

		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.
			 */
P
Pete Zaitcev 已提交
1217
			ub_state_stat_counted(sc, cmd);
L
Linus Torvalds 已提交
1218 1219 1220
			return;
		}

P
Pete Zaitcev 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
		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;
				}
			}
P
Pete Zaitcev 已提交
1234 1235
		}

L
Linus Torvalds 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
		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);
1247 1248
			ub_state_done(sc, cmd, -EINVAL);
			return;
L
Linus Torvalds 已提交
1249 1250 1251
		}

		/* Not zeroing error to preserve a babble indicator */
P
Pete Zaitcev 已提交
1252 1253 1254 1255
		if (cmd->error != 0) {
			ub_state_sense(sc, cmd);
			return;
		}
L
Linus Torvalds 已提交
1256 1257 1258 1259 1260 1261 1262 1263
		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 {
P
Pete Zaitcev 已提交
1264
		printk(KERN_WARNING "%s: wrong command state %d\n",
1265
		    sc->name, cmd->state);
1266 1267
		ub_state_done(sc, cmd, -EINVAL);
		return;
L
Linus Torvalds 已提交
1268 1269 1270 1271 1272 1273 1274
	}
	return;

Bad_End: /* Little Excel is dead */
	ub_state_done(sc, cmd, -EIO);
}

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
/*
 * Factorization helper for the command state machine:
 * Initiate a data segment transfer.
 */
static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
	int pipe;
	int rc;

	UB_INIT_COMPLETION(sc->work_done);

	if (cmd->dir == UB_DIR_READ)
		pipe = sc->recv_bulk_pipe;
	else
		pipe = sc->send_bulk_pipe;
	sc->last_pipe = pipe;
J
Jens Axboe 已提交
1292 1293
	usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe, sg_virt(sg),
	    sg->length, ub_urb_complete, sc);
1294 1295 1296 1297 1298 1299 1300 1301

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

P
Pete Zaitcev 已提交
1302 1303 1304 1305
	if (cmd->timeo)
		sc->work_timer.expires = jiffies + cmd->timeo;
	else
		sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1306 1307 1308 1309 1310
	add_timer(&sc->work_timer);

	cmd->state = UB_CMDST_DATA;
}

L
Linus Torvalds 已提交
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
/*
 * Factorization helper for the command state machine:
 * Finish the command.
 */
static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
{

	cmd->error = rc;
	cmd->state = UB_CMDST_DONE;
	ub_cmdq_pop(sc);
	(*cmd->done)(sc, cmd);
}

/*
 * Factorization helper for the command state machine:
 * Submit a CSW read.
 */
P
Pete Zaitcev 已提交
1328
static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
L
Linus Torvalds 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
{
	int rc;

	UB_INIT_COMPLETION(sc->work_done);

	sc->last_pipe = sc->recv_bulk_pipe;
	usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
	    &sc->work_bcs, US_BULK_CS_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);
		ub_state_done(sc, cmd, rc);
P
Pete Zaitcev 已提交
1342
		return -1;
L
Linus Torvalds 已提交
1343 1344
	}

P
Pete Zaitcev 已提交
1345 1346 1347 1348
	if (cmd->timeo)
		sc->work_timer.expires = jiffies + cmd->timeo;
	else
		sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
L
Linus Torvalds 已提交
1349
	add_timer(&sc->work_timer);
P
Pete Zaitcev 已提交
1350
	return 0;
L
Linus Torvalds 已提交
1351 1352 1353 1354 1355 1356 1357 1358
}

/*
 * Factorization helper for the command state machine:
 * Submit a CSW read and go to STAT state.
 */
static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
P
Pete Zaitcev 已提交
1359 1360 1361

	if (__ub_state_stat(sc, cmd) != 0)
		return;
L
Linus Torvalds 已提交
1362 1363 1364

	cmd->stat_count = 0;
	cmd->state = UB_CMDST_STAT;
P
Pete Zaitcev 已提交
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
}

/*
 * Factorization helper for the command state machine:
 * Submit a CSW read and go to STAT state with counter (along [C] path).
 */
static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{

	if (++cmd->stat_count >= 4) {
		ub_state_sense(sc, cmd);
		return;
	}

	if (__ub_state_stat(sc, cmd) != 0)
		return;

	cmd->state = UB_CMDST_STAT;
L
Linus Torvalds 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391
}

/*
 * Factorization helper for the command state machine:
 * Submit a REQUEST SENSE and go to SENSE state.
 */
static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct ub_scsi_cmd *scmd;
1392
	struct scatterlist *sg;
L
Linus Torvalds 已提交
1393 1394 1395 1396 1397 1398 1399 1400
	int rc;

	if (cmd->cdb[0] == REQUEST_SENSE) {
		rc = -EPIPE;
		goto error;
	}

	scmd = &sc->top_rqs_cmd;
1401
	memset(scmd, 0, sizeof(struct ub_scsi_cmd));
L
Linus Torvalds 已提交
1402 1403 1404 1405 1406
	scmd->cdb[0] = REQUEST_SENSE;
	scmd->cdb[4] = UB_SENSE_SIZE;
	scmd->cdb_len = 6;
	scmd->dir = UB_DIR_READ;
	scmd->state = UB_CMDST_INIT;
1407 1408
	scmd->nsg = 1;
	sg = &scmd->sgv[0];
1409
	sg_init_table(sg, UB_MAX_REQ_SG);
1410 1411
	sg_set_page(sg, virt_to_page(sc->top_sense), UB_SENSE_SIZE,
			(unsigned long)sc->top_sense & (PAGE_SIZE-1));
L
Linus Torvalds 已提交
1412
	scmd->len = UB_SENSE_SIZE;
1413
	scmd->lun = cmd->lun;
L
Linus Torvalds 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
	scmd->done = ub_top_sense_done;
	scmd->back = cmd;

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

	cmd->state = UB_CMDST_SENSE;

	ub_cmdq_insert(sc, scmd);
	return;

error:
	ub_state_done(sc, cmd, rc);
}

/*
 * A helper for the command's state machine:
 * Submit a stall clear.
 */
static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
    int stalled_pipe)
{
	int endp;
	struct usb_ctrlrequest *cr;
	int rc;

	endp = usb_pipeendpoint(stalled_pipe);
	if (usb_pipein (stalled_pipe))
		endp |= USB_DIR_IN;

	cr = &sc->work_cr;
	cr->bRequestType = USB_RECIP_ENDPOINT;
	cr->bRequest = USB_REQ_CLEAR_FEATURE;
	cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
	cr->wIndex = cpu_to_le16(endp);
	cr->wLength = cpu_to_le16(0);

	UB_INIT_COMPLETION(sc->work_done);

	usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
	    (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);

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

	sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
	add_timer(&sc->work_timer);
	return 0;
}

/*
 */
static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
{
1469
	unsigned char *sense = sc->top_sense;
L
Linus Torvalds 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
	struct ub_scsi_cmd *cmd;

	/*
	 * Find the command which triggered the unit attention or a check,
	 * save the sense into it, and advance its state machine.
	 */
	if ((cmd = ub_cmdq_peek(sc)) == NULL) {
		printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
		return;
	}
	if (cmd != scmd->back) {
		printk(KERN_WARNING "%s: "
1482 1483
		    "sense done for wrong command 0x%x\n",
		    sc->name, cmd->tag);
L
Linus Torvalds 已提交
1484 1485 1486
		return;
	}
	if (cmd->state != UB_CMDST_SENSE) {
P
Pete Zaitcev 已提交
1487
		printk(KERN_WARNING "%s: sense done with bad cmd state %d\n",
1488
		    sc->name, cmd->state);
L
Linus Torvalds 已提交
1489 1490 1491
		return;
	}

P
Pete Zaitcev 已提交
1492 1493 1494
	/*
	 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
	 */
L
Linus Torvalds 已提交
1495 1496 1497 1498 1499 1500 1501
	cmd->key = sense[2] & 0x0F;
	cmd->asc = sense[12];
	cmd->ascq = sense[13];

	ub_scsi_urb_compl(sc, cmd);
}

1502 1503 1504 1505
/*
 * Reset management
 */

P
Pete Zaitcev 已提交
1506
static void ub_reset_enter(struct ub_dev *sc, int try)
1507 1508 1509 1510 1511 1512
{

	if (sc->reset) {
		/* This happens often on multi-LUN devices. */
		return;
	}
P
Pete Zaitcev 已提交
1513
	sc->reset = try + 1;
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523

#if 0 /* Not needed because the disconnect waits for us. */
	unsigned long flags;
	spin_lock_irqsave(&ub_lock, flags);
	sc->openc++;
	spin_unlock_irqrestore(&ub_lock, flags);
#endif

#if 0 /* We let them stop themselves. */
	struct ub_lun *lun;
1524
	list_for_each_entry(lun, &sc->luns, link) {
1525 1526 1527 1528 1529 1530 1531
		blk_stop_queue(lun->disk->queue);
	}
#endif

	schedule_work(&sc->reset_work);
}

D
David Howells 已提交
1532
static void ub_reset_task(struct work_struct *work)
1533
{
D
David Howells 已提交
1534
	struct ub_dev *sc = container_of(work, struct ub_dev, reset_work);
1535 1536
	unsigned long flags;
	struct ub_lun *lun;
1537
	int rc;
1538 1539 1540 1541 1542 1543 1544 1545

	if (!sc->reset) {
		printk(KERN_WARNING "%s: Running reset unrequested\n",
		    sc->name);
		return;
	}

	if (atomic_read(&sc->poison)) {
P
Pete Zaitcev 已提交
1546
		;
P
Pete Zaitcev 已提交
1547 1548 1549 1550 1551
	} else if ((sc->reset & 1) == 0) {
		ub_sync_reset(sc);
		msleep(700);	/* usb-storage sleeps 6s (!) */
		ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
		ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1552
	} else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
P
Pete Zaitcev 已提交
1553
		;
1554
	} else {
1555 1556
		rc = usb_lock_device_for_reset(sc->dev, sc->intf);
		if (rc < 0) {
1557 1558
			printk(KERN_NOTICE
			    "%s: usb_lock_device_for_reset failed (%d)\n",
1559
			    sc->name, rc);
1560 1561 1562 1563 1564 1565 1566
		} else {
			rc = usb_reset_device(sc->dev);
			if (rc < 0) {
				printk(KERN_NOTICE "%s: "
				    "usb_lock_device_for_reset failed (%d)\n",
				    sc->name, rc);
			}
1567
			usb_unlock_device(sc->dev);
1568 1569 1570 1571 1572 1573 1574 1575 1576
		}
	}

	/*
	 * In theory, no commands can be running while reset is active,
	 * so nobody can ask for another reset, and so we do not need any
	 * queues of resets or anything. We do need a spinlock though,
	 * to interact with block layer.
	 */
P
Pete Zaitcev 已提交
1577
	spin_lock_irqsave(sc->lock, flags);
1578 1579
	sc->reset = 0;
	tasklet_schedule(&sc->tasklet);
1580
	list_for_each_entry(lun, &sc->luns, link) {
1581 1582 1583
		blk_start_queue(lun->disk->queue);
	}
	wake_up(&sc->reset_wait);
P
Pete Zaitcev 已提交
1584
	spin_unlock_irqrestore(sc->lock, flags);
1585 1586
}

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
/*
 * XXX Reset brackets are too much hassle to implement, so just stub them
 * in order to prevent forced unbinding (which deadlocks solid when our
 * ->disconnect method waits for the reset to complete and this kills keventd).
 *
 * XXX Tell Alan to move usb_unlock_device inside of usb_reset_device,
 * or else the post_reset is invoked, and restats I/O on a locked device.
 */
static int ub_pre_reset(struct usb_interface *iface) {
	return 0;
}

static int ub_post_reset(struct usb_interface *iface) {
	return 0;
}

L
Linus Torvalds 已提交
1603 1604 1605
/*
 * This is called from a process context.
 */
1606
static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
L
Linus Torvalds 已提交
1607 1608
{

1609
	lun->readonly = 0;	/* XXX Query this from the device */
L
Linus Torvalds 已提交
1610

1611 1612 1613
	lun->capacity.nsec = 0;
	lun->capacity.bsize = 512;
	lun->capacity.bshift = 0;
L
Linus Torvalds 已提交
1614

1615
	if (ub_sync_tur(sc, lun) != 0)
L
Linus Torvalds 已提交
1616
		return;			/* Not ready */
1617
	lun->changed = 0;
L
Linus Torvalds 已提交
1618

1619
	if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
L
Linus Torvalds 已提交
1620 1621 1622 1623 1624
		/*
		 * The retry here means something is wrong, either with the
		 * device, with the transport, or with our code.
		 * We keep this because sd.c has retries for capacity.
		 */
1625 1626 1627 1628
		if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
			lun->capacity.nsec = 0;
			lun->capacity.bsize = 512;
			lun->capacity.bshift = 0;
L
Linus Torvalds 已提交
1629 1630 1631 1632 1633 1634 1635 1636 1637
		}
	}
}

/*
 * The open funcion.
 * This is mostly needed to keep refcounting, but also to support
 * media checks on removable media drives.
 */
A
Al Viro 已提交
1638
static int ub_bd_open(struct block_device *bdev, fmode_t mode)
L
Linus Torvalds 已提交
1639
{
A
Al Viro 已提交
1640
	struct ub_lun *lun = bdev->bd_disk->private_data;
1641
	struct ub_dev *sc = lun->udev;
L
Linus Torvalds 已提交
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
	unsigned long flags;
	int rc;

	spin_lock_irqsave(&ub_lock, flags);
	if (atomic_read(&sc->poison)) {
		spin_unlock_irqrestore(&ub_lock, flags);
		return -ENXIO;
	}
	sc->openc++;
	spin_unlock_irqrestore(&ub_lock, flags);

1653
	if (lun->removable || lun->readonly)
A
Al Viro 已提交
1654
		check_disk_change(bdev);
L
Linus Torvalds 已提交
1655 1656 1657 1658 1659 1660

	/*
	 * The sd.c considers ->media_present and ->changed not equivalent,
	 * under some pretty murky conditions (a failure of READ CAPACITY).
	 * We may need it one day.
	 */
A
Al Viro 已提交
1661
	if (lun->removable && lun->changed && !(mode & FMODE_NDELAY)) {
L
Linus Torvalds 已提交
1662 1663 1664 1665
		rc = -ENOMEDIUM;
		goto err_open;
	}

A
Al Viro 已提交
1666
	if (lun->readonly && (mode & FMODE_WRITE)) {
L
Linus Torvalds 已提交
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
		rc = -EROFS;
		goto err_open;
	}

	return 0;

err_open:
	ub_put(sc);
	return rc;
}

1678 1679 1680 1681
static int ub_bd_unlocked_open(struct block_device *bdev, fmode_t mode)
{
	int ret;

1682
	mutex_lock(&ub_mutex);
1683
	ret = ub_bd_open(bdev, mode);
1684
	mutex_unlock(&ub_mutex);
1685 1686 1687 1688 1689

	return ret;
}


L
Linus Torvalds 已提交
1690 1691
/*
 */
A
Al Viro 已提交
1692
static int ub_bd_release(struct gendisk *disk, fmode_t mode)
L
Linus Torvalds 已提交
1693
{
1694 1695
	struct ub_lun *lun = disk->private_data;
	struct ub_dev *sc = lun->udev;
L
Linus Torvalds 已提交
1696

1697
	mutex_lock(&ub_mutex);
L
Linus Torvalds 已提交
1698
	ub_put(sc);
1699
	mutex_unlock(&ub_mutex);
1700

L
Linus Torvalds 已提交
1701 1702 1703 1704 1705 1706
	return 0;
}

/*
 * The ioctl interface.
 */
A
Al Viro 已提交
1707
static int ub_bd_ioctl(struct block_device *bdev, fmode_t mode,
L
Linus Torvalds 已提交
1708 1709 1710
    unsigned int cmd, unsigned long arg)
{
	void __user *usermem = (void __user *) arg;
1711 1712
	int ret;

1713
	mutex_lock(&ub_mutex);
1714
	ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, usermem);
1715
	mutex_unlock(&ub_mutex);
L
Linus Torvalds 已提交
1716

1717
	return ret;
L
Linus Torvalds 已提交
1718 1719 1720
}

/*
P
Pete Zaitcev 已提交
1721
 * This is called by check_disk_change if we reported a media change.
L
Linus Torvalds 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
 * The main onjective here is to discover the features of the media such as
 * the capacity, read-only status, etc. USB storage generally does not
 * need to be spun up, but if we needed it, this would be the place.
 *
 * This call can sleep.
 *
 * The return code is not used.
 */
static int ub_bd_revalidate(struct gendisk *disk)
{
1732 1733 1734
	struct ub_lun *lun = disk->private_data;

	ub_revalidate(lun->udev, lun);
L
Linus Torvalds 已提交
1735 1736

	/* XXX Support sector size switching like in sr.c */
1737
	blk_queue_logical_block_size(disk->queue, lun->capacity.bsize);
1738 1739
	set_capacity(disk, lun->capacity.nsec);
	// set_disk_ro(sdkp->disk, lun->readonly);
L
Linus Torvalds 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

	return 0;
}

/*
 * The check is called by the block layer to verify if the media
 * is still available. It is supposed to be harmless, lightweight and
 * non-intrusive in case the media was not changed.
 *
 * This call can sleep.
 *
 * The return code is bool!
 */
T
Tejun Heo 已提交
1753 1754
static unsigned int ub_bd_check_events(struct gendisk *disk,
				       unsigned int clearing)
L
Linus Torvalds 已提交
1755
{
1756
	struct ub_lun *lun = disk->private_data;
L
Linus Torvalds 已提交
1757

1758
	if (!lun->removable)
L
Linus Torvalds 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
		return 0;

	/*
	 * We clean checks always after every command, so this is not
	 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
	 * the device is actually not ready with operator or software
	 * intervention required. One dangerous item might be a drive which
	 * spins itself down, and come the time to write dirty pages, this
	 * will fail, then block layer discards the data. Since we never
	 * spin drives up, such devices simply cannot be used with ub anyway.
	 */
1770 1771
	if (ub_sync_tur(lun->udev, lun) != 0) {
		lun->changed = 1;
T
Tejun Heo 已提交
1772
		return DISK_EVENT_MEDIA_CHANGE;
L
Linus Torvalds 已提交
1773 1774
	}

T
Tejun Heo 已提交
1775
	return lun->changed ? DISK_EVENT_MEDIA_CHANGE : 0;
L
Linus Torvalds 已提交
1776 1777
}

1778
static const struct block_device_operations ub_bd_fops = {
L
Linus Torvalds 已提交
1779
	.owner		= THIS_MODULE,
1780
	.open		= ub_bd_unlocked_open,
A
Al Viro 已提交
1781
	.release	= ub_bd_release,
1782
	.ioctl		= ub_bd_ioctl,
T
Tejun Heo 已提交
1783
	.check_events	= ub_bd_check_events,
L
Linus Torvalds 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
	.revalidate_disk = ub_bd_revalidate,
};

/*
 * Common ->done routine for commands executed synchronously.
 */
static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
{
	struct completion *cop = cmd->back;
	complete(cop);
}

/*
 * Test if the device has a check condition on it, synchronously.
 */
1799
static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
L
Linus Torvalds 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
{
	struct ub_scsi_cmd *cmd;
	enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
	unsigned long flags;
	struct completion compl;
	int rc;

	init_completion(&compl);

	rc = -ENOMEM;
P
Pete Zaitcev 已提交
1810
	if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
L
Linus Torvalds 已提交
1811 1812 1813 1814 1815 1816
		goto err_alloc;

	cmd->cdb[0] = TEST_UNIT_READY;
	cmd->cdb_len = 6;
	cmd->dir = UB_DIR_NONE;
	cmd->state = UB_CMDST_INIT;
1817
	cmd->lun = lun;			/* This may be NULL, but that's ok */
L
Linus Torvalds 已提交
1818 1819 1820
	cmd->done = ub_probe_done;
	cmd->back = &compl;

P
Pete Zaitcev 已提交
1821
	spin_lock_irqsave(sc->lock, flags);
L
Linus Torvalds 已提交
1822 1823 1824
	cmd->tag = sc->tagcnt++;

	rc = ub_submit_scsi(sc, cmd);
P
Pete Zaitcev 已提交
1825
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
1826

P
Pete Zaitcev 已提交
1827
	if (rc != 0)
L
Linus Torvalds 已提交
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
		goto err_submit;

	wait_for_completion(&compl);

	rc = cmd->error;

	if (rc == -EIO && cmd->key != 0)	/* Retries for benh's key */
		rc = cmd->key;

err_submit:
	kfree(cmd);
err_alloc:
	return rc;
}

/*
 * Read the SCSI capacity synchronously (for probing).
 */
1846 1847
static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
    struct ub_capacity *ret)
L
Linus Torvalds 已提交
1848 1849
{
	struct ub_scsi_cmd *cmd;
1850
	struct scatterlist *sg;
L
Linus Torvalds 已提交
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
	char *p;
	enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
	unsigned long flags;
	unsigned int bsize, shift;
	unsigned long nsec;
	struct completion compl;
	int rc;

	init_completion(&compl);

	rc = -ENOMEM;
P
Pete Zaitcev 已提交
1862
	if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
L
Linus Torvalds 已提交
1863 1864 1865 1866 1867 1868 1869
		goto err_alloc;
	p = (char *)cmd + sizeof(struct ub_scsi_cmd);

	cmd->cdb[0] = 0x25;
	cmd->cdb_len = 10;
	cmd->dir = UB_DIR_READ;
	cmd->state = UB_CMDST_INIT;
1870 1871
	cmd->nsg = 1;
	sg = &cmd->sgv[0];
1872
	sg_init_table(sg, UB_MAX_REQ_SG);
1873
	sg_set_page(sg, virt_to_page(p), 8, (unsigned long)p & (PAGE_SIZE-1));
L
Linus Torvalds 已提交
1874
	cmd->len = 8;
1875
	cmd->lun = lun;
L
Linus Torvalds 已提交
1876 1877 1878
	cmd->done = ub_probe_done;
	cmd->back = &compl;

P
Pete Zaitcev 已提交
1879
	spin_lock_irqsave(sc->lock, flags);
L
Linus Torvalds 已提交
1880 1881 1882
	cmd->tag = sc->tagcnt++;

	rc = ub_submit_scsi(sc, cmd);
P
Pete Zaitcev 已提交
1883
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
1884

P
Pete Zaitcev 已提交
1885
	if (rc != 0)
L
Linus Torvalds 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
		goto err_submit;

	wait_for_completion(&compl);

	if (cmd->error != 0) {
		rc = -EIO;
		goto err_read;
	}
	if (cmd->act_len != 8) {
		rc = -EIO;
		goto err_read;
	}

	/* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
	nsec = be32_to_cpu(*(__be32 *)p) + 1;
	bsize = be32_to_cpu(*(__be32 *)(p + 4));
	switch (bsize) {
	case 512:	shift = 0;	break;
	case 1024:	shift = 1;	break;
	case 2048:	shift = 2;	break;
	case 4096:	shift = 3;	break;
	default:
		rc = -EDOM;
		goto err_inv_bsize;
	}

	ret->bsize = bsize;
	ret->bshift = shift;
	ret->nsec = nsec << shift;
	rc = 0;

err_inv_bsize:
err_read:
err_submit:
	kfree(cmd);
err_alloc:
	return rc;
}

/*
 */
1927
static void ub_probe_urb_complete(struct urb *urb)
L
Linus Torvalds 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
{
	struct completion *cop = urb->context;
	complete(cop);
}

static void ub_probe_timeout(unsigned long arg)
{
	struct completion *cop = (struct completion *) arg;
	complete(cop);
}

P
Pete Zaitcev 已提交
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
/*
 * Reset with a Bulk reset.
 */
static int ub_sync_reset(struct ub_dev *sc)
{
	int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
	struct usb_ctrlrequest *cr;
	struct completion compl;
	struct timer_list timer;
	int rc;

	init_completion(&compl);

	cr = &sc->work_cr;
	cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	cr->bRequest = US_BULK_RESET_REQUEST;
	cr->wValue = cpu_to_le16(0);
	cr->wIndex = cpu_to_le16(ifnum);
	cr->wLength = cpu_to_le16(0);

	usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
	    (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);

	if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
		printk(KERN_WARNING
		     "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
		return rc;
	}

	init_timer(&timer);
	timer.function = ub_probe_timeout;
	timer.data = (unsigned long) &compl;
	timer.expires = jiffies + UB_CTRL_TIMEOUT;
	add_timer(&timer);

	wait_for_completion(&compl);

	del_timer_sync(&timer);
	usb_kill_urb(&sc->work_urb);

	return sc->work_urb.status;
}

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
/*
 * Get number of LUNs by the way of Bulk GetMaxLUN command.
 */
static int ub_sync_getmaxlun(struct ub_dev *sc)
{
	int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
	unsigned char *p;
	enum { ALLOC_SIZE = 1 };
	struct usb_ctrlrequest *cr;
	struct completion compl;
	struct timer_list timer;
	int nluns;
	int rc;

	init_completion(&compl);

	rc = -ENOMEM;
	if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
		goto err_alloc;
	*p = 55;

	cr = &sc->work_cr;
	cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	cr->bRequest = US_BULK_GET_MAX_LUN;
	cr->wValue = cpu_to_le16(0);
	cr->wIndex = cpu_to_le16(ifnum);
	cr->wLength = cpu_to_le16(1);

	usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
	    (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);

P
Pete Zaitcev 已提交
2013
	if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
		goto err_submit;

	init_timer(&timer);
	timer.function = ub_probe_timeout;
	timer.data = (unsigned long) &compl;
	timer.expires = jiffies + UB_CTRL_TIMEOUT;
	add_timer(&timer);

	wait_for_completion(&compl);

	del_timer_sync(&timer);
	usb_kill_urb(&sc->work_urb);

P
Pete Zaitcev 已提交
2027
	if ((rc = sc->work_urb.status) < 0)
P
Pete Zaitcev 已提交
2028 2029
		goto err_io;

2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
	if (sc->work_urb.actual_length != 1) {
		nluns = 0;
	} else {
		if ((nluns = *p) == 55) {
			nluns = 0;
		} else {
  			/* GetMaxLUN returns the maximum LUN number */
			nluns += 1;
			if (nluns > UB_MAX_LUNS)
				nluns = UB_MAX_LUNS;
		}
	}

	kfree(p);
	return nluns;

P
Pete Zaitcev 已提交
2046
err_io:
2047 2048 2049 2050 2051 2052
err_submit:
	kfree(p);
err_alloc:
	return rc;
}

L
Linus Torvalds 已提交
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
/*
 * Clear initial stalls.
 */
static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
{
	int endp;
	struct usb_ctrlrequest *cr;
	struct completion compl;
	struct timer_list timer;
	int rc;

	init_completion(&compl);

	endp = usb_pipeendpoint(stalled_pipe);
	if (usb_pipein (stalled_pipe))
		endp |= USB_DIR_IN;

	cr = &sc->work_cr;
	cr->bRequestType = USB_RECIP_ENDPOINT;
	cr->bRequest = USB_REQ_CLEAR_FEATURE;
	cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
	cr->wIndex = cpu_to_le16(endp);
	cr->wLength = cpu_to_le16(0);

	usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
	    (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);

	if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
		printk(KERN_WARNING
		     "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
		return rc;
	}

	init_timer(&timer);
	timer.function = ub_probe_timeout;
	timer.data = (unsigned long) &compl;
	timer.expires = jiffies + UB_CTRL_TIMEOUT;
	add_timer(&timer);

	wait_for_completion(&compl);

	del_timer_sync(&timer);
	usb_kill_urb(&sc->work_urb);

2097
	usb_reset_endpoint(sc->dev, endp);
L
Linus Torvalds 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122

	return 0;
}

/*
 * Get the pipe settings.
 */
static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
    struct usb_interface *intf)
{
	struct usb_host_interface *altsetting = intf->cur_altsetting;
	struct usb_endpoint_descriptor *ep_in = NULL;
	struct usb_endpoint_descriptor *ep_out = NULL;
	struct usb_endpoint_descriptor *ep;
	int i;

	/*
	 * Find the endpoints we need.
	 * We are expecting a minimum of 2 endpoints - in and out (bulk).
	 * We will ignore any others.
	 */
	for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
		ep = &altsetting->endpoint[i].desc;

		/* Is it a BULK endpoint? */
2123
		if (usb_endpoint_xfer_bulk(ep)) {
L
Linus Torvalds 已提交
2124
			/* BULK in or out? */
2125
			if (usb_endpoint_dir_in(ep)) {
2126 2127 2128 2129 2130 2131
				if (ep_in == NULL)
					ep_in = ep;
			} else {
				if (ep_out == NULL)
					ep_out = ep;
			}
L
Linus Torvalds 已提交
2132 2133 2134 2135
		}
	}

	if (ep_in == NULL || ep_out == NULL) {
P
Pete Zaitcev 已提交
2136
		printk(KERN_NOTICE "%s: failed endpoint check\n", sc->name);
2137
		return -ENODEV;
L
Linus Torvalds 已提交
2138 2139 2140 2141 2142 2143
	}

	/* Calculate and store the pipe values */
	sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
	sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
	sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2144
		usb_endpoint_num(ep_out));
L
Linus Torvalds 已提交
2145
	sc->recv_bulk_pipe = usb_rcvbulkpipe(dev, 
2146
		usb_endpoint_num(ep_in));
L
Linus Torvalds 已提交
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158

	return 0;
}

/*
 * Probing is done in the process context, which allows us to cheat
 * and not to build a state machine for the discovery.
 */
static int ub_probe(struct usb_interface *intf,
    const struct usb_device_id *dev_id)
{
	struct ub_dev *sc;
2159
	int nluns;
L
Linus Torvalds 已提交
2160 2161 2162
	int rc;
	int i;

2163 2164 2165
	if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
		return -ENXIO;

L
Linus Torvalds 已提交
2166
	rc = -ENOMEM;
P
Pete Zaitcev 已提交
2167
	if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
L
Linus Torvalds 已提交
2168
		goto err_core;
P
Pete Zaitcev 已提交
2169
	sc->lock = ub_next_lock();
2170
	INIT_LIST_HEAD(&sc->luns);
L
Linus Torvalds 已提交
2171 2172 2173
	usb_init_urb(&sc->work_urb);
	tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
	atomic_set(&sc->poison, 0);
D
David Howells 已提交
2174
	INIT_WORK(&sc->reset_work, ub_reset_task);
2175
	init_waitqueue_head(&sc->reset_wait);
L
Linus Torvalds 已提交
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

	init_timer(&sc->work_timer);
	sc->work_timer.data = (unsigned long) sc;
	sc->work_timer.function = ub_urb_timeout;

	ub_init_completion(&sc->work_done);
	sc->work_done.done = 1;		/* A little yuk, but oh well... */

	sc->dev = interface_to_usbdev(intf);
	sc->intf = intf;
	// sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
	usb_set_intfdata(intf, sc);
	usb_get_dev(sc->dev);
2189 2190 2191 2192 2193 2194
	/*
	 * Since we give the interface struct to the block level through
	 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
	 * oopses on close after a disconnect (kernels 2.6.16 and up).
	 */
	usb_get_intf(sc->intf);
L
Linus Torvalds 已提交
2195

2196 2197 2198
	snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
	    sc->dev->bus->busnum, sc->dev->devnum);

L
Linus Torvalds 已提交
2199 2200
	/* XXX Verify that we can handle the device (from descriptors) */

2201 2202
	if (ub_get_pipes(sc, sc->dev, intf) != 0)
		goto err_dev_desc;
L
Linus Torvalds 已提交
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214

	/*
	 * At this point, all USB initialization is done, do upper layer.
	 * We really hate halfway initialized structures, so from the
	 * invariants perspective, this ub_dev is fully constructed at
	 * this point.
	 */

	/*
	 * This is needed to clear toggles. It is a problem only if we do
	 * `rmmod ub && modprobe ub` without disconnects, but we like that.
	 */
2215
#if 0 /* iPod Mini fails if we do this (big white iPod works) */
L
Linus Torvalds 已提交
2216 2217
	ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
	ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2218
#endif
L
Linus Torvalds 已提交
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234

	/*
	 * The way this is used by the startup code is a little specific.
	 * A SCSI check causes a USB stall. Our common case code sees it
	 * and clears the check, after which the device is ready for use.
	 * But if a check was not present, any command other than
	 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
	 *
	 * If we neglect to clear the SCSI check, the first real command fails
	 * (which is the capacity readout). We clear that and retry, but why
	 * causing spurious retries for no reason.
	 *
	 * Revalidation may start with its own TEST_UNIT_READY, but that one
	 * has to succeed, so we clear checks with an additional one here.
	 * In any case it's not our business how revaliadation is implemented.
	 */
P
Pete Zaitcev 已提交
2235
	for (i = 0; i < 3; i++) {  /* Retries for the schwag key from KS'04 */
2236
		if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
L
Linus Torvalds 已提交
2237 2238 2239 2240
		if (rc != 0x6) break;
		msleep(10);
	}

2241 2242
	nluns = 1;
	for (i = 0; i < 3; i++) {
2243
		if ((rc = ub_sync_getmaxlun(sc)) < 0)
2244 2245 2246 2247 2248
			break;
		if (rc != 0) {
			nluns = rc;
			break;
		}
P
Pete Zaitcev 已提交
2249
		msleep(100);
2250
	}
L
Linus Torvalds 已提交
2251

2252 2253 2254 2255 2256
	for (i = 0; i < nluns; i++) {
		ub_probe_lun(sc, i);
	}
	return 0;

2257
err_dev_desc:
2258
	usb_set_intfdata(intf, NULL);
2259
	usb_put_intf(sc->intf);
2260 2261 2262 2263 2264 2265 2266 2267 2268
	usb_put_dev(sc->dev);
	kfree(sc);
err_core:
	return rc;
}

static int ub_probe_lun(struct ub_dev *sc, int lnum)
{
	struct ub_lun *lun;
2269
	struct request_queue *q;
2270 2271 2272 2273
	struct gendisk *disk;
	int rc;

	rc = -ENOMEM;
P
Pete Zaitcev 已提交
2274
	if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
		goto err_alloc;
	lun->num = lnum;

	rc = -ENOSR;
	if ((lun->id = ub_id_get()) == -1)
		goto err_id;

	lun->udev = sc;

	snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
	    lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);

	lun->removable = 1;		/* XXX Query this from the device */
	lun->changed = 1;		/* ub_revalidate clears only */
	ub_revalidate(sc, lun);
L
Linus Torvalds 已提交
2290 2291

	rc = -ENOMEM;
P
Pete Zaitcev 已提交
2292
	if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
L
Linus Torvalds 已提交
2293 2294
		goto err_diskalloc;

2295
	sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
L
Linus Torvalds 已提交
2296
	disk->major = UB_MAJOR;
P
Pete Zaitcev 已提交
2297
	disk->first_minor = lun->id * UB_PARTS_PER_LUN;
L
Linus Torvalds 已提交
2298
	disk->fops = &ub_bd_fops;
2299
	disk->private_data = lun;
P
Pete Zaitcev 已提交
2300
	disk->driverfs_dev = &sc->intf->dev;
L
Linus Torvalds 已提交
2301 2302

	rc = -ENOMEM;
P
Pete Zaitcev 已提交
2303
	if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
L
Linus Torvalds 已提交
2304 2305 2306 2307
		goto err_blkqinit;

	disk->queue = q;

2308
	blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2309
	blk_queue_max_segments(q, UB_MAX_REQ_SG);
2310
	blk_queue_segment_boundary(q, 0xffffffff);	/* Dubious. */
2311
	blk_queue_max_hw_sectors(q, UB_MAX_SECTORS);
2312
	blk_queue_logical_block_size(q, lun->capacity.bsize);
L
Linus Torvalds 已提交
2313

P
Pete Zaitcev 已提交
2314
	lun->disk = disk;
2315
	q->queuedata = lun;
P
Pete Zaitcev 已提交
2316
	list_add(&lun->link, &sc->luns);
L
Linus Torvalds 已提交
2317

2318 2319
	set_capacity(disk, lun->capacity.nsec);
	if (lun->removable)
L
Linus Torvalds 已提交
2320 2321 2322 2323 2324 2325 2326 2327 2328
		disk->flags |= GENHD_FL_REMOVABLE;

	add_disk(disk);

	return 0;

err_blkqinit:
	put_disk(disk);
err_diskalloc:
2329
	ub_id_put(lun->id);
L
Linus Torvalds 已提交
2330
err_id:
2331 2332
	kfree(lun);
err_alloc:
L
Linus Torvalds 已提交
2333 2334 2335 2336 2337 2338
	return rc;
}

static void ub_disconnect(struct usb_interface *intf)
{
	struct ub_dev *sc = usb_get_intfdata(intf);
2339
	struct ub_lun *lun;
L
Linus Torvalds 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
	unsigned long flags;

	/*
	 * Prevent ub_bd_release from pulling the rug from under us.
	 * XXX This is starting to look like a kref.
	 * XXX Why not to take this ref at probe time?
	 */
	spin_lock_irqsave(&ub_lock, flags);
	sc->openc++;
	spin_unlock_irqrestore(&ub_lock, flags);

	/*
P
Pete Zaitcev 已提交
2352
	 * Fence stall clearings, operations triggered by unlinkings and so on.
L
Linus Torvalds 已提交
2353 2354 2355 2356 2357
	 * We do not attempt to unlink any URBs, because we do not trust the
	 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
	 */
	atomic_set(&sc->poison, 1);

2358 2359 2360 2361 2362
	/*
	 * Wait for reset to end, if any.
	 */
	wait_event(sc->reset_wait, !sc->reset);

L
Linus Torvalds 已提交
2363 2364 2365 2366 2367 2368 2369 2370 2371
	/*
	 * Blow away queued commands.
	 *
	 * Actually, this never works, because before we get here
	 * the HCD terminates outstanding URB(s). It causes our
	 * SCSI command queue to advance, commands fail to submit,
	 * and the whole queue drains. So, we just use this code to
	 * print warnings.
	 */
P
Pete Zaitcev 已提交
2372
	spin_lock_irqsave(sc->lock, flags);
L
Linus Torvalds 已提交
2373 2374 2375
	{
		struct ub_scsi_cmd *cmd;
		int cnt = 0;
2376
		while ((cmd = ub_cmdq_peek(sc)) != NULL) {
L
Linus Torvalds 已提交
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
			cmd->error = -ENOTCONN;
			cmd->state = UB_CMDST_DONE;
			ub_cmdq_pop(sc);
			(*cmd->done)(sc, cmd);
			cnt++;
		}
		if (cnt != 0) {
			printk(KERN_WARNING "%s: "
			    "%d was queued after shutdown\n", sc->name, cnt);
		}
	}
P
Pete Zaitcev 已提交
2388
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
2389 2390 2391 2392

	/*
	 * Unregister the upper layer.
	 */
2393
	list_for_each_entry(lun, &sc->luns, link) {
P
Pete Zaitcev 已提交
2394
		del_gendisk(lun->disk);
2395 2396
		/*
		 * I wish I could do:
N
Nick Piggin 已提交
2397
		 *    queue_flag_set(QUEUE_FLAG_DEAD, q);
2398 2399 2400 2401
		 * As it is, we rely on our internal poisoning and let
		 * the upper levels to spin furiously failing all the I/O.
		 */
	}
L
Linus Torvalds 已提交
2402 2403 2404 2405 2406

	/*
	 * Testing for -EINPROGRESS is always a bug, so we are bending
	 * the rules a little.
	 */
P
Pete Zaitcev 已提交
2407
	spin_lock_irqsave(sc->lock, flags);
L
Linus Torvalds 已提交
2408 2409 2410 2411
	if (sc->work_urb.status == -EINPROGRESS) {	/* janitors: ignore */
		printk(KERN_WARNING "%s: "
		    "URB is active after disconnect\n", sc->name);
	}
P
Pete Zaitcev 已提交
2412
	spin_unlock_irqrestore(sc->lock, flags);
L
Linus Torvalds 已提交
2413 2414

	/*
P
Pete Zaitcev 已提交
2415
	 * There is virtually no chance that other CPU runs a timeout so long
L
Linus Torvalds 已提交
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
	 * after ub_urb_complete should have called del_timer, but only if HCD
	 * didn't forget to deliver a callback on unlink.
	 */
	del_timer_sync(&sc->work_timer);

	/*
	 * At this point there must be no commands coming from anyone
	 * and no URBs left in transit.
	 */

	ub_put(sc);
}

static struct usb_driver ub_driver = {
	.name =		"ub",
	.probe =	ub_probe,
	.disconnect =	ub_disconnect,
	.id_table =	ub_usb_ids,
2434 2435
	.pre_reset =	ub_pre_reset,
	.post_reset =	ub_post_reset,
L
Linus Torvalds 已提交
2436 2437 2438 2439 2440
};

static int __init ub_init(void)
{
	int rc;
P
Pete Zaitcev 已提交
2441 2442
	int i;

2443 2444
	pr_info("'Low Performance USB Block' driver is deprecated. "
			"Please switch to usb-storage\n");
P
Pete Zaitcev 已提交
2445 2446
	for (i = 0; i < UB_QLOCK_NUM; i++)
		spin_lock_init(&ub_qlockv[i]);
L
Linus Torvalds 已提交
2447 2448 2449 2450 2451 2452 2453

	if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
		goto err_regblkdev;

	if ((rc = usb_register(&ub_driver)) != 0)
		goto err_register;

2454
	usb_usual_set_present(USB_US_TYPE_UB);
L
Linus Torvalds 已提交
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
	return 0;

err_register:
	unregister_blkdev(UB_MAJOR, DRV_NAME);
err_regblkdev:
	return rc;
}

static void __exit ub_exit(void)
{
	usb_deregister(&ub_driver);

	unregister_blkdev(UB_MAJOR, DRV_NAME);
2468
	usb_usual_clear_present(USB_US_TYPE_UB);
L
Linus Torvalds 已提交
2469 2470 2471 2472 2473 2474
}

module_init(ub_init);
module_exit(ub_exit);

MODULE_LICENSE("GPL");