2 * The low performance USB storage driver (ub).
4 * Copyright (c) 1999, 2000 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
5 * Copyright (C) 2004 Pete Zaitcev (zaitcev@yahoo.com)
7 * This work is a part of Linux kernel, is derived from it,
8 * and is not licensed separately. See file COPYING for details.
10 * TODO (sorted by decreasing priority)
11 * -- Return sense now that rq allows it (we always auto-sense anyway).
12 * -- set readonly flag for CDs, set removable flag for CF readers
13 * -- do inquiry and verify we got a disk and not a tape (for LUN mismatch)
14 * -- verify the 13 conditions and do bulk resets
16 * -- move top_sense and work_bcs into separate allocations (if they survive)
17 * for cache purists and esoteric architectures.
18 * -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
19 * -- prune comments, they are too volumnous
21 * -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
23 #include <linux/kernel.h>
24 #include <linux/module.h>
25 #include <linux/usb.h>
26 #include <linux/usb_usual.h>
27 #include <linux/blkdev.h>
28 #include <linux/timer.h>
29 #include <linux/scatterlist.h>
30 #include <linux/slab.h>
31 #include <linux/smp_lock.h>
32 #include <scsi/scsi.h>
39 * The command state machine is the key model for understanding of this driver.
41 * The general rule is that all transitions are done towards the bottom
42 * of the diagram, thus preventing any loops.
44 * An exception to that is how the STAT state is handled. A counter allows it
45 * to be re-entered along the path marked with [C].
51 * ub_scsi_cmd_start fails ->--------------------------------------\
58 * was -EPIPE -->-------------------------------->! CLEAR ! !
61 * was error -->------------------------------------- ! --------->\
63 * /--<-- cmd->dir == NONE ? ! !
70 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
73 * ! ! was error -->---- ! --------->\
74 * ! was error -->--------------------- ! ------------- ! --------->\
77 * \--->+--------+ ! ! !
78 * ! STAT !<--------------------------/ ! !
81 * [C] was -EPIPE -->-----------\ ! !
83 * +<---- len == 0 ! ! !
85 * ! was error -->--------------------------------------!---------->\
87 * +<---- bad CSW ! ! !
88 * +<---- bad tag ! ! !
94 * \------- ! --------------------[C]--------\ ! !
96 * cmd->error---\ +--------+ ! !
97 * ! +--------------->! SENSE !<----------/ !
98 * STAT_FAIL----/ +--------+ !
101 * \--------------------------------\--------------------->! DONE !
106 * This many LUNs per USB device.
107 * Every one of them takes a host, see UB_MAX_HOSTS.
109 #define UB_MAX_LUNS 9
114 #define UB_PARTS_PER_LUN 8
116 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
118 #define UB_SENSE_SIZE 18
123 /* command block wrapper */
124 struct bulk_cb_wrap {
125 __le32 Signature; /* contains 'USBC' */
126 u32 Tag; /* unique per command id */
127 __le32 DataTransferLength; /* size of data */
128 u8 Flags; /* direction in bit 0 */
130 u8 Length; /* of of the CDB */
131 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
134 #define US_BULK_CB_WRAP_LEN 31
135 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
136 #define US_BULK_FLAG_IN 1
137 #define US_BULK_FLAG_OUT 0
139 /* command status wrapper */
140 struct bulk_cs_wrap {
141 __le32 Signature; /* should = 'USBS' */
142 u32 Tag; /* same as original command */
143 __le32 Residue; /* amount not transferred */
144 u8 Status; /* see below */
147 #define US_BULK_CS_WRAP_LEN 13
148 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
149 #define US_BULK_STAT_OK 0
150 #define US_BULK_STAT_FAIL 1
151 #define US_BULK_STAT_PHASE 2
153 /* bulk-only class specific requests */
154 #define US_BULK_RESET_REQUEST 0xff
155 #define US_BULK_GET_MAX_LUN 0xfe
161 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
162 #define UB_MAX_SECTORS 64
165 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
166 * even if a webcam hogs the bus, but some devices need time to spin up.
168 #define UB_URB_TIMEOUT (HZ*2)
169 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
170 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
171 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
174 * An instance of a SCSI command in transit.
176 #define UB_DIR_NONE 0
177 #define UB_DIR_READ 1
178 #define UB_DIR_ILLEGAL2 2
179 #define UB_DIR_WRITE 3
181 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
182 (((c)==UB_DIR_READ)? 'r': 'n'))
184 enum ub_scsi_cmd_state {
185 UB_CMDST_INIT, /* Initial state */
186 UB_CMDST_CMD, /* Command submitted */
187 UB_CMDST_DATA, /* Data phase */
188 UB_CMDST_CLR2STS, /* Clearing before requesting status */
189 UB_CMDST_STAT, /* Status phase */
190 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
191 UB_CMDST_CLRRS, /* Clearing before retrying status */
192 UB_CMDST_SENSE, /* Sending Request Sense */
193 UB_CMDST_DONE /* Final state */
197 unsigned char cdb[UB_MAX_CDB_SIZE];
198 unsigned char cdb_len;
200 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
201 enum ub_scsi_cmd_state state;
203 struct ub_scsi_cmd *next;
205 int error; /* Return code - valid upon done */
206 unsigned int act_len; /* Return size */
207 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
209 int stat_count; /* Retries getting status. */
210 unsigned int timeo; /* jiffies until rq->timeout changes */
212 unsigned int len; /* Requested length */
213 unsigned int current_sg;
214 unsigned int nsg; /* sgv[nsg] */
215 struct scatterlist sgv[UB_MAX_REQ_SG];
218 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
224 unsigned int current_try;
225 unsigned int nsg; /* sgv[nsg] */
226 struct scatterlist sgv[UB_MAX_REQ_SG];
232 unsigned long nsec; /* Linux size - 512 byte sectors */
233 unsigned int bsize; /* Linux hardsect_size */
234 unsigned int bshift; /* Shift between 512 and hard sects */
238 * This is a direct take-off from linux/include/completion.h
239 * The difference is that I do not wait on this thing, just poll.
240 * When I want to wait (ub_probe), I just use the stock completion.
242 * Note that INIT_COMPLETION takes no lock. It is correct. But why
243 * in the bloody hell that thing takes struct instead of pointer to struct
244 * is quite beyond me. I just copied it from the stock completion.
246 struct ub_completion {
251 static inline void ub_init_completion(struct ub_completion *x)
254 spin_lock_init(&x->lock);
257 #define UB_INIT_COMPLETION(x) ((x).done = 0)
259 static void ub_complete(struct ub_completion *x)
263 spin_lock_irqsave(&x->lock, flags);
265 spin_unlock_irqrestore(&x->lock, flags);
268 static int ub_is_completed(struct ub_completion *x)
273 spin_lock_irqsave(&x->lock, flags);
275 spin_unlock_irqrestore(&x->lock, flags);
281 struct ub_scsi_cmd_queue {
283 struct ub_scsi_cmd *head, *tail;
287 * The block device instance (one per LUN).
291 struct list_head link;
292 struct gendisk *disk;
293 int id; /* Host index */
294 int num; /* LUN number */
297 int changed; /* Media was changed */
301 struct ub_request urq;
303 /* Use Ingo's mempool if or when we have more than one command. */
305 * Currently we never need more than one command for the whole device.
306 * However, giving every LUN a command is a cheap and automatic way
307 * to enforce fairness between them.
310 struct ub_scsi_cmd cmdv[1];
312 struct ub_capacity capacity;
316 * The USB device instance.
320 atomic_t poison; /* The USB device is disconnected */
321 int openc; /* protected by ub_lock! */
322 /* kref is too implicit for our taste */
323 int reset; /* Reset is running */
327 struct usb_device *dev;
328 struct usb_interface *intf;
330 struct list_head luns;
332 unsigned int send_bulk_pipe; /* cached pipe values */
333 unsigned int recv_bulk_pipe;
334 unsigned int send_ctrl_pipe;
335 unsigned int recv_ctrl_pipe;
337 struct tasklet_struct tasklet;
339 struct ub_scsi_cmd_queue cmd_queue;
340 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
341 unsigned char top_sense[UB_SENSE_SIZE];
343 struct ub_completion work_done;
345 struct timer_list work_timer;
346 int last_pipe; /* What might need clearing */
347 __le32 signature; /* Learned signature */
348 struct bulk_cb_wrap work_bcb;
349 struct bulk_cs_wrap work_bcs;
350 struct usb_ctrlrequest work_cr;
352 struct work_struct reset_work;
353 wait_queue_head_t reset_wait;
358 static void ub_cleanup(struct ub_dev *sc);
359 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
360 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
361 struct ub_scsi_cmd *cmd, struct ub_request *urq);
362 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
363 struct ub_scsi_cmd *cmd, struct ub_request *urq);
364 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
365 static void ub_end_rq(struct request *rq, unsigned int status);
366 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
367 struct ub_request *urq, struct ub_scsi_cmd *cmd);
368 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
369 static void ub_urb_complete(struct urb *urb);
370 static void ub_scsi_action(unsigned long _dev);
371 static void ub_scsi_dispatch(struct ub_dev *sc);
372 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
373 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
374 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
375 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
376 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
377 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
378 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
379 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
381 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
382 static void ub_reset_enter(struct ub_dev *sc, int try);
383 static void ub_reset_task(struct work_struct *work);
384 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
385 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
386 struct ub_capacity *ret);
387 static int ub_sync_reset(struct ub_dev *sc);
388 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
389 static int ub_probe_lun(struct ub_dev *sc, int lnum);
393 #ifdef CONFIG_USB_LIBUSUAL
395 #define ub_usb_ids usb_storage_usb_ids
398 static const struct usb_device_id ub_usb_ids[] = {
399 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
403 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
404 #endif /* CONFIG_USB_LIBUSUAL */
407 * Find me a way to identify "next free minor" for add_disk(),
408 * and the array disappears the next day. However, the number of
409 * hosts has something to do with the naming and /proc/partitions.
410 * This has to be thought out in detail before changing.
411 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
413 #define UB_MAX_HOSTS 26
414 static char ub_hostv[UB_MAX_HOSTS];
416 #define UB_QLOCK_NUM 5
417 static spinlock_t ub_qlockv[UB_QLOCK_NUM];
418 static int ub_qlock_next = 0;
420 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
425 * This also stores the host for indexing by minor, which is somewhat dirty.
427 static int ub_id_get(void)
432 spin_lock_irqsave(&ub_lock, flags);
433 for (i = 0; i < UB_MAX_HOSTS; i++) {
434 if (ub_hostv[i] == 0) {
436 spin_unlock_irqrestore(&ub_lock, flags);
440 spin_unlock_irqrestore(&ub_lock, flags);
444 static void ub_id_put(int id)
448 if (id < 0 || id >= UB_MAX_HOSTS) {
449 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
453 spin_lock_irqsave(&ub_lock, flags);
454 if (ub_hostv[id] == 0) {
455 spin_unlock_irqrestore(&ub_lock, flags);
456 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
460 spin_unlock_irqrestore(&ub_lock, flags);
464 * This is necessitated by the fact that blk_cleanup_queue does not
465 * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
466 * Since our blk_init_queue() passes a spinlock common with ub_dev,
467 * we have life time issues when ub_cleanup frees ub_dev.
469 static spinlock_t *ub_next_lock(void)
474 spin_lock_irqsave(&ub_lock, flags);
475 ret = &ub_qlockv[ub_qlock_next];
476 ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
477 spin_unlock_irqrestore(&ub_lock, flags);
482 * Downcount for deallocation. This rides on two assumptions:
483 * - once something is poisoned, its refcount cannot grow
484 * - opens cannot happen at this time (del_gendisk was done)
485 * If the above is true, we can drop the lock, which we need for
486 * blk_cleanup_queue(): the silly thing may attempt to sleep.
487 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
489 static void ub_put(struct ub_dev *sc)
493 spin_lock_irqsave(&ub_lock, flags);
495 if (sc->openc == 0 && atomic_read(&sc->poison)) {
496 spin_unlock_irqrestore(&ub_lock, flags);
499 spin_unlock_irqrestore(&ub_lock, flags);
504 * Final cleanup and deallocation.
506 static void ub_cleanup(struct ub_dev *sc)
510 struct request_queue *q;
512 while (!list_empty(&sc->luns)) {
514 lun = list_entry(p, struct ub_lun, link);
517 /* I don't think queue can be NULL. But... Stolen from sx8.c */
518 if ((q = lun->disk->queue) != NULL)
519 blk_cleanup_queue(q);
521 * If we zero disk->private_data BEFORE put_disk, we have
522 * to check for NULL all over the place in open, release,
523 * check_media and revalidate, because the block level
524 * semaphore is well inside the put_disk.
525 * But we cannot zero after the call, because *disk is gone.
526 * The sd.c is blatantly racy in this area.
528 /* disk->private_data = NULL; */
536 usb_set_intfdata(sc->intf, NULL);
537 usb_put_intf(sc->intf);
538 usb_put_dev(sc->dev);
543 * The "command allocator".
545 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
547 struct ub_scsi_cmd *ret;
556 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
558 if (cmd != &lun->cmdv[0]) {
559 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
564 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
573 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
575 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
577 if (t->qlen++ == 0) {
585 if (t->qlen > t->qmax)
589 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
591 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
593 if (t->qlen++ == 0) {
601 if (t->qlen > t->qmax)
605 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
607 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
608 struct ub_scsi_cmd *cmd;
620 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
623 * The request function is our main entry point
626 static void ub_request_fn(struct request_queue *q)
628 struct ub_lun *lun = q->queuedata;
631 while ((rq = blk_peek_request(q)) != NULL) {
632 if (ub_request_fn_1(lun, rq) != 0) {
639 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
641 struct ub_dev *sc = lun->udev;
642 struct ub_scsi_cmd *cmd;
643 struct ub_request *urq;
646 if (atomic_read(&sc->poison)) {
647 blk_start_request(rq);
648 ub_end_rq(rq, DID_NO_CONNECT << 16);
652 if (lun->changed && rq->cmd_type != REQ_TYPE_BLOCK_PC) {
653 blk_start_request(rq);
654 ub_end_rq(rq, SAM_STAT_CHECK_CONDITION);
658 if (lun->urq.rq != NULL)
660 if ((cmd = ub_get_cmd(lun)) == NULL)
662 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
664 blk_start_request(rq);
667 memset(urq, 0, sizeof(struct ub_request));
671 * get scatterlist from block layer
673 sg_init_table(&urq->sgv[0], UB_MAX_REQ_SG);
674 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
676 /* Impossible, because blk_rq_map_sg should not hit ENOMEM. */
677 printk(KERN_INFO "%s: failed request map (%d)\n",
681 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
682 printk(KERN_WARNING "%s: request with %d segments\n",
688 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
689 ub_cmd_build_packet(sc, lun, cmd, urq);
691 ub_cmd_build_block(sc, lun, cmd, urq);
693 cmd->state = UB_CMDST_INIT;
695 cmd->done = ub_rw_cmd_done;
698 cmd->tag = sc->tagcnt++;
699 if (ub_submit_scsi(sc, cmd) != 0)
705 ub_put_cmd(lun, cmd);
706 ub_end_rq(rq, DID_ERROR << 16);
710 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
711 struct ub_scsi_cmd *cmd, struct ub_request *urq)
713 struct request *rq = urq->rq;
714 unsigned int block, nblks;
716 if (rq_data_dir(rq) == WRITE)
717 cmd->dir = UB_DIR_WRITE;
719 cmd->dir = UB_DIR_READ;
722 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
727 * The call to blk_queue_logical_block_size() guarantees that request
728 * is aligned, but it is given in terms of 512 byte units, always.
730 block = blk_rq_pos(rq) >> lun->capacity.bshift;
731 nblks = blk_rq_sectors(rq) >> lun->capacity.bshift;
733 cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
734 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
735 cmd->cdb[2] = block >> 24;
736 cmd->cdb[3] = block >> 16;
737 cmd->cdb[4] = block >> 8;
739 cmd->cdb[7] = nblks >> 8;
743 cmd->len = blk_rq_bytes(rq);
746 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
747 struct ub_scsi_cmd *cmd, struct ub_request *urq)
749 struct request *rq = urq->rq;
751 if (blk_rq_bytes(rq) == 0) {
752 cmd->dir = UB_DIR_NONE;
754 if (rq_data_dir(rq) == WRITE)
755 cmd->dir = UB_DIR_WRITE;
757 cmd->dir = UB_DIR_READ;
761 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
763 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
764 cmd->cdb_len = rq->cmd_len;
766 cmd->len = blk_rq_bytes(rq);
769 * To reapply this to every URB is not as incorrect as it looks.
770 * In return, we avoid any complicated tracking calculations.
772 cmd->timeo = rq->timeout;
775 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
777 struct ub_lun *lun = cmd->lun;
778 struct ub_request *urq = cmd->back;
780 unsigned int scsi_status;
784 if (cmd->error == 0) {
785 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
786 if (cmd->act_len >= rq->resid_len)
789 rq->resid_len -= cmd->act_len;
792 if (cmd->act_len != cmd->len) {
793 scsi_status = SAM_STAT_CHECK_CONDITION;
799 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
800 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
801 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
802 rq->sense_len = UB_SENSE_SIZE;
803 if (sc->top_sense[0] != 0)
804 scsi_status = SAM_STAT_CHECK_CONDITION;
806 scsi_status = DID_ERROR << 16;
808 if (cmd->error == -EIO &&
810 cmd->key == MEDIUM_ERROR ||
811 cmd->key == UNIT_ATTENTION)) {
812 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
815 scsi_status = SAM_STAT_CHECK_CONDITION;
821 ub_put_cmd(lun, cmd);
822 ub_end_rq(rq, scsi_status);
823 blk_start_queue(lun->disk->queue);
826 static void ub_end_rq(struct request *rq, unsigned int scsi_status)
830 if (scsi_status == 0) {
834 rq->errors = scsi_status;
836 __blk_end_request_all(rq, error);
839 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
840 struct ub_request *urq, struct ub_scsi_cmd *cmd)
843 if (atomic_read(&sc->poison))
846 ub_reset_enter(sc, urq->current_try);
848 if (urq->current_try >= 3)
852 /* Remove this if anyone complains of flooding. */
853 printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
854 "[sense %x %02x %02x] retry %d\n",
855 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
856 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
858 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
859 ub_cmd_build_block(sc, lun, cmd, urq);
861 cmd->state = UB_CMDST_INIT;
863 cmd->done = ub_rw_cmd_done;
866 cmd->tag = sc->tagcnt++;
869 return ub_submit_scsi(sc, cmd);
871 ub_cmdq_add(sc, cmd);
877 * Submit a regular SCSI operation (not an auto-sense).
879 * The Iron Law of Good Submit Routine is:
880 * Zero return - callback is done, Nonzero return - callback is not done.
883 * Host is assumed locked.
885 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
888 if (cmd->state != UB_CMDST_INIT ||
889 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
893 ub_cmdq_add(sc, cmd);
895 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
896 * safer to jump to a tasklet, in case upper layers do something silly.
898 tasklet_schedule(&sc->tasklet);
903 * Submit the first URB for the queued command.
904 * This function does not deal with queueing in any way.
906 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
908 struct bulk_cb_wrap *bcb;
914 * ``If the allocation length is eighteen or greater, and a device
915 * server returns less than eithteen bytes of data, the application
916 * client should assume that the bytes not transferred would have been
917 * zeroes had the device server returned those bytes.''
919 * We zero sense for all commands so that when a packet request
920 * fails it does not return a stale sense.
922 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
924 /* set up the command wrapper */
925 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
926 bcb->Tag = cmd->tag; /* Endianness is not important */
927 bcb->DataTransferLength = cpu_to_le32(cmd->len);
928 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
929 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
930 bcb->Length = cmd->cdb_len;
932 /* copy the command payload */
933 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
935 UB_INIT_COMPLETION(sc->work_done);
937 sc->last_pipe = sc->send_bulk_pipe;
938 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
939 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
941 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
942 /* XXX Clear stalls */
943 ub_complete(&sc->work_done);
947 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
948 add_timer(&sc->work_timer);
950 cmd->state = UB_CMDST_CMD;
957 static void ub_urb_timeout(unsigned long arg)
959 struct ub_dev *sc = (struct ub_dev *) arg;
962 spin_lock_irqsave(sc->lock, flags);
963 if (!ub_is_completed(&sc->work_done))
964 usb_unlink_urb(&sc->work_urb);
965 spin_unlock_irqrestore(sc->lock, flags);
969 * Completion routine for the work URB.
971 * This can be called directly from usb_submit_urb (while we have
972 * the sc->lock taken) and from an interrupt (while we do NOT have
973 * the sc->lock taken). Therefore, bounce this off to a tasklet.
975 static void ub_urb_complete(struct urb *urb)
977 struct ub_dev *sc = urb->context;
979 ub_complete(&sc->work_done);
980 tasklet_schedule(&sc->tasklet);
983 static void ub_scsi_action(unsigned long _dev)
985 struct ub_dev *sc = (struct ub_dev *) _dev;
988 spin_lock_irqsave(sc->lock, flags);
989 ub_scsi_dispatch(sc);
990 spin_unlock_irqrestore(sc->lock, flags);
993 static void ub_scsi_dispatch(struct ub_dev *sc)
995 struct ub_scsi_cmd *cmd;
998 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
999 if (cmd->state == UB_CMDST_DONE) {
1001 (*cmd->done)(sc, cmd);
1002 } else if (cmd->state == UB_CMDST_INIT) {
1003 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1006 cmd->state = UB_CMDST_DONE;
1008 if (!ub_is_completed(&sc->work_done))
1010 del_timer(&sc->work_timer);
1011 ub_scsi_urb_compl(sc, cmd);
1016 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1018 struct urb *urb = &sc->work_urb;
1019 struct bulk_cs_wrap *bcs;
1024 if (atomic_read(&sc->poison)) {
1025 ub_state_done(sc, cmd, -ENODEV);
1029 endp = usb_pipeendpoint(sc->last_pipe);
1030 if (usb_pipein(sc->last_pipe))
1033 if (cmd->state == UB_CMDST_CLEAR) {
1034 if (urb->status == -EPIPE) {
1036 * STALL while clearning STALL.
1037 * The control pipe clears itself - nothing to do.
1039 printk(KERN_NOTICE "%s: stall on control pipe\n",
1045 * We ignore the result for the halt clear.
1048 usb_reset_endpoint(sc->dev, endp);
1050 ub_state_sense(sc, cmd);
1052 } else if (cmd->state == UB_CMDST_CLR2STS) {
1053 if (urb->status == -EPIPE) {
1054 printk(KERN_NOTICE "%s: stall on control pipe\n",
1060 * We ignore the result for the halt clear.
1063 usb_reset_endpoint(sc->dev, endp);
1065 ub_state_stat(sc, cmd);
1067 } else if (cmd->state == UB_CMDST_CLRRS) {
1068 if (urb->status == -EPIPE) {
1069 printk(KERN_NOTICE "%s: stall on control pipe\n",
1075 * We ignore the result for the halt clear.
1078 usb_reset_endpoint(sc->dev, endp);
1080 ub_state_stat_counted(sc, cmd);
1082 } else if (cmd->state == UB_CMDST_CMD) {
1083 switch (urb->status) {
1089 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1091 printk(KERN_NOTICE "%s: "
1092 "unable to submit clear (%d)\n",
1095 * This is typically ENOMEM or some other such shit.
1096 * Retrying is pointless. Just do Bad End on it...
1098 ub_state_done(sc, cmd, rc);
1101 cmd->state = UB_CMDST_CLEAR;
1103 case -ESHUTDOWN: /* unplug */
1104 case -EILSEQ: /* unplug timeout on uhci */
1105 ub_state_done(sc, cmd, -ENODEV);
1110 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1114 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1115 ub_state_stat(sc, cmd);
1119 // udelay(125); // usb-storage has this
1120 ub_data_start(sc, cmd);
1122 } else if (cmd->state == UB_CMDST_DATA) {
1123 if (urb->status == -EPIPE) {
1124 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1126 printk(KERN_NOTICE "%s: "
1127 "unable to submit clear (%d)\n",
1129 ub_state_done(sc, cmd, rc);
1132 cmd->state = UB_CMDST_CLR2STS;
1135 if (urb->status == -EOVERFLOW) {
1137 * A babble? Failure, but we must transfer CSW now.
1139 cmd->error = -EOVERFLOW; /* A cheap trick... */
1140 ub_state_stat(sc, cmd);
1144 if (cmd->dir == UB_DIR_WRITE) {
1146 * Do not continue writes in case of a failure.
1147 * Doing so would cause sectors to be mixed up,
1148 * which is worse than sectors lost.
1150 * We must try to read the CSW, or many devices
1153 len = urb->actual_length;
1154 if (urb->status != 0 ||
1155 len != cmd->sgv[cmd->current_sg].length) {
1156 cmd->act_len += len;
1159 ub_state_stat(sc, cmd);
1165 * If an error occurs on read, we record it, and
1166 * continue to fetch data in order to avoid bubble.
1168 * As a small shortcut, we stop if we detect that
1169 * a CSW mixed into data.
1171 if (urb->status != 0)
1174 len = urb->actual_length;
1175 if (urb->status != 0 ||
1176 len != cmd->sgv[cmd->current_sg].length) {
1177 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1182 cmd->act_len += urb->actual_length;
1184 if (++cmd->current_sg < cmd->nsg) {
1185 ub_data_start(sc, cmd);
1188 ub_state_stat(sc, cmd);
1190 } else if (cmd->state == UB_CMDST_STAT) {
1191 if (urb->status == -EPIPE) {
1192 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1194 printk(KERN_NOTICE "%s: "
1195 "unable to submit clear (%d)\n",
1197 ub_state_done(sc, cmd, rc);
1202 * Having a stall when getting CSW is an error, so
1203 * make sure uppper levels are not oblivious to it.
1205 cmd->error = -EIO; /* A cheap trick... */
1207 cmd->state = UB_CMDST_CLRRS;
1211 /* Catch everything, including -EOVERFLOW and other nasties. */
1212 if (urb->status != 0)
1215 if (urb->actual_length == 0) {
1216 ub_state_stat_counted(sc, cmd);
1221 * Check the returned Bulk protocol status.
1222 * The status block has to be validated first.
1225 bcs = &sc->work_bcs;
1227 if (sc->signature == cpu_to_le32(0)) {
1229 * This is the first reply, so do not perform the check.
1230 * Instead, remember the signature the device uses
1231 * for future checks. But do not allow a nul.
1233 sc->signature = bcs->Signature;
1234 if (sc->signature == cpu_to_le32(0)) {
1235 ub_state_stat_counted(sc, cmd);
1239 if (bcs->Signature != sc->signature) {
1240 ub_state_stat_counted(sc, cmd);
1245 if (bcs->Tag != cmd->tag) {
1247 * This usually happens when we disagree with the
1248 * device's microcode about something. For instance,
1249 * a few of them throw this after timeouts. They buffer
1250 * commands and reply at commands we timed out before.
1251 * Without flushing these replies we loop forever.
1253 ub_state_stat_counted(sc, cmd);
1257 if (!sc->bad_resid) {
1258 len = le32_to_cpu(bcs->Residue);
1259 if (len != cmd->len - cmd->act_len) {
1261 * Only start ignoring if this cmd ended well.
1263 if (cmd->len == cmd->act_len) {
1264 printk(KERN_NOTICE "%s: "
1265 "bad residual %d of %d, ignoring\n",
1266 sc->name, len, cmd->len);
1272 switch (bcs->Status) {
1273 case US_BULK_STAT_OK:
1275 case US_BULK_STAT_FAIL:
1276 ub_state_sense(sc, cmd);
1278 case US_BULK_STAT_PHASE:
1281 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1282 sc->name, bcs->Status);
1283 ub_state_done(sc, cmd, -EINVAL);
1287 /* Not zeroing error to preserve a babble indicator */
1288 if (cmd->error != 0) {
1289 ub_state_sense(sc, cmd);
1292 cmd->state = UB_CMDST_DONE;
1294 (*cmd->done)(sc, cmd);
1296 } else if (cmd->state == UB_CMDST_SENSE) {
1297 ub_state_done(sc, cmd, -EIO);
1300 printk(KERN_WARNING "%s: wrong command state %d\n",
1301 sc->name, cmd->state);
1302 ub_state_done(sc, cmd, -EINVAL);
1307 Bad_End: /* Little Excel is dead */
1308 ub_state_done(sc, cmd, -EIO);
1312 * Factorization helper for the command state machine:
1313 * Initiate a data segment transfer.
1315 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1317 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1321 UB_INIT_COMPLETION(sc->work_done);
1323 if (cmd->dir == UB_DIR_READ)
1324 pipe = sc->recv_bulk_pipe;
1326 pipe = sc->send_bulk_pipe;
1327 sc->last_pipe = pipe;
1328 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe, sg_virt(sg),
1329 sg->length, ub_urb_complete, sc);
1331 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1332 /* XXX Clear stalls */
1333 ub_complete(&sc->work_done);
1334 ub_state_done(sc, cmd, rc);
1339 sc->work_timer.expires = jiffies + cmd->timeo;
1341 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1342 add_timer(&sc->work_timer);
1344 cmd->state = UB_CMDST_DATA;
1348 * Factorization helper for the command state machine:
1349 * Finish the command.
1351 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1355 cmd->state = UB_CMDST_DONE;
1357 (*cmd->done)(sc, cmd);
1361 * Factorization helper for the command state machine:
1362 * Submit a CSW read.
1364 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1368 UB_INIT_COMPLETION(sc->work_done);
1370 sc->last_pipe = sc->recv_bulk_pipe;
1371 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1372 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1374 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1375 /* XXX Clear stalls */
1376 ub_complete(&sc->work_done);
1377 ub_state_done(sc, cmd, rc);
1382 sc->work_timer.expires = jiffies + cmd->timeo;
1384 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1385 add_timer(&sc->work_timer);
1390 * Factorization helper for the command state machine:
1391 * Submit a CSW read and go to STAT state.
1393 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1396 if (__ub_state_stat(sc, cmd) != 0)
1399 cmd->stat_count = 0;
1400 cmd->state = UB_CMDST_STAT;
1404 * Factorization helper for the command state machine:
1405 * Submit a CSW read and go to STAT state with counter (along [C] path).
1407 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1410 if (++cmd->stat_count >= 4) {
1411 ub_state_sense(sc, cmd);
1415 if (__ub_state_stat(sc, cmd) != 0)
1418 cmd->state = UB_CMDST_STAT;
1422 * Factorization helper for the command state machine:
1423 * Submit a REQUEST SENSE and go to SENSE state.
1425 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1427 struct ub_scsi_cmd *scmd;
1428 struct scatterlist *sg;
1431 if (cmd->cdb[0] == REQUEST_SENSE) {
1436 scmd = &sc->top_rqs_cmd;
1437 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1438 scmd->cdb[0] = REQUEST_SENSE;
1439 scmd->cdb[4] = UB_SENSE_SIZE;
1441 scmd->dir = UB_DIR_READ;
1442 scmd->state = UB_CMDST_INIT;
1445 sg_init_table(sg, UB_MAX_REQ_SG);
1446 sg_set_page(sg, virt_to_page(sc->top_sense), UB_SENSE_SIZE,
1447 (unsigned long)sc->top_sense & (PAGE_SIZE-1));
1448 scmd->len = UB_SENSE_SIZE;
1449 scmd->lun = cmd->lun;
1450 scmd->done = ub_top_sense_done;
1453 scmd->tag = sc->tagcnt++;
1455 cmd->state = UB_CMDST_SENSE;
1457 ub_cmdq_insert(sc, scmd);
1461 ub_state_done(sc, cmd, rc);
1465 * A helper for the command's state machine:
1466 * Submit a stall clear.
1468 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1472 struct usb_ctrlrequest *cr;
1475 endp = usb_pipeendpoint(stalled_pipe);
1476 if (usb_pipein (stalled_pipe))
1480 cr->bRequestType = USB_RECIP_ENDPOINT;
1481 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1482 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1483 cr->wIndex = cpu_to_le16(endp);
1484 cr->wLength = cpu_to_le16(0);
1486 UB_INIT_COMPLETION(sc->work_done);
1488 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1489 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1491 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1492 ub_complete(&sc->work_done);
1496 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1497 add_timer(&sc->work_timer);
1503 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1505 unsigned char *sense = sc->top_sense;
1506 struct ub_scsi_cmd *cmd;
1509 * Find the command which triggered the unit attention or a check,
1510 * save the sense into it, and advance its state machine.
1512 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1513 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1516 if (cmd != scmd->back) {
1517 printk(KERN_WARNING "%s: "
1518 "sense done for wrong command 0x%x\n",
1519 sc->name, cmd->tag);
1522 if (cmd->state != UB_CMDST_SENSE) {
1523 printk(KERN_WARNING "%s: sense done with bad cmd state %d\n",
1524 sc->name, cmd->state);
1529 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1531 cmd->key = sense[2] & 0x0F;
1532 cmd->asc = sense[12];
1533 cmd->ascq = sense[13];
1535 ub_scsi_urb_compl(sc, cmd);
1542 static void ub_reset_enter(struct ub_dev *sc, int try)
1546 /* This happens often on multi-LUN devices. */
1549 sc->reset = try + 1;
1551 #if 0 /* Not needed because the disconnect waits for us. */
1552 unsigned long flags;
1553 spin_lock_irqsave(&ub_lock, flags);
1555 spin_unlock_irqrestore(&ub_lock, flags);
1558 #if 0 /* We let them stop themselves. */
1560 list_for_each_entry(lun, &sc->luns, link) {
1561 blk_stop_queue(lun->disk->queue);
1565 schedule_work(&sc->reset_work);
1568 static void ub_reset_task(struct work_struct *work)
1570 struct ub_dev *sc = container_of(work, struct ub_dev, reset_work);
1571 unsigned long flags;
1576 printk(KERN_WARNING "%s: Running reset unrequested\n",
1581 if (atomic_read(&sc->poison)) {
1583 } else if ((sc->reset & 1) == 0) {
1585 msleep(700); /* usb-storage sleeps 6s (!) */
1586 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1587 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1588 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1591 rc = usb_lock_device_for_reset(sc->dev, sc->intf);
1594 "%s: usb_lock_device_for_reset failed (%d)\n",
1597 rc = usb_reset_device(sc->dev);
1599 printk(KERN_NOTICE "%s: "
1600 "usb_lock_device_for_reset failed (%d)\n",
1603 usb_unlock_device(sc->dev);
1608 * In theory, no commands can be running while reset is active,
1609 * so nobody can ask for another reset, and so we do not need any
1610 * queues of resets or anything. We do need a spinlock though,
1611 * to interact with block layer.
1613 spin_lock_irqsave(sc->lock, flags);
1615 tasklet_schedule(&sc->tasklet);
1616 list_for_each_entry(lun, &sc->luns, link) {
1617 blk_start_queue(lun->disk->queue);
1619 wake_up(&sc->reset_wait);
1620 spin_unlock_irqrestore(sc->lock, flags);
1624 * XXX Reset brackets are too much hassle to implement, so just stub them
1625 * in order to prevent forced unbinding (which deadlocks solid when our
1626 * ->disconnect method waits for the reset to complete and this kills keventd).
1628 * XXX Tell Alan to move usb_unlock_device inside of usb_reset_device,
1629 * or else the post_reset is invoked, and restats I/O on a locked device.
1631 static int ub_pre_reset(struct usb_interface *iface) {
1635 static int ub_post_reset(struct usb_interface *iface) {
1640 * This is called from a process context.
1642 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1645 lun->readonly = 0; /* XXX Query this from the device */
1647 lun->capacity.nsec = 0;
1648 lun->capacity.bsize = 512;
1649 lun->capacity.bshift = 0;
1651 if (ub_sync_tur(sc, lun) != 0)
1652 return; /* Not ready */
1655 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1657 * The retry here means something is wrong, either with the
1658 * device, with the transport, or with our code.
1659 * We keep this because sd.c has retries for capacity.
1661 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1662 lun->capacity.nsec = 0;
1663 lun->capacity.bsize = 512;
1664 lun->capacity.bshift = 0;
1671 * This is mostly needed to keep refcounting, but also to support
1672 * media checks on removable media drives.
1674 static int ub_bd_open(struct block_device *bdev, fmode_t mode)
1676 struct ub_lun *lun = bdev->bd_disk->private_data;
1677 struct ub_dev *sc = lun->udev;
1678 unsigned long flags;
1681 spin_lock_irqsave(&ub_lock, flags);
1682 if (atomic_read(&sc->poison)) {
1683 spin_unlock_irqrestore(&ub_lock, flags);
1687 spin_unlock_irqrestore(&ub_lock, flags);
1689 if (lun->removable || lun->readonly)
1690 check_disk_change(bdev);
1693 * The sd.c considers ->media_present and ->changed not equivalent,
1694 * under some pretty murky conditions (a failure of READ CAPACITY).
1695 * We may need it one day.
1697 if (lun->removable && lun->changed && !(mode & FMODE_NDELAY)) {
1702 if (lun->readonly && (mode & FMODE_WRITE)) {
1716 static int ub_bd_release(struct gendisk *disk, fmode_t mode)
1718 struct ub_lun *lun = disk->private_data;
1719 struct ub_dev *sc = lun->udev;
1726 * The ioctl interface.
1728 static int ub_bd_ioctl(struct block_device *bdev, fmode_t mode,
1729 unsigned int cmd, unsigned long arg)
1731 struct gendisk *disk = bdev->bd_disk;
1732 void __user *usermem = (void __user *) arg;
1736 ret = scsi_cmd_ioctl(disk->queue, disk, mode, cmd, usermem);
1743 * This is called by check_disk_change if we reported a media change.
1744 * The main onjective here is to discover the features of the media such as
1745 * the capacity, read-only status, etc. USB storage generally does not
1746 * need to be spun up, but if we needed it, this would be the place.
1748 * This call can sleep.
1750 * The return code is not used.
1752 static int ub_bd_revalidate(struct gendisk *disk)
1754 struct ub_lun *lun = disk->private_data;
1756 ub_revalidate(lun->udev, lun);
1758 /* XXX Support sector size switching like in sr.c */
1759 blk_queue_logical_block_size(disk->queue, lun->capacity.bsize);
1760 set_capacity(disk, lun->capacity.nsec);
1761 // set_disk_ro(sdkp->disk, lun->readonly);
1767 * The check is called by the block layer to verify if the media
1768 * is still available. It is supposed to be harmless, lightweight and
1769 * non-intrusive in case the media was not changed.
1771 * This call can sleep.
1773 * The return code is bool!
1775 static int ub_bd_media_changed(struct gendisk *disk)
1777 struct ub_lun *lun = disk->private_data;
1779 if (!lun->removable)
1783 * We clean checks always after every command, so this is not
1784 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1785 * the device is actually not ready with operator or software
1786 * intervention required. One dangerous item might be a drive which
1787 * spins itself down, and come the time to write dirty pages, this
1788 * will fail, then block layer discards the data. Since we never
1789 * spin drives up, such devices simply cannot be used with ub anyway.
1791 if (ub_sync_tur(lun->udev, lun) != 0) {
1796 return lun->changed;
1799 static const struct block_device_operations ub_bd_fops = {
1800 .owner = THIS_MODULE,
1802 .release = ub_bd_release,
1803 .ioctl = ub_bd_ioctl,
1804 .media_changed = ub_bd_media_changed,
1805 .revalidate_disk = ub_bd_revalidate,
1809 * Common ->done routine for commands executed synchronously.
1811 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1813 struct completion *cop = cmd->back;
1818 * Test if the device has a check condition on it, synchronously.
1820 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1822 struct ub_scsi_cmd *cmd;
1823 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1824 unsigned long flags;
1825 struct completion compl;
1828 init_completion(&compl);
1831 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1834 cmd->cdb[0] = TEST_UNIT_READY;
1836 cmd->dir = UB_DIR_NONE;
1837 cmd->state = UB_CMDST_INIT;
1838 cmd->lun = lun; /* This may be NULL, but that's ok */
1839 cmd->done = ub_probe_done;
1842 spin_lock_irqsave(sc->lock, flags);
1843 cmd->tag = sc->tagcnt++;
1845 rc = ub_submit_scsi(sc, cmd);
1846 spin_unlock_irqrestore(sc->lock, flags);
1851 wait_for_completion(&compl);
1855 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1865 * Read the SCSI capacity synchronously (for probing).
1867 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1868 struct ub_capacity *ret)
1870 struct ub_scsi_cmd *cmd;
1871 struct scatterlist *sg;
1873 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1874 unsigned long flags;
1875 unsigned int bsize, shift;
1877 struct completion compl;
1880 init_completion(&compl);
1883 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1885 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1889 cmd->dir = UB_DIR_READ;
1890 cmd->state = UB_CMDST_INIT;
1893 sg_init_table(sg, UB_MAX_REQ_SG);
1894 sg_set_page(sg, virt_to_page(p), 8, (unsigned long)p & (PAGE_SIZE-1));
1897 cmd->done = ub_probe_done;
1900 spin_lock_irqsave(sc->lock, flags);
1901 cmd->tag = sc->tagcnt++;
1903 rc = ub_submit_scsi(sc, cmd);
1904 spin_unlock_irqrestore(sc->lock, flags);
1909 wait_for_completion(&compl);
1911 if (cmd->error != 0) {
1915 if (cmd->act_len != 8) {
1920 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1921 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1922 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1924 case 512: shift = 0; break;
1925 case 1024: shift = 1; break;
1926 case 2048: shift = 2; break;
1927 case 4096: shift = 3; break;
1934 ret->bshift = shift;
1935 ret->nsec = nsec << shift;
1948 static void ub_probe_urb_complete(struct urb *urb)
1950 struct completion *cop = urb->context;
1954 static void ub_probe_timeout(unsigned long arg)
1956 struct completion *cop = (struct completion *) arg;
1961 * Reset with a Bulk reset.
1963 static int ub_sync_reset(struct ub_dev *sc)
1965 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1966 struct usb_ctrlrequest *cr;
1967 struct completion compl;
1968 struct timer_list timer;
1971 init_completion(&compl);
1974 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1975 cr->bRequest = US_BULK_RESET_REQUEST;
1976 cr->wValue = cpu_to_le16(0);
1977 cr->wIndex = cpu_to_le16(ifnum);
1978 cr->wLength = cpu_to_le16(0);
1980 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1981 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1983 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1985 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1990 timer.function = ub_probe_timeout;
1991 timer.data = (unsigned long) &compl;
1992 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1995 wait_for_completion(&compl);
1997 del_timer_sync(&timer);
1998 usb_kill_urb(&sc->work_urb);
2000 return sc->work_urb.status;
2004 * Get number of LUNs by the way of Bulk GetMaxLUN command.
2006 static int ub_sync_getmaxlun(struct ub_dev *sc)
2008 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2010 enum { ALLOC_SIZE = 1 };
2011 struct usb_ctrlrequest *cr;
2012 struct completion compl;
2013 struct timer_list timer;
2017 init_completion(&compl);
2020 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2025 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2026 cr->bRequest = US_BULK_GET_MAX_LUN;
2027 cr->wValue = cpu_to_le16(0);
2028 cr->wIndex = cpu_to_le16(ifnum);
2029 cr->wLength = cpu_to_le16(1);
2031 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2032 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2034 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2038 timer.function = ub_probe_timeout;
2039 timer.data = (unsigned long) &compl;
2040 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2043 wait_for_completion(&compl);
2045 del_timer_sync(&timer);
2046 usb_kill_urb(&sc->work_urb);
2048 if ((rc = sc->work_urb.status) < 0)
2051 if (sc->work_urb.actual_length != 1) {
2054 if ((nluns = *p) == 55) {
2057 /* GetMaxLUN returns the maximum LUN number */
2059 if (nluns > UB_MAX_LUNS)
2060 nluns = UB_MAX_LUNS;
2075 * Clear initial stalls.
2077 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2080 struct usb_ctrlrequest *cr;
2081 struct completion compl;
2082 struct timer_list timer;
2085 init_completion(&compl);
2087 endp = usb_pipeendpoint(stalled_pipe);
2088 if (usb_pipein (stalled_pipe))
2092 cr->bRequestType = USB_RECIP_ENDPOINT;
2093 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2094 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2095 cr->wIndex = cpu_to_le16(endp);
2096 cr->wLength = cpu_to_le16(0);
2098 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2099 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2101 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2103 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2108 timer.function = ub_probe_timeout;
2109 timer.data = (unsigned long) &compl;
2110 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2113 wait_for_completion(&compl);
2115 del_timer_sync(&timer);
2116 usb_kill_urb(&sc->work_urb);
2118 usb_reset_endpoint(sc->dev, endp);
2124 * Get the pipe settings.
2126 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2127 struct usb_interface *intf)
2129 struct usb_host_interface *altsetting = intf->cur_altsetting;
2130 struct usb_endpoint_descriptor *ep_in = NULL;
2131 struct usb_endpoint_descriptor *ep_out = NULL;
2132 struct usb_endpoint_descriptor *ep;
2136 * Find the endpoints we need.
2137 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2138 * We will ignore any others.
2140 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2141 ep = &altsetting->endpoint[i].desc;
2143 /* Is it a BULK endpoint? */
2144 if (usb_endpoint_xfer_bulk(ep)) {
2145 /* BULK in or out? */
2146 if (usb_endpoint_dir_in(ep)) {
2156 if (ep_in == NULL || ep_out == NULL) {
2157 printk(KERN_NOTICE "%s: failed endpoint check\n", sc->name);
2161 /* Calculate and store the pipe values */
2162 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2163 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2164 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2165 usb_endpoint_num(ep_out));
2166 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2167 usb_endpoint_num(ep_in));
2173 * Probing is done in the process context, which allows us to cheat
2174 * and not to build a state machine for the discovery.
2176 static int ub_probe(struct usb_interface *intf,
2177 const struct usb_device_id *dev_id)
2184 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2188 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2190 sc->lock = ub_next_lock();
2191 INIT_LIST_HEAD(&sc->luns);
2192 usb_init_urb(&sc->work_urb);
2193 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2194 atomic_set(&sc->poison, 0);
2195 INIT_WORK(&sc->reset_work, ub_reset_task);
2196 init_waitqueue_head(&sc->reset_wait);
2198 init_timer(&sc->work_timer);
2199 sc->work_timer.data = (unsigned long) sc;
2200 sc->work_timer.function = ub_urb_timeout;
2202 ub_init_completion(&sc->work_done);
2203 sc->work_done.done = 1; /* A little yuk, but oh well... */
2205 sc->dev = interface_to_usbdev(intf);
2207 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2208 usb_set_intfdata(intf, sc);
2209 usb_get_dev(sc->dev);
2211 * Since we give the interface struct to the block level through
2212 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2213 * oopses on close after a disconnect (kernels 2.6.16 and up).
2215 usb_get_intf(sc->intf);
2217 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2218 sc->dev->bus->busnum, sc->dev->devnum);
2220 /* XXX Verify that we can handle the device (from descriptors) */
2222 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2226 * At this point, all USB initialization is done, do upper layer.
2227 * We really hate halfway initialized structures, so from the
2228 * invariants perspective, this ub_dev is fully constructed at
2233 * This is needed to clear toggles. It is a problem only if we do
2234 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2236 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2237 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2238 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2242 * The way this is used by the startup code is a little specific.
2243 * A SCSI check causes a USB stall. Our common case code sees it
2244 * and clears the check, after which the device is ready for use.
2245 * But if a check was not present, any command other than
2246 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2248 * If we neglect to clear the SCSI check, the first real command fails
2249 * (which is the capacity readout). We clear that and retry, but why
2250 * causing spurious retries for no reason.
2252 * Revalidation may start with its own TEST_UNIT_READY, but that one
2253 * has to succeed, so we clear checks with an additional one here.
2254 * In any case it's not our business how revaliadation is implemented.
2256 for (i = 0; i < 3; i++) { /* Retries for the schwag key from KS'04 */
2257 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2258 if (rc != 0x6) break;
2263 for (i = 0; i < 3; i++) {
2264 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2273 for (i = 0; i < nluns; i++) {
2274 ub_probe_lun(sc, i);
2279 usb_set_intfdata(intf, NULL);
2280 usb_put_intf(sc->intf);
2281 usb_put_dev(sc->dev);
2287 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2290 struct request_queue *q;
2291 struct gendisk *disk;
2295 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2300 if ((lun->id = ub_id_get()) == -1)
2305 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2306 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2308 lun->removable = 1; /* XXX Query this from the device */
2309 lun->changed = 1; /* ub_revalidate clears only */
2310 ub_revalidate(sc, lun);
2313 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2316 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2317 disk->major = UB_MAJOR;
2318 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2319 disk->fops = &ub_bd_fops;
2320 disk->private_data = lun;
2321 disk->driverfs_dev = &sc->intf->dev;
2324 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2329 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2330 blk_queue_max_segments(q, UB_MAX_REQ_SG);
2331 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2332 blk_queue_max_hw_sectors(q, UB_MAX_SECTORS);
2333 blk_queue_logical_block_size(q, lun->capacity.bsize);
2337 list_add(&lun->link, &sc->luns);
2339 set_capacity(disk, lun->capacity.nsec);
2341 disk->flags |= GENHD_FL_REMOVABLE;
2357 static void ub_disconnect(struct usb_interface *intf)
2359 struct ub_dev *sc = usb_get_intfdata(intf);
2361 unsigned long flags;
2364 * Prevent ub_bd_release from pulling the rug from under us.
2365 * XXX This is starting to look like a kref.
2366 * XXX Why not to take this ref at probe time?
2368 spin_lock_irqsave(&ub_lock, flags);
2370 spin_unlock_irqrestore(&ub_lock, flags);
2373 * Fence stall clearings, operations triggered by unlinkings and so on.
2374 * We do not attempt to unlink any URBs, because we do not trust the
2375 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2377 atomic_set(&sc->poison, 1);
2380 * Wait for reset to end, if any.
2382 wait_event(sc->reset_wait, !sc->reset);
2385 * Blow away queued commands.
2387 * Actually, this never works, because before we get here
2388 * the HCD terminates outstanding URB(s). It causes our
2389 * SCSI command queue to advance, commands fail to submit,
2390 * and the whole queue drains. So, we just use this code to
2393 spin_lock_irqsave(sc->lock, flags);
2395 struct ub_scsi_cmd *cmd;
2397 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2398 cmd->error = -ENOTCONN;
2399 cmd->state = UB_CMDST_DONE;
2401 (*cmd->done)(sc, cmd);
2405 printk(KERN_WARNING "%s: "
2406 "%d was queued after shutdown\n", sc->name, cnt);
2409 spin_unlock_irqrestore(sc->lock, flags);
2412 * Unregister the upper layer.
2414 list_for_each_entry(lun, &sc->luns, link) {
2415 del_gendisk(lun->disk);
2417 * I wish I could do:
2418 * queue_flag_set(QUEUE_FLAG_DEAD, q);
2419 * As it is, we rely on our internal poisoning and let
2420 * the upper levels to spin furiously failing all the I/O.
2425 * Testing for -EINPROGRESS is always a bug, so we are bending
2426 * the rules a little.
2428 spin_lock_irqsave(sc->lock, flags);
2429 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2430 printk(KERN_WARNING "%s: "
2431 "URB is active after disconnect\n", sc->name);
2433 spin_unlock_irqrestore(sc->lock, flags);
2436 * There is virtually no chance that other CPU runs a timeout so long
2437 * after ub_urb_complete should have called del_timer, but only if HCD
2438 * didn't forget to deliver a callback on unlink.
2440 del_timer_sync(&sc->work_timer);
2443 * At this point there must be no commands coming from anyone
2444 * and no URBs left in transit.
2450 static struct usb_driver ub_driver = {
2453 .disconnect = ub_disconnect,
2454 .id_table = ub_usb_ids,
2455 .pre_reset = ub_pre_reset,
2456 .post_reset = ub_post_reset,
2459 static int __init ub_init(void)
2464 for (i = 0; i < UB_QLOCK_NUM; i++)
2465 spin_lock_init(&ub_qlockv[i]);
2467 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2470 if ((rc = usb_register(&ub_driver)) != 0)
2473 usb_usual_set_present(USB_US_TYPE_UB);
2477 unregister_blkdev(UB_MAJOR, DRV_NAME);
2482 static void __exit ub_exit(void)
2484 usb_deregister(&ub_driver);
2486 unregister_blkdev(UB_MAJOR, DRV_NAME);
2487 usb_usual_clear_present(USB_US_TYPE_UB);
2490 module_init(ub_init);
2491 module_exit(ub_exit);
2493 MODULE_LICENSE("GPL");