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