2 * The low performance USB storage driver (ub).
4 * Copyright (c) 1999, 2000 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
5 * Copyright (C) 2004 Pete Zaitcev (zaitcev@yahoo.com)
7 * This work is a part of Linux kernel, is derived from it,
8 * and is not licensed separately. See file COPYING for details.
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 * -- special case some senses, e.g. 3a/0 -> no media present, reduce retries
14 * -- verify the 13 conditions and do bulk resets
15 * -- kill last_pipe and simply do two-state clearing on both pipes
17 * -- move top_sense and work_bcs into separate allocations (if they survive)
18 * for cache purists and esoteric architectures.
19 * -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
20 * -- prune comments, they are too volumnous
21 * -- Exterminate P3 printks
23 * -- Redo "benh's retries", perhaps have spin-up code to handle them. V:D=?
24 * -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
26 #include <linux/kernel.h>
27 #include <linux/module.h>
28 #include <linux/usb.h>
29 #include <linux/usb_usual.h>
30 #include <linux/blkdev.h>
31 #include <linux/devfs_fs_kernel.h>
32 #include <linux/timer.h>
33 #include <scsi/scsi.h>
36 #define DEVFS_NAME DRV_NAME
41 * The command state machine is the key model for understanding of this driver.
43 * The general rule is that all transitions are done towards the bottom
44 * of the diagram, thus preventing any loops.
46 * An exception to that is how the STAT state is handled. A counter allows it
47 * to be re-entered along the path marked with [C].
53 * ub_scsi_cmd_start fails ->--------------------------------------\
60 * was -EPIPE -->-------------------------------->! CLEAR ! !
63 * was error -->------------------------------------- ! --------->\
65 * /--<-- cmd->dir == NONE ? ! !
72 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
75 * ! ! was error -->---- ! --------->\
76 * ! was error -->--------------------- ! ------------- ! --------->\
79 * \--->+--------+ ! ! !
80 * ! STAT !<--------------------------/ ! !
83 * [C] was -EPIPE -->-----------\ ! !
85 * +<---- len == 0 ! ! !
87 * ! was error -->--------------------------------------!---------->\
89 * +<---- bad CSW ! ! !
90 * +<---- bad tag ! ! !
96 * \------- ! --------------------[C]--------\ ! !
98 * cmd->error---\ +--------+ ! !
99 * ! +--------------->! SENSE !<----------/ !
100 * STAT_FAIL----/ +--------+ !
103 * \--------------------------------\--------------------->! DONE !
108 * This many LUNs per USB device.
109 * Every one of them takes a host, see UB_MAX_HOSTS.
111 #define UB_MAX_LUNS 9
116 #define UB_PARTS_PER_LUN 8
118 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
120 #define UB_SENSE_SIZE 18
125 /* command block wrapper */
126 struct bulk_cb_wrap {
127 __le32 Signature; /* contains 'USBC' */
128 u32 Tag; /* unique per command id */
129 __le32 DataTransferLength; /* size of data */
130 u8 Flags; /* direction in bit 0 */
132 u8 Length; /* of of the CDB */
133 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
136 #define US_BULK_CB_WRAP_LEN 31
137 #define US_BULK_CB_SIGN 0x43425355 /*spells out USBC */
138 #define US_BULK_FLAG_IN 1
139 #define US_BULK_FLAG_OUT 0
141 /* command status wrapper */
142 struct bulk_cs_wrap {
143 __le32 Signature; /* should = 'USBS' */
144 u32 Tag; /* same as original command */
145 __le32 Residue; /* amount not transferred */
146 u8 Status; /* see below */
149 #define US_BULK_CS_WRAP_LEN 13
150 #define US_BULK_CS_SIGN 0x53425355 /* spells out 'USBS' */
151 #define US_BULK_STAT_OK 0
152 #define US_BULK_STAT_FAIL 1
153 #define US_BULK_STAT_PHASE 2
155 /* bulk-only class specific requests */
156 #define US_BULK_RESET_REQUEST 0xff
157 #define US_BULK_GET_MAX_LUN 0xfe
163 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
164 #define UB_MAX_SECTORS 64
167 * A second is more than enough for a 32K transfer (UB_MAX_SECTORS)
168 * even if a webcam hogs the bus, but some devices need time to spin up.
170 #define UB_URB_TIMEOUT (HZ*2)
171 #define UB_DATA_TIMEOUT (HZ*5) /* ZIP does spin-ups in the data phase */
172 #define UB_STAT_TIMEOUT (HZ*5) /* Same spinups and eject for a dataless cmd. */
173 #define UB_CTRL_TIMEOUT (HZ/2) /* 500ms ought to be enough to clear a stall */
176 * An instance of a SCSI command in transit.
178 #define UB_DIR_NONE 0
179 #define UB_DIR_READ 1
180 #define UB_DIR_ILLEGAL2 2
181 #define UB_DIR_WRITE 3
184 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
185 (((c)==UB_DIR_READ)? 'r': 'n'))
187 enum ub_scsi_cmd_state {
188 UB_CMDST_INIT, /* Initial state */
189 UB_CMDST_CMD, /* Command submitted */
190 UB_CMDST_DATA, /* Data phase */
191 UB_CMDST_CLR2STS, /* Clearing before requesting status */
192 UB_CMDST_STAT, /* Status phase */
193 UB_CMDST_CLEAR, /* Clearing a stall (halt, actually) */
194 UB_CMDST_CLRRS, /* Clearing before retrying status */
195 UB_CMDST_SENSE, /* Sending Request Sense */
196 UB_CMDST_DONE /* Final state */
200 unsigned char cdb[UB_MAX_CDB_SIZE];
201 unsigned char cdb_len;
203 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
204 enum ub_scsi_cmd_state state;
206 struct ub_scsi_cmd *next;
208 int error; /* Return code - valid upon done */
209 unsigned int act_len; /* Return size */
210 unsigned char key, asc, ascq; /* May be valid if error==-EIO */
212 int stat_count; /* Retries getting status. */
214 unsigned int len; /* Requested length */
215 unsigned int current_sg;
216 unsigned int nsg; /* sgv[nsg] */
217 struct scatterlist sgv[UB_MAX_REQ_SG];
220 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
226 unsigned int current_try;
227 unsigned int nsg; /* sgv[nsg] */
228 struct scatterlist sgv[UB_MAX_REQ_SG];
234 unsigned long nsec; /* Linux size - 512 byte sectors */
235 unsigned int bsize; /* Linux hardsect_size */
236 unsigned int bshift; /* Shift between 512 and hard sects */
240 * This is a direct take-off from linux/include/completion.h
241 * The difference is that I do not wait on this thing, just poll.
242 * When I want to wait (ub_probe), I just use the stock completion.
244 * Note that INIT_COMPLETION takes no lock. It is correct. But why
245 * in the bloody hell that thing takes struct instead of pointer to struct
246 * is quite beyond me. I just copied it from the stock completion.
248 struct ub_completion {
253 static inline void ub_init_completion(struct ub_completion *x)
256 spin_lock_init(&x->lock);
259 #define UB_INIT_COMPLETION(x) ((x).done = 0)
261 static void ub_complete(struct ub_completion *x)
265 spin_lock_irqsave(&x->lock, flags);
267 spin_unlock_irqrestore(&x->lock, flags);
270 static int ub_is_completed(struct ub_completion *x)
275 spin_lock_irqsave(&x->lock, flags);
277 spin_unlock_irqrestore(&x->lock, flags);
283 struct ub_scsi_cmd_queue {
285 struct ub_scsi_cmd *head, *tail;
289 * The block device instance (one per LUN).
293 struct list_head link;
294 struct gendisk *disk;
295 int id; /* Host index */
296 int num; /* LUN number */
299 int changed; /* Media was changed */
303 struct ub_request urq;
305 /* Use Ingo's mempool if or when we have more than one command. */
307 * Currently we never need more than one command for the whole device.
308 * However, giving every LUN a command is a cheap and automatic way
309 * to enforce fairness between them.
312 struct ub_scsi_cmd cmdv[1];
314 struct ub_capacity capacity;
318 * The USB device instance.
322 atomic_t poison; /* The USB device is disconnected */
323 int openc; /* protected by ub_lock! */
324 /* kref is too implicit for our taste */
325 int reset; /* Reset is running */
328 struct usb_device *dev;
329 struct usb_interface *intf;
331 struct list_head luns;
333 unsigned int send_bulk_pipe; /* cached pipe values */
334 unsigned int recv_bulk_pipe;
335 unsigned int send_ctrl_pipe;
336 unsigned int recv_ctrl_pipe;
338 struct tasklet_struct tasklet;
340 struct ub_scsi_cmd_queue cmd_queue;
341 struct ub_scsi_cmd top_rqs_cmd; /* REQUEST SENSE */
342 unsigned char top_sense[UB_SENSE_SIZE];
344 struct ub_completion work_done;
346 struct timer_list work_timer;
347 int last_pipe; /* What might need clearing */
348 __le32 signature; /* Learned signature */
349 struct bulk_cb_wrap work_bcb;
350 struct bulk_cs_wrap work_bcs;
351 struct usb_ctrlrequest work_cr;
353 struct work_struct reset_work;
354 wait_queue_head_t reset_wait;
361 static void ub_cleanup(struct ub_dev *sc);
362 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
363 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
364 struct ub_scsi_cmd *cmd, struct ub_request *urq);
365 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
366 struct ub_scsi_cmd *cmd, struct ub_request *urq);
367 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
368 static void ub_end_rq(struct request *rq, int uptodate);
369 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
370 struct ub_request *urq, struct ub_scsi_cmd *cmd);
371 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
372 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
373 static void ub_scsi_action(unsigned long _dev);
374 static void ub_scsi_dispatch(struct ub_dev *sc);
375 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
376 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
377 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
378 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
379 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
380 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
381 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
382 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
384 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
385 static void ub_reset_enter(struct ub_dev *sc, int try);
386 static void ub_reset_task(void *arg);
387 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
388 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
389 struct ub_capacity *ret);
390 static int ub_sync_reset(struct ub_dev *sc);
391 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
392 static int ub_probe_lun(struct ub_dev *sc, int lnum);
396 #ifdef CONFIG_USB_LIBUSUAL
398 #define ub_usb_ids storage_usb_ids
401 static struct usb_device_id ub_usb_ids[] = {
402 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
406 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
407 #endif /* CONFIG_USB_LIBUSUAL */
410 * Find me a way to identify "next free minor" for add_disk(),
411 * and the array disappears the next day. However, the number of
412 * hosts has something to do with the naming and /proc/partitions.
413 * This has to be thought out in detail before changing.
414 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
416 #define UB_MAX_HOSTS 26
417 static char ub_hostv[UB_MAX_HOSTS];
419 #define UB_QLOCK_NUM 5
420 static spinlock_t ub_qlockv[UB_QLOCK_NUM];
421 static int ub_qlock_next = 0;
423 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
428 * This also stores the host for indexing by minor, which is somewhat dirty.
430 static int ub_id_get(void)
435 spin_lock_irqsave(&ub_lock, flags);
436 for (i = 0; i < UB_MAX_HOSTS; i++) {
437 if (ub_hostv[i] == 0) {
439 spin_unlock_irqrestore(&ub_lock, flags);
443 spin_unlock_irqrestore(&ub_lock, flags);
447 static void ub_id_put(int id)
451 if (id < 0 || id >= UB_MAX_HOSTS) {
452 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
456 spin_lock_irqsave(&ub_lock, flags);
457 if (ub_hostv[id] == 0) {
458 spin_unlock_irqrestore(&ub_lock, flags);
459 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
463 spin_unlock_irqrestore(&ub_lock, flags);
467 * This is necessitated by the fact that blk_cleanup_queue does not
468 * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
469 * Since our blk_init_queue() passes a spinlock common with ub_dev,
470 * we have life time issues when ub_cleanup frees ub_dev.
472 static spinlock_t *ub_next_lock(void)
477 spin_lock_irqsave(&ub_lock, flags);
478 ret = &ub_qlockv[ub_qlock_next];
479 ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
480 spin_unlock_irqrestore(&ub_lock, flags);
485 * Downcount for deallocation. This rides on two assumptions:
486 * - once something is poisoned, its refcount cannot grow
487 * - opens cannot happen at this time (del_gendisk was done)
488 * If the above is true, we can drop the lock, which we need for
489 * blk_cleanup_queue(): the silly thing may attempt to sleep.
490 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
492 static void ub_put(struct ub_dev *sc)
496 spin_lock_irqsave(&ub_lock, flags);
498 if (sc->openc == 0 && atomic_read(&sc->poison)) {
499 spin_unlock_irqrestore(&ub_lock, flags);
502 spin_unlock_irqrestore(&ub_lock, flags);
507 * Final cleanup and deallocation.
509 static void ub_cleanup(struct ub_dev *sc)
515 while (!list_empty(&sc->luns)) {
517 lun = list_entry(p, struct ub_lun, link);
520 /* I don't think queue can be NULL. But... Stolen from sx8.c */
521 if ((q = lun->disk->queue) != NULL)
522 blk_cleanup_queue(q);
524 * If we zero disk->private_data BEFORE put_disk, we have
525 * to check for NULL all over the place in open, release,
526 * check_media and revalidate, because the block level
527 * semaphore is well inside the put_disk.
528 * But we cannot zero after the call, because *disk is gone.
529 * The sd.c is blatantly racy in this area.
531 /* disk->private_data = NULL; */
543 * The "command allocator".
545 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
547 struct ub_scsi_cmd *ret;
556 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
558 if (cmd != &lun->cmdv[0]) {
559 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
564 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
573 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
575 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
577 if (t->qlen++ == 0) {
585 if (t->qlen > t->qmax)
589 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
591 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
593 if (t->qlen++ == 0) {
601 if (t->qlen > t->qmax)
605 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
607 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
608 struct ub_scsi_cmd *cmd;
620 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
623 * The request function is our main entry point
626 static void ub_request_fn(request_queue_t *q)
628 struct ub_lun *lun = q->queuedata;
631 while ((rq = elv_next_request(q)) != NULL) {
632 if (ub_request_fn_1(lun, rq) != 0) {
639 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
641 struct ub_dev *sc = lun->udev;
642 struct ub_scsi_cmd *cmd;
643 struct ub_request *urq;
646 if (atomic_read(&sc->poison) || lun->changed) {
647 blkdev_dequeue_request(rq);
652 if (lun->urq.rq != NULL)
654 if ((cmd = ub_get_cmd(lun)) == NULL)
656 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
658 blkdev_dequeue_request(rq);
661 memset(urq, 0, sizeof(struct ub_request));
665 * get scatterlist from block layer
667 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
669 printk(KERN_INFO "%s: failed request map (%d)\n",
670 lun->name, n_elem); /* P3 */
673 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
674 printk(KERN_WARNING "%s: request with %d segments\n",
679 sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
681 if (blk_pc_request(rq)) {
682 ub_cmd_build_packet(sc, lun, cmd, urq);
684 ub_cmd_build_block(sc, lun, cmd, urq);
686 cmd->state = UB_CMDST_INIT;
688 cmd->done = ub_rw_cmd_done;
691 cmd->tag = sc->tagcnt++;
692 if (ub_submit_scsi(sc, cmd) != 0)
698 ub_put_cmd(lun, cmd);
703 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
704 struct ub_scsi_cmd *cmd, struct ub_request *urq)
706 struct request *rq = urq->rq;
707 unsigned int block, nblks;
709 if (rq_data_dir(rq) == WRITE)
710 cmd->dir = UB_DIR_WRITE;
712 cmd->dir = UB_DIR_READ;
715 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
720 * The call to blk_queue_hardsect_size() guarantees that request
721 * is aligned, but it is given in terms of 512 byte units, always.
723 block = rq->sector >> lun->capacity.bshift;
724 nblks = rq->nr_sectors >> lun->capacity.bshift;
726 cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
727 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
728 cmd->cdb[2] = block >> 24;
729 cmd->cdb[3] = block >> 16;
730 cmd->cdb[4] = block >> 8;
732 cmd->cdb[7] = nblks >> 8;
736 cmd->len = rq->nr_sectors * 512;
739 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
740 struct ub_scsi_cmd *cmd, struct ub_request *urq)
742 struct request *rq = urq->rq;
744 if (rq->data_len == 0) {
745 cmd->dir = UB_DIR_NONE;
747 if (rq_data_dir(rq) == WRITE)
748 cmd->dir = UB_DIR_WRITE;
750 cmd->dir = UB_DIR_READ;
754 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
756 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
757 cmd->cdb_len = rq->cmd_len;
759 cmd->len = rq->data_len;
762 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
764 struct ub_lun *lun = cmd->lun;
765 struct ub_request *urq = cmd->back;
771 if (cmd->error == 0) {
774 if (blk_pc_request(rq)) {
775 if (cmd->act_len >= rq->data_len)
778 rq->data_len -= cmd->act_len;
783 if (blk_pc_request(rq)) {
784 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
785 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
786 rq->sense_len = UB_SENSE_SIZE;
787 if (sc->top_sense[0] != 0)
788 rq->errors = SAM_STAT_CHECK_CONDITION;
790 rq->errors = DID_ERROR << 16;
792 if (cmd->error == -EIO) {
793 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
801 ub_put_cmd(lun, cmd);
802 ub_end_rq(rq, uptodate);
803 blk_start_queue(lun->disk->queue);
806 static void ub_end_rq(struct request *rq, int uptodate)
808 end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
809 end_that_request_last(rq, uptodate);
812 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
813 struct ub_request *urq, struct ub_scsi_cmd *cmd)
816 if (atomic_read(&sc->poison))
819 ub_reset_enter(sc, urq->current_try);
821 if (urq->current_try >= 3)
824 /* P3 */ printk("%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);
829 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
830 ub_cmd_build_block(sc, lun, cmd, urq);
832 cmd->state = UB_CMDST_INIT;
834 cmd->done = ub_rw_cmd_done;
837 cmd->tag = sc->tagcnt++;
840 return ub_submit_scsi(sc, cmd);
842 ub_cmdq_add(sc, cmd);
848 * Submit a regular SCSI operation (not an auto-sense).
850 * The Iron Law of Good Submit Routine is:
851 * Zero return - callback is done, Nonzero return - callback is not done.
854 * Host is assumed locked.
856 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
859 if (cmd->state != UB_CMDST_INIT ||
860 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
864 ub_cmdq_add(sc, cmd);
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.
869 tasklet_schedule(&sc->tasklet);
874 * Submit the first URB for the queued command.
875 * This function does not deal with queueing in any way.
877 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
879 struct bulk_cb_wrap *bcb;
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.''
890 * We zero sense for all commands so that when a packet request
891 * fails it does not return a stale sense.
893 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
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;
903 /* copy the command payload */
904 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
906 UB_INIT_COMPLETION(sc->work_done);
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);
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;
917 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
918 /* XXX Clear stalls */
919 ub_complete(&sc->work_done);
923 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
924 add_timer(&sc->work_timer);
926 cmd->state = UB_CMDST_CMD;
933 static void ub_urb_timeout(unsigned long arg)
935 struct ub_dev *sc = (struct ub_dev *) arg;
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);
945 * Completion routine for the work URB.
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.
951 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
953 struct ub_dev *sc = urb->context;
955 ub_complete(&sc->work_done);
956 tasklet_schedule(&sc->tasklet);
959 static void ub_scsi_action(unsigned long _dev)
961 struct ub_dev *sc = (struct ub_dev *) _dev;
964 spin_lock_irqsave(sc->lock, flags);
965 ub_scsi_dispatch(sc);
966 spin_unlock_irqrestore(sc->lock, flags);
969 static void ub_scsi_dispatch(struct ub_dev *sc)
971 struct ub_scsi_cmd *cmd;
974 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
975 if (cmd->state == UB_CMDST_DONE) {
977 (*cmd->done)(sc, cmd);
978 } else if (cmd->state == UB_CMDST_INIT) {
979 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
982 cmd->state = UB_CMDST_DONE;
984 if (!ub_is_completed(&sc->work_done))
986 del_timer(&sc->work_timer);
987 ub_scsi_urb_compl(sc, cmd);
992 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
994 struct urb *urb = &sc->work_urb;
995 struct bulk_cs_wrap *bcs;
999 if (atomic_read(&sc->poison)) {
1000 ub_state_done(sc, cmd, -ENODEV);
1004 if (cmd->state == UB_CMDST_CLEAR) {
1005 if (urb->status == -EPIPE) {
1007 * STALL while clearning STALL.
1008 * The control pipe clears itself - nothing to do.
1010 printk(KERN_NOTICE "%s: stall on control pipe\n",
1016 * We ignore the result for the halt clear.
1019 /* reset the endpoint toggle */
1020 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1021 usb_pipeout(sc->last_pipe), 0);
1023 ub_state_sense(sc, cmd);
1025 } else if (cmd->state == UB_CMDST_CLR2STS) {
1026 if (urb->status == -EPIPE) {
1027 printk(KERN_NOTICE "%s: stall on control pipe\n",
1033 * We ignore the result for the halt clear.
1036 /* reset the endpoint toggle */
1037 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1038 usb_pipeout(sc->last_pipe), 0);
1040 ub_state_stat(sc, cmd);
1042 } else if (cmd->state == UB_CMDST_CLRRS) {
1043 if (urb->status == -EPIPE) {
1044 printk(KERN_NOTICE "%s: stall on control pipe\n",
1050 * We ignore the result for the halt clear.
1053 /* reset the endpoint toggle */
1054 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1055 usb_pipeout(sc->last_pipe), 0);
1057 ub_state_stat_counted(sc, cmd);
1059 } else if (cmd->state == UB_CMDST_CMD) {
1060 switch (urb->status) {
1066 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1068 printk(KERN_NOTICE "%s: "
1069 "unable to submit clear (%d)\n",
1072 * This is typically ENOMEM or some other such shit.
1073 * Retrying is pointless. Just do Bad End on it...
1075 ub_state_done(sc, cmd, rc);
1078 cmd->state = UB_CMDST_CLEAR;
1080 case -ESHUTDOWN: /* unplug */
1081 case -EILSEQ: /* unplug timeout on uhci */
1082 ub_state_done(sc, cmd, -ENODEV);
1087 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1091 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1092 ub_state_stat(sc, cmd);
1096 // udelay(125); // usb-storage has this
1097 ub_data_start(sc, cmd);
1099 } else if (cmd->state == UB_CMDST_DATA) {
1100 if (urb->status == -EPIPE) {
1101 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1103 printk(KERN_NOTICE "%s: "
1104 "unable to submit clear (%d)\n",
1106 ub_state_done(sc, cmd, rc);
1109 cmd->state = UB_CMDST_CLR2STS;
1112 if (urb->status == -EOVERFLOW) {
1114 * A babble? Failure, but we must transfer CSW now.
1116 cmd->error = -EOVERFLOW; /* A cheap trick... */
1117 ub_state_stat(sc, cmd);
1121 if (cmd->dir == UB_DIR_WRITE) {
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.
1127 * We must try to read the CSW, or many devices
1130 len = urb->actual_length;
1131 if (urb->status != 0 ||
1132 len != cmd->sgv[cmd->current_sg].length) {
1133 cmd->act_len += len;
1136 ub_state_stat(sc, cmd);
1142 * If an error occurs on read, we record it, and
1143 * continue to fetch data in order to avoid bubble.
1145 * As a small shortcut, we stop if we detect that
1146 * a CSW mixed into data.
1148 if (urb->status != 0)
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)
1159 cmd->act_len += urb->actual_length;
1161 if (++cmd->current_sg < cmd->nsg) {
1162 ub_data_start(sc, cmd);
1165 ub_state_stat(sc, cmd);
1167 } else if (cmd->state == UB_CMDST_STAT) {
1168 if (urb->status == -EPIPE) {
1169 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1171 printk(KERN_NOTICE "%s: "
1172 "unable to submit clear (%d)\n",
1174 ub_state_done(sc, cmd, rc);
1179 * Having a stall when getting CSW is an error, so
1180 * make sure uppper levels are not oblivious to it.
1182 cmd->error = -EIO; /* A cheap trick... */
1184 cmd->state = UB_CMDST_CLRRS;
1188 /* Catch everything, including -EOVERFLOW and other nasties. */
1189 if (urb->status != 0)
1192 if (urb->actual_length == 0) {
1193 ub_state_stat_counted(sc, cmd);
1198 * Check the returned Bulk protocol status.
1199 * The status block has to be validated first.
1202 bcs = &sc->work_bcs;
1204 if (sc->signature == cpu_to_le32(0)) {
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.
1210 sc->signature = bcs->Signature;
1211 if (sc->signature == cpu_to_le32(0)) {
1212 ub_state_stat_counted(sc, cmd);
1216 if (bcs->Signature != sc->signature) {
1217 ub_state_stat_counted(sc, cmd);
1222 if (bcs->Tag != cmd->tag) {
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.
1230 ub_state_stat_counted(sc, cmd);
1234 len = le32_to_cpu(bcs->Residue);
1235 if (len != cmd->len - cmd->act_len) {
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.
1241 /* P3 */ printk("%s: resid %d len %d act %d\n",
1242 sc->name, len, cmd->len, cmd->act_len);
1246 switch (bcs->Status) {
1247 case US_BULK_STAT_OK:
1249 case US_BULK_STAT_FAIL:
1250 ub_state_sense(sc, cmd);
1252 case US_BULK_STAT_PHASE:
1253 /* P3 */ printk("%s: status PHASE\n", sc->name);
1256 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1257 sc->name, bcs->Status);
1258 ub_state_done(sc, cmd, -EINVAL);
1262 /* Not zeroing error to preserve a babble indicator */
1263 if (cmd->error != 0) {
1264 ub_state_sense(sc, cmd);
1267 cmd->state = UB_CMDST_DONE;
1269 (*cmd->done)(sc, cmd);
1271 } else if (cmd->state == UB_CMDST_SENSE) {
1272 ub_state_done(sc, cmd, -EIO);
1275 printk(KERN_WARNING "%s: "
1276 "wrong command state %d\n",
1277 sc->name, cmd->state);
1278 ub_state_done(sc, cmd, -EINVAL);
1283 Bad_End: /* Little Excel is dead */
1284 ub_state_done(sc, cmd, -EIO);
1288 * Factorization helper for the command state machine:
1289 * Initiate a data segment transfer.
1291 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1293 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1297 UB_INIT_COMPLETION(sc->work_done);
1299 if (cmd->dir == UB_DIR_READ)
1300 pipe = sc->recv_bulk_pipe;
1302 pipe = sc->send_bulk_pipe;
1303 sc->last_pipe = pipe;
1304 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1305 page_address(sg->page) + sg->offset, sg->length,
1306 ub_urb_complete, sc);
1307 sc->work_urb.actual_length = 0;
1308 sc->work_urb.error_count = 0;
1309 sc->work_urb.status = 0;
1311 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1312 /* XXX Clear stalls */
1313 ub_complete(&sc->work_done);
1314 ub_state_done(sc, cmd, rc);
1318 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1319 add_timer(&sc->work_timer);
1321 cmd->state = UB_CMDST_DATA;
1325 * Factorization helper for the command state machine:
1326 * Finish the command.
1328 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1332 cmd->state = UB_CMDST_DONE;
1334 (*cmd->done)(sc, cmd);
1338 * Factorization helper for the command state machine:
1339 * Submit a CSW read.
1341 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1345 UB_INIT_COMPLETION(sc->work_done);
1347 sc->last_pipe = sc->recv_bulk_pipe;
1348 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1349 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1350 sc->work_urb.actual_length = 0;
1351 sc->work_urb.error_count = 0;
1352 sc->work_urb.status = 0;
1354 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1355 /* XXX Clear stalls */
1356 ub_complete(&sc->work_done);
1357 ub_state_done(sc, cmd, rc);
1361 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1362 add_timer(&sc->work_timer);
1367 * Factorization helper for the command state machine:
1368 * Submit a CSW read and go to STAT state.
1370 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1373 if (__ub_state_stat(sc, cmd) != 0)
1376 cmd->stat_count = 0;
1377 cmd->state = UB_CMDST_STAT;
1381 * Factorization helper for the command state machine:
1382 * Submit a CSW read and go to STAT state with counter (along [C] path).
1384 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1387 if (++cmd->stat_count >= 4) {
1388 ub_state_sense(sc, cmd);
1392 if (__ub_state_stat(sc, cmd) != 0)
1395 cmd->state = UB_CMDST_STAT;
1399 * Factorization helper for the command state machine:
1400 * Submit a REQUEST SENSE and go to SENSE state.
1402 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1404 struct ub_scsi_cmd *scmd;
1405 struct scatterlist *sg;
1408 if (cmd->cdb[0] == REQUEST_SENSE) {
1413 scmd = &sc->top_rqs_cmd;
1414 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1415 scmd->cdb[0] = REQUEST_SENSE;
1416 scmd->cdb[4] = UB_SENSE_SIZE;
1418 scmd->dir = UB_DIR_READ;
1419 scmd->state = UB_CMDST_INIT;
1422 sg->page = virt_to_page(sc->top_sense);
1423 sg->offset = (unsigned long)sc->top_sense & (PAGE_SIZE-1);
1424 sg->length = UB_SENSE_SIZE;
1425 scmd->len = UB_SENSE_SIZE;
1426 scmd->lun = cmd->lun;
1427 scmd->done = ub_top_sense_done;
1430 scmd->tag = sc->tagcnt++;
1432 cmd->state = UB_CMDST_SENSE;
1434 ub_cmdq_insert(sc, scmd);
1438 ub_state_done(sc, cmd, rc);
1442 * A helper for the command's state machine:
1443 * Submit a stall clear.
1445 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1449 struct usb_ctrlrequest *cr;
1452 endp = usb_pipeendpoint(stalled_pipe);
1453 if (usb_pipein (stalled_pipe))
1457 cr->bRequestType = USB_RECIP_ENDPOINT;
1458 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1459 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1460 cr->wIndex = cpu_to_le16(endp);
1461 cr->wLength = cpu_to_le16(0);
1463 UB_INIT_COMPLETION(sc->work_done);
1465 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1466 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1467 sc->work_urb.actual_length = 0;
1468 sc->work_urb.error_count = 0;
1469 sc->work_urb.status = 0;
1471 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1472 ub_complete(&sc->work_done);
1476 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1477 add_timer(&sc->work_timer);
1483 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1485 unsigned char *sense = sc->top_sense;
1486 struct ub_scsi_cmd *cmd;
1489 * Find the command which triggered the unit attention or a check,
1490 * save the sense into it, and advance its state machine.
1492 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1493 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1496 if (cmd != scmd->back) {
1497 printk(KERN_WARNING "%s: "
1498 "sense done for wrong command 0x%x\n",
1499 sc->name, cmd->tag);
1502 if (cmd->state != UB_CMDST_SENSE) {
1503 printk(KERN_WARNING "%s: "
1504 "sense done with bad cmd state %d\n",
1505 sc->name, cmd->state);
1510 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1512 cmd->key = sense[2] & 0x0F;
1513 cmd->asc = sense[12];
1514 cmd->ascq = sense[13];
1516 ub_scsi_urb_compl(sc, cmd);
1521 * XXX Move usb_reset_device to khubd. Hogging kevent is not a good thing.
1522 * XXX Make usb_sync_reset asynchronous.
1525 static void ub_reset_enter(struct ub_dev *sc, int try)
1529 /* This happens often on multi-LUN devices. */
1532 sc->reset = try + 1;
1534 #if 0 /* Not needed because the disconnect waits for us. */
1535 unsigned long flags;
1536 spin_lock_irqsave(&ub_lock, flags);
1538 spin_unlock_irqrestore(&ub_lock, flags);
1541 #if 0 /* We let them stop themselves. */
1542 struct list_head *p;
1544 list_for_each(p, &sc->luns) {
1545 lun = list_entry(p, struct ub_lun, link);
1546 blk_stop_queue(lun->disk->queue);
1550 schedule_work(&sc->reset_work);
1553 static void ub_reset_task(void *arg)
1555 struct ub_dev *sc = arg;
1556 unsigned long flags;
1557 struct list_head *p;
1562 printk(KERN_WARNING "%s: Running reset unrequested\n",
1567 if (atomic_read(&sc->poison)) {
1568 printk(KERN_NOTICE "%s: Not resetting disconnected device\n",
1569 sc->name); /* P3 This floods. Remove soon. XXX */
1570 } else if ((sc->reset & 1) == 0) {
1572 msleep(700); /* usb-storage sleeps 6s (!) */
1573 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1574 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1575 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1576 printk(KERN_NOTICE "%s: Not resetting multi-interface device\n",
1577 sc->name); /* P3 This floods. Remove soon. XXX */
1579 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1581 "%s: usb_lock_device_for_reset failed (%d)\n",
1584 rc = usb_reset_device(sc->dev);
1586 printk(KERN_NOTICE "%s: "
1587 "usb_lock_device_for_reset failed (%d)\n",
1592 usb_unlock_device(sc->dev);
1597 * In theory, no commands can be running while reset is active,
1598 * so nobody can ask for another reset, and so we do not need any
1599 * queues of resets or anything. We do need a spinlock though,
1600 * to interact with block layer.
1602 spin_lock_irqsave(sc->lock, flags);
1604 tasklet_schedule(&sc->tasklet);
1605 list_for_each(p, &sc->luns) {
1606 lun = list_entry(p, struct ub_lun, link);
1607 blk_start_queue(lun->disk->queue);
1609 wake_up(&sc->reset_wait);
1610 spin_unlock_irqrestore(sc->lock, flags);
1614 * This is called from a process context.
1616 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1619 lun->readonly = 0; /* XXX Query this from the device */
1621 lun->capacity.nsec = 0;
1622 lun->capacity.bsize = 512;
1623 lun->capacity.bshift = 0;
1625 if (ub_sync_tur(sc, lun) != 0)
1626 return; /* Not ready */
1629 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1631 * The retry here means something is wrong, either with the
1632 * device, with the transport, or with our code.
1633 * We keep this because sd.c has retries for capacity.
1635 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1636 lun->capacity.nsec = 0;
1637 lun->capacity.bsize = 512;
1638 lun->capacity.bshift = 0;
1645 * This is mostly needed to keep refcounting, but also to support
1646 * media checks on removable media drives.
1648 static int ub_bd_open(struct inode *inode, struct file *filp)
1650 struct gendisk *disk = inode->i_bdev->bd_disk;
1653 unsigned long flags;
1656 if ((lun = disk->private_data) == NULL)
1660 spin_lock_irqsave(&ub_lock, flags);
1661 if (atomic_read(&sc->poison)) {
1662 spin_unlock_irqrestore(&ub_lock, flags);
1666 spin_unlock_irqrestore(&ub_lock, flags);
1668 if (lun->removable || lun->readonly)
1669 check_disk_change(inode->i_bdev);
1672 * The sd.c considers ->media_present and ->changed not equivalent,
1673 * under some pretty murky conditions (a failure of READ CAPACITY).
1674 * We may need it one day.
1676 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1681 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1695 static int ub_bd_release(struct inode *inode, struct file *filp)
1697 struct gendisk *disk = inode->i_bdev->bd_disk;
1698 struct ub_lun *lun = disk->private_data;
1699 struct ub_dev *sc = lun->udev;
1706 * The ioctl interface.
1708 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1709 unsigned int cmd, unsigned long arg)
1711 struct gendisk *disk = inode->i_bdev->bd_disk;
1712 void __user *usermem = (void __user *) arg;
1714 return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1718 * This is called once a new disk was seen by the block layer or by ub_probe().
1719 * The main onjective here is to discover the features of the media such as
1720 * the capacity, read-only status, etc. USB storage generally does not
1721 * need to be spun up, but if we needed it, this would be the place.
1723 * This call can sleep.
1725 * The return code is not used.
1727 static int ub_bd_revalidate(struct gendisk *disk)
1729 struct ub_lun *lun = disk->private_data;
1731 ub_revalidate(lun->udev, lun);
1733 /* XXX Support sector size switching like in sr.c */
1734 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1735 set_capacity(disk, lun->capacity.nsec);
1736 // set_disk_ro(sdkp->disk, lun->readonly);
1742 * The check is called by the block layer to verify if the media
1743 * is still available. It is supposed to be harmless, lightweight and
1744 * non-intrusive in case the media was not changed.
1746 * This call can sleep.
1748 * The return code is bool!
1750 static int ub_bd_media_changed(struct gendisk *disk)
1752 struct ub_lun *lun = disk->private_data;
1754 if (!lun->removable)
1758 * We clean checks always after every command, so this is not
1759 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1760 * the device is actually not ready with operator or software
1761 * intervention required. One dangerous item might be a drive which
1762 * spins itself down, and come the time to write dirty pages, this
1763 * will fail, then block layer discards the data. Since we never
1764 * spin drives up, such devices simply cannot be used with ub anyway.
1766 if (ub_sync_tur(lun->udev, lun) != 0) {
1771 return lun->changed;
1774 static struct block_device_operations ub_bd_fops = {
1775 .owner = THIS_MODULE,
1777 .release = ub_bd_release,
1778 .ioctl = ub_bd_ioctl,
1779 .media_changed = ub_bd_media_changed,
1780 .revalidate_disk = ub_bd_revalidate,
1784 * Common ->done routine for commands executed synchronously.
1786 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1788 struct completion *cop = cmd->back;
1793 * Test if the device has a check condition on it, synchronously.
1795 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1797 struct ub_scsi_cmd *cmd;
1798 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1799 unsigned long flags;
1800 struct completion compl;
1803 init_completion(&compl);
1806 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1809 cmd->cdb[0] = TEST_UNIT_READY;
1811 cmd->dir = UB_DIR_NONE;
1812 cmd->state = UB_CMDST_INIT;
1813 cmd->lun = lun; /* This may be NULL, but that's ok */
1814 cmd->done = ub_probe_done;
1817 spin_lock_irqsave(sc->lock, flags);
1818 cmd->tag = sc->tagcnt++;
1820 rc = ub_submit_scsi(sc, cmd);
1821 spin_unlock_irqrestore(sc->lock, flags);
1824 printk("ub: testing ready: submit error (%d)\n", rc); /* P3 */
1828 wait_for_completion(&compl);
1832 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1842 * Read the SCSI capacity synchronously (for probing).
1844 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1845 struct ub_capacity *ret)
1847 struct ub_scsi_cmd *cmd;
1848 struct scatterlist *sg;
1850 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1851 unsigned long flags;
1852 unsigned int bsize, shift;
1854 struct completion compl;
1857 init_completion(&compl);
1860 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1862 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1866 cmd->dir = UB_DIR_READ;
1867 cmd->state = UB_CMDST_INIT;
1870 sg->page = virt_to_page(p);
1871 sg->offset = (unsigned long)p & (PAGE_SIZE-1);
1875 cmd->done = ub_probe_done;
1878 spin_lock_irqsave(sc->lock, flags);
1879 cmd->tag = sc->tagcnt++;
1881 rc = ub_submit_scsi(sc, cmd);
1882 spin_unlock_irqrestore(sc->lock, flags);
1885 printk("ub: reading capacity: submit error (%d)\n", rc); /* P3 */
1889 wait_for_completion(&compl);
1891 if (cmd->error != 0) {
1892 printk("ub: reading capacity: error %d\n", cmd->error); /* P3 */
1896 if (cmd->act_len != 8) {
1897 printk("ub: reading capacity: size %d\n", cmd->act_len); /* P3 */
1902 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1903 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1904 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1906 case 512: shift = 0; break;
1907 case 1024: shift = 1; break;
1908 case 2048: shift = 2; break;
1909 case 4096: shift = 3; break;
1911 printk("ub: Bad sector size %u\n", bsize); /* P3 */
1917 ret->bshift = shift;
1918 ret->nsec = nsec << shift;
1931 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
1933 struct completion *cop = urb->context;
1937 static void ub_probe_timeout(unsigned long arg)
1939 struct completion *cop = (struct completion *) arg;
1944 * Reset with a Bulk reset.
1946 static int ub_sync_reset(struct ub_dev *sc)
1948 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1949 struct usb_ctrlrequest *cr;
1950 struct completion compl;
1951 struct timer_list timer;
1954 init_completion(&compl);
1957 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1958 cr->bRequest = US_BULK_RESET_REQUEST;
1959 cr->wValue = cpu_to_le16(0);
1960 cr->wIndex = cpu_to_le16(ifnum);
1961 cr->wLength = cpu_to_le16(0);
1963 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1964 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1965 sc->work_urb.actual_length = 0;
1966 sc->work_urb.error_count = 0;
1967 sc->work_urb.status = 0;
1969 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1971 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1976 timer.function = ub_probe_timeout;
1977 timer.data = (unsigned long) &compl;
1978 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1981 wait_for_completion(&compl);
1983 del_timer_sync(&timer);
1984 usb_kill_urb(&sc->work_urb);
1986 return sc->work_urb.status;
1990 * Get number of LUNs by the way of Bulk GetMaxLUN command.
1992 static int ub_sync_getmaxlun(struct ub_dev *sc)
1994 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1996 enum { ALLOC_SIZE = 1 };
1997 struct usb_ctrlrequest *cr;
1998 struct completion compl;
1999 struct timer_list timer;
2003 init_completion(&compl);
2006 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
2011 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2012 cr->bRequest = US_BULK_GET_MAX_LUN;
2013 cr->wValue = cpu_to_le16(0);
2014 cr->wIndex = cpu_to_le16(ifnum);
2015 cr->wLength = cpu_to_le16(1);
2017 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2018 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2019 sc->work_urb.actual_length = 0;
2020 sc->work_urb.error_count = 0;
2021 sc->work_urb.status = 0;
2023 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2025 printk("%s: Stall submitting GetMaxLUN, using 1 LUN\n",
2029 "%s: Unable to submit GetMaxLUN (%d)\n",
2036 timer.function = ub_probe_timeout;
2037 timer.data = (unsigned long) &compl;
2038 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2041 wait_for_completion(&compl);
2043 del_timer_sync(&timer);
2044 usb_kill_urb(&sc->work_urb);
2046 if ((rc = sc->work_urb.status) < 0) {
2048 printk("%s: Stall at GetMaxLUN, using 1 LUN\n",
2052 "%s: Error at GetMaxLUN (%d)\n",
2058 if (sc->work_urb.actual_length != 1) {
2059 printk("%s: GetMaxLUN returned %d bytes\n", sc->name,
2060 sc->work_urb.actual_length); /* P3 */
2063 if ((nluns = *p) == 55) {
2066 /* GetMaxLUN returns the maximum LUN number */
2068 if (nluns > UB_MAX_LUNS)
2069 nluns = UB_MAX_LUNS;
2071 printk("%s: GetMaxLUN returned %d, using %d LUNs\n", sc->name,
2072 *p, nluns); /* P3 */
2086 * Clear initial stalls.
2088 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2091 struct usb_ctrlrequest *cr;
2092 struct completion compl;
2093 struct timer_list timer;
2096 init_completion(&compl);
2098 endp = usb_pipeendpoint(stalled_pipe);
2099 if (usb_pipein (stalled_pipe))
2103 cr->bRequestType = USB_RECIP_ENDPOINT;
2104 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2105 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2106 cr->wIndex = cpu_to_le16(endp);
2107 cr->wLength = cpu_to_le16(0);
2109 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2110 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2111 sc->work_urb.actual_length = 0;
2112 sc->work_urb.error_count = 0;
2113 sc->work_urb.status = 0;
2115 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2117 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2122 timer.function = ub_probe_timeout;
2123 timer.data = (unsigned long) &compl;
2124 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2127 wait_for_completion(&compl);
2129 del_timer_sync(&timer);
2130 usb_kill_urb(&sc->work_urb);
2132 /* reset the endpoint toggle */
2133 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2139 * Get the pipe settings.
2141 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2142 struct usb_interface *intf)
2144 struct usb_host_interface *altsetting = intf->cur_altsetting;
2145 struct usb_endpoint_descriptor *ep_in = NULL;
2146 struct usb_endpoint_descriptor *ep_out = NULL;
2147 struct usb_endpoint_descriptor *ep;
2151 * Find the endpoints we need.
2152 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2153 * We will ignore any others.
2155 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2156 ep = &altsetting->endpoint[i].desc;
2158 /* Is it a BULK endpoint? */
2159 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2160 == USB_ENDPOINT_XFER_BULK) {
2161 /* BULK in or out? */
2162 if (ep->bEndpointAddress & USB_DIR_IN)
2169 if (ep_in == NULL || ep_out == NULL) {
2170 printk(KERN_NOTICE "%s: failed endpoint check\n",
2175 /* Calculate and store the pipe values */
2176 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2177 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2178 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2179 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2180 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2181 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2187 * Probing is done in the process context, which allows us to cheat
2188 * and not to build a state machine for the discovery.
2190 static int ub_probe(struct usb_interface *intf,
2191 const struct usb_device_id *dev_id)
2198 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2202 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2204 sc->lock = ub_next_lock();
2205 INIT_LIST_HEAD(&sc->luns);
2206 usb_init_urb(&sc->work_urb);
2207 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2208 atomic_set(&sc->poison, 0);
2209 INIT_WORK(&sc->reset_work, ub_reset_task, sc);
2210 init_waitqueue_head(&sc->reset_wait);
2212 init_timer(&sc->work_timer);
2213 sc->work_timer.data = (unsigned long) sc;
2214 sc->work_timer.function = ub_urb_timeout;
2216 ub_init_completion(&sc->work_done);
2217 sc->work_done.done = 1; /* A little yuk, but oh well... */
2219 sc->dev = interface_to_usbdev(intf);
2221 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2222 usb_set_intfdata(intf, sc);
2223 usb_get_dev(sc->dev);
2224 // usb_get_intf(sc->intf); /* Do we need this? */
2226 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2227 sc->dev->bus->busnum, sc->dev->devnum);
2229 /* XXX Verify that we can handle the device (from descriptors) */
2231 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2235 * At this point, all USB initialization is done, do upper layer.
2236 * We really hate halfway initialized structures, so from the
2237 * invariants perspective, this ub_dev is fully constructed at
2242 * This is needed to clear toggles. It is a problem only if we do
2243 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2245 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2246 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2247 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2251 * The way this is used by the startup code is a little specific.
2252 * A SCSI check causes a USB stall. Our common case code sees it
2253 * and clears the check, after which the device is ready for use.
2254 * But if a check was not present, any command other than
2255 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2257 * If we neglect to clear the SCSI check, the first real command fails
2258 * (which is the capacity readout). We clear that and retry, but why
2259 * causing spurious retries for no reason.
2261 * Revalidation may start with its own TEST_UNIT_READY, but that one
2262 * has to succeed, so we clear checks with an additional one here.
2263 * In any case it's not our business how revaliadation is implemented.
2265 for (i = 0; i < 3; i++) { /* Retries for benh's key */
2266 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2267 if (rc != 0x6) break;
2272 for (i = 0; i < 3; i++) {
2273 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2282 for (i = 0; i < nluns; i++) {
2283 ub_probe_lun(sc, i);
2288 usb_set_intfdata(intf, NULL);
2289 // usb_put_intf(sc->intf);
2290 usb_put_dev(sc->dev);
2296 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2300 struct gendisk *disk;
2304 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2309 if ((lun->id = ub_id_get()) == -1)
2313 list_add(&lun->link, &sc->luns);
2315 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2316 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2318 lun->removable = 1; /* XXX Query this from the device */
2319 lun->changed = 1; /* ub_revalidate clears only */
2320 ub_revalidate(sc, lun);
2323 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2327 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2328 sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2329 disk->major = UB_MAJOR;
2330 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2331 disk->fops = &ub_bd_fops;
2332 disk->private_data = lun;
2333 disk->driverfs_dev = &sc->intf->dev;
2336 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2341 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2342 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2343 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2344 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2345 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2346 blk_queue_hardsect_size(q, lun->capacity.bsize);
2350 set_capacity(disk, lun->capacity.nsec);
2352 disk->flags |= GENHD_FL_REMOVABLE;
2361 list_del(&lun->link);
2369 static void ub_disconnect(struct usb_interface *intf)
2371 struct ub_dev *sc = usb_get_intfdata(intf);
2372 struct list_head *p;
2374 struct gendisk *disk;
2375 unsigned long flags;
2378 * Prevent ub_bd_release from pulling the rug from under us.
2379 * XXX This is starting to look like a kref.
2380 * XXX Why not to take this ref at probe time?
2382 spin_lock_irqsave(&ub_lock, flags);
2384 spin_unlock_irqrestore(&ub_lock, flags);
2387 * Fence stall clearnings, operations triggered by unlinkings and so on.
2388 * We do not attempt to unlink any URBs, because we do not trust the
2389 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2391 atomic_set(&sc->poison, 1);
2394 * Wait for reset to end, if any.
2396 wait_event(sc->reset_wait, !sc->reset);
2399 * Blow away queued commands.
2401 * Actually, this never works, because before we get here
2402 * the HCD terminates outstanding URB(s). It causes our
2403 * SCSI command queue to advance, commands fail to submit,
2404 * and the whole queue drains. So, we just use this code to
2407 spin_lock_irqsave(sc->lock, flags);
2409 struct ub_scsi_cmd *cmd;
2411 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2412 cmd->error = -ENOTCONN;
2413 cmd->state = UB_CMDST_DONE;
2415 (*cmd->done)(sc, cmd);
2419 printk(KERN_WARNING "%s: "
2420 "%d was queued after shutdown\n", sc->name, cnt);
2423 spin_unlock_irqrestore(sc->lock, flags);
2426 * Unregister the upper layer.
2428 list_for_each (p, &sc->luns) {
2429 lun = list_entry(p, struct ub_lun, link);
2431 if (disk->flags & GENHD_FL_UP)
2434 * I wish I could do:
2435 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2436 * As it is, we rely on our internal poisoning and let
2437 * the upper levels to spin furiously failing all the I/O.
2442 * Testing for -EINPROGRESS is always a bug, so we are bending
2443 * the rules a little.
2445 spin_lock_irqsave(sc->lock, flags);
2446 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2447 printk(KERN_WARNING "%s: "
2448 "URB is active after disconnect\n", sc->name);
2450 spin_unlock_irqrestore(sc->lock, flags);
2453 * There is virtually no chance that other CPU runs times so long
2454 * after ub_urb_complete should have called del_timer, but only if HCD
2455 * didn't forget to deliver a callback on unlink.
2457 del_timer_sync(&sc->work_timer);
2460 * At this point there must be no commands coming from anyone
2461 * and no URBs left in transit.
2464 usb_set_intfdata(intf, NULL);
2465 // usb_put_intf(sc->intf);
2467 usb_put_dev(sc->dev);
2473 static struct usb_driver ub_driver = {
2476 .disconnect = ub_disconnect,
2477 .id_table = ub_usb_ids,
2480 static int __init ub_init(void)
2485 for (i = 0; i < UB_QLOCK_NUM; i++)
2486 spin_lock_init(&ub_qlockv[i]);
2488 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2490 devfs_mk_dir(DEVFS_NAME);
2492 if ((rc = usb_register(&ub_driver)) != 0)
2495 usb_usual_set_present(USB_US_TYPE_UB);
2499 devfs_remove(DEVFS_NAME);
2500 unregister_blkdev(UB_MAJOR, DRV_NAME);
2505 static void __exit ub_exit(void)
2507 usb_deregister(&ub_driver);
2509 devfs_remove(DEVFS_NAME);
2510 unregister_blkdev(UB_MAJOR, DRV_NAME);
2511 usb_usual_clear_present(USB_US_TYPE_UB);
2514 module_init(ub_init);
2515 module_exit(ub_exit);
2517 MODULE_LICENSE("GPL");