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