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 <scsi/scsi.h>
38 * The command state machine is the key model for understanding of this driver.
40 * The general rule is that all transitions are done towards the bottom
41 * of the diagram, thus preventing any loops.
43 * An exception to that is how the STAT state is handled. A counter allows it
44 * to be re-entered along the path marked with [C].
50 * ub_scsi_cmd_start fails ->--------------------------------------\
57 * was -EPIPE -->-------------------------------->! CLEAR ! !
60 * was error -->------------------------------------- ! --------->\
62 * /--<-- cmd->dir == NONE ? ! !
69 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
72 * ! ! was error -->---- ! --------->\
73 * ! was error -->--------------------- ! ------------- ! --------->\
76 * \--->+--------+ ! ! !
77 * ! STAT !<--------------------------/ ! !
80 * [C] was -EPIPE -->-----------\ ! !
82 * +<---- len == 0 ! ! !
84 * ! was error -->--------------------------------------!---------->\
86 * +<---- bad CSW ! ! !
87 * +<---- bad tag ! ! !
93 * \------- ! --------------------[C]--------\ ! !
95 * cmd->error---\ +--------+ ! !
96 * ! +--------------->! SENSE !<----------/ !
97 * STAT_FAIL----/ +--------+ !
100 * \--------------------------------\--------------------->! DONE !
105 * This many LUNs per USB device.
106 * Every one of them takes a host, see UB_MAX_HOSTS.
108 #define UB_MAX_LUNS 9
113 #define UB_PARTS_PER_LUN 8
115 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
117 #define UB_SENSE_SIZE 18
122 /* command block wrapper */
123 struct bulk_cb_wrap {
124 __le32 Signature; /* contains 'USBC' */
125 u32 Tag; /* unique per command id */
126 __le32 DataTransferLength; /* size of data */
127 u8 Flags; /* direction in bit 0 */
129 u8 Length; /* of of the CDB */
130 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
133 #define US_BULK_CB_WRAP_LEN 31
134 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
135 #define US_BULK_FLAG_IN 1
136 #define US_BULK_FLAG_OUT 0
138 /* command status wrapper */
139 struct bulk_cs_wrap {
140 __le32 Signature; /* should = 'USBS' */
141 u32 Tag; /* same as original command */
142 __le32 Residue; /* amount not transferred */
143 u8 Status; /* see below */
146 #define US_BULK_CS_WRAP_LEN 13
147 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
148 #define US_BULK_STAT_OK 0
149 #define US_BULK_STAT_FAIL 1
150 #define US_BULK_STAT_PHASE 2
152 /* bulk-only class specific requests */
153 #define US_BULK_RESET_REQUEST 0xff
154 #define US_BULK_GET_MAX_LUN 0xfe
160 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
161 #define UB_MAX_SECTORS 64
164 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
165 * even if a webcam hogs the bus, but some devices need time to spin up.
167 #define UB_URB_TIMEOUT (HZ*2)
168 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
169 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
170 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
173 * An instance of a SCSI command in transit.
175 #define UB_DIR_NONE 0
176 #define UB_DIR_READ 1
177 #define UB_DIR_ILLEGAL2 2
178 #define UB_DIR_WRITE 3
180 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
181 (((c)==UB_DIR_READ)? 'r': 'n'))
183 enum ub_scsi_cmd_state {
184 UB_CMDST_INIT, /* Initial state */
185 UB_CMDST_CMD, /* Command submitted */
186 UB_CMDST_DATA, /* Data phase */
187 UB_CMDST_CLR2STS, /* Clearing before requesting status */
188 UB_CMDST_STAT, /* Status phase */
189 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
190 UB_CMDST_CLRRS, /* Clearing before retrying status */
191 UB_CMDST_SENSE, /* Sending Request Sense */
192 UB_CMDST_DONE /* Final state */
196 unsigned char cdb[UB_MAX_CDB_SIZE];
197 unsigned char cdb_len;
199 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
200 enum ub_scsi_cmd_state state;
202 struct ub_scsi_cmd *next;
204 int error; /* Return code - valid upon done */
205 unsigned int act_len; /* Return size */
206 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
208 int stat_count; /* Retries getting status. */
209 unsigned int timeo; /* jiffies until rq->timeout changes */
211 unsigned int len; /* Requested length */
212 unsigned int current_sg;
213 unsigned int nsg; /* sgv[nsg] */
214 struct scatterlist sgv[UB_MAX_REQ_SG];
217 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
223 unsigned int current_try;
224 unsigned int nsg; /* sgv[nsg] */
225 struct scatterlist sgv[UB_MAX_REQ_SG];
231 unsigned long nsec; /* Linux size - 512 byte sectors */
232 unsigned int bsize; /* Linux hardsect_size */
233 unsigned int bshift; /* Shift between 512 and hard sects */
237 * This is a direct take-off from linux/include/completion.h
238 * The difference is that I do not wait on this thing, just poll.
239 * When I want to wait (ub_probe), I just use the stock completion.
241 * Note that INIT_COMPLETION takes no lock. It is correct. But why
242 * in the bloody hell that thing takes struct instead of pointer to struct
243 * is quite beyond me. I just copied it from the stock completion.
245 struct ub_completion {
250 static inline void ub_init_completion(struct ub_completion *x)
253 spin_lock_init(&x->lock);
256 #define UB_INIT_COMPLETION(x) ((x).done = 0)
258 static void ub_complete(struct ub_completion *x)
262 spin_lock_irqsave(&x->lock, flags);
264 spin_unlock_irqrestore(&x->lock, flags);
267 static int ub_is_completed(struct ub_completion *x)
272 spin_lock_irqsave(&x->lock, flags);
274 spin_unlock_irqrestore(&x->lock, flags);
280 struct ub_scsi_cmd_queue {
282 struct ub_scsi_cmd *head, *tail;
286 * The block device instance (one per LUN).
290 struct list_head link;
291 struct gendisk *disk;
292 int id; /* Host index */
293 int num; /* LUN number */
296 int changed; /* Media was changed */
300 struct ub_request urq;
302 /* Use Ingo's mempool if or when we have more than one command. */
304 * Currently we never need more than one command for the whole device.
305 * However, giving every LUN a command is a cheap and automatic way
306 * to enforce fairness between them.
309 struct ub_scsi_cmd cmdv[1];
311 struct ub_capacity capacity;
315 * The USB device instance.
319 atomic_t poison; /* The USB device is disconnected */
320 int openc; /* protected by ub_lock! */
321 /* kref is too implicit for our taste */
322 int reset; /* Reset is running */
326 struct usb_device *dev;
327 struct usb_interface *intf;
329 struct list_head luns;
331 unsigned int send_bulk_pipe; /* cached pipe values */
332 unsigned int recv_bulk_pipe;
333 unsigned int send_ctrl_pipe;
334 unsigned int recv_ctrl_pipe;
336 struct tasklet_struct tasklet;
338 struct ub_scsi_cmd_queue cmd_queue;
339 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
340 unsigned char top_sense[UB_SENSE_SIZE];
342 struct ub_completion work_done;
344 struct timer_list work_timer;
345 int last_pipe; /* What might need clearing */
346 __le32 signature; /* Learned signature */
347 struct bulk_cb_wrap work_bcb;
348 struct bulk_cs_wrap work_bcs;
349 struct usb_ctrlrequest work_cr;
351 struct work_struct reset_work;
352 wait_queue_head_t reset_wait;
357 static void ub_cleanup(struct ub_dev *sc);
358 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
359 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
360 struct ub_scsi_cmd *cmd, struct ub_request *urq);
361 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
362 struct ub_scsi_cmd *cmd, struct ub_request *urq);
363 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
364 static void ub_end_rq(struct request *rq, unsigned int status);
365 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
366 struct ub_request *urq, struct ub_scsi_cmd *cmd);
367 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
368 static void ub_urb_complete(struct urb *urb);
369 static void ub_scsi_action(unsigned long _dev);
370 static void ub_scsi_dispatch(struct ub_dev *sc);
371 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
372 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
373 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
374 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
375 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
376 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
377 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
378 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
380 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
381 static void ub_reset_enter(struct ub_dev *sc, int try);
382 static void ub_reset_task(struct work_struct *work);
383 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
384 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
385 struct ub_capacity *ret);
386 static int ub_sync_reset(struct ub_dev *sc);
387 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
388 static int ub_probe_lun(struct ub_dev *sc, int lnum);
392 #ifdef CONFIG_USB_LIBUSUAL
394 #define ub_usb_ids usb_storage_usb_ids
397 static const struct usb_device_id ub_usb_ids[] = {
398 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
402 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
403 #endif /* CONFIG_USB_LIBUSUAL */
406 * Find me a way to identify "next free minor" for add_disk(),
407 * and the array disappears the next day. However, the number of
408 * hosts has something to do with the naming and /proc/partitions.
409 * This has to be thought out in detail before changing.
410 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
412 #define UB_MAX_HOSTS 26
413 static char ub_hostv[UB_MAX_HOSTS];
415 #define UB_QLOCK_NUM 5
416 static spinlock_t ub_qlockv[UB_QLOCK_NUM];
417 static int ub_qlock_next = 0;
419 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
424 * This also stores the host for indexing by minor, which is somewhat dirty.
426 static int ub_id_get(void)
431 spin_lock_irqsave(&ub_lock, flags);
432 for (i = 0; i < UB_MAX_HOSTS; i++) {
433 if (ub_hostv[i] == 0) {
435 spin_unlock_irqrestore(&ub_lock, flags);
439 spin_unlock_irqrestore(&ub_lock, flags);
443 static void ub_id_put(int id)
447 if (id < 0 || id >= UB_MAX_HOSTS) {
448 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
452 spin_lock_irqsave(&ub_lock, flags);
453 if (ub_hostv[id] == 0) {
454 spin_unlock_irqrestore(&ub_lock, flags);
455 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
459 spin_unlock_irqrestore(&ub_lock, flags);
463 * This is necessitated by the fact that blk_cleanup_queue does not
464 * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
465 * Since our blk_init_queue() passes a spinlock common with ub_dev,
466 * we have life time issues when ub_cleanup frees ub_dev.
468 static spinlock_t *ub_next_lock(void)
473 spin_lock_irqsave(&ub_lock, flags);
474 ret = &ub_qlockv[ub_qlock_next];
475 ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
476 spin_unlock_irqrestore(&ub_lock, flags);
481 * Downcount for deallocation. This rides on two assumptions:
482 * - once something is poisoned, its refcount cannot grow
483 * - opens cannot happen at this time (del_gendisk was done)
484 * If the above is true, we can drop the lock, which we need for
485 * blk_cleanup_queue(): the silly thing may attempt to sleep.
486 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
488 static void ub_put(struct ub_dev *sc)
492 spin_lock_irqsave(&ub_lock, flags);
494 if (sc->openc == 0 && atomic_read(&sc->poison)) {
495 spin_unlock_irqrestore(&ub_lock, flags);
498 spin_unlock_irqrestore(&ub_lock, flags);
503 * Final cleanup and deallocation.
505 static void ub_cleanup(struct ub_dev *sc)
509 struct request_queue *q;
511 while (!list_empty(&sc->luns)) {
513 lun = list_entry(p, struct ub_lun, link);
516 /* I don't think queue can be NULL. But... Stolen from sx8.c */
517 if ((q = lun->disk->queue) != NULL)
518 blk_cleanup_queue(q);
520 * If we zero disk->private_data BEFORE put_disk, we have
521 * to check for NULL all over the place in open, release,
522 * check_media and revalidate, because the block level
523 * semaphore is well inside the put_disk.
524 * But we cannot zero after the call, because *disk is gone.
525 * The sd.c is blatantly racy in this area.
527 /* disk->private_data = NULL; */
535 usb_set_intfdata(sc->intf, NULL);
536 usb_put_intf(sc->intf);
537 usb_put_dev(sc->dev);
542 * The "command allocator".
544 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
546 struct ub_scsi_cmd *ret;
555 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
557 if (cmd != &lun->cmdv[0]) {
558 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
563 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
572 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
574 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
576 if (t->qlen++ == 0) {
584 if (t->qlen > t->qmax)
588 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
590 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
592 if (t->qlen++ == 0) {
600 if (t->qlen > t->qmax)
604 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
606 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
607 struct ub_scsi_cmd *cmd;
619 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
622 * The request function is our main entry point
625 static void ub_request_fn(struct request_queue *q)
627 struct ub_lun *lun = q->queuedata;
630 while ((rq = blk_peek_request(q)) != NULL) {
631 if (ub_request_fn_1(lun, rq) != 0) {
638 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
640 struct ub_dev *sc = lun->udev;
641 struct ub_scsi_cmd *cmd;
642 struct ub_request *urq;
645 if (atomic_read(&sc->poison)) {
646 blk_start_request(rq);
647 ub_end_rq(rq, DID_NO_CONNECT << 16);
651 if (lun->changed && !blk_pc_request(rq)) {
652 blk_start_request(rq);
653 ub_end_rq(rq, SAM_STAT_CHECK_CONDITION);
657 if (lun->urq.rq != NULL)
659 if ((cmd = ub_get_cmd(lun)) == NULL)
661 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
663 blk_start_request(rq);
666 memset(urq, 0, sizeof(struct ub_request));
670 * get scatterlist from block layer
672 sg_init_table(&urq->sgv[0], UB_MAX_REQ_SG);
673 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
675 /* Impossible, because blk_rq_map_sg should not hit ENOMEM. */
676 printk(KERN_INFO "%s: failed request map (%d)\n",
680 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
681 printk(KERN_WARNING "%s: request with %d segments\n",
687 if (blk_pc_request(rq)) {
688 ub_cmd_build_packet(sc, lun, cmd, urq);
690 ub_cmd_build_block(sc, lun, cmd, urq);
692 cmd->state = UB_CMDST_INIT;
694 cmd->done = ub_rw_cmd_done;
697 cmd->tag = sc->tagcnt++;
698 if (ub_submit_scsi(sc, cmd) != 0)
704 ub_put_cmd(lun, cmd);
705 ub_end_rq(rq, DID_ERROR << 16);
709 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
710 struct ub_scsi_cmd *cmd, struct ub_request *urq)
712 struct request *rq = urq->rq;
713 unsigned int block, nblks;
715 if (rq_data_dir(rq) == WRITE)
716 cmd->dir = UB_DIR_WRITE;
718 cmd->dir = UB_DIR_READ;
721 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
726 * The call to blk_queue_logical_block_size() guarantees that request
727 * is aligned, but it is given in terms of 512 byte units, always.
729 block = blk_rq_pos(rq) >> lun->capacity.bshift;
730 nblks = blk_rq_sectors(rq) >> lun->capacity.bshift;
732 cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
733 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
734 cmd->cdb[2] = block >> 24;
735 cmd->cdb[3] = block >> 16;
736 cmd->cdb[4] = block >> 8;
738 cmd->cdb[7] = nblks >> 8;
742 cmd->len = blk_rq_bytes(rq);
745 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
746 struct ub_scsi_cmd *cmd, struct ub_request *urq)
748 struct request *rq = urq->rq;
750 if (blk_rq_bytes(rq) == 0) {
751 cmd->dir = UB_DIR_NONE;
753 if (rq_data_dir(rq) == WRITE)
754 cmd->dir = UB_DIR_WRITE;
756 cmd->dir = UB_DIR_READ;
760 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
762 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
763 cmd->cdb_len = rq->cmd_len;
765 cmd->len = blk_rq_bytes(rq);
768 * To reapply this to every URB is not as incorrect as it looks.
769 * In return, we avoid any complicated tracking calculations.
771 cmd->timeo = rq->timeout;
774 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
776 struct ub_lun *lun = cmd->lun;
777 struct ub_request *urq = cmd->back;
779 unsigned int scsi_status;
783 if (cmd->error == 0) {
784 if (blk_pc_request(rq)) {
785 if (cmd->act_len >= rq->resid_len)
788 rq->resid_len -= cmd->act_len;
791 if (cmd->act_len != cmd->len) {
792 scsi_status = SAM_STAT_CHECK_CONDITION;
798 if (blk_pc_request(rq)) {
799 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
800 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
801 rq->sense_len = UB_SENSE_SIZE;
802 if (sc->top_sense[0] != 0)
803 scsi_status = SAM_STAT_CHECK_CONDITION;
805 scsi_status = DID_ERROR << 16;
807 if (cmd->error == -EIO &&
809 cmd->key == MEDIUM_ERROR ||
810 cmd->key == UNIT_ATTENTION)) {
811 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
814 scsi_status = SAM_STAT_CHECK_CONDITION;
820 ub_put_cmd(lun, cmd);
821 ub_end_rq(rq, scsi_status);
822 blk_start_queue(lun->disk->queue);
825 static void ub_end_rq(struct request *rq, unsigned int scsi_status)
829 if (scsi_status == 0) {
833 rq->errors = scsi_status;
835 __blk_end_request_all(rq, error);
838 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
839 struct ub_request *urq, struct ub_scsi_cmd *cmd)
842 if (atomic_read(&sc->poison))
845 ub_reset_enter(sc, urq->current_try);
847 if (urq->current_try >= 3)
851 /* Remove this if anyone complains of flooding. */
852 printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
853 "[sense %x %02x %02x] retry %d\n",
854 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
855 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
857 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
858 ub_cmd_build_block(sc, lun, cmd, urq);
860 cmd->state = UB_CMDST_INIT;
862 cmd->done = ub_rw_cmd_done;
865 cmd->tag = sc->tagcnt++;
868 return ub_submit_scsi(sc, cmd);
870 ub_cmdq_add(sc, cmd);
876 * Submit a regular SCSI operation (not an auto-sense).
878 * The Iron Law of Good Submit Routine is:
879 * Zero return - callback is done, Nonzero return - callback is not done.
882 * Host is assumed locked.
884 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
887 if (cmd->state != UB_CMDST_INIT ||
888 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
892 ub_cmdq_add(sc, cmd);
894 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
895 * safer to jump to a tasklet, in case upper layers do something silly.
897 tasklet_schedule(&sc->tasklet);
902 * Submit the first URB for the queued command.
903 * This function does not deal with queueing in any way.
905 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
907 struct bulk_cb_wrap *bcb;
913 * ``If the allocation length is eighteen or greater, and a device
914 * server returns less than eithteen bytes of data, the application
915 * client should assume that the bytes not transferred would have been
916 * zeroes had the device server returned those bytes.''
918 * We zero sense for all commands so that when a packet request
919 * fails it does not return a stale sense.
921 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
923 /* set up the command wrapper */
924 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
925 bcb->Tag = cmd->tag; /* Endianness is not important */
926 bcb->DataTransferLength = cpu_to_le32(cmd->len);
927 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
928 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
929 bcb->Length = cmd->cdb_len;
931 /* copy the command payload */
932 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
934 UB_INIT_COMPLETION(sc->work_done);
936 sc->last_pipe = sc->send_bulk_pipe;
937 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
938 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
940 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
941 /* XXX Clear stalls */
942 ub_complete(&sc->work_done);
946 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
947 add_timer(&sc->work_timer);
949 cmd->state = UB_CMDST_CMD;
956 static void ub_urb_timeout(unsigned long arg)
958 struct ub_dev *sc = (struct ub_dev *) arg;
961 spin_lock_irqsave(sc->lock, flags);
962 if (!ub_is_completed(&sc->work_done))
963 usb_unlink_urb(&sc->work_urb);
964 spin_unlock_irqrestore(sc->lock, flags);
968 * Completion routine for the work URB.
970 * This can be called directly from usb_submit_urb (while we have
971 * the sc->lock taken) and from an interrupt (while we do NOT have
972 * the sc->lock taken). Therefore, bounce this off to a tasklet.
974 static void ub_urb_complete(struct urb *urb)
976 struct ub_dev *sc = urb->context;
978 ub_complete(&sc->work_done);
979 tasklet_schedule(&sc->tasklet);
982 static void ub_scsi_action(unsigned long _dev)
984 struct ub_dev *sc = (struct ub_dev *) _dev;
987 spin_lock_irqsave(sc->lock, flags);
988 ub_scsi_dispatch(sc);
989 spin_unlock_irqrestore(sc->lock, flags);
992 static void ub_scsi_dispatch(struct ub_dev *sc)
994 struct ub_scsi_cmd *cmd;
997 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
998 if (cmd->state == UB_CMDST_DONE) {
1000 (*cmd->done)(sc, cmd);
1001 } else if (cmd->state == UB_CMDST_INIT) {
1002 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1005 cmd->state = UB_CMDST_DONE;
1007 if (!ub_is_completed(&sc->work_done))
1009 del_timer(&sc->work_timer);
1010 ub_scsi_urb_compl(sc, cmd);
1015 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1017 struct urb *urb = &sc->work_urb;
1018 struct bulk_cs_wrap *bcs;
1023 if (atomic_read(&sc->poison)) {
1024 ub_state_done(sc, cmd, -ENODEV);
1028 endp = usb_pipeendpoint(sc->last_pipe);
1029 if (usb_pipein(sc->last_pipe))
1032 if (cmd->state == UB_CMDST_CLEAR) {
1033 if (urb->status == -EPIPE) {
1035 * STALL while clearning STALL.
1036 * The control pipe clears itself - nothing to do.
1038 printk(KERN_NOTICE "%s: stall on control pipe\n",
1044 * We ignore the result for the halt clear.
1047 usb_reset_endpoint(sc->dev, endp);
1049 ub_state_sense(sc, cmd);
1051 } else if (cmd->state == UB_CMDST_CLR2STS) {
1052 if (urb->status == -EPIPE) {
1053 printk(KERN_NOTICE "%s: stall on control pipe\n",
1059 * We ignore the result for the halt clear.
1062 usb_reset_endpoint(sc->dev, endp);
1064 ub_state_stat(sc, cmd);
1066 } else if (cmd->state == UB_CMDST_CLRRS) {
1067 if (urb->status == -EPIPE) {
1068 printk(KERN_NOTICE "%s: stall on control pipe\n",
1074 * We ignore the result for the halt clear.
1077 usb_reset_endpoint(sc->dev, endp);
1079 ub_state_stat_counted(sc, cmd);
1081 } else if (cmd->state == UB_CMDST_CMD) {
1082 switch (urb->status) {
1088 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1090 printk(KERN_NOTICE "%s: "
1091 "unable to submit clear (%d)\n",
1094 * This is typically ENOMEM or some other such shit.
1095 * Retrying is pointless. Just do Bad End on it...
1097 ub_state_done(sc, cmd, rc);
1100 cmd->state = UB_CMDST_CLEAR;
1102 case -ESHUTDOWN: /* unplug */
1103 case -EILSEQ: /* unplug timeout on uhci */
1104 ub_state_done(sc, cmd, -ENODEV);
1109 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1113 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1114 ub_state_stat(sc, cmd);
1118 // udelay(125); // usb-storage has this
1119 ub_data_start(sc, cmd);
1121 } else if (cmd->state == UB_CMDST_DATA) {
1122 if (urb->status == -EPIPE) {
1123 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1125 printk(KERN_NOTICE "%s: "
1126 "unable to submit clear (%d)\n",
1128 ub_state_done(sc, cmd, rc);
1131 cmd->state = UB_CMDST_CLR2STS;
1134 if (urb->status == -EOVERFLOW) {
1136 * A babble? Failure, but we must transfer CSW now.
1138 cmd->error = -EOVERFLOW; /* A cheap trick... */
1139 ub_state_stat(sc, cmd);
1143 if (cmd->dir == UB_DIR_WRITE) {
1145 * Do not continue writes in case of a failure.
1146 * Doing so would cause sectors to be mixed up,
1147 * which is worse than sectors lost.
1149 * We must try to read the CSW, or many devices
1152 len = urb->actual_length;
1153 if (urb->status != 0 ||
1154 len != cmd->sgv[cmd->current_sg].length) {
1155 cmd->act_len += len;
1158 ub_state_stat(sc, cmd);
1164 * If an error occurs on read, we record it, and
1165 * continue to fetch data in order to avoid bubble.
1167 * As a small shortcut, we stop if we detect that
1168 * a CSW mixed into data.
1170 if (urb->status != 0)
1173 len = urb->actual_length;
1174 if (urb->status != 0 ||
1175 len != cmd->sgv[cmd->current_sg].length) {
1176 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1181 cmd->act_len += urb->actual_length;
1183 if (++cmd->current_sg < cmd->nsg) {
1184 ub_data_start(sc, cmd);
1187 ub_state_stat(sc, cmd);
1189 } else if (cmd->state == UB_CMDST_STAT) {
1190 if (urb->status == -EPIPE) {
1191 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1193 printk(KERN_NOTICE "%s: "
1194 "unable to submit clear (%d)\n",
1196 ub_state_done(sc, cmd, rc);
1201 * Having a stall when getting CSW is an error, so
1202 * make sure uppper levels are not oblivious to it.
1204 cmd->error = -EIO; /* A cheap trick... */
1206 cmd->state = UB_CMDST_CLRRS;
1210 /* Catch everything, including -EOVERFLOW and other nasties. */
1211 if (urb->status != 0)
1214 if (urb->actual_length == 0) {
1215 ub_state_stat_counted(sc, cmd);
1220 * Check the returned Bulk protocol status.
1221 * The status block has to be validated first.
1224 bcs = &sc->work_bcs;
1226 if (sc->signature == cpu_to_le32(0)) {
1228 * This is the first reply, so do not perform the check.
1229 * Instead, remember the signature the device uses
1230 * for future checks. But do not allow a nul.
1232 sc->signature = bcs->Signature;
1233 if (sc->signature == cpu_to_le32(0)) {
1234 ub_state_stat_counted(sc, cmd);
1238 if (bcs->Signature != sc->signature) {
1239 ub_state_stat_counted(sc, cmd);
1244 if (bcs->Tag != cmd->tag) {
1246 * This usually happens when we disagree with the
1247 * device's microcode about something. For instance,
1248 * a few of them throw this after timeouts. They buffer
1249 * commands and reply at commands we timed out before.
1250 * Without flushing these replies we loop forever.
1252 ub_state_stat_counted(sc, cmd);
1256 if (!sc->bad_resid) {
1257 len = le32_to_cpu(bcs->Residue);
1258 if (len != cmd->len - cmd->act_len) {
1260 * Only start ignoring if this cmd ended well.
1262 if (cmd->len == cmd->act_len) {
1263 printk(KERN_NOTICE "%s: "
1264 "bad residual %d of %d, ignoring\n",
1265 sc->name, len, cmd->len);
1271 switch (bcs->Status) {
1272 case US_BULK_STAT_OK:
1274 case US_BULK_STAT_FAIL:
1275 ub_state_sense(sc, cmd);
1277 case US_BULK_STAT_PHASE:
1280 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1281 sc->name, bcs->Status);
1282 ub_state_done(sc, cmd, -EINVAL);
1286 /* Not zeroing error to preserve a babble indicator */
1287 if (cmd->error != 0) {
1288 ub_state_sense(sc, cmd);
1291 cmd->state = UB_CMDST_DONE;
1293 (*cmd->done)(sc, cmd);
1295 } else if (cmd->state == UB_CMDST_SENSE) {
1296 ub_state_done(sc, cmd, -EIO);
1299 printk(KERN_WARNING "%s: wrong command state %d\n",
1300 sc->name, cmd->state);
1301 ub_state_done(sc, cmd, -EINVAL);
1306 Bad_End: /* Little Excel is dead */
1307 ub_state_done(sc, cmd, -EIO);
1311 * Factorization helper for the command state machine:
1312 * Initiate a data segment transfer.
1314 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1316 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1320 UB_INIT_COMPLETION(sc->work_done);
1322 if (cmd->dir == UB_DIR_READ)
1323 pipe = sc->recv_bulk_pipe;
1325 pipe = sc->send_bulk_pipe;
1326 sc->last_pipe = pipe;
1327 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe, sg_virt(sg),
1328 sg->length, ub_urb_complete, sc);
1330 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1331 /* XXX Clear stalls */
1332 ub_complete(&sc->work_done);
1333 ub_state_done(sc, cmd, rc);
1338 sc->work_timer.expires = jiffies + cmd->timeo;
1340 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1341 add_timer(&sc->work_timer);
1343 cmd->state = UB_CMDST_DATA;
1347 * Factorization helper for the command state machine:
1348 * Finish the command.
1350 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1354 cmd->state = UB_CMDST_DONE;
1356 (*cmd->done)(sc, cmd);
1360 * Factorization helper for the command state machine:
1361 * Submit a CSW read.
1363 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1367 UB_INIT_COMPLETION(sc->work_done);
1369 sc->last_pipe = sc->recv_bulk_pipe;
1370 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1371 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1373 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1374 /* XXX Clear stalls */
1375 ub_complete(&sc->work_done);
1376 ub_state_done(sc, cmd, rc);
1381 sc->work_timer.expires = jiffies + cmd->timeo;
1383 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1384 add_timer(&sc->work_timer);
1389 * Factorization helper for the command state machine:
1390 * Submit a CSW read and go to STAT state.
1392 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1395 if (__ub_state_stat(sc, cmd) != 0)
1398 cmd->stat_count = 0;
1399 cmd->state = UB_CMDST_STAT;
1403 * Factorization helper for the command state machine:
1404 * Submit a CSW read and go to STAT state with counter (along [C] path).
1406 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1409 if (++cmd->stat_count >= 4) {
1410 ub_state_sense(sc, cmd);
1414 if (__ub_state_stat(sc, cmd) != 0)
1417 cmd->state = UB_CMDST_STAT;
1421 * Factorization helper for the command state machine:
1422 * Submit a REQUEST SENSE and go to SENSE state.
1424 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1426 struct ub_scsi_cmd *scmd;
1427 struct scatterlist *sg;
1430 if (cmd->cdb[0] == REQUEST_SENSE) {
1435 scmd = &sc->top_rqs_cmd;
1436 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1437 scmd->cdb[0] = REQUEST_SENSE;
1438 scmd->cdb[4] = UB_SENSE_SIZE;
1440 scmd->dir = UB_DIR_READ;
1441 scmd->state = UB_CMDST_INIT;
1444 sg_init_table(sg, UB_MAX_REQ_SG);
1445 sg_set_page(sg, virt_to_page(sc->top_sense), UB_SENSE_SIZE,
1446 (unsigned long)sc->top_sense & (PAGE_SIZE-1));
1447 scmd->len = UB_SENSE_SIZE;
1448 scmd->lun = cmd->lun;
1449 scmd->done = ub_top_sense_done;
1452 scmd->tag = sc->tagcnt++;
1454 cmd->state = UB_CMDST_SENSE;
1456 ub_cmdq_insert(sc, scmd);
1460 ub_state_done(sc, cmd, rc);
1464 * A helper for the command's state machine:
1465 * Submit a stall clear.
1467 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1471 struct usb_ctrlrequest *cr;
1474 endp = usb_pipeendpoint(stalled_pipe);
1475 if (usb_pipein (stalled_pipe))
1479 cr->bRequestType = USB_RECIP_ENDPOINT;
1480 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1481 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1482 cr->wIndex = cpu_to_le16(endp);
1483 cr->wLength = cpu_to_le16(0);
1485 UB_INIT_COMPLETION(sc->work_done);
1487 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1488 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1490 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1491 ub_complete(&sc->work_done);
1495 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1496 add_timer(&sc->work_timer);
1502 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1504 unsigned char *sense = sc->top_sense;
1505 struct ub_scsi_cmd *cmd;
1508 * Find the command which triggered the unit attention or a check,
1509 * save the sense into it, and advance its state machine.
1511 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1512 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1515 if (cmd != scmd->back) {
1516 printk(KERN_WARNING "%s: "
1517 "sense done for wrong command 0x%x\n",
1518 sc->name, cmd->tag);
1521 if (cmd->state != UB_CMDST_SENSE) {
1522 printk(KERN_WARNING "%s: sense done with bad cmd state %d\n",
1523 sc->name, cmd->state);
1528 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1530 cmd->key = sense[2] & 0x0F;
1531 cmd->asc = sense[12];
1532 cmd->ascq = sense[13];
1534 ub_scsi_urb_compl(sc, cmd);
1541 static void ub_reset_enter(struct ub_dev *sc, int try)
1545 /* This happens often on multi-LUN devices. */
1548 sc->reset = try + 1;
1550 #if 0 /* Not needed because the disconnect waits for us. */
1551 unsigned long flags;
1552 spin_lock_irqsave(&ub_lock, flags);
1554 spin_unlock_irqrestore(&ub_lock, flags);
1557 #if 0 /* We let them stop themselves. */
1559 list_for_each_entry(lun, &sc->luns, link) {
1560 blk_stop_queue(lun->disk->queue);
1564 schedule_work(&sc->reset_work);
1567 static void ub_reset_task(struct work_struct *work)
1569 struct ub_dev *sc = container_of(work, struct ub_dev, reset_work);
1570 unsigned long flags;
1575 printk(KERN_WARNING "%s: Running reset unrequested\n",
1580 if (atomic_read(&sc->poison)) {
1582 } else if ((sc->reset & 1) == 0) {
1584 msleep(700); /* usb-storage sleeps 6s (!) */
1585 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1586 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1587 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1590 rc = usb_lock_device_for_reset(sc->dev, sc->intf);
1593 "%s: usb_lock_device_for_reset failed (%d)\n",
1596 rc = usb_reset_device(sc->dev);
1598 printk(KERN_NOTICE "%s: "
1599 "usb_lock_device_for_reset failed (%d)\n",
1602 usb_unlock_device(sc->dev);
1607 * In theory, no commands can be running while reset is active,
1608 * so nobody can ask for another reset, and so we do not need any
1609 * queues of resets or anything. We do need a spinlock though,
1610 * to interact with block layer.
1612 spin_lock_irqsave(sc->lock, flags);
1614 tasklet_schedule(&sc->tasklet);
1615 list_for_each_entry(lun, &sc->luns, link) {
1616 blk_start_queue(lun->disk->queue);
1618 wake_up(&sc->reset_wait);
1619 spin_unlock_irqrestore(sc->lock, flags);
1623 * XXX Reset brackets are too much hassle to implement, so just stub them
1624 * in order to prevent forced unbinding (which deadlocks solid when our
1625 * ->disconnect method waits for the reset to complete and this kills keventd).
1627 * XXX Tell Alan to move usb_unlock_device inside of usb_reset_device,
1628 * or else the post_reset is invoked, and restats I/O on a locked device.
1630 static int ub_pre_reset(struct usb_interface *iface) {
1634 static int ub_post_reset(struct usb_interface *iface) {
1639 * This is called from a process context.
1641 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1644 lun->readonly = 0; /* XXX Query this from the device */
1646 lun->capacity.nsec = 0;
1647 lun->capacity.bsize = 512;
1648 lun->capacity.bshift = 0;
1650 if (ub_sync_tur(sc, lun) != 0)
1651 return; /* Not ready */
1654 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1656 * The retry here means something is wrong, either with the
1657 * device, with the transport, or with our code.
1658 * We keep this because sd.c has retries for capacity.
1660 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1661 lun->capacity.nsec = 0;
1662 lun->capacity.bsize = 512;
1663 lun->capacity.bshift = 0;
1670 * This is mostly needed to keep refcounting, but also to support
1671 * media checks on removable media drives.
1673 static int ub_bd_open(struct block_device *bdev, fmode_t mode)
1675 struct ub_lun *lun = bdev->bd_disk->private_data;
1676 struct ub_dev *sc = lun->udev;
1677 unsigned long flags;
1680 spin_lock_irqsave(&ub_lock, flags);
1681 if (atomic_read(&sc->poison)) {
1682 spin_unlock_irqrestore(&ub_lock, flags);
1686 spin_unlock_irqrestore(&ub_lock, flags);
1688 if (lun->removable || lun->readonly)
1689 check_disk_change(bdev);
1692 * The sd.c considers ->media_present and ->changed not equivalent,
1693 * under some pretty murky conditions (a failure of READ CAPACITY).
1694 * We may need it one day.
1696 if (lun->removable && lun->changed && !(mode & FMODE_NDELAY)) {
1701 if (lun->readonly && (mode & FMODE_WRITE)) {
1715 static int ub_bd_release(struct gendisk *disk, fmode_t mode)
1717 struct ub_lun *lun = disk->private_data;
1718 struct ub_dev *sc = lun->udev;
1725 * The ioctl interface.
1727 static int ub_bd_ioctl(struct block_device *bdev, fmode_t mode,
1728 unsigned int cmd, unsigned long arg)
1730 struct gendisk *disk = bdev->bd_disk;
1731 void __user *usermem = (void __user *) arg;
1733 return scsi_cmd_ioctl(disk->queue, disk, mode, cmd, usermem);
1737 * This is called by check_disk_change if we reported a media change.
1738 * The main onjective here is to discover the features of the media such as
1739 * the capacity, read-only status, etc. USB storage generally does not
1740 * need to be spun up, but if we needed it, this would be the place.
1742 * This call can sleep.
1744 * The return code is not used.
1746 static int ub_bd_revalidate(struct gendisk *disk)
1748 struct ub_lun *lun = disk->private_data;
1750 ub_revalidate(lun->udev, lun);
1752 /* XXX Support sector size switching like in sr.c */
1753 blk_queue_logical_block_size(disk->queue, lun->capacity.bsize);
1754 set_capacity(disk, lun->capacity.nsec);
1755 // set_disk_ro(sdkp->disk, lun->readonly);
1761 * The check is called by the block layer to verify if the media
1762 * is still available. It is supposed to be harmless, lightweight and
1763 * non-intrusive in case the media was not changed.
1765 * This call can sleep.
1767 * The return code is bool!
1769 static int ub_bd_media_changed(struct gendisk *disk)
1771 struct ub_lun *lun = disk->private_data;
1773 if (!lun->removable)
1777 * We clean checks always after every command, so this is not
1778 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1779 * the device is actually not ready with operator or software
1780 * intervention required. One dangerous item might be a drive which
1781 * spins itself down, and come the time to write dirty pages, this
1782 * will fail, then block layer discards the data. Since we never
1783 * spin drives up, such devices simply cannot be used with ub anyway.
1785 if (ub_sync_tur(lun->udev, lun) != 0) {
1790 return lun->changed;
1793 static const struct block_device_operations ub_bd_fops = {
1794 .owner = THIS_MODULE,
1796 .release = ub_bd_release,
1797 .locked_ioctl = ub_bd_ioctl,
1798 .media_changed = ub_bd_media_changed,
1799 .revalidate_disk = ub_bd_revalidate,
1803 * Common ->done routine for commands executed synchronously.
1805 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1807 struct completion *cop = cmd->back;
1812 * Test if the device has a check condition on it, synchronously.
1814 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1816 struct ub_scsi_cmd *cmd;
1817 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1818 unsigned long flags;
1819 struct completion compl;
1822 init_completion(&compl);
1825 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1828 cmd->cdb[0] = TEST_UNIT_READY;
1830 cmd->dir = UB_DIR_NONE;
1831 cmd->state = UB_CMDST_INIT;
1832 cmd->lun = lun; /* This may be NULL, but that's ok */
1833 cmd->done = ub_probe_done;
1836 spin_lock_irqsave(sc->lock, flags);
1837 cmd->tag = sc->tagcnt++;
1839 rc = ub_submit_scsi(sc, cmd);
1840 spin_unlock_irqrestore(sc->lock, flags);
1845 wait_for_completion(&compl);
1849 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1859 * Read the SCSI capacity synchronously (for probing).
1861 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1862 struct ub_capacity *ret)
1864 struct ub_scsi_cmd *cmd;
1865 struct scatterlist *sg;
1867 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1868 unsigned long flags;
1869 unsigned int bsize, shift;
1871 struct completion compl;
1874 init_completion(&compl);
1877 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1879 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1883 cmd->dir = UB_DIR_READ;
1884 cmd->state = UB_CMDST_INIT;
1887 sg_init_table(sg, UB_MAX_REQ_SG);
1888 sg_set_page(sg, virt_to_page(p), 8, (unsigned long)p & (PAGE_SIZE-1));
1891 cmd->done = ub_probe_done;
1894 spin_lock_irqsave(sc->lock, flags);
1895 cmd->tag = sc->tagcnt++;
1897 rc = ub_submit_scsi(sc, cmd);
1898 spin_unlock_irqrestore(sc->lock, flags);
1903 wait_for_completion(&compl);
1905 if (cmd->error != 0) {
1909 if (cmd->act_len != 8) {
1914 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1915 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1916 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1918 case 512: shift = 0; break;
1919 case 1024: shift = 1; break;
1920 case 2048: shift = 2; break;
1921 case 4096: shift = 3; break;
1928 ret->bshift = shift;
1929 ret->nsec = nsec << shift;
1942 static void ub_probe_urb_complete(struct urb *urb)
1944 struct completion *cop = urb->context;
1948 static void ub_probe_timeout(unsigned long arg)
1950 struct completion *cop = (struct completion *) arg;
1955 * Reset with a Bulk reset.
1957 static int ub_sync_reset(struct ub_dev *sc)
1959 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1960 struct usb_ctrlrequest *cr;
1961 struct completion compl;
1962 struct timer_list timer;
1965 init_completion(&compl);
1968 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1969 cr->bRequest = US_BULK_RESET_REQUEST;
1970 cr->wValue = cpu_to_le16(0);
1971 cr->wIndex = cpu_to_le16(ifnum);
1972 cr->wLength = cpu_to_le16(0);
1974 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1975 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1977 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1979 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1984 timer.function = ub_probe_timeout;
1985 timer.data = (unsigned long) &compl;
1986 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1989 wait_for_completion(&compl);
1991 del_timer_sync(&timer);
1992 usb_kill_urb(&sc->work_urb);
1994 return sc->work_urb.status;
1998 * Get number of LUNs by the way of Bulk GetMaxLUN command.
2000 static int ub_sync_getmaxlun(struct ub_dev *sc)
2002 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2004 enum { ALLOC_SIZE = 1 };
2005 struct usb_ctrlrequest *cr;
2006 struct completion compl;
2007 struct timer_list timer;
2011 init_completion(&compl);
2014 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2019 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2020 cr->bRequest = US_BULK_GET_MAX_LUN;
2021 cr->wValue = cpu_to_le16(0);
2022 cr->wIndex = cpu_to_le16(ifnum);
2023 cr->wLength = cpu_to_le16(1);
2025 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2026 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2028 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2032 timer.function = ub_probe_timeout;
2033 timer.data = (unsigned long) &compl;
2034 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2037 wait_for_completion(&compl);
2039 del_timer_sync(&timer);
2040 usb_kill_urb(&sc->work_urb);
2042 if ((rc = sc->work_urb.status) < 0)
2045 if (sc->work_urb.actual_length != 1) {
2048 if ((nluns = *p) == 55) {
2051 /* GetMaxLUN returns the maximum LUN number */
2053 if (nluns > UB_MAX_LUNS)
2054 nluns = UB_MAX_LUNS;
2069 * Clear initial stalls.
2071 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2074 struct usb_ctrlrequest *cr;
2075 struct completion compl;
2076 struct timer_list timer;
2079 init_completion(&compl);
2081 endp = usb_pipeendpoint(stalled_pipe);
2082 if (usb_pipein (stalled_pipe))
2086 cr->bRequestType = USB_RECIP_ENDPOINT;
2087 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2088 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2089 cr->wIndex = cpu_to_le16(endp);
2090 cr->wLength = cpu_to_le16(0);
2092 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2093 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2095 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2097 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2102 timer.function = ub_probe_timeout;
2103 timer.data = (unsigned long) &compl;
2104 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2107 wait_for_completion(&compl);
2109 del_timer_sync(&timer);
2110 usb_kill_urb(&sc->work_urb);
2112 usb_reset_endpoint(sc->dev, endp);
2118 * Get the pipe settings.
2120 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2121 struct usb_interface *intf)
2123 struct usb_host_interface *altsetting = intf->cur_altsetting;
2124 struct usb_endpoint_descriptor *ep_in = NULL;
2125 struct usb_endpoint_descriptor *ep_out = NULL;
2126 struct usb_endpoint_descriptor *ep;
2130 * Find the endpoints we need.
2131 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2132 * We will ignore any others.
2134 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2135 ep = &altsetting->endpoint[i].desc;
2137 /* Is it a BULK endpoint? */
2138 if (usb_endpoint_xfer_bulk(ep)) {
2139 /* BULK in or out? */
2140 if (usb_endpoint_dir_in(ep)) {
2150 if (ep_in == NULL || ep_out == NULL) {
2151 printk(KERN_NOTICE "%s: failed endpoint check\n", sc->name);
2155 /* Calculate and store the pipe values */
2156 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2157 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2158 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2159 usb_endpoint_num(ep_out));
2160 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2161 usb_endpoint_num(ep_in));
2167 * Probing is done in the process context, which allows us to cheat
2168 * and not to build a state machine for the discovery.
2170 static int ub_probe(struct usb_interface *intf,
2171 const struct usb_device_id *dev_id)
2178 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2182 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2184 sc->lock = ub_next_lock();
2185 INIT_LIST_HEAD(&sc->luns);
2186 usb_init_urb(&sc->work_urb);
2187 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2188 atomic_set(&sc->poison, 0);
2189 INIT_WORK(&sc->reset_work, ub_reset_task);
2190 init_waitqueue_head(&sc->reset_wait);
2192 init_timer(&sc->work_timer);
2193 sc->work_timer.data = (unsigned long) sc;
2194 sc->work_timer.function = ub_urb_timeout;
2196 ub_init_completion(&sc->work_done);
2197 sc->work_done.done = 1; /* A little yuk, but oh well... */
2199 sc->dev = interface_to_usbdev(intf);
2201 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2202 usb_set_intfdata(intf, sc);
2203 usb_get_dev(sc->dev);
2205 * Since we give the interface struct to the block level through
2206 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2207 * oopses on close after a disconnect (kernels 2.6.16 and up).
2209 usb_get_intf(sc->intf);
2211 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2212 sc->dev->bus->busnum, sc->dev->devnum);
2214 /* XXX Verify that we can handle the device (from descriptors) */
2216 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2220 * At this point, all USB initialization is done, do upper layer.
2221 * We really hate halfway initialized structures, so from the
2222 * invariants perspective, this ub_dev is fully constructed at
2227 * This is needed to clear toggles. It is a problem only if we do
2228 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2230 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2231 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2232 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2236 * The way this is used by the startup code is a little specific.
2237 * A SCSI check causes a USB stall. Our common case code sees it
2238 * and clears the check, after which the device is ready for use.
2239 * But if a check was not present, any command other than
2240 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2242 * If we neglect to clear the SCSI check, the first real command fails
2243 * (which is the capacity readout). We clear that and retry, but why
2244 * causing spurious retries for no reason.
2246 * Revalidation may start with its own TEST_UNIT_READY, but that one
2247 * has to succeed, so we clear checks with an additional one here.
2248 * In any case it's not our business how revaliadation is implemented.
2250 for (i = 0; i < 3; i++) { /* Retries for the schwag key from KS'04 */
2251 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2252 if (rc != 0x6) break;
2257 for (i = 0; i < 3; i++) {
2258 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2267 for (i = 0; i < nluns; i++) {
2268 ub_probe_lun(sc, i);
2273 usb_set_intfdata(intf, NULL);
2274 usb_put_intf(sc->intf);
2275 usb_put_dev(sc->dev);
2281 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2284 struct request_queue *q;
2285 struct gendisk *disk;
2289 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2294 if ((lun->id = ub_id_get()) == -1)
2299 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2300 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2302 lun->removable = 1; /* XXX Query this from the device */
2303 lun->changed = 1; /* ub_revalidate clears only */
2304 ub_revalidate(sc, lun);
2307 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2310 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2311 disk->major = UB_MAJOR;
2312 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2313 disk->fops = &ub_bd_fops;
2314 disk->private_data = lun;
2315 disk->driverfs_dev = &sc->intf->dev;
2318 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2323 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2324 blk_queue_max_segments(q, UB_MAX_REQ_SG);
2325 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2326 blk_queue_max_hw_sectors(q, UB_MAX_SECTORS);
2327 blk_queue_logical_block_size(q, lun->capacity.bsize);
2331 list_add(&lun->link, &sc->luns);
2333 set_capacity(disk, lun->capacity.nsec);
2335 disk->flags |= GENHD_FL_REMOVABLE;
2351 static void ub_disconnect(struct usb_interface *intf)
2353 struct ub_dev *sc = usb_get_intfdata(intf);
2355 unsigned long flags;
2358 * Prevent ub_bd_release from pulling the rug from under us.
2359 * XXX This is starting to look like a kref.
2360 * XXX Why not to take this ref at probe time?
2362 spin_lock_irqsave(&ub_lock, flags);
2364 spin_unlock_irqrestore(&ub_lock, flags);
2367 * Fence stall clearings, operations triggered by unlinkings and so on.
2368 * We do not attempt to unlink any URBs, because we do not trust the
2369 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2371 atomic_set(&sc->poison, 1);
2374 * Wait for reset to end, if any.
2376 wait_event(sc->reset_wait, !sc->reset);
2379 * Blow away queued commands.
2381 * Actually, this never works, because before we get here
2382 * the HCD terminates outstanding URB(s). It causes our
2383 * SCSI command queue to advance, commands fail to submit,
2384 * and the whole queue drains. So, we just use this code to
2387 spin_lock_irqsave(sc->lock, flags);
2389 struct ub_scsi_cmd *cmd;
2391 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2392 cmd->error = -ENOTCONN;
2393 cmd->state = UB_CMDST_DONE;
2395 (*cmd->done)(sc, cmd);
2399 printk(KERN_WARNING "%s: "
2400 "%d was queued after shutdown\n", sc->name, cnt);
2403 spin_unlock_irqrestore(sc->lock, flags);
2406 * Unregister the upper layer.
2408 list_for_each_entry(lun, &sc->luns, link) {
2409 del_gendisk(lun->disk);
2411 * I wish I could do:
2412 * queue_flag_set(QUEUE_FLAG_DEAD, q);
2413 * As it is, we rely on our internal poisoning and let
2414 * the upper levels to spin furiously failing all the I/O.
2419 * Testing for -EINPROGRESS is always a bug, so we are bending
2420 * the rules a little.
2422 spin_lock_irqsave(sc->lock, flags);
2423 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2424 printk(KERN_WARNING "%s: "
2425 "URB is active after disconnect\n", sc->name);
2427 spin_unlock_irqrestore(sc->lock, flags);
2430 * There is virtually no chance that other CPU runs a timeout so long
2431 * after ub_urb_complete should have called del_timer, but only if HCD
2432 * didn't forget to deliver a callback on unlink.
2434 del_timer_sync(&sc->work_timer);
2437 * At this point there must be no commands coming from anyone
2438 * and no URBs left in transit.
2444 static struct usb_driver ub_driver = {
2447 .disconnect = ub_disconnect,
2448 .id_table = ub_usb_ids,
2449 .pre_reset = ub_pre_reset,
2450 .post_reset = ub_post_reset,
2453 static int __init ub_init(void)
2458 for (i = 0; i < UB_QLOCK_NUM; i++)
2459 spin_lock_init(&ub_qlockv[i]);
2461 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2464 if ((rc = usb_register(&ub_driver)) != 0)
2467 usb_usual_set_present(USB_US_TYPE_UB);
2471 unregister_blkdev(UB_MAJOR, DRV_NAME);
2476 static void __exit ub_exit(void)
2478 usb_deregister(&ub_driver);
2480 unregister_blkdev(UB_MAJOR, DRV_NAME);
2481 usb_usual_clear_present(USB_US_TYPE_UB);
2484 module_init(ub_init);
2485 module_exit(ub_exit);
2487 MODULE_LICENSE("GPL");