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 <linux/configfs.h>
32 #include <net/genetlink.h>
33 #include <scsi/scsi_common.h>
34 #include <scsi/scsi_proto.h>
35 #include <target/target_core_base.h>
36 #include <target/target_core_fabric.h>
37 #include <target/target_core_backend.h>
39 #include <linux/target_core_user.h>
42 * Define a shared-memory interface for LIO to pass SCSI commands and
43 * data to userspace for processing. This is to allow backends that
44 * are too complex for in-kernel support to be possible.
46 * It uses the UIO framework to do a lot of the device-creation and
47 * introspection work for us.
49 * See the .h file for how the ring is laid out. Note that while the
50 * command ring is defined, the particulars of the data area are
51 * not. Offset values in the command entry point to other locations
52 * internal to the mmap()ed area. There is separate space outside the
53 * command ring for data buffers. This leaves maximum flexibility for
54 * moving buffer allocations, or even page flipping or other
55 * allocation techniques, without altering the command ring layout.
58 * The user process must be assumed to be malicious. There's no way to
59 * prevent it breaking the command ring protocol if it wants, but in
60 * order to prevent other issues we must only ever read *data* from
61 * the shared memory area, not offsets or sizes. This applies to
62 * command ring entries as well as the mailbox. Extra code needed for
63 * this may have a 'UAM' comment.
67 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
69 #define DATA_BLOCK_BITS 256
70 #define DATA_BLOCK_SIZE 4096
72 #define CMDR_SIZE (16 * 4096)
73 #define DATA_SIZE (DATA_BLOCK_BITS * DATA_BLOCK_SIZE)
75 #define TCMU_RING_SIZE (CMDR_SIZE + DATA_SIZE)
77 static struct device *tcmu_root_device;
83 #define TCMU_CONFIG_LEN 256
86 struct se_device se_dev;
91 #define TCMU_DEV_BIT_OPEN 0
92 #define TCMU_DEV_BIT_BROKEN 1
95 struct uio_info uio_info;
97 struct tcmu_mailbox *mb_addr;
100 u32 cmdr_last_cleaned;
101 /* Offset of data area from start of mb */
102 /* Must add data_off and mb_addr to get the address */
106 DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
108 wait_queue_head_t wait_cmdr;
109 /* TODO should this be a mutex? */
110 spinlock_t cmdr_lock;
113 spinlock_t commands_lock;
115 struct timer_list timeout;
116 unsigned int cmd_time_out;
118 char dev_config[TCMU_CONFIG_LEN];
121 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
123 #define CMDR_OFF sizeof(struct tcmu_mailbox)
126 struct se_cmd *se_cmd;
127 struct tcmu_dev *tcmu_dev;
131 /* Can't use se_cmd when cleaning up expired cmds, because if
132 cmd has been completed then accessing se_cmd is off limits */
133 DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
135 unsigned long deadline;
137 #define TCMU_CMD_BIT_EXPIRED 0
141 static struct kmem_cache *tcmu_cmd_cache;
143 /* multicast group */
144 enum tcmu_multicast_groups {
148 static const struct genl_multicast_group tcmu_mcgrps[] = {
149 [TCMU_MCGRP_CONFIG] = { .name = "config", },
152 /* Our generic netlink family */
153 static struct genl_family tcmu_genl_family __ro_after_init = {
154 .module = THIS_MODULE,
158 .maxattr = TCMU_ATTR_MAX,
159 .mcgrps = tcmu_mcgrps,
160 .n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
164 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
166 struct se_device *se_dev = se_cmd->se_dev;
167 struct tcmu_dev *udev = TCMU_DEV(se_dev);
168 struct tcmu_cmd *tcmu_cmd;
171 tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
175 tcmu_cmd->se_cmd = se_cmd;
176 tcmu_cmd->tcmu_dev = udev;
177 if (udev->cmd_time_out)
178 tcmu_cmd->deadline = jiffies +
179 msecs_to_jiffies(udev->cmd_time_out);
181 idr_preload(GFP_KERNEL);
182 spin_lock_irq(&udev->commands_lock);
183 cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 0,
184 USHRT_MAX, GFP_NOWAIT);
185 spin_unlock_irq(&udev->commands_lock);
189 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
192 tcmu_cmd->cmd_id = cmd_id;
197 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
199 unsigned long offset = offset_in_page(vaddr);
201 size = round_up(size+offset, PAGE_SIZE);
205 flush_dcache_page(virt_to_page(vaddr));
211 * Some ring helper functions. We don't assume size is a power of 2 so
212 * we can't use circ_buf.h.
214 static inline size_t spc_used(size_t head, size_t tail, size_t size)
216 int diff = head - tail;
224 static inline size_t spc_free(size_t head, size_t tail, size_t size)
226 /* Keep 1 byte unused or we can't tell full from empty */
227 return (size - spc_used(head, tail, size) - 1);
230 static inline size_t head_to_end(size_t head, size_t size)
235 static inline void new_iov(struct iovec **iov, int *iov_cnt,
236 struct tcmu_dev *udev)
245 memset(iovec, 0, sizeof(struct iovec));
248 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
250 /* offset is relative to mb_addr */
251 static inline size_t get_block_offset(struct tcmu_dev *dev,
252 int block, int remaining)
254 return dev->data_off + block * DATA_BLOCK_SIZE +
255 DATA_BLOCK_SIZE - remaining;
258 static inline size_t iov_tail(struct tcmu_dev *udev, struct iovec *iov)
260 return (size_t)iov->iov_base + iov->iov_len;
263 static void alloc_and_scatter_data_area(struct tcmu_dev *udev,
264 struct scatterlist *data_sg, unsigned int data_nents,
265 struct iovec **iov, int *iov_cnt, bool copy_data)
268 int block_remaining = 0;
270 size_t copy_bytes, to_offset;
271 struct scatterlist *sg;
273 for_each_sg(data_sg, sg, data_nents, i) {
274 int sg_remaining = sg->length;
275 from = kmap_atomic(sg_page(sg)) + sg->offset;
276 while (sg_remaining > 0) {
277 if (block_remaining == 0) {
278 block = find_first_zero_bit(udev->data_bitmap,
280 block_remaining = DATA_BLOCK_SIZE;
281 set_bit(block, udev->data_bitmap);
283 copy_bytes = min_t(size_t, sg_remaining,
285 to_offset = get_block_offset(udev, block,
287 to = (void *)udev->mb_addr + to_offset;
289 to_offset == iov_tail(udev, *iov)) {
290 (*iov)->iov_len += copy_bytes;
292 new_iov(iov, iov_cnt, udev);
293 (*iov)->iov_base = (void __user *) to_offset;
294 (*iov)->iov_len = copy_bytes;
297 memcpy(to, from + sg->length - sg_remaining,
299 tcmu_flush_dcache_range(to, copy_bytes);
301 sg_remaining -= copy_bytes;
302 block_remaining -= copy_bytes;
304 kunmap_atomic(from - sg->offset);
308 static void free_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd)
310 bitmap_xor(udev->data_bitmap, udev->data_bitmap, cmd->data_bitmap,
314 static void gather_data_area(struct tcmu_dev *udev, unsigned long *cmd_bitmap,
315 struct scatterlist *data_sg, unsigned int data_nents)
318 int block_remaining = 0;
320 size_t copy_bytes, from_offset;
321 struct scatterlist *sg;
323 for_each_sg(data_sg, sg, data_nents, i) {
324 int sg_remaining = sg->length;
325 to = kmap_atomic(sg_page(sg)) + sg->offset;
326 while (sg_remaining > 0) {
327 if (block_remaining == 0) {
328 block = find_first_bit(cmd_bitmap,
330 block_remaining = DATA_BLOCK_SIZE;
331 clear_bit(block, cmd_bitmap);
333 copy_bytes = min_t(size_t, sg_remaining,
335 from_offset = get_block_offset(udev, block,
337 from = (void *) udev->mb_addr + from_offset;
338 tcmu_flush_dcache_range(from, copy_bytes);
339 memcpy(to + sg->length - sg_remaining, from,
342 sg_remaining -= copy_bytes;
343 block_remaining -= copy_bytes;
345 kunmap_atomic(to - sg->offset);
349 static inline size_t spc_bitmap_free(unsigned long *bitmap)
351 return DATA_BLOCK_SIZE * (DATA_BLOCK_BITS -
352 bitmap_weight(bitmap, DATA_BLOCK_BITS));
356 * We can't queue a command until we have space available on the cmd ring *and*
357 * space available on the data area.
359 * Called with ring lock held.
361 static bool is_ring_space_avail(struct tcmu_dev *udev, size_t cmd_size, size_t data_needed)
363 struct tcmu_mailbox *mb = udev->mb_addr;
364 size_t space, cmd_needed;
367 tcmu_flush_dcache_range(mb, sizeof(*mb));
369 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
372 * If cmd end-of-ring space is too small then we need space for a NOP plus
373 * original cmd - cmds are internally contiguous.
375 if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
376 cmd_needed = cmd_size;
378 cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
380 space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
381 if (space < cmd_needed) {
382 pr_debug("no cmd space: %u %u %u\n", cmd_head,
383 udev->cmdr_last_cleaned, udev->cmdr_size);
387 space = spc_bitmap_free(udev->data_bitmap);
388 if (space < data_needed) {
389 pr_debug("no data space: only %zu available, but ask for %zu\n",
397 static inline size_t tcmu_cmd_get_data_length(struct tcmu_cmd *tcmu_cmd)
399 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
400 size_t data_length = round_up(se_cmd->data_length, DATA_BLOCK_SIZE);
402 if (se_cmd->se_cmd_flags & SCF_BIDI) {
403 BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
404 data_length += round_up(se_cmd->t_bidi_data_sg->length,
411 static sense_reason_t
412 tcmu_queue_cmd_ring(struct tcmu_cmd *tcmu_cmd)
414 struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
415 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
416 size_t base_command_size, command_size;
417 struct tcmu_mailbox *mb;
418 struct tcmu_cmd_entry *entry;
423 bool copy_to_data_area;
424 size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
425 DECLARE_BITMAP(old_bitmap, DATA_BLOCK_BITS);
427 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
428 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
431 * Must be a certain minimum size for response sense info, but
432 * also may be larger if the iov array is large.
434 * We prepare way too many iovs for potential uses here, because it's
435 * expensive to tell how many regions are freed in the bitmap
437 base_command_size = max(offsetof(struct tcmu_cmd_entry,
438 req.iov[se_cmd->t_bidi_data_nents +
439 se_cmd->t_data_nents]),
440 sizeof(struct tcmu_cmd_entry));
441 command_size = base_command_size
442 + round_up(scsi_command_size(se_cmd->t_task_cdb), TCMU_OP_ALIGN_SIZE);
444 WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
446 spin_lock_irq(&udev->cmdr_lock);
449 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
450 if ((command_size > (udev->cmdr_size / 2)) ||
451 data_length > udev->data_size) {
452 pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
453 "cmd ring/data area\n", command_size, data_length,
454 udev->cmdr_size, udev->data_size);
455 spin_unlock_irq(&udev->cmdr_lock);
456 return TCM_INVALID_CDB_FIELD;
459 while (!is_ring_space_avail(udev, command_size, data_length)) {
463 prepare_to_wait(&udev->wait_cmdr, &__wait, TASK_INTERRUPTIBLE);
465 pr_debug("sleeping for ring space\n");
466 spin_unlock_irq(&udev->cmdr_lock);
467 if (udev->cmd_time_out)
468 ret = schedule_timeout(
469 msecs_to_jiffies(udev->cmd_time_out));
471 ret = schedule_timeout(msecs_to_jiffies(TCMU_TIME_OUT));
472 finish_wait(&udev->wait_cmdr, &__wait);
474 pr_warn("tcmu: command timed out\n");
475 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
478 spin_lock_irq(&udev->cmdr_lock);
480 /* We dropped cmdr_lock, cmd_head is stale */
481 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
484 /* Insert a PAD if end-of-ring space is too small */
485 if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
486 size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
488 entry = (void *) mb + CMDR_OFF + cmd_head;
489 tcmu_flush_dcache_range(entry, sizeof(*entry));
490 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
491 tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
492 entry->hdr.cmd_id = 0; /* not used for PAD */
493 entry->hdr.kflags = 0;
494 entry->hdr.uflags = 0;
496 UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
498 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
499 WARN_ON(cmd_head != 0);
502 entry = (void *) mb + CMDR_OFF + cmd_head;
503 tcmu_flush_dcache_range(entry, sizeof(*entry));
504 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
505 tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
506 entry->hdr.cmd_id = tcmu_cmd->cmd_id;
507 entry->hdr.kflags = 0;
508 entry->hdr.uflags = 0;
510 bitmap_copy(old_bitmap, udev->data_bitmap, DATA_BLOCK_BITS);
512 /* Handle allocating space from the data area */
513 iov = &entry->req.iov[0];
515 copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
516 || se_cmd->se_cmd_flags & SCF_BIDI);
517 alloc_and_scatter_data_area(udev, se_cmd->t_data_sg,
518 se_cmd->t_data_nents, &iov, &iov_cnt, copy_to_data_area);
519 entry->req.iov_cnt = iov_cnt;
520 entry->req.iov_dif_cnt = 0;
522 /* Handle BIDI commands */
523 if (se_cmd->se_cmd_flags & SCF_BIDI) {
526 alloc_and_scatter_data_area(udev, se_cmd->t_bidi_data_sg,
527 se_cmd->t_bidi_data_nents, &iov, &iov_cnt,
529 entry->req.iov_bidi_cnt = iov_cnt;
531 /* cmd's data_bitmap is what changed in process */
532 bitmap_xor(tcmu_cmd->data_bitmap, old_bitmap, udev->data_bitmap,
535 /* All offsets relative to mb_addr, not start of entry! */
536 cdb_off = CMDR_OFF + cmd_head + base_command_size;
537 memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
538 entry->req.cdb_off = cdb_off;
539 tcmu_flush_dcache_range(entry, sizeof(*entry));
541 UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
542 tcmu_flush_dcache_range(mb, sizeof(*mb));
544 spin_unlock_irq(&udev->cmdr_lock);
546 /* TODO: only if FLUSH and FUA? */
547 uio_event_notify(&udev->uio_info);
549 if (udev->cmd_time_out)
550 mod_timer(&udev->timeout, round_jiffies_up(jiffies +
551 msecs_to_jiffies(udev->cmd_time_out)));
556 static sense_reason_t
557 tcmu_queue_cmd(struct se_cmd *se_cmd)
559 struct se_device *se_dev = se_cmd->se_dev;
560 struct tcmu_dev *udev = TCMU_DEV(se_dev);
561 struct tcmu_cmd *tcmu_cmd;
564 tcmu_cmd = tcmu_alloc_cmd(se_cmd);
566 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
568 ret = tcmu_queue_cmd_ring(tcmu_cmd);
569 if (ret != TCM_NO_SENSE) {
570 pr_err("TCMU: Could not queue command\n");
571 spin_lock_irq(&udev->commands_lock);
572 idr_remove(&udev->commands, tcmu_cmd->cmd_id);
573 spin_unlock_irq(&udev->commands_lock);
575 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
581 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
583 struct se_cmd *se_cmd = cmd->se_cmd;
584 struct tcmu_dev *udev = cmd->tcmu_dev;
586 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
588 * cmd has been completed already from timeout, just reclaim
589 * data area space and free cmd
591 free_data_area(udev, cmd);
593 kmem_cache_free(tcmu_cmd_cache, cmd);
597 if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
598 free_data_area(udev, cmd);
599 pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
601 entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
602 } else if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
603 memcpy(se_cmd->sense_buffer, entry->rsp.sense_buffer,
604 se_cmd->scsi_sense_length);
605 free_data_area(udev, cmd);
606 } else if (se_cmd->se_cmd_flags & SCF_BIDI) {
607 DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
609 /* Get Data-In buffer before clean up */
610 bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
611 gather_data_area(udev, bitmap,
612 se_cmd->t_bidi_data_sg, se_cmd->t_bidi_data_nents);
613 free_data_area(udev, cmd);
614 } else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
615 DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
617 bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
618 gather_data_area(udev, bitmap,
619 se_cmd->t_data_sg, se_cmd->t_data_nents);
620 free_data_area(udev, cmd);
621 } else if (se_cmd->data_direction == DMA_TO_DEVICE) {
622 free_data_area(udev, cmd);
623 } else if (se_cmd->data_direction != DMA_NONE) {
624 pr_warn("TCMU: data direction was %d!\n",
625 se_cmd->data_direction);
628 target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
631 kmem_cache_free(tcmu_cmd_cache, cmd);
634 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
636 struct tcmu_mailbox *mb;
640 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
641 pr_err("ring broken, not handling completions\n");
645 spin_lock_irqsave(&udev->cmdr_lock, flags);
648 tcmu_flush_dcache_range(mb, sizeof(*mb));
650 while (udev->cmdr_last_cleaned != ACCESS_ONCE(mb->cmd_tail)) {
652 struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
653 struct tcmu_cmd *cmd;
655 tcmu_flush_dcache_range(entry, sizeof(*entry));
657 if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
658 UPDATE_HEAD(udev->cmdr_last_cleaned,
659 tcmu_hdr_get_len(entry->hdr.len_op),
663 WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
665 spin_lock(&udev->commands_lock);
666 cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
667 spin_unlock(&udev->commands_lock);
670 pr_err("cmd_id not found, ring is broken\n");
671 set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
675 tcmu_handle_completion(cmd, entry);
677 UPDATE_HEAD(udev->cmdr_last_cleaned,
678 tcmu_hdr_get_len(entry->hdr.len_op),
684 if (mb->cmd_tail == mb->cmd_head)
685 del_timer(&udev->timeout); /* no more pending cmds */
687 spin_unlock_irqrestore(&udev->cmdr_lock, flags);
689 wake_up(&udev->wait_cmdr);
694 static int tcmu_check_expired_cmd(int id, void *p, void *data)
696 struct tcmu_cmd *cmd = p;
698 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
701 if (!time_after(jiffies, cmd->deadline))
704 set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
705 target_complete_cmd(cmd->se_cmd, SAM_STAT_CHECK_CONDITION);
711 static void tcmu_device_timedout(unsigned long data)
713 struct tcmu_dev *udev = (struct tcmu_dev *)data;
717 handled = tcmu_handle_completions(udev);
719 pr_warn("%d completions handled from timeout\n", handled);
721 spin_lock_irqsave(&udev->commands_lock, flags);
722 idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
723 spin_unlock_irqrestore(&udev->commands_lock, flags);
726 * We don't need to wakeup threads on wait_cmdr since they have their
731 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
733 struct tcmu_hba *tcmu_hba;
735 tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
739 tcmu_hba->host_id = host_id;
740 hba->hba_ptr = tcmu_hba;
745 static void tcmu_detach_hba(struct se_hba *hba)
751 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
753 struct tcmu_dev *udev;
755 udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
759 udev->name = kstrdup(name, GFP_KERNEL);
766 udev->cmd_time_out = TCMU_TIME_OUT;
768 init_waitqueue_head(&udev->wait_cmdr);
769 spin_lock_init(&udev->cmdr_lock);
771 idr_init(&udev->commands);
772 spin_lock_init(&udev->commands_lock);
774 setup_timer(&udev->timeout, tcmu_device_timedout,
775 (unsigned long)udev);
777 return &udev->se_dev;
780 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
782 struct tcmu_dev *tcmu_dev = container_of(info, struct tcmu_dev, uio_info);
784 tcmu_handle_completions(tcmu_dev);
790 * mmap code from uio.c. Copied here because we want to hook mmap()
791 * and this stuff must come along.
793 static int tcmu_find_mem_index(struct vm_area_struct *vma)
795 struct tcmu_dev *udev = vma->vm_private_data;
796 struct uio_info *info = &udev->uio_info;
798 if (vma->vm_pgoff < MAX_UIO_MAPS) {
799 if (info->mem[vma->vm_pgoff].size == 0)
801 return (int)vma->vm_pgoff;
806 static int tcmu_vma_fault(struct vm_fault *vmf)
808 struct tcmu_dev *udev = vmf->vma->vm_private_data;
809 struct uio_info *info = &udev->uio_info;
811 unsigned long offset;
814 int mi = tcmu_find_mem_index(vmf->vma);
816 return VM_FAULT_SIGBUS;
819 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
822 offset = (vmf->pgoff - mi) << PAGE_SHIFT;
824 addr = (void *)(unsigned long)info->mem[mi].addr + offset;
825 if (info->mem[mi].memtype == UIO_MEM_LOGICAL)
826 page = virt_to_page(addr);
828 page = vmalloc_to_page(addr);
834 static const struct vm_operations_struct tcmu_vm_ops = {
835 .fault = tcmu_vma_fault,
838 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
840 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
842 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
843 vma->vm_ops = &tcmu_vm_ops;
845 vma->vm_private_data = udev;
847 /* Ensure the mmap is exactly the right size */
848 if (vma_pages(vma) != (TCMU_RING_SIZE >> PAGE_SHIFT))
854 static int tcmu_open(struct uio_info *info, struct inode *inode)
856 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
858 /* O_EXCL not supported for char devs, so fake it? */
859 if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
867 static int tcmu_release(struct uio_info *info, struct inode *inode)
869 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
871 clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
878 static int tcmu_netlink_event(enum tcmu_genl_cmd cmd, const char *name, int minor)
884 skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
888 msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
892 ret = nla_put_string(skb, TCMU_ATTR_DEVICE, name);
896 ret = nla_put_u32(skb, TCMU_ATTR_MINOR, minor);
900 genlmsg_end(skb, msg_header);
902 ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
903 TCMU_MCGRP_CONFIG, GFP_KERNEL);
905 /* We don't care if no one is listening */
915 static int tcmu_configure_device(struct se_device *dev)
917 struct tcmu_dev *udev = TCMU_DEV(dev);
918 struct tcmu_hba *hba = udev->hba->hba_ptr;
919 struct uio_info *info;
920 struct tcmu_mailbox *mb;
926 info = &udev->uio_info;
928 size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
930 size += 1; /* for \0 */
931 str = kmalloc(size, GFP_KERNEL);
935 used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
937 if (udev->dev_config[0])
938 snprintf(str + used, size - used, "/%s", udev->dev_config);
942 udev->mb_addr = vzalloc(TCMU_RING_SIZE);
943 if (!udev->mb_addr) {
948 /* mailbox fits in first part of CMDR space */
949 udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
950 udev->data_off = CMDR_SIZE;
951 udev->data_size = TCMU_RING_SIZE - CMDR_SIZE;
954 mb->version = TCMU_MAILBOX_VERSION;
955 mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC;
956 mb->cmdr_off = CMDR_OFF;
957 mb->cmdr_size = udev->cmdr_size;
959 WARN_ON(!PAGE_ALIGNED(udev->data_off));
960 WARN_ON(udev->data_size % PAGE_SIZE);
961 WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
963 info->version = __stringify(TCMU_MAILBOX_VERSION);
965 info->mem[0].name = "tcm-user command & data buffer";
966 info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
967 info->mem[0].size = TCMU_RING_SIZE;
968 info->mem[0].memtype = UIO_MEM_VIRTUAL;
970 info->irqcontrol = tcmu_irqcontrol;
971 info->irq = UIO_IRQ_CUSTOM;
973 info->mmap = tcmu_mmap;
974 info->open = tcmu_open;
975 info->release = tcmu_release;
977 ret = uio_register_device(tcmu_root_device, info);
981 /* User can set hw_block_size before enable the device */
982 if (dev->dev_attrib.hw_block_size == 0)
983 dev->dev_attrib.hw_block_size = 512;
984 /* Other attributes can be configured in userspace */
985 if (!dev->dev_attrib.hw_max_sectors)
986 dev->dev_attrib.hw_max_sectors = 128;
987 dev->dev_attrib.hw_queue_depth = 128;
989 ret = tcmu_netlink_event(TCMU_CMD_ADDED_DEVICE, udev->uio_info.name,
990 udev->uio_info.uio_dev->minor);
997 uio_unregister_device(&udev->uio_info);
999 vfree(udev->mb_addr);
1006 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1008 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1009 kmem_cache_free(tcmu_cmd_cache, cmd);
1015 static void tcmu_dev_call_rcu(struct rcu_head *p)
1017 struct se_device *dev = container_of(p, struct se_device, rcu_head);
1018 struct tcmu_dev *udev = TCMU_DEV(dev);
1023 static bool tcmu_dev_configured(struct tcmu_dev *udev)
1025 return udev->uio_info.uio_dev ? true : false;
1028 static void tcmu_free_device(struct se_device *dev)
1030 struct tcmu_dev *udev = TCMU_DEV(dev);
1031 struct tcmu_cmd *cmd;
1032 bool all_expired = true;
1035 del_timer_sync(&udev->timeout);
1037 vfree(udev->mb_addr);
1039 /* Upper layer should drain all requests before calling this */
1040 spin_lock_irq(&udev->commands_lock);
1041 idr_for_each_entry(&udev->commands, cmd, i) {
1042 if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1043 all_expired = false;
1045 idr_destroy(&udev->commands);
1046 spin_unlock_irq(&udev->commands_lock);
1047 WARN_ON(!all_expired);
1049 if (tcmu_dev_configured(udev)) {
1050 tcmu_netlink_event(TCMU_CMD_REMOVED_DEVICE, udev->uio_info.name,
1051 udev->uio_info.uio_dev->minor);
1053 uio_unregister_device(&udev->uio_info);
1054 kfree(udev->uio_info.name);
1057 call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1061 Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
1065 static match_table_t tokens = {
1066 {Opt_dev_config, "dev_config=%s"},
1067 {Opt_dev_size, "dev_size=%u"},
1068 {Opt_hw_block_size, "hw_block_size=%u"},
1069 {Opt_hw_max_sectors, "hw_max_sectors=%u"},
1073 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
1075 unsigned long tmp_ul;
1079 arg_p = match_strdup(arg);
1083 ret = kstrtoul(arg_p, 0, &tmp_ul);
1086 pr_err("kstrtoul() failed for dev attrib\n");
1090 pr_err("dev attrib must be nonzero\n");
1093 *dev_attrib = tmp_ul;
1097 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
1098 const char *page, ssize_t count)
1100 struct tcmu_dev *udev = TCMU_DEV(dev);
1101 char *orig, *ptr, *opts, *arg_p;
1102 substring_t args[MAX_OPT_ARGS];
1105 opts = kstrdup(page, GFP_KERNEL);
1111 while ((ptr = strsep(&opts, ",\n")) != NULL) {
1115 token = match_token(ptr, tokens, args);
1117 case Opt_dev_config:
1118 if (match_strlcpy(udev->dev_config, &args[0],
1119 TCMU_CONFIG_LEN) == 0) {
1123 pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
1126 arg_p = match_strdup(&args[0]);
1131 ret = kstrtoul(arg_p, 0, (unsigned long *) &udev->dev_size);
1134 pr_err("kstrtoul() failed for dev_size=\n");
1136 case Opt_hw_block_size:
1137 ret = tcmu_set_dev_attrib(&args[0],
1138 &(dev->dev_attrib.hw_block_size));
1140 case Opt_hw_max_sectors:
1141 ret = tcmu_set_dev_attrib(&args[0],
1142 &(dev->dev_attrib.hw_max_sectors));
1153 return (!ret) ? count : ret;
1156 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
1158 struct tcmu_dev *udev = TCMU_DEV(dev);
1161 bl = sprintf(b + bl, "Config: %s ",
1162 udev->dev_config[0] ? udev->dev_config : "NULL");
1163 bl += sprintf(b + bl, "Size: %zu\n", udev->dev_size);
1168 static sector_t tcmu_get_blocks(struct se_device *dev)
1170 struct tcmu_dev *udev = TCMU_DEV(dev);
1172 return div_u64(udev->dev_size - dev->dev_attrib.block_size,
1173 dev->dev_attrib.block_size);
1176 static sense_reason_t
1177 tcmu_parse_cdb(struct se_cmd *cmd)
1179 return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
1182 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
1184 struct se_dev_attrib *da = container_of(to_config_group(item),
1185 struct se_dev_attrib, da_group);
1186 struct tcmu_dev *udev = container_of(da->da_dev,
1187 struct tcmu_dev, se_dev);
1189 return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
1192 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
1195 struct se_dev_attrib *da = container_of(to_config_group(item),
1196 struct se_dev_attrib, da_group);
1197 struct tcmu_dev *udev = container_of(da->da_dev,
1198 struct tcmu_dev, se_dev);
1202 if (da->da_dev->export_count) {
1203 pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
1207 ret = kstrtou32(page, 0, &val);
1211 udev->cmd_time_out = val * MSEC_PER_SEC;
1214 CONFIGFS_ATTR(tcmu_, cmd_time_out);
1216 static struct configfs_attribute **tcmu_attrs;
1218 static struct target_backend_ops tcmu_ops = {
1220 .owner = THIS_MODULE,
1221 .transport_flags = TRANSPORT_FLAG_PASSTHROUGH,
1222 .attach_hba = tcmu_attach_hba,
1223 .detach_hba = tcmu_detach_hba,
1224 .alloc_device = tcmu_alloc_device,
1225 .configure_device = tcmu_configure_device,
1226 .free_device = tcmu_free_device,
1227 .parse_cdb = tcmu_parse_cdb,
1228 .set_configfs_dev_params = tcmu_set_configfs_dev_params,
1229 .show_configfs_dev_params = tcmu_show_configfs_dev_params,
1230 .get_device_type = sbc_get_device_type,
1231 .get_blocks = tcmu_get_blocks,
1232 .tb_dev_attrib_attrs = NULL,
1235 static int __init tcmu_module_init(void)
1237 int ret, i, len = 0;
1239 BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
1241 tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
1242 sizeof(struct tcmu_cmd),
1243 __alignof__(struct tcmu_cmd),
1245 if (!tcmu_cmd_cache)
1248 tcmu_root_device = root_device_register("tcm_user");
1249 if (IS_ERR(tcmu_root_device)) {
1250 ret = PTR_ERR(tcmu_root_device);
1251 goto out_free_cache;
1254 ret = genl_register_family(&tcmu_genl_family);
1256 goto out_unreg_device;
1259 for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
1260 len += sizeof(struct configfs_attribute *);
1262 len += sizeof(struct configfs_attribute *) * 2;
1264 tcmu_attrs = kzalloc(len, GFP_KERNEL);
1267 goto out_unreg_genl;
1270 for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
1271 tcmu_attrs[i] = passthrough_attrib_attrs[i];
1273 tcmu_attrs[i] = &tcmu_attr_cmd_time_out;
1274 tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
1276 ret = transport_backend_register(&tcmu_ops);
1285 genl_unregister_family(&tcmu_genl_family);
1287 root_device_unregister(tcmu_root_device);
1289 kmem_cache_destroy(tcmu_cmd_cache);
1294 static void __exit tcmu_module_exit(void)
1296 target_backend_unregister(&tcmu_ops);
1298 genl_unregister_family(&tcmu_genl_family);
1299 root_device_unregister(tcmu_root_device);
1300 kmem_cache_destroy(tcmu_cmd_cache);
1303 MODULE_DESCRIPTION("TCM USER subsystem plugin");
1304 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
1305 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
1306 MODULE_LICENSE("GPL");
1308 module_init(tcmu_module_init);
1309 module_exit(tcmu_module_exit);