[PATCH] USB: ub 01 rename
[linux-2.6/kmemtrace.git] / drivers / block / ub.c
blob813805908dec55b46fa5d118bbc77d5d01d47c33
1 /*
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 * -- set readonly flag for CDs, set removable flag for CF readers
13 * -- do inquiry and verify we got a disk and not a tape (for LUN mismatch)
14 * -- special case some senses, e.g. 3a/0 -> no media present, reduce retries
15 * -- verify the 13 conditions and do bulk resets
16 * -- kill last_pipe and simply do two-state clearing on both pipes
17 * -- verify protocol (bulk) from USB descriptors (maybe...)
18 * -- highmem
19 * -- move top_sense and work_bcs into separate allocations (if they survive)
20 * for cache purists and esoteric architectures.
21 * -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
22 * -- prune comments, they are too volumnous
23 * -- Exterminate P3 printks
24 * -- Resove XXX's
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/usb_usual.h>
32 #include <linux/blkdev.h>
33 #include <linux/devfs_fs_kernel.h>
34 #include <linux/timer.h>
35 #include <scsi/scsi.h>
37 #define DRV_NAME "ub"
38 #define DEVFS_NAME DRV_NAME
40 #define UB_MAJOR 180
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].
51 * +--------+
52 * ! INIT !
53 * +--------+
54 * !
55 * ub_scsi_cmd_start fails ->--------------------------------------\
56 * ! !
57 * V !
58 * +--------+ !
59 * ! CMD ! !
60 * +--------+ !
61 * ! +--------+ !
62 * was -EPIPE -->-------------------------------->! CLEAR ! !
63 * ! +--------+ !
64 * ! ! !
65 * was error -->------------------------------------- ! --------->\
66 * ! ! !
67 * /--<-- cmd->dir == NONE ? ! !
68 * ! ! ! !
69 * ! V ! !
70 * ! +--------+ ! !
71 * ! ! DATA ! ! !
72 * ! +--------+ ! !
73 * ! ! +---------+ ! !
74 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
75 * ! ! +---------+ ! !
76 * ! ! ! ! !
77 * ! ! was error -->---- ! --------->\
78 * ! was error -->--------------------- ! ------------- ! --------->\
79 * ! ! ! ! !
80 * ! V ! ! !
81 * \--->+--------+ ! ! !
82 * ! STAT !<--------------------------/ ! !
83 * /--->+--------+ ! !
84 * ! ! ! !
85 * [C] was -EPIPE -->-----------\ ! !
86 * ! ! ! ! !
87 * +<---- len == 0 ! ! !
88 * ! ! ! ! !
89 * ! was error -->--------------------------------------!---------->\
90 * ! ! ! ! !
91 * +<---- bad CSW ! ! !
92 * +<---- bad tag ! ! !
93 * ! ! V ! !
94 * ! ! +--------+ ! !
95 * ! ! ! CLRRS ! ! !
96 * ! ! +--------+ ! !
97 * ! ! ! ! !
98 * \------- ! --------------------[C]--------\ ! !
99 * ! ! ! !
100 * cmd->error---\ +--------+ ! !
101 * ! +--------------->! SENSE !<----------/ !
102 * STAT_FAIL----/ +--------+ !
103 * ! ! V
104 * ! V +--------+
105 * \--------------------------------\--------------------->! DONE !
106 * +--------+
110 * This many LUNs per USB device.
111 * Every one of them takes a host, see UB_MAX_HOSTS.
113 #define UB_MAX_LUNS 9
118 #define UB_PARTS_PER_LUN 8
120 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
122 #define UB_SENSE_SIZE 18
127 /* command block wrapper */
128 struct bulk_cb_wrap {
129 __le32 Signature; /* contains 'USBC' */
130 u32 Tag; /* unique per command id */
131 __le32 DataTransferLength; /* size of data */
132 u8 Flags; /* direction in bit 0 */
133 u8 Lun; /* LUN */
134 u8 Length; /* of of the CDB */
135 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
138 #define US_BULK_CB_WRAP_LEN 31
139 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
140 #define US_BULK_FLAG_IN 1
141 #define US_BULK_FLAG_OUT 0
143 /* command status wrapper */
144 struct bulk_cs_wrap {
145 __le32 Signature; /* should = 'USBS' */
146 u32 Tag; /* same as original command */
147 __le32 Residue; /* amount not transferred */
148 u8 Status; /* see below */
151 #define US_BULK_CS_WRAP_LEN 13
152 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
153 #define US_BULK_STAT_OK 0
154 #define US_BULK_STAT_FAIL 1
155 #define US_BULK_STAT_PHASE 2
157 /* bulk-only class specific requests */
158 #define US_BULK_RESET_REQUEST 0xff
159 #define US_BULK_GET_MAX_LUN 0xfe
163 struct ub_dev;
165 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
166 #define UB_MAX_SECTORS 64
169 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
170 * even if a webcam hogs the bus, but some devices need time to spin up.
172 #define UB_URB_TIMEOUT (HZ*2)
173 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
174 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
175 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
178 * An instance of a SCSI command in transit.
180 #define UB_DIR_NONE 0
181 #define UB_DIR_READ 1
182 #define UB_DIR_ILLEGAL2 2
183 #define UB_DIR_WRITE 3
185 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
186 (((c)==UB_DIR_READ)? 'r': 'n'))
188 enum ub_scsi_cmd_state {
189 UB_CMDST_INIT, /* Initial state */
190 UB_CMDST_CMD, /* Command submitted */
191 UB_CMDST_DATA, /* Data phase */
192 UB_CMDST_CLR2STS, /* Clearing before requesting status */
193 UB_CMDST_STAT, /* Status phase */
194 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
195 UB_CMDST_CLRRS, /* Clearing before retrying status */
196 UB_CMDST_SENSE, /* Sending Request Sense */
197 UB_CMDST_DONE /* Final state */
200 static char *ub_scsi_cmd_stname[] = {
201 ". ",
202 "Cmd",
203 "dat",
204 "c2s",
205 "sts",
206 "clr",
207 "crs",
208 "Sen",
209 "fin"
212 struct ub_scsi_cmd {
213 unsigned char cdb[UB_MAX_CDB_SIZE];
214 unsigned char cdb_len;
216 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
217 unsigned char trace_index;
218 enum ub_scsi_cmd_state state;
219 unsigned int tag;
220 struct ub_scsi_cmd *next;
222 int error; /* Return code - valid upon done */
223 unsigned int act_len; /* Return size */
224 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
226 int stat_count; /* Retries getting status. */
228 unsigned int len; /* Requested length */
229 unsigned int current_sg;
230 unsigned int nsg; /* sgv[nsg] */
231 struct scatterlist sgv[UB_MAX_REQ_SG];
233 struct ub_lun *lun;
234 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
235 void *back;
238 struct ub_request {
239 struct request *rq;
240 unsigned int current_try;
241 unsigned int nsg; /* sgv[nsg] */
242 struct scatterlist sgv[UB_MAX_REQ_SG];
247 struct ub_capacity {
248 unsigned long nsec; /* Linux size - 512 byte sectors */
249 unsigned int bsize; /* Linux hardsect_size */
250 unsigned int bshift; /* Shift between 512 and hard sects */
254 * The SCSI command tracing structure.
257 #define SCMD_ST_HIST_SZ 8
258 #define SCMD_TRACE_SZ 63 /* Less than 4KB of 61-byte lines */
260 struct ub_scsi_cmd_trace {
261 int hcur;
262 unsigned int tag;
263 unsigned int req_size, act_size;
264 unsigned char op;
265 unsigned char dir;
266 unsigned char key, asc, ascq;
267 char st_hst[SCMD_ST_HIST_SZ];
270 struct ub_scsi_trace {
271 int cur;
272 struct ub_scsi_cmd_trace vec[SCMD_TRACE_SZ];
276 * This is a direct take-off from linux/include/completion.h
277 * The difference is that I do not wait on this thing, just poll.
278 * When I want to wait (ub_probe), I just use the stock completion.
280 * Note that INIT_COMPLETION takes no lock. It is correct. But why
281 * in the bloody hell that thing takes struct instead of pointer to struct
282 * is quite beyond me. I just copied it from the stock completion.
284 struct ub_completion {
285 unsigned int done;
286 spinlock_t lock;
289 static inline void ub_init_completion(struct ub_completion *x)
291 x->done = 0;
292 spin_lock_init(&x->lock);
295 #define UB_INIT_COMPLETION(x) ((x).done = 0)
297 static void ub_complete(struct ub_completion *x)
299 unsigned long flags;
301 spin_lock_irqsave(&x->lock, flags);
302 x->done++;
303 spin_unlock_irqrestore(&x->lock, flags);
306 static int ub_is_completed(struct ub_completion *x)
308 unsigned long flags;
309 int ret;
311 spin_lock_irqsave(&x->lock, flags);
312 ret = x->done;
313 spin_unlock_irqrestore(&x->lock, flags);
314 return ret;
319 struct ub_scsi_cmd_queue {
320 int qlen, qmax;
321 struct ub_scsi_cmd *head, *tail;
325 * The block device instance (one per LUN).
327 struct ub_lun {
328 struct ub_dev *udev;
329 struct list_head link;
330 struct gendisk *disk;
331 int id; /* Host index */
332 int num; /* LUN number */
333 char name[16];
335 int changed; /* Media was changed */
336 int removable;
337 int readonly;
338 int first_open; /* Kludge. See ub_bd_open. */
340 struct ub_request urq;
342 /* Use Ingo's mempool if or when we have more than one command. */
344 * Currently we never need more than one command for the whole device.
345 * However, giving every LUN a command is a cheap and automatic way
346 * to enforce fairness between them.
348 int cmda[1];
349 struct ub_scsi_cmd cmdv[1];
351 struct ub_capacity capacity;
355 * The USB device instance.
357 struct ub_dev {
358 spinlock_t lock;
359 atomic_t poison; /* The USB device is disconnected */
360 int openc; /* protected by ub_lock! */
361 /* kref is too implicit for our taste */
362 int reset; /* Reset is running */
363 unsigned int tagcnt;
364 char name[12];
365 struct usb_device *dev;
366 struct usb_interface *intf;
368 struct list_head luns;
370 unsigned int send_bulk_pipe; /* cached pipe values */
371 unsigned int recv_bulk_pipe;
372 unsigned int send_ctrl_pipe;
373 unsigned int recv_ctrl_pipe;
375 struct tasklet_struct tasklet;
377 struct ub_scsi_cmd_queue cmd_queue;
378 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
379 unsigned char top_sense[UB_SENSE_SIZE];
381 struct ub_completion work_done;
382 struct urb work_urb;
383 struct timer_list work_timer;
384 int last_pipe; /* What might need clearing */
385 __le32 signature; /* Learned signature */
386 struct bulk_cb_wrap work_bcb;
387 struct bulk_cs_wrap work_bcs;
388 struct usb_ctrlrequest work_cr;
390 struct work_struct reset_work;
391 wait_queue_head_t reset_wait;
393 int sg_stat[6];
394 struct ub_scsi_trace tr;
399 static void ub_cleanup(struct ub_dev *sc);
400 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
401 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
402 struct ub_scsi_cmd *cmd, struct ub_request *urq);
403 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
404 struct ub_scsi_cmd *cmd, struct ub_request *urq);
405 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
406 static void ub_end_rq(struct request *rq, int uptodate);
407 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
408 struct ub_request *urq, struct ub_scsi_cmd *cmd);
409 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
410 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
411 static void ub_scsi_action(unsigned long _dev);
412 static void ub_scsi_dispatch(struct ub_dev *sc);
413 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
414 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
415 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
416 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
417 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
418 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
419 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
420 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
421 int stalled_pipe);
422 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
423 static void ub_reset_enter(struct ub_dev *sc);
424 static void ub_reset_task(void *arg);
425 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
426 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
427 struct ub_capacity *ret);
428 static int ub_probe_lun(struct ub_dev *sc, int lnum);
432 #ifdef CONFIG_USB_LIBUSUAL
434 #define ub_usb_ids storage_usb_ids
435 #else
437 static struct usb_device_id ub_usb_ids[] = {
438 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
442 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
443 #endif /* CONFIG_USB_LIBUSUAL */
446 * Find me a way to identify "next free minor" for add_disk(),
447 * and the array disappears the next day. However, the number of
448 * hosts has something to do with the naming and /proc/partitions.
449 * This has to be thought out in detail before changing.
450 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
452 #define UB_MAX_HOSTS 26
453 static char ub_hostv[UB_MAX_HOSTS];
455 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
458 * The SCSI command tracing procedures.
461 static void ub_cmdtr_new(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
463 int n;
464 struct ub_scsi_cmd_trace *t;
466 if ((n = sc->tr.cur + 1) == SCMD_TRACE_SZ) n = 0;
467 t = &sc->tr.vec[n];
469 memset(t, 0, sizeof(struct ub_scsi_cmd_trace));
470 t->tag = cmd->tag;
471 t->op = cmd->cdb[0];
472 t->dir = cmd->dir;
473 t->req_size = cmd->len;
474 t->st_hst[0] = cmd->state;
476 sc->tr.cur = n;
477 cmd->trace_index = n;
480 static void ub_cmdtr_state(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
482 int n;
483 struct ub_scsi_cmd_trace *t;
485 t = &sc->tr.vec[cmd->trace_index];
486 if (t->tag == cmd->tag) {
487 if ((n = t->hcur + 1) == SCMD_ST_HIST_SZ) n = 0;
488 t->st_hst[n] = cmd->state;
489 t->hcur = n;
493 static void ub_cmdtr_act_len(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
495 struct ub_scsi_cmd_trace *t;
497 t = &sc->tr.vec[cmd->trace_index];
498 if (t->tag == cmd->tag)
499 t->act_size = cmd->act_len;
502 static void ub_cmdtr_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
503 unsigned char *sense)
505 struct ub_scsi_cmd_trace *t;
507 t = &sc->tr.vec[cmd->trace_index];
508 if (t->tag == cmd->tag) {
509 t->key = sense[2] & 0x0F;
510 t->asc = sense[12];
511 t->ascq = sense[13];
515 static ssize_t ub_diag_show(struct device *dev, struct device_attribute *attr,
516 char *page)
518 struct usb_interface *intf;
519 struct ub_dev *sc;
520 struct list_head *p;
521 struct ub_lun *lun;
522 int cnt;
523 unsigned long flags;
524 int nc, nh;
525 int i, j;
526 struct ub_scsi_cmd_trace *t;
528 intf = to_usb_interface(dev);
529 sc = usb_get_intfdata(intf);
530 if (sc == NULL)
531 return 0;
533 cnt = 0;
534 spin_lock_irqsave(&sc->lock, flags);
536 cnt += sprintf(page + cnt,
537 "poison %d reset %d\n",
538 atomic_read(&sc->poison), sc->reset);
539 cnt += sprintf(page + cnt,
540 "qlen %d qmax %d\n",
541 sc->cmd_queue.qlen, sc->cmd_queue.qmax);
542 cnt += sprintf(page + cnt,
543 "sg %d %d %d %d %d .. %d\n",
544 sc->sg_stat[0],
545 sc->sg_stat[1],
546 sc->sg_stat[2],
547 sc->sg_stat[3],
548 sc->sg_stat[4],
549 sc->sg_stat[5]);
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++) {
560 t = &sc->tr.vec[nc];
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);
566 } else {
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);
583 return cnt;
586 static DEVICE_ATTR(diag, S_IRUGO, ub_diag_show, NULL); /* N.B. World readable */
589 * The id allocator.
591 * This also stores the host for indexing by minor, which is somewhat dirty.
593 static int ub_id_get(void)
595 unsigned long flags;
596 int i;
598 spin_lock_irqsave(&ub_lock, flags);
599 for (i = 0; i < UB_MAX_HOSTS; i++) {
600 if (ub_hostv[i] == 0) {
601 ub_hostv[i] = 1;
602 spin_unlock_irqrestore(&ub_lock, flags);
603 return i;
606 spin_unlock_irqrestore(&ub_lock, flags);
607 return -1;
610 static void ub_id_put(int id)
612 unsigned long flags;
614 if (id < 0 || id >= UB_MAX_HOSTS) {
615 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
616 return;
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);
623 return;
625 ub_hostv[id] = 0;
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)
639 unsigned long flags;
641 spin_lock_irqsave(&ub_lock, flags);
642 --sc->openc;
643 if (sc->openc == 0 && atomic_read(&sc->poison)) {
644 spin_unlock_irqrestore(&ub_lock, flags);
645 ub_cleanup(sc);
646 } else {
647 spin_unlock_irqrestore(&ub_lock, flags);
652 * Final cleanup and deallocation.
654 static void ub_cleanup(struct ub_dev *sc)
656 struct list_head *p;
657 struct ub_lun *lun;
658 request_queue_t *q;
660 while (!list_empty(&sc->luns)) {
661 p = sc->luns.next;
662 lun = list_entry(p, struct ub_lun, link);
663 list_del(p);
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; */
677 put_disk(lun->disk);
678 lun->disk = NULL;
680 ub_id_put(lun->id);
681 kfree(lun);
684 kfree(sc);
688 * The "command allocator".
690 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
692 struct ub_scsi_cmd *ret;
694 if (lun->cmda[0])
695 return NULL;
696 ret = &lun->cmdv[0];
697 lun->cmda[0] = 1;
698 return 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",
705 lun->name, cmd);
706 return;
708 if (!lun->cmda[0]) {
709 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
710 return;
712 lun->cmda[0] = 0;
716 * The command queue.
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) {
723 t->head = cmd;
724 t->tail = cmd;
725 } else {
726 t->tail->next = cmd;
727 t->tail = cmd;
730 if (t->qlen > t->qmax)
731 t->qmax = t->qlen;
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) {
739 t->head = cmd;
740 t->tail = cmd;
741 } else {
742 cmd->next = t->head;
743 t->head = cmd;
746 if (t->qlen > t->qmax)
747 t->qmax = t->qlen;
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;
755 if (t->qlen == 0)
756 return NULL;
757 if (--t->qlen == 0)
758 t->tail = NULL;
759 cmd = t->head;
760 t->head = cmd->next;
761 cmd->next = NULL;
762 return 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;
774 struct request *rq;
776 while ((rq = elv_next_request(q)) != NULL) {
777 if (ub_request_fn_1(lun, rq) != 0) {
778 blk_stop_queue(q);
779 break;
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;
788 struct ub_request *urq;
789 int n_elem;
791 if (atomic_read(&sc->poison) || lun->changed) {
792 blkdev_dequeue_request(rq);
793 ub_end_rq(rq, 0);
794 return 0;
797 if (lun->urq.rq != NULL)
798 return -1;
799 if ((cmd = ub_get_cmd(lun)) == NULL)
800 return -1;
801 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
803 blkdev_dequeue_request(rq);
805 urq = &lun->urq;
806 memset(urq, 0, sizeof(struct ub_request));
807 urq->rq = rq;
810 * get scatterlist from block layer
812 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
813 if (n_elem < 0) {
814 printk(KERN_INFO "%s: failed request map (%d)\n",
815 lun->name, n_elem); /* P3 */
816 goto drop;
818 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
819 printk(KERN_WARNING "%s: request with %d segments\n",
820 lun->name, n_elem);
821 goto drop;
823 urq->nsg = n_elem;
824 sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
826 if (blk_pc_request(rq)) {
827 ub_cmd_build_packet(sc, lun, cmd, urq);
828 } else {
829 ub_cmd_build_block(sc, lun, cmd, urq);
831 cmd->state = UB_CMDST_INIT;
832 cmd->lun = lun;
833 cmd->done = ub_rw_cmd_done;
834 cmd->back = urq;
836 cmd->tag = sc->tagcnt++;
837 if (ub_submit_scsi(sc, cmd) != 0)
838 goto drop;
840 return 0;
842 drop:
843 ub_put_cmd(lun, cmd);
844 ub_end_rq(rq, 0);
845 return 0;
848 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
849 struct ub_scsi_cmd *cmd, struct ub_request *urq)
851 struct request *rq = urq->rq;
852 unsigned int block, nblks;
854 if (rq_data_dir(rq) == WRITE)
855 cmd->dir = UB_DIR_WRITE;
856 else
857 cmd->dir = UB_DIR_READ;
859 cmd->nsg = urq->nsg;
860 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
863 * build the command
865 * The call to blk_queue_hardsect_size() guarantees that request
866 * is aligned, but it is given in terms of 512 byte units, always.
868 block = rq->sector >> lun->capacity.bshift;
869 nblks = rq->nr_sectors >> lun->capacity.bshift;
871 cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
872 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
873 cmd->cdb[2] = block >> 24;
874 cmd->cdb[3] = block >> 16;
875 cmd->cdb[4] = block >> 8;
876 cmd->cdb[5] = block;
877 cmd->cdb[7] = nblks >> 8;
878 cmd->cdb[8] = nblks;
879 cmd->cdb_len = 10;
881 cmd->len = rq->nr_sectors * 512;
884 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
885 struct ub_scsi_cmd *cmd, struct ub_request *urq)
887 struct request *rq = urq->rq;
889 if (rq->data_len == 0) {
890 cmd->dir = UB_DIR_NONE;
891 } else {
892 if (rq_data_dir(rq) == WRITE)
893 cmd->dir = UB_DIR_WRITE;
894 else
895 cmd->dir = UB_DIR_READ;
898 cmd->nsg = urq->nsg;
899 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
901 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
902 cmd->cdb_len = rq->cmd_len;
904 cmd->len = rq->data_len;
907 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
909 struct ub_lun *lun = cmd->lun;
910 struct ub_request *urq = cmd->back;
911 struct request *rq;
912 int uptodate;
914 rq = urq->rq;
916 if (cmd->error == 0) {
917 uptodate = 1;
919 if (blk_pc_request(rq)) {
920 if (cmd->act_len >= rq->data_len)
921 rq->data_len = 0;
922 else
923 rq->data_len -= cmd->act_len;
925 } else {
926 uptodate = 0;
928 if (blk_pc_request(rq)) {
929 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
930 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
931 rq->sense_len = UB_SENSE_SIZE;
932 if (sc->top_sense[0] != 0)
933 rq->errors = SAM_STAT_CHECK_CONDITION;
934 else
935 rq->errors = DID_ERROR << 16;
936 } else {
937 if (cmd->error == -EIO) {
938 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
939 return;
944 urq->rq = NULL;
946 ub_put_cmd(lun, cmd);
947 ub_end_rq(rq, uptodate);
948 blk_start_queue(lun->disk->queue);
951 static void ub_end_rq(struct request *rq, int uptodate)
953 int rc;
955 rc = end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
956 // assert(rc == 0);
957 end_that_request_last(rq);
960 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
961 struct ub_request *urq, struct ub_scsi_cmd *cmd)
964 if (atomic_read(&sc->poison))
965 return -ENXIO;
967 ub_reset_enter(sc);
969 if (urq->current_try >= 3)
970 return -EIO;
971 urq->current_try++;
972 /* P3 */ printk("%s: dir %c len/act %d/%d "
973 "[sense %x %02x %02x] retry %d\n",
974 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
975 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
977 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
978 ub_cmd_build_block(sc, lun, cmd, urq);
980 cmd->state = UB_CMDST_INIT;
981 cmd->lun = lun;
982 cmd->done = ub_rw_cmd_done;
983 cmd->back = urq;
985 cmd->tag = sc->tagcnt++;
987 #if 0 /* Wasteful */
988 return ub_submit_scsi(sc, cmd);
989 #else
990 ub_cmdq_add(sc, cmd);
991 return 0;
992 #endif
996 * Submit a regular SCSI operation (not an auto-sense).
998 * The Iron Law of Good Submit Routine is:
999 * Zero return - callback is done, Nonzero return - callback is not done.
1000 * No exceptions.
1002 * Host is assumed locked.
1004 * XXX We only support Bulk for the moment.
1006 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1009 if (cmd->state != UB_CMDST_INIT ||
1010 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
1011 return -EINVAL;
1014 ub_cmdq_add(sc, cmd);
1016 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
1017 * safer to jump to a tasklet, in case upper layers do something silly.
1019 tasklet_schedule(&sc->tasklet);
1020 return 0;
1024 * Submit the first URB for the queued command.
1025 * This function does not deal with queueing in any way.
1027 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1029 struct bulk_cb_wrap *bcb;
1030 int rc;
1032 bcb = &sc->work_bcb;
1035 * ``If the allocation length is eighteen or greater, and a device
1036 * server returns less than eithteen bytes of data, the application
1037 * client should assume that the bytes not transferred would have been
1038 * zeroes had the device server returned those bytes.''
1040 * We zero sense for all commands so that when a packet request
1041 * fails it does not return a stale sense.
1043 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
1045 /* set up the command wrapper */
1046 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1047 bcb->Tag = cmd->tag; /* Endianness is not important */
1048 bcb->DataTransferLength = cpu_to_le32(cmd->len);
1049 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
1050 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
1051 bcb->Length = cmd->cdb_len;
1053 /* copy the command payload */
1054 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
1056 UB_INIT_COMPLETION(sc->work_done);
1058 sc->last_pipe = sc->send_bulk_pipe;
1059 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
1060 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
1062 /* Fill what we shouldn't be filling, because usb-storage did so. */
1063 sc->work_urb.actual_length = 0;
1064 sc->work_urb.error_count = 0;
1065 sc->work_urb.status = 0;
1067 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1068 /* XXX Clear stalls */
1069 ub_complete(&sc->work_done);
1070 return rc;
1073 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
1074 add_timer(&sc->work_timer);
1076 cmd->state = UB_CMDST_CMD;
1077 ub_cmdtr_state(sc, cmd);
1078 return 0;
1082 * Timeout handler.
1084 static void ub_urb_timeout(unsigned long arg)
1086 struct ub_dev *sc = (struct ub_dev *) arg;
1087 unsigned long flags;
1089 spin_lock_irqsave(&sc->lock, flags);
1090 usb_unlink_urb(&sc->work_urb);
1091 spin_unlock_irqrestore(&sc->lock, flags);
1095 * Completion routine for the work URB.
1097 * This can be called directly from usb_submit_urb (while we have
1098 * the sc->lock taken) and from an interrupt (while we do NOT have
1099 * the sc->lock taken). Therefore, bounce this off to a tasklet.
1101 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
1103 struct ub_dev *sc = urb->context;
1105 ub_complete(&sc->work_done);
1106 tasklet_schedule(&sc->tasklet);
1109 static void ub_scsi_action(unsigned long _dev)
1111 struct ub_dev *sc = (struct ub_dev *) _dev;
1112 unsigned long flags;
1114 spin_lock_irqsave(&sc->lock, flags);
1115 del_timer(&sc->work_timer);
1116 ub_scsi_dispatch(sc);
1117 spin_unlock_irqrestore(&sc->lock, flags);
1120 static void ub_scsi_dispatch(struct ub_dev *sc)
1122 struct ub_scsi_cmd *cmd;
1123 int rc;
1125 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
1126 if (cmd->state == UB_CMDST_DONE) {
1127 ub_cmdq_pop(sc);
1128 (*cmd->done)(sc, cmd);
1129 } else if (cmd->state == UB_CMDST_INIT) {
1130 ub_cmdtr_new(sc, cmd);
1131 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1132 break;
1133 cmd->error = rc;
1134 cmd->state = UB_CMDST_DONE;
1135 ub_cmdtr_state(sc, cmd);
1136 } else {
1137 if (!ub_is_completed(&sc->work_done))
1138 break;
1139 ub_scsi_urb_compl(sc, cmd);
1144 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1146 struct urb *urb = &sc->work_urb;
1147 struct bulk_cs_wrap *bcs;
1148 int len;
1149 int rc;
1151 if (atomic_read(&sc->poison)) {
1152 ub_state_done(sc, cmd, -ENODEV);
1153 return;
1156 if (cmd->state == UB_CMDST_CLEAR) {
1157 if (urb->status == -EPIPE) {
1159 * STALL while clearning STALL.
1160 * The control pipe clears itself - nothing to do.
1162 printk(KERN_NOTICE "%s: stall on control pipe\n",
1163 sc->name);
1164 goto Bad_End;
1168 * We ignore the result for the halt clear.
1171 /* reset the endpoint toggle */
1172 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1173 usb_pipeout(sc->last_pipe), 0);
1175 ub_state_sense(sc, cmd);
1177 } else if (cmd->state == UB_CMDST_CLR2STS) {
1178 if (urb->status == -EPIPE) {
1179 printk(KERN_NOTICE "%s: stall on control pipe\n",
1180 sc->name);
1181 goto Bad_End;
1185 * We ignore the result for the halt clear.
1188 /* reset the endpoint toggle */
1189 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1190 usb_pipeout(sc->last_pipe), 0);
1192 ub_state_stat(sc, cmd);
1194 } else if (cmd->state == UB_CMDST_CLRRS) {
1195 if (urb->status == -EPIPE) {
1196 printk(KERN_NOTICE "%s: stall on control pipe\n",
1197 sc->name);
1198 goto Bad_End;
1202 * We ignore the result for the halt clear.
1205 /* reset the endpoint toggle */
1206 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1207 usb_pipeout(sc->last_pipe), 0);
1209 ub_state_stat_counted(sc, cmd);
1211 } else if (cmd->state == UB_CMDST_CMD) {
1212 switch (urb->status) {
1213 case 0:
1214 break;
1215 case -EOVERFLOW:
1216 goto Bad_End;
1217 case -EPIPE:
1218 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1219 if (rc != 0) {
1220 printk(KERN_NOTICE "%s: "
1221 "unable to submit clear (%d)\n",
1222 sc->name, rc);
1224 * This is typically ENOMEM or some other such shit.
1225 * Retrying is pointless. Just do Bad End on it...
1227 ub_state_done(sc, cmd, rc);
1228 return;
1230 cmd->state = UB_CMDST_CLEAR;
1231 ub_cmdtr_state(sc, cmd);
1232 return;
1233 case -ESHUTDOWN: /* unplug */
1234 case -EILSEQ: /* unplug timeout on uhci */
1235 ub_state_done(sc, cmd, -ENODEV);
1236 return;
1237 default:
1238 goto Bad_End;
1240 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1241 goto Bad_End;
1244 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1245 ub_state_stat(sc, cmd);
1246 return;
1249 // udelay(125); // usb-storage has this
1250 ub_data_start(sc, cmd);
1252 } else if (cmd->state == UB_CMDST_DATA) {
1253 if (urb->status == -EPIPE) {
1254 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1255 if (rc != 0) {
1256 printk(KERN_NOTICE "%s: "
1257 "unable to submit clear (%d)\n",
1258 sc->name, rc);
1259 ub_state_done(sc, cmd, rc);
1260 return;
1262 cmd->state = UB_CMDST_CLR2STS;
1263 ub_cmdtr_state(sc, cmd);
1264 return;
1266 if (urb->status == -EOVERFLOW) {
1268 * A babble? Failure, but we must transfer CSW now.
1270 cmd->error = -EOVERFLOW; /* A cheap trick... */
1271 ub_state_stat(sc, cmd);
1272 return;
1275 if (cmd->dir == UB_DIR_WRITE) {
1277 * Do not continue writes in case of a failure.
1278 * Doing so would cause sectors to be mixed up,
1279 * which is worse than sectors lost.
1281 * We must try to read the CSW, or many devices
1282 * get confused.
1284 len = urb->actual_length;
1285 if (urb->status != 0 ||
1286 len != cmd->sgv[cmd->current_sg].length) {
1287 cmd->act_len += len;
1288 ub_cmdtr_act_len(sc, cmd);
1290 cmd->error = -EIO;
1291 ub_state_stat(sc, cmd);
1292 return;
1295 } else {
1297 * If an error occurs on read, we record it, and
1298 * continue to fetch data in order to avoid bubble.
1300 * As a small shortcut, we stop if we detect that
1301 * a CSW mixed into data.
1303 if (urb->status != 0)
1304 cmd->error = -EIO;
1306 len = urb->actual_length;
1307 if (urb->status != 0 ||
1308 len != cmd->sgv[cmd->current_sg].length) {
1309 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1310 goto Bad_End;
1314 cmd->act_len += urb->actual_length;
1315 ub_cmdtr_act_len(sc, cmd);
1317 if (++cmd->current_sg < cmd->nsg) {
1318 ub_data_start(sc, cmd);
1319 return;
1321 ub_state_stat(sc, cmd);
1323 } else if (cmd->state == UB_CMDST_STAT) {
1324 if (urb->status == -EPIPE) {
1325 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1326 if (rc != 0) {
1327 printk(KERN_NOTICE "%s: "
1328 "unable to submit clear (%d)\n",
1329 sc->name, rc);
1330 ub_state_done(sc, cmd, rc);
1331 return;
1335 * Having a stall when getting CSW is an error, so
1336 * make sure uppper levels are not oblivious to it.
1338 cmd->error = -EIO; /* A cheap trick... */
1340 cmd->state = UB_CMDST_CLRRS;
1341 ub_cmdtr_state(sc, cmd);
1342 return;
1345 /* Catch everything, including -EOVERFLOW and other nasties. */
1346 if (urb->status != 0)
1347 goto Bad_End;
1349 if (urb->actual_length == 0) {
1350 ub_state_stat_counted(sc, cmd);
1351 return;
1355 * Check the returned Bulk protocol status.
1356 * The status block has to be validated first.
1359 bcs = &sc->work_bcs;
1361 if (sc->signature == cpu_to_le32(0)) {
1363 * This is the first reply, so do not perform the check.
1364 * Instead, remember the signature the device uses
1365 * for future checks. But do not allow a nul.
1367 sc->signature = bcs->Signature;
1368 if (sc->signature == cpu_to_le32(0)) {
1369 ub_state_stat_counted(sc, cmd);
1370 return;
1372 } else {
1373 if (bcs->Signature != sc->signature) {
1374 ub_state_stat_counted(sc, cmd);
1375 return;
1379 if (bcs->Tag != cmd->tag) {
1381 * This usually happens when we disagree with the
1382 * device's microcode about something. For instance,
1383 * a few of them throw this after timeouts. They buffer
1384 * commands and reply at commands we timed out before.
1385 * Without flushing these replies we loop forever.
1387 ub_state_stat_counted(sc, cmd);
1388 return;
1391 len = le32_to_cpu(bcs->Residue);
1392 if (len != cmd->len - cmd->act_len) {
1394 * It is all right to transfer less, the caller has
1395 * to check. But it's not all right if the device
1396 * counts disagree with our counts.
1398 /* P3 */ printk("%s: resid %d len %d act %d\n",
1399 sc->name, len, cmd->len, cmd->act_len);
1400 goto Bad_End;
1403 switch (bcs->Status) {
1404 case US_BULK_STAT_OK:
1405 break;
1406 case US_BULK_STAT_FAIL:
1407 ub_state_sense(sc, cmd);
1408 return;
1409 case US_BULK_STAT_PHASE:
1410 /* P3 */ printk("%s: status PHASE\n", sc->name);
1411 goto Bad_End;
1412 default:
1413 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1414 sc->name, bcs->Status);
1415 ub_state_done(sc, cmd, -EINVAL);
1416 return;
1419 /* Not zeroing error to preserve a babble indicator */
1420 if (cmd->error != 0) {
1421 ub_state_sense(sc, cmd);
1422 return;
1424 cmd->state = UB_CMDST_DONE;
1425 ub_cmdtr_state(sc, cmd);
1426 ub_cmdq_pop(sc);
1427 (*cmd->done)(sc, cmd);
1429 } else if (cmd->state == UB_CMDST_SENSE) {
1430 ub_state_done(sc, cmd, -EIO);
1432 } else {
1433 printk(KERN_WARNING "%s: "
1434 "wrong command state %d\n",
1435 sc->name, cmd->state);
1436 ub_state_done(sc, cmd, -EINVAL);
1437 return;
1439 return;
1441 Bad_End: /* Little Excel is dead */
1442 ub_state_done(sc, cmd, -EIO);
1446 * Factorization helper for the command state machine:
1447 * Initiate a data segment transfer.
1449 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1451 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1452 int pipe;
1453 int rc;
1455 UB_INIT_COMPLETION(sc->work_done);
1457 if (cmd->dir == UB_DIR_READ)
1458 pipe = sc->recv_bulk_pipe;
1459 else
1460 pipe = sc->send_bulk_pipe;
1461 sc->last_pipe = pipe;
1462 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1463 page_address(sg->page) + sg->offset, sg->length,
1464 ub_urb_complete, sc);
1465 sc->work_urb.actual_length = 0;
1466 sc->work_urb.error_count = 0;
1467 sc->work_urb.status = 0;
1469 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1470 /* XXX Clear stalls */
1471 ub_complete(&sc->work_done);
1472 ub_state_done(sc, cmd, rc);
1473 return;
1476 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1477 add_timer(&sc->work_timer);
1479 cmd->state = UB_CMDST_DATA;
1480 ub_cmdtr_state(sc, cmd);
1484 * Factorization helper for the command state machine:
1485 * Finish the command.
1487 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1490 cmd->error = rc;
1491 cmd->state = UB_CMDST_DONE;
1492 ub_cmdtr_state(sc, cmd);
1493 ub_cmdq_pop(sc);
1494 (*cmd->done)(sc, cmd);
1498 * Factorization helper for the command state machine:
1499 * Submit a CSW read.
1501 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1503 int rc;
1505 UB_INIT_COMPLETION(sc->work_done);
1507 sc->last_pipe = sc->recv_bulk_pipe;
1508 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1509 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1510 sc->work_urb.actual_length = 0;
1511 sc->work_urb.error_count = 0;
1512 sc->work_urb.status = 0;
1514 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1515 /* XXX Clear stalls */
1516 ub_complete(&sc->work_done);
1517 ub_state_done(sc, cmd, rc);
1518 return -1;
1521 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1522 add_timer(&sc->work_timer);
1523 return 0;
1527 * Factorization helper for the command state machine:
1528 * Submit a CSW read and go to STAT state.
1530 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1533 if (__ub_state_stat(sc, cmd) != 0)
1534 return;
1536 cmd->stat_count = 0;
1537 cmd->state = UB_CMDST_STAT;
1538 ub_cmdtr_state(sc, cmd);
1542 * Factorization helper for the command state machine:
1543 * Submit a CSW read and go to STAT state with counter (along [C] path).
1545 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1548 if (++cmd->stat_count >= 4) {
1549 ub_state_sense(sc, cmd);
1550 return;
1553 if (__ub_state_stat(sc, cmd) != 0)
1554 return;
1556 cmd->state = UB_CMDST_STAT;
1557 ub_cmdtr_state(sc, cmd);
1561 * Factorization helper for the command state machine:
1562 * Submit a REQUEST SENSE and go to SENSE state.
1564 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1566 struct ub_scsi_cmd *scmd;
1567 struct scatterlist *sg;
1568 int rc;
1570 if (cmd->cdb[0] == REQUEST_SENSE) {
1571 rc = -EPIPE;
1572 goto error;
1575 scmd = &sc->top_rqs_cmd;
1576 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1577 scmd->cdb[0] = REQUEST_SENSE;
1578 scmd->cdb[4] = UB_SENSE_SIZE;
1579 scmd->cdb_len = 6;
1580 scmd->dir = UB_DIR_READ;
1581 scmd->state = UB_CMDST_INIT;
1582 scmd->nsg = 1;
1583 sg = &scmd->sgv[0];
1584 sg->page = virt_to_page(sc->top_sense);
1585 sg->offset = (unsigned long)sc->top_sense & (PAGE_SIZE-1);
1586 sg->length = UB_SENSE_SIZE;
1587 scmd->len = UB_SENSE_SIZE;
1588 scmd->lun = cmd->lun;
1589 scmd->done = ub_top_sense_done;
1590 scmd->back = cmd;
1592 scmd->tag = sc->tagcnt++;
1594 cmd->state = UB_CMDST_SENSE;
1595 ub_cmdtr_state(sc, cmd);
1597 ub_cmdq_insert(sc, scmd);
1598 return;
1600 error:
1601 ub_state_done(sc, cmd, rc);
1605 * A helper for the command's state machine:
1606 * Submit a stall clear.
1608 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1609 int stalled_pipe)
1611 int endp;
1612 struct usb_ctrlrequest *cr;
1613 int rc;
1615 endp = usb_pipeendpoint(stalled_pipe);
1616 if (usb_pipein (stalled_pipe))
1617 endp |= USB_DIR_IN;
1619 cr = &sc->work_cr;
1620 cr->bRequestType = USB_RECIP_ENDPOINT;
1621 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1622 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1623 cr->wIndex = cpu_to_le16(endp);
1624 cr->wLength = cpu_to_le16(0);
1626 UB_INIT_COMPLETION(sc->work_done);
1628 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1629 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1630 sc->work_urb.actual_length = 0;
1631 sc->work_urb.error_count = 0;
1632 sc->work_urb.status = 0;
1634 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1635 ub_complete(&sc->work_done);
1636 return rc;
1639 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1640 add_timer(&sc->work_timer);
1641 return 0;
1646 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1648 unsigned char *sense = sc->top_sense;
1649 struct ub_scsi_cmd *cmd;
1652 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1654 ub_cmdtr_sense(sc, scmd, sense);
1657 * Find the command which triggered the unit attention or a check,
1658 * save the sense into it, and advance its state machine.
1660 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1661 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1662 return;
1664 if (cmd != scmd->back) {
1665 printk(KERN_WARNING "%s: "
1666 "sense done for wrong command 0x%x\n",
1667 sc->name, cmd->tag);
1668 return;
1670 if (cmd->state != UB_CMDST_SENSE) {
1671 printk(KERN_WARNING "%s: "
1672 "sense done with bad cmd state %d\n",
1673 sc->name, cmd->state);
1674 return;
1677 cmd->key = sense[2] & 0x0F;
1678 cmd->asc = sense[12];
1679 cmd->ascq = sense[13];
1681 ub_scsi_urb_compl(sc, cmd);
1685 * Reset management
1688 static void ub_reset_enter(struct ub_dev *sc)
1691 if (sc->reset) {
1692 /* This happens often on multi-LUN devices. */
1693 return;
1695 sc->reset = 1;
1697 #if 0 /* Not needed because the disconnect waits for us. */
1698 unsigned long flags;
1699 spin_lock_irqsave(&ub_lock, flags);
1700 sc->openc++;
1701 spin_unlock_irqrestore(&ub_lock, flags);
1702 #endif
1704 #if 0 /* We let them stop themselves. */
1705 struct list_head *p;
1706 struct ub_lun *lun;
1707 list_for_each(p, &sc->luns) {
1708 lun = list_entry(p, struct ub_lun, link);
1709 blk_stop_queue(lun->disk->queue);
1711 #endif
1713 schedule_work(&sc->reset_work);
1716 static void ub_reset_task(void *arg)
1718 struct ub_dev *sc = arg;
1719 unsigned long flags;
1720 struct list_head *p;
1721 struct ub_lun *lun;
1722 int lkr, rc;
1724 if (!sc->reset) {
1725 printk(KERN_WARNING "%s: Running reset unrequested\n",
1726 sc->name);
1727 return;
1730 if (atomic_read(&sc->poison)) {
1731 printk(KERN_NOTICE "%s: Not resetting disconnected device\n",
1732 sc->name); /* P3 This floods. Remove soon. XXX */
1733 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1734 printk(KERN_NOTICE "%s: Not resetting multi-interface device\n",
1735 sc->name); /* P3 This floods. Remove soon. XXX */
1736 } else {
1737 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1738 printk(KERN_NOTICE
1739 "%s: usb_lock_device_for_reset failed (%d)\n",
1740 sc->name, lkr);
1741 } else {
1742 rc = usb_reset_device(sc->dev);
1743 if (rc < 0) {
1744 printk(KERN_NOTICE "%s: "
1745 "usb_lock_device_for_reset failed (%d)\n",
1746 sc->name, rc);
1749 if (lkr)
1750 usb_unlock_device(sc->dev);
1755 * In theory, no commands can be running while reset is active,
1756 * so nobody can ask for another reset, and so we do not need any
1757 * queues of resets or anything. We do need a spinlock though,
1758 * to interact with block layer.
1760 spin_lock_irqsave(&sc->lock, flags);
1761 sc->reset = 0;
1762 tasklet_schedule(&sc->tasklet);
1763 list_for_each(p, &sc->luns) {
1764 lun = list_entry(p, struct ub_lun, link);
1765 blk_start_queue(lun->disk->queue);
1767 wake_up(&sc->reset_wait);
1768 spin_unlock_irqrestore(&sc->lock, flags);
1772 * This is called from a process context.
1774 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1777 lun->readonly = 0; /* XXX Query this from the device */
1779 lun->capacity.nsec = 0;
1780 lun->capacity.bsize = 512;
1781 lun->capacity.bshift = 0;
1783 if (ub_sync_tur(sc, lun) != 0)
1784 return; /* Not ready */
1785 lun->changed = 0;
1787 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1789 * The retry here means something is wrong, either with the
1790 * device, with the transport, or with our code.
1791 * We keep this because sd.c has retries for capacity.
1793 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1794 lun->capacity.nsec = 0;
1795 lun->capacity.bsize = 512;
1796 lun->capacity.bshift = 0;
1802 * The open funcion.
1803 * This is mostly needed to keep refcounting, but also to support
1804 * media checks on removable media drives.
1806 static int ub_bd_open(struct inode *inode, struct file *filp)
1808 struct gendisk *disk = inode->i_bdev->bd_disk;
1809 struct ub_lun *lun;
1810 struct ub_dev *sc;
1811 unsigned long flags;
1812 int rc;
1814 if ((lun = disk->private_data) == NULL)
1815 return -ENXIO;
1816 sc = lun->udev;
1818 spin_lock_irqsave(&ub_lock, flags);
1819 if (atomic_read(&sc->poison)) {
1820 spin_unlock_irqrestore(&ub_lock, flags);
1821 return -ENXIO;
1823 sc->openc++;
1824 spin_unlock_irqrestore(&ub_lock, flags);
1827 * This is a workaround for a specific problem in our block layer.
1828 * In 2.6.9, register_disk duplicates the code from rescan_partitions.
1829 * However, if we do add_disk with a device which persistently reports
1830 * a changed media, add_disk calls register_disk, which does do_open,
1831 * which will call rescan_paritions for changed media. After that,
1832 * register_disk attempts to do it all again and causes double kobject
1833 * registration and a eventually an oops on module removal.
1835 * The bottom line is, Al Viro says that we should not allow
1836 * bdev->bd_invalidated to be set when doing add_disk no matter what.
1838 if (lun->first_open) {
1839 lun->first_open = 0;
1840 if (lun->changed) {
1841 rc = -ENOMEDIUM;
1842 goto err_open;
1846 if (lun->removable || lun->readonly)
1847 check_disk_change(inode->i_bdev);
1850 * The sd.c considers ->media_present and ->changed not equivalent,
1851 * under some pretty murky conditions (a failure of READ CAPACITY).
1852 * We may need it one day.
1854 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1855 rc = -ENOMEDIUM;
1856 goto err_open;
1859 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1860 rc = -EROFS;
1861 goto err_open;
1864 return 0;
1866 err_open:
1867 ub_put(sc);
1868 return rc;
1873 static int ub_bd_release(struct inode *inode, struct file *filp)
1875 struct gendisk *disk = inode->i_bdev->bd_disk;
1876 struct ub_lun *lun = disk->private_data;
1877 struct ub_dev *sc = lun->udev;
1879 ub_put(sc);
1880 return 0;
1884 * The ioctl interface.
1886 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1887 unsigned int cmd, unsigned long arg)
1889 struct gendisk *disk = inode->i_bdev->bd_disk;
1890 void __user *usermem = (void __user *) arg;
1892 return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1896 * This is called once a new disk was seen by the block layer or by ub_probe().
1897 * The main onjective here is to discover the features of the media such as
1898 * the capacity, read-only status, etc. USB storage generally does not
1899 * need to be spun up, but if we needed it, this would be the place.
1901 * This call can sleep.
1903 * The return code is not used.
1905 static int ub_bd_revalidate(struct gendisk *disk)
1907 struct ub_lun *lun = disk->private_data;
1909 ub_revalidate(lun->udev, lun);
1911 /* XXX Support sector size switching like in sr.c */
1912 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1913 set_capacity(disk, lun->capacity.nsec);
1914 // set_disk_ro(sdkp->disk, lun->readonly);
1916 return 0;
1920 * The check is called by the block layer to verify if the media
1921 * is still available. It is supposed to be harmless, lightweight and
1922 * non-intrusive in case the media was not changed.
1924 * This call can sleep.
1926 * The return code is bool!
1928 static int ub_bd_media_changed(struct gendisk *disk)
1930 struct ub_lun *lun = disk->private_data;
1932 if (!lun->removable)
1933 return 0;
1936 * We clean checks always after every command, so this is not
1937 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1938 * the device is actually not ready with operator or software
1939 * intervention required. One dangerous item might be a drive which
1940 * spins itself down, and come the time to write dirty pages, this
1941 * will fail, then block layer discards the data. Since we never
1942 * spin drives up, such devices simply cannot be used with ub anyway.
1944 if (ub_sync_tur(lun->udev, lun) != 0) {
1945 lun->changed = 1;
1946 return 1;
1949 return lun->changed;
1952 static struct block_device_operations ub_bd_fops = {
1953 .owner = THIS_MODULE,
1954 .open = ub_bd_open,
1955 .release = ub_bd_release,
1956 .ioctl = ub_bd_ioctl,
1957 .media_changed = ub_bd_media_changed,
1958 .revalidate_disk = ub_bd_revalidate,
1962 * Common ->done routine for commands executed synchronously.
1964 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1966 struct completion *cop = cmd->back;
1967 complete(cop);
1971 * Test if the device has a check condition on it, synchronously.
1973 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1975 struct ub_scsi_cmd *cmd;
1976 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1977 unsigned long flags;
1978 struct completion compl;
1979 int rc;
1981 init_completion(&compl);
1983 rc = -ENOMEM;
1984 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1985 goto err_alloc;
1986 memset(cmd, 0, ALLOC_SIZE);
1988 cmd->cdb[0] = TEST_UNIT_READY;
1989 cmd->cdb_len = 6;
1990 cmd->dir = UB_DIR_NONE;
1991 cmd->state = UB_CMDST_INIT;
1992 cmd->lun = lun; /* This may be NULL, but that's ok */
1993 cmd->done = ub_probe_done;
1994 cmd->back = &compl;
1996 spin_lock_irqsave(&sc->lock, flags);
1997 cmd->tag = sc->tagcnt++;
1999 rc = ub_submit_scsi(sc, cmd);
2000 spin_unlock_irqrestore(&sc->lock, flags);
2002 if (rc != 0) {
2003 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
2004 goto err_submit;
2007 wait_for_completion(&compl);
2009 rc = cmd->error;
2011 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
2012 rc = cmd->key;
2014 err_submit:
2015 kfree(cmd);
2016 err_alloc:
2017 return rc;
2021 * Read the SCSI capacity synchronously (for probing).
2023 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
2024 struct ub_capacity *ret)
2026 struct ub_scsi_cmd *cmd;
2027 struct scatterlist *sg;
2028 char *p;
2029 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
2030 unsigned long flags;
2031 unsigned int bsize, shift;
2032 unsigned long nsec;
2033 struct completion compl;
2034 int rc;
2036 init_completion(&compl);
2038 rc = -ENOMEM;
2039 if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2040 goto err_alloc;
2041 memset(cmd, 0, ALLOC_SIZE);
2042 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
2044 cmd->cdb[0] = 0x25;
2045 cmd->cdb_len = 10;
2046 cmd->dir = UB_DIR_READ;
2047 cmd->state = UB_CMDST_INIT;
2048 cmd->nsg = 1;
2049 sg = &cmd->sgv[0];
2050 sg->page = virt_to_page(p);
2051 sg->offset = (unsigned long)p & (PAGE_SIZE-1);
2052 sg->length = 8;
2053 cmd->len = 8;
2054 cmd->lun = lun;
2055 cmd->done = ub_probe_done;
2056 cmd->back = &compl;
2058 spin_lock_irqsave(&sc->lock, flags);
2059 cmd->tag = sc->tagcnt++;
2061 rc = ub_submit_scsi(sc, cmd);
2062 spin_unlock_irqrestore(&sc->lock, flags);
2064 if (rc != 0) {
2065 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
2066 goto err_submit;
2069 wait_for_completion(&compl);
2071 if (cmd->error != 0) {
2072 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
2073 rc = -EIO;
2074 goto err_read;
2076 if (cmd->act_len != 8) {
2077 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
2078 rc = -EIO;
2079 goto err_read;
2082 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
2083 nsec = be32_to_cpu(*(__be32 *)p) + 1;
2084 bsize = be32_to_cpu(*(__be32 *)(p + 4));
2085 switch (bsize) {
2086 case 512: shift = 0; break;
2087 case 1024: shift = 1; break;
2088 case 2048: shift = 2; break;
2089 case 4096: shift = 3; break;
2090 default:
2091 printk("ub: Bad sector size %u\n", bsize); /* P3 */
2092 rc = -EDOM;
2093 goto err_inv_bsize;
2096 ret->bsize = bsize;
2097 ret->bshift = shift;
2098 ret->nsec = nsec << shift;
2099 rc = 0;
2101 err_inv_bsize:
2102 err_read:
2103 err_submit:
2104 kfree(cmd);
2105 err_alloc:
2106 return rc;
2111 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
2113 struct completion *cop = urb->context;
2114 complete(cop);
2117 static void ub_probe_timeout(unsigned long arg)
2119 struct completion *cop = (struct completion *) arg;
2120 complete(cop);
2124 * Get number of LUNs by the way of Bulk GetMaxLUN command.
2126 static int ub_sync_getmaxlun(struct ub_dev *sc)
2128 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2129 unsigned char *p;
2130 enum { ALLOC_SIZE = 1 };
2131 struct usb_ctrlrequest *cr;
2132 struct completion compl;
2133 struct timer_list timer;
2134 int nluns;
2135 int rc;
2137 init_completion(&compl);
2139 rc = -ENOMEM;
2140 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2141 goto err_alloc;
2142 *p = 55;
2144 cr = &sc->work_cr;
2145 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2146 cr->bRequest = US_BULK_GET_MAX_LUN;
2147 cr->wValue = cpu_to_le16(0);
2148 cr->wIndex = cpu_to_le16(ifnum);
2149 cr->wLength = cpu_to_le16(1);
2151 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2152 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2153 sc->work_urb.actual_length = 0;
2154 sc->work_urb.error_count = 0;
2155 sc->work_urb.status = 0;
2157 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2158 if (rc == -EPIPE) {
2159 printk("%s: Stall submitting GetMaxLUN, using 1 LUN\n",
2160 sc->name); /* P3 */
2161 } else {
2162 printk(KERN_NOTICE
2163 "%s: Unable to submit GetMaxLUN (%d)\n",
2164 sc->name, rc);
2166 goto err_submit;
2169 init_timer(&timer);
2170 timer.function = ub_probe_timeout;
2171 timer.data = (unsigned long) &compl;
2172 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2173 add_timer(&timer);
2175 wait_for_completion(&compl);
2177 del_timer_sync(&timer);
2178 usb_kill_urb(&sc->work_urb);
2180 if ((rc = sc->work_urb.status) < 0) {
2181 if (rc == -EPIPE) {
2182 printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
2183 sc->name); /* P3 */
2184 } else {
2185 printk(KERN_NOTICE
2186 "%s: Error at GetMaxLUN (%d)\n",
2187 sc->name, rc);
2189 goto err_io;
2192 if (sc->work_urb.actual_length != 1) {
2193 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2194 sc->work_urb.actual_length); /* P3 */
2195 nluns = 0;
2196 } else {
2197 if ((nluns = *p) == 55) {
2198 nluns = 0;
2199 } else {
2200 /* GetMaxLUN returns the maximum LUN number */
2201 nluns += 1;
2202 if (nluns > UB_MAX_LUNS)
2203 nluns = UB_MAX_LUNS;
2205 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2206 *p, nluns); /* P3 */
2209 kfree(p);
2210 return nluns;
2212 err_io:
2213 err_submit:
2214 kfree(p);
2215 err_alloc:
2216 return rc;
2220 * Clear initial stalls.
2222 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2224 int endp;
2225 struct usb_ctrlrequest *cr;
2226 struct completion compl;
2227 struct timer_list timer;
2228 int rc;
2230 init_completion(&compl);
2232 endp = usb_pipeendpoint(stalled_pipe);
2233 if (usb_pipein (stalled_pipe))
2234 endp |= USB_DIR_IN;
2236 cr = &sc->work_cr;
2237 cr->bRequestType = USB_RECIP_ENDPOINT;
2238 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2239 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2240 cr->wIndex = cpu_to_le16(endp);
2241 cr->wLength = cpu_to_le16(0);
2243 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2244 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2245 sc->work_urb.actual_length = 0;
2246 sc->work_urb.error_count = 0;
2247 sc->work_urb.status = 0;
2249 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2250 printk(KERN_WARNING
2251 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2252 return rc;
2255 init_timer(&timer);
2256 timer.function = ub_probe_timeout;
2257 timer.data = (unsigned long) &compl;
2258 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2259 add_timer(&timer);
2261 wait_for_completion(&compl);
2263 del_timer_sync(&timer);
2264 usb_kill_urb(&sc->work_urb);
2266 /* reset the endpoint toggle */
2267 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2269 return 0;
2273 * Get the pipe settings.
2275 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2276 struct usb_interface *intf)
2278 struct usb_host_interface *altsetting = intf->cur_altsetting;
2279 struct usb_endpoint_descriptor *ep_in = NULL;
2280 struct usb_endpoint_descriptor *ep_out = NULL;
2281 struct usb_endpoint_descriptor *ep;
2282 int i;
2285 * Find the endpoints we need.
2286 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2287 * We will ignore any others.
2289 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2290 ep = &altsetting->endpoint[i].desc;
2292 /* Is it a BULK endpoint? */
2293 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2294 == USB_ENDPOINT_XFER_BULK) {
2295 /* BULK in or out? */
2296 if (ep->bEndpointAddress & USB_DIR_IN)
2297 ep_in = ep;
2298 else
2299 ep_out = ep;
2303 if (ep_in == NULL || ep_out == NULL) {
2304 printk(KERN_NOTICE "%s: failed endpoint check\n",
2305 sc->name);
2306 return -ENODEV;
2309 /* Calculate and store the pipe values */
2310 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2311 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2312 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2313 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2314 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2315 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2317 return 0;
2321 * Probing is done in the process context, which allows us to cheat
2322 * and not to build a state machine for the discovery.
2324 static int ub_probe(struct usb_interface *intf,
2325 const struct usb_device_id *dev_id)
2327 struct ub_dev *sc;
2328 int nluns;
2329 int rc;
2330 int i;
2332 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2333 return -ENXIO;
2335 rc = -ENOMEM;
2336 if ((sc = kmalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2337 goto err_core;
2338 memset(sc, 0, sizeof(struct ub_dev));
2339 spin_lock_init(&sc->lock);
2340 INIT_LIST_HEAD(&sc->luns);
2341 usb_init_urb(&sc->work_urb);
2342 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2343 atomic_set(&sc->poison, 0);
2344 INIT_WORK(&sc->reset_work, ub_reset_task, sc);
2345 init_waitqueue_head(&sc->reset_wait);
2347 init_timer(&sc->work_timer);
2348 sc->work_timer.data = (unsigned long) sc;
2349 sc->work_timer.function = ub_urb_timeout;
2351 ub_init_completion(&sc->work_done);
2352 sc->work_done.done = 1; /* A little yuk, but oh well... */
2354 sc->dev = interface_to_usbdev(intf);
2355 sc->intf = intf;
2356 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2357 usb_set_intfdata(intf, sc);
2358 usb_get_dev(sc->dev);
2359 // usb_get_intf(sc->intf); /* Do we need this? */
2361 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2362 sc->dev->bus->busnum, sc->dev->devnum);
2364 /* XXX Verify that we can handle the device (from descriptors) */
2366 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2367 goto err_dev_desc;
2369 if (device_create_file(&sc->intf->dev, &dev_attr_diag) != 0)
2370 goto err_diag;
2373 * At this point, all USB initialization is done, do upper layer.
2374 * We really hate halfway initialized structures, so from the
2375 * invariants perspective, this ub_dev is fully constructed at
2376 * this point.
2380 * This is needed to clear toggles. It is a problem only if we do
2381 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2383 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2384 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2385 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2386 #endif
2389 * The way this is used by the startup code is a little specific.
2390 * A SCSI check causes a USB stall. Our common case code sees it
2391 * and clears the check, after which the device is ready for use.
2392 * But if a check was not present, any command other than
2393 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2395 * If we neglect to clear the SCSI check, the first real command fails
2396 * (which is the capacity readout). We clear that and retry, but why
2397 * causing spurious retries for no reason.
2399 * Revalidation may start with its own TEST_UNIT_READY, but that one
2400 * has to succeed, so we clear checks with an additional one here.
2401 * In any case it's not our business how revaliadation is implemented.
2403 for (i = 0; i < 3; i++) { /* Retries for benh's key */
2404 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2405 if (rc != 0x6) break;
2406 msleep(10);
2409 nluns = 1;
2410 for (i = 0; i < 3; i++) {
2411 if ((rc = ub_sync_getmaxlun(sc)) < 0) {
2413 * This segment is taken from usb-storage. They say
2414 * that ZIP-100 needs this, but my own ZIP-100 works
2415 * fine without this.
2416 * Still, it does not seem to hurt anything.
2418 if (rc == -EPIPE) {
2419 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2420 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2422 break;
2424 if (rc != 0) {
2425 nluns = rc;
2426 break;
2428 msleep(100);
2431 for (i = 0; i < nluns; i++) {
2432 ub_probe_lun(sc, i);
2434 return 0;
2436 /* device_remove_file(&sc->intf->dev, &dev_attr_diag); */
2437 err_diag:
2438 err_dev_desc:
2439 usb_set_intfdata(intf, NULL);
2440 // usb_put_intf(sc->intf);
2441 usb_put_dev(sc->dev);
2442 kfree(sc);
2443 err_core:
2444 return rc;
2447 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2449 struct ub_lun *lun;
2450 request_queue_t *q;
2451 struct gendisk *disk;
2452 int rc;
2454 rc = -ENOMEM;
2455 if ((lun = kmalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2456 goto err_alloc;
2457 memset(lun, 0, sizeof(struct ub_lun));
2458 lun->num = lnum;
2460 rc = -ENOSR;
2461 if ((lun->id = ub_id_get()) == -1)
2462 goto err_id;
2464 lun->udev = sc;
2465 list_add(&lun->link, &sc->luns);
2467 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2468 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2470 lun->removable = 1; /* XXX Query this from the device */
2471 lun->changed = 1; /* ub_revalidate clears only */
2472 lun->first_open = 1;
2473 ub_revalidate(sc, lun);
2475 rc = -ENOMEM;
2476 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2477 goto err_diskalloc;
2479 lun->disk = disk;
2480 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2481 sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2482 disk->major = UB_MAJOR;
2483 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2484 disk->fops = &ub_bd_fops;
2485 disk->private_data = lun;
2486 disk->driverfs_dev = &sc->intf->dev;
2488 rc = -ENOMEM;
2489 if ((q = blk_init_queue(ub_request_fn, &sc->lock)) == NULL)
2490 goto err_blkqinit;
2492 disk->queue = q;
2494 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2495 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2496 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2497 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2498 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2499 blk_queue_hardsect_size(q, lun->capacity.bsize);
2501 q->queuedata = lun;
2503 set_capacity(disk, lun->capacity.nsec);
2504 if (lun->removable)
2505 disk->flags |= GENHD_FL_REMOVABLE;
2507 add_disk(disk);
2509 return 0;
2511 err_blkqinit:
2512 put_disk(disk);
2513 err_diskalloc:
2514 list_del(&lun->link);
2515 ub_id_put(lun->id);
2516 err_id:
2517 kfree(lun);
2518 err_alloc:
2519 return rc;
2522 static void ub_disconnect(struct usb_interface *intf)
2524 struct ub_dev *sc = usb_get_intfdata(intf);
2525 struct list_head *p;
2526 struct ub_lun *lun;
2527 struct gendisk *disk;
2528 unsigned long flags;
2531 * Prevent ub_bd_release from pulling the rug from under us.
2532 * XXX This is starting to look like a kref.
2533 * XXX Why not to take this ref at probe time?
2535 spin_lock_irqsave(&ub_lock, flags);
2536 sc->openc++;
2537 spin_unlock_irqrestore(&ub_lock, flags);
2540 * Fence stall clearnings, operations triggered by unlinkings and so on.
2541 * We do not attempt to unlink any URBs, because we do not trust the
2542 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2544 atomic_set(&sc->poison, 1);
2547 * Wait for reset to end, if any.
2549 wait_event(sc->reset_wait, !sc->reset);
2552 * Blow away queued commands.
2554 * Actually, this never works, because before we get here
2555 * the HCD terminates outstanding URB(s). It causes our
2556 * SCSI command queue to advance, commands fail to submit,
2557 * and the whole queue drains. So, we just use this code to
2558 * print warnings.
2560 spin_lock_irqsave(&sc->lock, flags);
2562 struct ub_scsi_cmd *cmd;
2563 int cnt = 0;
2564 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2565 cmd->error = -ENOTCONN;
2566 cmd->state = UB_CMDST_DONE;
2567 ub_cmdtr_state(sc, cmd);
2568 ub_cmdq_pop(sc);
2569 (*cmd->done)(sc, cmd);
2570 cnt++;
2572 if (cnt != 0) {
2573 printk(KERN_WARNING "%s: "
2574 "%d was queued after shutdown\n", sc->name, cnt);
2577 spin_unlock_irqrestore(&sc->lock, flags);
2580 * Unregister the upper layer.
2582 list_for_each (p, &sc->luns) {
2583 lun = list_entry(p, struct ub_lun, link);
2584 disk = lun->disk;
2585 if (disk->flags & GENHD_FL_UP)
2586 del_gendisk(disk);
2588 * I wish I could do:
2589 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2590 * As it is, we rely on our internal poisoning and let
2591 * the upper levels to spin furiously failing all the I/O.
2596 * Taking a lock on a structure which is about to be freed
2597 * is very nonsensual. Here it is largely a way to do a debug freeze,
2598 * and a bracket which shows where the nonsensual code segment ends.
2600 * Testing for -EINPROGRESS is always a bug, so we are bending
2601 * the rules a little.
2603 spin_lock_irqsave(&sc->lock, flags);
2604 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2605 printk(KERN_WARNING "%s: "
2606 "URB is active after disconnect\n", sc->name);
2608 spin_unlock_irqrestore(&sc->lock, flags);
2611 * There is virtually no chance that other CPU runs times so long
2612 * after ub_urb_complete should have called del_timer, but only if HCD
2613 * didn't forget to deliver a callback on unlink.
2615 del_timer_sync(&sc->work_timer);
2618 * At this point there must be no commands coming from anyone
2619 * and no URBs left in transit.
2622 device_remove_file(&sc->intf->dev, &dev_attr_diag);
2623 usb_set_intfdata(intf, NULL);
2624 // usb_put_intf(sc->intf);
2625 sc->intf = NULL;
2626 usb_put_dev(sc->dev);
2627 sc->dev = NULL;
2629 ub_put(sc);
2632 static struct usb_driver ub_driver = {
2633 .name = "ub",
2634 .probe = ub_probe,
2635 .disconnect = ub_disconnect,
2636 .id_table = ub_usb_ids,
2639 static int __init ub_init(void)
2641 int rc;
2643 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2644 goto err_regblkdev;
2645 devfs_mk_dir(DEVFS_NAME);
2647 if ((rc = usb_register(&ub_driver)) != 0)
2648 goto err_register;
2650 usb_usual_set_present(USB_US_TYPE_UB);
2651 return 0;
2653 err_register:
2654 devfs_remove(DEVFS_NAME);
2655 unregister_blkdev(UB_MAJOR, DRV_NAME);
2656 err_regblkdev:
2657 return rc;
2660 static void __exit ub_exit(void)
2662 usb_deregister(&ub_driver);
2664 devfs_remove(DEVFS_NAME);
2665 unregister_blkdev(UB_MAJOR, DRV_NAME);
2666 usb_usual_clear_present(USB_US_TYPE_UB);
2669 module_init(ub_init);
2670 module_exit(ub_exit);
2672 MODULE_LICENSE("GPL");