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 * -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
23 * -- prune comments, they are too volumnous
24 * -- Exterminate P3 printks
26 * -- Redo "benh's retries", perhaps have spin-up code to handle them. V:D=?
27 * -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
29 #include <linux/kernel.h>
30 #include <linux/module.h>
31 #include <linux/usb.h>
32 #include <linux/blkdev.h>
33 #include <linux/devfs_fs_kernel.h>
34 #include <linux/timer.h>
35 #include <scsi/scsi.h>
38 #define DEVFS_NAME DRV_NAME
43 * The command state machine is the key model for understanding of this driver.
45 * The general rule is that all transitions are done towards the bottom
46 * of the diagram, thus preventing any loops.
48 * An exception to that is how the STAT state is handled. A counter allows it
49 * to be re-entered along the path marked with [C].
55 * ub_scsi_cmd_start fails ->--------------------------------------\
62 * was -EPIPE -->-------------------------------->! CLEAR ! !
65 * was error -->------------------------------------- ! --------->\
67 * /--<-- cmd->dir == NONE ? ! !
74 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
77 * ! ! was error -->---- ! --------->\
78 * ! was error -->--------------------- ! ------------- ! --------->\
81 * \--->+--------+ ! ! !
82 * ! STAT !<--------------------------/ ! !
85 * [C] was -EPIPE -->-----------\ ! !
87 * +<---- len == 0 ! ! !
89 * ! was error -->--------------------------------------!---------->\
91 * +<---- bad CSW ! ! !
92 * +<---- bad tag ! ! !
98 * \------- ! --------------------[C]--------\ ! !
100 * cmd->error---\ +--------+ ! !
101 * ! +--------------->! SENSE !<----------/ !
102 * STAT_FAIL----/ +--------+ !
105 * \--------------------------------\--------------------->! DONE !
110 * Definitions which have to be scattered once we understand the layout better.
113 /* Transport (despite PR in the name) */
114 #define US_PR_BULK 0x50 /* bulk only */
117 #define US_SC_SCSI 0x06 /* Transparent */
120 * This many LUNs per USB device.
121 * Every one of them takes a host, see UB_MAX_HOSTS.
123 #define UB_MAX_LUNS 9
128 #define UB_MINORS_PER_MAJOR 8
130 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
132 #define UB_SENSE_SIZE 18
137 /* command block wrapper */
138 struct bulk_cb_wrap {
139 __le32 Signature; /* contains 'USBC' */
140 u32 Tag; /* unique per command id */
141 __le32 DataTransferLength; /* size of data */
142 u8 Flags; /* direction in bit 0 */
144 u8 Length; /* of of the CDB */
145 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
148 #define US_BULK_CB_WRAP_LEN 31
149 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
150 #define US_BULK_FLAG_IN 1
151 #define US_BULK_FLAG_OUT 0
153 /* command status wrapper */
154 struct bulk_cs_wrap {
155 __le32 Signature; /* should = 'USBS' */
156 u32 Tag; /* same as original command */
157 __le32 Residue; /* amount not transferred */
158 u8 Status; /* see below */
161 #define US_BULK_CS_WRAP_LEN 13
162 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
163 #define US_BULK_STAT_OK 0
164 #define US_BULK_STAT_FAIL 1
165 #define US_BULK_STAT_PHASE 2
167 /* bulk-only class specific requests */
168 #define US_BULK_RESET_REQUEST 0xff
169 #define US_BULK_GET_MAX_LUN 0xfe
175 #define UB_MAX_REQ_SG 4
176 #define UB_MAX_SECTORS 64
179 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
180 * even if a webcam hogs the bus, but some devices need time to spin up.
182 #define UB_URB_TIMEOUT (HZ*2)
183 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
184 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
185 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
188 * An instance of a SCSI command in transit.
190 #define UB_DIR_NONE 0
191 #define UB_DIR_READ 1
192 #define UB_DIR_ILLEGAL2 2
193 #define UB_DIR_WRITE 3
195 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
196 (((c)==UB_DIR_READ)? 'r': 'n'))
198 enum ub_scsi_cmd_state {
199 UB_CMDST_INIT, /* Initial state */
200 UB_CMDST_CMD, /* Command submitted */
201 UB_CMDST_DATA, /* Data phase */
202 UB_CMDST_CLR2STS, /* Clearing before requesting status */
203 UB_CMDST_STAT, /* Status phase */
204 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
205 UB_CMDST_CLRRS, /* Clearing before retrying status */
206 UB_CMDST_SENSE, /* Sending Request Sense */
207 UB_CMDST_DONE /* Final state */
210 static char *ub_scsi_cmd_stname[] = {
223 unsigned char cdb[UB_MAX_CDB_SIZE];
224 unsigned char cdb_len;
226 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
227 unsigned char trace_index;
228 enum ub_scsi_cmd_state state;
230 struct ub_scsi_cmd *next;
232 int error; /* Return code - valid upon done */
233 unsigned int act_len; /* Return size */
234 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
236 int stat_count; /* Retries getting status. */
239 * We do not support transfers from highmem pages
240 * because the underlying USB framework does not do what we need.
242 char *data; /* Requested buffer */
243 unsigned int len; /* Requested length */
246 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
253 unsigned int current_block;
254 unsigned int current_sg;
255 unsigned int nsg; /* sgv[nsg] */
256 struct scatterlist sgv[UB_MAX_REQ_SG];
262 unsigned long nsec; /* Linux size - 512 byte sectors */
263 unsigned int bsize; /* Linux hardsect_size */
264 unsigned int bshift; /* Shift between 512 and hard sects */
268 * The SCSI command tracing structure.
271 #define SCMD_ST_HIST_SZ 8
272 #define SCMD_TRACE_SZ 63 /* Less than 4KB of 61-byte lines */
274 struct ub_scsi_cmd_trace {
277 unsigned int req_size, act_size;
280 unsigned char key, asc, ascq;
281 char st_hst[SCMD_ST_HIST_SZ];
284 struct ub_scsi_trace {
286 struct ub_scsi_cmd_trace vec[SCMD_TRACE_SZ];
290 * This is a direct take-off from linux/include/completion.h
291 * The difference is that I do not wait on this thing, just poll.
292 * When I want to wait (ub_probe), I just use the stock completion.
294 * Note that INIT_COMPLETION takes no lock. It is correct. But why
295 * in the bloody hell that thing takes struct instead of pointer to struct
296 * is quite beyond me. I just copied it from the stock completion.
298 struct ub_completion {
303 static inline void ub_init_completion(struct ub_completion *x)
306 spin_lock_init(&x->lock);
309 #define UB_INIT_COMPLETION(x) ((x).done = 0)
311 static void ub_complete(struct ub_completion *x)
315 spin_lock_irqsave(&x->lock, flags);
317 spin_unlock_irqrestore(&x->lock, flags);
320 static int ub_is_completed(struct ub_completion *x)
325 spin_lock_irqsave(&x->lock, flags);
327 spin_unlock_irqrestore(&x->lock, flags);
333 struct ub_scsi_cmd_queue {
335 struct ub_scsi_cmd *head, *tail;
339 * The block device instance (one per LUN).
343 struct list_head link;
344 struct gendisk *disk;
345 int id; /* Host index */
346 int num; /* LUN number */
349 int changed; /* Media was changed */
352 int first_open; /* Kludge. See ub_bd_open. */
354 struct ub_request urq;
356 /* Use Ingo's mempool if or when we have more than one command. */
358 * Currently we never need more than one command for the whole device.
359 * However, giving every LUN a command is a cheap and automatic way
360 * to enforce fairness between them.
363 struct ub_scsi_cmd cmdv[1];
365 struct ub_capacity capacity;
369 * The USB device instance.
373 atomic_t poison; /* The USB device is disconnected */
374 int openc; /* protected by ub_lock! */
375 /* kref is too implicit for our taste */
378 struct usb_device *dev;
379 struct usb_interface *intf;
381 struct list_head luns;
383 unsigned int send_bulk_pipe; /* cached pipe values */
384 unsigned int recv_bulk_pipe;
385 unsigned int send_ctrl_pipe;
386 unsigned int recv_ctrl_pipe;
388 struct tasklet_struct tasklet;
390 struct ub_scsi_cmd_queue cmd_queue;
391 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
392 unsigned char top_sense[UB_SENSE_SIZE];
394 struct ub_completion work_done;
396 struct timer_list work_timer;
397 int last_pipe; /* What might need clearing */
398 __le32 signature; /* Learned signature */
399 struct bulk_cb_wrap work_bcb;
400 struct bulk_cs_wrap work_bcs;
401 struct usb_ctrlrequest work_cr;
403 int sg_stat[UB_MAX_REQ_SG+1];
404 struct ub_scsi_trace tr;
409 static void ub_cleanup(struct ub_dev *sc);
410 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
411 static int ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
412 struct ub_scsi_cmd *cmd, struct request *rq);
413 static void ub_scsi_build_block(struct ub_lun *lun,
414 struct ub_scsi_cmd *cmd, struct ub_request *urq);
415 static int ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
416 struct ub_scsi_cmd *cmd, struct request *rq);
417 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
418 static void ub_end_rq(struct request *rq, int uptodate);
419 static int ub_request_advance(struct ub_dev *sc, struct ub_lun *lun,
420 struct ub_request *urq, struct ub_scsi_cmd *cmd);
421 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
422 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
423 static void ub_scsi_action(unsigned long _dev);
424 static void ub_scsi_dispatch(struct ub_dev *sc);
425 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
426 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
427 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
428 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
429 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
430 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
431 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
433 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
434 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
435 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
436 struct ub_capacity *ret);
437 static int ub_probe_lun(struct ub_dev *sc, int lnum);
441 static struct usb_device_id ub_usb_ids[] = {
442 // { USB_DEVICE_VER(0x0781, 0x0002, 0x0009, 0x0009) }, /* SDDR-31 */
443 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
447 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
450 * Find me a way to identify "next free minor" for add_disk(),
451 * and the array disappears the next day. However, the number of
452 * hosts has something to do with the naming and /proc/partitions.
453 * This has to be thought out in detail before changing.
454 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
456 #define UB_MAX_HOSTS 26
457 static char ub_hostv[UB_MAX_HOSTS];
459 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
462 * The SCSI command tracing procedures.
465 static void ub_cmdtr_new(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
468 struct ub_scsi_cmd_trace *t;
470 if ((n = sc->tr.cur + 1) == SCMD_TRACE_SZ) n = 0;
473 memset(t, 0, sizeof(struct ub_scsi_cmd_trace));
477 t->req_size = cmd->len;
478 t->st_hst[0] = cmd->state;
481 cmd->trace_index = n;
484 static void ub_cmdtr_state(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
487 struct ub_scsi_cmd_trace *t;
489 t = &sc->tr.vec[cmd->trace_index];
490 if (t->tag == cmd->tag) {
491 if ((n = t->hcur + 1) == SCMD_ST_HIST_SZ) n = 0;
492 t->st_hst[n] = cmd->state;
497 static void ub_cmdtr_act_len(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
499 struct ub_scsi_cmd_trace *t;
501 t = &sc->tr.vec[cmd->trace_index];
502 if (t->tag == cmd->tag)
503 t->act_size = cmd->act_len;
506 static void ub_cmdtr_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
507 unsigned char *sense)
509 struct ub_scsi_cmd_trace *t;
511 t = &sc->tr.vec[cmd->trace_index];
512 if (t->tag == cmd->tag) {
513 t->key = sense[2] & 0x0F;
519 static ssize_t ub_diag_show(struct device *dev, struct device_attribute *attr,
522 struct usb_interface *intf;
530 struct ub_scsi_cmd_trace *t;
532 intf = to_usb_interface(dev);
533 sc = usb_get_intfdata(intf);
538 spin_lock_irqsave(&sc->lock, flags);
540 cnt += sprintf(page + cnt,
542 sc->cmd_queue.qlen, sc->cmd_queue.qmax);
543 cnt += sprintf(page + cnt,
544 "sg %d %d %d %d %d\n",
551 list_for_each (p, &sc->luns) {
552 lun = list_entry(p, struct ub_lun, link);
553 cnt += sprintf(page + cnt,
554 "lun %u changed %d removable %d readonly %d\n",
555 lun->num, lun->changed, lun->removable, lun->readonly);
558 if ((nc = sc->tr.cur + 1) == SCMD_TRACE_SZ) nc = 0;
559 for (j = 0; j < SCMD_TRACE_SZ; j++) {
562 cnt += sprintf(page + cnt, "%08x %02x", t->tag, t->op);
563 if (t->op == REQUEST_SENSE) {
564 cnt += sprintf(page + cnt, " [sense %x %02x %02x]",
565 t->key, t->asc, t->ascq);
567 cnt += sprintf(page + cnt, " %c", UB_DIR_CHAR(t->dir));
568 cnt += sprintf(page + cnt, " [%5d %5d]",
569 t->req_size, t->act_size);
571 if ((nh = t->hcur + 1) == SCMD_ST_HIST_SZ) nh = 0;
572 for (i = 0; i < SCMD_ST_HIST_SZ; i++) {
573 cnt += sprintf(page + cnt, " %s",
574 ub_scsi_cmd_stname[(int)t->st_hst[nh]]);
575 if (++nh == SCMD_ST_HIST_SZ) nh = 0;
577 cnt += sprintf(page + cnt, "\n");
579 if (++nc == SCMD_TRACE_SZ) nc = 0;
582 spin_unlock_irqrestore(&sc->lock, flags);
586 static DEVICE_ATTR(diag, S_IRUGO, ub_diag_show, NULL); /* N.B. World readable */
591 * This also stores the host for indexing by minor, which is somewhat dirty.
593 static int ub_id_get(void)
598 spin_lock_irqsave(&ub_lock, flags);
599 for (i = 0; i < UB_MAX_HOSTS; i++) {
600 if (ub_hostv[i] == 0) {
602 spin_unlock_irqrestore(&ub_lock, flags);
606 spin_unlock_irqrestore(&ub_lock, flags);
610 static void ub_id_put(int id)
614 if (id < 0 || id >= UB_MAX_HOSTS) {
615 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
619 spin_lock_irqsave(&ub_lock, flags);
620 if (ub_hostv[id] == 0) {
621 spin_unlock_irqrestore(&ub_lock, flags);
622 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
626 spin_unlock_irqrestore(&ub_lock, flags);
630 * Downcount for deallocation. This rides on two assumptions:
631 * - once something is poisoned, its refcount cannot grow
632 * - opens cannot happen at this time (del_gendisk was done)
633 * If the above is true, we can drop the lock, which we need for
634 * blk_cleanup_queue(): the silly thing may attempt to sleep.
635 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
637 static void ub_put(struct ub_dev *sc)
641 spin_lock_irqsave(&ub_lock, flags);
643 if (sc->openc == 0 && atomic_read(&sc->poison)) {
644 spin_unlock_irqrestore(&ub_lock, flags);
647 spin_unlock_irqrestore(&ub_lock, flags);
652 * Final cleanup and deallocation.
654 static void ub_cleanup(struct ub_dev *sc)
660 while (!list_empty(&sc->luns)) {
662 lun = list_entry(p, struct ub_lun, link);
665 /* I don't think queue can be NULL. But... Stolen from sx8.c */
666 if ((q = lun->disk->queue) != NULL)
667 blk_cleanup_queue(q);
669 * If we zero disk->private_data BEFORE put_disk, we have
670 * to check for NULL all over the place in open, release,
671 * check_media and revalidate, because the block level
672 * semaphore is well inside the put_disk.
673 * But we cannot zero after the call, because *disk is gone.
674 * The sd.c is blatantly racy in this area.
676 /* disk->private_data = NULL; */
688 * The "command allocator".
690 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
692 struct ub_scsi_cmd *ret;
701 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
703 if (cmd != &lun->cmdv[0]) {
704 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
709 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
718 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
720 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
722 if (t->qlen++ == 0) {
730 if (t->qlen > t->qmax)
734 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
736 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
738 if (t->qlen++ == 0) {
746 if (t->qlen > t->qmax)
750 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
752 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
753 struct ub_scsi_cmd *cmd;
765 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
768 * The request function is our main entry point
771 static void ub_request_fn(request_queue_t *q)
773 struct ub_lun *lun = q->queuedata;
776 while ((rq = elv_next_request(q)) != NULL) {
777 if (ub_request_fn_1(lun, rq) != 0) {
784 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
786 struct ub_dev *sc = lun->udev;
787 struct ub_scsi_cmd *cmd;
790 if (atomic_read(&sc->poison) || lun->changed) {
791 blkdev_dequeue_request(rq);
796 if (lun->urq.rq != NULL)
798 if ((cmd = ub_get_cmd(lun)) == NULL)
800 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
802 blkdev_dequeue_request(rq);
803 if (blk_pc_request(rq)) {
804 rc = ub_cmd_build_packet(sc, lun, cmd, rq);
806 rc = ub_cmd_build_block(sc, lun, cmd, rq);
809 ub_put_cmd(lun, cmd);
813 cmd->state = UB_CMDST_INIT;
815 cmd->done = ub_rw_cmd_done;
816 cmd->back = &lun->urq;
818 cmd->tag = sc->tagcnt++;
819 if (ub_submit_scsi(sc, cmd) != 0) {
820 ub_put_cmd(lun, cmd);
828 static int ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
829 struct ub_scsi_cmd *cmd, struct request *rq)
831 struct ub_request *urq;
836 memset(urq, 0, sizeof(struct ub_request));
838 if (rq_data_dir(rq) == WRITE)
839 ub_dir = UB_DIR_WRITE;
841 ub_dir = UB_DIR_READ;
844 * get scatterlist from block layer
846 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
848 printk(KERN_INFO "%s: failed request map (%d)\n",
849 sc->name, n_elem); /* P3 */
850 return -1; /* request with no s/g entries? */
852 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
853 printk(KERN_WARNING "%s: request with %d segments\n",
858 sc->sg_stat[n_elem]++;
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 urq->current_block = rq->sector >> lun->capacity.bshift;
867 // nblks = rq->nr_sectors >> lun->capacity.bshift;
873 ub_scsi_build_block(lun, cmd, urq);
877 static void ub_scsi_build_block(struct ub_lun *lun,
878 struct ub_scsi_cmd *cmd, struct ub_request *urq)
880 struct scatterlist *sg;
881 unsigned int block, nblks;
883 sg = &urq->sgv[urq->current_sg];
885 block = urq->current_block;
886 nblks = sg->length >> (lun->capacity.bshift + 9);
888 cmd->cdb[0] = (urq->dir == UB_DIR_READ)? READ_10: WRITE_10;
889 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
890 cmd->cdb[2] = block >> 24;
891 cmd->cdb[3] = block >> 16;
892 cmd->cdb[4] = block >> 8;
894 cmd->cdb[7] = nblks >> 8;
899 cmd->data = page_address(sg->page) + sg->offset;
900 cmd->len = sg->length;
903 static int ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
904 struct ub_scsi_cmd *cmd, struct request *rq)
906 struct ub_request *urq;
909 memset(urq, 0, sizeof(struct ub_request));
913 if (rq->data_len != 0 && rq->data == NULL) {
914 static int do_print = 1;
916 printk(KERN_WARNING "%s: unmapped packet request"
917 " flags 0x%lx length %d\n",
918 sc->name, rq->flags, rq->data_len);
924 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
925 cmd->cdb_len = rq->cmd_len;
927 if (rq->data_len == 0) {
928 cmd->dir = UB_DIR_NONE;
930 if (rq_data_dir(rq) == WRITE)
931 cmd->dir = UB_DIR_WRITE;
933 cmd->dir = UB_DIR_READ;
935 cmd->data = rq->data;
936 cmd->len = rq->data_len;
941 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
943 struct ub_lun *lun = cmd->lun;
944 struct ub_request *urq = cmd->back;
950 if (blk_pc_request(rq)) {
951 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
952 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
953 rq->sense_len = UB_SENSE_SIZE;
961 if (cmd->error == 0 && urq->current_sg+1 < urq->nsg) {
962 if (ub_request_advance(sc, lun, urq, cmd) == 0) {
963 /* Stay on target... */
971 ub_put_cmd(lun, cmd);
972 ub_end_rq(rq, uptodate);
973 blk_start_queue(lun->disk->queue);
976 static void ub_end_rq(struct request *rq, int uptodate)
980 rc = end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
982 end_that_request_last(rq);
985 static int ub_request_advance(struct ub_dev *sc, struct ub_lun *lun,
986 struct ub_request *urq, struct ub_scsi_cmd *cmd)
988 struct scatterlist *sg;
991 /* XXX This is temporary, until we sort out S/G in packet requests. */
992 if (blk_pc_request(urq->rq)) {
994 "2-segment packet request completed\n"); /* P3 */
998 sg = &urq->sgv[urq->current_sg];
999 nblks = sg->length >> (lun->capacity.bshift + 9);
1000 urq->current_block += nblks;
1004 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
1005 ub_scsi_build_block(lun, cmd, urq);
1006 cmd->state = UB_CMDST_INIT;
1008 cmd->done = ub_rw_cmd_done;
1009 cmd->back = &lun->urq;
1011 cmd->tag = sc->tagcnt++;
1012 if (ub_submit_scsi(sc, cmd) != 0) {
1020 * Submit a regular SCSI operation (not an auto-sense).
1022 * The Iron Law of Good Submit Routine is:
1023 * Zero return - callback is done, Nonzero return - callback is not done.
1026 * Host is assumed locked.
1028 * XXX We only support Bulk for the moment.
1030 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1033 if (cmd->state != UB_CMDST_INIT ||
1034 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
1038 ub_cmdq_add(sc, cmd);
1040 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
1041 * safer to jump to a tasklet, in case upper layers do something silly.
1043 tasklet_schedule(&sc->tasklet);
1048 * Submit the first URB for the queued command.
1049 * This function does not deal with queueing in any way.
1051 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1053 struct bulk_cb_wrap *bcb;
1056 bcb = &sc->work_bcb;
1059 * ``If the allocation length is eighteen or greater, and a device
1060 * server returns less than eithteen bytes of data, the application
1061 * client should assume that the bytes not transferred would have been
1062 * zeroes had the device server returned those bytes.''
1064 * We zero sense for all commands so that when a packet request
1065 * fails it does not return a stale sense.
1067 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
1069 /* set up the command wrapper */
1070 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1071 bcb->Tag = cmd->tag; /* Endianness is not important */
1072 bcb->DataTransferLength = cpu_to_le32(cmd->len);
1073 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
1074 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
1075 bcb->Length = cmd->cdb_len;
1077 /* copy the command payload */
1078 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
1080 UB_INIT_COMPLETION(sc->work_done);
1082 sc->last_pipe = sc->send_bulk_pipe;
1083 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
1084 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
1085 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1087 /* Fill what we shouldn't be filling, because usb-storage did so. */
1088 sc->work_urb.actual_length = 0;
1089 sc->work_urb.error_count = 0;
1090 sc->work_urb.status = 0;
1092 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1093 /* XXX Clear stalls */
1094 printk("ub: cmd #%d start failed (%d)\n", cmd->tag, rc); /* P3 */
1095 ub_complete(&sc->work_done);
1099 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
1100 add_timer(&sc->work_timer);
1102 cmd->state = UB_CMDST_CMD;
1103 ub_cmdtr_state(sc, cmd);
1110 static void ub_urb_timeout(unsigned long arg)
1112 struct ub_dev *sc = (struct ub_dev *) arg;
1113 unsigned long flags;
1115 spin_lock_irqsave(&sc->lock, flags);
1116 usb_unlink_urb(&sc->work_urb);
1117 spin_unlock_irqrestore(&sc->lock, flags);
1121 * Completion routine for the work URB.
1123 * This can be called directly from usb_submit_urb (while we have
1124 * the sc->lock taken) and from an interrupt (while we do NOT have
1125 * the sc->lock taken). Therefore, bounce this off to a tasklet.
1127 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
1129 struct ub_dev *sc = urb->context;
1131 ub_complete(&sc->work_done);
1132 tasklet_schedule(&sc->tasklet);
1135 static void ub_scsi_action(unsigned long _dev)
1137 struct ub_dev *sc = (struct ub_dev *) _dev;
1138 unsigned long flags;
1140 spin_lock_irqsave(&sc->lock, flags);
1141 del_timer(&sc->work_timer);
1142 ub_scsi_dispatch(sc);
1143 spin_unlock_irqrestore(&sc->lock, flags);
1146 static void ub_scsi_dispatch(struct ub_dev *sc)
1148 struct ub_scsi_cmd *cmd;
1151 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
1152 if (cmd->state == UB_CMDST_DONE) {
1154 (*cmd->done)(sc, cmd);
1155 } else if (cmd->state == UB_CMDST_INIT) {
1156 ub_cmdtr_new(sc, cmd);
1157 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1160 cmd->state = UB_CMDST_DONE;
1161 ub_cmdtr_state(sc, cmd);
1163 if (!ub_is_completed(&sc->work_done))
1165 ub_scsi_urb_compl(sc, cmd);
1170 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1172 struct urb *urb = &sc->work_urb;
1173 struct bulk_cs_wrap *bcs;
1177 if (atomic_read(&sc->poison)) {
1178 /* A little too simplistic, I feel... */
1182 if (cmd->state == UB_CMDST_CLEAR) {
1183 if (urb->status == -EPIPE) {
1185 * STALL while clearning STALL.
1186 * The control pipe clears itself - nothing to do.
1187 * XXX Might try to reset the device here and retry.
1189 printk(KERN_NOTICE "%s: stall on control pipe\n",
1195 * We ignore the result for the halt clear.
1198 /* reset the endpoint toggle */
1199 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1200 usb_pipeout(sc->last_pipe), 0);
1202 ub_state_sense(sc, cmd);
1204 } else if (cmd->state == UB_CMDST_CLR2STS) {
1205 if (urb->status == -EPIPE) {
1207 * STALL while clearning STALL.
1208 * The control pipe clears itself - nothing to do.
1209 * XXX Might try to reset the device here and retry.
1211 printk(KERN_NOTICE "%s: stall on control pipe\n",
1217 * We ignore the result for the halt clear.
1220 /* reset the endpoint toggle */
1221 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1222 usb_pipeout(sc->last_pipe), 0);
1224 ub_state_stat(sc, cmd);
1226 } else if (cmd->state == UB_CMDST_CLRRS) {
1227 if (urb->status == -EPIPE) {
1229 * STALL while clearning STALL.
1230 * The control pipe clears itself - nothing to do.
1231 * XXX Might try to reset the device here and retry.
1233 printk(KERN_NOTICE "%s: stall on control pipe\n",
1239 * We ignore the result for the halt clear.
1242 /* reset the endpoint toggle */
1243 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1244 usb_pipeout(sc->last_pipe), 0);
1246 ub_state_stat_counted(sc, cmd);
1248 } else if (cmd->state == UB_CMDST_CMD) {
1249 if (urb->status == -EPIPE) {
1250 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1252 printk(KERN_NOTICE "%s: "
1253 "unable to submit clear (%d)\n",
1256 * This is typically ENOMEM or some other such shit.
1257 * Retrying is pointless. Just do Bad End on it...
1261 cmd->state = UB_CMDST_CLEAR;
1262 ub_cmdtr_state(sc, cmd);
1265 if (urb->status != 0) {
1266 printk("ub: cmd #%d cmd status (%d)\n", cmd->tag, urb->status); /* P3 */
1269 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1270 printk("ub: cmd #%d xferred %d\n", cmd->tag, urb->actual_length); /* P3 */
1271 /* XXX Must do reset here to unconfuse the device */
1275 if (cmd->dir == UB_DIR_NONE) {
1276 ub_state_stat(sc, cmd);
1280 UB_INIT_COMPLETION(sc->work_done);
1282 if (cmd->dir == UB_DIR_READ)
1283 pipe = sc->recv_bulk_pipe;
1285 pipe = sc->send_bulk_pipe;
1286 sc->last_pipe = pipe;
1287 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1288 cmd->data, cmd->len, ub_urb_complete, sc);
1289 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1290 sc->work_urb.actual_length = 0;
1291 sc->work_urb.error_count = 0;
1292 sc->work_urb.status = 0;
1294 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1295 /* XXX Clear stalls */
1296 printk("ub: data #%d submit failed (%d)\n", cmd->tag, rc); /* P3 */
1297 ub_complete(&sc->work_done);
1298 ub_state_done(sc, cmd, rc);
1302 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1303 add_timer(&sc->work_timer);
1305 cmd->state = UB_CMDST_DATA;
1306 ub_cmdtr_state(sc, cmd);
1308 } else if (cmd->state == UB_CMDST_DATA) {
1309 if (urb->status == -EPIPE) {
1310 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1312 printk(KERN_NOTICE "%s: "
1313 "unable to submit clear (%d)\n",
1316 * This is typically ENOMEM or some other such shit.
1317 * Retrying is pointless. Just do Bad End on it...
1321 cmd->state = UB_CMDST_CLR2STS;
1322 ub_cmdtr_state(sc, cmd);
1325 if (urb->status == -EOVERFLOW) {
1327 * A babble? Failure, but we must transfer CSW now.
1329 cmd->error = -EOVERFLOW; /* A cheap trick... */
1331 if (urb->status != 0)
1335 cmd->act_len = urb->actual_length;
1336 ub_cmdtr_act_len(sc, cmd);
1338 ub_state_stat(sc, cmd);
1340 } else if (cmd->state == UB_CMDST_STAT) {
1341 if (urb->status == -EPIPE) {
1342 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1344 printk(KERN_NOTICE "%s: "
1345 "unable to submit clear (%d)\n",
1348 * This is typically ENOMEM or some other such shit.
1349 * Retrying is pointless. Just do Bad End on it...
1355 * Having a stall when getting CSW is an error, so
1356 * make sure uppper levels are not oblivious to it.
1358 cmd->error = -EIO; /* A cheap trick... */
1360 cmd->state = UB_CMDST_CLRRS;
1361 ub_cmdtr_state(sc, cmd);
1364 if (urb->status == -EOVERFLOW) {
1366 * XXX We are screwed here. Retrying is pointless,
1367 * because the pipelined data will not get in until
1368 * we read with a big enough buffer. We must reset XXX.
1372 if (urb->status != 0)
1375 if (urb->actual_length == 0) {
1376 ub_state_stat_counted(sc, cmd);
1381 * Check the returned Bulk protocol status.
1382 * The status block has to be validated first.
1385 bcs = &sc->work_bcs;
1387 if (sc->signature == cpu_to_le32(0)) {
1389 * This is the first reply, so do not perform the check.
1390 * Instead, remember the signature the device uses
1391 * for future checks. But do not allow a nul.
1393 sc->signature = bcs->Signature;
1394 if (sc->signature == cpu_to_le32(0)) {
1395 ub_state_stat_counted(sc, cmd);
1399 if (bcs->Signature != sc->signature) {
1400 ub_state_stat_counted(sc, cmd);
1405 if (bcs->Tag != cmd->tag) {
1407 * This usually happens when we disagree with the
1408 * device's microcode about something. For instance,
1409 * a few of them throw this after timeouts. They buffer
1410 * commands and reply at commands we timed out before.
1411 * Without flushing these replies we loop forever.
1413 ub_state_stat_counted(sc, cmd);
1417 rc = le32_to_cpu(bcs->Residue);
1418 if (rc != cmd->len - cmd->act_len) {
1420 * It is all right to transfer less, the caller has
1421 * to check. But it's not all right if the device
1422 * counts disagree with our counts.
1424 /* P3 */ printk("%s: resid %d len %d act %d\n",
1425 sc->name, rc, cmd->len, cmd->act_len);
1429 switch (bcs->Status) {
1430 case US_BULK_STAT_OK:
1432 case US_BULK_STAT_FAIL:
1433 ub_state_sense(sc, cmd);
1435 case US_BULK_STAT_PHASE:
1436 /* XXX We must reset the transport here */
1437 /* P3 */ printk("%s: status PHASE\n", sc->name);
1440 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1441 sc->name, bcs->Status);
1445 /* Not zeroing error to preserve a babble indicator */
1446 if (cmd->error != 0) {
1447 ub_state_sense(sc, cmd);
1450 cmd->state = UB_CMDST_DONE;
1451 ub_cmdtr_state(sc, cmd);
1453 (*cmd->done)(sc, cmd);
1455 } else if (cmd->state == UB_CMDST_SENSE) {
1456 ub_state_done(sc, cmd, -EIO);
1459 printk(KERN_WARNING "%s: "
1460 "wrong command state %d\n",
1461 sc->name, cmd->state);
1466 Bad_End: /* Little Excel is dead */
1467 ub_state_done(sc, cmd, -EIO);
1471 * Factorization helper for the command state machine:
1472 * Finish the command.
1474 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1478 cmd->state = UB_CMDST_DONE;
1479 ub_cmdtr_state(sc, cmd);
1481 (*cmd->done)(sc, cmd);
1485 * Factorization helper for the command state machine:
1486 * Submit a CSW read.
1488 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1492 UB_INIT_COMPLETION(sc->work_done);
1494 sc->last_pipe = sc->recv_bulk_pipe;
1495 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1496 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1497 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1498 sc->work_urb.actual_length = 0;
1499 sc->work_urb.error_count = 0;
1500 sc->work_urb.status = 0;
1502 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1503 /* XXX Clear stalls */
1504 ub_complete(&sc->work_done);
1505 ub_state_done(sc, cmd, rc);
1509 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1510 add_timer(&sc->work_timer);
1515 * Factorization helper for the command state machine:
1516 * Submit a CSW read and go to STAT state.
1518 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1521 if (__ub_state_stat(sc, cmd) != 0)
1524 cmd->stat_count = 0;
1525 cmd->state = UB_CMDST_STAT;
1526 ub_cmdtr_state(sc, cmd);
1530 * Factorization helper for the command state machine:
1531 * Submit a CSW read and go to STAT state with counter (along [C] path).
1533 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1536 if (++cmd->stat_count >= 4) {
1537 ub_state_sense(sc, cmd);
1541 if (__ub_state_stat(sc, cmd) != 0)
1544 cmd->state = UB_CMDST_STAT;
1545 ub_cmdtr_state(sc, cmd);
1549 * Factorization helper for the command state machine:
1550 * Submit a REQUEST SENSE and go to SENSE state.
1552 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1554 struct ub_scsi_cmd *scmd;
1557 if (cmd->cdb[0] == REQUEST_SENSE) {
1562 scmd = &sc->top_rqs_cmd;
1563 scmd->cdb[0] = REQUEST_SENSE;
1564 scmd->cdb[4] = UB_SENSE_SIZE;
1566 scmd->dir = UB_DIR_READ;
1567 scmd->state = UB_CMDST_INIT;
1568 scmd->data = sc->top_sense;
1569 scmd->len = UB_SENSE_SIZE;
1570 scmd->lun = cmd->lun;
1571 scmd->done = ub_top_sense_done;
1574 scmd->tag = sc->tagcnt++;
1576 cmd->state = UB_CMDST_SENSE;
1577 ub_cmdtr_state(sc, cmd);
1579 ub_cmdq_insert(sc, scmd);
1583 ub_state_done(sc, cmd, rc);
1587 * A helper for the command's state machine:
1588 * Submit a stall clear.
1590 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1594 struct usb_ctrlrequest *cr;
1597 endp = usb_pipeendpoint(stalled_pipe);
1598 if (usb_pipein (stalled_pipe))
1602 cr->bRequestType = USB_RECIP_ENDPOINT;
1603 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1604 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1605 cr->wIndex = cpu_to_le16(endp);
1606 cr->wLength = cpu_to_le16(0);
1608 UB_INIT_COMPLETION(sc->work_done);
1610 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1611 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1612 sc->work_urb.transfer_flags = URB_ASYNC_UNLINK;
1613 sc->work_urb.actual_length = 0;
1614 sc->work_urb.error_count = 0;
1615 sc->work_urb.status = 0;
1617 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1618 ub_complete(&sc->work_done);
1622 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1623 add_timer(&sc->work_timer);
1629 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1631 unsigned char *sense = scmd->data;
1632 struct ub_scsi_cmd *cmd;
1635 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1637 ub_cmdtr_sense(sc, scmd, sense);
1640 * Find the command which triggered the unit attention or a check,
1641 * save the sense into it, and advance its state machine.
1643 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1644 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1647 if (cmd != scmd->back) {
1648 printk(KERN_WARNING "%s: "
1649 "sense done for wrong command 0x%x\n",
1650 sc->name, cmd->tag);
1653 if (cmd->state != UB_CMDST_SENSE) {
1654 printk(KERN_WARNING "%s: "
1655 "sense done with bad cmd state %d\n",
1656 sc->name, cmd->state);
1660 cmd->key = sense[2] & 0x0F;
1661 cmd->asc = sense[12];
1662 cmd->ascq = sense[13];
1664 ub_scsi_urb_compl(sc, cmd);
1668 * This is called from a process context.
1670 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1673 lun->readonly = 0; /* XXX Query this from the device */
1675 lun->capacity.nsec = 0;
1676 lun->capacity.bsize = 512;
1677 lun->capacity.bshift = 0;
1679 if (ub_sync_tur(sc, lun) != 0)
1680 return; /* Not ready */
1683 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1685 * The retry here means something is wrong, either with the
1686 * device, with the transport, or with our code.
1687 * We keep this because sd.c has retries for capacity.
1689 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1690 lun->capacity.nsec = 0;
1691 lun->capacity.bsize = 512;
1692 lun->capacity.bshift = 0;
1699 * This is mostly needed to keep refcounting, but also to support
1700 * media checks on removable media drives.
1702 static int ub_bd_open(struct inode *inode, struct file *filp)
1704 struct gendisk *disk = inode->i_bdev->bd_disk;
1707 unsigned long flags;
1710 if ((lun = disk->private_data) == NULL)
1714 spin_lock_irqsave(&ub_lock, flags);
1715 if (atomic_read(&sc->poison)) {
1716 spin_unlock_irqrestore(&ub_lock, flags);
1720 spin_unlock_irqrestore(&ub_lock, flags);
1723 * This is a workaround for a specific problem in our block layer.
1724 * In 2.6.9, register_disk duplicates the code from rescan_partitions.
1725 * However, if we do add_disk with a device which persistently reports
1726 * a changed media, add_disk calls register_disk, which does do_open,
1727 * which will call rescan_paritions for changed media. After that,
1728 * register_disk attempts to do it all again and causes double kobject
1729 * registration and a eventually an oops on module removal.
1731 * The bottom line is, Al Viro says that we should not allow
1732 * bdev->bd_invalidated to be set when doing add_disk no matter what.
1734 if (lun->first_open) {
1735 lun->first_open = 0;
1742 if (lun->removable || lun->readonly)
1743 check_disk_change(inode->i_bdev);
1746 * The sd.c considers ->media_present and ->changed not equivalent,
1747 * under some pretty murky conditions (a failure of READ CAPACITY).
1748 * We may need it one day.
1750 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1755 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1769 static int ub_bd_release(struct inode *inode, struct file *filp)
1771 struct gendisk *disk = inode->i_bdev->bd_disk;
1772 struct ub_lun *lun = disk->private_data;
1773 struct ub_dev *sc = lun->udev;
1780 * The ioctl interface.
1782 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1783 unsigned int cmd, unsigned long arg)
1785 struct gendisk *disk = inode->i_bdev->bd_disk;
1786 void __user *usermem = (void __user *) arg;
1788 return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1792 * This is called once a new disk was seen by the block layer or by ub_probe().
1793 * The main onjective here is to discover the features of the media such as
1794 * the capacity, read-only status, etc. USB storage generally does not
1795 * need to be spun up, but if we needed it, this would be the place.
1797 * This call can sleep.
1799 * The return code is not used.
1801 static int ub_bd_revalidate(struct gendisk *disk)
1803 struct ub_lun *lun = disk->private_data;
1805 ub_revalidate(lun->udev, lun);
1807 /* XXX Support sector size switching like in sr.c */
1808 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1809 set_capacity(disk, lun->capacity.nsec);
1810 // set_disk_ro(sdkp->disk, lun->readonly);
1816 * The check is called by the block layer to verify if the media
1817 * is still available. It is supposed to be harmless, lightweight and
1818 * non-intrusive in case the media was not changed.
1820 * This call can sleep.
1822 * The return code is bool!
1824 static int ub_bd_media_changed(struct gendisk *disk)
1826 struct ub_lun *lun = disk->private_data;
1828 if (!lun->removable)
1832 * We clean checks always after every command, so this is not
1833 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1834 * the device is actually not ready with operator or software
1835 * intervention required. One dangerous item might be a drive which
1836 * spins itself down, and come the time to write dirty pages, this
1837 * will fail, then block layer discards the data. Since we never
1838 * spin drives up, such devices simply cannot be used with ub anyway.
1840 if (ub_sync_tur(lun->udev, lun) != 0) {
1845 return lun->changed;
1848 static struct block_device_operations ub_bd_fops = {
1849 .owner = THIS_MODULE,
1851 .release = ub_bd_release,
1852 .ioctl = ub_bd_ioctl,
1853 .media_changed = ub_bd_media_changed,
1854 .revalidate_disk = ub_bd_revalidate,
1858 * Common ->done routine for commands executed synchronously.
1860 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1862 struct completion *cop = cmd->back;
1867 * Test if the device has a check condition on it, synchronously.
1869 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1871 struct ub_scsi_cmd *cmd;
1872 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1873 unsigned long flags;
1874 struct completion compl;
1877 init_completion(&compl);
1880 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1882 memset(cmd, 0, ALLOC_SIZE);
1884 cmd->cdb[0] = TEST_UNIT_READY;
1886 cmd->dir = UB_DIR_NONE;
1887 cmd->state = UB_CMDST_INIT;
1888 cmd->lun = lun; /* This may be NULL, but that's ok */
1889 cmd->done = ub_probe_done;
1892 spin_lock_irqsave(&sc->lock, flags);
1893 cmd->tag = sc->tagcnt++;
1895 rc = ub_submit_scsi(sc, cmd);
1896 spin_unlock_irqrestore(&sc->lock, flags);
1899 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
1903 wait_for_completion(&compl);
1907 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1917 * Read the SCSI capacity synchronously (for probing).
1919 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1920 struct ub_capacity *ret)
1922 struct ub_scsi_cmd *cmd;
1924 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1925 unsigned long flags;
1926 unsigned int bsize, shift;
1928 struct completion compl;
1931 init_completion(&compl);
1934 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1936 memset(cmd, 0, ALLOC_SIZE);
1937 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1941 cmd->dir = UB_DIR_READ;
1942 cmd->state = UB_CMDST_INIT;
1946 cmd->done = ub_probe_done;
1949 spin_lock_irqsave(&sc->lock, flags);
1950 cmd->tag = sc->tagcnt++;
1952 rc = ub_submit_scsi(sc, cmd);
1953 spin_unlock_irqrestore(&sc->lock, flags);
1956 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
1960 wait_for_completion(&compl);
1962 if (cmd->error != 0) {
1963 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
1967 if (cmd->act_len != 8) {
1968 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
1973 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1974 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1975 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1977 case 512: shift = 0; break;
1978 case 1024: shift = 1; break;
1979 case 2048: shift = 2; break;
1980 case 4096: shift = 3; break;
1982 printk("ub: Bad sector size %u\n", bsize); /* P3 */
1988 ret->bshift = shift;
1989 ret->nsec = nsec << shift;
2002 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
2004 struct completion *cop = urb->context;
2008 static void ub_probe_timeout(unsigned long arg)
2010 struct completion *cop = (struct completion *) arg;
2015 * Get number of LUNs by the way of Bulk GetMaxLUN command.
2017 static int ub_sync_getmaxlun(struct ub_dev *sc)
2019 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2021 enum { ALLOC_SIZE = 1 };
2022 struct usb_ctrlrequest *cr;
2023 struct completion compl;
2024 struct timer_list timer;
2028 init_completion(&compl);
2031 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2036 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2037 cr->bRequest = US_BULK_GET_MAX_LUN;
2038 cr->wValue = cpu_to_le16(0);
2039 cr->wIndex = cpu_to_le16(ifnum);
2040 cr->wLength = cpu_to_le16(1);
2042 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2043 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2044 sc->work_urb.transfer_flags = 0;
2045 sc->work_urb.actual_length = 0;
2046 sc->work_urb.error_count = 0;
2047 sc->work_urb.status = 0;
2049 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2051 printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
2055 "%s: Unable to submit GetMaxLUN (%d)\n",
2062 timer.function = ub_probe_timeout;
2063 timer.data = (unsigned long) &compl;
2064 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2067 wait_for_completion(&compl);
2069 del_timer_sync(&timer);
2070 usb_kill_urb(&sc->work_urb);
2072 if (sc->work_urb.actual_length != 1) {
2073 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2074 sc->work_urb.actual_length); /* P3 */
2077 if ((nluns = *p) == 55) {
2080 /* GetMaxLUN returns the maximum LUN number */
2082 if (nluns > UB_MAX_LUNS)
2083 nluns = UB_MAX_LUNS;
2085 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2086 *p, nluns); /* P3 */
2099 * Clear initial stalls.
2101 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2104 struct usb_ctrlrequest *cr;
2105 struct completion compl;
2106 struct timer_list timer;
2109 init_completion(&compl);
2111 endp = usb_pipeendpoint(stalled_pipe);
2112 if (usb_pipein (stalled_pipe))
2116 cr->bRequestType = USB_RECIP_ENDPOINT;
2117 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2118 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2119 cr->wIndex = cpu_to_le16(endp);
2120 cr->wLength = cpu_to_le16(0);
2122 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2123 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2124 sc->work_urb.transfer_flags = 0;
2125 sc->work_urb.actual_length = 0;
2126 sc->work_urb.error_count = 0;
2127 sc->work_urb.status = 0;
2129 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2131 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2136 timer.function = ub_probe_timeout;
2137 timer.data = (unsigned long) &compl;
2138 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2141 wait_for_completion(&compl);
2143 del_timer_sync(&timer);
2144 usb_kill_urb(&sc->work_urb);
2146 /* reset the endpoint toggle */
2147 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2153 * Get the pipe settings.
2155 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2156 struct usb_interface *intf)
2158 struct usb_host_interface *altsetting = intf->cur_altsetting;
2159 struct usb_endpoint_descriptor *ep_in = NULL;
2160 struct usb_endpoint_descriptor *ep_out = NULL;
2161 struct usb_endpoint_descriptor *ep;
2165 * Find the endpoints we need.
2166 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2167 * We will ignore any others.
2169 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2170 ep = &altsetting->endpoint[i].desc;
2172 /* Is it a BULK endpoint? */
2173 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2174 == USB_ENDPOINT_XFER_BULK) {
2175 /* BULK in or out? */
2176 if (ep->bEndpointAddress & USB_DIR_IN)
2183 if (ep_in == NULL || ep_out == NULL) {
2184 printk(KERN_NOTICE "%s: failed endpoint check\n",
2189 /* Calculate and store the pipe values */
2190 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2191 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2192 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2193 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2194 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2195 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2201 * Probing is done in the process context, which allows us to cheat
2202 * and not to build a state machine for the discovery.
2204 static int ub_probe(struct usb_interface *intf,
2205 const struct usb_device_id *dev_id)
2213 if ((sc = kmalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2215 memset(sc, 0, sizeof(struct ub_dev));
2216 spin_lock_init(&sc->lock);
2217 INIT_LIST_HEAD(&sc->luns);
2218 usb_init_urb(&sc->work_urb);
2219 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2220 atomic_set(&sc->poison, 0);
2222 init_timer(&sc->work_timer);
2223 sc->work_timer.data = (unsigned long) sc;
2224 sc->work_timer.function = ub_urb_timeout;
2226 ub_init_completion(&sc->work_done);
2227 sc->work_done.done = 1; /* A little yuk, but oh well... */
2229 sc->dev = interface_to_usbdev(intf);
2231 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2232 usb_set_intfdata(intf, sc);
2233 usb_get_dev(sc->dev);
2234 // usb_get_intf(sc->intf); /* Do we need this? */
2236 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2237 sc->dev->bus->busnum, sc->dev->devnum);
2239 /* XXX Verify that we can handle the device (from descriptors) */
2241 ub_get_pipes(sc, sc->dev, intf);
2243 if (device_create_file(&sc->intf->dev, &dev_attr_diag) != 0)
2247 * At this point, all USB initialization is done, do upper layer.
2248 * We really hate halfway initialized structures, so from the
2249 * invariants perspective, this ub_dev is fully constructed at
2254 * This is needed to clear toggles. It is a problem only if we do
2255 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2257 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2258 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2261 * The way this is used by the startup code is a little specific.
2262 * A SCSI check causes a USB stall. Our common case code sees it
2263 * and clears the check, after which the device is ready for use.
2264 * But if a check was not present, any command other than
2265 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2267 * If we neglect to clear the SCSI check, the first real command fails
2268 * (which is the capacity readout). We clear that and retry, but why
2269 * causing spurious retries for no reason.
2271 * Revalidation may start with its own TEST_UNIT_READY, but that one
2272 * has to succeed, so we clear checks with an additional one here.
2273 * In any case it's not our business how revaliadation is implemented.
2275 for (i = 0; i < 3; i++) { /* Retries for benh's key */
2276 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2277 if (rc != 0x6) break;
2282 for (i = 0; i < 3; i++) {
2283 if ((rc = ub_sync_getmaxlun(sc)) < 0) {
2285 * Some devices (i.e. Iomega Zip100) need this --
2286 * apparently the bulk pipes get STALLed when the
2287 * GetMaxLUN request is processed.
2288 * XXX I have a ZIP-100, verify it does this.
2291 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2292 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2303 for (i = 0; i < nluns; i++) {
2304 ub_probe_lun(sc, i);
2308 /* device_remove_file(&sc->intf->dev, &dev_attr_diag); */
2310 usb_set_intfdata(intf, NULL);
2311 // usb_put_intf(sc->intf);
2312 usb_put_dev(sc->dev);
2318 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2322 struct gendisk *disk;
2326 if ((lun = kmalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2328 memset(lun, 0, sizeof(struct ub_lun));
2332 if ((lun->id = ub_id_get()) == -1)
2336 list_add(&lun->link, &sc->luns);
2338 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2339 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2341 lun->removable = 1; /* XXX Query this from the device */
2342 lun->changed = 1; /* ub_revalidate clears only */
2343 lun->first_open = 1;
2344 ub_revalidate(sc, lun);
2347 if ((disk = alloc_disk(UB_MINORS_PER_MAJOR)) == NULL)
2351 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2352 sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2353 disk->major = UB_MAJOR;
2354 disk->first_minor = lun->id * UB_MINORS_PER_MAJOR;
2355 disk->fops = &ub_bd_fops;
2356 disk->private_data = lun;
2357 disk->driverfs_dev = &sc->intf->dev; /* XXX Many to one ok? */
2360 if ((q = blk_init_queue(ub_request_fn, &sc->lock)) == NULL)
2365 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2366 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2367 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2368 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2369 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2370 blk_queue_hardsect_size(q, lun->capacity.bsize);
2374 set_capacity(disk, lun->capacity.nsec);
2376 disk->flags |= GENHD_FL_REMOVABLE;
2385 list_del(&lun->link);
2393 static void ub_disconnect(struct usb_interface *intf)
2395 struct ub_dev *sc = usb_get_intfdata(intf);
2396 struct list_head *p;
2398 struct gendisk *disk;
2399 unsigned long flags;
2402 * Prevent ub_bd_release from pulling the rug from under us.
2403 * XXX This is starting to look like a kref.
2404 * XXX Why not to take this ref at probe time?
2406 spin_lock_irqsave(&ub_lock, flags);
2408 spin_unlock_irqrestore(&ub_lock, flags);
2411 * Fence stall clearnings, operations triggered by unlinkings and so on.
2412 * We do not attempt to unlink any URBs, because we do not trust the
2413 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2415 atomic_set(&sc->poison, 1);
2418 * Blow away queued commands.
2420 * Actually, this never works, because before we get here
2421 * the HCD terminates outstanding URB(s). It causes our
2422 * SCSI command queue to advance, commands fail to submit,
2423 * and the whole queue drains. So, we just use this code to
2426 spin_lock_irqsave(&sc->lock, flags);
2428 struct ub_scsi_cmd *cmd;
2430 while ((cmd = ub_cmdq_pop(sc)) != NULL) {
2431 cmd->error = -ENOTCONN;
2432 cmd->state = UB_CMDST_DONE;
2433 ub_cmdtr_state(sc, cmd);
2435 (*cmd->done)(sc, cmd);
2439 printk(KERN_WARNING "%s: "
2440 "%d was queued after shutdown\n", sc->name, cnt);
2443 spin_unlock_irqrestore(&sc->lock, flags);
2446 * Unregister the upper layer.
2448 list_for_each (p, &sc->luns) {
2449 lun = list_entry(p, struct ub_lun, link);
2451 if (disk->flags & GENHD_FL_UP)
2454 * I wish I could do:
2455 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2456 * As it is, we rely on our internal poisoning and let
2457 * the upper levels to spin furiously failing all the I/O.
2462 * Taking a lock on a structure which is about to be freed
2463 * is very nonsensual. Here it is largely a way to do a debug freeze,
2464 * and a bracket which shows where the nonsensual code segment ends.
2466 * Testing for -EINPROGRESS is always a bug, so we are bending
2467 * the rules a little.
2469 spin_lock_irqsave(&sc->lock, flags);
2470 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2471 printk(KERN_WARNING "%s: "
2472 "URB is active after disconnect\n", sc->name);
2474 spin_unlock_irqrestore(&sc->lock, flags);
2477 * There is virtually no chance that other CPU runs times so long
2478 * after ub_urb_complete should have called del_timer, but only if HCD
2479 * didn't forget to deliver a callback on unlink.
2481 del_timer_sync(&sc->work_timer);
2484 * At this point there must be no commands coming from anyone
2485 * and no URBs left in transit.
2488 device_remove_file(&sc->intf->dev, &dev_attr_diag);
2489 usb_set_intfdata(intf, NULL);
2490 // usb_put_intf(sc->intf);
2492 usb_put_dev(sc->dev);
2498 static struct usb_driver ub_driver = {
2499 .owner = THIS_MODULE,
2502 .disconnect = ub_disconnect,
2503 .id_table = ub_usb_ids,
2506 static int __init ub_init(void)
2510 /* P3 */ printk("ub: sizeof ub_scsi_cmd %zu ub_dev %zu ub_lun %zu\n",
2511 sizeof(struct ub_scsi_cmd), sizeof(struct ub_dev), sizeof(struct ub_lun));
2513 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2515 devfs_mk_dir(DEVFS_NAME);
2517 if ((rc = usb_register(&ub_driver)) != 0)
2523 devfs_remove(DEVFS_NAME);
2524 unregister_blkdev(UB_MAJOR, DRV_NAME);
2529 static void __exit ub_exit(void)
2531 usb_deregister(&ub_driver);
2533 devfs_remove(DEVFS_NAME);
2534 unregister_blkdev(UB_MAJOR, DRV_NAME);
2537 module_init(ub_init);
2538 module_exit(ub_exit);
2540 MODULE_LICENSE("GPL");