2 * Copyright (C) 2013 Shaohua Li <shli@kernel.org>
3 * Copyright (C) 2014 Red Hat, Inc.
4 * Copyright (C) 2015 Arrikto, Inc.
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms and conditions of the GNU General Public License,
8 * version 2, as published by the Free Software Foundation.
10 * This program is distributed in the hope it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
20 #include <linux/spinlock.h>
21 #include <linux/module.h>
22 #include <linux/idr.h>
23 #include <linux/kernel.h>
24 #include <linux/timer.h>
25 #include <linux/parser.h>
26 #include <linux/vmalloc.h>
27 #include <linux/uio_driver.h>
28 #include <linux/stringify.h>
29 #include <linux/bitops.h>
30 #include <linux/highmem.h>
31 #include <net/genetlink.h>
32 #include <scsi/scsi_common.h>
33 #include <scsi/scsi_proto.h>
34 #include <target/target_core_base.h>
35 #include <target/target_core_fabric.h>
36 #include <target/target_core_backend.h>
38 #include <linux/target_core_user.h>
41 * Define a shared-memory interface for LIO to pass SCSI commands and
42 * data to userspace for processing. This is to allow backends that
43 * are too complex for in-kernel support to be possible.
45 * It uses the UIO framework to do a lot of the device-creation and
46 * introspection work for us.
48 * See the .h file for how the ring is laid out. Note that while the
49 * command ring is defined, the particulars of the data area are
50 * not. Offset values in the command entry point to other locations
51 * internal to the mmap()ed area. There is separate space outside the
52 * command ring for data buffers. This leaves maximum flexibility for
53 * moving buffer allocations, or even page flipping or other
54 * allocation techniques, without altering the command ring layout.
57 * The user process must be assumed to be malicious. There's no way to
58 * prevent it breaking the command ring protocol if it wants, but in
59 * order to prevent other issues we must only ever read *data* from
60 * the shared memory area, not offsets or sizes. This applies to
61 * command ring entries as well as the mailbox. Extra code needed for
62 * this may have a 'UAM' comment.
66 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
68 #define DATA_BLOCK_BITS 256
69 #define DATA_BLOCK_SIZE 4096
71 #define CMDR_SIZE (16 * 4096)
72 #define DATA_SIZE (DATA_BLOCK_BITS * DATA_BLOCK_SIZE)
74 #define TCMU_RING_SIZE (CMDR_SIZE + DATA_SIZE)
76 static struct device *tcmu_root_device;
82 #define TCMU_CONFIG_LEN 256
85 struct se_device se_dev;
90 #define TCMU_DEV_BIT_OPEN 0
91 #define TCMU_DEV_BIT_BROKEN 1
94 struct uio_info uio_info;
96 struct tcmu_mailbox *mb_addr;
99 u32 cmdr_last_cleaned;
100 /* Offset of data area from start of mb */
101 /* Must add data_off and mb_addr to get the address */
105 DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
107 wait_queue_head_t wait_cmdr;
108 /* TODO should this be a mutex? */
109 spinlock_t cmdr_lock;
112 spinlock_t commands_lock;
114 struct timer_list timeout;
115 unsigned int cmd_time_out;
117 char dev_config[TCMU_CONFIG_LEN];
120 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
122 #define CMDR_OFF sizeof(struct tcmu_mailbox)
125 struct se_cmd *se_cmd;
126 struct tcmu_dev *tcmu_dev;
130 /* Can't use se_cmd when cleaning up expired cmds, because if
131 cmd has been completed then accessing se_cmd is off limits */
132 DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
134 unsigned long deadline;
136 #define TCMU_CMD_BIT_EXPIRED 0
140 static struct kmem_cache *tcmu_cmd_cache;
142 /* multicast group */
143 enum tcmu_multicast_groups {
147 static const struct genl_multicast_group tcmu_mcgrps[] = {
148 [TCMU_MCGRP_CONFIG] = { .name = "config", },
151 /* Our generic netlink family */
152 static struct genl_family tcmu_genl_family __ro_after_init = {
153 .module = THIS_MODULE,
157 .maxattr = TCMU_ATTR_MAX,
158 .mcgrps = tcmu_mcgrps,
159 .n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
163 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
165 struct se_device *se_dev = se_cmd->se_dev;
166 struct tcmu_dev *udev = TCMU_DEV(se_dev);
167 struct tcmu_cmd *tcmu_cmd;
170 tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
174 tcmu_cmd->se_cmd = se_cmd;
175 tcmu_cmd->tcmu_dev = udev;
176 if (udev->cmd_time_out)
177 tcmu_cmd->deadline = jiffies +
178 msecs_to_jiffies(udev->cmd_time_out);
180 idr_preload(GFP_KERNEL);
181 spin_lock_irq(&udev->commands_lock);
182 cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 0,
183 USHRT_MAX, GFP_NOWAIT);
184 spin_unlock_irq(&udev->commands_lock);
188 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
191 tcmu_cmd->cmd_id = cmd_id;
196 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
198 unsigned long offset = offset_in_page(vaddr);
200 size = round_up(size+offset, PAGE_SIZE);
204 flush_dcache_page(virt_to_page(vaddr));
210 * Some ring helper functions. We don't assume size is a power of 2 so
211 * we can't use circ_buf.h.
213 static inline size_t spc_used(size_t head, size_t tail, size_t size)
215 int diff = head - tail;
223 static inline size_t spc_free(size_t head, size_t tail, size_t size)
225 /* Keep 1 byte unused or we can't tell full from empty */
226 return (size - spc_used(head, tail, size) - 1);
229 static inline size_t head_to_end(size_t head, size_t size)
234 static inline void new_iov(struct iovec **iov, int *iov_cnt,
235 struct tcmu_dev *udev)
244 memset(iovec, 0, sizeof(struct iovec));
247 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
249 /* offset is relative to mb_addr */
250 static inline size_t get_block_offset(struct tcmu_dev *dev,
251 int block, int remaining)
253 return dev->data_off + block * DATA_BLOCK_SIZE +
254 DATA_BLOCK_SIZE - remaining;
257 static inline size_t iov_tail(struct tcmu_dev *udev, struct iovec *iov)
259 return (size_t)iov->iov_base + iov->iov_len;
262 static void alloc_and_scatter_data_area(struct tcmu_dev *udev,
263 struct scatterlist *data_sg, unsigned int data_nents,
264 struct iovec **iov, int *iov_cnt, bool copy_data)
267 int block_remaining = 0;
269 size_t copy_bytes, to_offset;
270 struct scatterlist *sg;
272 for_each_sg(data_sg, sg, data_nents, i) {
273 int sg_remaining = sg->length;
274 from = kmap_atomic(sg_page(sg)) + sg->offset;
275 while (sg_remaining > 0) {
276 if (block_remaining == 0) {
277 block = find_first_zero_bit(udev->data_bitmap,
279 block_remaining = DATA_BLOCK_SIZE;
280 set_bit(block, udev->data_bitmap);
282 copy_bytes = min_t(size_t, sg_remaining,
284 to_offset = get_block_offset(udev, block,
286 to = (void *)udev->mb_addr + to_offset;
288 to_offset == iov_tail(udev, *iov)) {
289 (*iov)->iov_len += copy_bytes;
291 new_iov(iov, iov_cnt, udev);
292 (*iov)->iov_base = (void __user *) to_offset;
293 (*iov)->iov_len = copy_bytes;
296 memcpy(to, from + sg->length - sg_remaining,
298 tcmu_flush_dcache_range(to, copy_bytes);
300 sg_remaining -= copy_bytes;
301 block_remaining -= copy_bytes;
303 kunmap_atomic(from - sg->offset);
307 static void free_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd)
309 bitmap_xor(udev->data_bitmap, udev->data_bitmap, cmd->data_bitmap,
313 static void gather_data_area(struct tcmu_dev *udev, unsigned long *cmd_bitmap,
314 struct scatterlist *data_sg, unsigned int data_nents)
317 int block_remaining = 0;
319 size_t copy_bytes, from_offset;
320 struct scatterlist *sg;
322 for_each_sg(data_sg, sg, data_nents, i) {
323 int sg_remaining = sg->length;
324 to = kmap_atomic(sg_page(sg)) + sg->offset;
325 while (sg_remaining > 0) {
326 if (block_remaining == 0) {
327 block = find_first_bit(cmd_bitmap,
329 block_remaining = DATA_BLOCK_SIZE;
330 clear_bit(block, cmd_bitmap);
332 copy_bytes = min_t(size_t, sg_remaining,
334 from_offset = get_block_offset(udev, block,
336 from = (void *) udev->mb_addr + from_offset;
337 tcmu_flush_dcache_range(from, copy_bytes);
338 memcpy(to + sg->length - sg_remaining, from,
341 sg_remaining -= copy_bytes;
342 block_remaining -= copy_bytes;
344 kunmap_atomic(to - sg->offset);
348 static inline size_t spc_bitmap_free(unsigned long *bitmap)
350 return DATA_BLOCK_SIZE * (DATA_BLOCK_BITS -
351 bitmap_weight(bitmap, DATA_BLOCK_BITS));
355 * We can't queue a command until we have space available on the cmd ring *and*
356 * space available on the data area.
358 * Called with ring lock held.
360 static bool is_ring_space_avail(struct tcmu_dev *udev, size_t cmd_size, size_t data_needed)
362 struct tcmu_mailbox *mb = udev->mb_addr;
363 size_t space, cmd_needed;
366 tcmu_flush_dcache_range(mb, sizeof(*mb));
368 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
371 * If cmd end-of-ring space is too small then we need space for a NOP plus
372 * original cmd - cmds are internally contiguous.
374 if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
375 cmd_needed = cmd_size;
377 cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
379 space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
380 if (space < cmd_needed) {
381 pr_debug("no cmd space: %u %u %u\n", cmd_head,
382 udev->cmdr_last_cleaned, udev->cmdr_size);
386 space = spc_bitmap_free(udev->data_bitmap);
387 if (space < data_needed) {
388 pr_debug("no data space: only %zu available, but ask for %zu\n",
396 static sense_reason_t
397 tcmu_queue_cmd_ring(struct tcmu_cmd *tcmu_cmd)
399 struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
400 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
401 size_t base_command_size, command_size;
402 struct tcmu_mailbox *mb;
403 struct tcmu_cmd_entry *entry;
408 bool copy_to_data_area;
410 DECLARE_BITMAP(old_bitmap, DATA_BLOCK_BITS);
412 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
413 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
416 * Must be a certain minimum size for response sense info, but
417 * also may be larger if the iov array is large.
419 * We prepare way too many iovs for potential uses here, because it's
420 * expensive to tell how many regions are freed in the bitmap
422 base_command_size = max(offsetof(struct tcmu_cmd_entry,
423 req.iov[se_cmd->t_bidi_data_nents +
424 se_cmd->t_data_nents]),
425 sizeof(struct tcmu_cmd_entry));
426 command_size = base_command_size
427 + round_up(scsi_command_size(se_cmd->t_task_cdb), TCMU_OP_ALIGN_SIZE);
429 WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
431 spin_lock_irq(&udev->cmdr_lock);
434 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
435 data_length = se_cmd->data_length;
436 if (se_cmd->se_cmd_flags & SCF_BIDI) {
437 BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
438 data_length += se_cmd->t_bidi_data_sg->length;
440 if ((command_size > (udev->cmdr_size / 2)) ||
441 data_length > udev->data_size) {
442 pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
443 "cmd ring/data area\n", command_size, data_length,
444 udev->cmdr_size, udev->data_size);
445 spin_unlock_irq(&udev->cmdr_lock);
446 return TCM_INVALID_CDB_FIELD;
449 while (!is_ring_space_avail(udev, command_size, data_length)) {
453 prepare_to_wait(&udev->wait_cmdr, &__wait, TASK_INTERRUPTIBLE);
455 pr_debug("sleeping for ring space\n");
456 spin_unlock_irq(&udev->cmdr_lock);
457 if (udev->cmd_time_out)
458 ret = schedule_timeout(
459 msecs_to_jiffies(udev->cmd_time_out));
461 ret = schedule_timeout(msecs_to_jiffies(TCMU_TIME_OUT));
462 finish_wait(&udev->wait_cmdr, &__wait);
464 pr_warn("tcmu: command timed out\n");
465 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
468 spin_lock_irq(&udev->cmdr_lock);
470 /* We dropped cmdr_lock, cmd_head is stale */
471 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
474 /* Insert a PAD if end-of-ring space is too small */
475 if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
476 size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
478 entry = (void *) mb + CMDR_OFF + cmd_head;
479 tcmu_flush_dcache_range(entry, sizeof(*entry));
480 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
481 tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
482 entry->hdr.cmd_id = 0; /* not used for PAD */
483 entry->hdr.kflags = 0;
484 entry->hdr.uflags = 0;
486 UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
488 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
489 WARN_ON(cmd_head != 0);
492 entry = (void *) mb + CMDR_OFF + cmd_head;
493 tcmu_flush_dcache_range(entry, sizeof(*entry));
494 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
495 tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
496 entry->hdr.cmd_id = tcmu_cmd->cmd_id;
497 entry->hdr.kflags = 0;
498 entry->hdr.uflags = 0;
500 bitmap_copy(old_bitmap, udev->data_bitmap, DATA_BLOCK_BITS);
502 /* Handle allocating space from the data area */
503 iov = &entry->req.iov[0];
505 copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
506 || se_cmd->se_cmd_flags & SCF_BIDI);
507 alloc_and_scatter_data_area(udev, se_cmd->t_data_sg,
508 se_cmd->t_data_nents, &iov, &iov_cnt, copy_to_data_area);
509 entry->req.iov_cnt = iov_cnt;
510 entry->req.iov_dif_cnt = 0;
512 /* Handle BIDI commands */
514 alloc_and_scatter_data_area(udev, se_cmd->t_bidi_data_sg,
515 se_cmd->t_bidi_data_nents, &iov, &iov_cnt, false);
516 entry->req.iov_bidi_cnt = iov_cnt;
518 /* cmd's data_bitmap is what changed in process */
519 bitmap_xor(tcmu_cmd->data_bitmap, old_bitmap, udev->data_bitmap,
522 /* All offsets relative to mb_addr, not start of entry! */
523 cdb_off = CMDR_OFF + cmd_head + base_command_size;
524 memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
525 entry->req.cdb_off = cdb_off;
526 tcmu_flush_dcache_range(entry, sizeof(*entry));
528 UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
529 tcmu_flush_dcache_range(mb, sizeof(*mb));
531 spin_unlock_irq(&udev->cmdr_lock);
533 /* TODO: only if FLUSH and FUA? */
534 uio_event_notify(&udev->uio_info);
536 if (udev->cmd_time_out)
537 mod_timer(&udev->timeout, round_jiffies_up(jiffies +
538 msecs_to_jiffies(udev->cmd_time_out)));
543 static sense_reason_t
544 tcmu_queue_cmd(struct se_cmd *se_cmd)
546 struct se_device *se_dev = se_cmd->se_dev;
547 struct tcmu_dev *udev = TCMU_DEV(se_dev);
548 struct tcmu_cmd *tcmu_cmd;
551 tcmu_cmd = tcmu_alloc_cmd(se_cmd);
553 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
555 ret = tcmu_queue_cmd_ring(tcmu_cmd);
556 if (ret != TCM_NO_SENSE) {
557 pr_err("TCMU: Could not queue command\n");
558 spin_lock_irq(&udev->commands_lock);
559 idr_remove(&udev->commands, tcmu_cmd->cmd_id);
560 spin_unlock_irq(&udev->commands_lock);
562 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
568 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
570 struct se_cmd *se_cmd = cmd->se_cmd;
571 struct tcmu_dev *udev = cmd->tcmu_dev;
573 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
575 * cmd has been completed already from timeout, just reclaim
576 * data area space and free cmd
578 free_data_area(udev, cmd);
580 kmem_cache_free(tcmu_cmd_cache, cmd);
584 if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
585 free_data_area(udev, cmd);
586 pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
588 entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
589 } else if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
590 memcpy(se_cmd->sense_buffer, entry->rsp.sense_buffer,
591 se_cmd->scsi_sense_length);
592 free_data_area(udev, cmd);
593 } else if (se_cmd->se_cmd_flags & SCF_BIDI) {
594 DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
596 /* Get Data-In buffer before clean up */
597 bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
598 gather_data_area(udev, bitmap,
599 se_cmd->t_bidi_data_sg, se_cmd->t_bidi_data_nents);
600 free_data_area(udev, cmd);
601 } else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
602 DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
604 bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
605 gather_data_area(udev, bitmap,
606 se_cmd->t_data_sg, se_cmd->t_data_nents);
607 free_data_area(udev, cmd);
608 } else if (se_cmd->data_direction == DMA_TO_DEVICE) {
609 free_data_area(udev, cmd);
610 } else if (se_cmd->data_direction != DMA_NONE) {
611 pr_warn("TCMU: data direction was %d!\n",
612 se_cmd->data_direction);
615 target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
618 kmem_cache_free(tcmu_cmd_cache, cmd);
621 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
623 struct tcmu_mailbox *mb;
627 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
628 pr_err("ring broken, not handling completions\n");
632 spin_lock_irqsave(&udev->cmdr_lock, flags);
635 tcmu_flush_dcache_range(mb, sizeof(*mb));
637 while (udev->cmdr_last_cleaned != ACCESS_ONCE(mb->cmd_tail)) {
639 struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
640 struct tcmu_cmd *cmd;
642 tcmu_flush_dcache_range(entry, sizeof(*entry));
644 if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
645 UPDATE_HEAD(udev->cmdr_last_cleaned,
646 tcmu_hdr_get_len(entry->hdr.len_op),
650 WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
652 spin_lock(&udev->commands_lock);
653 cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
654 spin_unlock(&udev->commands_lock);
657 pr_err("cmd_id not found, ring is broken\n");
658 set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
662 tcmu_handle_completion(cmd, entry);
664 UPDATE_HEAD(udev->cmdr_last_cleaned,
665 tcmu_hdr_get_len(entry->hdr.len_op),
671 if (mb->cmd_tail == mb->cmd_head)
672 del_timer(&udev->timeout); /* no more pending cmds */
674 spin_unlock_irqrestore(&udev->cmdr_lock, flags);
676 wake_up(&udev->wait_cmdr);
681 static int tcmu_check_expired_cmd(int id, void *p, void *data)
683 struct tcmu_cmd *cmd = p;
685 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
688 if (!time_after(jiffies, cmd->deadline))
691 set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
692 target_complete_cmd(cmd->se_cmd, SAM_STAT_CHECK_CONDITION);
698 static void tcmu_device_timedout(unsigned long data)
700 struct tcmu_dev *udev = (struct tcmu_dev *)data;
704 handled = tcmu_handle_completions(udev);
706 pr_warn("%d completions handled from timeout\n", handled);
708 spin_lock_irqsave(&udev->commands_lock, flags);
709 idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
710 spin_unlock_irqrestore(&udev->commands_lock, flags);
713 * We don't need to wakeup threads on wait_cmdr since they have their
718 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
720 struct tcmu_hba *tcmu_hba;
722 tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
726 tcmu_hba->host_id = host_id;
727 hba->hba_ptr = tcmu_hba;
732 static void tcmu_detach_hba(struct se_hba *hba)
738 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
740 struct tcmu_dev *udev;
742 udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
746 udev->name = kstrdup(name, GFP_KERNEL);
753 udev->cmd_time_out = TCMU_TIME_OUT;
755 init_waitqueue_head(&udev->wait_cmdr);
756 spin_lock_init(&udev->cmdr_lock);
758 idr_init(&udev->commands);
759 spin_lock_init(&udev->commands_lock);
761 setup_timer(&udev->timeout, tcmu_device_timedout,
762 (unsigned long)udev);
764 return &udev->se_dev;
767 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
769 struct tcmu_dev *tcmu_dev = container_of(info, struct tcmu_dev, uio_info);
771 tcmu_handle_completions(tcmu_dev);
777 * mmap code from uio.c. Copied here because we want to hook mmap()
778 * and this stuff must come along.
780 static int tcmu_find_mem_index(struct vm_area_struct *vma)
782 struct tcmu_dev *udev = vma->vm_private_data;
783 struct uio_info *info = &udev->uio_info;
785 if (vma->vm_pgoff < MAX_UIO_MAPS) {
786 if (info->mem[vma->vm_pgoff].size == 0)
788 return (int)vma->vm_pgoff;
793 static int tcmu_vma_fault(struct vm_fault *vmf)
795 struct tcmu_dev *udev = vmf->vma->vm_private_data;
796 struct uio_info *info = &udev->uio_info;
798 unsigned long offset;
801 int mi = tcmu_find_mem_index(vmf->vma);
803 return VM_FAULT_SIGBUS;
806 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
809 offset = (vmf->pgoff - mi) << PAGE_SHIFT;
811 addr = (void *)(unsigned long)info->mem[mi].addr + offset;
812 if (info->mem[mi].memtype == UIO_MEM_LOGICAL)
813 page = virt_to_page(addr);
815 page = vmalloc_to_page(addr);
821 static const struct vm_operations_struct tcmu_vm_ops = {
822 .fault = tcmu_vma_fault,
825 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
827 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
829 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
830 vma->vm_ops = &tcmu_vm_ops;
832 vma->vm_private_data = udev;
834 /* Ensure the mmap is exactly the right size */
835 if (vma_pages(vma) != (TCMU_RING_SIZE >> PAGE_SHIFT))
841 static int tcmu_open(struct uio_info *info, struct inode *inode)
843 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
845 /* O_EXCL not supported for char devs, so fake it? */
846 if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
854 static int tcmu_release(struct uio_info *info, struct inode *inode)
856 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
858 clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
865 static int tcmu_netlink_event(enum tcmu_genl_cmd cmd, const char *name, int minor)
871 skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
875 msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
879 ret = nla_put_string(skb, TCMU_ATTR_DEVICE, name);
883 ret = nla_put_u32(skb, TCMU_ATTR_MINOR, minor);
887 genlmsg_end(skb, msg_header);
889 ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
890 TCMU_MCGRP_CONFIG, GFP_KERNEL);
892 /* We don't care if no one is listening */
902 static int tcmu_configure_device(struct se_device *dev)
904 struct tcmu_dev *udev = TCMU_DEV(dev);
905 struct tcmu_hba *hba = udev->hba->hba_ptr;
906 struct uio_info *info;
907 struct tcmu_mailbox *mb;
913 info = &udev->uio_info;
915 size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
917 size += 1; /* for \0 */
918 str = kmalloc(size, GFP_KERNEL);
922 used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
924 if (udev->dev_config[0])
925 snprintf(str + used, size - used, "/%s", udev->dev_config);
929 udev->mb_addr = vzalloc(TCMU_RING_SIZE);
930 if (!udev->mb_addr) {
935 /* mailbox fits in first part of CMDR space */
936 udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
937 udev->data_off = CMDR_SIZE;
938 udev->data_size = TCMU_RING_SIZE - CMDR_SIZE;
941 mb->version = TCMU_MAILBOX_VERSION;
942 mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC;
943 mb->cmdr_off = CMDR_OFF;
944 mb->cmdr_size = udev->cmdr_size;
946 WARN_ON(!PAGE_ALIGNED(udev->data_off));
947 WARN_ON(udev->data_size % PAGE_SIZE);
948 WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
950 info->version = __stringify(TCMU_MAILBOX_VERSION);
952 info->mem[0].name = "tcm-user command & data buffer";
953 info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
954 info->mem[0].size = TCMU_RING_SIZE;
955 info->mem[0].memtype = UIO_MEM_VIRTUAL;
957 info->irqcontrol = tcmu_irqcontrol;
958 info->irq = UIO_IRQ_CUSTOM;
960 info->mmap = tcmu_mmap;
961 info->open = tcmu_open;
962 info->release = tcmu_release;
964 ret = uio_register_device(tcmu_root_device, info);
968 /* User can set hw_block_size before enable the device */
969 if (dev->dev_attrib.hw_block_size == 0)
970 dev->dev_attrib.hw_block_size = 512;
971 /* Other attributes can be configured in userspace */
972 if (!dev->dev_attrib.hw_max_sectors)
973 dev->dev_attrib.hw_max_sectors = 128;
974 dev->dev_attrib.hw_queue_depth = 128;
976 ret = tcmu_netlink_event(TCMU_CMD_ADDED_DEVICE, udev->uio_info.name,
977 udev->uio_info.uio_dev->minor);
984 uio_unregister_device(&udev->uio_info);
986 vfree(udev->mb_addr);
993 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
995 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
996 kmem_cache_free(tcmu_cmd_cache, cmd);
1002 static void tcmu_dev_call_rcu(struct rcu_head *p)
1004 struct se_device *dev = container_of(p, struct se_device, rcu_head);
1005 struct tcmu_dev *udev = TCMU_DEV(dev);
1010 static bool tcmu_dev_configured(struct tcmu_dev *udev)
1012 return udev->uio_info.uio_dev ? true : false;
1015 static void tcmu_free_device(struct se_device *dev)
1017 struct tcmu_dev *udev = TCMU_DEV(dev);
1018 struct tcmu_cmd *cmd;
1019 bool all_expired = true;
1022 del_timer_sync(&udev->timeout);
1024 vfree(udev->mb_addr);
1026 /* Upper layer should drain all requests before calling this */
1027 spin_lock_irq(&udev->commands_lock);
1028 idr_for_each_entry(&udev->commands, cmd, i) {
1029 if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1030 all_expired = false;
1032 idr_destroy(&udev->commands);
1033 spin_unlock_irq(&udev->commands_lock);
1034 WARN_ON(!all_expired);
1036 if (tcmu_dev_configured(udev)) {
1037 tcmu_netlink_event(TCMU_CMD_REMOVED_DEVICE, udev->uio_info.name,
1038 udev->uio_info.uio_dev->minor);
1040 uio_unregister_device(&udev->uio_info);
1041 kfree(udev->uio_info.name);
1044 call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1048 Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
1049 Opt_cmd_time_out, Opt_err,
1052 static match_table_t tokens = {
1053 {Opt_dev_config, "dev_config=%s"},
1054 {Opt_dev_size, "dev_size=%u"},
1055 {Opt_hw_block_size, "hw_block_size=%u"},
1056 {Opt_hw_max_sectors, "hw_max_sectors=%u"},
1057 {Opt_cmd_time_out, "cmd_time_out=%u"},
1061 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
1063 unsigned long tmp_ul;
1067 arg_p = match_strdup(arg);
1071 ret = kstrtoul(arg_p, 0, &tmp_ul);
1074 pr_err("kstrtoul() failed for dev attrib\n");
1078 pr_err("dev attrib must be nonzero\n");
1081 *dev_attrib = tmp_ul;
1085 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
1086 const char *page, ssize_t count)
1088 struct tcmu_dev *udev = TCMU_DEV(dev);
1089 char *orig, *ptr, *opts, *arg_p;
1090 substring_t args[MAX_OPT_ARGS];
1093 opts = kstrdup(page, GFP_KERNEL);
1099 while ((ptr = strsep(&opts, ",\n")) != NULL) {
1103 token = match_token(ptr, tokens, args);
1105 case Opt_dev_config:
1106 if (match_strlcpy(udev->dev_config, &args[0],
1107 TCMU_CONFIG_LEN) == 0) {
1111 pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
1114 arg_p = match_strdup(&args[0]);
1119 ret = kstrtoul(arg_p, 0, (unsigned long *) &udev->dev_size);
1122 pr_err("kstrtoul() failed for dev_size=\n");
1124 case Opt_cmd_time_out:
1125 if (tcmu_dev_configured(udev)) {
1126 pr_err("Can not update cmd_time_out after device has been configured.\n");
1130 arg_p = match_strdup(&args[0]);
1135 ret = kstrtouint(arg_p, 0, &udev->cmd_time_out);
1138 pr_err("kstrtouint() failed for cmd_time_out=\n");
1139 udev->cmd_time_out *= MSEC_PER_SEC;
1141 case Opt_hw_block_size:
1142 ret = tcmu_set_dev_attrib(&args[0],
1143 &(dev->dev_attrib.hw_block_size));
1145 case Opt_hw_max_sectors:
1146 ret = tcmu_set_dev_attrib(&args[0],
1147 &(dev->dev_attrib.hw_max_sectors));
1158 return (!ret) ? count : ret;
1161 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
1163 struct tcmu_dev *udev = TCMU_DEV(dev);
1166 bl = sprintf(b + bl, "Config: %s ",
1167 udev->dev_config[0] ? udev->dev_config : "NULL");
1168 bl += sprintf(b + bl, "Size: %zu ", udev->dev_size);
1169 bl += sprintf(b + bl, "Cmd Time Out: %lu\n",
1170 udev->cmd_time_out / MSEC_PER_SEC);
1175 static sector_t tcmu_get_blocks(struct se_device *dev)
1177 struct tcmu_dev *udev = TCMU_DEV(dev);
1179 return div_u64(udev->dev_size - dev->dev_attrib.block_size,
1180 dev->dev_attrib.block_size);
1183 static sense_reason_t
1184 tcmu_parse_cdb(struct se_cmd *cmd)
1186 return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
1189 static const struct target_backend_ops tcmu_ops = {
1191 .owner = THIS_MODULE,
1192 .transport_flags = TRANSPORT_FLAG_PASSTHROUGH,
1193 .attach_hba = tcmu_attach_hba,
1194 .detach_hba = tcmu_detach_hba,
1195 .alloc_device = tcmu_alloc_device,
1196 .configure_device = tcmu_configure_device,
1197 .free_device = tcmu_free_device,
1198 .parse_cdb = tcmu_parse_cdb,
1199 .set_configfs_dev_params = tcmu_set_configfs_dev_params,
1200 .show_configfs_dev_params = tcmu_show_configfs_dev_params,
1201 .get_device_type = sbc_get_device_type,
1202 .get_blocks = tcmu_get_blocks,
1203 .tb_dev_attrib_attrs = passthrough_attrib_attrs,
1206 static int __init tcmu_module_init(void)
1210 BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
1212 tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
1213 sizeof(struct tcmu_cmd),
1214 __alignof__(struct tcmu_cmd),
1216 if (!tcmu_cmd_cache)
1219 tcmu_root_device = root_device_register("tcm_user");
1220 if (IS_ERR(tcmu_root_device)) {
1221 ret = PTR_ERR(tcmu_root_device);
1222 goto out_free_cache;
1225 ret = genl_register_family(&tcmu_genl_family);
1227 goto out_unreg_device;
1230 ret = transport_backend_register(&tcmu_ops);
1232 goto out_unreg_genl;
1237 genl_unregister_family(&tcmu_genl_family);
1239 root_device_unregister(tcmu_root_device);
1241 kmem_cache_destroy(tcmu_cmd_cache);
1246 static void __exit tcmu_module_exit(void)
1248 target_backend_unregister(&tcmu_ops);
1249 genl_unregister_family(&tcmu_genl_family);
1250 root_device_unregister(tcmu_root_device);
1251 kmem_cache_destroy(tcmu_cmd_cache);
1254 MODULE_DESCRIPTION("TCM USER subsystem plugin");
1255 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
1256 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
1257 MODULE_LICENSE("GPL");
1259 module_init(tcmu_module_init);
1260 module_exit(tcmu_module_exit);