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