Merge branch 'lro'
[linux-2.6] / drivers / block / ub.c
1 /*
2  * The low performance USB storage driver (ub).
3  *
4  * Copyright (c) 1999, 2000 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
5  * Copyright (C) 2004 Pete Zaitcev (zaitcev@yahoo.com)
6  *
7  * This work is a part of Linux kernel, is derived from it,
8  * and is not licensed separately. See file COPYING for details.
9  *
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  *  -- highmem
18  *  -- move top_sense and work_bcs into separate allocations (if they survive)
19  *     for cache purists and esoteric architectures.
20  *  -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
21  *  -- prune comments, they are too volumnous
22  *  -- Exterminate P3 printks
23  *  -- Resove XXX's
24  *  -- Redo "benh's retries", perhaps have spin-up code to handle them. V:D=?
25  *  -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
26  */
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/usb.h>
30 #include <linux/usb_usual.h>
31 #include <linux/blkdev.h>
32 #include <linux/devfs_fs_kernel.h>
33 #include <linux/timer.h>
34 #include <scsi/scsi.h>
35
36 #define DRV_NAME "ub"
37 #define DEVFS_NAME DRV_NAME
38
39 #define UB_MAJOR 180
40
41 /*
42  * The command state machine is the key model for understanding of this driver.
43  *
44  * The general rule is that all transitions are done towards the bottom
45  * of the diagram, thus preventing any loops.
46  *
47  * An exception to that is how the STAT state is handled. A counter allows it
48  * to be re-entered along the path marked with [C].
49  *
50  *       +--------+
51  *       ! INIT   !
52  *       +--------+
53  *           !
54  *        ub_scsi_cmd_start fails ->--------------------------------------\
55  *           !                                                            !
56  *           V                                                            !
57  *       +--------+                                                       !
58  *       ! CMD    !                                                       !
59  *       +--------+                                                       !
60  *           !                                            +--------+      !
61  *         was -EPIPE -->-------------------------------->! CLEAR  !      !
62  *           !                                            +--------+      !
63  *           !                                                !           !
64  *         was error -->------------------------------------- ! --------->\
65  *           !                                                !           !
66  *  /--<-- cmd->dir == NONE ?                                 !           !
67  *  !        !                                                !           !
68  *  !        V                                                !           !
69  *  !    +--------+                                           !           !
70  *  !    ! DATA   !                                           !           !
71  *  !    +--------+                                           !           !
72  *  !        !                           +---------+          !           !
73  *  !      was -EPIPE -->--------------->! CLR2STS !          !           !
74  *  !        !                           +---------+          !           !
75  *  !        !                                !               !           !
76  *  !        !                              was error -->---- ! --------->\
77  *  !      was error -->--------------------- ! ------------- ! --------->\
78  *  !        !                                !               !           !
79  *  !        V                                !               !           !
80  *  \--->+--------+                           !               !           !
81  *       ! STAT   !<--------------------------/               !           !
82  *  /--->+--------+                                           !           !
83  *  !        !                                                !           !
84  * [C]     was -EPIPE -->-----------\                         !           !
85  *  !        !                      !                         !           !
86  *  +<---- len == 0                 !                         !           !
87  *  !        !                      !                         !           !
88  *  !      was error -->--------------------------------------!---------->\
89  *  !        !                      !                         !           !
90  *  +<---- bad CSW                  !                         !           !
91  *  +<---- bad tag                  !                         !           !
92  *  !        !                      V                         !           !
93  *  !        !                 +--------+                     !           !
94  *  !        !                 ! CLRRS  !                     !           !
95  *  !        !                 +--------+                     !           !
96  *  !        !                      !                         !           !
97  *  \------- ! --------------------[C]--------\               !           !
98  *           !                                !               !           !
99  *         cmd->error---\                +--------+           !           !
100  *           !          +--------------->! SENSE  !<----------/           !
101  *         STAT_FAIL----/                +--------+                       !
102  *           !                                !                           V
103  *           !                                V                      +--------+
104  *           \--------------------------------\--------------------->! DONE   !
105  *                                                                   +--------+
106  */
107
108 /*
109  * This many LUNs per USB device.
110  * Every one of them takes a host, see UB_MAX_HOSTS.
111  */
112 #define UB_MAX_LUNS   9
113
114 /*
115  */
116
117 #define UB_PARTS_PER_LUN      8
118
119 #define UB_MAX_CDB_SIZE      16         /* Corresponds to Bulk */
120
121 #define UB_SENSE_SIZE  18
122
123 /*
124  */
125
126 /* command block wrapper */
127 struct bulk_cb_wrap {
128         __le32  Signature;              /* contains 'USBC' */
129         u32     Tag;                    /* unique per command id */
130         __le32  DataTransferLength;     /* size of data */
131         u8      Flags;                  /* direction in bit 0 */
132         u8      Lun;                    /* LUN */
133         u8      Length;                 /* of of the CDB */
134         u8      CDB[UB_MAX_CDB_SIZE];   /* max command */
135 };
136
137 #define US_BULK_CB_WRAP_LEN     31
138 #define US_BULK_CB_SIGN         0x43425355      /*spells out USBC */
139 #define US_BULK_FLAG_IN         1
140 #define US_BULK_FLAG_OUT        0
141
142 /* command status wrapper */
143 struct bulk_cs_wrap {
144         __le32  Signature;              /* should = 'USBS' */
145         u32     Tag;                    /* same as original command */
146         __le32  Residue;                /* amount not transferred */
147         u8      Status;                 /* see below */
148 };
149
150 #define US_BULK_CS_WRAP_LEN     13
151 #define US_BULK_CS_SIGN         0x53425355      /* spells out 'USBS' */
152 #define US_BULK_STAT_OK         0
153 #define US_BULK_STAT_FAIL       1
154 #define US_BULK_STAT_PHASE      2
155
156 /* bulk-only class specific requests */
157 #define US_BULK_RESET_REQUEST   0xff
158 #define US_BULK_GET_MAX_LUN     0xfe
159
160 /*
161  */
162 struct ub_dev;
163
164 #define UB_MAX_REQ_SG   9       /* cdrecord requires 32KB and maybe a header */
165 #define UB_MAX_SECTORS 64
166
167 /*
168  * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
169  * even if a webcam hogs the bus, but some devices need time to spin up.
170  */
171 #define UB_URB_TIMEOUT  (HZ*2)
172 #define UB_DATA_TIMEOUT (HZ*5)  /* ZIP does spin-ups in the data phase */
173 #define UB_STAT_TIMEOUT (HZ*5)  /* Same spinups and eject for a dataless cmd. */
174 #define UB_CTRL_TIMEOUT (HZ/2)  /* 500ms ought to be enough to clear a stall */
175
176 /*
177  * An instance of a SCSI command in transit.
178  */
179 #define UB_DIR_NONE     0
180 #define UB_DIR_READ     1
181 #define UB_DIR_ILLEGAL2 2
182 #define UB_DIR_WRITE    3
183
184 #define UB_DIR_CHAR(c)  (((c)==UB_DIR_WRITE)? 'w': \
185                          (((c)==UB_DIR_READ)? 'r': 'n'))
186
187 enum ub_scsi_cmd_state {
188         UB_CMDST_INIT,                  /* Initial state */
189         UB_CMDST_CMD,                   /* Command submitted */
190         UB_CMDST_DATA,                  /* Data phase */
191         UB_CMDST_CLR2STS,               /* Clearing before requesting status */
192         UB_CMDST_STAT,                  /* Status phase */
193         UB_CMDST_CLEAR,                 /* Clearing a stall (halt, actually) */
194         UB_CMDST_CLRRS,                 /* Clearing before retrying status */
195         UB_CMDST_SENSE,                 /* Sending Request Sense */
196         UB_CMDST_DONE                   /* Final state */
197 };
198
199 static char *ub_scsi_cmd_stname[] = {
200         ".  ",
201         "Cmd",
202         "dat",
203         "c2s",
204         "sts",
205         "clr",
206         "crs",
207         "Sen",
208         "fin"
209 };
210
211 struct ub_scsi_cmd {
212         unsigned char cdb[UB_MAX_CDB_SIZE];
213         unsigned char cdb_len;
214
215         unsigned char dir;              /* 0 - none, 1 - read, 3 - write. */
216         unsigned char trace_index;
217         enum ub_scsi_cmd_state state;
218         unsigned int tag;
219         struct ub_scsi_cmd *next;
220
221         int error;                      /* Return code - valid upon done */
222         unsigned int act_len;           /* Return size */
223         unsigned char key, asc, ascq;   /* May be valid if error==-EIO */
224
225         int stat_count;                 /* Retries getting status. */
226
227         unsigned int len;               /* Requested length */
228         unsigned int current_sg;
229         unsigned int nsg;               /* sgv[nsg] */
230         struct scatterlist sgv[UB_MAX_REQ_SG];
231
232         struct ub_lun *lun;
233         void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
234         void *back;
235 };
236
237 struct ub_request {
238         struct request *rq;
239         unsigned int current_try;
240         unsigned int nsg;               /* sgv[nsg] */
241         struct scatterlist sgv[UB_MAX_REQ_SG];
242 };
243
244 /*
245  */
246 struct ub_capacity {
247         unsigned long nsec;             /* Linux size - 512 byte sectors */
248         unsigned int bsize;             /* Linux hardsect_size */
249         unsigned int bshift;            /* Shift between 512 and hard sects */
250 };
251
252 /*
253  * The SCSI command tracing structure.
254  */
255
256 #define SCMD_ST_HIST_SZ   8
257 #define SCMD_TRACE_SZ    63             /* Less than 4KB of 61-byte lines */
258
259 struct ub_scsi_cmd_trace {
260         int hcur;
261         unsigned int tag;
262         unsigned int req_size, act_size;
263         unsigned char op;
264         unsigned char dir;
265         unsigned char key, asc, ascq;
266         char st_hst[SCMD_ST_HIST_SZ];   
267 };
268
269 struct ub_scsi_trace {
270         int cur;
271         struct ub_scsi_cmd_trace vec[SCMD_TRACE_SZ];
272 };
273
274 /*
275  * This is a direct take-off from linux/include/completion.h
276  * The difference is that I do not wait on this thing, just poll.
277  * When I want to wait (ub_probe), I just use the stock completion.
278  *
279  * Note that INIT_COMPLETION takes no lock. It is correct. But why
280  * in the bloody hell that thing takes struct instead of pointer to struct
281  * is quite beyond me. I just copied it from the stock completion.
282  */
283 struct ub_completion {
284         unsigned int done;
285         spinlock_t lock;
286 };
287
288 static inline void ub_init_completion(struct ub_completion *x)
289 {
290         x->done = 0;
291         spin_lock_init(&x->lock);
292 }
293
294 #define UB_INIT_COMPLETION(x)   ((x).done = 0)
295
296 static void ub_complete(struct ub_completion *x)
297 {
298         unsigned long flags;
299
300         spin_lock_irqsave(&x->lock, flags);
301         x->done++;
302         spin_unlock_irqrestore(&x->lock, flags);
303 }
304
305 static int ub_is_completed(struct ub_completion *x)
306 {
307         unsigned long flags;
308         int ret;
309
310         spin_lock_irqsave(&x->lock, flags);
311         ret = x->done;
312         spin_unlock_irqrestore(&x->lock, flags);
313         return ret;
314 }
315
316 /*
317  */
318 struct ub_scsi_cmd_queue {
319         int qlen, qmax;
320         struct ub_scsi_cmd *head, *tail;
321 };
322
323 /*
324  * The block device instance (one per LUN).
325  */
326 struct ub_lun {
327         struct ub_dev *udev;
328         struct list_head link;
329         struct gendisk *disk;
330         int id;                         /* Host index */
331         int num;                        /* LUN number */
332         char name[16];
333
334         int changed;                    /* Media was changed */
335         int removable;
336         int readonly;
337         int first_open;                 /* Kludge. See ub_bd_open. */
338
339         struct ub_request urq;
340
341         /* Use Ingo's mempool if or when we have more than one command. */
342         /*
343          * Currently we never need more than one command for the whole device.
344          * However, giving every LUN a command is a cheap and automatic way
345          * to enforce fairness between them.
346          */
347         int cmda[1];
348         struct ub_scsi_cmd cmdv[1];
349
350         struct ub_capacity capacity; 
351 };
352
353 /*
354  * The USB device instance.
355  */
356 struct ub_dev {
357         spinlock_t *lock;
358         atomic_t poison;                /* The USB device is disconnected */
359         int openc;                      /* protected by ub_lock! */
360                                         /* kref is too implicit for our taste */
361         int reset;                      /* Reset is running */
362         unsigned int tagcnt;
363         char name[12];
364         struct usb_device *dev;
365         struct usb_interface *intf;
366
367         struct list_head luns;
368
369         unsigned int send_bulk_pipe;    /* cached pipe values */
370         unsigned int recv_bulk_pipe;
371         unsigned int send_ctrl_pipe;
372         unsigned int recv_ctrl_pipe;
373
374         struct tasklet_struct tasklet;
375
376         struct ub_scsi_cmd_queue cmd_queue;
377         struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
378         unsigned char top_sense[UB_SENSE_SIZE];
379
380         struct ub_completion work_done;
381         struct urb work_urb;
382         struct timer_list work_timer;
383         int last_pipe;                  /* What might need clearing */
384         __le32 signature;               /* Learned signature */
385         struct bulk_cb_wrap work_bcb;
386         struct bulk_cs_wrap work_bcs;
387         struct usb_ctrlrequest work_cr;
388
389         struct work_struct reset_work;
390         wait_queue_head_t reset_wait;
391
392         int sg_stat[6];
393         struct ub_scsi_trace tr;
394 };
395
396 /*
397  */
398 static void ub_cleanup(struct ub_dev *sc);
399 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
400 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
401     struct ub_scsi_cmd *cmd, struct ub_request *urq);
402 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
403     struct ub_scsi_cmd *cmd, struct ub_request *urq);
404 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
405 static void ub_end_rq(struct request *rq, int uptodate);
406 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
407     struct ub_request *urq, struct ub_scsi_cmd *cmd);
408 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
409 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
410 static void ub_scsi_action(unsigned long _dev);
411 static void ub_scsi_dispatch(struct ub_dev *sc);
412 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
413 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
414 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
415 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
416 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
417 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
418 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
419 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
420     int stalled_pipe);
421 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
422 static void ub_reset_enter(struct ub_dev *sc, int try);
423 static void ub_reset_task(void *arg);
424 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
425 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
426     struct ub_capacity *ret);
427 static int ub_sync_reset(struct ub_dev *sc);
428 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
429 static int ub_probe_lun(struct ub_dev *sc, int lnum);
430
431 /*
432  */
433 #ifdef CONFIG_USB_LIBUSUAL
434
435 #define ub_usb_ids  storage_usb_ids
436 #else
437
438 static struct usb_device_id ub_usb_ids[] = {
439         { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
440         { }
441 };
442
443 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
444 #endif /* CONFIG_USB_LIBUSUAL */
445
446 /*
447  * Find me a way to identify "next free minor" for add_disk(),
448  * and the array disappears the next day. However, the number of
449  * hosts has something to do with the naming and /proc/partitions.
450  * This has to be thought out in detail before changing.
451  * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
452  */
453 #define UB_MAX_HOSTS  26
454 static char ub_hostv[UB_MAX_HOSTS];
455
456 #define UB_QLOCK_NUM 5
457 static spinlock_t ub_qlockv[UB_QLOCK_NUM];
458 static int ub_qlock_next = 0;
459
460 static DEFINE_SPINLOCK(ub_lock);        /* Locks globals and ->openc */
461
462 /*
463  * The SCSI command tracing procedures.
464  */
465
466 static void ub_cmdtr_new(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
467 {
468         int n;
469         struct ub_scsi_cmd_trace *t;
470
471         if ((n = sc->tr.cur + 1) == SCMD_TRACE_SZ) n = 0;
472         t = &sc->tr.vec[n];
473
474         memset(t, 0, sizeof(struct ub_scsi_cmd_trace));
475         t->tag = cmd->tag;
476         t->op = cmd->cdb[0];
477         t->dir = cmd->dir;
478         t->req_size = cmd->len;
479         t->st_hst[0] = cmd->state;
480
481         sc->tr.cur = n;
482         cmd->trace_index = n;
483 }
484
485 static void ub_cmdtr_state(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
486 {
487         int n;
488         struct ub_scsi_cmd_trace *t;
489
490         t = &sc->tr.vec[cmd->trace_index];
491         if (t->tag == cmd->tag) {
492                 if ((n = t->hcur + 1) == SCMD_ST_HIST_SZ) n = 0;
493                 t->st_hst[n] = cmd->state;
494                 t->hcur = n;
495         }
496 }
497
498 static void ub_cmdtr_act_len(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
499 {
500         struct ub_scsi_cmd_trace *t;
501
502         t = &sc->tr.vec[cmd->trace_index];
503         if (t->tag == cmd->tag)
504                 t->act_size = cmd->act_len;
505 }
506
507 static void ub_cmdtr_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
508     unsigned char *sense)
509 {
510         struct ub_scsi_cmd_trace *t;
511
512         t = &sc->tr.vec[cmd->trace_index];
513         if (t->tag == cmd->tag) {
514                 t->key = sense[2] & 0x0F;
515                 t->asc = sense[12];
516                 t->ascq = sense[13];
517         }
518 }
519
520 static ssize_t ub_diag_show(struct device *dev, struct device_attribute *attr,
521     char *page)
522 {
523         struct usb_interface *intf;
524         struct ub_dev *sc;
525         struct list_head *p;
526         struct ub_lun *lun;
527         int cnt;
528         unsigned long flags;
529         int nc, nh;
530         int i, j;
531         struct ub_scsi_cmd_trace *t;
532
533         intf = to_usb_interface(dev);
534         sc = usb_get_intfdata(intf);
535         if (sc == NULL)
536                 return 0;
537
538         cnt = 0;
539         spin_lock_irqsave(sc->lock, flags);
540
541         cnt += sprintf(page + cnt,
542             "poison %d reset %d\n",
543             atomic_read(&sc->poison), sc->reset);
544         cnt += sprintf(page + cnt,
545             "qlen %d qmax %d\n",
546             sc->cmd_queue.qlen, sc->cmd_queue.qmax);
547         cnt += sprintf(page + cnt,
548             "sg %d %d %d %d %d .. %d\n",
549             sc->sg_stat[0],
550             sc->sg_stat[1],
551             sc->sg_stat[2],
552             sc->sg_stat[3],
553             sc->sg_stat[4],
554             sc->sg_stat[5]);
555
556         list_for_each (p, &sc->luns) {
557                 lun = list_entry(p, struct ub_lun, link);
558                 cnt += sprintf(page + cnt,
559                     "lun %u changed %d removable %d readonly %d\n",
560                     lun->num, lun->changed, lun->removable, lun->readonly);
561         }
562
563         if ((nc = sc->tr.cur + 1) == SCMD_TRACE_SZ) nc = 0;
564         for (j = 0; j < SCMD_TRACE_SZ; j++) {
565                 t = &sc->tr.vec[nc];
566
567                 cnt += sprintf(page + cnt, "%08x %02x", t->tag, t->op);
568                 if (t->op == REQUEST_SENSE) {
569                         cnt += sprintf(page + cnt, " [sense %x %02x %02x]",
570                                         t->key, t->asc, t->ascq);
571                 } else {
572                         cnt += sprintf(page + cnt, " %c", UB_DIR_CHAR(t->dir));
573                         cnt += sprintf(page + cnt, " [%5d %5d]",
574                                         t->req_size, t->act_size);
575                 }
576                 if ((nh = t->hcur + 1) == SCMD_ST_HIST_SZ) nh = 0;
577                 for (i = 0; i < SCMD_ST_HIST_SZ; i++) {
578                         cnt += sprintf(page + cnt, " %s",
579                                         ub_scsi_cmd_stname[(int)t->st_hst[nh]]);
580                         if (++nh == SCMD_ST_HIST_SZ) nh = 0;
581                 }
582                 cnt += sprintf(page + cnt, "\n");
583
584                 if (++nc == SCMD_TRACE_SZ) nc = 0;
585         }
586
587         spin_unlock_irqrestore(sc->lock, flags);
588         return cnt;
589 }
590
591 static DEVICE_ATTR(diag, S_IRUGO, ub_diag_show, NULL); /* N.B. World readable */
592
593 /*
594  * The id allocator.
595  *
596  * This also stores the host for indexing by minor, which is somewhat dirty.
597  */
598 static int ub_id_get(void)
599 {
600         unsigned long flags;
601         int i;
602
603         spin_lock_irqsave(&ub_lock, flags);
604         for (i = 0; i < UB_MAX_HOSTS; i++) {
605                 if (ub_hostv[i] == 0) {
606                         ub_hostv[i] = 1;
607                         spin_unlock_irqrestore(&ub_lock, flags);
608                         return i;
609                 }
610         }
611         spin_unlock_irqrestore(&ub_lock, flags);
612         return -1;
613 }
614
615 static void ub_id_put(int id)
616 {
617         unsigned long flags;
618
619         if (id < 0 || id >= UB_MAX_HOSTS) {
620                 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
621                 return;
622         }
623
624         spin_lock_irqsave(&ub_lock, flags);
625         if (ub_hostv[id] == 0) {
626                 spin_unlock_irqrestore(&ub_lock, flags);
627                 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
628                 return;
629         }
630         ub_hostv[id] = 0;
631         spin_unlock_irqrestore(&ub_lock, flags);
632 }
633
634 /*
635  * This is necessitated by the fact that blk_cleanup_queue does not
636  * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
637  * Since our blk_init_queue() passes a spinlock common with ub_dev,
638  * we have life time issues when ub_cleanup frees ub_dev.
639  */
640 static spinlock_t *ub_next_lock(void)
641 {
642         unsigned long flags;
643         spinlock_t *ret;
644
645         spin_lock_irqsave(&ub_lock, flags);
646         ret = &ub_qlockv[ub_qlock_next];
647         ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
648         spin_unlock_irqrestore(&ub_lock, flags);
649         return ret;
650 }
651
652 /*
653  * Downcount for deallocation. This rides on two assumptions:
654  *  - once something is poisoned, its refcount cannot grow
655  *  - opens cannot happen at this time (del_gendisk was done)
656  * If the above is true, we can drop the lock, which we need for
657  * blk_cleanup_queue(): the silly thing may attempt to sleep.
658  * [Actually, it never needs to sleep for us, but it calls might_sleep()]
659  */
660 static void ub_put(struct ub_dev *sc)
661 {
662         unsigned long flags;
663
664         spin_lock_irqsave(&ub_lock, flags);
665         --sc->openc;
666         if (sc->openc == 0 && atomic_read(&sc->poison)) {
667                 spin_unlock_irqrestore(&ub_lock, flags);
668                 ub_cleanup(sc);
669         } else {
670                 spin_unlock_irqrestore(&ub_lock, flags);
671         }
672 }
673
674 /*
675  * Final cleanup and deallocation.
676  */
677 static void ub_cleanup(struct ub_dev *sc)
678 {
679         struct list_head *p;
680         struct ub_lun *lun;
681         request_queue_t *q;
682
683         while (!list_empty(&sc->luns)) {
684                 p = sc->luns.next;
685                 lun = list_entry(p, struct ub_lun, link);
686                 list_del(p);
687
688                 /* I don't think queue can be NULL. But... Stolen from sx8.c */
689                 if ((q = lun->disk->queue) != NULL)
690                         blk_cleanup_queue(q);
691                 /*
692                  * If we zero disk->private_data BEFORE put_disk, we have
693                  * to check for NULL all over the place in open, release,
694                  * check_media and revalidate, because the block level
695                  * semaphore is well inside the put_disk.
696                  * But we cannot zero after the call, because *disk is gone.
697                  * The sd.c is blatantly racy in this area.
698                  */
699                 /* disk->private_data = NULL; */
700                 put_disk(lun->disk);
701                 lun->disk = NULL;
702
703                 ub_id_put(lun->id);
704                 kfree(lun);
705         }
706
707         kfree(sc);
708 }
709
710 /*
711  * The "command allocator".
712  */
713 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
714 {
715         struct ub_scsi_cmd *ret;
716
717         if (lun->cmda[0])
718                 return NULL;
719         ret = &lun->cmdv[0];
720         lun->cmda[0] = 1;
721         return ret;
722 }
723
724 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
725 {
726         if (cmd != &lun->cmdv[0]) {
727                 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
728                     lun->name, cmd);
729                 return;
730         }
731         if (!lun->cmda[0]) {
732                 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
733                 return;
734         }
735         lun->cmda[0] = 0;
736 }
737
738 /*
739  * The command queue.
740  */
741 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
742 {
743         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
744
745         if (t->qlen++ == 0) {
746                 t->head = cmd;
747                 t->tail = cmd;
748         } else {
749                 t->tail->next = cmd;
750                 t->tail = cmd;
751         }
752
753         if (t->qlen > t->qmax)
754                 t->qmax = t->qlen;
755 }
756
757 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
758 {
759         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
760
761         if (t->qlen++ == 0) {
762                 t->head = cmd;
763                 t->tail = cmd;
764         } else {
765                 cmd->next = t->head;
766                 t->head = cmd;
767         }
768
769         if (t->qlen > t->qmax)
770                 t->qmax = t->qlen;
771 }
772
773 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
774 {
775         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
776         struct ub_scsi_cmd *cmd;
777
778         if (t->qlen == 0)
779                 return NULL;
780         if (--t->qlen == 0)
781                 t->tail = NULL;
782         cmd = t->head;
783         t->head = cmd->next;
784         cmd->next = NULL;
785         return cmd;
786 }
787
788 #define ub_cmdq_peek(sc)  ((sc)->cmd_queue.head)
789
790 /*
791  * The request function is our main entry point
792  */
793
794 static void ub_request_fn(request_queue_t *q)
795 {
796         struct ub_lun *lun = q->queuedata;
797         struct request *rq;
798
799         while ((rq = elv_next_request(q)) != NULL) {
800                 if (ub_request_fn_1(lun, rq) != 0) {
801                         blk_stop_queue(q);
802                         break;
803                 }
804         }
805 }
806
807 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
808 {
809         struct ub_dev *sc = lun->udev;
810         struct ub_scsi_cmd *cmd;
811         struct ub_request *urq;
812         int n_elem;
813
814         if (atomic_read(&sc->poison) || lun->changed) {
815                 blkdev_dequeue_request(rq);
816                 ub_end_rq(rq, 0);
817                 return 0;
818         }
819
820         if (lun->urq.rq != NULL)
821                 return -1;
822         if ((cmd = ub_get_cmd(lun)) == NULL)
823                 return -1;
824         memset(cmd, 0, sizeof(struct ub_scsi_cmd));
825
826         blkdev_dequeue_request(rq);
827
828         urq = &lun->urq;
829         memset(urq, 0, sizeof(struct ub_request));
830         urq->rq = rq;
831
832         /*
833          * get scatterlist from block layer
834          */
835         n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
836         if (n_elem < 0) {
837                 printk(KERN_INFO "%s: failed request map (%d)\n",
838                     lun->name, n_elem); /* P3 */
839                 goto drop;
840         }
841         if (n_elem > UB_MAX_REQ_SG) {   /* Paranoia */
842                 printk(KERN_WARNING "%s: request with %d segments\n",
843                     lun->name, n_elem);
844                 goto drop;
845         }
846         urq->nsg = n_elem;
847         sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
848
849         if (blk_pc_request(rq)) {
850                 ub_cmd_build_packet(sc, lun, cmd, urq);
851         } else {
852                 ub_cmd_build_block(sc, lun, cmd, urq);
853         }
854         cmd->state = UB_CMDST_INIT;
855         cmd->lun = lun;
856         cmd->done = ub_rw_cmd_done;
857         cmd->back = urq;
858
859         cmd->tag = sc->tagcnt++;
860         if (ub_submit_scsi(sc, cmd) != 0)
861                 goto drop;
862
863         return 0;
864
865 drop:
866         ub_put_cmd(lun, cmd);
867         ub_end_rq(rq, 0);
868         return 0;
869 }
870
871 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
872     struct ub_scsi_cmd *cmd, struct ub_request *urq)
873 {
874         struct request *rq = urq->rq;
875         unsigned int block, nblks;
876
877         if (rq_data_dir(rq) == WRITE)
878                 cmd->dir = UB_DIR_WRITE;
879         else
880                 cmd->dir = UB_DIR_READ;
881
882         cmd->nsg = urq->nsg;
883         memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
884
885         /*
886          * build the command
887          *
888          * The call to blk_queue_hardsect_size() guarantees that request
889          * is aligned, but it is given in terms of 512 byte units, always.
890          */
891         block = rq->sector >> lun->capacity.bshift;
892         nblks = rq->nr_sectors >> lun->capacity.bshift;
893
894         cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
895         /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
896         cmd->cdb[2] = block >> 24;
897         cmd->cdb[3] = block >> 16;
898         cmd->cdb[4] = block >> 8;
899         cmd->cdb[5] = block;
900         cmd->cdb[7] = nblks >> 8;
901         cmd->cdb[8] = nblks;
902         cmd->cdb_len = 10;
903
904         cmd->len = rq->nr_sectors * 512;
905 }
906
907 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
908     struct ub_scsi_cmd *cmd, struct ub_request *urq)
909 {
910         struct request *rq = urq->rq;
911
912         if (rq->data_len == 0) {
913                 cmd->dir = UB_DIR_NONE;
914         } else {
915                 if (rq_data_dir(rq) == WRITE)
916                         cmd->dir = UB_DIR_WRITE;
917                 else
918                         cmd->dir = UB_DIR_READ;
919         }
920
921         cmd->nsg = urq->nsg;
922         memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
923
924         memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
925         cmd->cdb_len = rq->cmd_len;
926
927         cmd->len = rq->data_len;
928 }
929
930 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
931 {
932         struct ub_lun *lun = cmd->lun;
933         struct ub_request *urq = cmd->back;
934         struct request *rq;
935         int uptodate;
936
937         rq = urq->rq;
938
939         if (cmd->error == 0) {
940                 uptodate = 1;
941
942                 if (blk_pc_request(rq)) {
943                         if (cmd->act_len >= rq->data_len)
944                                 rq->data_len = 0;
945                         else
946                                 rq->data_len -= cmd->act_len;
947                 }
948         } else {
949                 uptodate = 0;
950
951                 if (blk_pc_request(rq)) {
952                         /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
953                         memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
954                         rq->sense_len = UB_SENSE_SIZE;
955                         if (sc->top_sense[0] != 0)
956                                 rq->errors = SAM_STAT_CHECK_CONDITION;
957                         else
958                                 rq->errors = DID_ERROR << 16;
959                 } else {
960                         if (cmd->error == -EIO) {
961                                 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
962                                         return;
963                         }
964                 }
965         }
966
967         urq->rq = NULL;
968
969         ub_put_cmd(lun, cmd);
970         ub_end_rq(rq, uptodate);
971         blk_start_queue(lun->disk->queue);
972 }
973
974 static void ub_end_rq(struct request *rq, int uptodate)
975 {
976         end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
977         end_that_request_last(rq, uptodate);
978 }
979
980 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
981     struct ub_request *urq, struct ub_scsi_cmd *cmd)
982 {
983
984         if (atomic_read(&sc->poison))
985                 return -ENXIO;
986
987         ub_reset_enter(sc, urq->current_try);
988
989         if (urq->current_try >= 3)
990                 return -EIO;
991         urq->current_try++;
992         /* P3 */ printk("%s: dir %c len/act %d/%d "
993             "[sense %x %02x %02x] retry %d\n",
994             sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
995             cmd->key, cmd->asc, cmd->ascq, urq->current_try);
996
997         memset(cmd, 0, sizeof(struct ub_scsi_cmd));
998         ub_cmd_build_block(sc, lun, cmd, urq);
999
1000         cmd->state = UB_CMDST_INIT;
1001         cmd->lun = lun;
1002         cmd->done = ub_rw_cmd_done;
1003         cmd->back = urq;
1004
1005         cmd->tag = sc->tagcnt++;
1006
1007 #if 0 /* Wasteful */
1008         return ub_submit_scsi(sc, cmd);
1009 #else
1010         ub_cmdq_add(sc, cmd);
1011         return 0;
1012 #endif
1013 }
1014
1015 /*
1016  * Submit a regular SCSI operation (not an auto-sense).
1017  *
1018  * The Iron Law of Good Submit Routine is:
1019  * Zero return - callback is done, Nonzero return - callback is not done.
1020  * No exceptions.
1021  *
1022  * Host is assumed locked.
1023  */
1024 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1025 {
1026
1027         if (cmd->state != UB_CMDST_INIT ||
1028             (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
1029                 return -EINVAL;
1030         }
1031
1032         ub_cmdq_add(sc, cmd);
1033         /*
1034          * We can call ub_scsi_dispatch(sc) right away here, but it's a little
1035          * safer to jump to a tasklet, in case upper layers do something silly.
1036          */
1037         tasklet_schedule(&sc->tasklet);
1038         return 0;
1039 }
1040
1041 /*
1042  * Submit the first URB for the queued command.
1043  * This function does not deal with queueing in any way.
1044  */
1045 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1046 {
1047         struct bulk_cb_wrap *bcb;
1048         int rc;
1049
1050         bcb = &sc->work_bcb;
1051
1052         /*
1053          * ``If the allocation length is eighteen or greater, and a device
1054          * server returns less than eithteen bytes of data, the application
1055          * client should assume that the bytes not transferred would have been
1056          * zeroes had the device server returned those bytes.''
1057          *
1058          * We zero sense for all commands so that when a packet request
1059          * fails it does not return a stale sense.
1060          */
1061         memset(&sc->top_sense, 0, UB_SENSE_SIZE);
1062
1063         /* set up the command wrapper */
1064         bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1065         bcb->Tag = cmd->tag;            /* Endianness is not important */
1066         bcb->DataTransferLength = cpu_to_le32(cmd->len);
1067         bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
1068         bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
1069         bcb->Length = cmd->cdb_len;
1070
1071         /* copy the command payload */
1072         memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
1073
1074         UB_INIT_COMPLETION(sc->work_done);
1075
1076         sc->last_pipe = sc->send_bulk_pipe;
1077         usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
1078             bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
1079
1080         /* Fill what we shouldn't be filling, because usb-storage did so. */
1081         sc->work_urb.actual_length = 0;
1082         sc->work_urb.error_count = 0;
1083         sc->work_urb.status = 0;
1084
1085         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1086                 /* XXX Clear stalls */
1087                 ub_complete(&sc->work_done);
1088                 return rc;
1089         }
1090
1091         sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
1092         add_timer(&sc->work_timer);
1093
1094         cmd->state = UB_CMDST_CMD;
1095         ub_cmdtr_state(sc, cmd);
1096         return 0;
1097 }
1098
1099 /*
1100  * Timeout handler.
1101  */
1102 static void ub_urb_timeout(unsigned long arg)
1103 {
1104         struct ub_dev *sc = (struct ub_dev *) arg;
1105         unsigned long flags;
1106
1107         spin_lock_irqsave(sc->lock, flags);
1108         if (!ub_is_completed(&sc->work_done))
1109                 usb_unlink_urb(&sc->work_urb);
1110         spin_unlock_irqrestore(sc->lock, flags);
1111 }
1112
1113 /*
1114  * Completion routine for the work URB.
1115  *
1116  * This can be called directly from usb_submit_urb (while we have
1117  * the sc->lock taken) and from an interrupt (while we do NOT have
1118  * the sc->lock taken). Therefore, bounce this off to a tasklet.
1119  */
1120 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
1121 {
1122         struct ub_dev *sc = urb->context;
1123
1124         ub_complete(&sc->work_done);
1125         tasklet_schedule(&sc->tasklet);
1126 }
1127
1128 static void ub_scsi_action(unsigned long _dev)
1129 {
1130         struct ub_dev *sc = (struct ub_dev *) _dev;
1131         unsigned long flags;
1132
1133         spin_lock_irqsave(sc->lock, flags);
1134         ub_scsi_dispatch(sc);
1135         spin_unlock_irqrestore(sc->lock, flags);
1136 }
1137
1138 static void ub_scsi_dispatch(struct ub_dev *sc)
1139 {
1140         struct ub_scsi_cmd *cmd;
1141         int rc;
1142
1143         while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
1144                 if (cmd->state == UB_CMDST_DONE) {
1145                         ub_cmdq_pop(sc);
1146                         (*cmd->done)(sc, cmd);
1147                 } else if (cmd->state == UB_CMDST_INIT) {
1148                         ub_cmdtr_new(sc, cmd);
1149                         if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1150                                 break;
1151                         cmd->error = rc;
1152                         cmd->state = UB_CMDST_DONE;
1153                         ub_cmdtr_state(sc, cmd);
1154                 } else {
1155                         if (!ub_is_completed(&sc->work_done))
1156                                 break;
1157                         del_timer(&sc->work_timer);
1158                         ub_scsi_urb_compl(sc, cmd);
1159                 }
1160         }
1161 }
1162
1163 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1164 {
1165         struct urb *urb = &sc->work_urb;
1166         struct bulk_cs_wrap *bcs;
1167         int len;
1168         int rc;
1169
1170         if (atomic_read(&sc->poison)) {
1171                 ub_state_done(sc, cmd, -ENODEV);
1172                 return;
1173         }
1174
1175         if (cmd->state == UB_CMDST_CLEAR) {
1176                 if (urb->status == -EPIPE) {
1177                         /*
1178                          * STALL while clearning STALL.
1179                          * The control pipe clears itself - nothing to do.
1180                          */
1181                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1182                             sc->name);
1183                         goto Bad_End;
1184                 }
1185
1186                 /*
1187                  * We ignore the result for the halt clear.
1188                  */
1189
1190                 /* reset the endpoint toggle */
1191                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1192                         usb_pipeout(sc->last_pipe), 0);
1193
1194                 ub_state_sense(sc, cmd);
1195
1196         } else if (cmd->state == UB_CMDST_CLR2STS) {
1197                 if (urb->status == -EPIPE) {
1198                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1199                             sc->name);
1200                         goto Bad_End;
1201                 }
1202
1203                 /*
1204                  * We ignore the result for the halt clear.
1205                  */
1206
1207                 /* reset the endpoint toggle */
1208                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1209                         usb_pipeout(sc->last_pipe), 0);
1210
1211                 ub_state_stat(sc, cmd);
1212
1213         } else if (cmd->state == UB_CMDST_CLRRS) {
1214                 if (urb->status == -EPIPE) {
1215                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1216                             sc->name);
1217                         goto Bad_End;
1218                 }
1219
1220                 /*
1221                  * We ignore the result for the halt clear.
1222                  */
1223
1224                 /* reset the endpoint toggle */
1225                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1226                         usb_pipeout(sc->last_pipe), 0);
1227
1228                 ub_state_stat_counted(sc, cmd);
1229
1230         } else if (cmd->state == UB_CMDST_CMD) {
1231                 switch (urb->status) {
1232                 case 0:
1233                         break;
1234                 case -EOVERFLOW:
1235                         goto Bad_End;
1236                 case -EPIPE:
1237                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1238                         if (rc != 0) {
1239                                 printk(KERN_NOTICE "%s: "
1240                                     "unable to submit clear (%d)\n",
1241                                     sc->name, rc);
1242                                 /*
1243                                  * This is typically ENOMEM or some other such shit.
1244                                  * Retrying is pointless. Just do Bad End on it...
1245                                  */
1246                                 ub_state_done(sc, cmd, rc);
1247                                 return;
1248                         }
1249                         cmd->state = UB_CMDST_CLEAR;
1250                         ub_cmdtr_state(sc, cmd);
1251                         return;
1252                 case -ESHUTDOWN:        /* unplug */
1253                 case -EILSEQ:           /* unplug timeout on uhci */
1254                         ub_state_done(sc, cmd, -ENODEV);
1255                         return;
1256                 default:
1257                         goto Bad_End;
1258                 }
1259                 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1260                         goto Bad_End;
1261                 }
1262
1263                 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1264                         ub_state_stat(sc, cmd);
1265                         return;
1266                 }
1267
1268                 // udelay(125);         // usb-storage has this
1269                 ub_data_start(sc, cmd);
1270
1271         } else if (cmd->state == UB_CMDST_DATA) {
1272                 if (urb->status == -EPIPE) {
1273                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1274                         if (rc != 0) {
1275                                 printk(KERN_NOTICE "%s: "
1276                                     "unable to submit clear (%d)\n",
1277                                     sc->name, rc);
1278                                 ub_state_done(sc, cmd, rc);
1279                                 return;
1280                         }
1281                         cmd->state = UB_CMDST_CLR2STS;
1282                         ub_cmdtr_state(sc, cmd);
1283                         return;
1284                 }
1285                 if (urb->status == -EOVERFLOW) {
1286                         /*
1287                          * A babble? Failure, but we must transfer CSW now.
1288                          */
1289                         cmd->error = -EOVERFLOW;        /* A cheap trick... */
1290                         ub_state_stat(sc, cmd);
1291                         return;
1292                 }
1293
1294                 if (cmd->dir == UB_DIR_WRITE) {
1295                         /*
1296                          * Do not continue writes in case of a failure.
1297                          * Doing so would cause sectors to be mixed up,
1298                          * which is worse than sectors lost.
1299                          *
1300                          * We must try to read the CSW, or many devices
1301                          * get confused.
1302                          */
1303                         len = urb->actual_length;
1304                         if (urb->status != 0 ||
1305                             len != cmd->sgv[cmd->current_sg].length) {
1306                                 cmd->act_len += len;
1307                                 ub_cmdtr_act_len(sc, cmd);
1308
1309                                 cmd->error = -EIO;
1310                                 ub_state_stat(sc, cmd);
1311                                 return;
1312                         }
1313
1314                 } else {
1315                         /*
1316                          * If an error occurs on read, we record it, and
1317                          * continue to fetch data in order to avoid bubble.
1318                          *
1319                          * As a small shortcut, we stop if we detect that
1320                          * a CSW mixed into data.
1321                          */
1322                         if (urb->status != 0)
1323                                 cmd->error = -EIO;
1324
1325                         len = urb->actual_length;
1326                         if (urb->status != 0 ||
1327                             len != cmd->sgv[cmd->current_sg].length) {
1328                                 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1329                                         goto Bad_End;
1330                         }
1331                 }
1332
1333                 cmd->act_len += urb->actual_length;
1334                 ub_cmdtr_act_len(sc, cmd);
1335
1336                 if (++cmd->current_sg < cmd->nsg) {
1337                         ub_data_start(sc, cmd);
1338                         return;
1339                 }
1340                 ub_state_stat(sc, cmd);
1341
1342         } else if (cmd->state == UB_CMDST_STAT) {
1343                 if (urb->status == -EPIPE) {
1344                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1345                         if (rc != 0) {
1346                                 printk(KERN_NOTICE "%s: "
1347                                     "unable to submit clear (%d)\n",
1348                                     sc->name, rc);
1349                                 ub_state_done(sc, cmd, rc);
1350                                 return;
1351                         }
1352
1353                         /*
1354                          * Having a stall when getting CSW is an error, so
1355                          * make sure uppper levels are not oblivious to it.
1356                          */
1357                         cmd->error = -EIO;              /* A cheap trick... */
1358
1359                         cmd->state = UB_CMDST_CLRRS;
1360                         ub_cmdtr_state(sc, cmd);
1361                         return;
1362                 }
1363
1364                 /* Catch everything, including -EOVERFLOW and other nasties. */
1365                 if (urb->status != 0)
1366                         goto Bad_End;
1367
1368                 if (urb->actual_length == 0) {
1369                         ub_state_stat_counted(sc, cmd);
1370                         return;
1371                 }
1372
1373                 /*
1374                  * Check the returned Bulk protocol status.
1375                  * The status block has to be validated first.
1376                  */
1377
1378                 bcs = &sc->work_bcs;
1379
1380                 if (sc->signature == cpu_to_le32(0)) {
1381                         /*
1382                          * This is the first reply, so do not perform the check.
1383                          * Instead, remember the signature the device uses
1384                          * for future checks. But do not allow a nul.
1385                          */
1386                         sc->signature = bcs->Signature;
1387                         if (sc->signature == cpu_to_le32(0)) {
1388                                 ub_state_stat_counted(sc, cmd);
1389                                 return;
1390                         }
1391                 } else {
1392                         if (bcs->Signature != sc->signature) {
1393                                 ub_state_stat_counted(sc, cmd);
1394                                 return;
1395                         }
1396                 }
1397
1398                 if (bcs->Tag != cmd->tag) {
1399                         /*
1400                          * This usually happens when we disagree with the
1401                          * device's microcode about something. For instance,
1402                          * a few of them throw this after timeouts. They buffer
1403                          * commands and reply at commands we timed out before.
1404                          * Without flushing these replies we loop forever.
1405                          */
1406                         ub_state_stat_counted(sc, cmd);
1407                         return;
1408                 }
1409
1410                 len = le32_to_cpu(bcs->Residue);
1411                 if (len != cmd->len - cmd->act_len) {
1412                         /*
1413                          * It is all right to transfer less, the caller has
1414                          * to check. But it's not all right if the device
1415                          * counts disagree with our counts.
1416                          */
1417                         /* P3 */ printk("%s: resid %d len %d act %d\n",
1418                             sc->name, len, cmd->len, cmd->act_len);
1419                         goto Bad_End;
1420                 }
1421
1422                 switch (bcs->Status) {
1423                 case US_BULK_STAT_OK:
1424                         break;
1425                 case US_BULK_STAT_FAIL:
1426                         ub_state_sense(sc, cmd);
1427                         return;
1428                 case US_BULK_STAT_PHASE:
1429                         /* P3 */ printk("%s: status PHASE\n", sc->name);
1430                         goto Bad_End;
1431                 default:
1432                         printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1433                             sc->name, bcs->Status);
1434                         ub_state_done(sc, cmd, -EINVAL);
1435                         return;
1436                 }
1437
1438                 /* Not zeroing error to preserve a babble indicator */
1439                 if (cmd->error != 0) {
1440                         ub_state_sense(sc, cmd);
1441                         return;
1442                 }
1443                 cmd->state = UB_CMDST_DONE;
1444                 ub_cmdtr_state(sc, cmd);
1445                 ub_cmdq_pop(sc);
1446                 (*cmd->done)(sc, cmd);
1447
1448         } else if (cmd->state == UB_CMDST_SENSE) {
1449                 ub_state_done(sc, cmd, -EIO);
1450
1451         } else {
1452                 printk(KERN_WARNING "%s: "
1453                     "wrong command state %d\n",
1454                     sc->name, cmd->state);
1455                 ub_state_done(sc, cmd, -EINVAL);
1456                 return;
1457         }
1458         return;
1459
1460 Bad_End: /* Little Excel is dead */
1461         ub_state_done(sc, cmd, -EIO);
1462 }
1463
1464 /*
1465  * Factorization helper for the command state machine:
1466  * Initiate a data segment transfer.
1467  */
1468 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1469 {
1470         struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1471         int pipe;
1472         int rc;
1473
1474         UB_INIT_COMPLETION(sc->work_done);
1475
1476         if (cmd->dir == UB_DIR_READ)
1477                 pipe = sc->recv_bulk_pipe;
1478         else
1479                 pipe = sc->send_bulk_pipe;
1480         sc->last_pipe = pipe;
1481         usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1482             page_address(sg->page) + sg->offset, sg->length,
1483             ub_urb_complete, sc);
1484         sc->work_urb.actual_length = 0;
1485         sc->work_urb.error_count = 0;
1486         sc->work_urb.status = 0;
1487
1488         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1489                 /* XXX Clear stalls */
1490                 ub_complete(&sc->work_done);
1491                 ub_state_done(sc, cmd, rc);
1492                 return;
1493         }
1494
1495         sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1496         add_timer(&sc->work_timer);
1497
1498         cmd->state = UB_CMDST_DATA;
1499         ub_cmdtr_state(sc, cmd);
1500 }
1501
1502 /*
1503  * Factorization helper for the command state machine:
1504  * Finish the command.
1505  */
1506 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1507 {
1508
1509         cmd->error = rc;
1510         cmd->state = UB_CMDST_DONE;
1511         ub_cmdtr_state(sc, cmd);
1512         ub_cmdq_pop(sc);
1513         (*cmd->done)(sc, cmd);
1514 }
1515
1516 /*
1517  * Factorization helper for the command state machine:
1518  * Submit a CSW read.
1519  */
1520 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1521 {
1522         int rc;
1523
1524         UB_INIT_COMPLETION(sc->work_done);
1525
1526         sc->last_pipe = sc->recv_bulk_pipe;
1527         usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1528             &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1529         sc->work_urb.actual_length = 0;
1530         sc->work_urb.error_count = 0;
1531         sc->work_urb.status = 0;
1532
1533         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1534                 /* XXX Clear stalls */
1535                 ub_complete(&sc->work_done);
1536                 ub_state_done(sc, cmd, rc);
1537                 return -1;
1538         }
1539
1540         sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1541         add_timer(&sc->work_timer);
1542         return 0;
1543 }
1544
1545 /*
1546  * Factorization helper for the command state machine:
1547  * Submit a CSW read and go to STAT state.
1548  */
1549 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1550 {
1551
1552         if (__ub_state_stat(sc, cmd) != 0)
1553                 return;
1554
1555         cmd->stat_count = 0;
1556         cmd->state = UB_CMDST_STAT;
1557         ub_cmdtr_state(sc, cmd);
1558 }
1559
1560 /*
1561  * Factorization helper for the command state machine:
1562  * Submit a CSW read and go to STAT state with counter (along [C] path).
1563  */
1564 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1565 {
1566
1567         if (++cmd->stat_count >= 4) {
1568                 ub_state_sense(sc, cmd);
1569                 return;
1570         }
1571
1572         if (__ub_state_stat(sc, cmd) != 0)
1573                 return;
1574
1575         cmd->state = UB_CMDST_STAT;
1576         ub_cmdtr_state(sc, cmd);
1577 }
1578
1579 /*
1580  * Factorization helper for the command state machine:
1581  * Submit a REQUEST SENSE and go to SENSE state.
1582  */
1583 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1584 {
1585         struct ub_scsi_cmd *scmd;
1586         struct scatterlist *sg;
1587         int rc;
1588
1589         if (cmd->cdb[0] == REQUEST_SENSE) {
1590                 rc = -EPIPE;
1591                 goto error;
1592         }
1593
1594         scmd = &sc->top_rqs_cmd;
1595         memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1596         scmd->cdb[0] = REQUEST_SENSE;
1597         scmd->cdb[4] = UB_SENSE_SIZE;
1598         scmd->cdb_len = 6;
1599         scmd->dir = UB_DIR_READ;
1600         scmd->state = UB_CMDST_INIT;
1601         scmd->nsg = 1;
1602         sg = &scmd->sgv[0];
1603         sg->page = virt_to_page(sc->top_sense);
1604         sg->offset = (unsigned long)sc->top_sense & (PAGE_SIZE-1);
1605         sg->length = UB_SENSE_SIZE;
1606         scmd->len = UB_SENSE_SIZE;
1607         scmd->lun = cmd->lun;
1608         scmd->done = ub_top_sense_done;
1609         scmd->back = cmd;
1610
1611         scmd->tag = sc->tagcnt++;
1612
1613         cmd->state = UB_CMDST_SENSE;
1614         ub_cmdtr_state(sc, cmd);
1615
1616         ub_cmdq_insert(sc, scmd);
1617         return;
1618
1619 error:
1620         ub_state_done(sc, cmd, rc);
1621 }
1622
1623 /*
1624  * A helper for the command's state machine:
1625  * Submit a stall clear.
1626  */
1627 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1628     int stalled_pipe)
1629 {
1630         int endp;
1631         struct usb_ctrlrequest *cr;
1632         int rc;
1633
1634         endp = usb_pipeendpoint(stalled_pipe);
1635         if (usb_pipein (stalled_pipe))
1636                 endp |= USB_DIR_IN;
1637
1638         cr = &sc->work_cr;
1639         cr->bRequestType = USB_RECIP_ENDPOINT;
1640         cr->bRequest = USB_REQ_CLEAR_FEATURE;
1641         cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1642         cr->wIndex = cpu_to_le16(endp);
1643         cr->wLength = cpu_to_le16(0);
1644
1645         UB_INIT_COMPLETION(sc->work_done);
1646
1647         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1648             (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1649         sc->work_urb.actual_length = 0;
1650         sc->work_urb.error_count = 0;
1651         sc->work_urb.status = 0;
1652
1653         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1654                 ub_complete(&sc->work_done);
1655                 return rc;
1656         }
1657
1658         sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1659         add_timer(&sc->work_timer);
1660         return 0;
1661 }
1662
1663 /*
1664  */
1665 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1666 {
1667         unsigned char *sense = sc->top_sense;
1668         struct ub_scsi_cmd *cmd;
1669
1670         /*
1671          * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1672          */
1673         ub_cmdtr_sense(sc, scmd, sense);
1674
1675         /*
1676          * Find the command which triggered the unit attention or a check,
1677          * save the sense into it, and advance its state machine.
1678          */
1679         if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1680                 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1681                 return;
1682         }
1683         if (cmd != scmd->back) {
1684                 printk(KERN_WARNING "%s: "
1685                     "sense done for wrong command 0x%x\n",
1686                     sc->name, cmd->tag);
1687                 return;
1688         }
1689         if (cmd->state != UB_CMDST_SENSE) {
1690                 printk(KERN_WARNING "%s: "
1691                     "sense done with bad cmd state %d\n",
1692                     sc->name, cmd->state);
1693                 return;
1694         }
1695
1696         cmd->key = sense[2] & 0x0F;
1697         cmd->asc = sense[12];
1698         cmd->ascq = sense[13];
1699
1700         ub_scsi_urb_compl(sc, cmd);
1701 }
1702
1703 /*
1704  * Reset management
1705  * XXX Move usb_reset_device to khubd. Hogging kevent is not a good thing.
1706  * XXX Make usb_sync_reset asynchronous.
1707  */
1708
1709 static void ub_reset_enter(struct ub_dev *sc, int try)
1710 {
1711
1712         if (sc->reset) {
1713                 /* This happens often on multi-LUN devices. */
1714                 return;
1715         }
1716         sc->reset = try + 1;
1717
1718 #if 0 /* Not needed because the disconnect waits for us. */
1719         unsigned long flags;
1720         spin_lock_irqsave(&ub_lock, flags);
1721         sc->openc++;
1722         spin_unlock_irqrestore(&ub_lock, flags);
1723 #endif
1724
1725 #if 0 /* We let them stop themselves. */
1726         struct list_head *p;
1727         struct ub_lun *lun;
1728         list_for_each(p, &sc->luns) {
1729                 lun = list_entry(p, struct ub_lun, link);
1730                 blk_stop_queue(lun->disk->queue);
1731         }
1732 #endif
1733
1734         schedule_work(&sc->reset_work);
1735 }
1736
1737 static void ub_reset_task(void *arg)
1738 {
1739         struct ub_dev *sc = arg;
1740         unsigned long flags;
1741         struct list_head *p;
1742         struct ub_lun *lun;
1743         int lkr, rc;
1744
1745         if (!sc->reset) {
1746                 printk(KERN_WARNING "%s: Running reset unrequested\n",
1747                     sc->name);
1748                 return;
1749         }
1750
1751         if (atomic_read(&sc->poison)) {
1752                 printk(KERN_NOTICE "%s: Not resetting disconnected device\n",
1753                     sc->name); /* P3 This floods. Remove soon. XXX */
1754         } else if ((sc->reset & 1) == 0) {
1755                 ub_sync_reset(sc);
1756                 msleep(700);    /* usb-storage sleeps 6s (!) */
1757                 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1758                 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1759         } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1760                 printk(KERN_NOTICE "%s: Not resetting multi-interface device\n",
1761                     sc->name); /* P3 This floods. Remove soon. XXX */
1762         } else {
1763                 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1764                         printk(KERN_NOTICE
1765                             "%s: usb_lock_device_for_reset failed (%d)\n",
1766                             sc->name, lkr);
1767                 } else {
1768                         rc = usb_reset_device(sc->dev);
1769                         if (rc < 0) {
1770                                 printk(KERN_NOTICE "%s: "
1771                                     "usb_lock_device_for_reset failed (%d)\n",
1772                                     sc->name, rc);
1773                         }
1774
1775                         if (lkr)
1776                                 usb_unlock_device(sc->dev);
1777                 }
1778         }
1779
1780         /*
1781          * In theory, no commands can be running while reset is active,
1782          * so nobody can ask for another reset, and so we do not need any
1783          * queues of resets or anything. We do need a spinlock though,
1784          * to interact with block layer.
1785          */
1786         spin_lock_irqsave(sc->lock, flags);
1787         sc->reset = 0;
1788         tasklet_schedule(&sc->tasklet);
1789         list_for_each(p, &sc->luns) {
1790                 lun = list_entry(p, struct ub_lun, link);
1791                 blk_start_queue(lun->disk->queue);
1792         }
1793         wake_up(&sc->reset_wait);
1794         spin_unlock_irqrestore(sc->lock, flags);
1795 }
1796
1797 /*
1798  * This is called from a process context.
1799  */
1800 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1801 {
1802
1803         lun->readonly = 0;      /* XXX Query this from the device */
1804
1805         lun->capacity.nsec = 0;
1806         lun->capacity.bsize = 512;
1807         lun->capacity.bshift = 0;
1808
1809         if (ub_sync_tur(sc, lun) != 0)
1810                 return;                 /* Not ready */
1811         lun->changed = 0;
1812
1813         if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1814                 /*
1815                  * The retry here means something is wrong, either with the
1816                  * device, with the transport, or with our code.
1817                  * We keep this because sd.c has retries for capacity.
1818                  */
1819                 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1820                         lun->capacity.nsec = 0;
1821                         lun->capacity.bsize = 512;
1822                         lun->capacity.bshift = 0;
1823                 }
1824         }
1825 }
1826
1827 /*
1828  * The open funcion.
1829  * This is mostly needed to keep refcounting, but also to support
1830  * media checks on removable media drives.
1831  */
1832 static int ub_bd_open(struct inode *inode, struct file *filp)
1833 {
1834         struct gendisk *disk = inode->i_bdev->bd_disk;
1835         struct ub_lun *lun;
1836         struct ub_dev *sc;
1837         unsigned long flags;
1838         int rc;
1839
1840         if ((lun = disk->private_data) == NULL)
1841                 return -ENXIO;
1842         sc = lun->udev;
1843
1844         spin_lock_irqsave(&ub_lock, flags);
1845         if (atomic_read(&sc->poison)) {
1846                 spin_unlock_irqrestore(&ub_lock, flags);
1847                 return -ENXIO;
1848         }
1849         sc->openc++;
1850         spin_unlock_irqrestore(&ub_lock, flags);
1851
1852         /*
1853          * This is a workaround for a specific problem in our block layer.
1854          * In 2.6.9, register_disk duplicates the code from rescan_partitions.
1855          * However, if we do add_disk with a device which persistently reports
1856          * a changed media, add_disk calls register_disk, which does do_open,
1857          * which will call rescan_paritions for changed media. After that,
1858          * register_disk attempts to do it all again and causes double kobject
1859          * registration and a eventually an oops on module removal.
1860          *
1861          * The bottom line is, Al Viro says that we should not allow
1862          * bdev->bd_invalidated to be set when doing add_disk no matter what.
1863          */
1864         if (lun->first_open) {
1865                 lun->first_open = 0;
1866                 if (lun->changed) {
1867                         rc = -ENOMEDIUM;
1868                         goto err_open;
1869                 }
1870         }
1871
1872         if (lun->removable || lun->readonly)
1873                 check_disk_change(inode->i_bdev);
1874
1875         /*
1876          * The sd.c considers ->media_present and ->changed not equivalent,
1877          * under some pretty murky conditions (a failure of READ CAPACITY).
1878          * We may need it one day.
1879          */
1880         if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1881                 rc = -ENOMEDIUM;
1882                 goto err_open;
1883         }
1884
1885         if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1886                 rc = -EROFS;
1887                 goto err_open;
1888         }
1889
1890         return 0;
1891
1892 err_open:
1893         ub_put(sc);
1894         return rc;
1895 }
1896
1897 /*
1898  */
1899 static int ub_bd_release(struct inode *inode, struct file *filp)
1900 {
1901         struct gendisk *disk = inode->i_bdev->bd_disk;
1902         struct ub_lun *lun = disk->private_data;
1903         struct ub_dev *sc = lun->udev;
1904
1905         ub_put(sc);
1906         return 0;
1907 }
1908
1909 /*
1910  * The ioctl interface.
1911  */
1912 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1913     unsigned int cmd, unsigned long arg)
1914 {
1915         struct gendisk *disk = inode->i_bdev->bd_disk;
1916         void __user *usermem = (void __user *) arg;
1917
1918         return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1919 }
1920
1921 /*
1922  * This is called once a new disk was seen by the block layer or by ub_probe().
1923  * The main onjective here is to discover the features of the media such as
1924  * the capacity, read-only status, etc. USB storage generally does not
1925  * need to be spun up, but if we needed it, this would be the place.
1926  *
1927  * This call can sleep.
1928  *
1929  * The return code is not used.
1930  */
1931 static int ub_bd_revalidate(struct gendisk *disk)
1932 {
1933         struct ub_lun *lun = disk->private_data;
1934
1935         ub_revalidate(lun->udev, lun);
1936
1937         /* XXX Support sector size switching like in sr.c */
1938         blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1939         set_capacity(disk, lun->capacity.nsec);
1940         // set_disk_ro(sdkp->disk, lun->readonly);
1941
1942         return 0;
1943 }
1944
1945 /*
1946  * The check is called by the block layer to verify if the media
1947  * is still available. It is supposed to be harmless, lightweight and
1948  * non-intrusive in case the media was not changed.
1949  *
1950  * This call can sleep.
1951  *
1952  * The return code is bool!
1953  */
1954 static int ub_bd_media_changed(struct gendisk *disk)
1955 {
1956         struct ub_lun *lun = disk->private_data;
1957
1958         if (!lun->removable)
1959                 return 0;
1960
1961         /*
1962          * We clean checks always after every command, so this is not
1963          * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1964          * the device is actually not ready with operator or software
1965          * intervention required. One dangerous item might be a drive which
1966          * spins itself down, and come the time to write dirty pages, this
1967          * will fail, then block layer discards the data. Since we never
1968          * spin drives up, such devices simply cannot be used with ub anyway.
1969          */
1970         if (ub_sync_tur(lun->udev, lun) != 0) {
1971                 lun->changed = 1;
1972                 return 1;
1973         }
1974
1975         return lun->changed;
1976 }
1977
1978 static struct block_device_operations ub_bd_fops = {
1979         .owner          = THIS_MODULE,
1980         .open           = ub_bd_open,
1981         .release        = ub_bd_release,
1982         .ioctl          = ub_bd_ioctl,
1983         .media_changed  = ub_bd_media_changed,
1984         .revalidate_disk = ub_bd_revalidate,
1985 };
1986
1987 /*
1988  * Common ->done routine for commands executed synchronously.
1989  */
1990 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1991 {
1992         struct completion *cop = cmd->back;
1993         complete(cop);
1994 }
1995
1996 /*
1997  * Test if the device has a check condition on it, synchronously.
1998  */
1999 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
2000 {
2001         struct ub_scsi_cmd *cmd;
2002         enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
2003         unsigned long flags;
2004         struct completion compl;
2005         int rc;
2006
2007         init_completion(&compl);
2008
2009         rc = -ENOMEM;
2010         if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2011                 goto err_alloc;
2012         memset(cmd, 0, ALLOC_SIZE);
2013
2014         cmd->cdb[0] = TEST_UNIT_READY;
2015         cmd->cdb_len = 6;
2016         cmd->dir = UB_DIR_NONE;
2017         cmd->state = UB_CMDST_INIT;
2018         cmd->lun = lun;                 /* This may be NULL, but that's ok */
2019         cmd->done = ub_probe_done;
2020         cmd->back = &compl;
2021
2022         spin_lock_irqsave(sc->lock, flags);
2023         cmd->tag = sc->tagcnt++;
2024
2025         rc = ub_submit_scsi(sc, cmd);
2026         spin_unlock_irqrestore(sc->lock, flags);
2027
2028         if (rc != 0) {
2029                 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
2030                 goto err_submit;
2031         }
2032
2033         wait_for_completion(&compl);
2034
2035         rc = cmd->error;
2036
2037         if (rc == -EIO && cmd->key != 0)        /* Retries for benh's key */
2038                 rc = cmd->key;
2039
2040 err_submit:
2041         kfree(cmd);
2042 err_alloc:
2043         return rc;
2044 }
2045
2046 /*
2047  * Read the SCSI capacity synchronously (for probing).
2048  */
2049 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
2050     struct ub_capacity *ret)
2051 {
2052         struct ub_scsi_cmd *cmd;
2053         struct scatterlist *sg;
2054         char *p;
2055         enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
2056         unsigned long flags;
2057         unsigned int bsize, shift;
2058         unsigned long nsec;
2059         struct completion compl;
2060         int rc;
2061
2062         init_completion(&compl);
2063
2064         rc = -ENOMEM;
2065         if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2066                 goto err_alloc;
2067         memset(cmd, 0, ALLOC_SIZE);
2068         p = (char *)cmd + sizeof(struct ub_scsi_cmd);
2069
2070         cmd->cdb[0] = 0x25;
2071         cmd->cdb_len = 10;
2072         cmd->dir = UB_DIR_READ;
2073         cmd->state = UB_CMDST_INIT;
2074         cmd->nsg = 1;
2075         sg = &cmd->sgv[0];
2076         sg->page = virt_to_page(p);
2077         sg->offset = (unsigned long)p & (PAGE_SIZE-1);
2078         sg->length = 8;
2079         cmd->len = 8;
2080         cmd->lun = lun;
2081         cmd->done = ub_probe_done;
2082         cmd->back = &compl;
2083
2084         spin_lock_irqsave(sc->lock, flags);
2085         cmd->tag = sc->tagcnt++;
2086
2087         rc = ub_submit_scsi(sc, cmd);
2088         spin_unlock_irqrestore(sc->lock, flags);
2089
2090         if (rc != 0) {
2091                 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
2092                 goto err_submit;
2093         }
2094
2095         wait_for_completion(&compl);
2096
2097         if (cmd->error != 0) {
2098                 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
2099                 rc = -EIO;
2100                 goto err_read;
2101         }
2102         if (cmd->act_len != 8) {
2103                 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
2104                 rc = -EIO;
2105                 goto err_read;
2106         }
2107
2108         /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
2109         nsec = be32_to_cpu(*(__be32 *)p) + 1;
2110         bsize = be32_to_cpu(*(__be32 *)(p + 4));
2111         switch (bsize) {
2112         case 512:       shift = 0;      break;
2113         case 1024:      shift = 1;      break;
2114         case 2048:      shift = 2;      break;
2115         case 4096:      shift = 3;      break;
2116         default:
2117                 printk("ub: Bad sector size %u\n", bsize); /* P3 */
2118                 rc = -EDOM;
2119                 goto err_inv_bsize;
2120         }
2121
2122         ret->bsize = bsize;
2123         ret->bshift = shift;
2124         ret->nsec = nsec << shift;
2125         rc = 0;
2126
2127 err_inv_bsize:
2128 err_read:
2129 err_submit:
2130         kfree(cmd);
2131 err_alloc:
2132         return rc;
2133 }
2134
2135 /*
2136  */
2137 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
2138 {
2139         struct completion *cop = urb->context;
2140         complete(cop);
2141 }
2142
2143 static void ub_probe_timeout(unsigned long arg)
2144 {
2145         struct completion *cop = (struct completion *) arg;
2146         complete(cop);
2147 }
2148
2149 /*
2150  * Reset with a Bulk reset.
2151  */
2152 static int ub_sync_reset(struct ub_dev *sc)
2153 {
2154         int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2155         struct usb_ctrlrequest *cr;
2156         struct completion compl;
2157         struct timer_list timer;
2158         int rc;
2159
2160         init_completion(&compl);
2161
2162         cr = &sc->work_cr;
2163         cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2164         cr->bRequest = US_BULK_RESET_REQUEST;
2165         cr->wValue = cpu_to_le16(0);
2166         cr->wIndex = cpu_to_le16(ifnum);
2167         cr->wLength = cpu_to_le16(0);
2168
2169         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2170             (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2171         sc->work_urb.actual_length = 0;
2172         sc->work_urb.error_count = 0;
2173         sc->work_urb.status = 0;
2174
2175         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2176                 printk(KERN_WARNING
2177                      "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
2178                 return rc;
2179         }
2180
2181         init_timer(&timer);
2182         timer.function = ub_probe_timeout;
2183         timer.data = (unsigned long) &compl;
2184         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2185         add_timer(&timer);
2186
2187         wait_for_completion(&compl);
2188
2189         del_timer_sync(&timer);
2190         usb_kill_urb(&sc->work_urb);
2191
2192         return sc->work_urb.status;
2193 }
2194
2195 /*
2196  * Get number of LUNs by the way of Bulk GetMaxLUN command.
2197  */
2198 static int ub_sync_getmaxlun(struct ub_dev *sc)
2199 {
2200         int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2201         unsigned char *p;
2202         enum { ALLOC_SIZE = 1 };
2203         struct usb_ctrlrequest *cr;
2204         struct completion compl;
2205         struct timer_list timer;
2206         int nluns;
2207         int rc;
2208
2209         init_completion(&compl);
2210
2211         rc = -ENOMEM;
2212         if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2213                 goto err_alloc;
2214         *p = 55;
2215
2216         cr = &sc->work_cr;
2217         cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2218         cr->bRequest = US_BULK_GET_MAX_LUN;
2219         cr->wValue = cpu_to_le16(0);
2220         cr->wIndex = cpu_to_le16(ifnum);
2221         cr->wLength = cpu_to_le16(1);
2222
2223         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2224             (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2225         sc->work_urb.actual_length = 0;
2226         sc->work_urb.error_count = 0;
2227         sc->work_urb.status = 0;
2228
2229         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2230                 if (rc == -EPIPE) {
2231                         printk("%s: Stall submitting GetMaxLUN, using 1 LUN\n",
2232                              sc->name); /* P3 */
2233                 } else {
2234                         printk(KERN_NOTICE
2235                              "%s: Unable to submit GetMaxLUN (%d)\n",
2236                              sc->name, rc);
2237                 }
2238                 goto err_submit;
2239         }
2240
2241         init_timer(&timer);
2242         timer.function = ub_probe_timeout;
2243         timer.data = (unsigned long) &compl;
2244         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2245         add_timer(&timer);
2246
2247         wait_for_completion(&compl);
2248
2249         del_timer_sync(&timer);
2250         usb_kill_urb(&sc->work_urb);
2251
2252         if ((rc = sc->work_urb.status) < 0) {
2253                 if (rc == -EPIPE) {
2254                         printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
2255                              sc->name); /* P3 */
2256                 } else {
2257                         printk(KERN_NOTICE
2258                              "%s: Error at GetMaxLUN (%d)\n",
2259                              sc->name, rc);
2260                 }
2261                 goto err_io;
2262         }
2263
2264         if (sc->work_urb.actual_length != 1) {
2265                 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2266                     sc->work_urb.actual_length); /* P3 */
2267                 nluns = 0;
2268         } else {
2269                 if ((nluns = *p) == 55) {
2270                         nluns = 0;
2271                 } else {
2272                         /* GetMaxLUN returns the maximum LUN number */
2273                         nluns += 1;
2274                         if (nluns > UB_MAX_LUNS)
2275                                 nluns = UB_MAX_LUNS;
2276                 }
2277                 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2278                     *p, nluns); /* P3 */
2279         }
2280
2281         kfree(p);
2282         return nluns;
2283
2284 err_io:
2285 err_submit:
2286         kfree(p);
2287 err_alloc:
2288         return rc;
2289 }
2290
2291 /*
2292  * Clear initial stalls.
2293  */
2294 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2295 {
2296         int endp;
2297         struct usb_ctrlrequest *cr;
2298         struct completion compl;
2299         struct timer_list timer;
2300         int rc;
2301
2302         init_completion(&compl);
2303
2304         endp = usb_pipeendpoint(stalled_pipe);
2305         if (usb_pipein (stalled_pipe))
2306                 endp |= USB_DIR_IN;
2307
2308         cr = &sc->work_cr;
2309         cr->bRequestType = USB_RECIP_ENDPOINT;
2310         cr->bRequest = USB_REQ_CLEAR_FEATURE;
2311         cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2312         cr->wIndex = cpu_to_le16(endp);
2313         cr->wLength = cpu_to_le16(0);
2314
2315         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2316             (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2317         sc->work_urb.actual_length = 0;
2318         sc->work_urb.error_count = 0;
2319         sc->work_urb.status = 0;
2320
2321         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2322                 printk(KERN_WARNING
2323                      "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2324                 return rc;
2325         }
2326
2327         init_timer(&timer);
2328         timer.function = ub_probe_timeout;
2329         timer.data = (unsigned long) &compl;
2330         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2331         add_timer(&timer);
2332
2333         wait_for_completion(&compl);
2334
2335         del_timer_sync(&timer);
2336         usb_kill_urb(&sc->work_urb);
2337
2338         /* reset the endpoint toggle */
2339         usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2340
2341         return 0;
2342 }
2343
2344 /*
2345  * Get the pipe settings.
2346  */
2347 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2348     struct usb_interface *intf)
2349 {
2350         struct usb_host_interface *altsetting = intf->cur_altsetting;
2351         struct usb_endpoint_descriptor *ep_in = NULL;
2352         struct usb_endpoint_descriptor *ep_out = NULL;
2353         struct usb_endpoint_descriptor *ep;
2354         int i;
2355
2356         /*
2357          * Find the endpoints we need.
2358          * We are expecting a minimum of 2 endpoints - in and out (bulk).
2359          * We will ignore any others.
2360          */
2361         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2362                 ep = &altsetting->endpoint[i].desc;
2363
2364                 /* Is it a BULK endpoint? */
2365                 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2366                                 == USB_ENDPOINT_XFER_BULK) {
2367                         /* BULK in or out? */
2368                         if (ep->bEndpointAddress & USB_DIR_IN)
2369                                 ep_in = ep;
2370                         else
2371                                 ep_out = ep;
2372                 }
2373         }
2374
2375         if (ep_in == NULL || ep_out == NULL) {
2376                 printk(KERN_NOTICE "%s: failed endpoint check\n",
2377                     sc->name);
2378                 return -ENODEV;
2379         }
2380
2381         /* Calculate and store the pipe values */
2382         sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2383         sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2384         sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2385                 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2386         sc->recv_bulk_pipe = usb_rcvbulkpipe(dev, 
2387                 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2388
2389         return 0;
2390 }
2391
2392 /*
2393  * Probing is done in the process context, which allows us to cheat
2394  * and not to build a state machine for the discovery.
2395  */
2396 static int ub_probe(struct usb_interface *intf,
2397     const struct usb_device_id *dev_id)
2398 {
2399         struct ub_dev *sc;
2400         int nluns;
2401         int rc;
2402         int i;
2403
2404         if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2405                 return -ENXIO;
2406
2407         rc = -ENOMEM;
2408         if ((sc = kmalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2409                 goto err_core;
2410         memset(sc, 0, sizeof(struct ub_dev));
2411         sc->lock = ub_next_lock();
2412         INIT_LIST_HEAD(&sc->luns);
2413         usb_init_urb(&sc->work_urb);
2414         tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2415         atomic_set(&sc->poison, 0);
2416         INIT_WORK(&sc->reset_work, ub_reset_task, sc);
2417         init_waitqueue_head(&sc->reset_wait);
2418
2419         init_timer(&sc->work_timer);
2420         sc->work_timer.data = (unsigned long) sc;
2421         sc->work_timer.function = ub_urb_timeout;
2422
2423         ub_init_completion(&sc->work_done);
2424         sc->work_done.done = 1;         /* A little yuk, but oh well... */
2425
2426         sc->dev = interface_to_usbdev(intf);
2427         sc->intf = intf;
2428         // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2429         usb_set_intfdata(intf, sc);
2430         usb_get_dev(sc->dev);
2431         // usb_get_intf(sc->intf);      /* Do we need this? */
2432
2433         snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2434             sc->dev->bus->busnum, sc->dev->devnum);
2435
2436         /* XXX Verify that we can handle the device (from descriptors) */
2437
2438         if (ub_get_pipes(sc, sc->dev, intf) != 0)
2439                 goto err_dev_desc;
2440
2441         if (device_create_file(&sc->intf->dev, &dev_attr_diag) != 0)
2442                 goto err_diag;
2443
2444         /*
2445          * At this point, all USB initialization is done, do upper layer.
2446          * We really hate halfway initialized structures, so from the
2447          * invariants perspective, this ub_dev is fully constructed at
2448          * this point.
2449          */
2450
2451         /*
2452          * This is needed to clear toggles. It is a problem only if we do
2453          * `rmmod ub && modprobe ub` without disconnects, but we like that.
2454          */
2455 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2456         ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2457         ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2458 #endif
2459
2460         /*
2461          * The way this is used by the startup code is a little specific.
2462          * A SCSI check causes a USB stall. Our common case code sees it
2463          * and clears the check, after which the device is ready for use.
2464          * But if a check was not present, any command other than
2465          * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2466          *
2467          * If we neglect to clear the SCSI check, the first real command fails
2468          * (which is the capacity readout). We clear that and retry, but why
2469          * causing spurious retries for no reason.
2470          *
2471          * Revalidation may start with its own TEST_UNIT_READY, but that one
2472          * has to succeed, so we clear checks with an additional one here.
2473          * In any case it's not our business how revaliadation is implemented.
2474          */
2475         for (i = 0; i < 3; i++) {       /* Retries for benh's key */
2476                 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2477                 if (rc != 0x6) break;
2478                 msleep(10);
2479         }
2480
2481         nluns = 1;
2482         for (i = 0; i < 3; i++) {
2483                 if ((rc = ub_sync_getmaxlun(sc)) < 0) {
2484                         /* 
2485                          * This segment is taken from usb-storage. They say
2486                          * that ZIP-100 needs this, but my own ZIP-100 works
2487                          * fine without this.
2488                          * Still, it does not seem to hurt anything.
2489                          */
2490                         if (rc == -EPIPE) {
2491                                 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2492                                 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2493                         }
2494                         break;
2495                 }
2496                 if (rc != 0) {
2497                         nluns = rc;
2498                         break;
2499                 }
2500                 msleep(100);
2501         }
2502
2503         for (i = 0; i < nluns; i++) {
2504                 ub_probe_lun(sc, i);
2505         }
2506         return 0;
2507
2508         /* device_remove_file(&sc->intf->dev, &dev_attr_diag); */
2509 err_diag:
2510 err_dev_desc:
2511         usb_set_intfdata(intf, NULL);
2512         // usb_put_intf(sc->intf);
2513         usb_put_dev(sc->dev);
2514         kfree(sc);
2515 err_core:
2516         return rc;
2517 }
2518
2519 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2520 {
2521         struct ub_lun *lun;
2522         request_queue_t *q;
2523         struct gendisk *disk;
2524         int rc;
2525
2526         rc = -ENOMEM;
2527         if ((lun = kmalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2528                 goto err_alloc;
2529         memset(lun, 0, sizeof(struct ub_lun));
2530         lun->num = lnum;
2531
2532         rc = -ENOSR;
2533         if ((lun->id = ub_id_get()) == -1)
2534                 goto err_id;
2535
2536         lun->udev = sc;
2537         list_add(&lun->link, &sc->luns);
2538
2539         snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2540             lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2541
2542         lun->removable = 1;             /* XXX Query this from the device */
2543         lun->changed = 1;               /* ub_revalidate clears only */
2544         lun->first_open = 1;
2545         ub_revalidate(sc, lun);
2546
2547         rc = -ENOMEM;
2548         if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2549                 goto err_diskalloc;
2550
2551         lun->disk = disk;
2552         sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2553         sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2554         disk->major = UB_MAJOR;
2555         disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2556         disk->fops = &ub_bd_fops;
2557         disk->private_data = lun;
2558         disk->driverfs_dev = &sc->intf->dev;
2559
2560         rc = -ENOMEM;
2561         if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2562                 goto err_blkqinit;
2563
2564         disk->queue = q;
2565
2566         blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2567         blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2568         blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2569         blk_queue_segment_boundary(q, 0xffffffff);      /* Dubious. */
2570         blk_queue_max_sectors(q, UB_MAX_SECTORS);
2571         blk_queue_hardsect_size(q, lun->capacity.bsize);
2572
2573         q->queuedata = lun;
2574
2575         set_capacity(disk, lun->capacity.nsec);
2576         if (lun->removable)
2577                 disk->flags |= GENHD_FL_REMOVABLE;
2578
2579         add_disk(disk);
2580
2581         return 0;
2582
2583 err_blkqinit:
2584         put_disk(disk);
2585 err_diskalloc:
2586         list_del(&lun->link);
2587         ub_id_put(lun->id);
2588 err_id:
2589         kfree(lun);
2590 err_alloc:
2591         return rc;
2592 }
2593
2594 static void ub_disconnect(struct usb_interface *intf)
2595 {
2596         struct ub_dev *sc = usb_get_intfdata(intf);
2597         struct list_head *p;
2598         struct ub_lun *lun;
2599         struct gendisk *disk;
2600         unsigned long flags;
2601
2602         /*
2603          * Prevent ub_bd_release from pulling the rug from under us.
2604          * XXX This is starting to look like a kref.
2605          * XXX Why not to take this ref at probe time?
2606          */
2607         spin_lock_irqsave(&ub_lock, flags);
2608         sc->openc++;
2609         spin_unlock_irqrestore(&ub_lock, flags);
2610
2611         /*
2612          * Fence stall clearnings, operations triggered by unlinkings and so on.
2613          * We do not attempt to unlink any URBs, because we do not trust the
2614          * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2615          */
2616         atomic_set(&sc->poison, 1);
2617
2618         /*
2619          * Wait for reset to end, if any.
2620          */
2621         wait_event(sc->reset_wait, !sc->reset);
2622
2623         /*
2624          * Blow away queued commands.
2625          *
2626          * Actually, this never works, because before we get here
2627          * the HCD terminates outstanding URB(s). It causes our
2628          * SCSI command queue to advance, commands fail to submit,
2629          * and the whole queue drains. So, we just use this code to
2630          * print warnings.
2631          */
2632         spin_lock_irqsave(sc->lock, flags);
2633         {
2634                 struct ub_scsi_cmd *cmd;
2635                 int cnt = 0;
2636                 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2637                         cmd->error = -ENOTCONN;
2638                         cmd->state = UB_CMDST_DONE;
2639                         ub_cmdtr_state(sc, cmd);
2640                         ub_cmdq_pop(sc);
2641                         (*cmd->done)(sc, cmd);
2642                         cnt++;
2643                 }
2644                 if (cnt != 0) {
2645                         printk(KERN_WARNING "%s: "
2646                             "%d was queued after shutdown\n", sc->name, cnt);
2647                 }
2648         }
2649         spin_unlock_irqrestore(sc->lock, flags);
2650
2651         /*
2652          * Unregister the upper layer.
2653          */
2654         list_for_each (p, &sc->luns) {
2655                 lun = list_entry(p, struct ub_lun, link);
2656                 disk = lun->disk;
2657                 if (disk->flags & GENHD_FL_UP)
2658                         del_gendisk(disk);
2659                 /*
2660                  * I wish I could do:
2661                  *    set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2662                  * As it is, we rely on our internal poisoning and let
2663                  * the upper levels to spin furiously failing all the I/O.
2664                  */
2665         }
2666
2667         /*
2668          * Testing for -EINPROGRESS is always a bug, so we are bending
2669          * the rules a little.
2670          */
2671         spin_lock_irqsave(sc->lock, flags);
2672         if (sc->work_urb.status == -EINPROGRESS) {      /* janitors: ignore */
2673                 printk(KERN_WARNING "%s: "
2674                     "URB is active after disconnect\n", sc->name);
2675         }
2676         spin_unlock_irqrestore(sc->lock, flags);
2677
2678         /*
2679          * There is virtually no chance that other CPU runs times so long
2680          * after ub_urb_complete should have called del_timer, but only if HCD
2681          * didn't forget to deliver a callback on unlink.
2682          */
2683         del_timer_sync(&sc->work_timer);
2684
2685         /*
2686          * At this point there must be no commands coming from anyone
2687          * and no URBs left in transit.
2688          */
2689
2690         device_remove_file(&sc->intf->dev, &dev_attr_diag);
2691         usb_set_intfdata(intf, NULL);
2692         // usb_put_intf(sc->intf);
2693         sc->intf = NULL;
2694         usb_put_dev(sc->dev);
2695         sc->dev = NULL;
2696
2697         ub_put(sc);
2698 }
2699
2700 static struct usb_driver ub_driver = {
2701         .name =         "ub",
2702         .probe =        ub_probe,
2703         .disconnect =   ub_disconnect,
2704         .id_table =     ub_usb_ids,
2705 };
2706
2707 static int __init ub_init(void)
2708 {
2709         int rc;
2710         int i;
2711
2712         for (i = 0; i < UB_QLOCK_NUM; i++)
2713                 spin_lock_init(&ub_qlockv[i]);
2714
2715         if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2716                 goto err_regblkdev;
2717         devfs_mk_dir(DEVFS_NAME);
2718
2719         if ((rc = usb_register(&ub_driver)) != 0)
2720                 goto err_register;
2721
2722         usb_usual_set_present(USB_US_TYPE_UB);
2723         return 0;
2724
2725 err_register:
2726         devfs_remove(DEVFS_NAME);
2727         unregister_blkdev(UB_MAJOR, DRV_NAME);
2728 err_regblkdev:
2729         return rc;
2730 }
2731
2732 static void __exit ub_exit(void)
2733 {
2734         usb_deregister(&ub_driver);
2735
2736         devfs_remove(DEVFS_NAME);
2737         unregister_blkdev(UB_MAJOR, DRV_NAME);
2738         usb_usual_clear_present(USB_US_TYPE_UB);
2739 }
2740
2741 module_init(ub_init);
2742 module_exit(ub_exit);
2743
2744 MODULE_LICENSE("GPL");