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