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