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