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. */
208 unsigned int timeo; /* jiffies until rq->timeout changes */
210 unsigned int len; /* Requested length */
211 unsigned int current_sg;
212 unsigned int nsg; /* sgv[nsg] */
213 struct scatterlist sgv[UB_MAX_REQ_SG];
216 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
222 unsigned int current_try;
223 unsigned int nsg; /* sgv[nsg] */
224 struct scatterlist sgv[UB_MAX_REQ_SG];
230 unsigned long nsec; /* Linux size - 512 byte sectors */
231 unsigned int bsize; /* Linux hardsect_size */
232 unsigned int bshift; /* Shift between 512 and hard sects */
236 * This is a direct take-off from linux/include/completion.h
237 * The difference is that I do not wait on this thing, just poll.
238 * When I want to wait (ub_probe), I just use the stock completion.
240 * Note that INIT_COMPLETION takes no lock. It is correct. But why
241 * in the bloody hell that thing takes struct instead of pointer to struct
242 * is quite beyond me. I just copied it from the stock completion.
244 struct ub_completion {
249 static inline void ub_init_completion(struct ub_completion *x)
252 spin_lock_init(&x->lock);
255 #define UB_INIT_COMPLETION(x) ((x).done = 0)
257 static void ub_complete(struct ub_completion *x)
261 spin_lock_irqsave(&x->lock, flags);
263 spin_unlock_irqrestore(&x->lock, flags);
266 static int ub_is_completed(struct ub_completion *x)
271 spin_lock_irqsave(&x->lock, flags);
273 spin_unlock_irqrestore(&x->lock, flags);
279 struct ub_scsi_cmd_queue {
281 struct ub_scsi_cmd *head, *tail;
285 * The block device instance (one per LUN).
289 struct list_head link;
290 struct gendisk *disk;
291 int id; /* Host index */
292 int num; /* LUN number */
295 int changed; /* Media was changed */
299 struct ub_request urq;
301 /* Use Ingo's mempool if or when we have more than one command. */
303 * Currently we never need more than one command for the whole device.
304 * However, giving every LUN a command is a cheap and automatic way
305 * to enforce fairness between them.
308 struct ub_scsi_cmd cmdv[1];
310 struct ub_capacity capacity;
314 * The USB device instance.
318 atomic_t poison; /* The USB device is disconnected */
319 int openc; /* protected by ub_lock! */
320 /* kref is too implicit for our taste */
321 int reset; /* Reset is running */
325 struct usb_device *dev;
326 struct usb_interface *intf;
328 struct list_head luns;
330 unsigned int send_bulk_pipe; /* cached pipe values */
331 unsigned int recv_bulk_pipe;
332 unsigned int send_ctrl_pipe;
333 unsigned int recv_ctrl_pipe;
335 struct tasklet_struct tasklet;
337 struct ub_scsi_cmd_queue cmd_queue;
338 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
339 unsigned char top_sense[UB_SENSE_SIZE];
341 struct ub_completion work_done;
343 struct timer_list work_timer;
344 int last_pipe; /* What might need clearing */
345 __le32 signature; /* Learned signature */
346 struct bulk_cb_wrap work_bcb;
347 struct bulk_cs_wrap work_bcs;
348 struct usb_ctrlrequest work_cr;
350 struct work_struct reset_work;
351 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 usb_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",
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, blk_rq_bytes(rq));
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_hardsect_size() guarantees that request
727 * is aligned, but it is given in terms of 512 byte units, always.
729 block = rq->sector >> lun->capacity.bshift;
730 nblks = rq->nr_sectors >> 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 = rq->nr_sectors * 512;
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 (rq->data_len == 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 = rq->data_len;
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;
780 unsigned int cmd_len;
784 if (cmd->error == 0) {
785 if (blk_pc_request(rq)) {
786 if (cmd->act_len >= rq->data_len)
789 rq->data_len -= cmd->act_len;
792 if (cmd->act_len != cmd->len) {
793 scsi_status = SAM_STAT_CHECK_CONDITION;
799 if (blk_pc_request(rq)) {
800 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
801 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
802 rq->sense_len = UB_SENSE_SIZE;
803 if (sc->top_sense[0] != 0)
804 scsi_status = SAM_STAT_CHECK_CONDITION;
806 scsi_status = DID_ERROR << 16;
808 if (cmd->error == -EIO &&
810 cmd->key == MEDIUM_ERROR ||
811 cmd->key == UNIT_ATTENTION)) {
812 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
815 scsi_status = SAM_STAT_CHECK_CONDITION;
822 ub_put_cmd(lun, cmd);
823 ub_end_rq(rq, scsi_status, cmd_len);
824 blk_start_queue(lun->disk->queue);
827 static void ub_end_rq(struct request *rq, unsigned int scsi_status,
828 unsigned int cmd_len)
833 if (scsi_status == 0) {
837 rq->errors = scsi_status;
839 rqlen = blk_rq_bytes(rq); /* Oddly enough, this is the residue. */
840 if (__blk_end_request(rq, error, cmd_len)) {
841 printk(KERN_WARNING DRV_NAME
842 ": __blk_end_request blew, %s-cmd total %u rqlen %ld\n",
843 blk_pc_request(rq)? "pc": "fs", cmd_len, rqlen);
847 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
848 struct ub_request *urq, struct ub_scsi_cmd *cmd)
851 if (atomic_read(&sc->poison))
854 ub_reset_enter(sc, urq->current_try);
856 if (urq->current_try >= 3)
860 /* Remove this if anyone complains of flooding. */
861 printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
862 "[sense %x %02x %02x] retry %d\n",
863 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
864 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
866 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
867 ub_cmd_build_block(sc, lun, cmd, urq);
869 cmd->state = UB_CMDST_INIT;
871 cmd->done = ub_rw_cmd_done;
874 cmd->tag = sc->tagcnt++;
877 return ub_submit_scsi(sc, cmd);
879 ub_cmdq_add(sc, cmd);
885 * Submit a regular SCSI operation (not an auto-sense).
887 * The Iron Law of Good Submit Routine is:
888 * Zero return - callback is done, Nonzero return - callback is not done.
891 * Host is assumed locked.
893 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
896 if (cmd->state != UB_CMDST_INIT ||
897 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
901 ub_cmdq_add(sc, cmd);
903 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
904 * safer to jump to a tasklet, in case upper layers do something silly.
906 tasklet_schedule(&sc->tasklet);
911 * Submit the first URB for the queued command.
912 * This function does not deal with queueing in any way.
914 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
916 struct bulk_cb_wrap *bcb;
922 * ``If the allocation length is eighteen or greater, and a device
923 * server returns less than eithteen bytes of data, the application
924 * client should assume that the bytes not transferred would have been
925 * zeroes had the device server returned those bytes.''
927 * We zero sense for all commands so that when a packet request
928 * fails it does not return a stale sense.
930 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
932 /* set up the command wrapper */
933 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
934 bcb->Tag = cmd->tag; /* Endianness is not important */
935 bcb->DataTransferLength = cpu_to_le32(cmd->len);
936 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
937 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
938 bcb->Length = cmd->cdb_len;
940 /* copy the command payload */
941 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
943 UB_INIT_COMPLETION(sc->work_done);
945 sc->last_pipe = sc->send_bulk_pipe;
946 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
947 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
949 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
950 /* XXX Clear stalls */
951 ub_complete(&sc->work_done);
955 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
956 add_timer(&sc->work_timer);
958 cmd->state = UB_CMDST_CMD;
965 static void ub_urb_timeout(unsigned long arg)
967 struct ub_dev *sc = (struct ub_dev *) arg;
970 spin_lock_irqsave(sc->lock, flags);
971 if (!ub_is_completed(&sc->work_done))
972 usb_unlink_urb(&sc->work_urb);
973 spin_unlock_irqrestore(sc->lock, flags);
977 * Completion routine for the work URB.
979 * This can be called directly from usb_submit_urb (while we have
980 * the sc->lock taken) and from an interrupt (while we do NOT have
981 * the sc->lock taken). Therefore, bounce this off to a tasklet.
983 static void ub_urb_complete(struct urb *urb)
985 struct ub_dev *sc = urb->context;
987 ub_complete(&sc->work_done);
988 tasklet_schedule(&sc->tasklet);
991 static void ub_scsi_action(unsigned long _dev)
993 struct ub_dev *sc = (struct ub_dev *) _dev;
996 spin_lock_irqsave(sc->lock, flags);
997 ub_scsi_dispatch(sc);
998 spin_unlock_irqrestore(sc->lock, flags);
1001 static void ub_scsi_dispatch(struct ub_dev *sc)
1003 struct ub_scsi_cmd *cmd;
1006 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
1007 if (cmd->state == UB_CMDST_DONE) {
1009 (*cmd->done)(sc, cmd);
1010 } else if (cmd->state == UB_CMDST_INIT) {
1011 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1014 cmd->state = UB_CMDST_DONE;
1016 if (!ub_is_completed(&sc->work_done))
1018 del_timer(&sc->work_timer);
1019 ub_scsi_urb_compl(sc, cmd);
1024 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1026 struct urb *urb = &sc->work_urb;
1027 struct bulk_cs_wrap *bcs;
1031 if (atomic_read(&sc->poison)) {
1032 ub_state_done(sc, cmd, -ENODEV);
1036 if (cmd->state == UB_CMDST_CLEAR) {
1037 if (urb->status == -EPIPE) {
1039 * STALL while clearning STALL.
1040 * The control pipe clears itself - nothing to do.
1042 printk(KERN_NOTICE "%s: stall on control pipe\n",
1048 * We ignore the result for the halt clear.
1051 /* reset the endpoint toggle */
1052 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1053 usb_pipeout(sc->last_pipe), 0);
1055 ub_state_sense(sc, cmd);
1057 } else if (cmd->state == UB_CMDST_CLR2STS) {
1058 if (urb->status == -EPIPE) {
1059 printk(KERN_NOTICE "%s: stall on control pipe\n",
1065 * We ignore the result for the halt clear.
1068 /* reset the endpoint toggle */
1069 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1070 usb_pipeout(sc->last_pipe), 0);
1072 ub_state_stat(sc, cmd);
1074 } else if (cmd->state == UB_CMDST_CLRRS) {
1075 if (urb->status == -EPIPE) {
1076 printk(KERN_NOTICE "%s: stall on control pipe\n",
1082 * We ignore the result for the halt clear.
1085 /* reset the endpoint toggle */
1086 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1087 usb_pipeout(sc->last_pipe), 0);
1089 ub_state_stat_counted(sc, cmd);
1091 } else if (cmd->state == UB_CMDST_CMD) {
1092 switch (urb->status) {
1098 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1100 printk(KERN_NOTICE "%s: "
1101 "unable to submit clear (%d)\n",
1104 * This is typically ENOMEM or some other such shit.
1105 * Retrying is pointless. Just do Bad End on it...
1107 ub_state_done(sc, cmd, rc);
1110 cmd->state = UB_CMDST_CLEAR;
1112 case -ESHUTDOWN: /* unplug */
1113 case -EILSEQ: /* unplug timeout on uhci */
1114 ub_state_done(sc, cmd, -ENODEV);
1119 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1123 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1124 ub_state_stat(sc, cmd);
1128 // udelay(125); // usb-storage has this
1129 ub_data_start(sc, cmd);
1131 } else if (cmd->state == UB_CMDST_DATA) {
1132 if (urb->status == -EPIPE) {
1133 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1135 printk(KERN_NOTICE "%s: "
1136 "unable to submit clear (%d)\n",
1138 ub_state_done(sc, cmd, rc);
1141 cmd->state = UB_CMDST_CLR2STS;
1144 if (urb->status == -EOVERFLOW) {
1146 * A babble? Failure, but we must transfer CSW now.
1148 cmd->error = -EOVERFLOW; /* A cheap trick... */
1149 ub_state_stat(sc, cmd);
1153 if (cmd->dir == UB_DIR_WRITE) {
1155 * Do not continue writes in case of a failure.
1156 * Doing so would cause sectors to be mixed up,
1157 * which is worse than sectors lost.
1159 * We must try to read the CSW, or many devices
1162 len = urb->actual_length;
1163 if (urb->status != 0 ||
1164 len != cmd->sgv[cmd->current_sg].length) {
1165 cmd->act_len += len;
1168 ub_state_stat(sc, cmd);
1174 * If an error occurs on read, we record it, and
1175 * continue to fetch data in order to avoid bubble.
1177 * As a small shortcut, we stop if we detect that
1178 * a CSW mixed into data.
1180 if (urb->status != 0)
1183 len = urb->actual_length;
1184 if (urb->status != 0 ||
1185 len != cmd->sgv[cmd->current_sg].length) {
1186 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1191 cmd->act_len += urb->actual_length;
1193 if (++cmd->current_sg < cmd->nsg) {
1194 ub_data_start(sc, cmd);
1197 ub_state_stat(sc, cmd);
1199 } else if (cmd->state == UB_CMDST_STAT) {
1200 if (urb->status == -EPIPE) {
1201 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1203 printk(KERN_NOTICE "%s: "
1204 "unable to submit clear (%d)\n",
1206 ub_state_done(sc, cmd, rc);
1211 * Having a stall when getting CSW is an error, so
1212 * make sure uppper levels are not oblivious to it.
1214 cmd->error = -EIO; /* A cheap trick... */
1216 cmd->state = UB_CMDST_CLRRS;
1220 /* Catch everything, including -EOVERFLOW and other nasties. */
1221 if (urb->status != 0)
1224 if (urb->actual_length == 0) {
1225 ub_state_stat_counted(sc, cmd);
1230 * Check the returned Bulk protocol status.
1231 * The status block has to be validated first.
1234 bcs = &sc->work_bcs;
1236 if (sc->signature == cpu_to_le32(0)) {
1238 * This is the first reply, so do not perform the check.
1239 * Instead, remember the signature the device uses
1240 * for future checks. But do not allow a nul.
1242 sc->signature = bcs->Signature;
1243 if (sc->signature == cpu_to_le32(0)) {
1244 ub_state_stat_counted(sc, cmd);
1248 if (bcs->Signature != sc->signature) {
1249 ub_state_stat_counted(sc, cmd);
1254 if (bcs->Tag != cmd->tag) {
1256 * This usually happens when we disagree with the
1257 * device's microcode about something. For instance,
1258 * a few of them throw this after timeouts. They buffer
1259 * commands and reply at commands we timed out before.
1260 * Without flushing these replies we loop forever.
1262 ub_state_stat_counted(sc, cmd);
1266 if (!sc->bad_resid) {
1267 len = le32_to_cpu(bcs->Residue);
1268 if (len != cmd->len - cmd->act_len) {
1270 * Only start ignoring if this cmd ended well.
1272 if (cmd->len == cmd->act_len) {
1273 printk(KERN_NOTICE "%s: "
1274 "bad residual %d of %d, ignoring\n",
1275 sc->name, len, cmd->len);
1281 switch (bcs->Status) {
1282 case US_BULK_STAT_OK:
1284 case US_BULK_STAT_FAIL:
1285 ub_state_sense(sc, cmd);
1287 case US_BULK_STAT_PHASE:
1290 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1291 sc->name, bcs->Status);
1292 ub_state_done(sc, cmd, -EINVAL);
1296 /* Not zeroing error to preserve a babble indicator */
1297 if (cmd->error != 0) {
1298 ub_state_sense(sc, cmd);
1301 cmd->state = UB_CMDST_DONE;
1303 (*cmd->done)(sc, cmd);
1305 } else if (cmd->state == UB_CMDST_SENSE) {
1306 ub_state_done(sc, cmd, -EIO);
1309 printk(KERN_WARNING "%s: wrong command state %d\n",
1310 sc->name, cmd->state);
1311 ub_state_done(sc, cmd, -EINVAL);
1316 Bad_End: /* Little Excel is dead */
1317 ub_state_done(sc, cmd, -EIO);
1321 * Factorization helper for the command state machine:
1322 * Initiate a data segment transfer.
1324 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1326 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1330 UB_INIT_COMPLETION(sc->work_done);
1332 if (cmd->dir == UB_DIR_READ)
1333 pipe = sc->recv_bulk_pipe;
1335 pipe = sc->send_bulk_pipe;
1336 sc->last_pipe = pipe;
1337 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe, sg_virt(sg),
1338 sg->length, ub_urb_complete, sc);
1340 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1341 /* XXX Clear stalls */
1342 ub_complete(&sc->work_done);
1343 ub_state_done(sc, cmd, rc);
1348 sc->work_timer.expires = jiffies + cmd->timeo;
1350 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1351 add_timer(&sc->work_timer);
1353 cmd->state = UB_CMDST_DATA;
1357 * Factorization helper for the command state machine:
1358 * Finish the command.
1360 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1364 cmd->state = UB_CMDST_DONE;
1366 (*cmd->done)(sc, cmd);
1370 * Factorization helper for the command state machine:
1371 * Submit a CSW read.
1373 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1377 UB_INIT_COMPLETION(sc->work_done);
1379 sc->last_pipe = sc->recv_bulk_pipe;
1380 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1381 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1383 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1384 /* XXX Clear stalls */
1385 ub_complete(&sc->work_done);
1386 ub_state_done(sc, cmd, rc);
1391 sc->work_timer.expires = jiffies + cmd->timeo;
1393 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1394 add_timer(&sc->work_timer);
1399 * Factorization helper for the command state machine:
1400 * Submit a CSW read and go to STAT state.
1402 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1405 if (__ub_state_stat(sc, cmd) != 0)
1408 cmd->stat_count = 0;
1409 cmd->state = UB_CMDST_STAT;
1413 * Factorization helper for the command state machine:
1414 * Submit a CSW read and go to STAT state with counter (along [C] path).
1416 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1419 if (++cmd->stat_count >= 4) {
1420 ub_state_sense(sc, cmd);
1424 if (__ub_state_stat(sc, cmd) != 0)
1427 cmd->state = UB_CMDST_STAT;
1431 * Factorization helper for the command state machine:
1432 * Submit a REQUEST SENSE and go to SENSE state.
1434 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1436 struct ub_scsi_cmd *scmd;
1437 struct scatterlist *sg;
1440 if (cmd->cdb[0] == REQUEST_SENSE) {
1445 scmd = &sc->top_rqs_cmd;
1446 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1447 scmd->cdb[0] = REQUEST_SENSE;
1448 scmd->cdb[4] = UB_SENSE_SIZE;
1450 scmd->dir = UB_DIR_READ;
1451 scmd->state = UB_CMDST_INIT;
1454 sg_init_table(sg, UB_MAX_REQ_SG);
1455 sg_set_page(sg, virt_to_page(sc->top_sense), UB_SENSE_SIZE,
1456 (unsigned long)sc->top_sense & (PAGE_SIZE-1));
1457 scmd->len = UB_SENSE_SIZE;
1458 scmd->lun = cmd->lun;
1459 scmd->done = ub_top_sense_done;
1462 scmd->tag = sc->tagcnt++;
1464 cmd->state = UB_CMDST_SENSE;
1466 ub_cmdq_insert(sc, scmd);
1470 ub_state_done(sc, cmd, rc);
1474 * A helper for the command's state machine:
1475 * Submit a stall clear.
1477 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1481 struct usb_ctrlrequest *cr;
1484 endp = usb_pipeendpoint(stalled_pipe);
1485 if (usb_pipein (stalled_pipe))
1489 cr->bRequestType = USB_RECIP_ENDPOINT;
1490 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1491 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1492 cr->wIndex = cpu_to_le16(endp);
1493 cr->wLength = cpu_to_le16(0);
1495 UB_INIT_COMPLETION(sc->work_done);
1497 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1498 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1500 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1501 ub_complete(&sc->work_done);
1505 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1506 add_timer(&sc->work_timer);
1512 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1514 unsigned char *sense = sc->top_sense;
1515 struct ub_scsi_cmd *cmd;
1518 * Find the command which triggered the unit attention or a check,
1519 * save the sense into it, and advance its state machine.
1521 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1522 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1525 if (cmd != scmd->back) {
1526 printk(KERN_WARNING "%s: "
1527 "sense done for wrong command 0x%x\n",
1528 sc->name, cmd->tag);
1531 if (cmd->state != UB_CMDST_SENSE) {
1532 printk(KERN_WARNING "%s: sense done with bad cmd state %d\n",
1533 sc->name, cmd->state);
1538 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1540 cmd->key = sense[2] & 0x0F;
1541 cmd->asc = sense[12];
1542 cmd->ascq = sense[13];
1544 ub_scsi_urb_compl(sc, cmd);
1551 static void ub_reset_enter(struct ub_dev *sc, int try)
1555 /* This happens often on multi-LUN devices. */
1558 sc->reset = try + 1;
1560 #if 0 /* Not needed because the disconnect waits for us. */
1561 unsigned long flags;
1562 spin_lock_irqsave(&ub_lock, flags);
1564 spin_unlock_irqrestore(&ub_lock, flags);
1567 #if 0 /* We let them stop themselves. */
1569 list_for_each_entry(lun, &sc->luns, link) {
1570 blk_stop_queue(lun->disk->queue);
1574 schedule_work(&sc->reset_work);
1577 static void ub_reset_task(struct work_struct *work)
1579 struct ub_dev *sc = container_of(work, struct ub_dev, reset_work);
1580 unsigned long flags;
1585 printk(KERN_WARNING "%s: Running reset unrequested\n",
1590 if (atomic_read(&sc->poison)) {
1592 } else if ((sc->reset & 1) == 0) {
1594 msleep(700); /* usb-storage sleeps 6s (!) */
1595 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1596 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1597 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1600 rc = usb_lock_device_for_reset(sc->dev, sc->intf);
1603 "%s: usb_lock_device_for_reset failed (%d)\n",
1606 rc = usb_reset_device(sc->dev);
1608 printk(KERN_NOTICE "%s: "
1609 "usb_lock_device_for_reset failed (%d)\n",
1612 usb_unlock_device(sc->dev);
1617 * In theory, no commands can be running while reset is active,
1618 * so nobody can ask for another reset, and so we do not need any
1619 * queues of resets or anything. We do need a spinlock though,
1620 * to interact with block layer.
1622 spin_lock_irqsave(sc->lock, flags);
1624 tasklet_schedule(&sc->tasklet);
1625 list_for_each_entry(lun, &sc->luns, link) {
1626 blk_start_queue(lun->disk->queue);
1628 wake_up(&sc->reset_wait);
1629 spin_unlock_irqrestore(sc->lock, flags);
1633 * XXX Reset brackets are too much hassle to implement, so just stub them
1634 * in order to prevent forced unbinding (which deadlocks solid when our
1635 * ->disconnect method waits for the reset to complete and this kills keventd).
1637 * XXX Tell Alan to move usb_unlock_device inside of usb_reset_device,
1638 * or else the post_reset is invoked, and restats I/O on a locked device.
1640 static int ub_pre_reset(struct usb_interface *iface) {
1644 static int ub_post_reset(struct usb_interface *iface) {
1649 * This is called from a process context.
1651 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1654 lun->readonly = 0; /* XXX Query this from the device */
1656 lun->capacity.nsec = 0;
1657 lun->capacity.bsize = 512;
1658 lun->capacity.bshift = 0;
1660 if (ub_sync_tur(sc, lun) != 0)
1661 return; /* Not ready */
1664 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1666 * The retry here means something is wrong, either with the
1667 * device, with the transport, or with our code.
1668 * We keep this because sd.c has retries for capacity.
1670 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1671 lun->capacity.nsec = 0;
1672 lun->capacity.bsize = 512;
1673 lun->capacity.bshift = 0;
1680 * This is mostly needed to keep refcounting, but also to support
1681 * media checks on removable media drives.
1683 static int ub_bd_open(struct block_device *bdev, fmode_t mode)
1685 struct ub_lun *lun = bdev->bd_disk->private_data;
1686 struct ub_dev *sc = lun->udev;
1687 unsigned long flags;
1690 spin_lock_irqsave(&ub_lock, flags);
1691 if (atomic_read(&sc->poison)) {
1692 spin_unlock_irqrestore(&ub_lock, flags);
1696 spin_unlock_irqrestore(&ub_lock, flags);
1698 if (lun->removable || lun->readonly)
1699 check_disk_change(bdev);
1702 * The sd.c considers ->media_present and ->changed not equivalent,
1703 * under some pretty murky conditions (a failure of READ CAPACITY).
1704 * We may need it one day.
1706 if (lun->removable && lun->changed && !(mode & FMODE_NDELAY)) {
1711 if (lun->readonly && (mode & FMODE_WRITE)) {
1725 static int ub_bd_release(struct gendisk *disk, fmode_t mode)
1727 struct ub_lun *lun = disk->private_data;
1728 struct ub_dev *sc = lun->udev;
1735 * The ioctl interface.
1737 static int ub_bd_ioctl(struct block_device *bdev, fmode_t mode,
1738 unsigned int cmd, unsigned long arg)
1740 struct gendisk *disk = bdev->bd_disk;
1741 void __user *usermem = (void __user *) arg;
1743 return scsi_cmd_ioctl(disk->queue, disk, mode, cmd, usermem);
1747 * This is called by check_disk_change if we reported a media change.
1748 * The main onjective here is to discover the features of the media such as
1749 * the capacity, read-only status, etc. USB storage generally does not
1750 * need to be spun up, but if we needed it, this would be the place.
1752 * This call can sleep.
1754 * The return code is not used.
1756 static int ub_bd_revalidate(struct gendisk *disk)
1758 struct ub_lun *lun = disk->private_data;
1760 ub_revalidate(lun->udev, lun);
1762 /* XXX Support sector size switching like in sr.c */
1763 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1764 set_capacity(disk, lun->capacity.nsec);
1765 // set_disk_ro(sdkp->disk, lun->readonly);
1771 * The check is called by the block layer to verify if the media
1772 * is still available. It is supposed to be harmless, lightweight and
1773 * non-intrusive in case the media was not changed.
1775 * This call can sleep.
1777 * The return code is bool!
1779 static int ub_bd_media_changed(struct gendisk *disk)
1781 struct ub_lun *lun = disk->private_data;
1783 if (!lun->removable)
1787 * We clean checks always after every command, so this is not
1788 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1789 * the device is actually not ready with operator or software
1790 * intervention required. One dangerous item might be a drive which
1791 * spins itself down, and come the time to write dirty pages, this
1792 * will fail, then block layer discards the data. Since we never
1793 * spin drives up, such devices simply cannot be used with ub anyway.
1795 if (ub_sync_tur(lun->udev, lun) != 0) {
1800 return lun->changed;
1803 static struct block_device_operations ub_bd_fops = {
1804 .owner = THIS_MODULE,
1806 .release = ub_bd_release,
1807 .locked_ioctl = ub_bd_ioctl,
1808 .media_changed = ub_bd_media_changed,
1809 .revalidate_disk = ub_bd_revalidate,
1813 * Common ->done routine for commands executed synchronously.
1815 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1817 struct completion *cop = cmd->back;
1822 * Test if the device has a check condition on it, synchronously.
1824 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1826 struct ub_scsi_cmd *cmd;
1827 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1828 unsigned long flags;
1829 struct completion compl;
1832 init_completion(&compl);
1835 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1838 cmd->cdb[0] = TEST_UNIT_READY;
1840 cmd->dir = UB_DIR_NONE;
1841 cmd->state = UB_CMDST_INIT;
1842 cmd->lun = lun; /* This may be NULL, but that's ok */
1843 cmd->done = ub_probe_done;
1846 spin_lock_irqsave(sc->lock, flags);
1847 cmd->tag = sc->tagcnt++;
1849 rc = ub_submit_scsi(sc, cmd);
1850 spin_unlock_irqrestore(sc->lock, flags);
1855 wait_for_completion(&compl);
1859 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1869 * Read the SCSI capacity synchronously (for probing).
1871 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1872 struct ub_capacity *ret)
1874 struct ub_scsi_cmd *cmd;
1875 struct scatterlist *sg;
1877 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1878 unsigned long flags;
1879 unsigned int bsize, shift;
1881 struct completion compl;
1884 init_completion(&compl);
1887 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1889 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1893 cmd->dir = UB_DIR_READ;
1894 cmd->state = UB_CMDST_INIT;
1897 sg_init_table(sg, UB_MAX_REQ_SG);
1898 sg_set_page(sg, virt_to_page(p), 8, (unsigned long)p & (PAGE_SIZE-1));
1901 cmd->done = ub_probe_done;
1904 spin_lock_irqsave(sc->lock, flags);
1905 cmd->tag = sc->tagcnt++;
1907 rc = ub_submit_scsi(sc, cmd);
1908 spin_unlock_irqrestore(sc->lock, flags);
1913 wait_for_completion(&compl);
1915 if (cmd->error != 0) {
1919 if (cmd->act_len != 8) {
1924 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1925 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1926 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1928 case 512: shift = 0; break;
1929 case 1024: shift = 1; break;
1930 case 2048: shift = 2; break;
1931 case 4096: shift = 3; break;
1938 ret->bshift = shift;
1939 ret->nsec = nsec << shift;
1952 static void ub_probe_urb_complete(struct urb *urb)
1954 struct completion *cop = urb->context;
1958 static void ub_probe_timeout(unsigned long arg)
1960 struct completion *cop = (struct completion *) arg;
1965 * Reset with a Bulk reset.
1967 static int ub_sync_reset(struct ub_dev *sc)
1969 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1970 struct usb_ctrlrequest *cr;
1971 struct completion compl;
1972 struct timer_list timer;
1975 init_completion(&compl);
1978 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1979 cr->bRequest = US_BULK_RESET_REQUEST;
1980 cr->wValue = cpu_to_le16(0);
1981 cr->wIndex = cpu_to_le16(ifnum);
1982 cr->wLength = cpu_to_le16(0);
1984 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1985 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1987 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1989 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1994 timer.function = ub_probe_timeout;
1995 timer.data = (unsigned long) &compl;
1996 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1999 wait_for_completion(&compl);
2001 del_timer_sync(&timer);
2002 usb_kill_urb(&sc->work_urb);
2004 return sc->work_urb.status;
2008 * Get number of LUNs by the way of Bulk GetMaxLUN command.
2010 static int ub_sync_getmaxlun(struct ub_dev *sc)
2012 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2014 enum { ALLOC_SIZE = 1 };
2015 struct usb_ctrlrequest *cr;
2016 struct completion compl;
2017 struct timer_list timer;
2021 init_completion(&compl);
2024 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2029 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2030 cr->bRequest = US_BULK_GET_MAX_LUN;
2031 cr->wValue = cpu_to_le16(0);
2032 cr->wIndex = cpu_to_le16(ifnum);
2033 cr->wLength = cpu_to_le16(1);
2035 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2036 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2038 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2042 timer.function = ub_probe_timeout;
2043 timer.data = (unsigned long) &compl;
2044 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2047 wait_for_completion(&compl);
2049 del_timer_sync(&timer);
2050 usb_kill_urb(&sc->work_urb);
2052 if ((rc = sc->work_urb.status) < 0)
2055 if (sc->work_urb.actual_length != 1) {
2058 if ((nluns = *p) == 55) {
2061 /* GetMaxLUN returns the maximum LUN number */
2063 if (nluns > UB_MAX_LUNS)
2064 nluns = UB_MAX_LUNS;
2079 * Clear initial stalls.
2081 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2084 struct usb_ctrlrequest *cr;
2085 struct completion compl;
2086 struct timer_list timer;
2089 init_completion(&compl);
2091 endp = usb_pipeendpoint(stalled_pipe);
2092 if (usb_pipein (stalled_pipe))
2096 cr->bRequestType = USB_RECIP_ENDPOINT;
2097 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2098 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2099 cr->wIndex = cpu_to_le16(endp);
2100 cr->wLength = cpu_to_le16(0);
2102 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2103 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2105 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2107 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2112 timer.function = ub_probe_timeout;
2113 timer.data = (unsigned long) &compl;
2114 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2117 wait_for_completion(&compl);
2119 del_timer_sync(&timer);
2120 usb_kill_urb(&sc->work_urb);
2122 /* reset the endpoint toggle */
2123 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2129 * Get the pipe settings.
2131 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2132 struct usb_interface *intf)
2134 struct usb_host_interface *altsetting = intf->cur_altsetting;
2135 struct usb_endpoint_descriptor *ep_in = NULL;
2136 struct usb_endpoint_descriptor *ep_out = NULL;
2137 struct usb_endpoint_descriptor *ep;
2141 * Find the endpoints we need.
2142 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2143 * We will ignore any others.
2145 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2146 ep = &altsetting->endpoint[i].desc;
2148 /* Is it a BULK endpoint? */
2149 if (usb_endpoint_xfer_bulk(ep)) {
2150 /* BULK in or out? */
2151 if (usb_endpoint_dir_in(ep)) {
2161 if (ep_in == NULL || ep_out == NULL) {
2162 printk(KERN_NOTICE "%s: failed endpoint check\n", sc->name);
2166 /* Calculate and store the pipe values */
2167 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2168 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2169 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2170 usb_endpoint_num(ep_out));
2171 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2172 usb_endpoint_num(ep_in));
2178 * Probing is done in the process context, which allows us to cheat
2179 * and not to build a state machine for the discovery.
2181 static int ub_probe(struct usb_interface *intf,
2182 const struct usb_device_id *dev_id)
2189 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2193 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2195 sc->lock = ub_next_lock();
2196 INIT_LIST_HEAD(&sc->luns);
2197 usb_init_urb(&sc->work_urb);
2198 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2199 atomic_set(&sc->poison, 0);
2200 INIT_WORK(&sc->reset_work, ub_reset_task);
2201 init_waitqueue_head(&sc->reset_wait);
2203 init_timer(&sc->work_timer);
2204 sc->work_timer.data = (unsigned long) sc;
2205 sc->work_timer.function = ub_urb_timeout;
2207 ub_init_completion(&sc->work_done);
2208 sc->work_done.done = 1; /* A little yuk, but oh well... */
2210 sc->dev = interface_to_usbdev(intf);
2212 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2213 usb_set_intfdata(intf, sc);
2214 usb_get_dev(sc->dev);
2216 * Since we give the interface struct to the block level through
2217 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2218 * oopses on close after a disconnect (kernels 2.6.16 and up).
2220 usb_get_intf(sc->intf);
2222 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2223 sc->dev->bus->busnum, sc->dev->devnum);
2225 /* XXX Verify that we can handle the device (from descriptors) */
2227 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2231 * At this point, all USB initialization is done, do upper layer.
2232 * We really hate halfway initialized structures, so from the
2233 * invariants perspective, this ub_dev is fully constructed at
2238 * This is needed to clear toggles. It is a problem only if we do
2239 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2241 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2242 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2243 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2247 * The way this is used by the startup code is a little specific.
2248 * A SCSI check causes a USB stall. Our common case code sees it
2249 * and clears the check, after which the device is ready for use.
2250 * But if a check was not present, any command other than
2251 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2253 * If we neglect to clear the SCSI check, the first real command fails
2254 * (which is the capacity readout). We clear that and retry, but why
2255 * causing spurious retries for no reason.
2257 * Revalidation may start with its own TEST_UNIT_READY, but that one
2258 * has to succeed, so we clear checks with an additional one here.
2259 * In any case it's not our business how revaliadation is implemented.
2261 for (i = 0; i < 3; i++) { /* Retries for the schwag key from KS'04 */
2262 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2263 if (rc != 0x6) break;
2268 for (i = 0; i < 3; i++) {
2269 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2278 for (i = 0; i < nluns; i++) {
2279 ub_probe_lun(sc, i);
2284 usb_set_intfdata(intf, NULL);
2285 usb_put_intf(sc->intf);
2286 usb_put_dev(sc->dev);
2292 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2295 struct request_queue *q;
2296 struct gendisk *disk;
2300 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2305 if ((lun->id = ub_id_get()) == -1)
2310 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2311 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2313 lun->removable = 1; /* XXX Query this from the device */
2314 lun->changed = 1; /* ub_revalidate clears only */
2315 ub_revalidate(sc, lun);
2318 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2321 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2322 disk->major = UB_MAJOR;
2323 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2324 disk->fops = &ub_bd_fops;
2325 disk->private_data = lun;
2326 disk->driverfs_dev = &sc->intf->dev;
2329 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2334 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2335 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2336 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2337 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2338 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2339 blk_queue_hardsect_size(q, lun->capacity.bsize);
2343 list_add(&lun->link, &sc->luns);
2345 set_capacity(disk, lun->capacity.nsec);
2347 disk->flags |= GENHD_FL_REMOVABLE;
2363 static void ub_disconnect(struct usb_interface *intf)
2365 struct ub_dev *sc = usb_get_intfdata(intf);
2367 unsigned long flags;
2370 * Prevent ub_bd_release from pulling the rug from under us.
2371 * XXX This is starting to look like a kref.
2372 * XXX Why not to take this ref at probe time?
2374 spin_lock_irqsave(&ub_lock, flags);
2376 spin_unlock_irqrestore(&ub_lock, flags);
2379 * Fence stall clearings, operations triggered by unlinkings and so on.
2380 * We do not attempt to unlink any URBs, because we do not trust the
2381 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2383 atomic_set(&sc->poison, 1);
2386 * Wait for reset to end, if any.
2388 wait_event(sc->reset_wait, !sc->reset);
2391 * Blow away queued commands.
2393 * Actually, this never works, because before we get here
2394 * the HCD terminates outstanding URB(s). It causes our
2395 * SCSI command queue to advance, commands fail to submit,
2396 * and the whole queue drains. So, we just use this code to
2399 spin_lock_irqsave(sc->lock, flags);
2401 struct ub_scsi_cmd *cmd;
2403 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2404 cmd->error = -ENOTCONN;
2405 cmd->state = UB_CMDST_DONE;
2407 (*cmd->done)(sc, cmd);
2411 printk(KERN_WARNING "%s: "
2412 "%d was queued after shutdown\n", sc->name, cnt);
2415 spin_unlock_irqrestore(sc->lock, flags);
2418 * Unregister the upper layer.
2420 list_for_each_entry(lun, &sc->luns, link) {
2421 del_gendisk(lun->disk);
2423 * I wish I could do:
2424 * queue_flag_set(QUEUE_FLAG_DEAD, q);
2425 * As it is, we rely on our internal poisoning and let
2426 * the upper levels to spin furiously failing all the I/O.
2431 * Testing for -EINPROGRESS is always a bug, so we are bending
2432 * the rules a little.
2434 spin_lock_irqsave(sc->lock, flags);
2435 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2436 printk(KERN_WARNING "%s: "
2437 "URB is active after disconnect\n", sc->name);
2439 spin_unlock_irqrestore(sc->lock, flags);
2442 * There is virtually no chance that other CPU runs a timeout so long
2443 * after ub_urb_complete should have called del_timer, but only if HCD
2444 * didn't forget to deliver a callback on unlink.
2446 del_timer_sync(&sc->work_timer);
2449 * At this point there must be no commands coming from anyone
2450 * and no URBs left in transit.
2456 static struct usb_driver ub_driver = {
2459 .disconnect = ub_disconnect,
2460 .id_table = ub_usb_ids,
2461 .pre_reset = ub_pre_reset,
2462 .post_reset = ub_post_reset,
2465 static int __init ub_init(void)
2470 for (i = 0; i < UB_QLOCK_NUM; i++)
2471 spin_lock_init(&ub_qlockv[i]);
2473 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2476 if ((rc = usb_register(&ub_driver)) != 0)
2479 usb_usual_set_present(USB_US_TYPE_UB);
2483 unregister_blkdev(UB_MAJOR, DRV_NAME);
2488 static void __exit ub_exit(void)
2490 usb_deregister(&ub_driver);
2492 unregister_blkdev(UB_MAJOR, DRV_NAME);
2493 usb_usual_clear_present(USB_US_TYPE_UB);
2496 module_init(ub_init);
2497 module_exit(ub_exit);
2499 MODULE_LICENSE("GPL");