Merge tag 'block-5.11-2021-01-10' of git://git.kernel.dk/linux-block
[linux/fpc-iii.git] / drivers / target / target_core_user.c
blob6b171fff007b63dec6d1cb2d0a4e1cd96bc76b63
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2013 Shaohua Li <shli@kernel.org>
4 * Copyright (C) 2014 Red Hat, Inc.
5 * Copyright (C) 2015 Arrikto, Inc.
6 * Copyright (C) 2017 Chinamobile, Inc.
7 */
9 #include <linux/spinlock.h>
10 #include <linux/module.h>
11 #include <linux/idr.h>
12 #include <linux/kernel.h>
13 #include <linux/timer.h>
14 #include <linux/parser.h>
15 #include <linux/vmalloc.h>
16 #include <linux/uio_driver.h>
17 #include <linux/radix-tree.h>
18 #include <linux/stringify.h>
19 #include <linux/bitops.h>
20 #include <linux/highmem.h>
21 #include <linux/configfs.h>
22 #include <linux/mutex.h>
23 #include <linux/workqueue.h>
24 #include <net/genetlink.h>
25 #include <scsi/scsi_common.h>
26 #include <scsi/scsi_proto.h>
27 #include <target/target_core_base.h>
28 #include <target/target_core_fabric.h>
29 #include <target/target_core_backend.h>
31 #include <linux/target_core_user.h>
33 /**
34 * DOC: Userspace I/O
35 * Userspace I/O
36 * -------------
38 * Define a shared-memory interface for LIO to pass SCSI commands and
39 * data to userspace for processing. This is to allow backends that
40 * are too complex for in-kernel support to be possible.
42 * It uses the UIO framework to do a lot of the device-creation and
43 * introspection work for us.
45 * See the .h file for how the ring is laid out. Note that while the
46 * command ring is defined, the particulars of the data area are
47 * not. Offset values in the command entry point to other locations
48 * internal to the mmap-ed area. There is separate space outside the
49 * command ring for data buffers. This leaves maximum flexibility for
50 * moving buffer allocations, or even page flipping or other
51 * allocation techniques, without altering the command ring layout.
53 * SECURITY:
54 * The user process must be assumed to be malicious. There's no way to
55 * prevent it breaking the command ring protocol if it wants, but in
56 * order to prevent other issues we must only ever read *data* from
57 * the shared memory area, not offsets or sizes. This applies to
58 * command ring entries as well as the mailbox. Extra code needed for
59 * this may have a 'UAM' comment.
62 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
64 /* For cmd area, the size is fixed 8MB */
65 #define CMDR_SIZE (8 * 1024 * 1024)
68 * For data area, the block size is PAGE_SIZE and
69 * the total size is 256K * PAGE_SIZE.
71 #define DATA_BLOCK_SIZE PAGE_SIZE
72 #define DATA_BLOCK_SHIFT PAGE_SHIFT
73 #define DATA_BLOCK_BITS_DEF (256 * 1024)
75 #define TCMU_MBS_TO_BLOCKS(_mbs) (_mbs << (20 - DATA_BLOCK_SHIFT))
76 #define TCMU_BLOCKS_TO_MBS(_blocks) (_blocks >> (20 - DATA_BLOCK_SHIFT))
79 * Default number of global data blocks(512K * PAGE_SIZE)
80 * when the unmap thread will be started.
82 #define TCMU_GLOBAL_MAX_BLOCKS_DEF (512 * 1024)
84 static u8 tcmu_kern_cmd_reply_supported;
85 static u8 tcmu_netlink_blocked;
87 static struct device *tcmu_root_device;
89 struct tcmu_hba {
90 u32 host_id;
93 #define TCMU_CONFIG_LEN 256
95 static DEFINE_MUTEX(tcmu_nl_cmd_mutex);
96 static LIST_HEAD(tcmu_nl_cmd_list);
98 struct tcmu_dev;
100 struct tcmu_nl_cmd {
101 /* wake up thread waiting for reply */
102 struct completion complete;
103 struct list_head nl_list;
104 struct tcmu_dev *udev;
105 int cmd;
106 int status;
109 struct tcmu_dev {
110 struct list_head node;
111 struct kref kref;
113 struct se_device se_dev;
115 char *name;
116 struct se_hba *hba;
118 #define TCMU_DEV_BIT_OPEN 0
119 #define TCMU_DEV_BIT_BROKEN 1
120 #define TCMU_DEV_BIT_BLOCKED 2
121 #define TCMU_DEV_BIT_TMR_NOTIFY 3
122 unsigned long flags;
124 struct uio_info uio_info;
126 struct inode *inode;
128 struct tcmu_mailbox *mb_addr;
129 uint64_t dev_size;
130 u32 cmdr_size;
131 u32 cmdr_last_cleaned;
132 /* Offset of data area from start of mb */
133 /* Must add data_off and mb_addr to get the address */
134 size_t data_off;
135 size_t data_size;
136 uint32_t max_blocks;
137 size_t ring_size;
139 struct mutex cmdr_lock;
140 struct list_head qfull_queue;
141 struct list_head tmr_queue;
143 uint32_t dbi_max;
144 uint32_t dbi_thresh;
145 unsigned long *data_bitmap;
146 struct radix_tree_root data_blocks;
148 struct idr commands;
150 struct timer_list cmd_timer;
151 unsigned int cmd_time_out;
152 struct list_head inflight_queue;
154 struct timer_list qfull_timer;
155 int qfull_time_out;
157 struct list_head timedout_entry;
159 struct tcmu_nl_cmd curr_nl_cmd;
161 char dev_config[TCMU_CONFIG_LEN];
163 int nl_reply_supported;
166 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
168 #define CMDR_OFF sizeof(struct tcmu_mailbox)
170 struct tcmu_cmd {
171 struct se_cmd *se_cmd;
172 struct tcmu_dev *tcmu_dev;
173 struct list_head queue_entry;
175 uint16_t cmd_id;
177 /* Can't use se_cmd when cleaning up expired cmds, because if
178 cmd has been completed then accessing se_cmd is off limits */
179 uint32_t dbi_cnt;
180 uint32_t dbi_bidi_cnt;
181 uint32_t dbi_cur;
182 uint32_t *dbi;
184 uint32_t data_len_bidi;
186 unsigned long deadline;
188 #define TCMU_CMD_BIT_EXPIRED 0
189 unsigned long flags;
192 struct tcmu_tmr {
193 struct list_head queue_entry;
195 uint8_t tmr_type;
196 uint32_t tmr_cmd_cnt;
197 int16_t tmr_cmd_ids[];
201 * To avoid dead lock the mutex lock order should always be:
203 * mutex_lock(&root_udev_mutex);
204 * ...
205 * mutex_lock(&tcmu_dev->cmdr_lock);
206 * mutex_unlock(&tcmu_dev->cmdr_lock);
207 * ...
208 * mutex_unlock(&root_udev_mutex);
210 static DEFINE_MUTEX(root_udev_mutex);
211 static LIST_HEAD(root_udev);
213 static DEFINE_SPINLOCK(timed_out_udevs_lock);
214 static LIST_HEAD(timed_out_udevs);
216 static struct kmem_cache *tcmu_cmd_cache;
218 static atomic_t global_db_count = ATOMIC_INIT(0);
219 static struct delayed_work tcmu_unmap_work;
220 static int tcmu_global_max_blocks = TCMU_GLOBAL_MAX_BLOCKS_DEF;
222 static int tcmu_set_global_max_data_area(const char *str,
223 const struct kernel_param *kp)
225 int ret, max_area_mb;
227 ret = kstrtoint(str, 10, &max_area_mb);
228 if (ret)
229 return -EINVAL;
231 if (max_area_mb <= 0) {
232 pr_err("global_max_data_area must be larger than 0.\n");
233 return -EINVAL;
236 tcmu_global_max_blocks = TCMU_MBS_TO_BLOCKS(max_area_mb);
237 if (atomic_read(&global_db_count) > tcmu_global_max_blocks)
238 schedule_delayed_work(&tcmu_unmap_work, 0);
239 else
240 cancel_delayed_work_sync(&tcmu_unmap_work);
242 return 0;
245 static int tcmu_get_global_max_data_area(char *buffer,
246 const struct kernel_param *kp)
248 return sprintf(buffer, "%d\n", TCMU_BLOCKS_TO_MBS(tcmu_global_max_blocks));
251 static const struct kernel_param_ops tcmu_global_max_data_area_op = {
252 .set = tcmu_set_global_max_data_area,
253 .get = tcmu_get_global_max_data_area,
256 module_param_cb(global_max_data_area_mb, &tcmu_global_max_data_area_op, NULL,
257 S_IWUSR | S_IRUGO);
258 MODULE_PARM_DESC(global_max_data_area_mb,
259 "Max MBs allowed to be allocated to all the tcmu device's "
260 "data areas.");
262 static int tcmu_get_block_netlink(char *buffer,
263 const struct kernel_param *kp)
265 return sprintf(buffer, "%s\n", tcmu_netlink_blocked ?
266 "blocked" : "unblocked");
269 static int tcmu_set_block_netlink(const char *str,
270 const struct kernel_param *kp)
272 int ret;
273 u8 val;
275 ret = kstrtou8(str, 0, &val);
276 if (ret < 0)
277 return ret;
279 if (val > 1) {
280 pr_err("Invalid block netlink value %u\n", val);
281 return -EINVAL;
284 tcmu_netlink_blocked = val;
285 return 0;
288 static const struct kernel_param_ops tcmu_block_netlink_op = {
289 .set = tcmu_set_block_netlink,
290 .get = tcmu_get_block_netlink,
293 module_param_cb(block_netlink, &tcmu_block_netlink_op, NULL, S_IWUSR | S_IRUGO);
294 MODULE_PARM_DESC(block_netlink, "Block new netlink commands.");
296 static int tcmu_fail_netlink_cmd(struct tcmu_nl_cmd *nl_cmd)
298 struct tcmu_dev *udev = nl_cmd->udev;
300 if (!tcmu_netlink_blocked) {
301 pr_err("Could not reset device's netlink interface. Netlink is not blocked.\n");
302 return -EBUSY;
305 if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
306 pr_debug("Aborting nl cmd %d on %s\n", nl_cmd->cmd, udev->name);
307 nl_cmd->status = -EINTR;
308 list_del(&nl_cmd->nl_list);
309 complete(&nl_cmd->complete);
311 return 0;
314 static int tcmu_set_reset_netlink(const char *str,
315 const struct kernel_param *kp)
317 struct tcmu_nl_cmd *nl_cmd, *tmp_cmd;
318 int ret;
319 u8 val;
321 ret = kstrtou8(str, 0, &val);
322 if (ret < 0)
323 return ret;
325 if (val != 1) {
326 pr_err("Invalid reset netlink value %u\n", val);
327 return -EINVAL;
330 mutex_lock(&tcmu_nl_cmd_mutex);
331 list_for_each_entry_safe(nl_cmd, tmp_cmd, &tcmu_nl_cmd_list, nl_list) {
332 ret = tcmu_fail_netlink_cmd(nl_cmd);
333 if (ret)
334 break;
336 mutex_unlock(&tcmu_nl_cmd_mutex);
338 return ret;
341 static const struct kernel_param_ops tcmu_reset_netlink_op = {
342 .set = tcmu_set_reset_netlink,
345 module_param_cb(reset_netlink, &tcmu_reset_netlink_op, NULL, S_IWUSR);
346 MODULE_PARM_DESC(reset_netlink, "Reset netlink commands.");
348 /* multicast group */
349 enum tcmu_multicast_groups {
350 TCMU_MCGRP_CONFIG,
353 static const struct genl_multicast_group tcmu_mcgrps[] = {
354 [TCMU_MCGRP_CONFIG] = { .name = "config", },
357 static struct nla_policy tcmu_attr_policy[TCMU_ATTR_MAX+1] = {
358 [TCMU_ATTR_DEVICE] = { .type = NLA_STRING },
359 [TCMU_ATTR_MINOR] = { .type = NLA_U32 },
360 [TCMU_ATTR_CMD_STATUS] = { .type = NLA_S32 },
361 [TCMU_ATTR_DEVICE_ID] = { .type = NLA_U32 },
362 [TCMU_ATTR_SUPP_KERN_CMD_REPLY] = { .type = NLA_U8 },
365 static int tcmu_genl_cmd_done(struct genl_info *info, int completed_cmd)
367 struct tcmu_dev *udev = NULL;
368 struct tcmu_nl_cmd *nl_cmd;
369 int dev_id, rc, ret = 0;
371 if (!info->attrs[TCMU_ATTR_CMD_STATUS] ||
372 !info->attrs[TCMU_ATTR_DEVICE_ID]) {
373 printk(KERN_ERR "TCMU_ATTR_CMD_STATUS or TCMU_ATTR_DEVICE_ID not set, doing nothing\n");
374 return -EINVAL;
377 dev_id = nla_get_u32(info->attrs[TCMU_ATTR_DEVICE_ID]);
378 rc = nla_get_s32(info->attrs[TCMU_ATTR_CMD_STATUS]);
380 mutex_lock(&tcmu_nl_cmd_mutex);
381 list_for_each_entry(nl_cmd, &tcmu_nl_cmd_list, nl_list) {
382 if (nl_cmd->udev->se_dev.dev_index == dev_id) {
383 udev = nl_cmd->udev;
384 break;
388 if (!udev) {
389 pr_err("tcmu nl cmd %u/%d completion could not find device with dev id %u.\n",
390 completed_cmd, rc, dev_id);
391 ret = -ENODEV;
392 goto unlock;
394 list_del(&nl_cmd->nl_list);
396 pr_debug("%s genl cmd done got id %d curr %d done %d rc %d stat %d\n",
397 udev->name, dev_id, nl_cmd->cmd, completed_cmd, rc,
398 nl_cmd->status);
400 if (nl_cmd->cmd != completed_cmd) {
401 pr_err("Mismatched commands on %s (Expecting reply for %d. Current %d).\n",
402 udev->name, completed_cmd, nl_cmd->cmd);
403 ret = -EINVAL;
404 goto unlock;
407 nl_cmd->status = rc;
408 complete(&nl_cmd->complete);
409 unlock:
410 mutex_unlock(&tcmu_nl_cmd_mutex);
411 return ret;
414 static int tcmu_genl_rm_dev_done(struct sk_buff *skb, struct genl_info *info)
416 return tcmu_genl_cmd_done(info, TCMU_CMD_REMOVED_DEVICE);
419 static int tcmu_genl_add_dev_done(struct sk_buff *skb, struct genl_info *info)
421 return tcmu_genl_cmd_done(info, TCMU_CMD_ADDED_DEVICE);
424 static int tcmu_genl_reconfig_dev_done(struct sk_buff *skb,
425 struct genl_info *info)
427 return tcmu_genl_cmd_done(info, TCMU_CMD_RECONFIG_DEVICE);
430 static int tcmu_genl_set_features(struct sk_buff *skb, struct genl_info *info)
432 if (info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]) {
433 tcmu_kern_cmd_reply_supported =
434 nla_get_u8(info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]);
435 printk(KERN_INFO "tcmu daemon: command reply support %u.\n",
436 tcmu_kern_cmd_reply_supported);
439 return 0;
442 static const struct genl_small_ops tcmu_genl_ops[] = {
444 .cmd = TCMU_CMD_SET_FEATURES,
445 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
446 .flags = GENL_ADMIN_PERM,
447 .doit = tcmu_genl_set_features,
450 .cmd = TCMU_CMD_ADDED_DEVICE_DONE,
451 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
452 .flags = GENL_ADMIN_PERM,
453 .doit = tcmu_genl_add_dev_done,
456 .cmd = TCMU_CMD_REMOVED_DEVICE_DONE,
457 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
458 .flags = GENL_ADMIN_PERM,
459 .doit = tcmu_genl_rm_dev_done,
462 .cmd = TCMU_CMD_RECONFIG_DEVICE_DONE,
463 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
464 .flags = GENL_ADMIN_PERM,
465 .doit = tcmu_genl_reconfig_dev_done,
469 /* Our generic netlink family */
470 static struct genl_family tcmu_genl_family __ro_after_init = {
471 .module = THIS_MODULE,
472 .hdrsize = 0,
473 .name = "TCM-USER",
474 .version = 2,
475 .maxattr = TCMU_ATTR_MAX,
476 .policy = tcmu_attr_policy,
477 .mcgrps = tcmu_mcgrps,
478 .n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
479 .netnsok = true,
480 .small_ops = tcmu_genl_ops,
481 .n_small_ops = ARRAY_SIZE(tcmu_genl_ops),
484 #define tcmu_cmd_set_dbi_cur(cmd, index) ((cmd)->dbi_cur = (index))
485 #define tcmu_cmd_reset_dbi_cur(cmd) tcmu_cmd_set_dbi_cur(cmd, 0)
486 #define tcmu_cmd_set_dbi(cmd, index) ((cmd)->dbi[(cmd)->dbi_cur++] = (index))
487 #define tcmu_cmd_get_dbi(cmd) ((cmd)->dbi[(cmd)->dbi_cur++])
489 static void tcmu_cmd_free_data(struct tcmu_cmd *tcmu_cmd, uint32_t len)
491 struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
492 uint32_t i;
494 for (i = 0; i < len; i++)
495 clear_bit(tcmu_cmd->dbi[i], udev->data_bitmap);
498 static inline int tcmu_get_empty_block(struct tcmu_dev *udev,
499 struct tcmu_cmd *tcmu_cmd,
500 int prev_dbi, int *iov_cnt)
502 struct page *page;
503 int ret, dbi;
505 dbi = find_first_zero_bit(udev->data_bitmap, udev->dbi_thresh);
506 if (dbi == udev->dbi_thresh)
507 return -1;
509 page = radix_tree_lookup(&udev->data_blocks, dbi);
510 if (!page) {
511 if (atomic_add_return(1, &global_db_count) >
512 tcmu_global_max_blocks)
513 schedule_delayed_work(&tcmu_unmap_work, 0);
515 /* try to get new page from the mm */
516 page = alloc_page(GFP_NOIO);
517 if (!page)
518 goto err_alloc;
520 ret = radix_tree_insert(&udev->data_blocks, dbi, page);
521 if (ret)
522 goto err_insert;
525 if (dbi > udev->dbi_max)
526 udev->dbi_max = dbi;
528 set_bit(dbi, udev->data_bitmap);
529 tcmu_cmd_set_dbi(tcmu_cmd, dbi);
531 if (dbi != prev_dbi + 1)
532 *iov_cnt += 1;
534 return dbi;
535 err_insert:
536 __free_page(page);
537 err_alloc:
538 atomic_dec(&global_db_count);
539 return -1;
542 static int tcmu_get_empty_blocks(struct tcmu_dev *udev,
543 struct tcmu_cmd *tcmu_cmd, int dbi_cnt)
545 /* start value of dbi + 1 must not be a valid dbi */
546 int dbi = -2;
547 int i, iov_cnt = 0;
549 for (i = 0; i < dbi_cnt; i++) {
550 dbi = tcmu_get_empty_block(udev, tcmu_cmd, dbi, &iov_cnt);
551 if (dbi < 0)
552 return -1;
554 return iov_cnt;
557 static inline struct page *
558 tcmu_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
560 return radix_tree_lookup(&udev->data_blocks, dbi);
563 static inline void tcmu_free_cmd(struct tcmu_cmd *tcmu_cmd)
565 if (tcmu_cmd->se_cmd)
566 tcmu_cmd->se_cmd->priv = NULL;
567 kfree(tcmu_cmd->dbi);
568 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
571 static inline void tcmu_cmd_set_block_cnts(struct tcmu_cmd *cmd)
573 int i, len;
574 struct se_cmd *se_cmd = cmd->se_cmd;
576 cmd->dbi_cnt = DIV_ROUND_UP(se_cmd->data_length, DATA_BLOCK_SIZE);
578 if (se_cmd->se_cmd_flags & SCF_BIDI) {
579 BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
580 for (i = 0, len = 0; i < se_cmd->t_bidi_data_nents; i++)
581 len += se_cmd->t_bidi_data_sg[i].length;
582 cmd->dbi_bidi_cnt = DIV_ROUND_UP(len, DATA_BLOCK_SIZE);
583 cmd->dbi_cnt += cmd->dbi_bidi_cnt;
584 cmd->data_len_bidi = len;
588 static int new_block_to_iov(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
589 struct iovec **iov, int prev_dbi, int len)
591 /* Get the next dbi */
592 int dbi = tcmu_cmd_get_dbi(cmd);
594 /* Do not add more than DATA_BLOCK_SIZE to iov */
595 if (len > DATA_BLOCK_SIZE)
596 len = DATA_BLOCK_SIZE;
599 * The following code will gather and map the blocks to the same iovec
600 * when the blocks are all next to each other.
602 if (dbi != prev_dbi + 1) {
603 /* dbi is not next to previous dbi, so start new iov */
604 if (prev_dbi >= 0)
605 (*iov)++;
606 /* write offset relative to mb_addr */
607 (*iov)->iov_base = (void __user *)
608 (udev->data_off + dbi * DATA_BLOCK_SIZE);
610 (*iov)->iov_len += len;
612 return dbi;
615 static void tcmu_setup_iovs(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
616 struct iovec **iov, int data_length)
618 /* start value of dbi + 1 must not be a valid dbi */
619 int dbi = -2;
621 /* We prepare the IOVs for DMA_FROM_DEVICE transfer direction */
622 for (; data_length > 0; data_length -= DATA_BLOCK_SIZE)
623 dbi = new_block_to_iov(udev, cmd, iov, dbi, data_length);
626 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
628 struct se_device *se_dev = se_cmd->se_dev;
629 struct tcmu_dev *udev = TCMU_DEV(se_dev);
630 struct tcmu_cmd *tcmu_cmd;
632 tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_NOIO);
633 if (!tcmu_cmd)
634 return NULL;
636 INIT_LIST_HEAD(&tcmu_cmd->queue_entry);
637 tcmu_cmd->se_cmd = se_cmd;
638 tcmu_cmd->tcmu_dev = udev;
640 tcmu_cmd_set_block_cnts(tcmu_cmd);
641 tcmu_cmd->dbi = kcalloc(tcmu_cmd->dbi_cnt, sizeof(uint32_t),
642 GFP_NOIO);
643 if (!tcmu_cmd->dbi) {
644 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
645 return NULL;
648 return tcmu_cmd;
651 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
653 unsigned long offset = offset_in_page(vaddr);
654 void *start = vaddr - offset;
656 size = round_up(size+offset, PAGE_SIZE);
658 while (size) {
659 flush_dcache_page(vmalloc_to_page(start));
660 start += PAGE_SIZE;
661 size -= PAGE_SIZE;
666 * Some ring helper functions. We don't assume size is a power of 2 so
667 * we can't use circ_buf.h.
669 static inline size_t spc_used(size_t head, size_t tail, size_t size)
671 int diff = head - tail;
673 if (diff >= 0)
674 return diff;
675 else
676 return size + diff;
679 static inline size_t spc_free(size_t head, size_t tail, size_t size)
681 /* Keep 1 byte unused or we can't tell full from empty */
682 return (size - spc_used(head, tail, size) - 1);
685 static inline size_t head_to_end(size_t head, size_t size)
687 return size - head;
690 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
692 #define TCMU_SG_TO_DATA_AREA 1
693 #define TCMU_DATA_AREA_TO_SG 2
695 static inline void tcmu_copy_data(struct tcmu_dev *udev,
696 struct tcmu_cmd *tcmu_cmd, uint32_t direction,
697 struct scatterlist *sg, unsigned int sg_nents,
698 struct iovec **iov, size_t data_len)
700 /* start value of dbi + 1 must not be a valid dbi */
701 int dbi = -2;
702 size_t block_remaining, cp_len;
703 struct sg_mapping_iter sg_iter;
704 unsigned int sg_flags;
705 struct page *page;
706 void *data_page_start, *data_addr;
708 if (direction == TCMU_SG_TO_DATA_AREA)
709 sg_flags = SG_MITER_ATOMIC | SG_MITER_FROM_SG;
710 else
711 sg_flags = SG_MITER_ATOMIC | SG_MITER_TO_SG;
712 sg_miter_start(&sg_iter, sg, sg_nents, sg_flags);
714 while (data_len) {
715 if (direction == TCMU_SG_TO_DATA_AREA)
716 dbi = new_block_to_iov(udev, tcmu_cmd, iov, dbi,
717 data_len);
718 else
719 dbi = tcmu_cmd_get_dbi(tcmu_cmd);
720 page = tcmu_get_block_page(udev, dbi);
721 if (direction == TCMU_DATA_AREA_TO_SG)
722 flush_dcache_page(page);
723 data_page_start = kmap_atomic(page);
724 block_remaining = DATA_BLOCK_SIZE;
726 while (block_remaining && data_len) {
727 if (!sg_miter_next(&sg_iter)) {
728 /* set length to 0 to abort outer loop */
729 data_len = 0;
730 pr_debug("tcmu_move_data: aborting data copy due to exhausted sg_list\n");
731 break;
733 cp_len = min3(sg_iter.length, block_remaining, data_len);
735 data_addr = data_page_start +
736 DATA_BLOCK_SIZE - block_remaining;
737 if (direction == TCMU_SG_TO_DATA_AREA)
738 memcpy(data_addr, sg_iter.addr, cp_len);
739 else
740 memcpy(sg_iter.addr, data_addr, cp_len);
742 data_len -= cp_len;
743 block_remaining -= cp_len;
744 sg_iter.consumed = cp_len;
746 sg_miter_stop(&sg_iter);
748 kunmap_atomic(data_page_start);
749 if (direction == TCMU_SG_TO_DATA_AREA)
750 flush_dcache_page(page);
754 static void scatter_data_area(struct tcmu_dev *udev, struct tcmu_cmd *tcmu_cmd,
755 struct iovec **iov)
757 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
759 tcmu_copy_data(udev, tcmu_cmd, TCMU_SG_TO_DATA_AREA, se_cmd->t_data_sg,
760 se_cmd->t_data_nents, iov, se_cmd->data_length);
763 static void gather_data_area(struct tcmu_dev *udev, struct tcmu_cmd *tcmu_cmd,
764 bool bidi, uint32_t read_len)
766 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
767 struct scatterlist *data_sg;
768 unsigned int data_nents;
770 if (!bidi) {
771 data_sg = se_cmd->t_data_sg;
772 data_nents = se_cmd->t_data_nents;
773 } else {
775 * For bidi case, the first count blocks are for Data-Out
776 * buffer blocks, and before gathering the Data-In buffer
777 * the Data-Out buffer blocks should be skipped.
779 tcmu_cmd_set_dbi_cur(tcmu_cmd,
780 tcmu_cmd->dbi_cnt - tcmu_cmd->dbi_bidi_cnt);
782 data_sg = se_cmd->t_bidi_data_sg;
783 data_nents = se_cmd->t_bidi_data_nents;
786 tcmu_copy_data(udev, tcmu_cmd, TCMU_DATA_AREA_TO_SG, data_sg,
787 data_nents, NULL, read_len);
790 static inline size_t spc_bitmap_free(unsigned long *bitmap, uint32_t thresh)
792 return thresh - bitmap_weight(bitmap, thresh);
796 * We can't queue a command until we have space available on the cmd ring.
798 * Called with ring lock held.
800 static bool is_ring_space_avail(struct tcmu_dev *udev, size_t cmd_size)
802 struct tcmu_mailbox *mb = udev->mb_addr;
803 size_t space, cmd_needed;
804 u32 cmd_head;
806 tcmu_flush_dcache_range(mb, sizeof(*mb));
808 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
811 * If cmd end-of-ring space is too small then we need space for a NOP plus
812 * original cmd - cmds are internally contiguous.
814 if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
815 cmd_needed = cmd_size;
816 else
817 cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
819 space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
820 if (space < cmd_needed) {
821 pr_debug("no cmd space: %u %u %u\n", cmd_head,
822 udev->cmdr_last_cleaned, udev->cmdr_size);
823 return false;
825 return true;
829 * We have to allocate data buffers before we can queue a command.
830 * Returns -1 on error (not enough space) or number of needed iovs on success
832 * Called with ring lock held.
834 static int tcmu_alloc_data_space(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
835 int *iov_bidi_cnt)
837 int space, iov_cnt = 0, ret = 0;
839 if (!cmd->dbi_cnt)
840 goto wr_iov_cnts;
842 /* try to check and get the data blocks as needed */
843 space = spc_bitmap_free(udev->data_bitmap, udev->dbi_thresh);
844 if (space < cmd->dbi_cnt) {
845 unsigned long blocks_left =
846 (udev->max_blocks - udev->dbi_thresh) + space;
848 if (blocks_left < cmd->dbi_cnt) {
849 pr_debug("no data space: only %lu available, but ask for %lu\n",
850 blocks_left * DATA_BLOCK_SIZE,
851 cmd->dbi_cnt * DATA_BLOCK_SIZE);
852 return -1;
855 udev->dbi_thresh += cmd->dbi_cnt;
856 if (udev->dbi_thresh > udev->max_blocks)
857 udev->dbi_thresh = udev->max_blocks;
860 iov_cnt = tcmu_get_empty_blocks(udev, cmd,
861 cmd->dbi_cnt - cmd->dbi_bidi_cnt);
862 if (iov_cnt < 0)
863 return -1;
865 if (cmd->dbi_bidi_cnt) {
866 ret = tcmu_get_empty_blocks(udev, cmd, cmd->dbi_bidi_cnt);
867 if (ret < 0)
868 return -1;
870 wr_iov_cnts:
871 *iov_bidi_cnt = ret;
872 return iov_cnt + ret;
875 static inline size_t tcmu_cmd_get_base_cmd_size(size_t iov_cnt)
877 return max(offsetof(struct tcmu_cmd_entry, req.iov[iov_cnt]),
878 sizeof(struct tcmu_cmd_entry));
881 static inline size_t tcmu_cmd_get_cmd_size(struct tcmu_cmd *tcmu_cmd,
882 size_t base_command_size)
884 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
885 size_t command_size;
887 command_size = base_command_size +
888 round_up(scsi_command_size(se_cmd->t_task_cdb),
889 TCMU_OP_ALIGN_SIZE);
891 WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
893 return command_size;
896 static void tcmu_setup_cmd_timer(struct tcmu_cmd *tcmu_cmd, unsigned int tmo,
897 struct timer_list *timer)
899 if (!tmo)
900 return;
902 tcmu_cmd->deadline = round_jiffies_up(jiffies + msecs_to_jiffies(tmo));
903 if (!timer_pending(timer))
904 mod_timer(timer, tcmu_cmd->deadline);
906 pr_debug("Timeout set up for cmd %p, dev = %s, tmo = %lu\n", tcmu_cmd,
907 tcmu_cmd->tcmu_dev->name, tmo / MSEC_PER_SEC);
910 static int add_to_qfull_queue(struct tcmu_cmd *tcmu_cmd)
912 struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
913 unsigned int tmo;
916 * For backwards compat if qfull_time_out is not set use
917 * cmd_time_out and if that's not set use the default time out.
919 if (!udev->qfull_time_out)
920 return -ETIMEDOUT;
921 else if (udev->qfull_time_out > 0)
922 tmo = udev->qfull_time_out;
923 else if (udev->cmd_time_out)
924 tmo = udev->cmd_time_out;
925 else
926 tmo = TCMU_TIME_OUT;
928 tcmu_setup_cmd_timer(tcmu_cmd, tmo, &udev->qfull_timer);
930 list_add_tail(&tcmu_cmd->queue_entry, &udev->qfull_queue);
931 pr_debug("adding cmd %p on dev %s to ring space wait queue\n",
932 tcmu_cmd, udev->name);
933 return 0;
936 static uint32_t ring_insert_padding(struct tcmu_dev *udev, size_t cmd_size)
938 struct tcmu_cmd_entry_hdr *hdr;
939 struct tcmu_mailbox *mb = udev->mb_addr;
940 uint32_t cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
942 /* Insert a PAD if end-of-ring space is too small */
943 if (head_to_end(cmd_head, udev->cmdr_size) < cmd_size) {
944 size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
946 hdr = (void *) mb + CMDR_OFF + cmd_head;
947 tcmu_hdr_set_op(&hdr->len_op, TCMU_OP_PAD);
948 tcmu_hdr_set_len(&hdr->len_op, pad_size);
949 hdr->cmd_id = 0; /* not used for PAD */
950 hdr->kflags = 0;
951 hdr->uflags = 0;
952 tcmu_flush_dcache_range(hdr, sizeof(*hdr));
954 UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
955 tcmu_flush_dcache_range(mb, sizeof(*mb));
957 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
958 WARN_ON(cmd_head != 0);
961 return cmd_head;
965 * queue_cmd_ring - queue cmd to ring or internally
966 * @tcmu_cmd: cmd to queue
967 * @scsi_err: TCM error code if failure (-1) returned.
969 * Returns:
970 * -1 we cannot queue internally or to the ring.
971 * 0 success
972 * 1 internally queued to wait for ring memory to free.
974 static int queue_cmd_ring(struct tcmu_cmd *tcmu_cmd, sense_reason_t *scsi_err)
976 struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
977 struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
978 size_t base_command_size, command_size;
979 struct tcmu_mailbox *mb = udev->mb_addr;
980 struct tcmu_cmd_entry *entry;
981 struct iovec *iov;
982 int iov_cnt, iov_bidi_cnt, cmd_id;
983 uint32_t cmd_head;
984 uint64_t cdb_off;
985 /* size of data buffer needed */
986 size_t data_length = (size_t)tcmu_cmd->dbi_cnt * DATA_BLOCK_SIZE;
988 *scsi_err = TCM_NO_SENSE;
990 if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags)) {
991 *scsi_err = TCM_LUN_BUSY;
992 return -1;
995 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
996 *scsi_err = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
997 return -1;
1000 if (!list_empty(&udev->qfull_queue))
1001 goto queue;
1003 if (data_length > udev->data_size) {
1004 pr_warn("TCMU: Request of size %zu is too big for %zu data area\n",
1005 data_length, udev->data_size);
1006 *scsi_err = TCM_INVALID_CDB_FIELD;
1007 return -1;
1010 iov_cnt = tcmu_alloc_data_space(udev, tcmu_cmd, &iov_bidi_cnt);
1011 if (iov_cnt < 0)
1012 goto free_and_queue;
1015 * Must be a certain minimum size for response sense info, but
1016 * also may be larger if the iov array is large.
1018 base_command_size = tcmu_cmd_get_base_cmd_size(iov_cnt);
1019 command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
1021 if (command_size > (udev->cmdr_size / 2)) {
1022 pr_warn("TCMU: Request of size %zu is too big for %u cmd ring\n",
1023 command_size, udev->cmdr_size);
1024 tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
1025 *scsi_err = TCM_INVALID_CDB_FIELD;
1026 return -1;
1029 if (!is_ring_space_avail(udev, command_size))
1031 * Don't leave commands partially setup because the unmap
1032 * thread might need the blocks to make forward progress.
1034 goto free_and_queue;
1036 cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 1, USHRT_MAX, GFP_NOWAIT);
1037 if (cmd_id < 0) {
1038 pr_err("tcmu: Could not allocate cmd id.\n");
1040 tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
1041 *scsi_err = TCM_OUT_OF_RESOURCES;
1042 return -1;
1044 tcmu_cmd->cmd_id = cmd_id;
1046 pr_debug("allocated cmd id %u for cmd %p dev %s\n", tcmu_cmd->cmd_id,
1047 tcmu_cmd, udev->name);
1049 cmd_head = ring_insert_padding(udev, command_size);
1051 entry = (void *) mb + CMDR_OFF + cmd_head;
1052 memset(entry, 0, command_size);
1053 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
1055 /* prepare iov list and copy data to data area if necessary */
1056 tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1057 iov = &entry->req.iov[0];
1059 if (se_cmd->data_direction == DMA_TO_DEVICE ||
1060 se_cmd->se_cmd_flags & SCF_BIDI)
1061 scatter_data_area(udev, tcmu_cmd, &iov);
1062 else
1063 tcmu_setup_iovs(udev, tcmu_cmd, &iov, se_cmd->data_length);
1065 entry->req.iov_cnt = iov_cnt - iov_bidi_cnt;
1067 /* Handle BIDI commands */
1068 if (se_cmd->se_cmd_flags & SCF_BIDI) {
1069 iov++;
1070 tcmu_setup_iovs(udev, tcmu_cmd, &iov, tcmu_cmd->data_len_bidi);
1071 entry->req.iov_bidi_cnt = iov_bidi_cnt;
1074 tcmu_setup_cmd_timer(tcmu_cmd, udev->cmd_time_out, &udev->cmd_timer);
1076 entry->hdr.cmd_id = tcmu_cmd->cmd_id;
1078 tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
1080 /* All offsets relative to mb_addr, not start of entry! */
1081 cdb_off = CMDR_OFF + cmd_head + base_command_size;
1082 memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
1083 entry->req.cdb_off = cdb_off;
1084 tcmu_flush_dcache_range(entry, command_size);
1086 UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
1087 tcmu_flush_dcache_range(mb, sizeof(*mb));
1089 list_add_tail(&tcmu_cmd->queue_entry, &udev->inflight_queue);
1091 /* TODO: only if FLUSH and FUA? */
1092 uio_event_notify(&udev->uio_info);
1094 return 0;
1096 free_and_queue:
1097 tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
1098 tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1100 queue:
1101 if (add_to_qfull_queue(tcmu_cmd)) {
1102 *scsi_err = TCM_OUT_OF_RESOURCES;
1103 return -1;
1106 return 1;
1110 * queue_tmr_ring - queue tmr info to ring or internally
1111 * @udev: related tcmu_dev
1112 * @tmr: tcmu_tmr containing tmr info to queue
1114 * Returns:
1115 * 0 success
1116 * 1 internally queued to wait for ring memory to free.
1118 static int
1119 queue_tmr_ring(struct tcmu_dev *udev, struct tcmu_tmr *tmr)
1121 struct tcmu_tmr_entry *entry;
1122 int cmd_size;
1123 int id_list_sz;
1124 struct tcmu_mailbox *mb = udev->mb_addr;
1125 uint32_t cmd_head;
1127 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
1128 goto out_free;
1130 id_list_sz = sizeof(tmr->tmr_cmd_ids[0]) * tmr->tmr_cmd_cnt;
1131 cmd_size = round_up(sizeof(*entry) + id_list_sz, TCMU_OP_ALIGN_SIZE);
1133 if (!list_empty(&udev->tmr_queue) ||
1134 !is_ring_space_avail(udev, cmd_size)) {
1135 list_add_tail(&tmr->queue_entry, &udev->tmr_queue);
1136 pr_debug("adding tmr %p on dev %s to TMR ring space wait queue\n",
1137 tmr, udev->name);
1138 return 1;
1141 cmd_head = ring_insert_padding(udev, cmd_size);
1143 entry = (void *)mb + CMDR_OFF + cmd_head;
1144 memset(entry, 0, cmd_size);
1145 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_TMR);
1146 tcmu_hdr_set_len(&entry->hdr.len_op, cmd_size);
1147 entry->tmr_type = tmr->tmr_type;
1148 entry->cmd_cnt = tmr->tmr_cmd_cnt;
1149 memcpy(&entry->cmd_ids[0], &tmr->tmr_cmd_ids[0], id_list_sz);
1150 tcmu_flush_dcache_range(entry, cmd_size);
1152 UPDATE_HEAD(mb->cmd_head, cmd_size, udev->cmdr_size);
1153 tcmu_flush_dcache_range(mb, sizeof(*mb));
1155 uio_event_notify(&udev->uio_info);
1157 out_free:
1158 kfree(tmr);
1160 return 0;
1163 static sense_reason_t
1164 tcmu_queue_cmd(struct se_cmd *se_cmd)
1166 struct se_device *se_dev = se_cmd->se_dev;
1167 struct tcmu_dev *udev = TCMU_DEV(se_dev);
1168 struct tcmu_cmd *tcmu_cmd;
1169 sense_reason_t scsi_ret = TCM_CHECK_CONDITION_ABORT_CMD;
1170 int ret = -1;
1172 tcmu_cmd = tcmu_alloc_cmd(se_cmd);
1173 if (!tcmu_cmd)
1174 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1176 mutex_lock(&udev->cmdr_lock);
1177 se_cmd->priv = tcmu_cmd;
1178 if (!(se_cmd->transport_state & CMD_T_ABORTED))
1179 ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1180 if (ret < 0)
1181 tcmu_free_cmd(tcmu_cmd);
1182 mutex_unlock(&udev->cmdr_lock);
1183 return scsi_ret;
1186 static void tcmu_set_next_deadline(struct list_head *queue,
1187 struct timer_list *timer)
1189 struct tcmu_cmd *cmd;
1191 if (!list_empty(queue)) {
1192 cmd = list_first_entry(queue, struct tcmu_cmd, queue_entry);
1193 mod_timer(timer, cmd->deadline);
1194 } else
1195 del_timer(timer);
1198 static int
1199 tcmu_tmr_type(enum tcm_tmreq_table tmf)
1201 switch (tmf) {
1202 case TMR_ABORT_TASK: return TCMU_TMR_ABORT_TASK;
1203 case TMR_ABORT_TASK_SET: return TCMU_TMR_ABORT_TASK_SET;
1204 case TMR_CLEAR_ACA: return TCMU_TMR_CLEAR_ACA;
1205 case TMR_CLEAR_TASK_SET: return TCMU_TMR_CLEAR_TASK_SET;
1206 case TMR_LUN_RESET: return TCMU_TMR_LUN_RESET;
1207 case TMR_TARGET_WARM_RESET: return TCMU_TMR_TARGET_WARM_RESET;
1208 case TMR_TARGET_COLD_RESET: return TCMU_TMR_TARGET_COLD_RESET;
1209 case TMR_LUN_RESET_PRO: return TCMU_TMR_LUN_RESET_PRO;
1210 default: return TCMU_TMR_UNKNOWN;
1214 static void
1215 tcmu_tmr_notify(struct se_device *se_dev, enum tcm_tmreq_table tmf,
1216 struct list_head *cmd_list)
1218 int i = 0, cmd_cnt = 0;
1219 bool unqueued = false;
1220 uint16_t *cmd_ids = NULL;
1221 struct tcmu_cmd *cmd;
1222 struct se_cmd *se_cmd;
1223 struct tcmu_tmr *tmr;
1224 struct tcmu_dev *udev = TCMU_DEV(se_dev);
1226 mutex_lock(&udev->cmdr_lock);
1228 /* First we check for aborted commands in qfull_queue */
1229 list_for_each_entry(se_cmd, cmd_list, state_list) {
1230 i++;
1231 if (!se_cmd->priv)
1232 continue;
1233 cmd = se_cmd->priv;
1234 /* Commands on qfull queue have no id yet */
1235 if (cmd->cmd_id) {
1236 cmd_cnt++;
1237 continue;
1239 pr_debug("Removing aborted command %p from queue on dev %s.\n",
1240 cmd, udev->name);
1242 list_del_init(&cmd->queue_entry);
1243 tcmu_free_cmd(cmd);
1244 target_complete_cmd(se_cmd, SAM_STAT_TASK_ABORTED);
1245 unqueued = true;
1247 if (unqueued)
1248 tcmu_set_next_deadline(&udev->qfull_queue, &udev->qfull_timer);
1250 if (!test_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags))
1251 goto unlock;
1253 pr_debug("TMR event %d on dev %s, aborted cmds %d, afflicted cmd_ids %d\n",
1254 tcmu_tmr_type(tmf), udev->name, i, cmd_cnt);
1256 tmr = kmalloc(sizeof(*tmr) + cmd_cnt * sizeof(*cmd_ids), GFP_KERNEL);
1257 if (!tmr)
1258 goto unlock;
1260 tmr->tmr_type = tcmu_tmr_type(tmf);
1261 tmr->tmr_cmd_cnt = cmd_cnt;
1263 if (cmd_cnt != 0) {
1264 cmd_cnt = 0;
1265 list_for_each_entry(se_cmd, cmd_list, state_list) {
1266 if (!se_cmd->priv)
1267 continue;
1268 cmd = se_cmd->priv;
1269 if (cmd->cmd_id)
1270 tmr->tmr_cmd_ids[cmd_cnt++] = cmd->cmd_id;
1274 queue_tmr_ring(udev, tmr);
1276 unlock:
1277 mutex_unlock(&udev->cmdr_lock);
1280 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
1282 struct se_cmd *se_cmd = cmd->se_cmd;
1283 struct tcmu_dev *udev = cmd->tcmu_dev;
1284 bool read_len_valid = false;
1285 uint32_t read_len;
1288 * cmd has been completed already from timeout, just reclaim
1289 * data area space and free cmd
1291 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1292 WARN_ON_ONCE(se_cmd);
1293 goto out;
1296 list_del_init(&cmd->queue_entry);
1298 tcmu_cmd_reset_dbi_cur(cmd);
1300 if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
1301 pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
1302 cmd->se_cmd);
1303 entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
1304 goto done;
1307 read_len = se_cmd->data_length;
1308 if (se_cmd->data_direction == DMA_FROM_DEVICE &&
1309 (entry->hdr.uflags & TCMU_UFLAG_READ_LEN) && entry->rsp.read_len) {
1310 read_len_valid = true;
1311 if (entry->rsp.read_len < read_len)
1312 read_len = entry->rsp.read_len;
1315 if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
1316 transport_copy_sense_to_cmd(se_cmd, entry->rsp.sense_buffer);
1317 if (!read_len_valid )
1318 goto done;
1319 else
1320 se_cmd->se_cmd_flags |= SCF_TREAT_READ_AS_NORMAL;
1322 if (se_cmd->se_cmd_flags & SCF_BIDI) {
1323 /* Get Data-In buffer before clean up */
1324 gather_data_area(udev, cmd, true, read_len);
1325 } else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
1326 gather_data_area(udev, cmd, false, read_len);
1327 } else if (se_cmd->data_direction == DMA_TO_DEVICE) {
1328 /* TODO: */
1329 } else if (se_cmd->data_direction != DMA_NONE) {
1330 pr_warn("TCMU: data direction was %d!\n",
1331 se_cmd->data_direction);
1334 done:
1335 if (read_len_valid) {
1336 pr_debug("read_len = %d\n", read_len);
1337 target_complete_cmd_with_length(cmd->se_cmd,
1338 entry->rsp.scsi_status, read_len);
1339 } else
1340 target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
1342 out:
1343 tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
1344 tcmu_free_cmd(cmd);
1347 static int tcmu_run_tmr_queue(struct tcmu_dev *udev)
1349 struct tcmu_tmr *tmr, *tmp;
1350 LIST_HEAD(tmrs);
1352 if (list_empty(&udev->tmr_queue))
1353 return 1;
1355 pr_debug("running %s's tmr queue\n", udev->name);
1357 list_splice_init(&udev->tmr_queue, &tmrs);
1359 list_for_each_entry_safe(tmr, tmp, &tmrs, queue_entry) {
1360 list_del_init(&tmr->queue_entry);
1362 pr_debug("removing tmr %p on dev %s from queue\n",
1363 tmr, udev->name);
1365 if (queue_tmr_ring(udev, tmr)) {
1366 pr_debug("ran out of space during tmr queue run\n");
1368 * tmr was requeued, so just put all tmrs back in
1369 * the queue
1371 list_splice_tail(&tmrs, &udev->tmr_queue);
1372 return 0;
1376 return 1;
1379 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
1381 struct tcmu_mailbox *mb;
1382 struct tcmu_cmd *cmd;
1383 bool free_space = false;
1385 if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
1386 pr_err("ring broken, not handling completions\n");
1387 return 0;
1390 mb = udev->mb_addr;
1391 tcmu_flush_dcache_range(mb, sizeof(*mb));
1393 while (udev->cmdr_last_cleaned != READ_ONCE(mb->cmd_tail)) {
1395 struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
1398 * Flush max. up to end of cmd ring since current entry might
1399 * be a padding that is shorter than sizeof(*entry)
1401 size_t ring_left = head_to_end(udev->cmdr_last_cleaned,
1402 udev->cmdr_size);
1403 tcmu_flush_dcache_range(entry, ring_left < sizeof(*entry) ?
1404 ring_left : sizeof(*entry));
1406 free_space = true;
1408 if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD ||
1409 tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_TMR) {
1410 UPDATE_HEAD(udev->cmdr_last_cleaned,
1411 tcmu_hdr_get_len(entry->hdr.len_op),
1412 udev->cmdr_size);
1413 continue;
1415 WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
1417 cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
1418 if (!cmd) {
1419 pr_err("cmd_id %u not found, ring is broken\n",
1420 entry->hdr.cmd_id);
1421 set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
1422 break;
1425 tcmu_handle_completion(cmd, entry);
1427 UPDATE_HEAD(udev->cmdr_last_cleaned,
1428 tcmu_hdr_get_len(entry->hdr.len_op),
1429 udev->cmdr_size);
1431 if (free_space)
1432 free_space = tcmu_run_tmr_queue(udev);
1434 if (atomic_read(&global_db_count) > tcmu_global_max_blocks &&
1435 idr_is_empty(&udev->commands) && list_empty(&udev->qfull_queue)) {
1437 * Allocated blocks exceeded global block limit, currently no
1438 * more pending or waiting commands so try to reclaim blocks.
1440 schedule_delayed_work(&tcmu_unmap_work, 0);
1442 if (udev->cmd_time_out)
1443 tcmu_set_next_deadline(&udev->inflight_queue, &udev->cmd_timer);
1445 return free_space;
1448 static void tcmu_check_expired_ring_cmd(struct tcmu_cmd *cmd)
1450 struct se_cmd *se_cmd;
1452 if (!time_after_eq(jiffies, cmd->deadline))
1453 return;
1455 set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
1456 list_del_init(&cmd->queue_entry);
1457 se_cmd = cmd->se_cmd;
1458 se_cmd->priv = NULL;
1459 cmd->se_cmd = NULL;
1461 pr_debug("Timing out inflight cmd %u on dev %s.\n",
1462 cmd->cmd_id, cmd->tcmu_dev->name);
1464 target_complete_cmd(se_cmd, SAM_STAT_CHECK_CONDITION);
1467 static void tcmu_check_expired_queue_cmd(struct tcmu_cmd *cmd)
1469 struct se_cmd *se_cmd;
1471 if (!time_after_eq(jiffies, cmd->deadline))
1472 return;
1474 pr_debug("Timing out queued cmd %p on dev %s.\n",
1475 cmd, cmd->tcmu_dev->name);
1477 list_del_init(&cmd->queue_entry);
1478 se_cmd = cmd->se_cmd;
1479 tcmu_free_cmd(cmd);
1481 target_complete_cmd(se_cmd, SAM_STAT_TASK_SET_FULL);
1484 static void tcmu_device_timedout(struct tcmu_dev *udev)
1486 spin_lock(&timed_out_udevs_lock);
1487 if (list_empty(&udev->timedout_entry))
1488 list_add_tail(&udev->timedout_entry, &timed_out_udevs);
1489 spin_unlock(&timed_out_udevs_lock);
1491 schedule_delayed_work(&tcmu_unmap_work, 0);
1494 static void tcmu_cmd_timedout(struct timer_list *t)
1496 struct tcmu_dev *udev = from_timer(udev, t, cmd_timer);
1498 pr_debug("%s cmd timeout has expired\n", udev->name);
1499 tcmu_device_timedout(udev);
1502 static void tcmu_qfull_timedout(struct timer_list *t)
1504 struct tcmu_dev *udev = from_timer(udev, t, qfull_timer);
1506 pr_debug("%s qfull timeout has expired\n", udev->name);
1507 tcmu_device_timedout(udev);
1510 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
1512 struct tcmu_hba *tcmu_hba;
1514 tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
1515 if (!tcmu_hba)
1516 return -ENOMEM;
1518 tcmu_hba->host_id = host_id;
1519 hba->hba_ptr = tcmu_hba;
1521 return 0;
1524 static void tcmu_detach_hba(struct se_hba *hba)
1526 kfree(hba->hba_ptr);
1527 hba->hba_ptr = NULL;
1530 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
1532 struct tcmu_dev *udev;
1534 udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
1535 if (!udev)
1536 return NULL;
1537 kref_init(&udev->kref);
1539 udev->name = kstrdup(name, GFP_KERNEL);
1540 if (!udev->name) {
1541 kfree(udev);
1542 return NULL;
1545 udev->hba = hba;
1546 udev->cmd_time_out = TCMU_TIME_OUT;
1547 udev->qfull_time_out = -1;
1549 udev->max_blocks = DATA_BLOCK_BITS_DEF;
1550 mutex_init(&udev->cmdr_lock);
1552 INIT_LIST_HEAD(&udev->node);
1553 INIT_LIST_HEAD(&udev->timedout_entry);
1554 INIT_LIST_HEAD(&udev->qfull_queue);
1555 INIT_LIST_HEAD(&udev->tmr_queue);
1556 INIT_LIST_HEAD(&udev->inflight_queue);
1557 idr_init(&udev->commands);
1559 timer_setup(&udev->qfull_timer, tcmu_qfull_timedout, 0);
1560 timer_setup(&udev->cmd_timer, tcmu_cmd_timedout, 0);
1562 INIT_RADIX_TREE(&udev->data_blocks, GFP_KERNEL);
1564 return &udev->se_dev;
1567 static void run_qfull_queue(struct tcmu_dev *udev, bool fail)
1569 struct tcmu_cmd *tcmu_cmd, *tmp_cmd;
1570 LIST_HEAD(cmds);
1571 sense_reason_t scsi_ret;
1572 int ret;
1574 if (list_empty(&udev->qfull_queue))
1575 return;
1577 pr_debug("running %s's cmdr queue forcefail %d\n", udev->name, fail);
1579 list_splice_init(&udev->qfull_queue, &cmds);
1581 list_for_each_entry_safe(tcmu_cmd, tmp_cmd, &cmds, queue_entry) {
1582 list_del_init(&tcmu_cmd->queue_entry);
1584 pr_debug("removing cmd %p on dev %s from queue\n",
1585 tcmu_cmd, udev->name);
1587 if (fail) {
1589 * We were not able to even start the command, so
1590 * fail with busy to allow a retry in case runner
1591 * was only temporarily down. If the device is being
1592 * removed then LIO core will do the right thing and
1593 * fail the retry.
1595 target_complete_cmd(tcmu_cmd->se_cmd, SAM_STAT_BUSY);
1596 tcmu_free_cmd(tcmu_cmd);
1597 continue;
1600 ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1601 if (ret < 0) {
1602 pr_debug("cmd %p on dev %s failed with %u\n",
1603 tcmu_cmd, udev->name, scsi_ret);
1605 * Ignore scsi_ret for now. target_complete_cmd
1606 * drops it.
1608 target_complete_cmd(tcmu_cmd->se_cmd,
1609 SAM_STAT_CHECK_CONDITION);
1610 tcmu_free_cmd(tcmu_cmd);
1611 } else if (ret > 0) {
1612 pr_debug("ran out of space during cmdr queue run\n");
1614 * cmd was requeued, so just put all cmds back in
1615 * the queue
1617 list_splice_tail(&cmds, &udev->qfull_queue);
1618 break;
1622 tcmu_set_next_deadline(&udev->qfull_queue, &udev->qfull_timer);
1625 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
1627 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1629 mutex_lock(&udev->cmdr_lock);
1630 if (tcmu_handle_completions(udev))
1631 run_qfull_queue(udev, false);
1632 mutex_unlock(&udev->cmdr_lock);
1634 return 0;
1638 * mmap code from uio.c. Copied here because we want to hook mmap()
1639 * and this stuff must come along.
1641 static int tcmu_find_mem_index(struct vm_area_struct *vma)
1643 struct tcmu_dev *udev = vma->vm_private_data;
1644 struct uio_info *info = &udev->uio_info;
1646 if (vma->vm_pgoff < MAX_UIO_MAPS) {
1647 if (info->mem[vma->vm_pgoff].size == 0)
1648 return -1;
1649 return (int)vma->vm_pgoff;
1651 return -1;
1654 static struct page *tcmu_try_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
1656 struct page *page;
1658 mutex_lock(&udev->cmdr_lock);
1659 page = tcmu_get_block_page(udev, dbi);
1660 if (likely(page)) {
1661 mutex_unlock(&udev->cmdr_lock);
1662 return page;
1666 * Userspace messed up and passed in a address not in the
1667 * data iov passed to it.
1669 pr_err("Invalid addr to data block mapping (dbi %u) on device %s\n",
1670 dbi, udev->name);
1671 page = NULL;
1672 mutex_unlock(&udev->cmdr_lock);
1674 return page;
1677 static vm_fault_t tcmu_vma_fault(struct vm_fault *vmf)
1679 struct tcmu_dev *udev = vmf->vma->vm_private_data;
1680 struct uio_info *info = &udev->uio_info;
1681 struct page *page;
1682 unsigned long offset;
1683 void *addr;
1685 int mi = tcmu_find_mem_index(vmf->vma);
1686 if (mi < 0)
1687 return VM_FAULT_SIGBUS;
1690 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
1691 * to use mem[N].
1693 offset = (vmf->pgoff - mi) << PAGE_SHIFT;
1695 if (offset < udev->data_off) {
1696 /* For the vmalloc()ed cmd area pages */
1697 addr = (void *)(unsigned long)info->mem[mi].addr + offset;
1698 page = vmalloc_to_page(addr);
1699 } else {
1700 uint32_t dbi;
1702 /* For the dynamically growing data area pages */
1703 dbi = (offset - udev->data_off) / DATA_BLOCK_SIZE;
1704 page = tcmu_try_get_block_page(udev, dbi);
1705 if (!page)
1706 return VM_FAULT_SIGBUS;
1709 get_page(page);
1710 vmf->page = page;
1711 return 0;
1714 static const struct vm_operations_struct tcmu_vm_ops = {
1715 .fault = tcmu_vma_fault,
1718 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
1720 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1722 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1723 vma->vm_ops = &tcmu_vm_ops;
1725 vma->vm_private_data = udev;
1727 /* Ensure the mmap is exactly the right size */
1728 if (vma_pages(vma) != (udev->ring_size >> PAGE_SHIFT))
1729 return -EINVAL;
1731 return 0;
1734 static int tcmu_open(struct uio_info *info, struct inode *inode)
1736 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1738 /* O_EXCL not supported for char devs, so fake it? */
1739 if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
1740 return -EBUSY;
1742 udev->inode = inode;
1743 kref_get(&udev->kref);
1745 pr_debug("open\n");
1747 return 0;
1750 static void tcmu_dev_call_rcu(struct rcu_head *p)
1752 struct se_device *dev = container_of(p, struct se_device, rcu_head);
1753 struct tcmu_dev *udev = TCMU_DEV(dev);
1755 kfree(udev->uio_info.name);
1756 kfree(udev->name);
1757 kfree(udev);
1760 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1762 if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1763 kmem_cache_free(tcmu_cmd_cache, cmd);
1764 return 0;
1766 return -EINVAL;
1769 static void tcmu_blocks_release(struct radix_tree_root *blocks,
1770 int start, int end)
1772 int i;
1773 struct page *page;
1775 for (i = start; i < end; i++) {
1776 page = radix_tree_delete(blocks, i);
1777 if (page) {
1778 __free_page(page);
1779 atomic_dec(&global_db_count);
1784 static void tcmu_remove_all_queued_tmr(struct tcmu_dev *udev)
1786 struct tcmu_tmr *tmr, *tmp;
1788 list_for_each_entry_safe(tmr, tmp, &udev->tmr_queue, queue_entry) {
1789 list_del_init(&tmr->queue_entry);
1790 kfree(tmr);
1794 static void tcmu_dev_kref_release(struct kref *kref)
1796 struct tcmu_dev *udev = container_of(kref, struct tcmu_dev, kref);
1797 struct se_device *dev = &udev->se_dev;
1798 struct tcmu_cmd *cmd;
1799 bool all_expired = true;
1800 int i;
1802 vfree(udev->mb_addr);
1803 udev->mb_addr = NULL;
1805 spin_lock_bh(&timed_out_udevs_lock);
1806 if (!list_empty(&udev->timedout_entry))
1807 list_del(&udev->timedout_entry);
1808 spin_unlock_bh(&timed_out_udevs_lock);
1810 /* Upper layer should drain all requests before calling this */
1811 mutex_lock(&udev->cmdr_lock);
1812 idr_for_each_entry(&udev->commands, cmd, i) {
1813 if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1814 all_expired = false;
1816 /* There can be left over TMR cmds. Remove them. */
1817 tcmu_remove_all_queued_tmr(udev);
1818 if (!list_empty(&udev->qfull_queue))
1819 all_expired = false;
1820 idr_destroy(&udev->commands);
1821 WARN_ON(!all_expired);
1823 tcmu_blocks_release(&udev->data_blocks, 0, udev->dbi_max + 1);
1824 bitmap_free(udev->data_bitmap);
1825 mutex_unlock(&udev->cmdr_lock);
1827 call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1830 static int tcmu_release(struct uio_info *info, struct inode *inode)
1832 struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1834 clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
1836 pr_debug("close\n");
1837 /* release ref from open */
1838 kref_put(&udev->kref, tcmu_dev_kref_release);
1839 return 0;
1842 static int tcmu_init_genl_cmd_reply(struct tcmu_dev *udev, int cmd)
1844 struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1846 if (!tcmu_kern_cmd_reply_supported)
1847 return 0;
1849 if (udev->nl_reply_supported <= 0)
1850 return 0;
1852 mutex_lock(&tcmu_nl_cmd_mutex);
1854 if (tcmu_netlink_blocked) {
1855 mutex_unlock(&tcmu_nl_cmd_mutex);
1856 pr_warn("Failing nl cmd %d on %s. Interface is blocked.\n", cmd,
1857 udev->name);
1858 return -EAGAIN;
1861 if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
1862 mutex_unlock(&tcmu_nl_cmd_mutex);
1863 pr_warn("netlink cmd %d already executing on %s\n",
1864 nl_cmd->cmd, udev->name);
1865 return -EBUSY;
1868 memset(nl_cmd, 0, sizeof(*nl_cmd));
1869 nl_cmd->cmd = cmd;
1870 nl_cmd->udev = udev;
1871 init_completion(&nl_cmd->complete);
1872 INIT_LIST_HEAD(&nl_cmd->nl_list);
1874 list_add_tail(&nl_cmd->nl_list, &tcmu_nl_cmd_list);
1876 mutex_unlock(&tcmu_nl_cmd_mutex);
1877 return 0;
1880 static void tcmu_destroy_genl_cmd_reply(struct tcmu_dev *udev)
1882 struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1884 if (!tcmu_kern_cmd_reply_supported)
1885 return;
1887 if (udev->nl_reply_supported <= 0)
1888 return;
1890 mutex_lock(&tcmu_nl_cmd_mutex);
1892 list_del(&nl_cmd->nl_list);
1893 memset(nl_cmd, 0, sizeof(*nl_cmd));
1895 mutex_unlock(&tcmu_nl_cmd_mutex);
1898 static int tcmu_wait_genl_cmd_reply(struct tcmu_dev *udev)
1900 struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1901 int ret;
1903 if (!tcmu_kern_cmd_reply_supported)
1904 return 0;
1906 if (udev->nl_reply_supported <= 0)
1907 return 0;
1909 pr_debug("sleeping for nl reply\n");
1910 wait_for_completion(&nl_cmd->complete);
1912 mutex_lock(&tcmu_nl_cmd_mutex);
1913 nl_cmd->cmd = TCMU_CMD_UNSPEC;
1914 ret = nl_cmd->status;
1915 mutex_unlock(&tcmu_nl_cmd_mutex);
1917 return ret;
1920 static int tcmu_netlink_event_init(struct tcmu_dev *udev,
1921 enum tcmu_genl_cmd cmd,
1922 struct sk_buff **buf, void **hdr)
1924 struct sk_buff *skb;
1925 void *msg_header;
1926 int ret = -ENOMEM;
1928 skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1929 if (!skb)
1930 return ret;
1932 msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
1933 if (!msg_header)
1934 goto free_skb;
1936 ret = nla_put_string(skb, TCMU_ATTR_DEVICE, udev->uio_info.name);
1937 if (ret < 0)
1938 goto free_skb;
1940 ret = nla_put_u32(skb, TCMU_ATTR_MINOR, udev->uio_info.uio_dev->minor);
1941 if (ret < 0)
1942 goto free_skb;
1944 ret = nla_put_u32(skb, TCMU_ATTR_DEVICE_ID, udev->se_dev.dev_index);
1945 if (ret < 0)
1946 goto free_skb;
1948 *buf = skb;
1949 *hdr = msg_header;
1950 return ret;
1952 free_skb:
1953 nlmsg_free(skb);
1954 return ret;
1957 static int tcmu_netlink_event_send(struct tcmu_dev *udev,
1958 enum tcmu_genl_cmd cmd,
1959 struct sk_buff *skb, void *msg_header)
1961 int ret;
1963 genlmsg_end(skb, msg_header);
1965 ret = tcmu_init_genl_cmd_reply(udev, cmd);
1966 if (ret) {
1967 nlmsg_free(skb);
1968 return ret;
1971 ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
1972 TCMU_MCGRP_CONFIG, GFP_KERNEL);
1974 /* Wait during an add as the listener may not be up yet */
1975 if (ret == 0 ||
1976 (ret == -ESRCH && cmd == TCMU_CMD_ADDED_DEVICE))
1977 return tcmu_wait_genl_cmd_reply(udev);
1978 else
1979 tcmu_destroy_genl_cmd_reply(udev);
1981 return ret;
1984 static int tcmu_send_dev_add_event(struct tcmu_dev *udev)
1986 struct sk_buff *skb = NULL;
1987 void *msg_header = NULL;
1988 int ret = 0;
1990 ret = tcmu_netlink_event_init(udev, TCMU_CMD_ADDED_DEVICE, &skb,
1991 &msg_header);
1992 if (ret < 0)
1993 return ret;
1994 return tcmu_netlink_event_send(udev, TCMU_CMD_ADDED_DEVICE, skb,
1995 msg_header);
1998 static int tcmu_send_dev_remove_event(struct tcmu_dev *udev)
2000 struct sk_buff *skb = NULL;
2001 void *msg_header = NULL;
2002 int ret = 0;
2004 ret = tcmu_netlink_event_init(udev, TCMU_CMD_REMOVED_DEVICE,
2005 &skb, &msg_header);
2006 if (ret < 0)
2007 return ret;
2008 return tcmu_netlink_event_send(udev, TCMU_CMD_REMOVED_DEVICE,
2009 skb, msg_header);
2012 static int tcmu_update_uio_info(struct tcmu_dev *udev)
2014 struct tcmu_hba *hba = udev->hba->hba_ptr;
2015 struct uio_info *info;
2016 char *str;
2018 info = &udev->uio_info;
2020 if (udev->dev_config[0])
2021 str = kasprintf(GFP_KERNEL, "tcm-user/%u/%s/%s", hba->host_id,
2022 udev->name, udev->dev_config);
2023 else
2024 str = kasprintf(GFP_KERNEL, "tcm-user/%u/%s", hba->host_id,
2025 udev->name);
2026 if (!str)
2027 return -ENOMEM;
2029 /* If the old string exists, free it */
2030 kfree(info->name);
2031 info->name = str;
2033 return 0;
2036 static int tcmu_configure_device(struct se_device *dev)
2038 struct tcmu_dev *udev = TCMU_DEV(dev);
2039 struct uio_info *info;
2040 struct tcmu_mailbox *mb;
2041 int ret = 0;
2043 ret = tcmu_update_uio_info(udev);
2044 if (ret)
2045 return ret;
2047 info = &udev->uio_info;
2049 mutex_lock(&udev->cmdr_lock);
2050 udev->data_bitmap = bitmap_zalloc(udev->max_blocks, GFP_KERNEL);
2051 mutex_unlock(&udev->cmdr_lock);
2052 if (!udev->data_bitmap) {
2053 ret = -ENOMEM;
2054 goto err_bitmap_alloc;
2057 udev->mb_addr = vzalloc(CMDR_SIZE);
2058 if (!udev->mb_addr) {
2059 ret = -ENOMEM;
2060 goto err_vzalloc;
2063 /* mailbox fits in first part of CMDR space */
2064 udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
2065 udev->data_off = CMDR_SIZE;
2066 udev->data_size = udev->max_blocks * DATA_BLOCK_SIZE;
2067 udev->dbi_thresh = 0; /* Default in Idle state */
2069 /* Initialise the mailbox of the ring buffer */
2070 mb = udev->mb_addr;
2071 mb->version = TCMU_MAILBOX_VERSION;
2072 mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC |
2073 TCMU_MAILBOX_FLAG_CAP_READ_LEN |
2074 TCMU_MAILBOX_FLAG_CAP_TMR;
2075 mb->cmdr_off = CMDR_OFF;
2076 mb->cmdr_size = udev->cmdr_size;
2078 WARN_ON(!PAGE_ALIGNED(udev->data_off));
2079 WARN_ON(udev->data_size % PAGE_SIZE);
2080 WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
2082 info->version = __stringify(TCMU_MAILBOX_VERSION);
2084 info->mem[0].name = "tcm-user command & data buffer";
2085 info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
2086 info->mem[0].size = udev->ring_size = udev->data_size + CMDR_SIZE;
2087 info->mem[0].memtype = UIO_MEM_NONE;
2089 info->irqcontrol = tcmu_irqcontrol;
2090 info->irq = UIO_IRQ_CUSTOM;
2092 info->mmap = tcmu_mmap;
2093 info->open = tcmu_open;
2094 info->release = tcmu_release;
2096 ret = uio_register_device(tcmu_root_device, info);
2097 if (ret)
2098 goto err_register;
2100 /* User can set hw_block_size before enable the device */
2101 if (dev->dev_attrib.hw_block_size == 0)
2102 dev->dev_attrib.hw_block_size = 512;
2103 /* Other attributes can be configured in userspace */
2104 if (!dev->dev_attrib.hw_max_sectors)
2105 dev->dev_attrib.hw_max_sectors = 128;
2106 if (!dev->dev_attrib.emulate_write_cache)
2107 dev->dev_attrib.emulate_write_cache = 0;
2108 dev->dev_attrib.hw_queue_depth = 128;
2110 /* If user didn't explicitly disable netlink reply support, use
2111 * module scope setting.
2113 if (udev->nl_reply_supported >= 0)
2114 udev->nl_reply_supported = tcmu_kern_cmd_reply_supported;
2117 * Get a ref incase userspace does a close on the uio device before
2118 * LIO has initiated tcmu_free_device.
2120 kref_get(&udev->kref);
2122 ret = tcmu_send_dev_add_event(udev);
2123 if (ret)
2124 goto err_netlink;
2126 mutex_lock(&root_udev_mutex);
2127 list_add(&udev->node, &root_udev);
2128 mutex_unlock(&root_udev_mutex);
2130 return 0;
2132 err_netlink:
2133 kref_put(&udev->kref, tcmu_dev_kref_release);
2134 uio_unregister_device(&udev->uio_info);
2135 err_register:
2136 vfree(udev->mb_addr);
2137 udev->mb_addr = NULL;
2138 err_vzalloc:
2139 bitmap_free(udev->data_bitmap);
2140 udev->data_bitmap = NULL;
2141 err_bitmap_alloc:
2142 kfree(info->name);
2143 info->name = NULL;
2145 return ret;
2148 static void tcmu_free_device(struct se_device *dev)
2150 struct tcmu_dev *udev = TCMU_DEV(dev);
2152 /* release ref from init */
2153 kref_put(&udev->kref, tcmu_dev_kref_release);
2156 static void tcmu_destroy_device(struct se_device *dev)
2158 struct tcmu_dev *udev = TCMU_DEV(dev);
2160 del_timer_sync(&udev->cmd_timer);
2161 del_timer_sync(&udev->qfull_timer);
2163 mutex_lock(&root_udev_mutex);
2164 list_del(&udev->node);
2165 mutex_unlock(&root_udev_mutex);
2167 tcmu_send_dev_remove_event(udev);
2169 uio_unregister_device(&udev->uio_info);
2171 /* release ref from configure */
2172 kref_put(&udev->kref, tcmu_dev_kref_release);
2175 static void tcmu_unblock_dev(struct tcmu_dev *udev)
2177 mutex_lock(&udev->cmdr_lock);
2178 clear_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags);
2179 mutex_unlock(&udev->cmdr_lock);
2182 static void tcmu_block_dev(struct tcmu_dev *udev)
2184 mutex_lock(&udev->cmdr_lock);
2186 if (test_and_set_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
2187 goto unlock;
2189 /* complete IO that has executed successfully */
2190 tcmu_handle_completions(udev);
2191 /* fail IO waiting to be queued */
2192 run_qfull_queue(udev, true);
2194 unlock:
2195 mutex_unlock(&udev->cmdr_lock);
2198 static void tcmu_reset_ring(struct tcmu_dev *udev, u8 err_level)
2200 struct tcmu_mailbox *mb;
2201 struct tcmu_cmd *cmd;
2202 int i;
2204 mutex_lock(&udev->cmdr_lock);
2206 idr_for_each_entry(&udev->commands, cmd, i) {
2207 pr_debug("removing cmd %u on dev %s from ring (is expired %d)\n",
2208 cmd->cmd_id, udev->name,
2209 test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags));
2211 idr_remove(&udev->commands, i);
2212 if (!test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
2213 WARN_ON(!cmd->se_cmd);
2214 list_del_init(&cmd->queue_entry);
2215 if (err_level == 1) {
2217 * Userspace was not able to start the
2218 * command or it is retryable.
2220 target_complete_cmd(cmd->se_cmd, SAM_STAT_BUSY);
2221 } else {
2222 /* hard failure */
2223 target_complete_cmd(cmd->se_cmd,
2224 SAM_STAT_CHECK_CONDITION);
2227 tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
2228 tcmu_free_cmd(cmd);
2231 mb = udev->mb_addr;
2232 tcmu_flush_dcache_range(mb, sizeof(*mb));
2233 pr_debug("mb last %u head %u tail %u\n", udev->cmdr_last_cleaned,
2234 mb->cmd_tail, mb->cmd_head);
2236 udev->cmdr_last_cleaned = 0;
2237 mb->cmd_tail = 0;
2238 mb->cmd_head = 0;
2239 tcmu_flush_dcache_range(mb, sizeof(*mb));
2240 clear_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
2242 del_timer(&udev->cmd_timer);
2245 * ring is empty and qfull queue never contains aborted commands.
2246 * So TMRs in tmr queue do not contain relevant cmd_ids.
2247 * After a ring reset userspace should do a fresh start, so
2248 * even LUN RESET message is no longer relevant.
2249 * Therefore remove all TMRs from qfull queue
2251 tcmu_remove_all_queued_tmr(udev);
2253 run_qfull_queue(udev, false);
2255 mutex_unlock(&udev->cmdr_lock);
2258 enum {
2259 Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
2260 Opt_nl_reply_supported, Opt_max_data_area_mb, Opt_err,
2263 static match_table_t tokens = {
2264 {Opt_dev_config, "dev_config=%s"},
2265 {Opt_dev_size, "dev_size=%s"},
2266 {Opt_hw_block_size, "hw_block_size=%d"},
2267 {Opt_hw_max_sectors, "hw_max_sectors=%d"},
2268 {Opt_nl_reply_supported, "nl_reply_supported=%d"},
2269 {Opt_max_data_area_mb, "max_data_area_mb=%d"},
2270 {Opt_err, NULL}
2273 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
2275 int val, ret;
2277 ret = match_int(arg, &val);
2278 if (ret < 0) {
2279 pr_err("match_int() failed for dev attrib. Error %d.\n",
2280 ret);
2281 return ret;
2284 if (val <= 0) {
2285 pr_err("Invalid dev attrib value %d. Must be greater than zero.\n",
2286 val);
2287 return -EINVAL;
2289 *dev_attrib = val;
2290 return 0;
2293 static int tcmu_set_max_blocks_param(struct tcmu_dev *udev, substring_t *arg)
2295 int val, ret;
2297 ret = match_int(arg, &val);
2298 if (ret < 0) {
2299 pr_err("match_int() failed for max_data_area_mb=. Error %d.\n",
2300 ret);
2301 return ret;
2304 if (val <= 0) {
2305 pr_err("Invalid max_data_area %d.\n", val);
2306 return -EINVAL;
2309 mutex_lock(&udev->cmdr_lock);
2310 if (udev->data_bitmap) {
2311 pr_err("Cannot set max_data_area_mb after it has been enabled.\n");
2312 ret = -EINVAL;
2313 goto unlock;
2316 udev->max_blocks = TCMU_MBS_TO_BLOCKS(val);
2317 if (udev->max_blocks > tcmu_global_max_blocks) {
2318 pr_err("%d is too large. Adjusting max_data_area_mb to global limit of %u\n",
2319 val, TCMU_BLOCKS_TO_MBS(tcmu_global_max_blocks));
2320 udev->max_blocks = tcmu_global_max_blocks;
2323 unlock:
2324 mutex_unlock(&udev->cmdr_lock);
2325 return ret;
2328 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
2329 const char *page, ssize_t count)
2331 struct tcmu_dev *udev = TCMU_DEV(dev);
2332 char *orig, *ptr, *opts;
2333 substring_t args[MAX_OPT_ARGS];
2334 int ret = 0, token;
2336 opts = kstrdup(page, GFP_KERNEL);
2337 if (!opts)
2338 return -ENOMEM;
2340 orig = opts;
2342 while ((ptr = strsep(&opts, ",\n")) != NULL) {
2343 if (!*ptr)
2344 continue;
2346 token = match_token(ptr, tokens, args);
2347 switch (token) {
2348 case Opt_dev_config:
2349 if (match_strlcpy(udev->dev_config, &args[0],
2350 TCMU_CONFIG_LEN) == 0) {
2351 ret = -EINVAL;
2352 break;
2354 pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
2355 break;
2356 case Opt_dev_size:
2357 ret = match_u64(&args[0], &udev->dev_size);
2358 if (ret < 0)
2359 pr_err("match_u64() failed for dev_size=. Error %d.\n",
2360 ret);
2361 break;
2362 case Opt_hw_block_size:
2363 ret = tcmu_set_dev_attrib(&args[0],
2364 &(dev->dev_attrib.hw_block_size));
2365 break;
2366 case Opt_hw_max_sectors:
2367 ret = tcmu_set_dev_attrib(&args[0],
2368 &(dev->dev_attrib.hw_max_sectors));
2369 break;
2370 case Opt_nl_reply_supported:
2371 ret = match_int(&args[0], &udev->nl_reply_supported);
2372 if (ret < 0)
2373 pr_err("match_int() failed for nl_reply_supported=. Error %d.\n",
2374 ret);
2375 break;
2376 case Opt_max_data_area_mb:
2377 ret = tcmu_set_max_blocks_param(udev, &args[0]);
2378 break;
2379 default:
2380 break;
2383 if (ret)
2384 break;
2387 kfree(orig);
2388 return (!ret) ? count : ret;
2391 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
2393 struct tcmu_dev *udev = TCMU_DEV(dev);
2394 ssize_t bl = 0;
2396 bl = sprintf(b + bl, "Config: %s ",
2397 udev->dev_config[0] ? udev->dev_config : "NULL");
2398 bl += sprintf(b + bl, "Size: %llu ", udev->dev_size);
2399 bl += sprintf(b + bl, "MaxDataAreaMB: %u\n",
2400 TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2402 return bl;
2405 static sector_t tcmu_get_blocks(struct se_device *dev)
2407 struct tcmu_dev *udev = TCMU_DEV(dev);
2409 return div_u64(udev->dev_size - dev->dev_attrib.block_size,
2410 dev->dev_attrib.block_size);
2413 static sense_reason_t
2414 tcmu_parse_cdb(struct se_cmd *cmd)
2416 return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
2419 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
2421 struct se_dev_attrib *da = container_of(to_config_group(item),
2422 struct se_dev_attrib, da_group);
2423 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2425 return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
2428 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
2429 size_t count)
2431 struct se_dev_attrib *da = container_of(to_config_group(item),
2432 struct se_dev_attrib, da_group);
2433 struct tcmu_dev *udev = container_of(da->da_dev,
2434 struct tcmu_dev, se_dev);
2435 u32 val;
2436 int ret;
2438 if (da->da_dev->export_count) {
2439 pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
2440 return -EINVAL;
2443 ret = kstrtou32(page, 0, &val);
2444 if (ret < 0)
2445 return ret;
2447 udev->cmd_time_out = val * MSEC_PER_SEC;
2448 return count;
2450 CONFIGFS_ATTR(tcmu_, cmd_time_out);
2452 static ssize_t tcmu_qfull_time_out_show(struct config_item *item, char *page)
2454 struct se_dev_attrib *da = container_of(to_config_group(item),
2455 struct se_dev_attrib, da_group);
2456 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2458 return snprintf(page, PAGE_SIZE, "%ld\n", udev->qfull_time_out <= 0 ?
2459 udev->qfull_time_out :
2460 udev->qfull_time_out / MSEC_PER_SEC);
2463 static ssize_t tcmu_qfull_time_out_store(struct config_item *item,
2464 const char *page, size_t count)
2466 struct se_dev_attrib *da = container_of(to_config_group(item),
2467 struct se_dev_attrib, da_group);
2468 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2469 s32 val;
2470 int ret;
2472 ret = kstrtos32(page, 0, &val);
2473 if (ret < 0)
2474 return ret;
2476 if (val >= 0) {
2477 udev->qfull_time_out = val * MSEC_PER_SEC;
2478 } else if (val == -1) {
2479 udev->qfull_time_out = val;
2480 } else {
2481 printk(KERN_ERR "Invalid qfull timeout value %d\n", val);
2482 return -EINVAL;
2484 return count;
2486 CONFIGFS_ATTR(tcmu_, qfull_time_out);
2488 static ssize_t tcmu_max_data_area_mb_show(struct config_item *item, char *page)
2490 struct se_dev_attrib *da = container_of(to_config_group(item),
2491 struct se_dev_attrib, da_group);
2492 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2494 return snprintf(page, PAGE_SIZE, "%u\n",
2495 TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2497 CONFIGFS_ATTR_RO(tcmu_, max_data_area_mb);
2499 static ssize_t tcmu_dev_config_show(struct config_item *item, char *page)
2501 struct se_dev_attrib *da = container_of(to_config_group(item),
2502 struct se_dev_attrib, da_group);
2503 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2505 return snprintf(page, PAGE_SIZE, "%s\n", udev->dev_config);
2508 static int tcmu_send_dev_config_event(struct tcmu_dev *udev,
2509 const char *reconfig_data)
2511 struct sk_buff *skb = NULL;
2512 void *msg_header = NULL;
2513 int ret = 0;
2515 ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2516 &skb, &msg_header);
2517 if (ret < 0)
2518 return ret;
2519 ret = nla_put_string(skb, TCMU_ATTR_DEV_CFG, reconfig_data);
2520 if (ret < 0) {
2521 nlmsg_free(skb);
2522 return ret;
2524 return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2525 skb, msg_header);
2529 static ssize_t tcmu_dev_config_store(struct config_item *item, const char *page,
2530 size_t count)
2532 struct se_dev_attrib *da = container_of(to_config_group(item),
2533 struct se_dev_attrib, da_group);
2534 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2535 int ret, len;
2537 len = strlen(page);
2538 if (!len || len > TCMU_CONFIG_LEN - 1)
2539 return -EINVAL;
2541 /* Check if device has been configured before */
2542 if (target_dev_configured(&udev->se_dev)) {
2543 ret = tcmu_send_dev_config_event(udev, page);
2544 if (ret) {
2545 pr_err("Unable to reconfigure device\n");
2546 return ret;
2548 strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2550 ret = tcmu_update_uio_info(udev);
2551 if (ret)
2552 return ret;
2553 return count;
2555 strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2557 return count;
2559 CONFIGFS_ATTR(tcmu_, dev_config);
2561 static ssize_t tcmu_dev_size_show(struct config_item *item, char *page)
2563 struct se_dev_attrib *da = container_of(to_config_group(item),
2564 struct se_dev_attrib, da_group);
2565 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2567 return snprintf(page, PAGE_SIZE, "%llu\n", udev->dev_size);
2570 static int tcmu_send_dev_size_event(struct tcmu_dev *udev, u64 size)
2572 struct sk_buff *skb = NULL;
2573 void *msg_header = NULL;
2574 int ret = 0;
2576 ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2577 &skb, &msg_header);
2578 if (ret < 0)
2579 return ret;
2580 ret = nla_put_u64_64bit(skb, TCMU_ATTR_DEV_SIZE,
2581 size, TCMU_ATTR_PAD);
2582 if (ret < 0) {
2583 nlmsg_free(skb);
2584 return ret;
2586 return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2587 skb, msg_header);
2590 static ssize_t tcmu_dev_size_store(struct config_item *item, const char *page,
2591 size_t count)
2593 struct se_dev_attrib *da = container_of(to_config_group(item),
2594 struct se_dev_attrib, da_group);
2595 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2596 u64 val;
2597 int ret;
2599 ret = kstrtou64(page, 0, &val);
2600 if (ret < 0)
2601 return ret;
2603 /* Check if device has been configured before */
2604 if (target_dev_configured(&udev->se_dev)) {
2605 ret = tcmu_send_dev_size_event(udev, val);
2606 if (ret) {
2607 pr_err("Unable to reconfigure device\n");
2608 return ret;
2611 udev->dev_size = val;
2612 return count;
2614 CONFIGFS_ATTR(tcmu_, dev_size);
2616 static ssize_t tcmu_nl_reply_supported_show(struct config_item *item,
2617 char *page)
2619 struct se_dev_attrib *da = container_of(to_config_group(item),
2620 struct se_dev_attrib, da_group);
2621 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2623 return snprintf(page, PAGE_SIZE, "%d\n", udev->nl_reply_supported);
2626 static ssize_t tcmu_nl_reply_supported_store(struct config_item *item,
2627 const char *page, size_t count)
2629 struct se_dev_attrib *da = container_of(to_config_group(item),
2630 struct se_dev_attrib, da_group);
2631 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2632 s8 val;
2633 int ret;
2635 ret = kstrtos8(page, 0, &val);
2636 if (ret < 0)
2637 return ret;
2639 udev->nl_reply_supported = val;
2640 return count;
2642 CONFIGFS_ATTR(tcmu_, nl_reply_supported);
2644 static ssize_t tcmu_emulate_write_cache_show(struct config_item *item,
2645 char *page)
2647 struct se_dev_attrib *da = container_of(to_config_group(item),
2648 struct se_dev_attrib, da_group);
2650 return snprintf(page, PAGE_SIZE, "%i\n", da->emulate_write_cache);
2653 static int tcmu_send_emulate_write_cache(struct tcmu_dev *udev, u8 val)
2655 struct sk_buff *skb = NULL;
2656 void *msg_header = NULL;
2657 int ret = 0;
2659 ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2660 &skb, &msg_header);
2661 if (ret < 0)
2662 return ret;
2663 ret = nla_put_u8(skb, TCMU_ATTR_WRITECACHE, val);
2664 if (ret < 0) {
2665 nlmsg_free(skb);
2666 return ret;
2668 return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2669 skb, msg_header);
2672 static ssize_t tcmu_emulate_write_cache_store(struct config_item *item,
2673 const char *page, size_t count)
2675 struct se_dev_attrib *da = container_of(to_config_group(item),
2676 struct se_dev_attrib, da_group);
2677 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2678 u8 val;
2679 int ret;
2681 ret = kstrtou8(page, 0, &val);
2682 if (ret < 0)
2683 return ret;
2685 /* Check if device has been configured before */
2686 if (target_dev_configured(&udev->se_dev)) {
2687 ret = tcmu_send_emulate_write_cache(udev, val);
2688 if (ret) {
2689 pr_err("Unable to reconfigure device\n");
2690 return ret;
2694 da->emulate_write_cache = val;
2695 return count;
2697 CONFIGFS_ATTR(tcmu_, emulate_write_cache);
2699 static ssize_t tcmu_tmr_notification_show(struct config_item *item, char *page)
2701 struct se_dev_attrib *da = container_of(to_config_group(item),
2702 struct se_dev_attrib, da_group);
2703 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2705 return snprintf(page, PAGE_SIZE, "%i\n",
2706 test_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags));
2709 static ssize_t tcmu_tmr_notification_store(struct config_item *item,
2710 const char *page, size_t count)
2712 struct se_dev_attrib *da = container_of(to_config_group(item),
2713 struct se_dev_attrib, da_group);
2714 struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2715 u8 val;
2716 int ret;
2718 ret = kstrtou8(page, 0, &val);
2719 if (ret < 0)
2720 return ret;
2721 if (val > 1)
2722 return -EINVAL;
2724 if (val)
2725 set_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags);
2726 else
2727 clear_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags);
2728 return count;
2730 CONFIGFS_ATTR(tcmu_, tmr_notification);
2732 static ssize_t tcmu_block_dev_show(struct config_item *item, char *page)
2734 struct se_device *se_dev = container_of(to_config_group(item),
2735 struct se_device,
2736 dev_action_group);
2737 struct tcmu_dev *udev = TCMU_DEV(se_dev);
2739 if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
2740 return snprintf(page, PAGE_SIZE, "%s\n", "blocked");
2741 else
2742 return snprintf(page, PAGE_SIZE, "%s\n", "unblocked");
2745 static ssize_t tcmu_block_dev_store(struct config_item *item, const char *page,
2746 size_t count)
2748 struct se_device *se_dev = container_of(to_config_group(item),
2749 struct se_device,
2750 dev_action_group);
2751 struct tcmu_dev *udev = TCMU_DEV(se_dev);
2752 u8 val;
2753 int ret;
2755 if (!target_dev_configured(&udev->se_dev)) {
2756 pr_err("Device is not configured.\n");
2757 return -EINVAL;
2760 ret = kstrtou8(page, 0, &val);
2761 if (ret < 0)
2762 return ret;
2764 if (val > 1) {
2765 pr_err("Invalid block value %d\n", val);
2766 return -EINVAL;
2769 if (!val)
2770 tcmu_unblock_dev(udev);
2771 else
2772 tcmu_block_dev(udev);
2773 return count;
2775 CONFIGFS_ATTR(tcmu_, block_dev);
2777 static ssize_t tcmu_reset_ring_store(struct config_item *item, const char *page,
2778 size_t count)
2780 struct se_device *se_dev = container_of(to_config_group(item),
2781 struct se_device,
2782 dev_action_group);
2783 struct tcmu_dev *udev = TCMU_DEV(se_dev);
2784 u8 val;
2785 int ret;
2787 if (!target_dev_configured(&udev->se_dev)) {
2788 pr_err("Device is not configured.\n");
2789 return -EINVAL;
2792 ret = kstrtou8(page, 0, &val);
2793 if (ret < 0)
2794 return ret;
2796 if (val != 1 && val != 2) {
2797 pr_err("Invalid reset ring value %d\n", val);
2798 return -EINVAL;
2801 tcmu_reset_ring(udev, val);
2802 return count;
2804 CONFIGFS_ATTR_WO(tcmu_, reset_ring);
2806 static struct configfs_attribute *tcmu_attrib_attrs[] = {
2807 &tcmu_attr_cmd_time_out,
2808 &tcmu_attr_qfull_time_out,
2809 &tcmu_attr_max_data_area_mb,
2810 &tcmu_attr_dev_config,
2811 &tcmu_attr_dev_size,
2812 &tcmu_attr_emulate_write_cache,
2813 &tcmu_attr_tmr_notification,
2814 &tcmu_attr_nl_reply_supported,
2815 NULL,
2818 static struct configfs_attribute **tcmu_attrs;
2820 static struct configfs_attribute *tcmu_action_attrs[] = {
2821 &tcmu_attr_block_dev,
2822 &tcmu_attr_reset_ring,
2823 NULL,
2826 static struct target_backend_ops tcmu_ops = {
2827 .name = "user",
2828 .owner = THIS_MODULE,
2829 .transport_flags_default = TRANSPORT_FLAG_PASSTHROUGH,
2830 .transport_flags_changeable = TRANSPORT_FLAG_PASSTHROUGH_PGR |
2831 TRANSPORT_FLAG_PASSTHROUGH_ALUA,
2832 .attach_hba = tcmu_attach_hba,
2833 .detach_hba = tcmu_detach_hba,
2834 .alloc_device = tcmu_alloc_device,
2835 .configure_device = tcmu_configure_device,
2836 .destroy_device = tcmu_destroy_device,
2837 .free_device = tcmu_free_device,
2838 .parse_cdb = tcmu_parse_cdb,
2839 .tmr_notify = tcmu_tmr_notify,
2840 .set_configfs_dev_params = tcmu_set_configfs_dev_params,
2841 .show_configfs_dev_params = tcmu_show_configfs_dev_params,
2842 .get_device_type = sbc_get_device_type,
2843 .get_blocks = tcmu_get_blocks,
2844 .tb_dev_action_attrs = tcmu_action_attrs,
2847 static void find_free_blocks(void)
2849 struct tcmu_dev *udev;
2850 loff_t off;
2851 u32 start, end, block, total_freed = 0;
2853 if (atomic_read(&global_db_count) <= tcmu_global_max_blocks)
2854 return;
2856 mutex_lock(&root_udev_mutex);
2857 list_for_each_entry(udev, &root_udev, node) {
2858 mutex_lock(&udev->cmdr_lock);
2860 if (!target_dev_configured(&udev->se_dev)) {
2861 mutex_unlock(&udev->cmdr_lock);
2862 continue;
2865 /* Try to complete the finished commands first */
2866 if (tcmu_handle_completions(udev))
2867 run_qfull_queue(udev, false);
2869 /* Skip the udevs in idle */
2870 if (!udev->dbi_thresh) {
2871 mutex_unlock(&udev->cmdr_lock);
2872 continue;
2875 end = udev->dbi_max + 1;
2876 block = find_last_bit(udev->data_bitmap, end);
2877 if (block == udev->dbi_max) {
2879 * The last bit is dbi_max, so it is not possible
2880 * reclaim any blocks.
2882 mutex_unlock(&udev->cmdr_lock);
2883 continue;
2884 } else if (block == end) {
2885 /* The current udev will goto idle state */
2886 udev->dbi_thresh = start = 0;
2887 udev->dbi_max = 0;
2888 } else {
2889 udev->dbi_thresh = start = block + 1;
2890 udev->dbi_max = block;
2893 /* Here will truncate the data area from off */
2894 off = udev->data_off + start * DATA_BLOCK_SIZE;
2895 unmap_mapping_range(udev->inode->i_mapping, off, 0, 1);
2897 /* Release the block pages */
2898 tcmu_blocks_release(&udev->data_blocks, start, end);
2899 mutex_unlock(&udev->cmdr_lock);
2901 total_freed += end - start;
2902 pr_debug("Freed %u blocks (total %u) from %s.\n", end - start,
2903 total_freed, udev->name);
2905 mutex_unlock(&root_udev_mutex);
2907 if (atomic_read(&global_db_count) > tcmu_global_max_blocks)
2908 schedule_delayed_work(&tcmu_unmap_work, msecs_to_jiffies(5000));
2911 static void check_timedout_devices(void)
2913 struct tcmu_dev *udev, *tmp_dev;
2914 struct tcmu_cmd *cmd, *tmp_cmd;
2915 LIST_HEAD(devs);
2917 spin_lock_bh(&timed_out_udevs_lock);
2918 list_splice_init(&timed_out_udevs, &devs);
2920 list_for_each_entry_safe(udev, tmp_dev, &devs, timedout_entry) {
2921 list_del_init(&udev->timedout_entry);
2922 spin_unlock_bh(&timed_out_udevs_lock);
2924 mutex_lock(&udev->cmdr_lock);
2927 * If cmd_time_out is disabled but qfull is set deadline
2928 * will only reflect the qfull timeout. Ignore it.
2930 if (udev->cmd_time_out) {
2931 list_for_each_entry_safe(cmd, tmp_cmd,
2932 &udev->inflight_queue,
2933 queue_entry) {
2934 tcmu_check_expired_ring_cmd(cmd);
2936 tcmu_set_next_deadline(&udev->inflight_queue,
2937 &udev->cmd_timer);
2939 list_for_each_entry_safe(cmd, tmp_cmd, &udev->qfull_queue,
2940 queue_entry) {
2941 tcmu_check_expired_queue_cmd(cmd);
2943 tcmu_set_next_deadline(&udev->qfull_queue, &udev->qfull_timer);
2945 mutex_unlock(&udev->cmdr_lock);
2947 spin_lock_bh(&timed_out_udevs_lock);
2950 spin_unlock_bh(&timed_out_udevs_lock);
2953 static void tcmu_unmap_work_fn(struct work_struct *work)
2955 check_timedout_devices();
2956 find_free_blocks();
2959 static int __init tcmu_module_init(void)
2961 int ret, i, k, len = 0;
2963 BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
2965 INIT_DELAYED_WORK(&tcmu_unmap_work, tcmu_unmap_work_fn);
2967 tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
2968 sizeof(struct tcmu_cmd),
2969 __alignof__(struct tcmu_cmd),
2970 0, NULL);
2971 if (!tcmu_cmd_cache)
2972 return -ENOMEM;
2974 tcmu_root_device = root_device_register("tcm_user");
2975 if (IS_ERR(tcmu_root_device)) {
2976 ret = PTR_ERR(tcmu_root_device);
2977 goto out_free_cache;
2980 ret = genl_register_family(&tcmu_genl_family);
2981 if (ret < 0) {
2982 goto out_unreg_device;
2985 for (i = 0; passthrough_attrib_attrs[i] != NULL; i++)
2986 len += sizeof(struct configfs_attribute *);
2987 for (i = 0; passthrough_pr_attrib_attrs[i] != NULL; i++)
2988 len += sizeof(struct configfs_attribute *);
2989 for (i = 0; tcmu_attrib_attrs[i] != NULL; i++)
2990 len += sizeof(struct configfs_attribute *);
2991 len += sizeof(struct configfs_attribute *);
2993 tcmu_attrs = kzalloc(len, GFP_KERNEL);
2994 if (!tcmu_attrs) {
2995 ret = -ENOMEM;
2996 goto out_unreg_genl;
2999 for (i = 0; passthrough_attrib_attrs[i] != NULL; i++)
3000 tcmu_attrs[i] = passthrough_attrib_attrs[i];
3001 for (k = 0; passthrough_pr_attrib_attrs[k] != NULL; k++)
3002 tcmu_attrs[i++] = passthrough_pr_attrib_attrs[k];
3003 for (k = 0; tcmu_attrib_attrs[k] != NULL; k++)
3004 tcmu_attrs[i++] = tcmu_attrib_attrs[k];
3005 tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
3007 ret = transport_backend_register(&tcmu_ops);
3008 if (ret)
3009 goto out_attrs;
3011 return 0;
3013 out_attrs:
3014 kfree(tcmu_attrs);
3015 out_unreg_genl:
3016 genl_unregister_family(&tcmu_genl_family);
3017 out_unreg_device:
3018 root_device_unregister(tcmu_root_device);
3019 out_free_cache:
3020 kmem_cache_destroy(tcmu_cmd_cache);
3022 return ret;
3025 static void __exit tcmu_module_exit(void)
3027 cancel_delayed_work_sync(&tcmu_unmap_work);
3028 target_backend_unregister(&tcmu_ops);
3029 kfree(tcmu_attrs);
3030 genl_unregister_family(&tcmu_genl_family);
3031 root_device_unregister(tcmu_root_device);
3032 kmem_cache_destroy(tcmu_cmd_cache);
3035 MODULE_DESCRIPTION("TCM USER subsystem plugin");
3036 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
3037 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
3038 MODULE_LICENSE("GPL");
3040 module_init(tcmu_module_init);
3041 module_exit(tcmu_module_exit);