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