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