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 * -- verify the 13 conditions and do bulk resets
15 * -- move top_sense and work_bcs into separate allocations (if they survive)
16 * for cache purists and esoteric architectures.
17 * -- Allocate structure for LUN 0 before the first ub_sync_tur, avoid NULL. ?
18 * -- prune comments, they are too volumnous
20 * -- CLEAR, CLR2STS, CLRRS seem to be ripe for refactoring.
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/usb.h>
25 #include <linux/usb_usual.h>
26 #include <linux/blkdev.h>
27 #include <linux/devfs_fs_kernel.h>
28 #include <linux/timer.h>
29 #include <scsi/scsi.h>
32 #define DEVFS_NAME DRV_NAME
37 * The command state machine is the key model for understanding of this driver.
39 * The general rule is that all transitions are done towards the bottom
40 * of the diagram, thus preventing any loops.
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].
49 * ub_scsi_cmd_start fails ->--------------------------------------\
56 * was -EPIPE -->-------------------------------->! CLEAR ! !
59 * was error -->------------------------------------- ! --------->\
61 * /--<-- cmd->dir == NONE ? ! !
68 * ! was -EPIPE -->--------------->! CLR2STS ! ! !
71 * ! ! was error -->---- ! --------->\
72 * ! was error -->--------------------- ! ------------- ! --------->\
75 * \--->+--------+ ! ! !
76 * ! STAT !<--------------------------/ ! !
79 * [C] was -EPIPE -->-----------\ ! !
81 * +<---- len == 0 ! ! !
83 * ! was error -->--------------------------------------!---------->\
85 * +<---- bad CSW ! ! !
86 * +<---- bad tag ! ! !
92 * \------- ! --------------------[C]--------\ ! !
94 * cmd->error---\ +--------+ ! !
95 * ! +--------------->! SENSE !<----------/ !
96 * STAT_FAIL----/ +--------+ !
99 * \--------------------------------\--------------------->! DONE !
104 * This many LUNs per USB device.
105 * Every one of them takes a host, see UB_MAX_HOSTS.
107 #define UB_MAX_LUNS 9
112 #define UB_PARTS_PER_LUN 8
114 #define UB_MAX_CDB_SIZE 16 /* Corresponds to Bulk */
116 #define UB_SENSE_SIZE 18
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 */
128 u8 Length; /* of of the CDB */
129 u8 CDB[UB_MAX_CDB_SIZE]; /* max command */
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
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 */
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
151 /* bulk-only class specific requests */
152 #define US_BULK_RESET_REQUEST 0xff
153 #define US_BULK_GET_MAX_LUN 0xfe
159 #define UB_MAX_REQ_SG 9 /* cdrecord requires 32KB and maybe a header */
160 #define UB_MAX_SECTORS 64
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.
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 */
172 * An instance of a SCSI command in transit.
174 #define UB_DIR_NONE 0
175 #define UB_DIR_READ 1
176 #define UB_DIR_ILLEGAL2 2
177 #define UB_DIR_WRITE 3
179 #define UB_DIR_CHAR(c) (((c)==UB_DIR_WRITE)? 'w': \
180 (((c)==UB_DIR_READ)? 'r': 'n'))
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 */
195 unsigned char cdb[UB_MAX_CDB_SIZE];
196 unsigned char cdb_len;
198 unsigned char dir; /* 0 - none, 1 - read, 3 - write. */
199 enum ub_scsi_cmd_state state;
201 struct ub_scsi_cmd *next;
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 */
207 int stat_count; /* Retries getting status. */
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];
215 void (*done)(struct ub_dev *, struct ub_scsi_cmd *);
221 unsigned int current_try;
222 unsigned int nsg; /* sgv[nsg] */
223 struct scatterlist sgv[UB_MAX_REQ_SG];
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 */
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.
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.
243 struct ub_completion {
248 static inline void ub_init_completion(struct ub_completion *x)
251 spin_lock_init(&x->lock);
254 #define UB_INIT_COMPLETION(x) ((x).done = 0)
256 static void ub_complete(struct ub_completion *x)
260 spin_lock_irqsave(&x->lock, flags);
262 spin_unlock_irqrestore(&x->lock, flags);
265 static int ub_is_completed(struct ub_completion *x)
270 spin_lock_irqsave(&x->lock, flags);
272 spin_unlock_irqrestore(&x->lock, flags);
278 struct ub_scsi_cmd_queue {
280 struct ub_scsi_cmd *head, *tail;
284 * The block device instance (one per LUN).
288 struct list_head link;
289 struct gendisk *disk;
290 int id; /* Host index */
291 int num; /* LUN number */
294 int changed; /* Media was changed */
298 struct ub_request urq;
300 /* Use Ingo's mempool if or when we have more than one command. */
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.
307 struct ub_scsi_cmd cmdv[1];
309 struct ub_capacity capacity;
313 * The USB device instance.
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 */
323 struct usb_device *dev;
324 struct usb_interface *intf;
326 struct list_head luns;
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;
333 struct tasklet_struct tasklet;
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];
339 struct ub_completion work_done;
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;
348 struct work_struct reset_work;
349 wait_queue_head_t reset_wait;
356 static void ub_cleanup(struct ub_dev *sc);
357 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq);
358 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
359 struct ub_scsi_cmd *cmd, struct ub_request *urq);
360 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
361 struct ub_scsi_cmd *cmd, struct ub_request *urq);
362 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
363 static void ub_end_rq(struct request *rq, int uptodate);
364 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
365 struct ub_request *urq, struct ub_scsi_cmd *cmd);
366 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
367 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt);
368 static void ub_scsi_action(unsigned long _dev);
369 static void ub_scsi_dispatch(struct ub_dev *sc);
370 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
371 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
372 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc);
373 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
374 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
375 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
376 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd);
377 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
379 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd);
380 static void ub_reset_enter(struct ub_dev *sc, int try);
381 static void ub_reset_task(void *arg);
382 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun);
383 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
384 struct ub_capacity *ret);
385 static int ub_sync_reset(struct ub_dev *sc);
386 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe);
387 static int ub_probe_lun(struct ub_dev *sc, int lnum);
391 #ifdef CONFIG_USB_LIBUSUAL
393 #define ub_usb_ids storage_usb_ids
396 static struct usb_device_id ub_usb_ids[] = {
397 { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, US_SC_SCSI, US_PR_BULK) },
401 MODULE_DEVICE_TABLE(usb, ub_usb_ids);
402 #endif /* CONFIG_USB_LIBUSUAL */
405 * Find me a way to identify "next free minor" for add_disk(),
406 * and the array disappears the next day. However, the number of
407 * hosts has something to do with the naming and /proc/partitions.
408 * This has to be thought out in detail before changing.
409 * If UB_MAX_HOST was 1000, we'd use a bitmap. Or a better data structure.
411 #define UB_MAX_HOSTS 26
412 static char ub_hostv[UB_MAX_HOSTS];
414 #define UB_QLOCK_NUM 5
415 static spinlock_t ub_qlockv[UB_QLOCK_NUM];
416 static int ub_qlock_next = 0;
418 static DEFINE_SPINLOCK(ub_lock); /* Locks globals and ->openc */
423 * This also stores the host for indexing by minor, which is somewhat dirty.
425 static int ub_id_get(void)
430 spin_lock_irqsave(&ub_lock, flags);
431 for (i = 0; i < UB_MAX_HOSTS; i++) {
432 if (ub_hostv[i] == 0) {
434 spin_unlock_irqrestore(&ub_lock, flags);
438 spin_unlock_irqrestore(&ub_lock, flags);
442 static void ub_id_put(int id)
446 if (id < 0 || id >= UB_MAX_HOSTS) {
447 printk(KERN_ERR DRV_NAME ": bad host ID %d\n", id);
451 spin_lock_irqsave(&ub_lock, flags);
452 if (ub_hostv[id] == 0) {
453 spin_unlock_irqrestore(&ub_lock, flags);
454 printk(KERN_ERR DRV_NAME ": freeing free host ID %d\n", id);
458 spin_unlock_irqrestore(&ub_lock, flags);
462 * This is necessitated by the fact that blk_cleanup_queue does not
463 * necesserily destroy the queue. Instead, it may merely decrease q->refcnt.
464 * Since our blk_init_queue() passes a spinlock common with ub_dev,
465 * we have life time issues when ub_cleanup frees ub_dev.
467 static spinlock_t *ub_next_lock(void)
472 spin_lock_irqsave(&ub_lock, flags);
473 ret = &ub_qlockv[ub_qlock_next];
474 ub_qlock_next = (ub_qlock_next + 1) % UB_QLOCK_NUM;
475 spin_unlock_irqrestore(&ub_lock, flags);
480 * Downcount for deallocation. This rides on two assumptions:
481 * - once something is poisoned, its refcount cannot grow
482 * - opens cannot happen at this time (del_gendisk was done)
483 * If the above is true, we can drop the lock, which we need for
484 * blk_cleanup_queue(): the silly thing may attempt to sleep.
485 * [Actually, it never needs to sleep for us, but it calls might_sleep()]
487 static void ub_put(struct ub_dev *sc)
491 spin_lock_irqsave(&ub_lock, flags);
493 if (sc->openc == 0 && atomic_read(&sc->poison)) {
494 spin_unlock_irqrestore(&ub_lock, flags);
497 spin_unlock_irqrestore(&ub_lock, flags);
502 * Final cleanup and deallocation.
504 static void ub_cleanup(struct ub_dev *sc)
510 while (!list_empty(&sc->luns)) {
512 lun = list_entry(p, struct ub_lun, link);
515 /* I don't think queue can be NULL. But... Stolen from sx8.c */
516 if ((q = lun->disk->queue) != NULL)
517 blk_cleanup_queue(q);
519 * If we zero disk->private_data BEFORE put_disk, we have
520 * to check for NULL all over the place in open, release,
521 * check_media and revalidate, because the block level
522 * semaphore is well inside the put_disk.
523 * But we cannot zero after the call, because *disk is gone.
524 * The sd.c is blatantly racy in this area.
526 /* disk->private_data = NULL; */
534 usb_set_intfdata(sc->intf, NULL);
535 usb_put_intf(sc->intf);
536 usb_put_dev(sc->dev);
541 * The "command allocator".
543 static struct ub_scsi_cmd *ub_get_cmd(struct ub_lun *lun)
545 struct ub_scsi_cmd *ret;
554 static void ub_put_cmd(struct ub_lun *lun, struct ub_scsi_cmd *cmd)
556 if (cmd != &lun->cmdv[0]) {
557 printk(KERN_WARNING "%s: releasing a foreign cmd %p\n",
562 printk(KERN_WARNING "%s: releasing a free cmd\n", lun->name);
571 static void ub_cmdq_add(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
573 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
575 if (t->qlen++ == 0) {
583 if (t->qlen > t->qmax)
587 static void ub_cmdq_insert(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
589 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
591 if (t->qlen++ == 0) {
599 if (t->qlen > t->qmax)
603 static struct ub_scsi_cmd *ub_cmdq_pop(struct ub_dev *sc)
605 struct ub_scsi_cmd_queue *t = &sc->cmd_queue;
606 struct ub_scsi_cmd *cmd;
618 #define ub_cmdq_peek(sc) ((sc)->cmd_queue.head)
621 * The request function is our main entry point
624 static void ub_request_fn(request_queue_t *q)
626 struct ub_lun *lun = q->queuedata;
629 while ((rq = elv_next_request(q)) != NULL) {
630 if (ub_request_fn_1(lun, rq) != 0) {
637 static int ub_request_fn_1(struct ub_lun *lun, struct request *rq)
639 struct ub_dev *sc = lun->udev;
640 struct ub_scsi_cmd *cmd;
641 struct ub_request *urq;
644 if (atomic_read(&sc->poison) || lun->changed) {
645 blkdev_dequeue_request(rq);
650 if (lun->urq.rq != NULL)
652 if ((cmd = ub_get_cmd(lun)) == NULL)
654 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
656 blkdev_dequeue_request(rq);
659 memset(urq, 0, sizeof(struct ub_request));
663 * get scatterlist from block layer
665 n_elem = blk_rq_map_sg(lun->disk->queue, rq, &urq->sgv[0]);
667 /* Impossible, because blk_rq_map_sg should not hit ENOMEM. */
668 printk(KERN_INFO "%s: failed request map (%d)\n",
672 if (n_elem > UB_MAX_REQ_SG) { /* Paranoia */
673 printk(KERN_WARNING "%s: request with %d segments\n",
678 sc->sg_stat[n_elem < 5 ? n_elem : 5]++;
680 if (blk_pc_request(rq)) {
681 ub_cmd_build_packet(sc, lun, cmd, urq);
683 ub_cmd_build_block(sc, lun, cmd, urq);
685 cmd->state = UB_CMDST_INIT;
687 cmd->done = ub_rw_cmd_done;
690 cmd->tag = sc->tagcnt++;
691 if (ub_submit_scsi(sc, cmd) != 0)
697 ub_put_cmd(lun, cmd);
702 static void ub_cmd_build_block(struct ub_dev *sc, struct ub_lun *lun,
703 struct ub_scsi_cmd *cmd, struct ub_request *urq)
705 struct request *rq = urq->rq;
706 unsigned int block, nblks;
708 if (rq_data_dir(rq) == WRITE)
709 cmd->dir = UB_DIR_WRITE;
711 cmd->dir = UB_DIR_READ;
714 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
719 * The call to blk_queue_hardsect_size() guarantees that request
720 * is aligned, but it is given in terms of 512 byte units, always.
722 block = rq->sector >> lun->capacity.bshift;
723 nblks = rq->nr_sectors >> lun->capacity.bshift;
725 cmd->cdb[0] = (cmd->dir == UB_DIR_READ)? READ_10: WRITE_10;
726 /* 10-byte uses 4 bytes of LBA: 2147483648KB, 2097152MB, 2048GB */
727 cmd->cdb[2] = block >> 24;
728 cmd->cdb[3] = block >> 16;
729 cmd->cdb[4] = block >> 8;
731 cmd->cdb[7] = nblks >> 8;
735 cmd->len = rq->nr_sectors * 512;
738 static void ub_cmd_build_packet(struct ub_dev *sc, struct ub_lun *lun,
739 struct ub_scsi_cmd *cmd, struct ub_request *urq)
741 struct request *rq = urq->rq;
743 if (rq->data_len == 0) {
744 cmd->dir = UB_DIR_NONE;
746 if (rq_data_dir(rq) == WRITE)
747 cmd->dir = UB_DIR_WRITE;
749 cmd->dir = UB_DIR_READ;
753 memcpy(cmd->sgv, urq->sgv, sizeof(struct scatterlist) * cmd->nsg);
755 memcpy(&cmd->cdb, rq->cmd, rq->cmd_len);
756 cmd->cdb_len = rq->cmd_len;
758 cmd->len = rq->data_len;
761 static void ub_rw_cmd_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
763 struct ub_lun *lun = cmd->lun;
764 struct ub_request *urq = cmd->back;
770 if (cmd->error == 0) {
773 if (blk_pc_request(rq)) {
774 if (cmd->act_len >= rq->data_len)
777 rq->data_len -= cmd->act_len;
782 if (blk_pc_request(rq)) {
783 /* UB_SENSE_SIZE is smaller than SCSI_SENSE_BUFFERSIZE */
784 memcpy(rq->sense, sc->top_sense, UB_SENSE_SIZE);
785 rq->sense_len = UB_SENSE_SIZE;
786 if (sc->top_sense[0] != 0)
787 rq->errors = SAM_STAT_CHECK_CONDITION;
789 rq->errors = DID_ERROR << 16;
791 if (cmd->error == -EIO) {
792 if (ub_rw_cmd_retry(sc, lun, urq, cmd) == 0)
800 ub_put_cmd(lun, cmd);
801 ub_end_rq(rq, uptodate);
802 blk_start_queue(lun->disk->queue);
805 static void ub_end_rq(struct request *rq, int uptodate)
807 end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
808 end_that_request_last(rq, uptodate);
811 static int ub_rw_cmd_retry(struct ub_dev *sc, struct ub_lun *lun,
812 struct ub_request *urq, struct ub_scsi_cmd *cmd)
815 if (atomic_read(&sc->poison))
818 ub_reset_enter(sc, urq->current_try);
820 if (urq->current_try >= 3)
824 /* Remove this if anyone complains of flooding. */
825 printk(KERN_DEBUG "%s: dir %c len/act %d/%d "
826 "[sense %x %02x %02x] retry %d\n",
827 sc->name, UB_DIR_CHAR(cmd->dir), cmd->len, cmd->act_len,
828 cmd->key, cmd->asc, cmd->ascq, urq->current_try);
830 memset(cmd, 0, sizeof(struct ub_scsi_cmd));
831 ub_cmd_build_block(sc, lun, cmd, urq);
833 cmd->state = UB_CMDST_INIT;
835 cmd->done = ub_rw_cmd_done;
838 cmd->tag = sc->tagcnt++;
841 return ub_submit_scsi(sc, cmd);
843 ub_cmdq_add(sc, cmd);
849 * Submit a regular SCSI operation (not an auto-sense).
851 * The Iron Law of Good Submit Routine is:
852 * Zero return - callback is done, Nonzero return - callback is not done.
855 * Host is assumed locked.
857 static int ub_submit_scsi(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
860 if (cmd->state != UB_CMDST_INIT ||
861 (cmd->dir != UB_DIR_NONE && cmd->len == 0)) {
865 ub_cmdq_add(sc, cmd);
867 * We can call ub_scsi_dispatch(sc) right away here, but it's a little
868 * safer to jump to a tasklet, in case upper layers do something silly.
870 tasklet_schedule(&sc->tasklet);
875 * Submit the first URB for the queued command.
876 * This function does not deal with queueing in any way.
878 static int ub_scsi_cmd_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
880 struct bulk_cb_wrap *bcb;
886 * ``If the allocation length is eighteen or greater, and a device
887 * server returns less than eithteen bytes of data, the application
888 * client should assume that the bytes not transferred would have been
889 * zeroes had the device server returned those bytes.''
891 * We zero sense for all commands so that when a packet request
892 * fails it does not return a stale sense.
894 memset(&sc->top_sense, 0, UB_SENSE_SIZE);
896 /* set up the command wrapper */
897 bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
898 bcb->Tag = cmd->tag; /* Endianness is not important */
899 bcb->DataTransferLength = cpu_to_le32(cmd->len);
900 bcb->Flags = (cmd->dir == UB_DIR_READ) ? 0x80 : 0;
901 bcb->Lun = (cmd->lun != NULL) ? cmd->lun->num : 0;
902 bcb->Length = cmd->cdb_len;
904 /* copy the command payload */
905 memcpy(bcb->CDB, cmd->cdb, UB_MAX_CDB_SIZE);
907 UB_INIT_COMPLETION(sc->work_done);
909 sc->last_pipe = sc->send_bulk_pipe;
910 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->send_bulk_pipe,
911 bcb, US_BULK_CB_WRAP_LEN, ub_urb_complete, sc);
913 /* Fill what we shouldn't be filling, because usb-storage did so. */
914 sc->work_urb.actual_length = 0;
915 sc->work_urb.error_count = 0;
916 sc->work_urb.status = 0;
918 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
919 /* XXX Clear stalls */
920 ub_complete(&sc->work_done);
924 sc->work_timer.expires = jiffies + UB_URB_TIMEOUT;
925 add_timer(&sc->work_timer);
927 cmd->state = UB_CMDST_CMD;
934 static void ub_urb_timeout(unsigned long arg)
936 struct ub_dev *sc = (struct ub_dev *) arg;
939 spin_lock_irqsave(sc->lock, flags);
940 if (!ub_is_completed(&sc->work_done))
941 usb_unlink_urb(&sc->work_urb);
942 spin_unlock_irqrestore(sc->lock, flags);
946 * Completion routine for the work URB.
948 * This can be called directly from usb_submit_urb (while we have
949 * the sc->lock taken) and from an interrupt (while we do NOT have
950 * the sc->lock taken). Therefore, bounce this off to a tasklet.
952 static void ub_urb_complete(struct urb *urb, struct pt_regs *pt)
954 struct ub_dev *sc = urb->context;
956 ub_complete(&sc->work_done);
957 tasklet_schedule(&sc->tasklet);
960 static void ub_scsi_action(unsigned long _dev)
962 struct ub_dev *sc = (struct ub_dev *) _dev;
965 spin_lock_irqsave(sc->lock, flags);
966 ub_scsi_dispatch(sc);
967 spin_unlock_irqrestore(sc->lock, flags);
970 static void ub_scsi_dispatch(struct ub_dev *sc)
972 struct ub_scsi_cmd *cmd;
975 while (!sc->reset && (cmd = ub_cmdq_peek(sc)) != NULL) {
976 if (cmd->state == UB_CMDST_DONE) {
978 (*cmd->done)(sc, cmd);
979 } else if (cmd->state == UB_CMDST_INIT) {
980 if ((rc = ub_scsi_cmd_start(sc, cmd)) == 0)
983 cmd->state = UB_CMDST_DONE;
985 if (!ub_is_completed(&sc->work_done))
987 del_timer(&sc->work_timer);
988 ub_scsi_urb_compl(sc, cmd);
993 static void ub_scsi_urb_compl(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
995 struct urb *urb = &sc->work_urb;
996 struct bulk_cs_wrap *bcs;
1000 if (atomic_read(&sc->poison)) {
1001 ub_state_done(sc, cmd, -ENODEV);
1005 if (cmd->state == UB_CMDST_CLEAR) {
1006 if (urb->status == -EPIPE) {
1008 * STALL while clearning STALL.
1009 * The control pipe clears itself - nothing to do.
1011 printk(KERN_NOTICE "%s: stall on control pipe\n",
1017 * We ignore the result for the halt clear.
1020 /* reset the endpoint toggle */
1021 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1022 usb_pipeout(sc->last_pipe), 0);
1024 ub_state_sense(sc, cmd);
1026 } else if (cmd->state == UB_CMDST_CLR2STS) {
1027 if (urb->status == -EPIPE) {
1028 printk(KERN_NOTICE "%s: stall on control pipe\n",
1034 * We ignore the result for the halt clear.
1037 /* reset the endpoint toggle */
1038 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1039 usb_pipeout(sc->last_pipe), 0);
1041 ub_state_stat(sc, cmd);
1043 } else if (cmd->state == UB_CMDST_CLRRS) {
1044 if (urb->status == -EPIPE) {
1045 printk(KERN_NOTICE "%s: stall on control pipe\n",
1051 * We ignore the result for the halt clear.
1054 /* reset the endpoint toggle */
1055 usb_settoggle(sc->dev, usb_pipeendpoint(sc->last_pipe),
1056 usb_pipeout(sc->last_pipe), 0);
1058 ub_state_stat_counted(sc, cmd);
1060 } else if (cmd->state == UB_CMDST_CMD) {
1061 switch (urb->status) {
1067 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1069 printk(KERN_NOTICE "%s: "
1070 "unable to submit clear (%d)\n",
1073 * This is typically ENOMEM or some other such shit.
1074 * Retrying is pointless. Just do Bad End on it...
1076 ub_state_done(sc, cmd, rc);
1079 cmd->state = UB_CMDST_CLEAR;
1081 case -ESHUTDOWN: /* unplug */
1082 case -EILSEQ: /* unplug timeout on uhci */
1083 ub_state_done(sc, cmd, -ENODEV);
1088 if (urb->actual_length != US_BULK_CB_WRAP_LEN) {
1092 if (cmd->dir == UB_DIR_NONE || cmd->nsg < 1) {
1093 ub_state_stat(sc, cmd);
1097 // udelay(125); // usb-storage has this
1098 ub_data_start(sc, cmd);
1100 } else if (cmd->state == UB_CMDST_DATA) {
1101 if (urb->status == -EPIPE) {
1102 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1104 printk(KERN_NOTICE "%s: "
1105 "unable to submit clear (%d)\n",
1107 ub_state_done(sc, cmd, rc);
1110 cmd->state = UB_CMDST_CLR2STS;
1113 if (urb->status == -EOVERFLOW) {
1115 * A babble? Failure, but we must transfer CSW now.
1117 cmd->error = -EOVERFLOW; /* A cheap trick... */
1118 ub_state_stat(sc, cmd);
1122 if (cmd->dir == UB_DIR_WRITE) {
1124 * Do not continue writes in case of a failure.
1125 * Doing so would cause sectors to be mixed up,
1126 * which is worse than sectors lost.
1128 * We must try to read the CSW, or many devices
1131 len = urb->actual_length;
1132 if (urb->status != 0 ||
1133 len != cmd->sgv[cmd->current_sg].length) {
1134 cmd->act_len += len;
1137 ub_state_stat(sc, cmd);
1143 * If an error occurs on read, we record it, and
1144 * continue to fetch data in order to avoid bubble.
1146 * As a small shortcut, we stop if we detect that
1147 * a CSW mixed into data.
1149 if (urb->status != 0)
1152 len = urb->actual_length;
1153 if (urb->status != 0 ||
1154 len != cmd->sgv[cmd->current_sg].length) {
1155 if ((len & 0x1FF) == US_BULK_CS_WRAP_LEN)
1160 cmd->act_len += urb->actual_length;
1162 if (++cmd->current_sg < cmd->nsg) {
1163 ub_data_start(sc, cmd);
1166 ub_state_stat(sc, cmd);
1168 } else if (cmd->state == UB_CMDST_STAT) {
1169 if (urb->status == -EPIPE) {
1170 rc = ub_submit_clear_stall(sc, cmd, sc->last_pipe);
1172 printk(KERN_NOTICE "%s: "
1173 "unable to submit clear (%d)\n",
1175 ub_state_done(sc, cmd, rc);
1180 * Having a stall when getting CSW is an error, so
1181 * make sure uppper levels are not oblivious to it.
1183 cmd->error = -EIO; /* A cheap trick... */
1185 cmd->state = UB_CMDST_CLRRS;
1189 /* Catch everything, including -EOVERFLOW and other nasties. */
1190 if (urb->status != 0)
1193 if (urb->actual_length == 0) {
1194 ub_state_stat_counted(sc, cmd);
1199 * Check the returned Bulk protocol status.
1200 * The status block has to be validated first.
1203 bcs = &sc->work_bcs;
1205 if (sc->signature == cpu_to_le32(0)) {
1207 * This is the first reply, so do not perform the check.
1208 * Instead, remember the signature the device uses
1209 * for future checks. But do not allow a nul.
1211 sc->signature = bcs->Signature;
1212 if (sc->signature == cpu_to_le32(0)) {
1213 ub_state_stat_counted(sc, cmd);
1217 if (bcs->Signature != sc->signature) {
1218 ub_state_stat_counted(sc, cmd);
1223 if (bcs->Tag != cmd->tag) {
1225 * This usually happens when we disagree with the
1226 * device's microcode about something. For instance,
1227 * a few of them throw this after timeouts. They buffer
1228 * commands and reply at commands we timed out before.
1229 * Without flushing these replies we loop forever.
1231 ub_state_stat_counted(sc, cmd);
1235 len = le32_to_cpu(bcs->Residue);
1236 if (len != cmd->len - cmd->act_len) {
1238 * It is all right to transfer less, the caller has
1239 * to check. But it's not all right if the device
1240 * counts disagree with our counts.
1245 switch (bcs->Status) {
1246 case US_BULK_STAT_OK:
1248 case US_BULK_STAT_FAIL:
1249 ub_state_sense(sc, cmd);
1251 case US_BULK_STAT_PHASE:
1254 printk(KERN_INFO "%s: unknown CSW status 0x%x\n",
1255 sc->name, bcs->Status);
1256 ub_state_done(sc, cmd, -EINVAL);
1260 /* Not zeroing error to preserve a babble indicator */
1261 if (cmd->error != 0) {
1262 ub_state_sense(sc, cmd);
1265 cmd->state = UB_CMDST_DONE;
1267 (*cmd->done)(sc, cmd);
1269 } else if (cmd->state == UB_CMDST_SENSE) {
1270 ub_state_done(sc, cmd, -EIO);
1273 printk(KERN_WARNING "%s: "
1274 "wrong command state %d\n",
1275 sc->name, cmd->state);
1276 ub_state_done(sc, cmd, -EINVAL);
1281 Bad_End: /* Little Excel is dead */
1282 ub_state_done(sc, cmd, -EIO);
1286 * Factorization helper for the command state machine:
1287 * Initiate a data segment transfer.
1289 static void ub_data_start(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1291 struct scatterlist *sg = &cmd->sgv[cmd->current_sg];
1295 UB_INIT_COMPLETION(sc->work_done);
1297 if (cmd->dir == UB_DIR_READ)
1298 pipe = sc->recv_bulk_pipe;
1300 pipe = sc->send_bulk_pipe;
1301 sc->last_pipe = pipe;
1302 usb_fill_bulk_urb(&sc->work_urb, sc->dev, pipe,
1303 page_address(sg->page) + sg->offset, sg->length,
1304 ub_urb_complete, sc);
1305 sc->work_urb.actual_length = 0;
1306 sc->work_urb.error_count = 0;
1307 sc->work_urb.status = 0;
1309 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1310 /* XXX Clear stalls */
1311 ub_complete(&sc->work_done);
1312 ub_state_done(sc, cmd, rc);
1316 sc->work_timer.expires = jiffies + UB_DATA_TIMEOUT;
1317 add_timer(&sc->work_timer);
1319 cmd->state = UB_CMDST_DATA;
1323 * Factorization helper for the command state machine:
1324 * Finish the command.
1326 static void ub_state_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd, int rc)
1330 cmd->state = UB_CMDST_DONE;
1332 (*cmd->done)(sc, cmd);
1336 * Factorization helper for the command state machine:
1337 * Submit a CSW read.
1339 static int __ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1343 UB_INIT_COMPLETION(sc->work_done);
1345 sc->last_pipe = sc->recv_bulk_pipe;
1346 usb_fill_bulk_urb(&sc->work_urb, sc->dev, sc->recv_bulk_pipe,
1347 &sc->work_bcs, US_BULK_CS_WRAP_LEN, ub_urb_complete, sc);
1348 sc->work_urb.actual_length = 0;
1349 sc->work_urb.error_count = 0;
1350 sc->work_urb.status = 0;
1352 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1353 /* XXX Clear stalls */
1354 ub_complete(&sc->work_done);
1355 ub_state_done(sc, cmd, rc);
1359 sc->work_timer.expires = jiffies + UB_STAT_TIMEOUT;
1360 add_timer(&sc->work_timer);
1365 * Factorization helper for the command state machine:
1366 * Submit a CSW read and go to STAT state.
1368 static void ub_state_stat(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1371 if (__ub_state_stat(sc, cmd) != 0)
1374 cmd->stat_count = 0;
1375 cmd->state = UB_CMDST_STAT;
1379 * Factorization helper for the command state machine:
1380 * Submit a CSW read and go to STAT state with counter (along [C] path).
1382 static void ub_state_stat_counted(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1385 if (++cmd->stat_count >= 4) {
1386 ub_state_sense(sc, cmd);
1390 if (__ub_state_stat(sc, cmd) != 0)
1393 cmd->state = UB_CMDST_STAT;
1397 * Factorization helper for the command state machine:
1398 * Submit a REQUEST SENSE and go to SENSE state.
1400 static void ub_state_sense(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1402 struct ub_scsi_cmd *scmd;
1403 struct scatterlist *sg;
1406 if (cmd->cdb[0] == REQUEST_SENSE) {
1411 scmd = &sc->top_rqs_cmd;
1412 memset(scmd, 0, sizeof(struct ub_scsi_cmd));
1413 scmd->cdb[0] = REQUEST_SENSE;
1414 scmd->cdb[4] = UB_SENSE_SIZE;
1416 scmd->dir = UB_DIR_READ;
1417 scmd->state = UB_CMDST_INIT;
1420 sg->page = virt_to_page(sc->top_sense);
1421 sg->offset = (unsigned long)sc->top_sense & (PAGE_SIZE-1);
1422 sg->length = UB_SENSE_SIZE;
1423 scmd->len = UB_SENSE_SIZE;
1424 scmd->lun = cmd->lun;
1425 scmd->done = ub_top_sense_done;
1428 scmd->tag = sc->tagcnt++;
1430 cmd->state = UB_CMDST_SENSE;
1432 ub_cmdq_insert(sc, scmd);
1436 ub_state_done(sc, cmd, rc);
1440 * A helper for the command's state machine:
1441 * Submit a stall clear.
1443 static int ub_submit_clear_stall(struct ub_dev *sc, struct ub_scsi_cmd *cmd,
1447 struct usb_ctrlrequest *cr;
1450 endp = usb_pipeendpoint(stalled_pipe);
1451 if (usb_pipein (stalled_pipe))
1455 cr->bRequestType = USB_RECIP_ENDPOINT;
1456 cr->bRequest = USB_REQ_CLEAR_FEATURE;
1457 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
1458 cr->wIndex = cpu_to_le16(endp);
1459 cr->wLength = cpu_to_le16(0);
1461 UB_INIT_COMPLETION(sc->work_done);
1463 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1464 (unsigned char*) cr, NULL, 0, ub_urb_complete, sc);
1465 sc->work_urb.actual_length = 0;
1466 sc->work_urb.error_count = 0;
1467 sc->work_urb.status = 0;
1469 if ((rc = usb_submit_urb(&sc->work_urb, GFP_ATOMIC)) != 0) {
1470 ub_complete(&sc->work_done);
1474 sc->work_timer.expires = jiffies + UB_CTRL_TIMEOUT;
1475 add_timer(&sc->work_timer);
1481 static void ub_top_sense_done(struct ub_dev *sc, struct ub_scsi_cmd *scmd)
1483 unsigned char *sense = sc->top_sense;
1484 struct ub_scsi_cmd *cmd;
1487 * Find the command which triggered the unit attention or a check,
1488 * save the sense into it, and advance its state machine.
1490 if ((cmd = ub_cmdq_peek(sc)) == NULL) {
1491 printk(KERN_WARNING "%s: sense done while idle\n", sc->name);
1494 if (cmd != scmd->back) {
1495 printk(KERN_WARNING "%s: "
1496 "sense done for wrong command 0x%x\n",
1497 sc->name, cmd->tag);
1500 if (cmd->state != UB_CMDST_SENSE) {
1501 printk(KERN_WARNING "%s: "
1502 "sense done with bad cmd state %d\n",
1503 sc->name, cmd->state);
1508 * Ignoring scmd->act_len, because the buffer was pre-zeroed.
1510 cmd->key = sense[2] & 0x0F;
1511 cmd->asc = sense[12];
1512 cmd->ascq = sense[13];
1514 ub_scsi_urb_compl(sc, cmd);
1519 * XXX Move usb_reset_device to khubd. Hogging kevent is not a good thing.
1520 * XXX Make usb_sync_reset asynchronous.
1523 static void ub_reset_enter(struct ub_dev *sc, int try)
1527 /* This happens often on multi-LUN devices. */
1530 sc->reset = try + 1;
1532 #if 0 /* Not needed because the disconnect waits for us. */
1533 unsigned long flags;
1534 spin_lock_irqsave(&ub_lock, flags);
1536 spin_unlock_irqrestore(&ub_lock, flags);
1539 #if 0 /* We let them stop themselves. */
1540 struct list_head *p;
1542 list_for_each(p, &sc->luns) {
1543 lun = list_entry(p, struct ub_lun, link);
1544 blk_stop_queue(lun->disk->queue);
1548 schedule_work(&sc->reset_work);
1551 static void ub_reset_task(void *arg)
1553 struct ub_dev *sc = arg;
1554 unsigned long flags;
1555 struct list_head *p;
1560 printk(KERN_WARNING "%s: Running reset unrequested\n",
1565 if (atomic_read(&sc->poison)) {
1567 } else if ((sc->reset & 1) == 0) {
1569 msleep(700); /* usb-storage sleeps 6s (!) */
1570 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
1571 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
1572 } else if (sc->dev->actconfig->desc.bNumInterfaces != 1) {
1575 if ((lkr = usb_lock_device_for_reset(sc->dev, sc->intf)) < 0) {
1577 "%s: usb_lock_device_for_reset failed (%d)\n",
1580 rc = usb_reset_device(sc->dev);
1582 printk(KERN_NOTICE "%s: "
1583 "usb_lock_device_for_reset failed (%d)\n",
1588 usb_unlock_device(sc->dev);
1593 * In theory, no commands can be running while reset is active,
1594 * so nobody can ask for another reset, and so we do not need any
1595 * queues of resets or anything. We do need a spinlock though,
1596 * to interact with block layer.
1598 spin_lock_irqsave(sc->lock, flags);
1600 tasklet_schedule(&sc->tasklet);
1601 list_for_each(p, &sc->luns) {
1602 lun = list_entry(p, struct ub_lun, link);
1603 blk_start_queue(lun->disk->queue);
1605 wake_up(&sc->reset_wait);
1606 spin_unlock_irqrestore(sc->lock, flags);
1610 * This is called from a process context.
1612 static void ub_revalidate(struct ub_dev *sc, struct ub_lun *lun)
1615 lun->readonly = 0; /* XXX Query this from the device */
1617 lun->capacity.nsec = 0;
1618 lun->capacity.bsize = 512;
1619 lun->capacity.bshift = 0;
1621 if (ub_sync_tur(sc, lun) != 0)
1622 return; /* Not ready */
1625 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1627 * The retry here means something is wrong, either with the
1628 * device, with the transport, or with our code.
1629 * We keep this because sd.c has retries for capacity.
1631 if (ub_sync_read_cap(sc, lun, &lun->capacity) != 0) {
1632 lun->capacity.nsec = 0;
1633 lun->capacity.bsize = 512;
1634 lun->capacity.bshift = 0;
1641 * This is mostly needed to keep refcounting, but also to support
1642 * media checks on removable media drives.
1644 static int ub_bd_open(struct inode *inode, struct file *filp)
1646 struct gendisk *disk = inode->i_bdev->bd_disk;
1647 struct ub_lun *lun = disk->private_data;
1648 struct ub_dev *sc = lun->udev;
1649 unsigned long flags;
1652 spin_lock_irqsave(&ub_lock, flags);
1653 if (atomic_read(&sc->poison)) {
1654 spin_unlock_irqrestore(&ub_lock, flags);
1658 spin_unlock_irqrestore(&ub_lock, flags);
1660 if (lun->removable || lun->readonly)
1661 check_disk_change(inode->i_bdev);
1664 * The sd.c considers ->media_present and ->changed not equivalent,
1665 * under some pretty murky conditions (a failure of READ CAPACITY).
1666 * We may need it one day.
1668 if (lun->removable && lun->changed && !(filp->f_flags & O_NDELAY)) {
1673 if (lun->readonly && (filp->f_mode & FMODE_WRITE)) {
1687 static int ub_bd_release(struct inode *inode, struct file *filp)
1689 struct gendisk *disk = inode->i_bdev->bd_disk;
1690 struct ub_lun *lun = disk->private_data;
1691 struct ub_dev *sc = lun->udev;
1698 * The ioctl interface.
1700 static int ub_bd_ioctl(struct inode *inode, struct file *filp,
1701 unsigned int cmd, unsigned long arg)
1703 struct gendisk *disk = inode->i_bdev->bd_disk;
1704 void __user *usermem = (void __user *) arg;
1706 return scsi_cmd_ioctl(filp, disk, cmd, usermem);
1710 * This is called once a new disk was seen by the block layer or by ub_probe().
1711 * The main onjective here is to discover the features of the media such as
1712 * the capacity, read-only status, etc. USB storage generally does not
1713 * need to be spun up, but if we needed it, this would be the place.
1715 * This call can sleep.
1717 * The return code is not used.
1719 static int ub_bd_revalidate(struct gendisk *disk)
1721 struct ub_lun *lun = disk->private_data;
1723 ub_revalidate(lun->udev, lun);
1725 /* XXX Support sector size switching like in sr.c */
1726 blk_queue_hardsect_size(disk->queue, lun->capacity.bsize);
1727 set_capacity(disk, lun->capacity.nsec);
1728 // set_disk_ro(sdkp->disk, lun->readonly);
1734 * The check is called by the block layer to verify if the media
1735 * is still available. It is supposed to be harmless, lightweight and
1736 * non-intrusive in case the media was not changed.
1738 * This call can sleep.
1740 * The return code is bool!
1742 static int ub_bd_media_changed(struct gendisk *disk)
1744 struct ub_lun *lun = disk->private_data;
1746 if (!lun->removable)
1750 * We clean checks always after every command, so this is not
1751 * as dangerous as it looks. If the TEST_UNIT_READY fails here,
1752 * the device is actually not ready with operator or software
1753 * intervention required. One dangerous item might be a drive which
1754 * spins itself down, and come the time to write dirty pages, this
1755 * will fail, then block layer discards the data. Since we never
1756 * spin drives up, such devices simply cannot be used with ub anyway.
1758 if (ub_sync_tur(lun->udev, lun) != 0) {
1763 return lun->changed;
1766 static struct block_device_operations ub_bd_fops = {
1767 .owner = THIS_MODULE,
1769 .release = ub_bd_release,
1770 .ioctl = ub_bd_ioctl,
1771 .media_changed = ub_bd_media_changed,
1772 .revalidate_disk = ub_bd_revalidate,
1776 * Common ->done routine for commands executed synchronously.
1778 static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd)
1780 struct completion *cop = cmd->back;
1785 * Test if the device has a check condition on it, synchronously.
1787 static int ub_sync_tur(struct ub_dev *sc, struct ub_lun *lun)
1789 struct ub_scsi_cmd *cmd;
1790 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) };
1791 unsigned long flags;
1792 struct completion compl;
1795 init_completion(&compl);
1798 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1801 cmd->cdb[0] = TEST_UNIT_READY;
1803 cmd->dir = UB_DIR_NONE;
1804 cmd->state = UB_CMDST_INIT;
1805 cmd->lun = lun; /* This may be NULL, but that's ok */
1806 cmd->done = ub_probe_done;
1809 spin_lock_irqsave(sc->lock, flags);
1810 cmd->tag = sc->tagcnt++;
1812 rc = ub_submit_scsi(sc, cmd);
1813 spin_unlock_irqrestore(sc->lock, flags);
1818 wait_for_completion(&compl);
1822 if (rc == -EIO && cmd->key != 0) /* Retries for benh's key */
1832 * Read the SCSI capacity synchronously (for probing).
1834 static int ub_sync_read_cap(struct ub_dev *sc, struct ub_lun *lun,
1835 struct ub_capacity *ret)
1837 struct ub_scsi_cmd *cmd;
1838 struct scatterlist *sg;
1840 enum { ALLOC_SIZE = sizeof(struct ub_scsi_cmd) + 8 };
1841 unsigned long flags;
1842 unsigned int bsize, shift;
1844 struct completion compl;
1847 init_completion(&compl);
1850 if ((cmd = kzalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1852 p = (char *)cmd + sizeof(struct ub_scsi_cmd);
1856 cmd->dir = UB_DIR_READ;
1857 cmd->state = UB_CMDST_INIT;
1860 sg->page = virt_to_page(p);
1861 sg->offset = (unsigned long)p & (PAGE_SIZE-1);
1865 cmd->done = ub_probe_done;
1868 spin_lock_irqsave(sc->lock, flags);
1869 cmd->tag = sc->tagcnt++;
1871 rc = ub_submit_scsi(sc, cmd);
1872 spin_unlock_irqrestore(sc->lock, flags);
1877 wait_for_completion(&compl);
1879 if (cmd->error != 0) {
1883 if (cmd->act_len != 8) {
1888 /* sd.c special-cases sector size of 0 to mean 512. Needed? Safe? */
1889 nsec = be32_to_cpu(*(__be32 *)p) + 1;
1890 bsize = be32_to_cpu(*(__be32 *)(p + 4));
1892 case 512: shift = 0; break;
1893 case 1024: shift = 1; break;
1894 case 2048: shift = 2; break;
1895 case 4096: shift = 3; break;
1902 ret->bshift = shift;
1903 ret->nsec = nsec << shift;
1916 static void ub_probe_urb_complete(struct urb *urb, struct pt_regs *pt)
1918 struct completion *cop = urb->context;
1922 static void ub_probe_timeout(unsigned long arg)
1924 struct completion *cop = (struct completion *) arg;
1929 * Reset with a Bulk reset.
1931 static int ub_sync_reset(struct ub_dev *sc)
1933 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1934 struct usb_ctrlrequest *cr;
1935 struct completion compl;
1936 struct timer_list timer;
1939 init_completion(&compl);
1942 cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1943 cr->bRequest = US_BULK_RESET_REQUEST;
1944 cr->wValue = cpu_to_le16(0);
1945 cr->wIndex = cpu_to_le16(ifnum);
1946 cr->wLength = cpu_to_le16(0);
1948 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
1949 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
1950 sc->work_urb.actual_length = 0;
1951 sc->work_urb.error_count = 0;
1952 sc->work_urb.status = 0;
1954 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
1956 "%s: Unable to submit a bulk reset (%d)\n", sc->name, rc);
1961 timer.function = ub_probe_timeout;
1962 timer.data = (unsigned long) &compl;
1963 timer.expires = jiffies + UB_CTRL_TIMEOUT;
1966 wait_for_completion(&compl);
1968 del_timer_sync(&timer);
1969 usb_kill_urb(&sc->work_urb);
1971 return sc->work_urb.status;
1975 * Get number of LUNs by the way of Bulk GetMaxLUN command.
1977 static int ub_sync_getmaxlun(struct ub_dev *sc)
1979 int ifnum = sc->intf->cur_altsetting->desc.bInterfaceNumber;
1981 enum { ALLOC_SIZE = 1 };
1982 struct usb_ctrlrequest *cr;
1983 struct completion compl;
1984 struct timer_list timer;
1988 init_completion(&compl);
1991 if ((p = kmalloc(ALLOC_SIZE, GFP_KERNEL)) == NULL)
1996 cr->bRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
1997 cr->bRequest = US_BULK_GET_MAX_LUN;
1998 cr->wValue = cpu_to_le16(0);
1999 cr->wIndex = cpu_to_le16(ifnum);
2000 cr->wLength = cpu_to_le16(1);
2002 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->recv_ctrl_pipe,
2003 (unsigned char*) cr, p, 1, ub_probe_urb_complete, &compl);
2004 sc->work_urb.actual_length = 0;
2005 sc->work_urb.error_count = 0;
2006 sc->work_urb.status = 0;
2008 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0)
2012 timer.function = ub_probe_timeout;
2013 timer.data = (unsigned long) &compl;
2014 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2017 wait_for_completion(&compl);
2019 del_timer_sync(&timer);
2020 usb_kill_urb(&sc->work_urb);
2022 if ((rc = sc->work_urb.status) < 0)
2025 if (sc->work_urb.actual_length != 1) {
2028 if ((nluns = *p) == 55) {
2031 /* GetMaxLUN returns the maximum LUN number */
2033 if (nluns > UB_MAX_LUNS)
2034 nluns = UB_MAX_LUNS;
2049 * Clear initial stalls.
2051 static int ub_probe_clear_stall(struct ub_dev *sc, int stalled_pipe)
2054 struct usb_ctrlrequest *cr;
2055 struct completion compl;
2056 struct timer_list timer;
2059 init_completion(&compl);
2061 endp = usb_pipeendpoint(stalled_pipe);
2062 if (usb_pipein (stalled_pipe))
2066 cr->bRequestType = USB_RECIP_ENDPOINT;
2067 cr->bRequest = USB_REQ_CLEAR_FEATURE;
2068 cr->wValue = cpu_to_le16(USB_ENDPOINT_HALT);
2069 cr->wIndex = cpu_to_le16(endp);
2070 cr->wLength = cpu_to_le16(0);
2072 usb_fill_control_urb(&sc->work_urb, sc->dev, sc->send_ctrl_pipe,
2073 (unsigned char*) cr, NULL, 0, ub_probe_urb_complete, &compl);
2074 sc->work_urb.actual_length = 0;
2075 sc->work_urb.error_count = 0;
2076 sc->work_urb.status = 0;
2078 if ((rc = usb_submit_urb(&sc->work_urb, GFP_KERNEL)) != 0) {
2080 "%s: Unable to submit a probe clear (%d)\n", sc->name, rc);
2085 timer.function = ub_probe_timeout;
2086 timer.data = (unsigned long) &compl;
2087 timer.expires = jiffies + UB_CTRL_TIMEOUT;
2090 wait_for_completion(&compl);
2092 del_timer_sync(&timer);
2093 usb_kill_urb(&sc->work_urb);
2095 /* reset the endpoint toggle */
2096 usb_settoggle(sc->dev, endp, usb_pipeout(sc->last_pipe), 0);
2102 * Get the pipe settings.
2104 static int ub_get_pipes(struct ub_dev *sc, struct usb_device *dev,
2105 struct usb_interface *intf)
2107 struct usb_host_interface *altsetting = intf->cur_altsetting;
2108 struct usb_endpoint_descriptor *ep_in = NULL;
2109 struct usb_endpoint_descriptor *ep_out = NULL;
2110 struct usb_endpoint_descriptor *ep;
2114 * Find the endpoints we need.
2115 * We are expecting a minimum of 2 endpoints - in and out (bulk).
2116 * We will ignore any others.
2118 for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
2119 ep = &altsetting->endpoint[i].desc;
2121 /* Is it a BULK endpoint? */
2122 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
2123 == USB_ENDPOINT_XFER_BULK) {
2124 /* BULK in or out? */
2125 if (ep->bEndpointAddress & USB_DIR_IN)
2132 if (ep_in == NULL || ep_out == NULL) {
2133 printk(KERN_NOTICE "%s: failed endpoint check\n",
2138 /* Calculate and store the pipe values */
2139 sc->send_ctrl_pipe = usb_sndctrlpipe(dev, 0);
2140 sc->recv_ctrl_pipe = usb_rcvctrlpipe(dev, 0);
2141 sc->send_bulk_pipe = usb_sndbulkpipe(dev,
2142 ep_out->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2143 sc->recv_bulk_pipe = usb_rcvbulkpipe(dev,
2144 ep_in->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2150 * Probing is done in the process context, which allows us to cheat
2151 * and not to build a state machine for the discovery.
2153 static int ub_probe(struct usb_interface *intf,
2154 const struct usb_device_id *dev_id)
2161 if (usb_usual_check_type(dev_id, USB_US_TYPE_UB))
2165 if ((sc = kzalloc(sizeof(struct ub_dev), GFP_KERNEL)) == NULL)
2167 sc->lock = ub_next_lock();
2168 INIT_LIST_HEAD(&sc->luns);
2169 usb_init_urb(&sc->work_urb);
2170 tasklet_init(&sc->tasklet, ub_scsi_action, (unsigned long)sc);
2171 atomic_set(&sc->poison, 0);
2172 INIT_WORK(&sc->reset_work, ub_reset_task, sc);
2173 init_waitqueue_head(&sc->reset_wait);
2175 init_timer(&sc->work_timer);
2176 sc->work_timer.data = (unsigned long) sc;
2177 sc->work_timer.function = ub_urb_timeout;
2179 ub_init_completion(&sc->work_done);
2180 sc->work_done.done = 1; /* A little yuk, but oh well... */
2182 sc->dev = interface_to_usbdev(intf);
2184 // sc->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2185 usb_set_intfdata(intf, sc);
2186 usb_get_dev(sc->dev);
2188 * Since we give the interface struct to the block level through
2189 * disk->driverfs_dev, we have to pin it. Otherwise, block_uevent
2190 * oopses on close after a disconnect (kernels 2.6.16 and up).
2192 usb_get_intf(sc->intf);
2194 snprintf(sc->name, 12, DRV_NAME "(%d.%d)",
2195 sc->dev->bus->busnum, sc->dev->devnum);
2197 /* XXX Verify that we can handle the device (from descriptors) */
2199 if (ub_get_pipes(sc, sc->dev, intf) != 0)
2203 * At this point, all USB initialization is done, do upper layer.
2204 * We really hate halfway initialized structures, so from the
2205 * invariants perspective, this ub_dev is fully constructed at
2210 * This is needed to clear toggles. It is a problem only if we do
2211 * `rmmod ub && modprobe ub` without disconnects, but we like that.
2213 #if 0 /* iPod Mini fails if we do this (big white iPod works) */
2214 ub_probe_clear_stall(sc, sc->recv_bulk_pipe);
2215 ub_probe_clear_stall(sc, sc->send_bulk_pipe);
2219 * The way this is used by the startup code is a little specific.
2220 * A SCSI check causes a USB stall. Our common case code sees it
2221 * and clears the check, after which the device is ready for use.
2222 * But if a check was not present, any command other than
2223 * TEST_UNIT_READY ends with a lockup (including REQUEST_SENSE).
2225 * If we neglect to clear the SCSI check, the first real command fails
2226 * (which is the capacity readout). We clear that and retry, but why
2227 * causing spurious retries for no reason.
2229 * Revalidation may start with its own TEST_UNIT_READY, but that one
2230 * has to succeed, so we clear checks with an additional one here.
2231 * In any case it's not our business how revaliadation is implemented.
2233 for (i = 0; i < 3; i++) { /* Retries for the schwag key from KS'04 */
2234 if ((rc = ub_sync_tur(sc, NULL)) <= 0) break;
2235 if (rc != 0x6) break;
2240 for (i = 0; i < 3; i++) {
2241 if ((rc = ub_sync_getmaxlun(sc)) < 0)
2250 for (i = 0; i < nluns; i++) {
2251 ub_probe_lun(sc, i);
2256 usb_set_intfdata(intf, NULL);
2257 usb_put_intf(sc->intf);
2258 usb_put_dev(sc->dev);
2264 static int ub_probe_lun(struct ub_dev *sc, int lnum)
2268 struct gendisk *disk;
2272 if ((lun = kzalloc(sizeof(struct ub_lun), GFP_KERNEL)) == NULL)
2277 if ((lun->id = ub_id_get()) == -1)
2282 snprintf(lun->name, 16, DRV_NAME "%c(%d.%d.%d)",
2283 lun->id + 'a', sc->dev->bus->busnum, sc->dev->devnum, lun->num);
2285 lun->removable = 1; /* XXX Query this from the device */
2286 lun->changed = 1; /* ub_revalidate clears only */
2287 ub_revalidate(sc, lun);
2290 if ((disk = alloc_disk(UB_PARTS_PER_LUN)) == NULL)
2293 sprintf(disk->disk_name, DRV_NAME "%c", lun->id + 'a');
2294 sprintf(disk->devfs_name, DEVFS_NAME "/%c", lun->id + 'a');
2295 disk->major = UB_MAJOR;
2296 disk->first_minor = lun->id * UB_PARTS_PER_LUN;
2297 disk->fops = &ub_bd_fops;
2298 disk->private_data = lun;
2299 disk->driverfs_dev = &sc->intf->dev;
2302 if ((q = blk_init_queue(ub_request_fn, sc->lock)) == NULL)
2307 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
2308 blk_queue_max_hw_segments(q, UB_MAX_REQ_SG);
2309 blk_queue_max_phys_segments(q, UB_MAX_REQ_SG);
2310 blk_queue_segment_boundary(q, 0xffffffff); /* Dubious. */
2311 blk_queue_max_sectors(q, UB_MAX_SECTORS);
2312 blk_queue_hardsect_size(q, lun->capacity.bsize);
2316 list_add(&lun->link, &sc->luns);
2318 set_capacity(disk, lun->capacity.nsec);
2320 disk->flags |= GENHD_FL_REMOVABLE;
2336 static void ub_disconnect(struct usb_interface *intf)
2338 struct ub_dev *sc = usb_get_intfdata(intf);
2339 struct list_head *p;
2341 unsigned long flags;
2344 * Prevent ub_bd_release from pulling the rug from under us.
2345 * XXX This is starting to look like a kref.
2346 * XXX Why not to take this ref at probe time?
2348 spin_lock_irqsave(&ub_lock, flags);
2350 spin_unlock_irqrestore(&ub_lock, flags);
2353 * Fence stall clearnings, operations triggered by unlinkings and so on.
2354 * We do not attempt to unlink any URBs, because we do not trust the
2355 * unlink paths in HC drivers. Also, we get -84 upon disconnect anyway.
2357 atomic_set(&sc->poison, 1);
2360 * Wait for reset to end, if any.
2362 wait_event(sc->reset_wait, !sc->reset);
2365 * Blow away queued commands.
2367 * Actually, this never works, because before we get here
2368 * the HCD terminates outstanding URB(s). It causes our
2369 * SCSI command queue to advance, commands fail to submit,
2370 * and the whole queue drains. So, we just use this code to
2373 spin_lock_irqsave(sc->lock, flags);
2375 struct ub_scsi_cmd *cmd;
2377 while ((cmd = ub_cmdq_peek(sc)) != NULL) {
2378 cmd->error = -ENOTCONN;
2379 cmd->state = UB_CMDST_DONE;
2381 (*cmd->done)(sc, cmd);
2385 printk(KERN_WARNING "%s: "
2386 "%d was queued after shutdown\n", sc->name, cnt);
2389 spin_unlock_irqrestore(sc->lock, flags);
2392 * Unregister the upper layer.
2394 list_for_each (p, &sc->luns) {
2395 lun = list_entry(p, struct ub_lun, link);
2396 del_gendisk(lun->disk);
2398 * I wish I could do:
2399 * set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
2400 * As it is, we rely on our internal poisoning and let
2401 * the upper levels to spin furiously failing all the I/O.
2406 * Testing for -EINPROGRESS is always a bug, so we are bending
2407 * the rules a little.
2409 spin_lock_irqsave(sc->lock, flags);
2410 if (sc->work_urb.status == -EINPROGRESS) { /* janitors: ignore */
2411 printk(KERN_WARNING "%s: "
2412 "URB is active after disconnect\n", sc->name);
2414 spin_unlock_irqrestore(sc->lock, flags);
2417 * There is virtually no chance that other CPU runs times so long
2418 * after ub_urb_complete should have called del_timer, but only if HCD
2419 * didn't forget to deliver a callback on unlink.
2421 del_timer_sync(&sc->work_timer);
2424 * At this point there must be no commands coming from anyone
2425 * and no URBs left in transit.
2431 static struct usb_driver ub_driver = {
2434 .disconnect = ub_disconnect,
2435 .id_table = ub_usb_ids,
2438 static int __init ub_init(void)
2443 for (i = 0; i < UB_QLOCK_NUM; i++)
2444 spin_lock_init(&ub_qlockv[i]);
2446 if ((rc = register_blkdev(UB_MAJOR, DRV_NAME)) != 0)
2448 devfs_mk_dir(DEVFS_NAME);
2450 if ((rc = usb_register(&ub_driver)) != 0)
2453 usb_usual_set_present(USB_US_TYPE_UB);
2457 devfs_remove(DEVFS_NAME);
2458 unregister_blkdev(UB_MAJOR, DRV_NAME);
2463 static void __exit ub_exit(void)
2465 usb_deregister(&ub_driver);
2467 devfs_remove(DEVFS_NAME);
2468 unregister_blkdev(UB_MAJOR, DRV_NAME);
2469 usb_usual_clear_present(USB_US_TYPE_UB);
2472 module_init(ub_init);
2473 module_exit(ub_exit);
2475 MODULE_LICENSE("GPL");