linux 2.6.16.38 w/ vs2.0.3-rc1
[linux-2.6.git] / 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         usb_set_intfdata(sc->intf, NULL);
708         usb_put_intf(sc->intf);
709         usb_put_dev(sc->dev);
710         kfree(sc);
711 }
712
713 /*
714  * The "command allocator".
715  */
716 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
717 {
718         struct ub_scsi_cmd *ret;
719
720         if (lun->cmda[0])
721                 return NULL;
722         ret = &lun->cmdv[0];
723         lun->cmda[0] = 1;
724         return ret;
725 }
726
727 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
728 {
729         if (cmd != &lun->cmdv[0]) {
730                 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
731                     lun->name, cmd);
732                 return;
733         }
734         if (!lun->cmda[0]) {
735                 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
736                 return;
737         }
738         lun->cmda[0] = 0;
739 }
740
741 /*
742  * The command queue.
743  */
744 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
745 {
746         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
747
748         if (t->qlen++ == 0) {
749                 t->head = cmd;
750                 t->tail = cmd;
751         } else {
752                 t->tail->next = cmd;
753                 t->tail = cmd;
754         }
755
756         if (t->qlen > t->qmax)
757                 t->qmax = t->qlen;
758 }
759
760 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
761 {
762         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
763
764         if (t->qlen++ == 0) {
765                 t->head = cmd;
766                 t->tail = cmd;
767         } else {
768                 cmd->next = t->head;
769                 t->head = cmd;
770         }
771
772         if (t->qlen > t->qmax)
773                 t->qmax = t->qlen;
774 }
775
776 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
777 {
778         struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
779         struct ub_scsi_cmd *cmd;
780
781         if (t->qlen == 0)
782                 return NULL;
783         if (--t->qlen == 0)
784                 t->tail = NULL;
785         cmd = t->head;
786         t->head = cmd->next;
787         cmd->next = NULL;
788         return cmd;
789 }
790
791 #define ub_cmdq_peek(sc)  ((sc)->cmd_queue.head)
792
793 /*
794  * The request function is our main entry point
795  */
796
797 static void ub_request_fn(request_queue_t *q)
798 {
799         struct ub_lun *lun = q->queuedata;
800         struct request *rq;
801
802         while ((rq = elv_next_request(q)) != NULL) {
803                 if (ub_request_fn_1(lun, rq) != 0) {
804                         blk_stop_queue(q);
805                         break;
806                 }
807         }
808 }
809
810 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
811 {
812         struct ub_dev *sc = lun->udev;
813         struct ub_scsi_cmd *cmd;
814         struct ub_request *urq;
815         int n_elem;
816
817         if (atomic_read(&sc->poison) || lun->changed) {
818                 blkdev_dequeue_request(rq);
819                 ub_end_rq(rq, 0);
820                 return 0;
821         }
822
823         if (lun->urq.rq != NULL)
824                 return -1;
825         if ((cmd = ub_get_cmd(lun)) == NULL)
826                 return -1;
827         memset(cmd, 0, sizeof(struct ub_scsi_cmd));
828
829         blkdev_dequeue_request(rq);
830
831         urq = &lun->urq;
832         memset(urq, 0, sizeof(struct ub_request));
833         urq->rq = rq;
834
835         /*
836          * get scatterlist from block layer
837          */
838         n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
839         if (n_elem < 0) {
840                 printk(KERN_INFO "%s: failed request map (%d)\n",
841                     lun->name, n_elem); /* P3 */
842                 goto drop;
843         }
844         if (n_elem > UB_MAX_REQ_SG) {   /* Paranoia */
845                 printk(KERN_WARNING "%s: request with %d segments\n",
846                     lun->name, n_elem);
847                 goto drop;
848         }
849         urq->nsg = n_elem;
850         sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
851
852         if (blk_pc_request(rq)) {
853                 ub_cmd_build_packet(sc, lun, cmd, urq);
854         } else {
855                 ub_cmd_build_block(sc, lun, cmd, urq);
856         }
857         cmd->state = UB_CMDST_INIT;
858         cmd->lun = lun;
859         cmd->done = ub_rw_cmd_done;
860         cmd->back = urq;
861
862         cmd->tag = sc->tagcnt++;
863         if (ub_submit_scsi(sc, cmd) != 0)
864                 goto drop;
865
866         return 0;
867
868 drop:
869         ub_put_cmd(lun, cmd);
870         ub_end_rq(rq, 0);
871         return 0;
872 }
873
874 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
875     struct ub_scsi_cmd *cmd, struct ub_request *urq)
876 {
877         struct request *rq = urq->rq;
878         unsigned int block, nblks;
879
880         if (rq_data_dir(rq) == WRITE)
881                 cmd->dir = UB_DIR_WRITE;
882         else
883                 cmd->dir = UB_DIR_READ;
884
885         cmd->nsg = urq->nsg;
886         memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
887
888         /*
889          * build the command
890          *
891          * The call to blk_queue_hardsect_size() guarantees that request
892          * is aligned, but it is given in terms of 512 byte units, always.
893          */
894         block = rq->sector >> lun->capacity.bshift;
895         nblks = rq->nr_sectors >> lun->capacity.bshift;
896
897         cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
898         /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
899         cmd->cdb[2] = block >> 24;
900         cmd->cdb[3] = block >> 16;
901         cmd->cdb[4] = block >> 8;
902         cmd->cdb[5] = block;
903         cmd->cdb[7] = nblks >> 8;
904         cmd->cdb[8] = nblks;
905         cmd->cdb_len = 10;
906
907         cmd->len = rq->nr_sectors * 512;
908 }
909
910 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
911     struct ub_scsi_cmd *cmd, struct ub_request *urq)
912 {
913         struct request *rq = urq->rq;
914
915         if (rq->data_len == 0) {
916                 cmd->dir = UB_DIR_NONE;
917         } else {
918                 if (rq_data_dir(rq) == WRITE)
919                         cmd->dir = UB_DIR_WRITE;
920                 else
921                         cmd->dir = UB_DIR_READ;
922         }
923
924         cmd->nsg = urq->nsg;
925         memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
926
927         memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
928         cmd->cdb_len = rq->cmd_len;
929
930         cmd->len = rq->data_len;
931 }
932
933 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
934 {
935         struct ub_lun *lun = cmd->lun;
936         struct ub_request *urq = cmd->back;
937         struct request *rq;
938         int uptodate;
939
940         rq = urq->rq;
941
942         if (cmd->error == 0) {
943                 uptodate = 1;
944
945                 if (blk_pc_request(rq)) {
946                         if (cmd->act_len >= rq->data_len)
947                                 rq->data_len = 0;
948                         else
949                                 rq->data_len -= cmd->act_len;
950                 }
951         } else {
952                 uptodate = 0;
953
954                 if (blk_pc_request(rq)) {
955                         /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
956                         memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
957                         rq->sense_len = UB_SENSE_SIZE;
958                         if (sc->top_sense[0] != 0)
959                                 rq->errors = SAM_STAT_CHECK_CONDITION;
960                         else
961                                 rq->errors = DID_ERROR << 16;
962                 } else {
963                         if (cmd->error == -EIO) {
964                                 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
965                                         return;
966                         }
967                 }
968         }
969
970         urq->rq = NULL;
971
972         ub_put_cmd(lun, cmd);
973         ub_end_rq(rq, uptodate);
974         blk_start_queue(lun->disk->queue);
975 }
976
977 static void ub_end_rq(struct request *rq, int uptodate)
978 {
979         end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
980         end_that_request_last(rq, uptodate);
981 }
982
983 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
984     struct ub_request *urq, struct ub_scsi_cmd *cmd)
985 {
986
987         if (atomic_read(&sc->poison))
988                 return -ENXIO;
989
990         ub_reset_enter(sc, urq->current_try);
991
992         if (urq->current_try >= 3)
993                 return -EIO;
994         urq->current_try++;
995         /* P3 */ printk("%s: dir %c len/act %d/%d "
996             "[sense %x %02x %02x] retry %d\n",
997             sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
998             cmd->key, cmd->asc, cmd->ascq, urq->current_try);
999
1000         memset(cmd, 0, sizeof(struct ub_scsi_cmd));
1001         ub_cmd_build_block(sc, lun, cmd, urq);
1002
1003         cmd->state = UB_CMDST_INIT;
1004         cmd->lun = lun;
1005         cmd->done = ub_rw_cmd_done;
1006         cmd->back = urq;
1007
1008         cmd->tag = sc->tagcnt++;
1009
1010 #if 0 /* Wasteful */
1011         return ub_submit_scsi(sc, cmd);
1012 #else
1013         ub_cmdq_add(sc, cmd);
1014         return 0;
1015 #endif
1016 }
1017
1018 /*
1019  * Submit a regular SCSI operation (not an auto-sense).
1020  *
1021  * The Iron Law of Good Submit Routine is:
1022  * Zero return - callback is done, Nonzero return - callback is not done.
1023  * No exceptions.
1024  *
1025  * Host is assumed locked.
1026  */
1027 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1028 {
1029
1030         if (cmd->state != UB_CMDST_INIT ||
1031             (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
1032                 return -EINVAL;
1033         }
1034
1035         ub_cmdq_add(sc, cmd);
1036         /*
1037          * We can call ub_scsi_dispatch(sc) right away here, but it's a little
1038          * safer to jump to a tasklet, in case upper layers do something silly.
1039          */
1040         tasklet_schedule(&sc->tasklet);
1041         return 0;
1042 }
1043
1044 /*
1045  * Submit the first URB for the queued command.
1046  * This function does not deal with queueing in any way.
1047  */
1048 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1049 {
1050         struct bulk_cb_wrap *bcb;
1051         int rc;
1052
1053         bcb = &sc->work_bcb;
1054
1055         /*
1056          * ``If the allocation length is eighteen or greater, and a device
1057          * server returns less than eithteen bytes of data, the application
1058          * client should assume that the bytes not transferred would have been
1059          * zeroes had the device server returned those bytes.''
1060          *
1061          * We zero sense for all commands so that when a packet request
1062          * fails it does not return a stale sense.
1063          */
1064         memset(&sc->top_sense, 0, UB_SENSE_SIZE);
1065
1066         /* set up the command wrapper */
1067         bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
1068         bcb->Tag = cmd->tag;            /* Endianness is not important */
1069         bcb->DataTransferLength = cpu_to_le32(cmd->len);
1070         bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
1071         bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
1072         bcb->Length = cmd->cdb_len;
1073
1074         /* copy the command payload */
1075         memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
1076
1077         UB_INIT_COMPLETION(sc->work_done);
1078
1079         sc->last_pipe = sc->send_bulk_pipe;
1080         usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
1081             bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
1082
1083         /* Fill what we shouldn't be filling, because usb-storage did so. */
1084         sc->work_urb.actual_length = 0;
1085         sc->work_urb.error_count = 0;
1086         sc->work_urb.status = 0;
1087
1088         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1089                 /* XXX Clear stalls */
1090                 ub_complete(&sc->work_done);
1091                 return rc;
1092         }
1093
1094         sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
1095         add_timer(&sc->work_timer);
1096
1097         cmd->state = UB_CMDST_CMD;
1098         ub_cmdtr_state(sc, cmd);
1099         return 0;
1100 }
1101
1102 /*
1103  * Timeout handler.
1104  */
1105 static void ub_urb_timeout(unsigned long arg)
1106 {
1107         struct ub_dev *sc = (struct ub_dev *) arg;
1108         unsigned long flags;
1109
1110         spin_lock_irqsave(sc->lock, flags);
1111         if (!ub_is_completed(&sc->work_done))
1112                 usb_unlink_urb(&sc->work_urb);
1113         spin_unlock_irqrestore(sc->lock, flags);
1114 }
1115
1116 /*
1117  * Completion routine for the work URB.
1118  *
1119  * This can be called directly from usb_submit_urb (while we have
1120  * the sc->lock taken) and from an interrupt (while we do NOT have
1121  * the sc->lock taken). Therefore, bounce this off to a tasklet.
1122  */
1123 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
1124 {
1125         struct ub_dev *sc = urb->context;
1126
1127         ub_complete(&sc->work_done);
1128         tasklet_schedule(&sc->tasklet);
1129 }
1130
1131 static void ub_scsi_action(unsigned long _dev)
1132 {
1133         struct ub_dev *sc = (struct ub_dev *) _dev;
1134         unsigned long flags;
1135
1136         spin_lock_irqsave(sc->lock, flags);
1137         ub_scsi_dispatch(sc);
1138         spin_unlock_irqrestore(sc->lock, flags);
1139 }
1140
1141 static void ub_scsi_dispatch(struct ub_dev *sc)
1142 {
1143         struct ub_scsi_cmd *cmd;
1144         int rc;
1145
1146         while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
1147                 if (cmd->state == UB_CMDST_DONE) {
1148                         ub_cmdq_pop(sc);
1149                         (*cmd->done)(sc, cmd);
1150                 } else if (cmd->state == UB_CMDST_INIT) {
1151                         ub_cmdtr_new(sc, cmd);
1152                         if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
1153                                 break;
1154                         cmd->error = rc;
1155                         cmd->state = UB_CMDST_DONE;
1156                         ub_cmdtr_state(sc, cmd);
1157                 } else {
1158                         if (!ub_is_completed(&sc->work_done))
1159                                 break;
1160                         del_timer(&sc->work_timer);
1161                         ub_scsi_urb_compl(sc, cmd);
1162                 }
1163         }
1164 }
1165
1166 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1167 {
1168         struct urb *urb = &sc->work_urb;
1169         struct bulk_cs_wrap *bcs;
1170         int len;
1171         int rc;
1172
1173         if (atomic_read(&sc->poison)) {
1174                 ub_state_done(sc, cmd, -ENODEV);
1175                 return;
1176         }
1177
1178         if (cmd->state == UB_CMDST_CLEAR) {
1179                 if (urb->status == -EPIPE) {
1180                         /*
1181                          * STALL while clearning STALL.
1182                          * The control pipe clears itself - nothing to do.
1183                          */
1184                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1185                             sc->name);
1186                         goto Bad_End;
1187                 }
1188
1189                 /*
1190                  * We ignore the result for the halt clear.
1191                  */
1192
1193                 /* reset the endpoint toggle */
1194                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1195                         usb_pipeout(sc->last_pipe), 0);
1196
1197                 ub_state_sense(sc, cmd);
1198
1199         } else if (cmd->state == UB_CMDST_CLR2STS) {
1200                 if (urb->status == -EPIPE) {
1201                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1202                             sc->name);
1203                         goto Bad_End;
1204                 }
1205
1206                 /*
1207                  * We ignore the result for the halt clear.
1208                  */
1209
1210                 /* reset the endpoint toggle */
1211                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1212                         usb_pipeout(sc->last_pipe), 0);
1213
1214                 ub_state_stat(sc, cmd);
1215
1216         } else if (cmd->state == UB_CMDST_CLRRS) {
1217                 if (urb->status == -EPIPE) {
1218                         printk(KERN_NOTICE "%s: stall on control pipe\n",
1219                             sc->name);
1220                         goto Bad_End;
1221                 }
1222
1223                 /*
1224                  * We ignore the result for the halt clear.
1225                  */
1226
1227                 /* reset the endpoint toggle */
1228                 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1229                         usb_pipeout(sc->last_pipe), 0);
1230
1231                 ub_state_stat_counted(sc, cmd);
1232
1233         } else if (cmd->state == UB_CMDST_CMD) {
1234                 switch (urb->status) {
1235                 case 0:
1236                         break;
1237                 case -EOVERFLOW:
1238                         goto Bad_End;
1239                 case -EPIPE:
1240                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1241                         if (rc != 0) {
1242                                 printk(KERN_NOTICE "%s: "
1243                                     "unable to submit clear (%d)\n",
1244                                     sc->name, rc);
1245                                 /*
1246                                  * This is typically ENOMEM or some other such shit.
1247                                  * Retrying is pointless. Just do Bad End on it...
1248                                  */
1249                                 ub_state_done(sc, cmd, rc);
1250                                 return;
1251                         }
1252                         cmd->state = UB_CMDST_CLEAR;
1253                         ub_cmdtr_state(sc, cmd);
1254                         return;
1255                 case -ESHUTDOWN:        /* unplug */
1256                 case -EILSEQ:           /* unplug timeout on uhci */
1257                         ub_state_done(sc, cmd, -ENODEV);
1258                         return;
1259                 default:
1260                         goto Bad_End;
1261                 }
1262                 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1263                         goto Bad_End;
1264                 }
1265
1266                 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1267                         ub_state_stat(sc, cmd);
1268                         return;
1269                 }
1270
1271                 // udelay(125);         // usb-storage has this
1272                 ub_data_start(sc, cmd);
1273
1274         } else if (cmd->state == UB_CMDST_DATA) {
1275                 if (urb->status == -EPIPE) {
1276                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1277                         if (rc != 0) {
1278                                 printk(KERN_NOTICE "%s: "
1279                                     "unable to submit clear (%d)\n",
1280                                     sc->name, rc);
1281                                 ub_state_done(sc, cmd, rc);
1282                                 return;
1283                         }
1284                         cmd->state = UB_CMDST_CLR2STS;
1285                         ub_cmdtr_state(sc, cmd);
1286                         return;
1287                 }
1288                 if (urb->status == -EOVERFLOW) {
1289                         /*
1290                          * A babble? Failure, but we must transfer CSW now.
1291                          */
1292                         cmd->error = -EOVERFLOW;        /* A cheap trick... */
1293                         ub_state_stat(sc, cmd);
1294                         return;
1295                 }
1296
1297                 if (cmd->dir == UB_DIR_WRITE) {
1298                         /*
1299                          * Do not continue writes in case of a failure.
1300                          * Doing so would cause sectors to be mixed up,
1301                          * which is worse than sectors lost.
1302                          *
1303                          * We must try to read the CSW, or many devices
1304                          * get confused.
1305                          */
1306                         len = urb->actual_length;
1307                         if (urb->status != 0 ||
1308                             len != cmd->sgv[cmd->current_sg].length) {
1309                                 cmd->act_len += len;
1310                                 ub_cmdtr_act_len(sc, cmd);
1311
1312                                 cmd->error = -EIO;
1313                                 ub_state_stat(sc, cmd);
1314                                 return;
1315                         }
1316
1317                 } else {
1318                         /*
1319                          * If an error occurs on read, we record it, and
1320                          * continue to fetch data in order to avoid bubble.
1321                          *
1322                          * As a small shortcut, we stop if we detect that
1323                          * a CSW mixed into data.
1324                          */
1325                         if (urb->status != 0)
1326                                 cmd->error = -EIO;
1327
1328                         len = urb->actual_length;
1329                         if (urb->status != 0 ||
1330                             len != cmd->sgv[cmd->current_sg].length) {
1331                                 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1332                                         goto Bad_End;
1333                         }
1334                 }
1335
1336                 cmd->act_len += urb->actual_length;
1337                 ub_cmdtr_act_len(sc, cmd);
1338
1339                 if (++cmd->current_sg < cmd->nsg) {
1340                         ub_data_start(sc, cmd);
1341                         return;
1342                 }
1343                 ub_state_stat(sc, cmd);
1344
1345         } else if (cmd->state == UB_CMDST_STAT) {
1346                 if (urb->status == -EPIPE) {
1347                         rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1348                         if (rc != 0) {
1349                                 printk(KERN_NOTICE "%s: "
1350                                     "unable to submit clear (%d)\n",
1351                                     sc->name, rc);
1352                                 ub_state_done(sc, cmd, rc);
1353                                 return;
1354                         }
1355
1356                         /*
1357                          * Having a stall when getting CSW is an error, so
1358                          * make sure uppper levels are not oblivious to it.
1359                          */
1360                         cmd->error = -EIO;              /* A cheap trick... */
1361
1362                         cmd->state = UB_CMDST_CLRRS;
1363                         ub_cmdtr_state(sc, cmd);
1364                         return;
1365                 }
1366
1367                 /* Catch everything, including -EOVERFLOW and other nasties. */
1368                 if (urb->status != 0)
1369                         goto Bad_End;
1370
1371                 if (urb->actual_length == 0) {
1372                         ub_state_stat_counted(sc, cmd);
1373                         return;
1374                 }
1375
1376                 /*
1377                  * Check the returned Bulk protocol status.
1378                  * The status block has to be validated first.
1379                  */
1380
1381                 bcs = &sc->work_bcs;
1382
1383                 if (sc->signature == cpu_to_le32(0)) {
1384                         /*
1385                          * This is the first reply, so do not perform the check.
1386                          * Instead, remember the signature the device uses
1387                          * for future checks. But do not allow a nul.
1388                          */
1389                         sc->signature = bcs->Signature;
1390                         if (sc->signature == cpu_to_le32(0)) {
1391                                 ub_state_stat_counted(sc, cmd);
1392                                 return;
1393                         }
1394                 } else {
1395                         if (bcs->Signature != sc->signature) {
1396                                 ub_state_stat_counted(sc, cmd);
1397                                 return;
1398                         }
1399                 }
1400
1401                 if (bcs->Tag != cmd->tag) {
1402                         /*
1403                          * This usually happens when we disagree with the
1404                          * device's microcode about something. For instance,
1405                          * a few of them throw this after timeouts. They buffer
1406                          * commands and reply at commands we timed out before.
1407                          * Without flushing these replies we loop forever.
1408                          */
1409                         ub_state_stat_counted(sc, cmd);
1410                         return;
1411                 }
1412
1413                 len = le32_to_cpu(bcs->Residue);
1414                 if (len != cmd->len - cmd->act_len) {
1415                         /*
1416                          * It is all right to transfer less, the caller has
1417                          * to check. But it's not all right if the device
1418                          * counts disagree with our counts.
1419                          */
1420                         /* P3 */ printk("%s: resid %d len %d act %d\n",
1421                             sc->name, len, cmd->len, cmd->act_len);
1422                         goto Bad_End;
1423                 }
1424
1425                 switch (bcs->Status) {
1426                 case US_BULK_STAT_OK:
1427                         break;
1428                 case US_BULK_STAT_FAIL:
1429                         ub_state_sense(sc, cmd);
1430                         return;
1431                 case US_BULK_STAT_PHASE:
1432                         /* P3 */ printk("%s: status PHASE\n", sc->name);
1433                         goto Bad_End;
1434                 default:
1435                         printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1436                             sc->name, bcs->Status);
1437                         ub_state_done(sc, cmd, -EINVAL);
1438                         return;
1439                 }
1440
1441                 /* Not zeroing error to preserve a babble indicator */
1442                 if (cmd->error != 0) {
1443                         ub_state_sense(sc, cmd);
1444                         return;
1445                 }
1446                 cmd->state = UB_CMDST_DONE;
1447                 ub_cmdtr_state(sc, cmd);
1448                 ub_cmdq_pop(sc);
1449                 (*cmd->done)(sc, cmd);
1450
1451         } else if (cmd->state == UB_CMDST_SENSE) {
1452                 ub_state_done(sc, cmd, -EIO);
1453
1454         } else {
1455                 printk(KERN_WARNING "%s: "
1456                     "wrong command state %d\n",
1457                     sc->name, cmd->state);
1458                 ub_state_done(sc, cmd, -EINVAL);
1459                 return;
1460         }
1461         return;
1462
1463 Bad_End: /* Little Excel is dead */
1464         ub_state_done(sc, cmd, -EIO);
1465 }
1466
1467 /*
1468  * Factorization helper for the command state machine:
1469  * Initiate a data segment transfer.
1470  */
1471 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1472 {
1473         struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1474         int pipe;
1475         int rc;
1476
1477         UB_INIT_COMPLETION(sc->work_done);
1478
1479         if (cmd->dir == UB_DIR_READ)
1480                 pipe = sc->recv_bulk_pipe;
1481         else
1482                 pipe = sc->send_bulk_pipe;
1483         sc->last_pipe = pipe;
1484         usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1485             page_address(sg->page) + sg->offset, sg->length,
1486             ub_urb_complete, sc);
1487         sc->work_urb.actual_length = 0;
1488         sc->work_urb.error_count = 0;
1489         sc->work_urb.status = 0;
1490
1491         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1492                 /* XXX Clear stalls */
1493                 ub_complete(&sc->work_done);
1494                 ub_state_done(sc, cmd, rc);
1495                 return;
1496         }
1497
1498         sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1499         add_timer(&sc->work_timer);
1500
1501         cmd->state = UB_CMDST_DATA;
1502         ub_cmdtr_state(sc, cmd);
1503 }
1504
1505 /*
1506  * Factorization helper for the command state machine:
1507  * Finish the command.
1508  */
1509 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1510 {
1511
1512         cmd->error = rc;
1513         cmd->state = UB_CMDST_DONE;
1514         ub_cmdtr_state(sc, cmd);
1515         ub_cmdq_pop(sc);
1516         (*cmd->done)(sc, cmd);
1517 }
1518
1519 /*
1520  * Factorization helper for the command state machine:
1521  * Submit a CSW read.
1522  */
1523 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1524 {
1525         int rc;
1526
1527         UB_INIT_COMPLETION(sc->work_done);
1528
1529         sc->last_pipe = sc->recv_bulk_pipe;
1530         usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1531             &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1532         sc->work_urb.actual_length = 0;
1533         sc->work_urb.error_count = 0;
1534         sc->work_urb.status = 0;
1535
1536         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1537                 /* XXX Clear stalls */
1538                 ub_complete(&sc->work_done);
1539                 ub_state_done(sc, cmd, rc);
1540                 return -1;
1541         }
1542
1543         sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1544         add_timer(&sc->work_timer);
1545         return 0;
1546 }
1547
1548 /*
1549  * Factorization helper for the command state machine:
1550  * Submit a CSW read and go to STAT state.
1551  */
1552 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1553 {
1554
1555         if (__ub_state_stat(sc, cmd) != 0)
1556                 return;
1557
1558         cmd->stat_count = 0;
1559         cmd->state = UB_CMDST_STAT;
1560         ub_cmdtr_state(sc, cmd);
1561 }
1562
1563 /*
1564  * Factorization helper for the command state machine:
1565  * Submit a CSW read and go to STAT state with counter (along [C] path).
1566  */
1567 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1568 {
1569
1570         if (++cmd->stat_count >= 4) {
1571                 ub_state_sense(sc, cmd);
1572                 return;
1573         }
1574
1575         if (__ub_state_stat(sc, cmd) != 0)
1576                 return;
1577
1578         cmd->state = UB_CMDST_STAT;
1579         ub_cmdtr_state(sc, cmd);
1580 }
1581
1582 /*
1583  * Factorization helper for the command state machine:
1584  * Submit a REQUEST SENSE and go to SENSE state.
1585  */
1586 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1587 {
1588         struct ub_scsi_cmd *scmd;
1589         struct scatterlist *sg;
1590         int rc;
1591
1592         if (cmd->cdb[0] == REQUEST_SENSE) {
1593                 rc = -EPIPE;
1594                 goto error;
1595         }
1596
1597         scmd = &sc->top_rqs_cmd;
1598         memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1599         scmd->cdb[0] = REQUEST_SENSE;
1600         scmd->cdb[4] = UB_SENSE_SIZE;
1601         scmd->cdb_len = 6;
1602         scmd->dir = UB_DIR_READ;
1603         scmd->state = UB_CMDST_INIT;
1604         scmd->nsg = 1;
1605         sg = &scmd->sgv[0];
1606         sg->page = virt_to_page(sc->top_sense);
1607         sg->offset = (unsigned long)sc->top_sense & (PAGE_SIZE-1);
1608         sg->length = UB_SENSE_SIZE;
1609         scmd->len = UB_SENSE_SIZE;
1610         scmd->lun = cmd->lun;
1611         scmd->done = ub_top_sense_done;
1612         scmd->back = cmd;
1613
1614         scmd->tag = sc->tagcnt++;
1615
1616         cmd->state = UB_CMDST_SENSE;
1617         ub_cmdtr_state(sc, cmd);
1618
1619         ub_cmdq_insert(sc, scmd);
1620         return;
1621
1622 error:
1623         ub_state_done(sc, cmd, rc);
1624 }
1625
1626 /*
1627  * A helper for the command's state machine:
1628  * Submit a stall clear.
1629  */
1630 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1631     int stalled_pipe)
1632 {
1633         int endp;
1634         struct usb_ctrlrequest *cr;
1635         int rc;
1636
1637         endp = usb_pipeendpoint(stalled_pipe);
1638         if (usb_pipein (stalled_pipe))
1639                 endp |= USB_DIR_IN;
1640
1641         cr = &sc->work_cr;
1642         cr->bRequestType = USB_RECIP_ENDPOINT;
1643         cr->bRequest = USB_REQ_CLEAR_FEATURE;
1644         cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1645         cr->wIndex = cpu_to_le16(endp);
1646         cr->wLength = cpu_to_le16(0);
1647
1648         UB_INIT_COMPLETION(sc->work_done);
1649
1650         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1651             (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1652         sc->work_urb.actual_length = 0;
1653         sc->work_urb.error_count = 0;
1654         sc->work_urb.status = 0;
1655
1656         if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1657                 ub_complete(&sc->work_done);
1658                 return rc;
1659         }
1660
1661         sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1662         add_timer(&sc->work_timer);
1663         return 0;
1664 }
1665
1666 /*
1667  */
1668 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1669 {
1670         unsigned char *sense = sc->top_sense;
1671         struct ub_scsi_cmd *cmd;
1672
1673         /*
1674          * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1675          */
1676         ub_cmdtr_sense(sc, scmd, sense);
1677
1678         /*
1679          * Find the command which triggered the unit attention or a check,
1680          * save the sense into it, and advance its state machine.
1681          */
1682         if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1683                 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1684                 return;
1685         }
1686         if (cmd != scmd->back) {
1687                 printk(KERN_WARNING "%s: "
1688                     "sense done for wrong command 0x%x\n",
1689                     sc->name, cmd->tag);
1690                 return;
1691         }
1692         if (cmd->state != UB_CMDST_SENSE) {
1693                 printk(KERN_WARNING "%s: "
1694                     "sense done with bad cmd state %d\n",
1695                     sc->name, cmd->state);
1696                 return;
1697         }
1698
1699         cmd->key = sense[2] & 0x0F;
1700         cmd->asc = sense[12];
1701         cmd->ascq = sense[13];
1702
1703         ub_scsi_urb_compl(sc, cmd);
1704 }
1705
1706 /*
1707  * Reset management
1708  * XXX Move usb_reset_device to khubd. Hogging kevent is not a good thing.
1709  * XXX Make usb_sync_reset asynchronous.
1710  */
1711
1712 static void ub_reset_enter(struct ub_dev *sc, int try)
1713 {
1714
1715         if (sc->reset) {
1716                 /* This happens often on multi-LUN devices. */
1717                 return;
1718         }
1719         sc->reset = try + 1;
1720
1721 #if 0 /* Not needed because the disconnect waits for us. */
1722         unsigned long flags;
1723         spin_lock_irqsave(&ub_lock, flags);
1724         sc->openc++;
1725         spin_unlock_irqrestore(&ub_lock, flags);
1726 #endif
1727
1728 #if 0 /* We let them stop themselves. */
1729         struct list_head *p;
1730         struct ub_lun *lun;
1731         list_for_each(p, &sc->luns) {
1732                 lun = list_entry(p, struct ub_lun, link);
1733                 blk_stop_queue(lun->disk->queue);
1734         }
1735 #endif
1736
1737         schedule_work(&sc->reset_work);
1738 }
1739
1740 static void ub_reset_task(void *arg)
1741 {
1742         struct ub_dev *sc = arg;
1743         unsigned long flags;
1744         struct list_head *p;
1745         struct ub_lun *lun;
1746         int lkr, rc;
1747
1748         if (!sc->reset) {
1749                 printk(KERN_WARNING "%s: Running reset unrequested\n",
1750                     sc->name);
1751                 return;
1752         }
1753
1754         if (atomic_read(&sc->poison)) {
1755                 printk(KERN_NOTICE "%s: Not resetting disconnected device\n",
1756                     sc->name); /* P3 This floods. Remove soon. XXX */
1757         } else if ((sc->reset & 1) == 0) {
1758                 ub_sync_reset(sc);
1759                 msleep(700);    /* usb-storage sleeps 6s (!) */
1760                 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1761                 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1762         } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1763                 printk(KERN_NOTICE "%s: Not resetting multi-interface device\n",
1764                     sc->name); /* P3 This floods. Remove soon. XXX */
1765         } else {
1766                 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1767                         printk(KERN_NOTICE
1768                             "%s: usb_lock_device_for_reset failed (%d)\n",
1769                             sc->name, lkr);
1770                 } else {
1771                         rc = usb_reset_device(sc->dev);
1772                         if (rc < 0) {
1773                                 printk(KERN_NOTICE "%s: "
1774                                     "usb_lock_device_for_reset failed (%d)\n",
1775                                     sc->name, rc);
1776                         }
1777
1778                         if (lkr)
1779                                 usb_unlock_device(sc->dev);
1780                 }
1781         }
1782
1783         /*
1784          * In theory, no commands can be running while reset is active,
1785          * so nobody can ask for another reset, and so we do not need any
1786          * queues of resets or anything. We do need a spinlock though,
1787          * to interact with block layer.
1788          */
1789         spin_lock_irqsave(sc->lock, flags);
1790         sc->reset = 0;
1791         tasklet_schedule(&sc->tasklet);
1792         list_for_each(p, &sc->luns) {
1793                 lun = list_entry(p, struct ub_lun, link);
1794                 blk_start_queue(lun->disk->queue);
1795         }
1796         wake_up(&sc->reset_wait);
1797         spin_unlock_irqrestore(sc->lock, flags);
1798 }
1799
1800 /*
1801  * This is called from a process context.
1802  */
1803 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1804 {
1805
1806         lun->readonly = 0;      /* XXX Query this from the device */
1807
1808         lun->capacity.nsec = 0;
1809         lun->capacity.bsize = 512;
1810         lun->capacity.bshift = 0;
1811
1812         if (ub_sync_tur(sc, lun) != 0)
1813                 return;                 /* Not ready */
1814         lun->changed = 0;
1815
1816         if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1817                 /*
1818                  * The retry here means something is wrong, either with the
1819                  * device, with the transport, or with our code.
1820                  * We keep this because sd.c has retries for capacity.
1821                  */
1822                 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1823                         lun->capacity.nsec = 0;
1824                         lun->capacity.bsize = 512;
1825                         lun->capacity.bshift = 0;
1826                 }
1827         }
1828 }
1829
1830 /*
1831  * The open funcion.
1832  * This is mostly needed to keep refcounting, but also to support
1833  * media checks on removable media drives.
1834  */
1835 static int ub_bd_open(struct inode *inode, struct file *filp)
1836 {
1837         struct gendisk *disk = inode->i_bdev->bd_disk;
1838         struct ub_lun *lun;
1839         struct ub_dev *sc;
1840         unsigned long flags;
1841         int rc;
1842
1843         if ((lun = disk->private_data) == NULL)
1844                 return -ENXIO;
1845         sc = lun->udev;
1846
1847         spin_lock_irqsave(&ub_lock, flags);
1848         if (atomic_read(&sc->poison)) {
1849                 spin_unlock_irqrestore(&ub_lock, flags);
1850                 return -ENXIO;
1851         }
1852         sc->openc++;
1853         spin_unlock_irqrestore(&ub_lock, flags);
1854
1855         /*
1856          * This is a workaround for a specific problem in our block layer.
1857          * In 2.6.9, register_disk duplicates the code from rescan_partitions.
1858          * However, if we do add_disk with a device which persistently reports
1859          * a changed media, add_disk calls register_disk, which does do_open,
1860          * which will call rescan_paritions for changed media. After that,
1861          * register_disk attempts to do it all again and causes double kobject
1862          * registration and a eventually an oops on module removal.
1863          *
1864          * The bottom line is, Al Viro says that we should not allow
1865          * bdev->bd_invalidated to be set when doing add_disk no matter what.
1866          */
1867         if (lun->first_open) {
1868                 lun->first_open = 0;
1869                 if (lun->changed) {
1870                         rc = -ENOMEDIUM;
1871                         goto err_open;
1872                 }
1873         }
1874
1875         if (lun->removable || lun->readonly)
1876                 check_disk_change(inode->i_bdev);
1877
1878         /*
1879          * The sd.c considers ->media_present and ->changed not equivalent,
1880          * under some pretty murky conditions (a failure of READ CAPACITY).
1881          * We may need it one day.
1882          */
1883         if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1884                 rc = -ENOMEDIUM;
1885                 goto err_open;
1886         }
1887
1888         if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1889                 rc = -EROFS;
1890                 goto err_open;
1891         }
1892
1893         return 0;
1894
1895 err_open:
1896         ub_put(sc);
1897         return rc;
1898 }
1899
1900 /*
1901  */
1902 static int ub_bd_release(struct inode *inode, struct file *filp)
1903 {
1904         struct gendisk *disk = inode->i_bdev->bd_disk;
1905         struct ub_lun *lun = disk->private_data;
1906         struct ub_dev *sc = lun->udev;
1907
1908         ub_put(sc);
1909         return 0;
1910 }
1911
1912 /*
1913  * The ioctl interface.
1914  */
1915 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1916     unsigned int cmd, unsigned long arg)
1917 {
1918         struct gendisk *disk = inode->i_bdev->bd_disk;
1919         void __user *usermem = (void __user *) arg;
1920
1921         return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1922 }
1923
1924 /*
1925  * This is called once a new disk was seen by the block layer or by ub_probe().
1926  * The main onjective here is to discover the features of the media such as
1927  * the capacity, read-only status, etc. USB storage generally does not
1928  * need to be spun up, but if we needed it, this would be the place.
1929  *
1930  * This call can sleep.
1931  *
1932  * The return code is not used.
1933  */
1934 static int ub_bd_revalidate(struct gendisk *disk)
1935 {
1936         struct ub_lun *lun = disk->private_data;
1937
1938         ub_revalidate(lun->udev, lun);
1939
1940         /* XXX Support sector size switching like in sr.c */
1941         blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1942         set_capacity(disk, lun->capacity.nsec);
1943         // set_disk_ro(sdkp->disk, lun->readonly);
1944
1945         return 0;
1946 }
1947
1948 /*
1949  * The check is called by the block layer to verify if the media
1950  * is still available. It is supposed to be harmless, lightweight and
1951  * non-intrusive in case the media was not changed.
1952  *
1953  * This call can sleep.
1954  *
1955  * The return code is bool!
1956  */
1957 static int ub_bd_media_changed(struct gendisk *disk)
1958 {
1959         struct ub_lun *lun = disk->private_data;
1960
1961         if (!lun->removable)
1962                 return 0;
1963
1964         /*
1965          * We clean checks always after every command, so this is not
1966          * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1967          * the device is actually not ready with operator or software
1968          * intervention required. One dangerous item might be a drive which
1969          * spins itself down, and come the time to write dirty pages, this
1970          * will fail, then block layer discards the data. Since we never
1971          * spin drives up, such devices simply cannot be used with ub anyway.
1972          */
1973         if (ub_sync_tur(lun->udev, lun) != 0) {
1974                 lun->changed = 1;
1975                 return 1;
1976         }
1977
1978         return lun->changed;
1979 }
1980
1981 static struct block_device_operations ub_bd_fops = {
1982         .owner          = THIS_MODULE,
1983         .open           = ub_bd_open,
1984         .release        = ub_bd_release,
1985         .ioctl          = ub_bd_ioctl,
1986         .media_changed  = ub_bd_media_changed,
1987         .revalidate_disk = ub_bd_revalidate,
1988 };
1989
1990 /*
1991  * Common ->done routine for commands executed synchronously.
1992  */
1993 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1994 {
1995         struct completion *cop = cmd->back;
1996         complete(cop);
1997 }
1998
1999 /*
2000  * Test if the device has a check condition on it, synchronously.
2001  */
2002 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
2003 {
2004         struct ub_scsi_cmd *cmd;
2005         enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
2006         unsigned long flags;
2007         struct completion compl;
2008         int rc;
2009
2010         init_completion(&compl);
2011
2012         rc = -ENOMEM;
2013         if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2014                 goto err_alloc;
2015         memset(cmd, 0, ALLOC_SIZE);
2016
2017         cmd->cdb[0] = TEST_UNIT_READY;
2018         cmd->cdb_len = 6;
2019         cmd->dir = UB_DIR_NONE;
2020         cmd->state = UB_CMDST_INIT;
2021         cmd->lun = lun;                 /* This may be NULL, but that's ok */
2022         cmd->done = ub_probe_done;
2023         cmd->back = &compl;
2024
2025         spin_lock_irqsave(sc->lock, flags);
2026         cmd->tag = sc->tagcnt++;
2027
2028         rc = ub_submit_scsi(sc, cmd);
2029         spin_unlock_irqrestore(sc->lock, flags);
2030
2031         if (rc != 0) {
2032                 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
2033                 goto err_submit;
2034         }
2035
2036         wait_for_completion(&compl);
2037
2038         rc = cmd->error;
2039
2040         if (rc == -EIO && cmd->key != 0)        /* Retries for benh's key */
2041                 rc = cmd->key;
2042
2043 err_submit:
2044         kfree(cmd);
2045 err_alloc:
2046         return rc;
2047 }
2048
2049 /*
2050  * Read the SCSI capacity synchronously (for probing).
2051  */
2052 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
2053     struct ub_capacity *ret)
2054 {
2055         struct ub_scsi_cmd *cmd;
2056         struct scatterlist *sg;
2057         char *p;
2058         enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
2059         unsigned long flags;
2060         unsigned int bsize, shift;
2061         unsigned long nsec;
2062         struct completion compl;
2063         int rc;
2064
2065         init_completion(&compl);
2066
2067         rc = -ENOMEM;
2068         if ((cmd = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2069                 goto err_alloc;
2070         memset(cmd, 0, ALLOC_SIZE);
2071         p = (char *)cmd + sizeof(struct ub_scsi_cmd);
2072
2073         cmd->cdb[0] = 0x25;
2074         cmd->cdb_len = 10;
2075         cmd->dir = UB_DIR_READ;
2076         cmd->state = UB_CMDST_INIT;
2077         cmd->nsg = 1;
2078         sg = &cmd->sgv[0];
2079         sg->page = virt_to_page(p);
2080         sg->offset = (unsigned long)p & (PAGE_SIZE-1);
2081         sg->length = 8;
2082         cmd->len = 8;
2083         cmd->lun = lun;
2084         cmd->done = ub_probe_done;
2085         cmd->back = &compl;
2086
2087         spin_lock_irqsave(sc->lock, flags);
2088         cmd->tag = sc->tagcnt++;
2089
2090         rc = ub_submit_scsi(sc, cmd);
2091         spin_unlock_irqrestore(sc->lock, flags);
2092
2093         if (rc != 0) {
2094                 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
2095                 goto err_submit;
2096         }
2097
2098         wait_for_completion(&compl);
2099
2100         if (cmd->error != 0) {
2101                 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
2102                 rc = -EIO;
2103                 goto err_read;
2104         }
2105         if (cmd->act_len != 8) {
2106                 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
2107                 rc = -EIO;
2108                 goto err_read;
2109         }
2110
2111         /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
2112         nsec = be32_to_cpu(*(__be32 *)p) + 1;
2113         bsize = be32_to_cpu(*(__be32 *)(p + 4));
2114         switch (bsize) {
2115         case 512:       shift = 0;      break;
2116         case 1024:      shift = 1;      break;
2117         case 2048:      shift = 2;      break;
2118         case 4096:      shift = 3;      break;
2119         default:
2120                 printk("ub: Bad sector size %u\n", bsize); /* P3 */
2121                 rc = -EDOM;
2122                 goto err_inv_bsize;
2123         }
2124
2125         ret->bsize = bsize;
2126         ret->bshift = shift;
2127         ret->nsec = nsec << shift;
2128         rc = 0;
2129
2130 err_inv_bsize:
2131 err_read:
2132 err_submit:
2133         kfree(cmd);
2134 err_alloc:
2135         return rc;
2136 }
2137
2138 /*
2139  */
2140 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
2141 {
2142         struct completion *cop = urb->context;
2143         complete(cop);
2144 }
2145
2146 static void ub_probe_timeout(unsigned long arg)
2147 {
2148         struct completion *cop = (struct completion *) arg;
2149         complete(cop);
2150 }
2151
2152 /*
2153  * Reset with a Bulk reset.
2154  */
2155 static int ub_sync_reset(struct ub_dev *sc)
2156 {
2157         int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2158         struct usb_ctrlrequest *cr;
2159         struct completion compl;
2160         struct timer_list timer;
2161         int rc;
2162
2163         init_completion(&compl);
2164
2165         cr = &sc->work_cr;
2166         cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2167         cr->bRequest = US_BULK_RESET_REQUEST;
2168         cr->wValue = cpu_to_le16(0);
2169         cr->wIndex = cpu_to_le16(ifnum);
2170         cr->wLength = cpu_to_le16(0);
2171
2172         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2173             (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2174         sc->work_urb.actual_length = 0;
2175         sc->work_urb.error_count = 0;
2176         sc->work_urb.status = 0;
2177
2178         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2179                 printk(KERN_WARNING
2180                      "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
2181                 return rc;
2182         }
2183
2184         init_timer(&timer);
2185         timer.function = ub_probe_timeout;
2186         timer.data = (unsigned long) &compl;
2187         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2188         add_timer(&timer);
2189
2190         wait_for_completion(&compl);
2191
2192         del_timer_sync(&timer);
2193         usb_kill_urb(&sc->work_urb);
2194
2195         return sc->work_urb.status;
2196 }
2197
2198 /*
2199  * Get number of LUNs by the way of Bulk GetMaxLUN command.
2200  */
2201 static int ub_sync_getmaxlun(struct ub_dev *sc)
2202 {
2203         int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
2204         unsigned char *p;
2205         enum { ALLOC_SIZE = 1 };
2206         struct usb_ctrlrequest *cr;
2207         struct completion compl;
2208         struct timer_list timer;
2209         int nluns;
2210         int rc;
2211
2212         init_completion(&compl);
2213
2214         rc = -ENOMEM;
2215         if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2216                 goto err_alloc;
2217         *p = 55;
2218
2219         cr = &sc->work_cr;
2220         cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2221         cr->bRequest = US_BULK_GET_MAX_LUN;
2222         cr->wValue = cpu_to_le16(0);
2223         cr->wIndex = cpu_to_le16(ifnum);
2224         cr->wLength = cpu_to_le16(1);
2225
2226         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2227             (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2228         sc->work_urb.actual_length = 0;
2229         sc->work_urb.error_count = 0;
2230         sc->work_urb.status = 0;
2231
2232         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2233                 if (rc == -EPIPE) {
2234                         printk("%s: Stall submitting GetMaxLUN, using 1 LUN\n",
2235                              sc->name); /* P3 */
2236                 } else {
2237                         printk(KERN_NOTICE
2238                              "%s: Unable to submit GetMaxLUN (%d)\n",
2239                              sc->name, rc);
2240                 }
2241                 goto err_submit;
2242         }
2243
2244         init_timer(&timer);
2245         timer.function = ub_probe_timeout;
2246         timer.data = (unsigned long) &compl;
2247         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2248         add_timer(&timer);
2249
2250         wait_for_completion(&compl);
2251
2252         del_timer_sync(&timer);
2253         usb_kill_urb(&sc->work_urb);
2254
2255         if ((rc = sc->work_urb.status) < 0) {
2256                 if (rc == -EPIPE) {
2257                         printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
2258                              sc->name); /* P3 */
2259                 } else {
2260                         printk(KERN_NOTICE
2261                              "%s: Error at GetMaxLUN (%d)\n",
2262                              sc->name, rc);
2263                 }
2264                 goto err_io;
2265         }
2266
2267         if (sc->work_urb.actual_length != 1) {
2268                 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2269                     sc->work_urb.actual_length); /* P3 */
2270                 nluns = 0;
2271         } else {
2272                 if ((nluns = *p) == 55) {
2273                         nluns = 0;
2274                 } else {
2275                         /* GetMaxLUN returns the maximum LUN number */
2276                         nluns += 1;
2277                         if (nluns > UB_MAX_LUNS)
2278                                 nluns = UB_MAX_LUNS;
2279                 }
2280                 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2281                     *p, nluns); /* P3 */
2282         }
2283
2284         kfree(p);
2285         return nluns;
2286
2287 err_io:
2288 err_submit:
2289         kfree(p);
2290 err_alloc:
2291         return rc;
2292 }
2293
2294 /*
2295  * Clear initial stalls.
2296  */
2297 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2298 {
2299         int endp;
2300         struct usb_ctrlrequest *cr;
2301         struct completion compl;
2302         struct timer_list timer;
2303         int rc;
2304
2305         init_completion(&compl);
2306
2307         endp = usb_pipeendpoint(stalled_pipe);
2308         if (usb_pipein (stalled_pipe))
2309                 endp |= USB_DIR_IN;
2310
2311         cr = &sc->work_cr;
2312         cr->bRequestType = USB_RECIP_ENDPOINT;
2313         cr->bRequest = USB_REQ_CLEAR_FEATURE;
2314         cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2315         cr->wIndex = cpu_to_le16(endp);
2316         cr->wLength = cpu_to_le16(0);
2317
2318         usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2319             (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2320         sc->work_urb.actual_length = 0;
2321         sc->work_urb.error_count = 0;
2322         sc->work_urb.status = 0;
2323
2324         if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2325                 printk(KERN_WARNING
2326                      "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2327                 return rc;
2328         }
2329
2330         init_timer(&timer);
2331         timer.function = ub_probe_timeout;
2332         timer.data = (unsigned long) &compl;
2333         timer.expires = jiffies + UB_CTRL_TIMEOUT;
2334         add_timer(&timer);
2335
2336         wait_for_completion(&compl);
2337
2338         del_timer_sync(&timer);
2339         usb_kill_urb(&sc->work_urb);
2340
2341         /* reset the endpoint toggle */
2342         usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2343
2344         return 0;
2345 }
2346
2347 /*
2348  * Get the pipe settings.
2349  */
2350 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2351     struct usb_interface *intf)
2352 {
2353         struct usb_host_interface *altsetting = intf->cur_altsetting;
2354         struct usb_endpoint_descriptor *ep_in = NULL;
2355         struct usb_endpoint_descriptor *ep_out = NULL;
2356         struct usb_endpoint_descriptor *ep;
2357         int i;
2358
2359         /*
2360          * Find the endpoints we need.
2361          * We are expecting a minimum of 2 endpoints - in and out (bulk).
2362          * We will ignore any others.
2363          */
2364         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2365                 ep = &altsetting->endpoint[i].desc;
2366
2367                 /* Is it a BULK endpoint? */
2368                 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2369                                 == USB_ENDPOINT_XFER_BULK) {
2370                         /* BULK in or out? */
2371                         if (ep->bEndpointAddress & USB_DIR_IN)
2372                                 ep_in = ep;
2373                         else
2374                                 ep_out = ep;
2375                 }
2376         }
2377
2378         if (ep_in == NULL || ep_out == NULL) {
2379                 printk(KERN_NOTICE "%s: failed endpoint check\n",
2380                     sc->name);
2381                 return -ENODEV;
2382         }
2383
2384         /* Calculate and store the pipe values */
2385         sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2386         sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2387         sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2388                 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2389         sc->recv_bulk_pipe = usb_rcvbulkpipe(dev, 
2390                 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2391
2392         return 0;
2393 }
2394
2395 /*
2396  * Probing is done in the process context, which allows us to cheat
2397  * and not to build a state machine for the discovery.
2398  */
2399 static int ub_probe(struct usb_interface *intf,
2400     const struct usb_device_id *dev_id)
2401 {
2402         struct ub_dev *sc;
2403         int nluns;
2404         int rc;
2405         int i;
2406
2407         if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2408                 return -ENXIO;
2409
2410         rc = -ENOMEM;
2411         if ((sc = kmalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2412                 goto err_core;
2413         memset(sc, 0, sizeof(struct ub_dev));
2414         sc->lock = ub_next_lock();
2415         INIT_LIST_HEAD(&sc->luns);
2416         usb_init_urb(&sc->work_urb);
2417         tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2418         atomic_set(&sc->poison, 0);
2419         INIT_WORK(&sc->reset_work, ub_reset_task, sc);
2420         init_waitqueue_head(&sc->reset_wait);
2421
2422         init_timer(&sc->work_timer);
2423         sc->work_timer.data = (unsigned long) sc;
2424         sc->work_timer.function = ub_urb_timeout;
2425
2426         ub_init_completion(&sc->work_done);
2427         sc->work_done.done = 1;         /* A little yuk, but oh well... */
2428
2429         sc->dev = interface_to_usbdev(intf);
2430         sc->intf = intf;
2431         // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2432         usb_set_intfdata(intf, sc);
2433         usb_get_dev(sc->dev);
2434         /*
2435          * Since we give the interface struct to the block level through
2436          * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2437          * oopses on close after a disconnect (kernels 2.6.16 and up).
2438          */
2439         usb_get_intf(sc->intf);
2440
2441         snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2442             sc->dev->bus->busnum, sc->dev->devnum);
2443
2444         /* XXX Verify that we can handle the device (from descriptors) */
2445
2446         if (ub_get_pipes(sc, sc->dev, intf) != 0)
2447                 goto err_dev_desc;
2448
2449         if (device_create_file(&sc->intf->dev, &dev_attr_diag) != 0)
2450                 goto err_diag;
2451
2452         /*
2453          * At this point, all USB initialization is done, do upper layer.
2454          * We really hate halfway initialized structures, so from the
2455          * invariants perspective, this ub_dev is fully constructed at
2456          * this point.
2457          */
2458
2459         /*
2460          * This is needed to clear toggles. It is a problem only if we do
2461          * `rmmod ub && modprobe ub` without disconnects, but we like that.
2462          */
2463 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2464         ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2465         ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2466 #endif
2467
2468         /*
2469          * The way this is used by the startup code is a little specific.
2470          * A SCSI check causes a USB stall. Our common case code sees it
2471          * and clears the check, after which the device is ready for use.
2472          * But if a check was not present, any command other than
2473          * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2474          *
2475          * If we neglect to clear the SCSI check, the first real command fails
2476          * (which is the capacity readout). We clear that and retry, but why
2477          * causing spurious retries for no reason.
2478          *
2479          * Revalidation may start with its own TEST_UNIT_READY, but that one
2480          * has to succeed, so we clear checks with an additional one here.
2481          * In any case it's not our business how revaliadation is implemented.
2482          */
2483         for (i = 0; i < 3; i++) {       /* Retries for benh's key */
2484                 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2485                 if (rc != 0x6) break;
2486                 msleep(10);
2487         }
2488
2489         nluns = 1;
2490         for (i = 0; i < 3; i++) {
2491                 if ((rc = ub_sync_getmaxlun(sc)) < 0) {
2492                         /* 
2493                          * This segment is taken from usb-storage. They say
2494                          * that ZIP-100 needs this, but my own ZIP-100 works
2495                          * fine without this.
2496                          * Still, it does not seem to hurt anything.
2497                          */
2498                         if (rc == -EPIPE) {
2499                                 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2500                                 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2501                         }
2502                         break;
2503                 }
2504                 if (rc != 0) {
2505                         nluns = rc;
2506                         break;
2507                 }
2508                 msleep(100);
2509         }
2510
2511         for (i = 0; i < nluns; i++) {
2512                 ub_probe_lun(sc, i);
2513         }
2514         return 0;
2515
2516         /* device_remove_file(&sc->intf->dev, &dev_attr_diag); */
2517 err_diag:
2518 err_dev_desc:
2519         usb_set_intfdata(intf, NULL);
2520         usb_put_intf(sc->intf);
2521         usb_put_dev(sc->dev);
2522         kfree(sc);
2523 err_core:
2524         return rc;
2525 }
2526
2527 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2528 {
2529         struct ub_lun *lun;
2530         request_queue_t *q;
2531         struct gendisk *disk;
2532         int rc;
2533
2534         rc = -ENOMEM;
2535         if ((lun = kmalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2536                 goto err_alloc;
2537         memset(lun, 0, sizeof(struct ub_lun));
2538         lun->num = lnum;
2539
2540         rc = -ENOSR;
2541         if ((lun->id = ub_id_get()) == -1)
2542                 goto err_id;
2543
2544         lun->udev = sc;
2545         list_add(&lun->link, &sc->luns);
2546
2547         snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2548             lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2549
2550         lun->removable = 1;             /* XXX Query this from the device */
2551         lun->changed = 1;               /* ub_revalidate clears only */
2552         lun->first_open = 1;
2553         ub_revalidate(sc, lun);
2554
2555         rc = -ENOMEM;
2556         if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2557                 goto err_diskalloc;
2558
2559         lun->disk = disk;
2560         sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2561         sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2562         disk->major = UB_MAJOR;
2563         disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2564         disk->fops = &ub_bd_fops;
2565         disk->private_data = lun;
2566         disk->driverfs_dev = &sc->intf->dev;
2567
2568         rc = -ENOMEM;
2569         if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2570                 goto err_blkqinit;
2571
2572         disk->queue = q;
2573
2574         blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2575         blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2576         blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2577         blk_queue_segment_boundary(q, 0xffffffff);      /* Dubious. */
2578         blk_queue_max_sectors(q, UB_MAX_SECTORS);
2579         blk_queue_hardsect_size(q, lun->capacity.bsize);
2580
2581         q->queuedata = lun;
2582
2583         set_capacity(disk, lun->capacity.nsec);
2584         if (lun->removable)
2585                 disk->flags |= GENHD_FL_REMOVABLE;
2586
2587         add_disk(disk);
2588
2589         return 0;
2590
2591 err_blkqinit:
2592         put_disk(disk);
2593 err_diskalloc:
2594         list_del(&lun->link);
2595         ub_id_put(lun->id);
2596 err_id:
2597         kfree(lun);
2598 err_alloc:
2599         return rc;
2600 }
2601
2602 static void ub_disconnect(struct usb_interface *intf)
2603 {
2604         struct ub_dev *sc = usb_get_intfdata(intf);
2605         struct list_head *p;
2606         struct ub_lun *lun;
2607         struct gendisk *disk;
2608         unsigned long flags;
2609
2610         /*
2611          * Prevent ub_bd_release from pulling the rug from under us.
2612          * XXX This is starting to look like a kref.
2613          * XXX Why not to take this ref at probe time?
2614          */
2615         spin_lock_irqsave(&ub_lock, flags);
2616         sc->openc++;
2617         spin_unlock_irqrestore(&ub_lock, flags);
2618
2619         /*
2620          * Fence stall clearnings, operations triggered by unlinkings and so on.
2621          * We do not attempt to unlink any URBs, because we do not trust the
2622          * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2623          */
2624         atomic_set(&sc->poison, 1);
2625
2626         /*
2627          * Wait for reset to end, if any.
2628          */
2629         wait_event(sc->reset_wait, !sc->reset);
2630
2631         /*
2632          * Blow away queued commands.
2633          *
2634          * Actually, this never works, because before we get here
2635          * the HCD terminates outstanding URB(s). It causes our
2636          * SCSI command queue to advance, commands fail to submit,
2637          * and the whole queue drains. So, we just use this code to
2638          * print warnings.
2639          */
2640         spin_lock_irqsave(sc->lock, flags);
2641         {
2642                 struct ub_scsi_cmd *cmd;
2643                 int cnt = 0;
2644                 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2645                         cmd->error = -ENOTCONN;
2646                         cmd->state = UB_CMDST_DONE;
2647                         ub_cmdtr_state(sc, cmd);
2648                         ub_cmdq_pop(sc);
2649                         (*cmd->done)(sc, cmd);
2650                         cnt++;
2651                 }
2652                 if (cnt != 0) {
2653                         printk(KERN_WARNING "%s: "
2654                             "%d was queued after shutdown\n", sc->name, cnt);
2655                 }
2656         }
2657         spin_unlock_irqrestore(sc->lock, flags);
2658
2659         /*
2660          * Unregister the upper layer.
2661          */
2662         list_for_each (p, &sc->luns) {
2663                 lun = list_entry(p, struct ub_lun, link);
2664                 disk = lun->disk;
2665                 if (disk->flags & GENHD_FL_UP)
2666                         del_gendisk(disk);
2667                 /*
2668                  * I wish I could do:
2669                  *    set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2670                  * As it is, we rely on our internal poisoning and let
2671                  * the upper levels to spin furiously failing all the I/O.
2672                  */
2673         }
2674
2675         /*
2676          * Testing for -EINPROGRESS is always a bug, so we are bending
2677          * the rules a little.
2678          */
2679         spin_lock_irqsave(sc->lock, flags);
2680         if (sc->work_urb.status == -EINPROGRESS) {      /* janitors: ignore */
2681                 printk(KERN_WARNING "%s: "
2682                     "URB is active after disconnect\n", sc->name);
2683         }
2684         spin_unlock_irqrestore(sc->lock, flags);
2685
2686         /*
2687          * There is virtually no chance that other CPU runs times so long
2688          * after ub_urb_complete should have called del_timer, but only if HCD
2689          * didn't forget to deliver a callback on unlink.
2690          */
2691         del_timer_sync(&sc->work_timer);
2692
2693         /*
2694          * At this point there must be no commands coming from anyone
2695          * and no URBs left in transit.
2696          */
2697
2698         device_remove_file(&sc->intf->dev, &dev_attr_diag);
2699         ub_put(sc);
2700 }
2701
2702 static struct usb_driver ub_driver = {
2703         .name =         "ub",
2704         .probe =        ub_probe,
2705         .disconnect =   ub_disconnect,
2706         .id_table =     ub_usb_ids,
2707 };
2708
2709 static int __init ub_init(void)
2710 {
2711         int rc;
2712         int i;
2713
2714         for (i = 0; i < UB_QLOCK_NUM; i++)
2715                 spin_lock_init(&ub_qlockv[i]);
2716
2717         if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2718                 goto err_regblkdev;
2719         devfs_mk_dir(DEVFS_NAME);
2720
2721         if ((rc = usb_register(&ub_driver)) != 0)
2722                 goto err_register;
2723
2724         usb_usual_set_present(USB_US_TYPE_UB);
2725         return 0;
2726
2727 err_register:
2728         devfs_remove(DEVFS_NAME);
2729         unregister_blkdev(UB_MAJOR, DRV_NAME);
2730 err_regblkdev:
2731         return rc;
2732 }
2733
2734 static void __exit ub_exit(void)
2735 {
2736         usb_deregister(&ub_driver);
2737
2738         devfs_remove(DEVFS_NAME);
2739         unregister_blkdev(UB_MAJOR, DRV_NAME);
2740         usb_usual_clear_present(USB_US_TYPE_UB);
2741 }
2742
2743 module_init(ub_init);
2744 module_exit(ub_exit);
2745
2746 MODULE_LICENSE("GPL");