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 <scsi/scsi.h>
37 * The command state machine is the key model for understanding of this driver.
39 * The general rule is that all transitions are done towards the bottom
40 * of the diagram, thus preventing any loops.
42 * An exception to that is how the STAT state is handled. A counter allows it
43 * to be re-entered along the path marked with [C].
49 * ub_scsi_cmd_start fails ->--------------------------------------\
56 * was -EPIPE -->-------------------------------->! CLEAR ! !
59 * was error -->------------------------------------- ! --------->\
61 * /--<-- cmd->dir == NONE ? ! !
68 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
71 * ! ! was error -->---- ! --------->\
72 * ! was error -->--------------------- ! ------------- ! --------->\
75 * \--->+--------+ ! ! !
76 * ! STAT !<--------------------------/ ! !
79 * [C] was -EPIPE -->-----------\ ! !
81 * +<---- len == 0 ! ! !
83 * ! was error -->--------------------------------------!---------->\
85 * +<---- bad CSW ! ! !
86 * +<---- bad tag ! ! !
92 * \------- ! --------------------[C]--------\ ! !
94 * cmd->error---\ +--------+ ! !
95 * ! +--------------->! SENSE !<----------/ !
96 * STAT_FAIL----/ +--------+ !
99 * \--------------------------------\--------------------->! DONE !
104 * This many LUNs per USB device.
105 * Every one of them takes a host, see UB_MAX_HOSTS.
107 #define UB_MAX_LUNS 9
112 #define UB_PARTS_PER_LUN 8
114 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
116 #define UB_SENSE_SIZE 18
121 /* command block wrapper */
122 struct bulk_cb_wrap {
123 __le32 Signature; /* contains 'USBC' */
124 u32 Tag; /* unique per command id */
125 __le32 DataTransferLength; /* size of data */
126 u8 Flags; /* direction in bit 0 */
128 u8 Length; /* of of the CDB */
129 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
132 #define US_BULK_CB_WRAP_LEN 31
133 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
134 #define US_BULK_FLAG_IN 1
135 #define US_BULK_FLAG_OUT 0
137 /* command status wrapper */
138 struct bulk_cs_wrap {
139 __le32 Signature; /* should = 'USBS' */
140 u32 Tag; /* same as original command */
141 __le32 Residue; /* amount not transferred */
142 u8 Status; /* see below */
145 #define US_BULK_CS_WRAP_LEN 13
146 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
147 #define US_BULK_STAT_OK 0
148 #define US_BULK_STAT_FAIL 1
149 #define US_BULK_STAT_PHASE 2
151 /* bulk-only class specific requests */
152 #define US_BULK_RESET_REQUEST 0xff
153 #define US_BULK_GET_MAX_LUN 0xfe
159 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
160 #define UB_MAX_SECTORS 64
163 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
164 * even if a webcam hogs the bus, but some devices need time to spin up.
166 #define UB_URB_TIMEOUT (HZ*2)
167 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
168 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
169 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
172 * An instance of a SCSI command in transit.
174 #define UB_DIR_NONE 0
175 #define UB_DIR_READ 1
176 #define UB_DIR_ILLEGAL2 2
177 #define UB_DIR_WRITE 3
179 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
180 (((c)==UB_DIR_READ)? 'r': 'n'))
182 enum ub_scsi_cmd_state {
183 UB_CMDST_INIT, /* Initial state */
184 UB_CMDST_CMD, /* Command submitted */
185 UB_CMDST_DATA, /* Data phase */
186 UB_CMDST_CLR2STS, /* Clearing before requesting status */
187 UB_CMDST_STAT, /* Status phase */
188 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
189 UB_CMDST_CLRRS, /* Clearing before retrying status */
190 UB_CMDST_SENSE, /* Sending Request Sense */
191 UB_CMDST_DONE /* Final state */
195 unsigned char cdb[UB_MAX_CDB_SIZE];
196 unsigned char cdb_len;
198 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
199 enum ub_scsi_cmd_state state;
201 struct ub_scsi_cmd *next;
203 int error; /* Return code - valid upon done */
204 unsigned int act_len; /* Return size */
205 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
207 int stat_count; /* Retries getting status. */
209 unsigned int len; /* Requested length */
210 unsigned int current_sg;
211 unsigned int nsg; /* sgv[nsg] */
212 struct scatterlist sgv[UB_MAX_REQ_SG];
215 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
221 unsigned int current_try;
222 unsigned int nsg; /* sgv[nsg] */
223 struct scatterlist sgv[UB_MAX_REQ_SG];
229 unsigned long nsec; /* Linux size - 512 byte sectors */
230 unsigned int bsize; /* Linux hardsect_size */
231 unsigned int bshift; /* Shift between 512 and hard sects */
235 * This is a direct take-off from linux/include/completion.h
236 * The difference is that I do not wait on this thing, just poll.
237 * When I want to wait (ub_probe), I just use the stock completion.
239 * Note that INIT_COMPLETION takes no lock. It is correct. But why
240 * in the bloody hell that thing takes struct instead of pointer to struct
241 * is quite beyond me. I just copied it from the stock completion.
243 struct ub_completion {
248 static inline void ub_init_completion(struct ub_completion *x)
251 spin_lock_init(&x->lock);
254 #define UB_INIT_COMPLETION(x) ((x).done = 0)
256 static void ub_complete(struct ub_completion *x)
260 spin_lock_irqsave(&x->lock, flags);
262 spin_unlock_irqrestore(&x->lock, flags);
265 static int ub_is_completed(struct ub_completion *x)
270 spin_lock_irqsave(&x->lock, flags);
272 spin_unlock_irqrestore(&x->lock, flags);
278 struct ub_scsi_cmd_queue {
280 struct ub_scsi_cmd *head, *tail;
284 * The block device instance (one per LUN).
288 struct list_head link;
289 struct gendisk *disk;
290 int id; /* Host index */
291 int num; /* LUN number */
294 int changed; /* Media was changed */
298 struct ub_request urq;
300 /* Use Ingo's mempool if or when we have more than one command. */
302 * Currently we never need more than one command for the whole device.
303 * However, giving every LUN a command is a cheap and automatic way
304 * to enforce fairness between them.
307 struct ub_scsi_cmd cmdv[1];
309 struct ub_capacity capacity;
313 * The USB device instance.
317 atomic_t poison; /* The USB device is disconnected */
318 int openc; /* protected by ub_lock! */
319 /* kref is too implicit for our taste */
320 int reset; /* Reset is running */
323 struct usb_device *dev;
324 struct usb_interface *intf;
326 struct list_head luns;
328 unsigned int send_bulk_pipe; /* cached pipe values */
329 unsigned int recv_bulk_pipe;
330 unsigned int send_ctrl_pipe;
331 unsigned int recv_ctrl_pipe;
333 struct tasklet_struct tasklet;
335 struct ub_scsi_cmd_queue cmd_queue;
336 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
337 unsigned char top_sense[UB_SENSE_SIZE];
339 struct ub_completion work_done;
341 struct timer_list work_timer;
342 int last_pipe; /* What might need clearing */
343 __le32 signature; /* Learned signature */
344 struct bulk_cb_wrap work_bcb;
345 struct bulk_cs_wrap work_bcs;
346 struct usb_ctrlrequest work_cr;
348 struct work_struct reset_work;
349 wait_queue_head_t reset_wait;
356 static void ub_cleanup(struct ub_dev *sc);
357 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
358 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
359 struct ub_scsi_cmd *cmd, struct ub_request *urq);
360 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
361 struct ub_scsi_cmd *cmd, struct ub_request *urq);
362 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
363 static void ub_end_rq(struct request *rq, unsigned int status,
364 unsigned int cmd_len);
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 storage_usb_ids
397 static 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 = elv_next_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 blkdev_dequeue_request(rq);
647 ub_end_rq(rq, DID_NO_CONNECT << 16, blk_rq_bytes(rq));
651 if (lun->changed && !blk_pc_request(rq)) {
652 blkdev_dequeue_request(rq);
653 ub_end_rq(rq, SAM_STAT_CHECK_CONDITION, blk_rq_bytes(rq));
657 if (lun->urq.rq != NULL)
659 if ((cmd = ub_get_cmd(lun)) == NULL)
661 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
663 blkdev_dequeue_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",
686 sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
688 if (blk_pc_request(rq)) {
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, blk_rq_bytes(rq));
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_hardsect_size() guarantees that request
728 * is aligned, but it is given in terms of 512 byte units, always.
730 block = rq->sector >> lun->capacity.bshift;
731 nblks = rq->nr_sectors >> 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 = rq->nr_sectors * 512;
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 (rq->data_len == 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 = rq->data_len;
769 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
771 struct ub_lun *lun = cmd->lun;
772 struct ub_request *urq = cmd->back;
774 unsigned int scsi_status;
775 unsigned int cmd_len;
779 if (cmd->error == 0) {
780 if (blk_pc_request(rq)) {
781 if (cmd->act_len >= rq->data_len)
784 rq->data_len -= cmd->act_len;
787 if (cmd->act_len != cmd->len) {
788 if ((cmd->key == MEDIUM_ERROR ||
789 cmd->key == UNIT_ATTENTION) &&
790 ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
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) {
808 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
811 scsi_status = SAM_STAT_CHECK_CONDITION;
818 ub_put_cmd(lun, cmd);
819 ub_end_rq(rq, scsi_status, cmd_len);
820 blk_start_queue(lun->disk->queue);
823 static void ub_end_rq(struct request *rq, unsigned int scsi_status,
824 unsigned int cmd_len)
829 if (scsi_status == 0) {
833 rq->errors = scsi_status;
835 rqlen = blk_rq_bytes(rq); /* Oddly enough, this is the residue. */
836 if (__blk_end_request(rq, error, cmd_len)) {
837 printk(KERN_WARNING DRV_NAME
838 ": __blk_end_request blew, %s-cmd total %u rqlen %ld\n",
839 blk_pc_request(rq)? "pc": "fs", cmd_len, rqlen);
843 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
844 struct ub_request *urq, struct ub_scsi_cmd *cmd)
847 if (atomic_read(&sc->poison))
850 ub_reset_enter(sc, urq->current_try);
852 if (urq->current_try >= 3)
856 /* Remove this if anyone complains of flooding. */
857 printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
858 "[sense %x %02x %02x] retry %d\n",
859 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
860 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
862 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
863 ub_cmd_build_block(sc, lun, cmd, urq);
865 cmd->state = UB_CMDST_INIT;
867 cmd->done = ub_rw_cmd_done;
870 cmd->tag = sc->tagcnt++;
873 return ub_submit_scsi(sc, cmd);
875 ub_cmdq_add(sc, cmd);
881 * Submit a regular SCSI operation (not an auto-sense).
883 * The Iron Law of Good Submit Routine is:
884 * Zero return - callback is done, Nonzero return - callback is not done.
887 * Host is assumed locked.
889 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
892 if (cmd->state != UB_CMDST_INIT ||
893 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
897 ub_cmdq_add(sc, cmd);
899 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
900 * safer to jump to a tasklet, in case upper layers do something silly.
902 tasklet_schedule(&sc->tasklet);
907 * Submit the first URB for the queued command.
908 * This function does not deal with queueing in any way.
910 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
912 struct bulk_cb_wrap *bcb;
918 * ``If the allocation length is eighteen or greater, and a device
919 * server returns less than eithteen bytes of data, the application
920 * client should assume that the bytes not transferred would have been
921 * zeroes had the device server returned those bytes.''
923 * We zero sense for all commands so that when a packet request
924 * fails it does not return a stale sense.
926 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
928 /* set up the command wrapper */
929 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
930 bcb->Tag = cmd->tag; /* Endianness is not important */
931 bcb->DataTransferLength = cpu_to_le32(cmd->len);
932 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
933 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
934 bcb->Length = cmd->cdb_len;
936 /* copy the command payload */
937 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
939 UB_INIT_COMPLETION(sc->work_done);
941 sc->last_pipe = sc->send_bulk_pipe;
942 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
943 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
945 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
946 /* XXX Clear stalls */
947 ub_complete(&sc->work_done);
951 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
952 add_timer(&sc->work_timer);
954 cmd->state = UB_CMDST_CMD;
961 static void ub_urb_timeout(unsigned long arg)
963 struct ub_dev *sc = (struct ub_dev *) arg;
966 spin_lock_irqsave(sc->lock, flags);
967 if (!ub_is_completed(&sc->work_done))
968 usb_unlink_urb(&sc->work_urb);
969 spin_unlock_irqrestore(sc->lock, flags);
973 * Completion routine for the work URB.
975 * This can be called directly from usb_submit_urb (while we have
976 * the sc->lock taken) and from an interrupt (while we do NOT have
977 * the sc->lock taken). Therefore, bounce this off to a tasklet.
979 static void ub_urb_complete(struct urb *urb)
981 struct ub_dev *sc = urb->context;
983 ub_complete(&sc->work_done);
984 tasklet_schedule(&sc->tasklet);
987 static void ub_scsi_action(unsigned long _dev)
989 struct ub_dev *sc = (struct ub_dev *) _dev;
992 spin_lock_irqsave(sc->lock, flags);
993 ub_scsi_dispatch(sc);
994 spin_unlock_irqrestore(sc->lock, flags);
997 static void ub_scsi_dispatch(struct ub_dev *sc)
999 struct ub_scsi_cmd *cmd;
1002 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
1003 if (cmd->state == UB_CMDST_DONE) {
1005 (*cmd->done)(sc, cmd);
1006 } else if (cmd->state == UB_CMDST_INIT) {
1007 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1010 cmd->state = UB_CMDST_DONE;
1012 if (!ub_is_completed(&sc->work_done))
1014 del_timer(&sc->work_timer);
1015 ub_scsi_urb_compl(sc, cmd);
1020 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1022 struct urb *urb = &sc->work_urb;
1023 struct bulk_cs_wrap *bcs;
1027 if (atomic_read(&sc->poison)) {
1028 ub_state_done(sc, cmd, -ENODEV);
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 /* reset the endpoint toggle */
1048 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1049 usb_pipeout(sc->last_pipe), 0);
1051 ub_state_sense(sc, cmd);
1053 } else if (cmd->state == UB_CMDST_CLR2STS) {
1054 if (urb->status == -EPIPE) {
1055 printk(KERN_NOTICE "%s: stall on control pipe\n",
1061 * We ignore the result for the halt clear.
1064 /* reset the endpoint toggle */
1065 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1066 usb_pipeout(sc->last_pipe), 0);
1068 ub_state_stat(sc, cmd);
1070 } else if (cmd->state == UB_CMDST_CLRRS) {
1071 if (urb->status == -EPIPE) {
1072 printk(KERN_NOTICE "%s: stall on control pipe\n",
1078 * We ignore the result for the halt clear.
1081 /* reset the endpoint toggle */
1082 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1083 usb_pipeout(sc->last_pipe), 0);
1085 ub_state_stat_counted(sc, cmd);
1087 } else if (cmd->state == UB_CMDST_CMD) {
1088 switch (urb->status) {
1094 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1096 printk(KERN_NOTICE "%s: "
1097 "unable to submit clear (%d)\n",
1100 * This is typically ENOMEM or some other such shit.
1101 * Retrying is pointless. Just do Bad End on it...
1103 ub_state_done(sc, cmd, rc);
1106 cmd->state = UB_CMDST_CLEAR;
1108 case -ESHUTDOWN: /* unplug */
1109 case -EILSEQ: /* unplug timeout on uhci */
1110 ub_state_done(sc, cmd, -ENODEV);
1115 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1119 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1120 ub_state_stat(sc, cmd);
1124 // udelay(125); // usb-storage has this
1125 ub_data_start(sc, cmd);
1127 } else if (cmd->state == UB_CMDST_DATA) {
1128 if (urb->status == -EPIPE) {
1129 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1131 printk(KERN_NOTICE "%s: "
1132 "unable to submit clear (%d)\n",
1134 ub_state_done(sc, cmd, rc);
1137 cmd->state = UB_CMDST_CLR2STS;
1140 if (urb->status == -EOVERFLOW) {
1142 * A babble? Failure, but we must transfer CSW now.
1144 cmd->error = -EOVERFLOW; /* A cheap trick... */
1145 ub_state_stat(sc, cmd);
1149 if (cmd->dir == UB_DIR_WRITE) {
1151 * Do not continue writes in case of a failure.
1152 * Doing so would cause sectors to be mixed up,
1153 * which is worse than sectors lost.
1155 * We must try to read the CSW, or many devices
1158 len = urb->actual_length;
1159 if (urb->status != 0 ||
1160 len != cmd->sgv[cmd->current_sg].length) {
1161 cmd->act_len += len;
1164 ub_state_stat(sc, cmd);
1170 * If an error occurs on read, we record it, and
1171 * continue to fetch data in order to avoid bubble.
1173 * As a small shortcut, we stop if we detect that
1174 * a CSW mixed into data.
1176 if (urb->status != 0)
1179 len = urb->actual_length;
1180 if (urb->status != 0 ||
1181 len != cmd->sgv[cmd->current_sg].length) {
1182 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1187 cmd->act_len += urb->actual_length;
1189 if (++cmd->current_sg < cmd->nsg) {
1190 ub_data_start(sc, cmd);
1193 ub_state_stat(sc, cmd);
1195 } else if (cmd->state == UB_CMDST_STAT) {
1196 if (urb->status == -EPIPE) {
1197 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1199 printk(KERN_NOTICE "%s: "
1200 "unable to submit clear (%d)\n",
1202 ub_state_done(sc, cmd, rc);
1207 * Having a stall when getting CSW is an error, so
1208 * make sure uppper levels are not oblivious to it.
1210 cmd->error = -EIO; /* A cheap trick... */
1212 cmd->state = UB_CMDST_CLRRS;
1216 /* Catch everything, including -EOVERFLOW and other nasties. */
1217 if (urb->status != 0)
1220 if (urb->actual_length == 0) {
1221 ub_state_stat_counted(sc, cmd);
1226 * Check the returned Bulk protocol status.
1227 * The status block has to be validated first.
1230 bcs = &sc->work_bcs;
1232 if (sc->signature == cpu_to_le32(0)) {
1234 * This is the first reply, so do not perform the check.
1235 * Instead, remember the signature the device uses
1236 * for future checks. But do not allow a nul.
1238 sc->signature = bcs->Signature;
1239 if (sc->signature == cpu_to_le32(0)) {
1240 ub_state_stat_counted(sc, cmd);
1244 if (bcs->Signature != sc->signature) {
1245 ub_state_stat_counted(sc, cmd);
1250 if (bcs->Tag != cmd->tag) {
1252 * This usually happens when we disagree with the
1253 * device's microcode about something. For instance,
1254 * a few of them throw this after timeouts. They buffer
1255 * commands and reply at commands we timed out before.
1256 * Without flushing these replies we loop forever.
1258 ub_state_stat_counted(sc, cmd);
1262 len = le32_to_cpu(bcs->Residue);
1263 if (len != cmd->len - cmd->act_len) {
1265 * It is all right to transfer less, the caller has
1266 * to check. But it's not all right if the device
1267 * counts disagree with our counts.
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: "
1301 "wrong command state %d\n",
1302 sc->name, cmd->state);
1303 ub_state_done(sc, cmd, -EINVAL);
1308 Bad_End: /* Little Excel is dead */
1309 ub_state_done(sc, cmd, -EIO);
1313 * Factorization helper for the command state machine:
1314 * Initiate a data segment transfer.
1316 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1318 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1322 UB_INIT_COMPLETION(sc->work_done);
1324 if (cmd->dir == UB_DIR_READ)
1325 pipe = sc->recv_bulk_pipe;
1327 pipe = sc->send_bulk_pipe;
1328 sc->last_pipe = pipe;
1329 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe, sg_virt(sg),
1330 sg->length, ub_urb_complete, sc);
1332 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1333 /* XXX Clear stalls */
1334 ub_complete(&sc->work_done);
1335 ub_state_done(sc, cmd, rc);
1339 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1340 add_timer(&sc->work_timer);
1342 cmd->state = UB_CMDST_DATA;
1346 * Factorization helper for the command state machine:
1347 * Finish the command.
1349 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1353 cmd->state = UB_CMDST_DONE;
1355 (*cmd->done)(sc, cmd);
1359 * Factorization helper for the command state machine:
1360 * Submit a CSW read.
1362 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1366 UB_INIT_COMPLETION(sc->work_done);
1368 sc->last_pipe = sc->recv_bulk_pipe;
1369 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1370 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1372 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1373 /* XXX Clear stalls */
1374 ub_complete(&sc->work_done);
1375 ub_state_done(sc, cmd, rc);
1379 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1380 add_timer(&sc->work_timer);
1385 * Factorization helper for the command state machine:
1386 * Submit a CSW read and go to STAT state.
1388 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1391 if (__ub_state_stat(sc, cmd) != 0)
1394 cmd->stat_count = 0;
1395 cmd->state = UB_CMDST_STAT;
1399 * Factorization helper for the command state machine:
1400 * Submit a CSW read and go to STAT state with counter (along [C] path).
1402 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1405 if (++cmd->stat_count >= 4) {
1406 ub_state_sense(sc, cmd);
1410 if (__ub_state_stat(sc, cmd) != 0)
1413 cmd->state = UB_CMDST_STAT;
1417 * Factorization helper for the command state machine:
1418 * Submit a REQUEST SENSE and go to SENSE state.
1420 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1422 struct ub_scsi_cmd *scmd;
1423 struct scatterlist *sg;
1426 if (cmd->cdb[0] == REQUEST_SENSE) {
1431 scmd = &sc->top_rqs_cmd;
1432 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1433 scmd->cdb[0] = REQUEST_SENSE;
1434 scmd->cdb[4] = UB_SENSE_SIZE;
1436 scmd->dir = UB_DIR_READ;
1437 scmd->state = UB_CMDST_INIT;
1440 sg_init_table(sg, UB_MAX_REQ_SG);
1441 sg_set_page(sg, virt_to_page(sc->top_sense), UB_SENSE_SIZE,
1442 (unsigned long)sc->top_sense & (PAGE_SIZE-1));
1443 scmd->len = UB_SENSE_SIZE;
1444 scmd->lun = cmd->lun;
1445 scmd->done = ub_top_sense_done;
1448 scmd->tag = sc->tagcnt++;
1450 cmd->state = UB_CMDST_SENSE;
1452 ub_cmdq_insert(sc, scmd);
1456 ub_state_done(sc, cmd, rc);
1460 * A helper for the command's state machine:
1461 * Submit a stall clear.
1463 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1467 struct usb_ctrlrequest *cr;
1470 endp = usb_pipeendpoint(stalled_pipe);
1471 if (usb_pipein (stalled_pipe))
1475 cr->bRequestType = USB_RECIP_ENDPOINT;
1476 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1477 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1478 cr->wIndex = cpu_to_le16(endp);
1479 cr->wLength = cpu_to_le16(0);
1481 UB_INIT_COMPLETION(sc->work_done);
1483 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1484 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1486 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1487 ub_complete(&sc->work_done);
1491 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1492 add_timer(&sc->work_timer);
1498 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1500 unsigned char *sense = sc->top_sense;
1501 struct ub_scsi_cmd *cmd;
1504 * Find the command which triggered the unit attention or a check,
1505 * save the sense into it, and advance its state machine.
1507 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1508 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1511 if (cmd != scmd->back) {
1512 printk(KERN_WARNING "%s: "
1513 "sense done for wrong command 0x%x\n",
1514 sc->name, cmd->tag);
1517 if (cmd->state != UB_CMDST_SENSE) {
1518 printk(KERN_WARNING "%s: "
1519 "sense done with bad cmd state %d\n",
1520 sc->name, cmd->state);
1525 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1527 cmd->key = sense[2] & 0x0F;
1528 cmd->asc = sense[12];
1529 cmd->ascq = sense[13];
1531 ub_scsi_urb_compl(sc, cmd);
1536 * XXX Move usb_reset_device to khubd. Hogging kevent is not a good thing.
1537 * XXX Make usb_sync_reset asynchronous.
1540 static void ub_reset_enter(struct ub_dev *sc, int try)
1544 /* This happens often on multi-LUN devices. */
1547 sc->reset = try + 1;
1549 #if 0 /* Not needed because the disconnect waits for us. */
1550 unsigned long flags;
1551 spin_lock_irqsave(&ub_lock, flags);
1553 spin_unlock_irqrestore(&ub_lock, flags);
1556 #if 0 /* We let them stop themselves. */
1558 list_for_each_entry(lun, &sc->luns, link) {
1559 blk_stop_queue(lun->disk->queue);
1563 schedule_work(&sc->reset_work);
1566 static void ub_reset_task(struct work_struct *work)
1568 struct ub_dev *sc = container_of(work, struct ub_dev, reset_work);
1569 unsigned long flags;
1574 printk(KERN_WARNING "%s: Running reset unrequested\n",
1579 if (atomic_read(&sc->poison)) {
1581 } else if ((sc->reset & 1) == 0) {
1583 msleep(700); /* usb-storage sleeps 6s (!) */
1584 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1585 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1586 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1589 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1591 "%s: usb_lock_device_for_reset failed (%d)\n",
1594 rc = usb_reset_device(sc->dev);
1596 printk(KERN_NOTICE "%s: "
1597 "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 * This is called from a process context.
1625 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1628 lun->readonly = 0; /* XXX Query this from the device */
1630 lun->capacity.nsec = 0;
1631 lun->capacity.bsize = 512;
1632 lun->capacity.bshift = 0;
1634 if (ub_sync_tur(sc, lun) != 0)
1635 return; /* Not ready */
1638 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1640 * The retry here means something is wrong, either with the
1641 * device, with the transport, or with our code.
1642 * We keep this because sd.c has retries for capacity.
1644 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1645 lun->capacity.nsec = 0;
1646 lun->capacity.bsize = 512;
1647 lun->capacity.bshift = 0;
1654 * This is mostly needed to keep refcounting, but also to support
1655 * media checks on removable media drives.
1657 static int ub_bd_open(struct inode *inode, struct file *filp)
1659 struct gendisk *disk = inode->i_bdev->bd_disk;
1660 struct ub_lun *lun = disk->private_data;
1661 struct ub_dev *sc = lun->udev;
1662 unsigned long flags;
1665 spin_lock_irqsave(&ub_lock, flags);
1666 if (atomic_read(&sc->poison)) {
1667 spin_unlock_irqrestore(&ub_lock, flags);
1671 spin_unlock_irqrestore(&ub_lock, flags);
1673 if (lun->removable || lun->readonly)
1674 check_disk_change(inode->i_bdev);
1677 * The sd.c considers ->media_present and ->changed not equivalent,
1678 * under some pretty murky conditions (a failure of READ CAPACITY).
1679 * We may need it one day.
1681 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1686 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1700 static int ub_bd_release(struct inode *inode, struct file *filp)
1702 struct gendisk *disk = inode->i_bdev->bd_disk;
1703 struct ub_lun *lun = disk->private_data;
1704 struct ub_dev *sc = lun->udev;
1711 * The ioctl interface.
1713 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1714 unsigned int cmd, unsigned long arg)
1716 struct gendisk *disk = inode->i_bdev->bd_disk;
1717 void __user *usermem = (void __user *) arg;
1719 return scsi_cmd_ioctl(filp, disk->queue, disk, cmd, usermem);
1723 * This is called once a new disk was seen by the block layer or by ub_probe().
1724 * The main onjective here is to discover the features of the media such as
1725 * the capacity, read-only status, etc. USB storage generally does not
1726 * need to be spun up, but if we needed it, this would be the place.
1728 * This call can sleep.
1730 * The return code is not used.
1732 static int ub_bd_revalidate(struct gendisk *disk)
1734 struct ub_lun *lun = disk->private_data;
1736 ub_revalidate(lun->udev, lun);
1738 /* XXX Support sector size switching like in sr.c */
1739 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1740 set_capacity(disk, lun->capacity.nsec);
1741 // set_disk_ro(sdkp->disk, lun->readonly);
1747 * The check is called by the block layer to verify if the media
1748 * is still available. It is supposed to be harmless, lightweight and
1749 * non-intrusive in case the media was not changed.
1751 * This call can sleep.
1753 * The return code is bool!
1755 static int ub_bd_media_changed(struct gendisk *disk)
1757 struct ub_lun *lun = disk->private_data;
1759 if (!lun->removable)
1763 * We clean checks always after every command, so this is not
1764 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1765 * the device is actually not ready with operator or software
1766 * intervention required. One dangerous item might be a drive which
1767 * spins itself down, and come the time to write dirty pages, this
1768 * will fail, then block layer discards the data. Since we never
1769 * spin drives up, such devices simply cannot be used with ub anyway.
1771 if (ub_sync_tur(lun->udev, lun) != 0) {
1776 return lun->changed;
1779 static struct block_device_operations ub_bd_fops = {
1780 .owner = THIS_MODULE,
1782 .release = ub_bd_release,
1783 .ioctl = ub_bd_ioctl,
1784 .media_changed = ub_bd_media_changed,
1785 .revalidate_disk = ub_bd_revalidate,
1789 * Common ->done routine for commands executed synchronously.
1791 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1793 struct completion *cop = cmd->back;
1798 * Test if the device has a check condition on it, synchronously.
1800 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1802 struct ub_scsi_cmd *cmd;
1803 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1804 unsigned long flags;
1805 struct completion compl;
1808 init_completion(&compl);
1811 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1814 cmd->cdb[0] = TEST_UNIT_READY;
1816 cmd->dir = UB_DIR_NONE;
1817 cmd->state = UB_CMDST_INIT;
1818 cmd->lun = lun; /* This may be NULL, but that's ok */
1819 cmd->done = ub_probe_done;
1822 spin_lock_irqsave(sc->lock, flags);
1823 cmd->tag = sc->tagcnt++;
1825 rc = ub_submit_scsi(sc, cmd);
1826 spin_unlock_irqrestore(sc->lock, flags);
1831 wait_for_completion(&compl);
1835 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1845 * Read the SCSI capacity synchronously (for probing).
1847 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1848 struct ub_capacity *ret)
1850 struct ub_scsi_cmd *cmd;
1851 struct scatterlist *sg;
1853 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1854 unsigned long flags;
1855 unsigned int bsize, shift;
1857 struct completion compl;
1860 init_completion(&compl);
1863 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1865 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1869 cmd->dir = UB_DIR_READ;
1870 cmd->state = UB_CMDST_INIT;
1873 sg_init_table(sg, UB_MAX_REQ_SG);
1874 sg_set_page(sg, virt_to_page(p), 8, (unsigned long)p & (PAGE_SIZE-1));
1877 cmd->done = ub_probe_done;
1880 spin_lock_irqsave(sc->lock, flags);
1881 cmd->tag = sc->tagcnt++;
1883 rc = ub_submit_scsi(sc, cmd);
1884 spin_unlock_irqrestore(sc->lock, flags);
1889 wait_for_completion(&compl);
1891 if (cmd->error != 0) {
1895 if (cmd->act_len != 8) {
1900 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1901 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1902 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1904 case 512: shift = 0; break;
1905 case 1024: shift = 1; break;
1906 case 2048: shift = 2; break;
1907 case 4096: shift = 3; break;
1914 ret->bshift = shift;
1915 ret->nsec = nsec << shift;
1928 static void ub_probe_urb_complete(struct urb *urb)
1930 struct completion *cop = urb->context;
1934 static void ub_probe_timeout(unsigned long arg)
1936 struct completion *cop = (struct completion *) arg;
1941 * Reset with a Bulk reset.
1943 static int ub_sync_reset(struct ub_dev *sc)
1945 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1946 struct usb_ctrlrequest *cr;
1947 struct completion compl;
1948 struct timer_list timer;
1951 init_completion(&compl);
1954 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1955 cr->bRequest = US_BULK_RESET_REQUEST;
1956 cr->wValue = cpu_to_le16(0);
1957 cr->wIndex = cpu_to_le16(ifnum);
1958 cr->wLength = cpu_to_le16(0);
1960 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1961 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1963 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1965 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1970 timer.function = ub_probe_timeout;
1971 timer.data = (unsigned long) &compl;
1972 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1975 wait_for_completion(&compl);
1977 del_timer_sync(&timer);
1978 usb_kill_urb(&sc->work_urb);
1980 return sc->work_urb.status;
1984 * Get number of LUNs by the way of Bulk GetMaxLUN command.
1986 static int ub_sync_getmaxlun(struct ub_dev *sc)
1988 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1990 enum { ALLOC_SIZE = 1 };
1991 struct usb_ctrlrequest *cr;
1992 struct completion compl;
1993 struct timer_list timer;
1997 init_completion(&compl);
2000 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2005 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2006 cr->bRequest = US_BULK_GET_MAX_LUN;
2007 cr->wValue = cpu_to_le16(0);
2008 cr->wIndex = cpu_to_le16(ifnum);
2009 cr->wLength = cpu_to_le16(1);
2011 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2012 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2014 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2018 timer.function = ub_probe_timeout;
2019 timer.data = (unsigned long) &compl;
2020 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2023 wait_for_completion(&compl);
2025 del_timer_sync(&timer);
2026 usb_kill_urb(&sc->work_urb);
2028 if ((rc = sc->work_urb.status) < 0)
2031 if (sc->work_urb.actual_length != 1) {
2034 if ((nluns = *p) == 55) {
2037 /* GetMaxLUN returns the maximum LUN number */
2039 if (nluns > UB_MAX_LUNS)
2040 nluns = UB_MAX_LUNS;
2055 * Clear initial stalls.
2057 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2060 struct usb_ctrlrequest *cr;
2061 struct completion compl;
2062 struct timer_list timer;
2065 init_completion(&compl);
2067 endp = usb_pipeendpoint(stalled_pipe);
2068 if (usb_pipein (stalled_pipe))
2072 cr->bRequestType = USB_RECIP_ENDPOINT;
2073 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2074 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2075 cr->wIndex = cpu_to_le16(endp);
2076 cr->wLength = cpu_to_le16(0);
2078 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2079 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2081 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2083 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2088 timer.function = ub_probe_timeout;
2089 timer.data = (unsigned long) &compl;
2090 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2093 wait_for_completion(&compl);
2095 del_timer_sync(&timer);
2096 usb_kill_urb(&sc->work_urb);
2098 /* reset the endpoint toggle */
2099 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2105 * Get the pipe settings.
2107 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2108 struct usb_interface *intf)
2110 struct usb_host_interface *altsetting = intf->cur_altsetting;
2111 struct usb_endpoint_descriptor *ep_in = NULL;
2112 struct usb_endpoint_descriptor *ep_out = NULL;
2113 struct usb_endpoint_descriptor *ep;
2117 * Find the endpoints we need.
2118 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2119 * We will ignore any others.
2121 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2122 ep = &altsetting->endpoint[i].desc;
2124 /* Is it a BULK endpoint? */
2125 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2126 == USB_ENDPOINT_XFER_BULK) {
2127 /* BULK in or out? */
2128 if (ep->bEndpointAddress & USB_DIR_IN) {
2138 if (ep_in == NULL || ep_out == NULL) {
2139 printk(KERN_NOTICE "%s: failed endpoint check\n",
2144 /* Calculate and store the pipe values */
2145 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2146 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2147 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2148 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2149 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2150 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2156 * Probing is done in the process context, which allows us to cheat
2157 * and not to build a state machine for the discovery.
2159 static int ub_probe(struct usb_interface *intf,
2160 const struct usb_device_id *dev_id)
2167 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2171 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2173 sc->lock = ub_next_lock();
2174 INIT_LIST_HEAD(&sc->luns);
2175 usb_init_urb(&sc->work_urb);
2176 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2177 atomic_set(&sc->poison, 0);
2178 INIT_WORK(&sc->reset_work, ub_reset_task);
2179 init_waitqueue_head(&sc->reset_wait);
2181 init_timer(&sc->work_timer);
2182 sc->work_timer.data = (unsigned long) sc;
2183 sc->work_timer.function = ub_urb_timeout;
2185 ub_init_completion(&sc->work_done);
2186 sc->work_done.done = 1; /* A little yuk, but oh well... */
2188 sc->dev = interface_to_usbdev(intf);
2190 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2191 usb_set_intfdata(intf, sc);
2192 usb_get_dev(sc->dev);
2194 * Since we give the interface struct to the block level through
2195 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2196 * oopses on close after a disconnect (kernels 2.6.16 and up).
2198 usb_get_intf(sc->intf);
2200 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2201 sc->dev->bus->busnum, sc->dev->devnum);
2203 /* XXX Verify that we can handle the device (from descriptors) */
2205 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2209 * At this point, all USB initialization is done, do upper layer.
2210 * We really hate halfway initialized structures, so from the
2211 * invariants perspective, this ub_dev is fully constructed at
2216 * This is needed to clear toggles. It is a problem only if we do
2217 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2219 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2220 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2221 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2225 * The way this is used by the startup code is a little specific.
2226 * A SCSI check causes a USB stall. Our common case code sees it
2227 * and clears the check, after which the device is ready for use.
2228 * But if a check was not present, any command other than
2229 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2231 * If we neglect to clear the SCSI check, the first real command fails
2232 * (which is the capacity readout). We clear that and retry, but why
2233 * causing spurious retries for no reason.
2235 * Revalidation may start with its own TEST_UNIT_READY, but that one
2236 * has to succeed, so we clear checks with an additional one here.
2237 * In any case it's not our business how revaliadation is implemented.
2239 for (i = 0; i < 3; i++) { /* Retries for the schwag key from KS'04 */
2240 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2241 if (rc != 0x6) break;
2246 for (i = 0; i < 3; i++) {
2247 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2256 for (i = 0; i < nluns; i++) {
2257 ub_probe_lun(sc, i);
2262 usb_set_intfdata(intf, NULL);
2263 usb_put_intf(sc->intf);
2264 usb_put_dev(sc->dev);
2270 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2273 struct request_queue *q;
2274 struct gendisk *disk;
2278 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2283 if ((lun->id = ub_id_get()) == -1)
2288 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2289 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2291 lun->removable = 1; /* XXX Query this from the device */
2292 lun->changed = 1; /* ub_revalidate clears only */
2293 ub_revalidate(sc, lun);
2296 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2299 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2300 disk->major = UB_MAJOR;
2301 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2302 disk->fops = &ub_bd_fops;
2303 disk->private_data = lun;
2304 disk->driverfs_dev = &sc->intf->dev;
2307 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2312 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2313 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2314 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2315 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2316 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2317 blk_queue_hardsect_size(q, lun->capacity.bsize);
2321 list_add(&lun->link, &sc->luns);
2323 set_capacity(disk, lun->capacity.nsec);
2325 disk->flags |= GENHD_FL_REMOVABLE;
2341 static void ub_disconnect(struct usb_interface *intf)
2343 struct ub_dev *sc = usb_get_intfdata(intf);
2345 unsigned long flags;
2348 * Prevent ub_bd_release from pulling the rug from under us.
2349 * XXX This is starting to look like a kref.
2350 * XXX Why not to take this ref at probe time?
2352 spin_lock_irqsave(&ub_lock, flags);
2354 spin_unlock_irqrestore(&ub_lock, flags);
2357 * Fence stall clearnings, operations triggered by unlinkings and so on.
2358 * We do not attempt to unlink any URBs, because we do not trust the
2359 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2361 atomic_set(&sc->poison, 1);
2364 * Wait for reset to end, if any.
2366 wait_event(sc->reset_wait, !sc->reset);
2369 * Blow away queued commands.
2371 * Actually, this never works, because before we get here
2372 * the HCD terminates outstanding URB(s). It causes our
2373 * SCSI command queue to advance, commands fail to submit,
2374 * and the whole queue drains. So, we just use this code to
2377 spin_lock_irqsave(sc->lock, flags);
2379 struct ub_scsi_cmd *cmd;
2381 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2382 cmd->error = -ENOTCONN;
2383 cmd->state = UB_CMDST_DONE;
2385 (*cmd->done)(sc, cmd);
2389 printk(KERN_WARNING "%s: "
2390 "%d was queued after shutdown\n", sc->name, cnt);
2393 spin_unlock_irqrestore(sc->lock, flags);
2396 * Unregister the upper layer.
2398 list_for_each_entry(lun, &sc->luns, link) {
2399 del_gendisk(lun->disk);
2401 * I wish I could do:
2402 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2403 * As it is, we rely on our internal poisoning and let
2404 * the upper levels to spin furiously failing all the I/O.
2409 * Testing for -EINPROGRESS is always a bug, so we are bending
2410 * the rules a little.
2412 spin_lock_irqsave(sc->lock, flags);
2413 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2414 printk(KERN_WARNING "%s: "
2415 "URB is active after disconnect\n", sc->name);
2417 spin_unlock_irqrestore(sc->lock, flags);
2420 * There is virtually no chance that other CPU runs times so long
2421 * after ub_urb_complete should have called del_timer, but only if HCD
2422 * didn't forget to deliver a callback on unlink.
2424 del_timer_sync(&sc->work_timer);
2427 * At this point there must be no commands coming from anyone
2428 * and no URBs left in transit.
2434 static struct usb_driver ub_driver = {
2437 .disconnect = ub_disconnect,
2438 .id_table = ub_usb_ids,
2441 static int __init ub_init(void)
2446 for (i = 0; i < UB_QLOCK_NUM; i++)
2447 spin_lock_init(&ub_qlockv[i]);
2449 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2452 if ((rc = usb_register(&ub_driver)) != 0)
2455 usb_usual_set_present(USB_US_TYPE_UB);
2459 unregister_blkdev(UB_MAJOR, DRV_NAME);
2464 static void __exit ub_exit(void)
2466 usb_deregister(&ub_driver);
2468 unregister_blkdev(UB_MAJOR, DRV_NAME);
2469 usb_usual_clear_present(USB_US_TYPE_UB);
2472 module_init(ub_init);
2473 module_exit(ub_exit);
2475 MODULE_LICENSE("GPL");