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