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