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 * -- Kill first_open (Al Viro fixed the block layer now)
12 * -- Do resets with usb_device_reset (needs a thread context, use khubd)
13 * -- set readonly flag for CDs, set removable flag for CF readers
14 * -- do inquiry and verify we got a disk and not a tape (for LUN mismatch)
15 * -- special case some senses, e.g. 3a/0 -> no media present, reduce retries
16 * -- verify the 13 conditions and do bulk resets
17 * -- kill last_pipe and simply do two-state clearing on both pipes
18 * -- verify protocol (bulk) from USB descriptors (maybe...)
20 * -- move top_sense and work_bcs into separate allocations (if they survive)
21 * for cache purists and esoteric architectures.
22 * -- prune comments, they are too volumnous
23 * -- Exterminate P3 printks
25 * -- Redo "benh's retries", perhaps have spin-up code to handle them. V:D=?
26 * -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/usb.h>
31 #include <linux/blkdev.h>
32 #include <linux/devfs_fs_kernel.h>
33 #include <linux/timer.h>
34 #include <scsi/scsi.h>
37 #define DEVFS_NAME DRV_NAME
42 * The command state machine is the key model for understanding of this driver.
44 * The general rule is that all transitions are done towards the bottom
45 * of the diagram, thus preventing any loops.
47 * An exception to that is how the STAT state is handled. A counter allows it
48 * to be re-entered along the path marked with [C].
54 * ub_scsi_cmd_start fails ->--------------------------------------\
61 * was -EPIPE -->-------------------------------->! CLEAR ! !
64 * was error -->------------------------------------- ! --------->\
66 * /--<-- cmd->dir == NONE ? ! !
73 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
76 * ! ! was error -->---- ! --------->\
77 * ! was error -->--------------------- ! ------------- ! --------->\
80 * \--->+--------+ ! ! !
81 * ! STAT !<--------------------------/ ! !
84 * [C] was -EPIPE -->-----------\ ! !
86 * +<---- len == 0 ! ! !
88 * ! was error -->--------------------------------------!---------->\
90 * +<---- bad CSW ! ! !
91 * +<---- bad tag ! ! !
97 * \------- ! --------------------[C]--------\ ! !
99 * cmd->error---\ +--------+ ! !
100 * ! +--------------->! SENSE !<----------/ !
101 * STAT_FAIL----/ +--------+ !
104 * \--------------------------------\--------------------->! DONE !
109 * Definitions which have to be scattered once we understand the layout better.
112 /* Transport (despite PR in the name) */
113 #define US_PR_BULK 0x50 /* bulk only */
116 #define US_SC_SCSI 0x06 /* Transparent */
119 * This many LUNs per USB device.
120 * Every one of them takes a host, see UB_MAX_HOSTS.
122 #define UB_MAX_LUNS 9
127 #define UB_MINORS_PER_MAJOR 8
129 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
131 #define UB_SENSE_SIZE 18
136 /* command block wrapper */
137 struct bulk_cb_wrap {
138 __le32 Signature; /* contains 'USBC' */
139 u32 Tag; /* unique per command id */
140 __le32 DataTransferLength; /* size of data */
141 u8 Flags; /* direction in bit 0 */
143 u8 Length; /* of of the CDB */
144 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
147 #define US_BULK_CB_WRAP_LEN 31
148 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
149 #define US_BULK_FLAG_IN 1
150 #define US_BULK_FLAG_OUT 0
152 /* command status wrapper */
153 struct bulk_cs_wrap {
154 __le32 Signature; /* should = 'USBS' */
155 u32 Tag; /* same as original command */
156 __le32 Residue; /* amount not transferred */
157 u8 Status; /* see below */
160 #define US_BULK_CS_WRAP_LEN 13
161 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
162 #define US_BULK_STAT_OK 0
163 #define US_BULK_STAT_FAIL 1
164 #define US_BULK_STAT_PHASE 2
166 /* bulk-only class specific requests */
167 #define US_BULK_RESET_REQUEST 0xff
168 #define US_BULK_GET_MAX_LUN 0xfe
174 #define UB_MAX_REQ_SG 1
175 #define UB_MAX_SECTORS 64
178 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
179 * even if a webcam hogs the bus, but some devices need time to spin up.
181 #define UB_URB_TIMEOUT (HZ*2)
182 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
183 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
184 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
187 * An instance of a SCSI command in transit.
189 #define UB_DIR_NONE 0
190 #define UB_DIR_READ 1
191 #define UB_DIR_ILLEGAL2 2
192 #define UB_DIR_WRITE 3
194 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
195 (((c)==UB_DIR_READ)? 'r': 'n'))
197 enum ub_scsi_cmd_state {
198 UB_CMDST_INIT, /* Initial state */
199 UB_CMDST_CMD, /* Command submitted */
200 UB_CMDST_DATA, /* Data phase */
201 UB_CMDST_CLR2STS, /* Clearing before requesting status */
202 UB_CMDST_STAT, /* Status phase */
203 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
204 UB_CMDST_CLRRS, /* Clearing before retrying status */
205 UB_CMDST_SENSE, /* Sending Request Sense */
206 UB_CMDST_DONE /* Final state */
209 static char *ub_scsi_cmd_stname[] = {
222 unsigned char cdb[UB_MAX_CDB_SIZE];
223 unsigned char cdb_len;
225 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
226 unsigned char trace_index;
227 enum ub_scsi_cmd_state state;
229 struct ub_scsi_cmd *next;
231 int error; /* Return code - valid upon done */
232 unsigned int act_len; /* Return size */
233 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
235 int stat_count; /* Retries getting status. */
238 * We do not support transfers from highmem pages
239 * because the underlying USB framework does not do what we need.
241 char *data; /* Requested buffer */
242 unsigned int len; /* Requested length */
243 // struct scatterlist sgv[UB_MAX_REQ_SG];
246 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
253 unsigned long nsec; /* Linux size - 512 byte sectors */
254 unsigned int bsize; /* Linux hardsect_size */
255 unsigned int bshift; /* Shift between 512 and hard sects */
259 * The SCSI command tracing structure.
262 #define SCMD_ST_HIST_SZ 8
263 #define SCMD_TRACE_SZ 63 /* Less than 4KB of 61-byte lines */
265 struct ub_scsi_cmd_trace {
268 unsigned int req_size, act_size;
271 unsigned char key, asc, ascq;
272 char st_hst[SCMD_ST_HIST_SZ];
275 struct ub_scsi_trace {
277 struct ub_scsi_cmd_trace vec[SCMD_TRACE_SZ];
281 * This is a direct take-off from linux/include/completion.h
282 * The difference is that I do not wait on this thing, just poll.
283 * When I want to wait (ub_probe), I just use the stock completion.
285 * Note that INIT_COMPLETION takes no lock. It is correct. But why
286 * in the bloody hell that thing takes struct instead of pointer to struct
287 * is quite beyond me. I just copied it from the stock completion.
289 struct ub_completion {
294 static inline void ub_init_completion(struct ub_completion *x)
297 spin_lock_init(&x->lock);
300 #define UB_INIT_COMPLETION(x) ((x).done = 0)
302 static void ub_complete(struct ub_completion *x)
306 spin_lock_irqsave(&x->lock, flags);
308 spin_unlock_irqrestore(&x->lock, flags);
311 static int ub_is_completed(struct ub_completion *x)
316 spin_lock_irqsave(&x->lock, flags);
318 spin_unlock_irqrestore(&x->lock, flags);
324 struct ub_scsi_cmd_queue {
326 struct ub_scsi_cmd *head, *tail;
330 * The block device instance (one per LUN).
334 struct list_head link;
335 struct gendisk *disk;
336 int id; /* Host index */
337 int num; /* LUN number */
340 int changed; /* Media was changed */
343 int first_open; /* Kludge. See ub_bd_open. */
345 /* Use Ingo's mempool if or when we have more than one command. */
347 * Currently we never need more than one command for the whole device.
348 * However, giving every LUN a command is a cheap and automatic way
349 * to enforce fairness between them.
352 struct ub_scsi_cmd cmdv[1];
354 struct ub_capacity capacity;
358 * The USB device instance.
362 atomic_t poison; /* The USB device is disconnected */
363 int openc; /* protected by ub_lock! */
364 /* kref is too implicit for our taste */
367 struct usb_device *dev;
368 struct usb_interface *intf;
370 struct list_head luns;
372 unsigned int send_bulk_pipe; /* cached pipe values */
373 unsigned int recv_bulk_pipe;
374 unsigned int send_ctrl_pipe;
375 unsigned int recv_ctrl_pipe;
377 struct tasklet_struct tasklet;
379 struct ub_scsi_cmd_queue cmd_queue;
380 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
381 unsigned char top_sense[UB_SENSE_SIZE];
383 struct ub_completion work_done;
385 struct timer_list work_timer;
386 int last_pipe; /* What might need clearing */
387 __le32 signature; /* Learned signature */
388 struct bulk_cb_wrap work_bcb;
389 struct bulk_cs_wrap work_bcs;
390 struct usb_ctrlrequest work_cr;
392 struct ub_scsi_trace tr;
397 static void ub_cleanup(struct ub_dev *sc);
398 static int ub_bd_rq_fn_1(struct ub_lun *lun, struct request *rq);
399 static int ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
400 struct ub_scsi_cmd *cmd, struct request *rq);
401 static int ub_cmd_build_packet(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
403 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
404 static void ub_end_rq(struct request *rq, int uptodate);
405 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
406 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
407 static void ub_scsi_action(unsigned long _dev);
408 static void ub_scsi_dispatch(struct ub_dev *sc);
409 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
410 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
411 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
412 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
413 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
414 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
415 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
417 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
418 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
419 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
420 struct ub_capacity *ret);
421 static int ub_probe_lun(struct ub_dev *sc, int lnum);
425 static struct usb_device_id ub_usb_ids[] = {
426 // { USB_DEVICE_VER(0x0781, 0x0002, 0x0009, 0x0009) }, /* SDDR-31 */
427 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
431 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
434 * Find me a way to identify "next free minor" for add_disk(),
435 * and the array disappears the next day. However, the number of
436 * hosts has something to do with the naming and /proc/partitions.
437 * This has to be thought out in detail before changing.
438 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
440 #define UB_MAX_HOSTS 26
441 static char ub_hostv[UB_MAX_HOSTS];
443 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
446 * The SCSI command tracing procedures.
449 static void ub_cmdtr_new(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
452 struct ub_scsi_cmd_trace *t;
454 if ((n = sc->tr.cur + 1) == SCMD_TRACE_SZ) n = 0;
457 memset(t, 0, sizeof(struct ub_scsi_cmd_trace));
461 t->req_size = cmd->len;
462 t->st_hst[0] = cmd->state;
465 cmd->trace_index = n;
468 static void ub_cmdtr_state(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
471 struct ub_scsi_cmd_trace *t;
473 t = &sc->tr.vec[cmd->trace_index];
474 if (t->tag == cmd->tag) {
475 if ((n = t->hcur + 1) == SCMD_ST_HIST_SZ) n = 0;
476 t->st_hst[n] = cmd->state;
481 static void ub_cmdtr_act_len(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
483 struct ub_scsi_cmd_trace *t;
485 t = &sc->tr.vec[cmd->trace_index];
486 if (t->tag == cmd->tag)
487 t->act_size = cmd->act_len;
490 static void ub_cmdtr_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
491 unsigned char *sense)
493 struct ub_scsi_cmd_trace *t;
495 t = &sc->tr.vec[cmd->trace_index];
496 if (t->tag == cmd->tag) {
497 t->key = sense[2] & 0x0F;
503 static ssize_t ub_diag_show(struct device *dev, struct device_attribute *attr, char *page)
505 struct usb_interface *intf;
513 struct ub_scsi_cmd_trace *t;
515 intf = to_usb_interface(dev);
516 sc = usb_get_intfdata(intf);
521 spin_lock_irqsave(&sc->lock, flags);
523 cnt += sprintf(page + cnt,
525 sc->cmd_queue.qlen, sc->cmd_queue.qmax);
527 list_for_each (p, &sc->luns) {
528 lun = list_entry(p, struct ub_lun, link);
529 cnt += sprintf(page + cnt,
530 "lun %u changed %d removable %d readonly %d\n",
531 lun->num, lun->changed, lun->removable, lun->readonly);
534 if ((nc = sc->tr.cur + 1) == SCMD_TRACE_SZ) nc = 0;
535 for (j = 0; j < SCMD_TRACE_SZ; j++) {
538 cnt += sprintf(page + cnt, "%08x %02x", t->tag, t->op);
539 if (t->op == REQUEST_SENSE) {
540 cnt += sprintf(page + cnt, " [sense %x %02x %02x]",
541 t->key, t->asc, t->ascq);
543 cnt += sprintf(page + cnt, " %c", UB_DIR_CHAR(t->dir));
544 cnt += sprintf(page + cnt, " [%5d %5d]",
545 t->req_size, t->act_size);
547 if ((nh = t->hcur + 1) == SCMD_ST_HIST_SZ) nh = 0;
548 for (i = 0; i < SCMD_ST_HIST_SZ; i++) {
549 cnt += sprintf(page + cnt, " %s",
550 ub_scsi_cmd_stname[(int)t->st_hst[nh]]);
551 if (++nh == SCMD_ST_HIST_SZ) nh = 0;
553 cnt += sprintf(page + cnt, "\n");
555 if (++nc == SCMD_TRACE_SZ) nc = 0;
558 spin_unlock_irqrestore(&sc->lock, flags);
562 static DEVICE_ATTR(diag, S_IRUGO, ub_diag_show, NULL); /* N.B. World readable */
567 * This also stores the host for indexing by minor, which is somewhat dirty.
569 static int ub_id_get(void)
574 spin_lock_irqsave(&ub_lock, flags);
575 for (i = 0; i < UB_MAX_HOSTS; i++) {
576 if (ub_hostv[i] == 0) {
578 spin_unlock_irqrestore(&ub_lock, flags);
582 spin_unlock_irqrestore(&ub_lock, flags);
586 static void ub_id_put(int id)
590 if (id < 0 || id >= UB_MAX_HOSTS) {
591 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
595 spin_lock_irqsave(&ub_lock, flags);
596 if (ub_hostv[id] == 0) {
597 spin_unlock_irqrestore(&ub_lock, flags);
598 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
602 spin_unlock_irqrestore(&ub_lock, flags);
606 * Downcount for deallocation. This rides on two assumptions:
607 * - once something is poisoned, its refcount cannot grow
608 * - opens cannot happen at this time (del_gendisk was done)
609 * If the above is true, we can drop the lock, which we need for
610 * blk_cleanup_queue(): the silly thing may attempt to sleep.
611 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
613 static void ub_put(struct ub_dev *sc)
617 spin_lock_irqsave(&ub_lock, flags);
619 if (sc->openc == 0 && atomic_read(&sc->poison)) {
620 spin_unlock_irqrestore(&ub_lock, flags);
623 spin_unlock_irqrestore(&ub_lock, flags);
628 * Final cleanup and deallocation.
630 static void ub_cleanup(struct ub_dev *sc)
636 while (!list_empty(&sc->luns)) {
638 lun = list_entry(p, struct ub_lun, link);
641 /* I don't think queue can be NULL. But... Stolen from sx8.c */
642 if ((q = lun->disk->queue) != NULL)
643 blk_cleanup_queue(q);
645 * If we zero disk->private_data BEFORE put_disk, we have
646 * to check for NULL all over the place in open, release,
647 * check_media and revalidate, because the block level
648 * semaphore is well inside the put_disk.
649 * But we cannot zero after the call, because *disk is gone.
650 * The sd.c is blatantly racy in this area.
652 /* disk->private_data = NULL; */
664 * The "command allocator".
666 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
668 struct ub_scsi_cmd *ret;
677 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
679 if (cmd != &lun->cmdv[0]) {
680 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
685 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
694 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
696 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
698 if (t->qlen++ == 0) {
706 if (t->qlen > t->qmax)
710 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
712 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
714 if (t->qlen++ == 0) {
722 if (t->qlen > t->qmax)
726 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
728 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
729 struct ub_scsi_cmd *cmd;
741 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
744 * The request function is our main entry point
747 static void ub_bd_rq_fn(request_queue_t *q)
749 struct ub_lun *lun = q->queuedata;
752 while ((rq = elv_next_request(q)) != NULL) {
753 if (ub_bd_rq_fn_1(lun, rq) != 0) {
760 static int ub_bd_rq_fn_1(struct ub_lun *lun, struct request *rq)
762 struct ub_dev *sc = lun->udev;
763 struct ub_scsi_cmd *cmd;
766 if (atomic_read(&sc->poison) || lun->changed) {
767 blkdev_dequeue_request(rq);
772 if ((cmd = ub_get_cmd(lun)) == NULL)
774 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
776 blkdev_dequeue_request(rq);
778 if (blk_pc_request(rq)) {
779 rc = ub_cmd_build_packet(sc, cmd, rq);
781 rc = ub_cmd_build_block(sc, lun, cmd, rq);
784 ub_put_cmd(lun, cmd);
788 cmd->state = UB_CMDST_INIT;
790 cmd->done = ub_rw_cmd_done;
793 cmd->tag = sc->tagcnt++;
794 if ((rc = ub_submit_scsi(sc, cmd)) != 0) {
795 ub_put_cmd(lun, cmd);
803 static int ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
804 struct ub_scsi_cmd *cmd, struct request *rq)
807 #if 0 /* We use rq->buffer for now */
808 struct scatterlist *sg;
811 unsigned int block, nblks;
813 if (rq_data_dir(rq) == WRITE)
814 ub_dir = UB_DIR_WRITE;
816 ub_dir = UB_DIR_READ;
819 * get scatterlist from block layer
821 #if 0 /* We use rq->buffer for now */
823 n_elem = blk_rq_map_sg(q, rq, sg);
825 ub_put_cmd(lun, cmd);
828 return 0; /* request with no s/g entries? */
831 if (n_elem != 1) { /* Paranoia */
832 printk(KERN_WARNING "%s: request with %d segments\n",
834 ub_put_cmd(lun, cmd);
842 * XXX Unfortunately, this check does not work. It is quite possible
843 * to get bogus non-null rq->buffer if you allow sg by mistake.
845 if (rq->buffer == NULL) {
847 * This must not happen if we set the queue right.
848 * The block level must create bounce buffers for us.
850 static int do_print = 1;
852 printk(KERN_WARNING "%s: unmapped block request"
853 " flags 0x%lx sectors %lu\n",
854 sc->name, rq->flags, rq->nr_sectors);
863 * The call to blk_queue_hardsect_size() guarantees that request
864 * is aligned, but it is given in terms of 512 byte units, always.
866 block = rq->sector >> lun->capacity.bshift;
867 nblks = rq->nr_sectors >> lun->capacity.bshift;
869 cmd->cdb[0] = (ub_dir == UB_DIR_READ)? READ_10: WRITE_10;
870 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
871 cmd->cdb[2] = block >> 24;
872 cmd->cdb[3] = block >> 16;
873 cmd->cdb[4] = block >> 8;
875 cmd->cdb[7] = nblks >> 8;
880 cmd->data = rq->buffer;
881 cmd->len = rq->nr_sectors * 512;
886 static int ub_cmd_build_packet(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
890 if (rq->data_len != 0 && rq->data == NULL) {
891 static int do_print = 1;
893 printk(KERN_WARNING "%s: unmapped packet request"
894 " flags 0x%lx length %d\n",
895 sc->name, rq->flags, rq->data_len);
901 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
902 cmd->cdb_len = rq->cmd_len;
904 if (rq->data_len == 0) {
905 cmd->dir = UB_DIR_NONE;
907 if (rq_data_dir(rq) == WRITE)
908 cmd->dir = UB_DIR_WRITE;
910 cmd->dir = UB_DIR_READ;
912 cmd->data = rq->data;
913 cmd->len = rq->data_len;
918 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
920 struct request *rq = cmd->back;
921 struct ub_lun *lun = cmd->lun;
922 struct gendisk *disk = lun->disk;
923 request_queue_t *q = disk->queue;
926 if (blk_pc_request(rq)) {
927 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
928 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
929 rq->sense_len = UB_SENSE_SIZE;
937 ub_put_cmd(lun, cmd);
938 ub_end_rq(rq, uptodate);
942 static void ub_end_rq(struct request *rq, int uptodate)
946 rc = end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
948 end_that_request_last(rq);
952 * Submit a regular SCSI operation (not an auto-sense).
954 * The Iron Law of Good Submit Routine is:
955 * Zero return - callback is done, Nonzero return - callback is not done.
958 * Host is assumed locked.
960 * XXX We only support Bulk for the moment.
962 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
965 if (cmd->state != UB_CMDST_INIT ||
966 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
970 ub_cmdq_add(sc, cmd);
972 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
973 * safer to jump to a tasklet, in case upper layers do something silly.
975 tasklet_schedule(&sc->tasklet);
980 * Submit the first URB for the queued command.
981 * This function does not deal with queueing in any way.
983 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
985 struct bulk_cb_wrap *bcb;
991 * ``If the allocation length is eighteen or greater, and a device
992 * server returns less than eithteen bytes of data, the application
993 * client should assume that the bytes not transferred would have been
994 * zeroes had the device server returned those bytes.''
996 * We zero sense for all commands so that when a packet request
997 * fails it does not return a stale sense.
999 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
1001 /* set up the command wrapper */
1002 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1003 bcb->Tag = cmd->tag; /* Endianness is not important */
1004 bcb->DataTransferLength = cpu_to_le32(cmd->len);
1005 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
1006 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
1007 bcb->Length = cmd->cdb_len;
1009 /* copy the command payload */
1010 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
1012 UB_INIT_COMPLETION(sc->work_done);
1014 sc->last_pipe = sc->send_bulk_pipe;
1015 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
1016 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
1017 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1019 /* Fill what we shouldn't be filling, because usb-storage did so. */
1020 sc->work_urb.actual_length = 0;
1021 sc->work_urb.error_count = 0;
1022 sc->work_urb.status = 0;
1024 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1025 /* XXX Clear stalls */
1026 printk("ub: cmd #%d start failed (%d)\n", cmd->tag, rc); /* P3 */
1027 ub_complete(&sc->work_done);
1031 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
1032 add_timer(&sc->work_timer);
1034 cmd->state = UB_CMDST_CMD;
1035 ub_cmdtr_state(sc, cmd);
1042 static void ub_urb_timeout(unsigned long arg)
1044 struct ub_dev *sc = (struct ub_dev *) arg;
1045 unsigned long flags;
1047 spin_lock_irqsave(&sc->lock, flags);
1048 usb_unlink_urb(&sc->work_urb);
1049 spin_unlock_irqrestore(&sc->lock, flags);
1053 * Completion routine for the work URB.
1055 * This can be called directly from usb_submit_urb (while we have
1056 * the sc->lock taken) and from an interrupt (while we do NOT have
1057 * the sc->lock taken). Therefore, bounce this off to a tasklet.
1059 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
1061 struct ub_dev *sc = urb->context;
1063 ub_complete(&sc->work_done);
1064 tasklet_schedule(&sc->tasklet);
1067 static void ub_scsi_action(unsigned long _dev)
1069 struct ub_dev *sc = (struct ub_dev *) _dev;
1070 unsigned long flags;
1072 spin_lock_irqsave(&sc->lock, flags);
1073 del_timer(&sc->work_timer);
1074 ub_scsi_dispatch(sc);
1075 spin_unlock_irqrestore(&sc->lock, flags);
1078 static void ub_scsi_dispatch(struct ub_dev *sc)
1080 struct ub_scsi_cmd *cmd;
1083 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
1084 if (cmd->state == UB_CMDST_DONE) {
1086 (*cmd->done)(sc, cmd);
1087 } else if (cmd->state == UB_CMDST_INIT) {
1088 ub_cmdtr_new(sc, cmd);
1089 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1092 cmd->state = UB_CMDST_DONE;
1093 ub_cmdtr_state(sc, cmd);
1095 if (!ub_is_completed(&sc->work_done))
1097 ub_scsi_urb_compl(sc, cmd);
1102 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1104 struct urb *urb = &sc->work_urb;
1105 struct bulk_cs_wrap *bcs;
1109 if (atomic_read(&sc->poison)) {
1110 /* A little too simplistic, I feel... */
1114 if (cmd->state == UB_CMDST_CLEAR) {
1115 if (urb->status == -EPIPE) {
1117 * STALL while clearning STALL.
1118 * The control pipe clears itself - nothing to do.
1119 * XXX Might try to reset the device here and retry.
1121 printk(KERN_NOTICE "%s: stall on control pipe\n",
1127 * We ignore the result for the halt clear.
1130 /* reset the endpoint toggle */
1131 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1132 usb_pipeout(sc->last_pipe), 0);
1134 ub_state_sense(sc, cmd);
1136 } else if (cmd->state == UB_CMDST_CLR2STS) {
1137 if (urb->status == -EPIPE) {
1139 * STALL while clearning STALL.
1140 * The control pipe clears itself - nothing to do.
1141 * XXX Might try to reset the device here and retry.
1143 printk(KERN_NOTICE "%s: stall on control pipe\n",
1149 * We ignore the result for the halt clear.
1152 /* reset the endpoint toggle */
1153 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1154 usb_pipeout(sc->last_pipe), 0);
1156 ub_state_stat(sc, cmd);
1158 } else if (cmd->state == UB_CMDST_CLRRS) {
1159 if (urb->status == -EPIPE) {
1161 * STALL while clearning STALL.
1162 * The control pipe clears itself - nothing to do.
1163 * XXX Might try to reset the device here and retry.
1165 printk(KERN_NOTICE "%s: stall on control pipe\n",
1171 * We ignore the result for the halt clear.
1174 /* reset the endpoint toggle */
1175 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1176 usb_pipeout(sc->last_pipe), 0);
1178 ub_state_stat_counted(sc, cmd);
1180 } else if (cmd->state == UB_CMDST_CMD) {
1181 if (urb->status == -EPIPE) {
1182 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1184 printk(KERN_NOTICE "%s: "
1185 "unable to submit clear (%d)\n",
1188 * This is typically ENOMEM or some other such shit.
1189 * Retrying is pointless. Just do Bad End on it...
1193 cmd->state = UB_CMDST_CLEAR;
1194 ub_cmdtr_state(sc, cmd);
1197 if (urb->status != 0) {
1198 printk("ub: cmd #%d cmd status (%d)\n", cmd->tag, urb->status); /* P3 */
1201 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1202 printk("ub: cmd #%d xferred %d\n", cmd->tag, urb->actual_length); /* P3 */
1203 /* XXX Must do reset here to unconfuse the device */
1207 if (cmd->dir == UB_DIR_NONE) {
1208 ub_state_stat(sc, cmd);
1212 UB_INIT_COMPLETION(sc->work_done);
1214 if (cmd->dir == UB_DIR_READ)
1215 pipe = sc->recv_bulk_pipe;
1217 pipe = sc->send_bulk_pipe;
1218 sc->last_pipe = pipe;
1219 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1220 cmd->data, cmd->len, ub_urb_complete, sc);
1221 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1222 sc->work_urb.actual_length = 0;
1223 sc->work_urb.error_count = 0;
1224 sc->work_urb.status = 0;
1226 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1227 /* XXX Clear stalls */
1228 printk("ub: data #%d submit failed (%d)\n", cmd->tag, rc); /* P3 */
1229 ub_complete(&sc->work_done);
1230 ub_state_done(sc, cmd, rc);
1234 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1235 add_timer(&sc->work_timer);
1237 cmd->state = UB_CMDST_DATA;
1238 ub_cmdtr_state(sc, cmd);
1240 } else if (cmd->state == UB_CMDST_DATA) {
1241 if (urb->status == -EPIPE) {
1242 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1244 printk(KERN_NOTICE "%s: "
1245 "unable to submit clear (%d)\n",
1248 * This is typically ENOMEM or some other such shit.
1249 * Retrying is pointless. Just do Bad End on it...
1253 cmd->state = UB_CMDST_CLR2STS;
1254 ub_cmdtr_state(sc, cmd);
1257 if (urb->status == -EOVERFLOW) {
1259 * A babble? Failure, but we must transfer CSW now.
1261 cmd->error = -EOVERFLOW; /* A cheap trick... */
1263 if (urb->status != 0)
1267 cmd->act_len = urb->actual_length;
1268 ub_cmdtr_act_len(sc, cmd);
1270 ub_state_stat(sc, cmd);
1272 } else if (cmd->state == UB_CMDST_STAT) {
1273 if (urb->status == -EPIPE) {
1274 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1276 printk(KERN_NOTICE "%s: "
1277 "unable to submit clear (%d)\n",
1280 * This is typically ENOMEM or some other such shit.
1281 * Retrying is pointless. Just do Bad End on it...
1287 * Having a stall when getting CSW is an error, so
1288 * make sure uppper levels are not oblivious to it.
1290 cmd->error = -EIO; /* A cheap trick... */
1292 cmd->state = UB_CMDST_CLRRS;
1293 ub_cmdtr_state(sc, cmd);
1296 if (urb->status == -EOVERFLOW) {
1298 * XXX We are screwed here. Retrying is pointless,
1299 * because the pipelined data will not get in until
1300 * we read with a big enough buffer. We must reset XXX.
1304 if (urb->status != 0)
1307 if (urb->actual_length == 0) {
1308 ub_state_stat_counted(sc, cmd);
1313 * Check the returned Bulk protocol status.
1314 * The status block has to be validated first.
1317 bcs = &sc->work_bcs;
1319 if (sc->signature == cpu_to_le32(0)) {
1321 * This is the first reply, so do not perform the check.
1322 * Instead, remember the signature the device uses
1323 * for future checks. But do not allow a nul.
1325 sc->signature = bcs->Signature;
1326 if (sc->signature == cpu_to_le32(0)) {
1327 ub_state_stat_counted(sc, cmd);
1331 if (bcs->Signature != sc->signature) {
1332 ub_state_stat_counted(sc, cmd);
1337 if (bcs->Tag != cmd->tag) {
1339 * This usually happens when we disagree with the
1340 * device's microcode about something. For instance,
1341 * a few of them throw this after timeouts. They buffer
1342 * commands and reply at commands we timed out before.
1343 * Without flushing these replies we loop forever.
1345 ub_state_stat_counted(sc, cmd);
1349 rc = le32_to_cpu(bcs->Residue);
1350 if (rc != cmd->len - cmd->act_len) {
1352 * It is all right to transfer less, the caller has
1353 * to check. But it's not all right if the device
1354 * counts disagree with our counts.
1356 /* P3 */ printk("%s: resid %d len %d act %d\n",
1357 sc->name, rc, cmd->len, cmd->act_len);
1361 switch (bcs->Status) {
1362 case US_BULK_STAT_OK:
1364 case US_BULK_STAT_FAIL:
1365 ub_state_sense(sc, cmd);
1367 case US_BULK_STAT_PHASE:
1368 /* XXX We must reset the transport here */
1369 /* P3 */ printk("%s: status PHASE\n", sc->name);
1372 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1373 sc->name, bcs->Status);
1377 /* Not zeroing error to preserve a babble indicator */
1378 if (cmd->error != 0) {
1379 ub_state_sense(sc, cmd);
1382 cmd->state = UB_CMDST_DONE;
1383 ub_cmdtr_state(sc, cmd);
1385 (*cmd->done)(sc, cmd);
1387 } else if (cmd->state == UB_CMDST_SENSE) {
1388 ub_state_done(sc, cmd, -EIO);
1391 printk(KERN_WARNING "%s: "
1392 "wrong command state %d\n",
1393 sc->name, cmd->state);
1398 Bad_End: /* Little Excel is dead */
1399 ub_state_done(sc, cmd, -EIO);
1403 * Factorization helper for the command state machine:
1404 * Finish the command.
1406 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1410 cmd->state = UB_CMDST_DONE;
1411 ub_cmdtr_state(sc, cmd);
1413 (*cmd->done)(sc, cmd);
1417 * Factorization helper for the command state machine:
1418 * Submit a CSW read.
1420 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1424 UB_INIT_COMPLETION(sc->work_done);
1426 sc->last_pipe = sc->recv_bulk_pipe;
1427 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1428 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1429 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1430 sc->work_urb.actual_length = 0;
1431 sc->work_urb.error_count = 0;
1432 sc->work_urb.status = 0;
1434 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1435 /* XXX Clear stalls */
1436 ub_complete(&sc->work_done);
1437 ub_state_done(sc, cmd, rc);
1441 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1442 add_timer(&sc->work_timer);
1447 * Factorization helper for the command state machine:
1448 * Submit a CSW read and go to STAT state.
1450 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1453 if (__ub_state_stat(sc, cmd) != 0)
1456 cmd->stat_count = 0;
1457 cmd->state = UB_CMDST_STAT;
1458 ub_cmdtr_state(sc, cmd);
1462 * Factorization helper for the command state machine:
1463 * Submit a CSW read and go to STAT state with counter (along [C] path).
1465 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1468 if (++cmd->stat_count >= 4) {
1469 ub_state_sense(sc, cmd);
1473 if (__ub_state_stat(sc, cmd) != 0)
1476 cmd->state = UB_CMDST_STAT;
1477 ub_cmdtr_state(sc, cmd);
1481 * Factorization helper for the command state machine:
1482 * Submit a REQUEST SENSE and go to SENSE state.
1484 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1486 struct ub_scsi_cmd *scmd;
1489 if (cmd->cdb[0] == REQUEST_SENSE) {
1494 scmd = &sc->top_rqs_cmd;
1495 scmd->cdb[0] = REQUEST_SENSE;
1496 scmd->cdb[4] = UB_SENSE_SIZE;
1498 scmd->dir = UB_DIR_READ;
1499 scmd->state = UB_CMDST_INIT;
1500 scmd->data = sc->top_sense;
1501 scmd->len = UB_SENSE_SIZE;
1502 scmd->lun = cmd->lun;
1503 scmd->done = ub_top_sense_done;
1506 scmd->tag = sc->tagcnt++;
1508 cmd->state = UB_CMDST_SENSE;
1509 ub_cmdtr_state(sc, cmd);
1511 ub_cmdq_insert(sc, scmd);
1515 ub_state_done(sc, cmd, rc);
1519 * A helper for the command's state machine:
1520 * Submit a stall clear.
1522 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1526 struct usb_ctrlrequest *cr;
1529 endp = usb_pipeendpoint(stalled_pipe);
1530 if (usb_pipein (stalled_pipe))
1534 cr->bRequestType = USB_RECIP_ENDPOINT;
1535 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1536 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1537 cr->wIndex = cpu_to_le16(endp);
1538 cr->wLength = cpu_to_le16(0);
1540 UB_INIT_COMPLETION(sc->work_done);
1542 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1543 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1544 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1545 sc->work_urb.actual_length = 0;
1546 sc->work_urb.error_count = 0;
1547 sc->work_urb.status = 0;
1549 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1550 ub_complete(&sc->work_done);
1554 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1555 add_timer(&sc->work_timer);
1561 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1563 unsigned char *sense = scmd->data;
1564 struct ub_scsi_cmd *cmd;
1567 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1569 ub_cmdtr_sense(sc, scmd, sense);
1572 * Find the command which triggered the unit attention or a check,
1573 * save the sense into it, and advance its state machine.
1575 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1576 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1579 if (cmd != scmd->back) {
1580 printk(KERN_WARNING "%s: "
1581 "sense done for wrong command 0x%x\n",
1582 sc->name, cmd->tag);
1585 if (cmd->state != UB_CMDST_SENSE) {
1586 printk(KERN_WARNING "%s: "
1587 "sense done with bad cmd state %d\n",
1588 sc->name, cmd->state);
1592 cmd->key = sense[2] & 0x0F;
1593 cmd->asc = sense[12];
1594 cmd->ascq = sense[13];
1596 ub_scsi_urb_compl(sc, cmd);
1600 * This is called from a process context.
1602 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1605 lun->readonly = 0; /* XXX Query this from the device */
1607 lun->capacity.nsec = 0;
1608 lun->capacity.bsize = 512;
1609 lun->capacity.bshift = 0;
1611 if (ub_sync_tur(sc, lun) != 0)
1612 return; /* Not ready */
1615 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1617 * The retry here means something is wrong, either with the
1618 * device, with the transport, or with our code.
1619 * We keep this because sd.c has retries for capacity.
1621 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1622 lun->capacity.nsec = 0;
1623 lun->capacity.bsize = 512;
1624 lun->capacity.bshift = 0;
1631 * This is mostly needed to keep refcounting, but also to support
1632 * media checks on removable media drives.
1634 static int ub_bd_open(struct inode *inode, struct file *filp)
1636 struct gendisk *disk = inode->i_bdev->bd_disk;
1639 unsigned long flags;
1642 if ((lun = disk->private_data) == NULL)
1646 spin_lock_irqsave(&ub_lock, flags);
1647 if (atomic_read(&sc->poison)) {
1648 spin_unlock_irqrestore(&ub_lock, flags);
1652 spin_unlock_irqrestore(&ub_lock, flags);
1655 * This is a workaround for a specific problem in our block layer.
1656 * In 2.6.9, register_disk duplicates the code from rescan_partitions.
1657 * However, if we do add_disk with a device which persistently reports
1658 * a changed media, add_disk calls register_disk, which does do_open,
1659 * which will call rescan_paritions for changed media. After that,
1660 * register_disk attempts to do it all again and causes double kobject
1661 * registration and a eventually an oops on module removal.
1663 * The bottom line is, Al Viro says that we should not allow
1664 * bdev->bd_invalidated to be set when doing add_disk no matter what.
1666 if (lun->first_open) {
1667 lun->first_open = 0;
1674 if (lun->removable || lun->readonly)
1675 check_disk_change(inode->i_bdev);
1678 * The sd.c considers ->media_present and ->changed not equivalent,
1679 * under some pretty murky conditions (a failure of READ CAPACITY).
1680 * We may need it one day.
1682 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1687 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1701 static int ub_bd_release(struct inode *inode, struct file *filp)
1703 struct gendisk *disk = inode->i_bdev->bd_disk;
1704 struct ub_lun *lun = disk->private_data;
1705 struct ub_dev *sc = lun->udev;
1712 * The ioctl interface.
1714 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1715 unsigned int cmd, unsigned long arg)
1717 struct gendisk *disk = inode->i_bdev->bd_disk;
1718 void __user *usermem = (void __user *) arg;
1720 return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1724 * This is called once a new disk was seen by the block layer or by ub_probe().
1725 * The main onjective here is to discover the features of the media such as
1726 * the capacity, read-only status, etc. USB storage generally does not
1727 * need to be spun up, but if we needed it, this would be the place.
1729 * This call can sleep.
1731 * The return code is not used.
1733 static int ub_bd_revalidate(struct gendisk *disk)
1735 struct ub_lun *lun = disk->private_data;
1737 ub_revalidate(lun->udev, lun);
1739 /* XXX Support sector size switching like in sr.c */
1740 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1741 set_capacity(disk, lun->capacity.nsec);
1742 // set_disk_ro(sdkp->disk, lun->readonly);
1748 * The check is called by the block layer to verify if the media
1749 * is still available. It is supposed to be harmless, lightweight and
1750 * non-intrusive in case the media was not changed.
1752 * This call can sleep.
1754 * The return code is bool!
1756 static int ub_bd_media_changed(struct gendisk *disk)
1758 struct ub_lun *lun = disk->private_data;
1760 if (!lun->removable)
1764 * We clean checks always after every command, so this is not
1765 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1766 * the device is actually not ready with operator or software
1767 * intervention required. One dangerous item might be a drive which
1768 * spins itself down, and come the time to write dirty pages, this
1769 * will fail, then block layer discards the data. Since we never
1770 * spin drives up, such devices simply cannot be used with ub anyway.
1772 if (ub_sync_tur(lun->udev, lun) != 0) {
1777 return lun->changed;
1780 static struct block_device_operations ub_bd_fops = {
1781 .owner = THIS_MODULE,
1783 .release = ub_bd_release,
1784 .ioctl = ub_bd_ioctl,
1785 .media_changed = ub_bd_media_changed,
1786 .revalidate_disk = ub_bd_revalidate,
1790 * Common ->done routine for commands executed synchronously.
1792 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1794 struct completion *cop = cmd->back;
1799 * Test if the device has a check condition on it, synchronously.
1801 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1803 struct ub_scsi_cmd *cmd;
1804 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1805 unsigned long flags;
1806 struct completion compl;
1809 init_completion(&compl);
1812 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1814 memset(cmd, 0, ALLOC_SIZE);
1816 cmd->cdb[0] = TEST_UNIT_READY;
1818 cmd->dir = UB_DIR_NONE;
1819 cmd->state = UB_CMDST_INIT;
1820 cmd->lun = lun; /* This may be NULL, but that's ok */
1821 cmd->done = ub_probe_done;
1824 spin_lock_irqsave(&sc->lock, flags);
1825 cmd->tag = sc->tagcnt++;
1827 rc = ub_submit_scsi(sc, cmd);
1828 spin_unlock_irqrestore(&sc->lock, flags);
1831 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
1835 wait_for_completion(&compl);
1839 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1849 * Read the SCSI capacity synchronously (for probing).
1851 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1852 struct ub_capacity *ret)
1854 struct ub_scsi_cmd *cmd;
1856 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1857 unsigned long flags;
1858 unsigned int bsize, shift;
1860 struct completion compl;
1863 init_completion(&compl);
1866 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1868 memset(cmd, 0, ALLOC_SIZE);
1869 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1873 cmd->dir = UB_DIR_READ;
1874 cmd->state = UB_CMDST_INIT;
1878 cmd->done = ub_probe_done;
1881 spin_lock_irqsave(&sc->lock, flags);
1882 cmd->tag = sc->tagcnt++;
1884 rc = ub_submit_scsi(sc, cmd);
1885 spin_unlock_irqrestore(&sc->lock, flags);
1888 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
1892 wait_for_completion(&compl);
1894 if (cmd->error != 0) {
1895 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
1899 if (cmd->act_len != 8) {
1900 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
1905 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1906 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1907 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1909 case 512: shift = 0; break;
1910 case 1024: shift = 1; break;
1911 case 2048: shift = 2; break;
1912 case 4096: shift = 3; break;
1914 printk("ub: Bad sector size %u\n", bsize); /* P3 */
1920 ret->bshift = shift;
1921 ret->nsec = nsec << shift;
1934 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
1936 struct completion *cop = urb->context;
1940 static void ub_probe_timeout(unsigned long arg)
1942 struct completion *cop = (struct completion *) arg;
1947 * Get number of LUNs by the way of Bulk GetMaxLUN command.
1949 static int ub_sync_getmaxlun(struct ub_dev *sc)
1951 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1953 enum { ALLOC_SIZE = 1 };
1954 struct usb_ctrlrequest *cr;
1955 struct completion compl;
1956 struct timer_list timer;
1960 init_completion(&compl);
1963 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1968 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1969 cr->bRequest = US_BULK_GET_MAX_LUN;
1970 cr->wValue = cpu_to_le16(0);
1971 cr->wIndex = cpu_to_le16(ifnum);
1972 cr->wLength = cpu_to_le16(1);
1974 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
1975 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
1976 sc->work_urb.transfer_flags = 0;
1977 sc->work_urb.actual_length = 0;
1978 sc->work_urb.error_count = 0;
1979 sc->work_urb.status = 0;
1981 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1983 printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
1987 "%s: Unable to submit GetMaxLUN (%d)\n",
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 if (sc->work_urb.actual_length != 1) {
2005 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2006 sc->work_urb.actual_length); /* P3 */
2009 if ((nluns = *p) == 55) {
2012 /* GetMaxLUN returns the maximum LUN number */
2014 if (nluns > UB_MAX_LUNS)
2015 nluns = UB_MAX_LUNS;
2017 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2018 *p, nluns); /* P3 */
2031 * Clear initial stalls.
2033 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2036 struct usb_ctrlrequest *cr;
2037 struct completion compl;
2038 struct timer_list timer;
2041 init_completion(&compl);
2043 endp = usb_pipeendpoint(stalled_pipe);
2044 if (usb_pipein (stalled_pipe))
2048 cr->bRequestType = USB_RECIP_ENDPOINT;
2049 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2050 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2051 cr->wIndex = cpu_to_le16(endp);
2052 cr->wLength = cpu_to_le16(0);
2054 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2055 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2056 sc->work_urb.transfer_flags = 0;
2057 sc->work_urb.actual_length = 0;
2058 sc->work_urb.error_count = 0;
2059 sc->work_urb.status = 0;
2061 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2063 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2068 timer.function = ub_probe_timeout;
2069 timer.data = (unsigned long) &compl;
2070 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2073 wait_for_completion(&compl);
2075 del_timer_sync(&timer);
2076 usb_kill_urb(&sc->work_urb);
2078 /* reset the endpoint toggle */
2079 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2085 * Get the pipe settings.
2087 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2088 struct usb_interface *intf)
2090 struct usb_host_interface *altsetting = intf->cur_altsetting;
2091 struct usb_endpoint_descriptor *ep_in = NULL;
2092 struct usb_endpoint_descriptor *ep_out = NULL;
2093 struct usb_endpoint_descriptor *ep;
2097 * Find the endpoints we need.
2098 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2099 * We will ignore any others.
2101 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2102 ep = &altsetting->endpoint[i].desc;
2104 /* Is it a BULK endpoint? */
2105 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2106 == USB_ENDPOINT_XFER_BULK) {
2107 /* BULK in or out? */
2108 if (ep->bEndpointAddress & USB_DIR_IN)
2115 if (ep_in == NULL || ep_out == NULL) {
2116 printk(KERN_NOTICE "%s: failed endpoint check\n",
2121 /* Calculate and store the pipe values */
2122 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2123 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2124 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2125 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2126 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2127 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2133 * Probing is done in the process context, which allows us to cheat
2134 * and not to build a state machine for the discovery.
2136 static int ub_probe(struct usb_interface *intf,
2137 const struct usb_device_id *dev_id)
2145 if ((sc = kmalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2147 memset(sc, 0, sizeof(struct ub_dev));
2148 spin_lock_init(&sc->lock);
2149 INIT_LIST_HEAD(&sc->luns);
2150 usb_init_urb(&sc->work_urb);
2151 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2152 atomic_set(&sc->poison, 0);
2154 init_timer(&sc->work_timer);
2155 sc->work_timer.data = (unsigned long) sc;
2156 sc->work_timer.function = ub_urb_timeout;
2158 ub_init_completion(&sc->work_done);
2159 sc->work_done.done = 1; /* A little yuk, but oh well... */
2161 sc->dev = interface_to_usbdev(intf);
2163 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2164 usb_set_intfdata(intf, sc);
2165 usb_get_dev(sc->dev);
2166 // usb_get_intf(sc->intf); /* Do we need this? */
2168 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2169 sc->dev->bus->busnum, sc->dev->devnum);
2171 /* XXX Verify that we can handle the device (from descriptors) */
2173 ub_get_pipes(sc, sc->dev, intf);
2175 if (device_create_file(&sc->intf->dev, &dev_attr_diag) != 0)
2179 * At this point, all USB initialization is done, do upper layer.
2180 * We really hate halfway initialized structures, so from the
2181 * invariants perspective, this ub_dev is fully constructed at
2186 * This is needed to clear toggles. It is a problem only if we do
2187 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2189 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2190 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2193 * The way this is used by the startup code is a little specific.
2194 * A SCSI check causes a USB stall. Our common case code sees it
2195 * and clears the check, after which the device is ready for use.
2196 * But if a check was not present, any command other than
2197 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2199 * If we neglect to clear the SCSI check, the first real command fails
2200 * (which is the capacity readout). We clear that and retry, but why
2201 * causing spurious retries for no reason.
2203 * Revalidation may start with its own TEST_UNIT_READY, but that one
2204 * has to succeed, so we clear checks with an additional one here.
2205 * In any case it's not our business how revaliadation is implemented.
2207 for (i = 0; i < 3; i++) { /* Retries for benh's key */
2208 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2209 if (rc != 0x6) break;
2214 for (i = 0; i < 3; i++) {
2215 if ((rc = ub_sync_getmaxlun(sc)) < 0) {
2217 * Some devices (i.e. Iomega Zip100) need this --
2218 * apparently the bulk pipes get STALLed when the
2219 * GetMaxLUN request is processed.
2220 * XXX I have a ZIP-100, verify it does this.
2223 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2224 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2235 for (i = 0; i < nluns; i++) {
2236 ub_probe_lun(sc, i);
2240 /* device_remove_file(&sc->intf->dev, &dev_attr_diag); */
2242 usb_set_intfdata(intf, NULL);
2243 // usb_put_intf(sc->intf);
2244 usb_put_dev(sc->dev);
2250 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2254 struct gendisk *disk;
2258 if ((lun = kmalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2260 memset(lun, 0, sizeof(struct ub_lun));
2264 if ((lun->id = ub_id_get()) == -1)
2268 list_add(&lun->link, &sc->luns);
2270 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2271 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2273 lun->removable = 1; /* XXX Query this from the device */
2274 lun->changed = 1; /* ub_revalidate clears only */
2275 lun->first_open = 1;
2276 ub_revalidate(sc, lun);
2279 if ((disk = alloc_disk(UB_MINORS_PER_MAJOR)) == NULL)
2283 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2284 sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2285 disk->major = UB_MAJOR;
2286 disk->first_minor = lun->id * UB_MINORS_PER_MAJOR;
2287 disk->fops = &ub_bd_fops;
2288 disk->private_data = lun;
2289 disk->driverfs_dev = &sc->intf->dev; /* XXX Many to one ok? */
2292 if ((q = blk_init_queue(ub_bd_rq_fn, &sc->lock)) == NULL)
2297 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2298 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2299 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2300 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2301 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2302 blk_queue_hardsect_size(q, lun->capacity.bsize);
2306 set_capacity(disk, lun->capacity.nsec);
2308 disk->flags |= GENHD_FL_REMOVABLE;
2317 list_del(&lun->link);
2325 static void ub_disconnect(struct usb_interface *intf)
2327 struct ub_dev *sc = usb_get_intfdata(intf);
2328 struct list_head *p;
2330 struct gendisk *disk;
2331 unsigned long flags;
2334 * Prevent ub_bd_release from pulling the rug from under us.
2335 * XXX This is starting to look like a kref.
2336 * XXX Why not to take this ref at probe time?
2338 spin_lock_irqsave(&ub_lock, flags);
2340 spin_unlock_irqrestore(&ub_lock, flags);
2343 * Fence stall clearnings, operations triggered by unlinkings and so on.
2344 * We do not attempt to unlink any URBs, because we do not trust the
2345 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2347 atomic_set(&sc->poison, 1);
2350 * Blow away queued commands.
2352 * Actually, this never works, because before we get here
2353 * the HCD terminates outstanding URB(s). It causes our
2354 * SCSI command queue to advance, commands fail to submit,
2355 * and the whole queue drains. So, we just use this code to
2358 spin_lock_irqsave(&sc->lock, flags);
2360 struct ub_scsi_cmd *cmd;
2362 while ((cmd = ub_cmdq_pop(sc)) != NULL) {
2363 cmd->error = -ENOTCONN;
2364 cmd->state = UB_CMDST_DONE;
2365 ub_cmdtr_state(sc, cmd);
2367 (*cmd->done)(sc, cmd);
2371 printk(KERN_WARNING "%s: "
2372 "%d was queued after shutdown\n", sc->name, cnt);
2375 spin_unlock_irqrestore(&sc->lock, flags);
2378 * Unregister the upper layer.
2380 list_for_each (p, &sc->luns) {
2381 lun = list_entry(p, struct ub_lun, link);
2383 if (disk->flags & GENHD_FL_UP)
2386 * I wish I could do:
2387 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2388 * As it is, we rely on our internal poisoning and let
2389 * the upper levels to spin furiously failing all the I/O.
2394 * Taking a lock on a structure which is about to be freed
2395 * is very nonsensual. Here it is largely a way to do a debug freeze,
2396 * and a bracket which shows where the nonsensual code segment ends.
2398 * Testing for -EINPROGRESS is always a bug, so we are bending
2399 * the rules a little.
2401 spin_lock_irqsave(&sc->lock, flags);
2402 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2403 printk(KERN_WARNING "%s: "
2404 "URB is active after disconnect\n", sc->name);
2406 spin_unlock_irqrestore(&sc->lock, flags);
2409 * There is virtually no chance that other CPU runs times so long
2410 * after ub_urb_complete should have called del_timer, but only if HCD
2411 * didn't forget to deliver a callback on unlink.
2413 del_timer_sync(&sc->work_timer);
2416 * At this point there must be no commands coming from anyone
2417 * and no URBs left in transit.
2420 device_remove_file(&sc->intf->dev, &dev_attr_diag);
2421 usb_set_intfdata(intf, NULL);
2422 // usb_put_intf(sc->intf);
2424 usb_put_dev(sc->dev);
2430 static struct usb_driver ub_driver = {
2431 .owner = THIS_MODULE,
2434 .disconnect = ub_disconnect,
2435 .id_table = ub_usb_ids,
2438 static int __init ub_init(void)
2442 /* P3 */ printk("ub: sizeof ub_scsi_cmd %zu ub_dev %zu ub_lun %zu\n",
2443 sizeof(struct ub_scsi_cmd), sizeof(struct ub_dev), sizeof(struct ub_lun));
2445 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2447 devfs_mk_dir(DEVFS_NAME);
2449 if ((rc = usb_register(&ub_driver)) != 0)
2455 devfs_remove(DEVFS_NAME);
2456 unregister_blkdev(UB_MAJOR, DRV_NAME);
2461 static void __exit ub_exit(void)
2463 usb_deregister(&ub_driver);
2465 devfs_remove(DEVFS_NAME);
2466 unregister_blkdev(UB_MAJOR, DRV_NAME);
2469 module_init(ub_init);
2470 module_exit(ub_exit);
2472 MODULE_LICENSE("GPL");