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