1 /*
2  * Copyright (C) 2013 Shaohua Li <shli@kernel.org>
3  * Copyright (C) 2014 Red Hat, Inc.
4  * Copyright (C) 2015 Arrikto, Inc.
5  * Copyright (C) 2017 Chinamobile, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms and conditions of the GNU General Public License,
9  * version 2, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 #include <linux/spinlock.h>
22 #include <linux/module.h>
23 #include <linux/idr.h>
24 #include <linux/kernel.h>
25 #include <linux/timer.h>
26 #include <linux/parser.h>
27 #include <linux/vmalloc.h>
28 #include <linux/uio_driver.h>
29 #include <linux/radix-tree.h>
30 #include <linux/stringify.h>
31 #include <linux/bitops.h>
32 #include <linux/highmem.h>
33 #include <linux/configfs.h>
34 #include <linux/mutex.h>
35 #include <linux/workqueue.h>
36 #include <net/genetlink.h>
37 #include <scsi/scsi_common.h>
38 #include <scsi/scsi_proto.h>
39 #include <target/target_core_base.h>
40 #include <target/target_core_fabric.h>
41 #include <target/target_core_backend.h>
42 
43 #include <linux/target_core_user.h>
44 
45 /**
46  * DOC: Userspace I/O
47  * Userspace I/O
48  * -------------
49  *
50  * Define a shared-memory interface for LIO to pass SCSI commands and
51  * data to userspace for processing. This is to allow backends that
52  * are too complex for in-kernel support to be possible.
53  *
54  * It uses the UIO framework to do a lot of the device-creation and
55  * introspection work for us.
56  *
57  * See the .h file for how the ring is laid out. Note that while the
58  * command ring is defined, the particulars of the data area are
59  * not. Offset values in the command entry point to other locations
60  * internal to the mmap-ed area. There is separate space outside the
61  * command ring for data buffers. This leaves maximum flexibility for
62  * moving buffer allocations, or even page flipping or other
63  * allocation techniques, without altering the command ring layout.
64  *
65  * SECURITY:
66  * The user process must be assumed to be malicious. There's no way to
67  * prevent it breaking the command ring protocol if it wants, but in
68  * order to prevent other issues we must only ever read *data* from
69  * the shared memory area, not offsets or sizes. This applies to
70  * command ring entries as well as the mailbox. Extra code needed for
71  * this may have a 'UAM' comment.
72  */
73 
74 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
75 
76 /* For cmd area, the size is fixed 8MB */
77 #define CMDR_SIZE (8 * 1024 * 1024)
78 
79 /*
80  * For data area, the block size is PAGE_SIZE and
81  * the total size is 256K * PAGE_SIZE.
82  */
83 #define DATA_BLOCK_SIZE PAGE_SIZE
84 #define DATA_BLOCK_SHIFT PAGE_SHIFT
85 #define DATA_BLOCK_BITS_DEF (256 * 1024)
86 
87 #define TCMU_MBS_TO_BLOCKS(_mbs) (_mbs << (20 - DATA_BLOCK_SHIFT))
88 #define TCMU_BLOCKS_TO_MBS(_blocks) (_blocks >> (20 - DATA_BLOCK_SHIFT))
89 
90 /*
91  * Default number of global data blocks(512K * PAGE_SIZE)
92  * when the unmap thread will be started.
93  */
94 #define TCMU_GLOBAL_MAX_BLOCKS_DEF (512 * 1024)
95 
96 static u8 tcmu_kern_cmd_reply_supported;
97 static u8 tcmu_netlink_blocked;
98 
99 static struct device *tcmu_root_device;
100 
101 struct tcmu_hba {
102 	u32 host_id;
103 };
104 
105 #define TCMU_CONFIG_LEN 256
106 
107 static DEFINE_MUTEX(tcmu_nl_cmd_mutex);
108 static LIST_HEAD(tcmu_nl_cmd_list);
109 
110 struct tcmu_dev;
111 
112 struct tcmu_nl_cmd {
113 	/* wake up thread waiting for reply */
114 	struct completion complete;
115 	struct list_head nl_list;
116 	struct tcmu_dev *udev;
117 	int cmd;
118 	int status;
119 };
120 
121 struct tcmu_dev {
122 	struct list_head node;
123 	struct kref kref;
124 
125 	struct se_device se_dev;
126 
127 	char *name;
128 	struct se_hba *hba;
129 
130 #define TCMU_DEV_BIT_OPEN 0
131 #define TCMU_DEV_BIT_BROKEN 1
132 #define TCMU_DEV_BIT_BLOCKED 2
133 	unsigned long flags;
134 
135 	struct uio_info uio_info;
136 
137 	struct inode *inode;
138 
139 	struct tcmu_mailbox *mb_addr;
140 	uint64_t dev_size;
141 	u32 cmdr_size;
142 	u32 cmdr_last_cleaned;
143 	/* Offset of data area from start of mb */
144 	/* Must add data_off and mb_addr to get the address */
145 	size_t data_off;
146 	size_t data_size;
147 	uint32_t max_blocks;
148 	size_t ring_size;
149 
150 	struct mutex cmdr_lock;
151 	struct list_head cmdr_queue;
152 
153 	uint32_t dbi_max;
154 	uint32_t dbi_thresh;
155 	unsigned long *data_bitmap;
156 	struct radix_tree_root data_blocks;
157 
158 	struct idr commands;
159 
160 	struct timer_list cmd_timer;
161 	unsigned int cmd_time_out;
162 
163 	struct timer_list qfull_timer;
164 	int qfull_time_out;
165 
166 	struct list_head timedout_entry;
167 
168 	struct tcmu_nl_cmd curr_nl_cmd;
169 
170 	char dev_config[TCMU_CONFIG_LEN];
171 
172 	int nl_reply_supported;
173 };
174 
175 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
176 
177 #define CMDR_OFF sizeof(struct tcmu_mailbox)
178 
179 struct tcmu_cmd {
180 	struct se_cmd *se_cmd;
181 	struct tcmu_dev *tcmu_dev;
182 	struct list_head cmdr_queue_entry;
183 
184 	uint16_t cmd_id;
185 
186 	/* Can't use se_cmd when cleaning up expired cmds, because if
187 	   cmd has been completed then accessing se_cmd is off limits */
188 	uint32_t dbi_cnt;
189 	uint32_t dbi_cur;
190 	uint32_t *dbi;
191 
192 	unsigned long deadline;
193 
194 #define TCMU_CMD_BIT_EXPIRED 0
195 	unsigned long flags;
196 };
197 /*
198  * To avoid dead lock the mutex lock order should always be:
199  *
200  * mutex_lock(&root_udev_mutex);
201  * ...
202  * mutex_lock(&tcmu_dev->cmdr_lock);
203  * mutex_unlock(&tcmu_dev->cmdr_lock);
204  * ...
205  * mutex_unlock(&root_udev_mutex);
206  */
207 static DEFINE_MUTEX(root_udev_mutex);
208 static LIST_HEAD(root_udev);
209 
210 static DEFINE_SPINLOCK(timed_out_udevs_lock);
211 static LIST_HEAD(timed_out_udevs);
212 
213 static struct kmem_cache *tcmu_cmd_cache;
214 
215 static atomic_t global_db_count = ATOMIC_INIT(0);
216 static struct delayed_work tcmu_unmap_work;
217 static int tcmu_global_max_blocks = TCMU_GLOBAL_MAX_BLOCKS_DEF;
218 
219 static int tcmu_set_global_max_data_area(const char *str,
220 					 const struct kernel_param *kp)
221 {
222 	int ret, max_area_mb;
223 
224 	ret = kstrtoint(str, 10, &max_area_mb);
225 	if (ret)
226 		return -EINVAL;
227 
228 	if (max_area_mb <= 0) {
229 		pr_err("global_max_data_area must be larger than 0.\n");
230 		return -EINVAL;
231 	}
232 
233 	tcmu_global_max_blocks = TCMU_MBS_TO_BLOCKS(max_area_mb);
234 	if (atomic_read(&global_db_count) > tcmu_global_max_blocks)
235 		schedule_delayed_work(&tcmu_unmap_work, 0);
236 	else
237 		cancel_delayed_work_sync(&tcmu_unmap_work);
238 
239 	return 0;
240 }
241 
242 static int tcmu_get_global_max_data_area(char *buffer,
243 					 const struct kernel_param *kp)
244 {
245 	return sprintf(buffer, "%d", TCMU_BLOCKS_TO_MBS(tcmu_global_max_blocks));
246 }
247 
248 static const struct kernel_param_ops tcmu_global_max_data_area_op = {
249 	.set = tcmu_set_global_max_data_area,
250 	.get = tcmu_get_global_max_data_area,
251 };
252 
253 module_param_cb(global_max_data_area_mb, &tcmu_global_max_data_area_op, NULL,
254 		S_IWUSR | S_IRUGO);
255 MODULE_PARM_DESC(global_max_data_area_mb,
256 		 "Max MBs allowed to be allocated to all the tcmu device's "
257 		 "data areas.");
258 
259 static int tcmu_get_block_netlink(char *buffer,
260 				  const struct kernel_param *kp)
261 {
262 	return sprintf(buffer, "%s\n", tcmu_netlink_blocked ?
263 		       "blocked" : "unblocked");
264 }
265 
266 static int tcmu_set_block_netlink(const char *str,
267 				  const struct kernel_param *kp)
268 {
269 	int ret;
270 	u8 val;
271 
272 	ret = kstrtou8(str, 0, &val);
273 	if (ret < 0)
274 		return ret;
275 
276 	if (val > 1) {
277 		pr_err("Invalid block netlink value %u\n", val);
278 		return -EINVAL;
279 	}
280 
281 	tcmu_netlink_blocked = val;
282 	return 0;
283 }
284 
285 static const struct kernel_param_ops tcmu_block_netlink_op = {
286 	.set = tcmu_set_block_netlink,
287 	.get = tcmu_get_block_netlink,
288 };
289 
290 module_param_cb(block_netlink, &tcmu_block_netlink_op, NULL, S_IWUSR | S_IRUGO);
291 MODULE_PARM_DESC(block_netlink, "Block new netlink commands.");
292 
293 static int tcmu_fail_netlink_cmd(struct tcmu_nl_cmd *nl_cmd)
294 {
295 	struct tcmu_dev *udev = nl_cmd->udev;
296 
297 	if (!tcmu_netlink_blocked) {
298 		pr_err("Could not reset device's netlink interface. Netlink is not blocked.\n");
299 		return -EBUSY;
300 	}
301 
302 	if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
303 		pr_debug("Aborting nl cmd %d on %s\n", nl_cmd->cmd, udev->name);
304 		nl_cmd->status = -EINTR;
305 		list_del(&nl_cmd->nl_list);
306 		complete(&nl_cmd->complete);
307 	}
308 	return 0;
309 }
310 
311 static int tcmu_set_reset_netlink(const char *str,
312 				  const struct kernel_param *kp)
313 {
314 	struct tcmu_nl_cmd *nl_cmd, *tmp_cmd;
315 	int ret;
316 	u8 val;
317 
318 	ret = kstrtou8(str, 0, &val);
319 	if (ret < 0)
320 		return ret;
321 
322 	if (val != 1) {
323 		pr_err("Invalid reset netlink value %u\n", val);
324 		return -EINVAL;
325 	}
326 
327 	mutex_lock(&tcmu_nl_cmd_mutex);
328 	list_for_each_entry_safe(nl_cmd, tmp_cmd, &tcmu_nl_cmd_list, nl_list) {
329 		ret = tcmu_fail_netlink_cmd(nl_cmd);
330 		if (ret)
331 			break;
332 	}
333 	mutex_unlock(&tcmu_nl_cmd_mutex);
334 
335 	return ret;
336 }
337 
338 static const struct kernel_param_ops tcmu_reset_netlink_op = {
339 	.set = tcmu_set_reset_netlink,
340 };
341 
342 module_param_cb(reset_netlink, &tcmu_reset_netlink_op, NULL, S_IWUSR);
343 MODULE_PARM_DESC(reset_netlink, "Reset netlink commands.");
344 
345 /* multicast group */
346 enum tcmu_multicast_groups {
347 	TCMU_MCGRP_CONFIG,
348 };
349 
350 static const struct genl_multicast_group tcmu_mcgrps[] = {
351 	[TCMU_MCGRP_CONFIG] = { .name = "config", },
352 };
353 
354 static struct nla_policy tcmu_attr_policy[TCMU_ATTR_MAX+1] = {
355 	[TCMU_ATTR_DEVICE]	= { .type = NLA_STRING },
356 	[TCMU_ATTR_MINOR]	= { .type = NLA_U32 },
357 	[TCMU_ATTR_CMD_STATUS]	= { .type = NLA_S32 },
358 	[TCMU_ATTR_DEVICE_ID]	= { .type = NLA_U32 },
359 	[TCMU_ATTR_SUPP_KERN_CMD_REPLY] = { .type = NLA_U8 },
360 };
361 
362 static int tcmu_genl_cmd_done(struct genl_info *info, int completed_cmd)
363 {
364 	struct tcmu_dev *udev = NULL;
365 	struct tcmu_nl_cmd *nl_cmd;
366 	int dev_id, rc, ret = 0;
367 
368 	if (!info->attrs[TCMU_ATTR_CMD_STATUS] ||
369 	    !info->attrs[TCMU_ATTR_DEVICE_ID]) {
370 		printk(KERN_ERR "TCMU_ATTR_CMD_STATUS or TCMU_ATTR_DEVICE_ID not set, doing nothing\n");
371 		return -EINVAL;
372         }
373 
374 	dev_id = nla_get_u32(info->attrs[TCMU_ATTR_DEVICE_ID]);
375 	rc = nla_get_s32(info->attrs[TCMU_ATTR_CMD_STATUS]);
376 
377 	mutex_lock(&tcmu_nl_cmd_mutex);
378 	list_for_each_entry(nl_cmd, &tcmu_nl_cmd_list, nl_list) {
379 		if (nl_cmd->udev->se_dev.dev_index == dev_id) {
380 			udev = nl_cmd->udev;
381 			break;
382 		}
383 	}
384 
385 	if (!udev) {
386 		pr_err("tcmu nl cmd %u/%d completion could not find device with dev id %u.\n",
387 		       completed_cmd, rc, dev_id);
388 		ret = -ENODEV;
389 		goto unlock;
390 	}
391 	list_del(&nl_cmd->nl_list);
392 
393 	pr_debug("%s genl cmd done got id %d curr %d done %d rc %d stat %d\n",
394 		 udev->name, dev_id, nl_cmd->cmd, completed_cmd, rc,
395 		 nl_cmd->status);
396 
397 	if (nl_cmd->cmd != completed_cmd) {
398 		pr_err("Mismatched commands on %s (Expecting reply for %d. Current %d).\n",
399 		       udev->name, completed_cmd, nl_cmd->cmd);
400 		ret = -EINVAL;
401 		goto unlock;
402 	}
403 
404 	nl_cmd->status = rc;
405 	complete(&nl_cmd->complete);
406 unlock:
407 	mutex_unlock(&tcmu_nl_cmd_mutex);
408 	return ret;
409 }
410 
411 static int tcmu_genl_rm_dev_done(struct sk_buff *skb, struct genl_info *info)
412 {
413 	return tcmu_genl_cmd_done(info, TCMU_CMD_REMOVED_DEVICE);
414 }
415 
416 static int tcmu_genl_add_dev_done(struct sk_buff *skb, struct genl_info *info)
417 {
418 	return tcmu_genl_cmd_done(info, TCMU_CMD_ADDED_DEVICE);
419 }
420 
421 static int tcmu_genl_reconfig_dev_done(struct sk_buff *skb,
422 				       struct genl_info *info)
423 {
424 	return tcmu_genl_cmd_done(info, TCMU_CMD_RECONFIG_DEVICE);
425 }
426 
427 static int tcmu_genl_set_features(struct sk_buff *skb, struct genl_info *info)
428 {
429 	if (info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]) {
430 		tcmu_kern_cmd_reply_supported  =
431 			nla_get_u8(info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]);
432 		printk(KERN_INFO "tcmu daemon: command reply support %u.\n",
433 		       tcmu_kern_cmd_reply_supported);
434 	}
435 
436 	return 0;
437 }
438 
439 static const struct genl_ops tcmu_genl_ops[] = {
440 	{
441 		.cmd	= TCMU_CMD_SET_FEATURES,
442 		.flags	= GENL_ADMIN_PERM,
443 		.policy	= tcmu_attr_policy,
444 		.doit	= tcmu_genl_set_features,
445 	},
446 	{
447 		.cmd	= TCMU_CMD_ADDED_DEVICE_DONE,
448 		.flags	= GENL_ADMIN_PERM,
449 		.policy	= tcmu_attr_policy,
450 		.doit	= tcmu_genl_add_dev_done,
451 	},
452 	{
453 		.cmd	= TCMU_CMD_REMOVED_DEVICE_DONE,
454 		.flags	= GENL_ADMIN_PERM,
455 		.policy	= tcmu_attr_policy,
456 		.doit	= tcmu_genl_rm_dev_done,
457 	},
458 	{
459 		.cmd	= TCMU_CMD_RECONFIG_DEVICE_DONE,
460 		.flags	= GENL_ADMIN_PERM,
461 		.policy	= tcmu_attr_policy,
462 		.doit	= tcmu_genl_reconfig_dev_done,
463 	},
464 };
465 
466 /* Our generic netlink family */
467 static struct genl_family tcmu_genl_family __ro_after_init = {
468 	.module = THIS_MODULE,
469 	.hdrsize = 0,
470 	.name = "TCM-USER",
471 	.version = 2,
472 	.maxattr = TCMU_ATTR_MAX,
473 	.mcgrps = tcmu_mcgrps,
474 	.n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
475 	.netnsok = true,
476 	.ops = tcmu_genl_ops,
477 	.n_ops = ARRAY_SIZE(tcmu_genl_ops),
478 };
479 
480 #define tcmu_cmd_set_dbi_cur(cmd, index) ((cmd)->dbi_cur = (index))
481 #define tcmu_cmd_reset_dbi_cur(cmd) tcmu_cmd_set_dbi_cur(cmd, 0)
482 #define tcmu_cmd_set_dbi(cmd, index) ((cmd)->dbi[(cmd)->dbi_cur++] = (index))
483 #define tcmu_cmd_get_dbi(cmd) ((cmd)->dbi[(cmd)->dbi_cur++])
484 
485 static void tcmu_cmd_free_data(struct tcmu_cmd *tcmu_cmd, uint32_t len)
486 {
487 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
488 	uint32_t i;
489 
490 	for (i = 0; i < len; i++)
491 		clear_bit(tcmu_cmd->dbi[i], udev->data_bitmap);
492 }
493 
494 static inline bool tcmu_get_empty_block(struct tcmu_dev *udev,
495 					struct tcmu_cmd *tcmu_cmd)
496 {
497 	struct page *page;
498 	int ret, dbi;
499 
500 	dbi = find_first_zero_bit(udev->data_bitmap, udev->dbi_thresh);
501 	if (dbi == udev->dbi_thresh)
502 		return false;
503 
504 	page = radix_tree_lookup(&udev->data_blocks, dbi);
505 	if (!page) {
506 		if (atomic_add_return(1, &global_db_count) >
507 				      tcmu_global_max_blocks)
508 			schedule_delayed_work(&tcmu_unmap_work, 0);
509 
510 		/* try to get new page from the mm */
511 		page = alloc_page(GFP_KERNEL);
512 		if (!page)
513 			goto err_alloc;
514 
515 		ret = radix_tree_insert(&udev->data_blocks, dbi, page);
516 		if (ret)
517 			goto err_insert;
518 	}
519 
520 	if (dbi > udev->dbi_max)
521 		udev->dbi_max = dbi;
522 
523 	set_bit(dbi, udev->data_bitmap);
524 	tcmu_cmd_set_dbi(tcmu_cmd, dbi);
525 
526 	return true;
527 err_insert:
528 	__free_page(page);
529 err_alloc:
530 	atomic_dec(&global_db_count);
531 	return false;
532 }
533 
534 static bool tcmu_get_empty_blocks(struct tcmu_dev *udev,
535 				  struct tcmu_cmd *tcmu_cmd)
536 {
537 	int i;
538 
539 	for (i = tcmu_cmd->dbi_cur; i < tcmu_cmd->dbi_cnt; i++) {
540 		if (!tcmu_get_empty_block(udev, tcmu_cmd))
541 			return false;
542 	}
543 	return true;
544 }
545 
546 static inline struct page *
547 tcmu_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
548 {
549 	return radix_tree_lookup(&udev->data_blocks, dbi);
550 }
551 
552 static inline void tcmu_free_cmd(struct tcmu_cmd *tcmu_cmd)
553 {
554 	kfree(tcmu_cmd->dbi);
555 	kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
556 }
557 
558 static inline size_t tcmu_cmd_get_data_length(struct tcmu_cmd *tcmu_cmd)
559 {
560 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
561 	size_t data_length = round_up(se_cmd->data_length, DATA_BLOCK_SIZE);
562 
563 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
564 		BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
565 		data_length += round_up(se_cmd->t_bidi_data_sg->length,
566 				DATA_BLOCK_SIZE);
567 	}
568 
569 	return data_length;
570 }
571 
572 static inline uint32_t tcmu_cmd_get_block_cnt(struct tcmu_cmd *tcmu_cmd)
573 {
574 	size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
575 
576 	return data_length / DATA_BLOCK_SIZE;
577 }
578 
579 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
580 {
581 	struct se_device *se_dev = se_cmd->se_dev;
582 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
583 	struct tcmu_cmd *tcmu_cmd;
584 
585 	tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
586 	if (!tcmu_cmd)
587 		return NULL;
588 
589 	INIT_LIST_HEAD(&tcmu_cmd->cmdr_queue_entry);
590 	tcmu_cmd->se_cmd = se_cmd;
591 	tcmu_cmd->tcmu_dev = udev;
592 
593 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
594 	tcmu_cmd->dbi_cnt = tcmu_cmd_get_block_cnt(tcmu_cmd);
595 	tcmu_cmd->dbi = kcalloc(tcmu_cmd->dbi_cnt, sizeof(uint32_t),
596 				GFP_KERNEL);
597 	if (!tcmu_cmd->dbi) {
598 		kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
599 		return NULL;
600 	}
601 
602 	return tcmu_cmd;
603 }
604 
605 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
606 {
607 	unsigned long offset = offset_in_page(vaddr);
608 	void *start = vaddr - offset;
609 
610 	size = round_up(size+offset, PAGE_SIZE);
611 
612 	while (size) {
613 		flush_dcache_page(virt_to_page(start));
614 		start += PAGE_SIZE;
615 		size -= PAGE_SIZE;
616 	}
617 }
618 
619 /*
620  * Some ring helper functions. We don't assume size is a power of 2 so
621  * we can't use circ_buf.h.
622  */
623 static inline size_t spc_used(size_t head, size_t tail, size_t size)
624 {
625 	int diff = head - tail;
626 
627 	if (diff >= 0)
628 		return diff;
629 	else
630 		return size + diff;
631 }
632 
633 static inline size_t spc_free(size_t head, size_t tail, size_t size)
634 {
635 	/* Keep 1 byte unused or we can't tell full from empty */
636 	return (size - spc_used(head, tail, size) - 1);
637 }
638 
639 static inline size_t head_to_end(size_t head, size_t size)
640 {
641 	return size - head;
642 }
643 
644 static inline void new_iov(struct iovec **iov, int *iov_cnt)
645 {
646 	struct iovec *iovec;
647 
648 	if (*iov_cnt != 0)
649 		(*iov)++;
650 	(*iov_cnt)++;
651 
652 	iovec = *iov;
653 	memset(iovec, 0, sizeof(struct iovec));
654 }
655 
656 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
657 
658 /* offset is relative to mb_addr */
659 static inline size_t get_block_offset_user(struct tcmu_dev *dev,
660 		int dbi, int remaining)
661 {
662 	return dev->data_off + dbi * DATA_BLOCK_SIZE +
663 		DATA_BLOCK_SIZE - remaining;
664 }
665 
666 static inline size_t iov_tail(struct iovec *iov)
667 {
668 	return (size_t)iov->iov_base + iov->iov_len;
669 }
670 
671 static void scatter_data_area(struct tcmu_dev *udev,
672 	struct tcmu_cmd *tcmu_cmd, struct scatterlist *data_sg,
673 	unsigned int data_nents, struct iovec **iov,
674 	int *iov_cnt, bool copy_data)
675 {
676 	int i, dbi;
677 	int block_remaining = 0;
678 	void *from, *to = NULL;
679 	size_t copy_bytes, to_offset, offset;
680 	struct scatterlist *sg;
681 	struct page *page;
682 
683 	for_each_sg(data_sg, sg, data_nents, i) {
684 		int sg_remaining = sg->length;
685 		from = kmap_atomic(sg_page(sg)) + sg->offset;
686 		while (sg_remaining > 0) {
687 			if (block_remaining == 0) {
688 				if (to)
689 					kunmap_atomic(to);
690 
691 				block_remaining = DATA_BLOCK_SIZE;
692 				dbi = tcmu_cmd_get_dbi(tcmu_cmd);
693 				page = tcmu_get_block_page(udev, dbi);
694 				to = kmap_atomic(page);
695 			}
696 
697 			/*
698 			 * Covert to virtual offset of the ring data area.
699 			 */
700 			to_offset = get_block_offset_user(udev, dbi,
701 					block_remaining);
702 
703 			/*
704 			 * The following code will gather and map the blocks
705 			 * to the same iovec when the blocks are all next to
706 			 * each other.
707 			 */
708 			copy_bytes = min_t(size_t, sg_remaining,
709 					block_remaining);
710 			if (*iov_cnt != 0 &&
711 			    to_offset == iov_tail(*iov)) {
712 				/*
713 				 * Will append to the current iovec, because
714 				 * the current block page is next to the
715 				 * previous one.
716 				 */
717 				(*iov)->iov_len += copy_bytes;
718 			} else {
719 				/*
720 				 * Will allocate a new iovec because we are
721 				 * first time here or the current block page
722 				 * is not next to the previous one.
723 				 */
724 				new_iov(iov, iov_cnt);
725 				(*iov)->iov_base = (void __user *)to_offset;
726 				(*iov)->iov_len = copy_bytes;
727 			}
728 
729 			if (copy_data) {
730 				offset = DATA_BLOCK_SIZE - block_remaining;
731 				memcpy(to + offset,
732 				       from + sg->length - sg_remaining,
733 				       copy_bytes);
734 				tcmu_flush_dcache_range(to, copy_bytes);
735 			}
736 
737 			sg_remaining -= copy_bytes;
738 			block_remaining -= copy_bytes;
739 		}
740 		kunmap_atomic(from - sg->offset);
741 	}
742 
743 	if (to)
744 		kunmap_atomic(to);
745 }
746 
747 static void gather_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
748 			     bool bidi, uint32_t read_len)
749 {
750 	struct se_cmd *se_cmd = cmd->se_cmd;
751 	int i, dbi;
752 	int block_remaining = 0;
753 	void *from = NULL, *to;
754 	size_t copy_bytes, offset;
755 	struct scatterlist *sg, *data_sg;
756 	struct page *page;
757 	unsigned int data_nents;
758 	uint32_t count = 0;
759 
760 	if (!bidi) {
761 		data_sg = se_cmd->t_data_sg;
762 		data_nents = se_cmd->t_data_nents;
763 	} else {
764 
765 		/*
766 		 * For bidi case, the first count blocks are for Data-Out
767 		 * buffer blocks, and before gathering the Data-In buffer
768 		 * the Data-Out buffer blocks should be discarded.
769 		 */
770 		count = DIV_ROUND_UP(se_cmd->data_length, DATA_BLOCK_SIZE);
771 
772 		data_sg = se_cmd->t_bidi_data_sg;
773 		data_nents = se_cmd->t_bidi_data_nents;
774 	}
775 
776 	tcmu_cmd_set_dbi_cur(cmd, count);
777 
778 	for_each_sg(data_sg, sg, data_nents, i) {
779 		int sg_remaining = sg->length;
780 		to = kmap_atomic(sg_page(sg)) + sg->offset;
781 		while (sg_remaining > 0 && read_len > 0) {
782 			if (block_remaining == 0) {
783 				if (from)
784 					kunmap_atomic(from);
785 
786 				block_remaining = DATA_BLOCK_SIZE;
787 				dbi = tcmu_cmd_get_dbi(cmd);
788 				page = tcmu_get_block_page(udev, dbi);
789 				from = kmap_atomic(page);
790 			}
791 			copy_bytes = min_t(size_t, sg_remaining,
792 					block_remaining);
793 			if (read_len < copy_bytes)
794 				copy_bytes = read_len;
795 			offset = DATA_BLOCK_SIZE - block_remaining;
796 			tcmu_flush_dcache_range(from, copy_bytes);
797 			memcpy(to + sg->length - sg_remaining, from + offset,
798 					copy_bytes);
799 
800 			sg_remaining -= copy_bytes;
801 			block_remaining -= copy_bytes;
802 			read_len -= copy_bytes;
803 		}
804 		kunmap_atomic(to - sg->offset);
805 		if (read_len == 0)
806 			break;
807 	}
808 	if (from)
809 		kunmap_atomic(from);
810 }
811 
812 static inline size_t spc_bitmap_free(unsigned long *bitmap, uint32_t thresh)
813 {
814 	return thresh - bitmap_weight(bitmap, thresh);
815 }
816 
817 /*
818  * We can't queue a command until we have space available on the cmd ring *and*
819  * space available on the data area.
820  *
821  * Called with ring lock held.
822  */
823 static bool is_ring_space_avail(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
824 		size_t cmd_size, size_t data_needed)
825 {
826 	struct tcmu_mailbox *mb = udev->mb_addr;
827 	uint32_t blocks_needed = (data_needed + DATA_BLOCK_SIZE - 1)
828 				/ DATA_BLOCK_SIZE;
829 	size_t space, cmd_needed;
830 	u32 cmd_head;
831 
832 	tcmu_flush_dcache_range(mb, sizeof(*mb));
833 
834 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
835 
836 	/*
837 	 * If cmd end-of-ring space is too small then we need space for a NOP plus
838 	 * original cmd - cmds are internally contiguous.
839 	 */
840 	if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
841 		cmd_needed = cmd_size;
842 	else
843 		cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
844 
845 	space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
846 	if (space < cmd_needed) {
847 		pr_debug("no cmd space: %u %u %u\n", cmd_head,
848 		       udev->cmdr_last_cleaned, udev->cmdr_size);
849 		return false;
850 	}
851 
852 	/* try to check and get the data blocks as needed */
853 	space = spc_bitmap_free(udev->data_bitmap, udev->dbi_thresh);
854 	if ((space * DATA_BLOCK_SIZE) < data_needed) {
855 		unsigned long blocks_left =
856 				(udev->max_blocks - udev->dbi_thresh) + space;
857 
858 		if (blocks_left < blocks_needed) {
859 			pr_debug("no data space: only %lu available, but ask for %zu\n",
860 					blocks_left * DATA_BLOCK_SIZE,
861 					data_needed);
862 			return false;
863 		}
864 
865 		udev->dbi_thresh += blocks_needed;
866 		if (udev->dbi_thresh > udev->max_blocks)
867 			udev->dbi_thresh = udev->max_blocks;
868 	}
869 
870 	return tcmu_get_empty_blocks(udev, cmd);
871 }
872 
873 static inline size_t tcmu_cmd_get_base_cmd_size(size_t iov_cnt)
874 {
875 	return max(offsetof(struct tcmu_cmd_entry, req.iov[iov_cnt]),
876 			sizeof(struct tcmu_cmd_entry));
877 }
878 
879 static inline size_t tcmu_cmd_get_cmd_size(struct tcmu_cmd *tcmu_cmd,
880 					   size_t base_command_size)
881 {
882 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
883 	size_t command_size;
884 
885 	command_size = base_command_size +
886 		round_up(scsi_command_size(se_cmd->t_task_cdb),
887 				TCMU_OP_ALIGN_SIZE);
888 
889 	WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
890 
891 	return command_size;
892 }
893 
894 static int tcmu_setup_cmd_timer(struct tcmu_cmd *tcmu_cmd, unsigned int tmo,
895 				struct timer_list *timer)
896 {
897 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
898 	int cmd_id;
899 
900 	if (tcmu_cmd->cmd_id)
901 		goto setup_timer;
902 
903 	cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 1, USHRT_MAX, GFP_NOWAIT);
904 	if (cmd_id < 0) {
905 		pr_err("tcmu: Could not allocate cmd id.\n");
906 		return cmd_id;
907 	}
908 	tcmu_cmd->cmd_id = cmd_id;
909 
910 	pr_debug("allocated cmd %u for dev %s tmo %lu\n", tcmu_cmd->cmd_id,
911 		 udev->name, tmo / MSEC_PER_SEC);
912 
913 setup_timer:
914 	if (!tmo)
915 		return 0;
916 
917 	tcmu_cmd->deadline = round_jiffies_up(jiffies + msecs_to_jiffies(tmo));
918 	mod_timer(timer, tcmu_cmd->deadline);
919 	return 0;
920 }
921 
922 static int add_to_cmdr_queue(struct tcmu_cmd *tcmu_cmd)
923 {
924 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
925 	unsigned int tmo;
926 	int ret;
927 
928 	/*
929 	 * For backwards compat if qfull_time_out is not set use
930 	 * cmd_time_out and if that's not set use the default time out.
931 	 */
932 	if (!udev->qfull_time_out)
933 		return -ETIMEDOUT;
934 	else if (udev->qfull_time_out > 0)
935 		tmo = udev->qfull_time_out;
936 	else if (udev->cmd_time_out)
937 		tmo = udev->cmd_time_out;
938 	else
939 		tmo = TCMU_TIME_OUT;
940 
941 	ret = tcmu_setup_cmd_timer(tcmu_cmd, tmo, &udev->qfull_timer);
942 	if (ret)
943 		return ret;
944 
945 	list_add_tail(&tcmu_cmd->cmdr_queue_entry, &udev->cmdr_queue);
946 	pr_debug("adding cmd %u on dev %s to ring space wait queue\n",
947 		 tcmu_cmd->cmd_id, udev->name);
948 	return 0;
949 }
950 
951 /**
952  * queue_cmd_ring - queue cmd to ring or internally
953  * @tcmu_cmd: cmd to queue
954  * @scsi_err: TCM error code if failure (-1) returned.
955  *
956  * Returns:
957  * -1 we cannot queue internally or to the ring.
958  *  0 success
959  *  1 internally queued to wait for ring memory to free.
960  */
961 static sense_reason_t queue_cmd_ring(struct tcmu_cmd *tcmu_cmd, int *scsi_err)
962 {
963 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
964 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
965 	size_t base_command_size, command_size;
966 	struct tcmu_mailbox *mb;
967 	struct tcmu_cmd_entry *entry;
968 	struct iovec *iov;
969 	int iov_cnt, ret;
970 	uint32_t cmd_head;
971 	uint64_t cdb_off;
972 	bool copy_to_data_area;
973 	size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
974 
975 	*scsi_err = TCM_NO_SENSE;
976 
977 	if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags)) {
978 		*scsi_err = TCM_LUN_BUSY;
979 		return -1;
980 	}
981 
982 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
983 		*scsi_err = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
984 		return -1;
985 	}
986 
987 	/*
988 	 * Must be a certain minimum size for response sense info, but
989 	 * also may be larger if the iov array is large.
990 	 *
991 	 * We prepare as many iovs as possbile for potential uses here,
992 	 * because it's expensive to tell how many regions are freed in
993 	 * the bitmap & global data pool, as the size calculated here
994 	 * will only be used to do the checks.
995 	 *
996 	 * The size will be recalculated later as actually needed to save
997 	 * cmd area memories.
998 	 */
999 	base_command_size = tcmu_cmd_get_base_cmd_size(tcmu_cmd->dbi_cnt);
1000 	command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
1001 
1002 	if (!list_empty(&udev->cmdr_queue))
1003 		goto queue;
1004 
1005 	mb = udev->mb_addr;
1006 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
1007 	if ((command_size > (udev->cmdr_size / 2)) ||
1008 	    data_length > udev->data_size) {
1009 		pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
1010 			"cmd ring/data area\n", command_size, data_length,
1011 			udev->cmdr_size, udev->data_size);
1012 		*scsi_err = TCM_INVALID_CDB_FIELD;
1013 		return -1;
1014 	}
1015 
1016 	if (!is_ring_space_avail(udev, tcmu_cmd, command_size, data_length)) {
1017 		/*
1018 		 * Don't leave commands partially setup because the unmap
1019 		 * thread might need the blocks to make forward progress.
1020 		 */
1021 		tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
1022 		tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1023 		goto queue;
1024 	}
1025 
1026 	/* Insert a PAD if end-of-ring space is too small */
1027 	if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
1028 		size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
1029 
1030 		entry = (void *) mb + CMDR_OFF + cmd_head;
1031 		tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
1032 		tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
1033 		entry->hdr.cmd_id = 0; /* not used for PAD */
1034 		entry->hdr.kflags = 0;
1035 		entry->hdr.uflags = 0;
1036 		tcmu_flush_dcache_range(entry, sizeof(*entry));
1037 
1038 		UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
1039 		tcmu_flush_dcache_range(mb, sizeof(*mb));
1040 
1041 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
1042 		WARN_ON(cmd_head != 0);
1043 	}
1044 
1045 	entry = (void *) mb + CMDR_OFF + cmd_head;
1046 	memset(entry, 0, command_size);
1047 	tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
1048 
1049 	/* Handle allocating space from the data area */
1050 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1051 	iov = &entry->req.iov[0];
1052 	iov_cnt = 0;
1053 	copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
1054 		|| se_cmd->se_cmd_flags & SCF_BIDI);
1055 	scatter_data_area(udev, tcmu_cmd, se_cmd->t_data_sg,
1056 			  se_cmd->t_data_nents, &iov, &iov_cnt,
1057 			  copy_to_data_area);
1058 	entry->req.iov_cnt = iov_cnt;
1059 
1060 	/* Handle BIDI commands */
1061 	iov_cnt = 0;
1062 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
1063 		iov++;
1064 		scatter_data_area(udev, tcmu_cmd, se_cmd->t_bidi_data_sg,
1065 				  se_cmd->t_bidi_data_nents, &iov, &iov_cnt,
1066 				  false);
1067 	}
1068 	entry->req.iov_bidi_cnt = iov_cnt;
1069 
1070 	ret = tcmu_setup_cmd_timer(tcmu_cmd, udev->cmd_time_out,
1071 				   &udev->cmd_timer);
1072 	if (ret) {
1073 		tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
1074 
1075 		*scsi_err = TCM_OUT_OF_RESOURCES;
1076 		return -1;
1077 	}
1078 	entry->hdr.cmd_id = tcmu_cmd->cmd_id;
1079 
1080 	/*
1081 	 * Recalaulate the command's base size and size according
1082 	 * to the actual needs
1083 	 */
1084 	base_command_size = tcmu_cmd_get_base_cmd_size(entry->req.iov_cnt +
1085 						       entry->req.iov_bidi_cnt);
1086 	command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
1087 
1088 	tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
1089 
1090 	/* All offsets relative to mb_addr, not start of entry! */
1091 	cdb_off = CMDR_OFF + cmd_head + base_command_size;
1092 	memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
1093 	entry->req.cdb_off = cdb_off;
1094 	tcmu_flush_dcache_range(entry, sizeof(*entry));
1095 
1096 	UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
1097 	tcmu_flush_dcache_range(mb, sizeof(*mb));
1098 
1099 	/* TODO: only if FLUSH and FUA? */
1100 	uio_event_notify(&udev->uio_info);
1101 
1102 	return 0;
1103 
1104 queue:
1105 	if (add_to_cmdr_queue(tcmu_cmd)) {
1106 		*scsi_err = TCM_OUT_OF_RESOURCES;
1107 		return -1;
1108 	}
1109 
1110 	return 1;
1111 }
1112 
1113 static sense_reason_t
1114 tcmu_queue_cmd(struct se_cmd *se_cmd)
1115 {
1116 	struct se_device *se_dev = se_cmd->se_dev;
1117 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
1118 	struct tcmu_cmd *tcmu_cmd;
1119 	sense_reason_t scsi_ret;
1120 	int ret;
1121 
1122 	tcmu_cmd = tcmu_alloc_cmd(se_cmd);
1123 	if (!tcmu_cmd)
1124 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1125 
1126 	mutex_lock(&udev->cmdr_lock);
1127 	ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1128 	mutex_unlock(&udev->cmdr_lock);
1129 	if (ret < 0)
1130 		tcmu_free_cmd(tcmu_cmd);
1131 	return scsi_ret;
1132 }
1133 
1134 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
1135 {
1136 	struct se_cmd *se_cmd = cmd->se_cmd;
1137 	struct tcmu_dev *udev = cmd->tcmu_dev;
1138 	bool read_len_valid = false;
1139 	uint32_t read_len = se_cmd->data_length;
1140 
1141 	/*
1142 	 * cmd has been completed already from timeout, just reclaim
1143 	 * data area space and free cmd
1144 	 */
1145 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
1146 		goto out;
1147 
1148 	tcmu_cmd_reset_dbi_cur(cmd);
1149 
1150 	if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
1151 		pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
1152 			cmd->se_cmd);
1153 		entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
1154 		goto done;
1155 	}
1156 
1157 	if (se_cmd->data_direction == DMA_FROM_DEVICE &&
1158 	    (entry->hdr.uflags & TCMU_UFLAG_READ_LEN) && entry->rsp.read_len) {
1159 		read_len_valid = true;
1160 		if (entry->rsp.read_len < read_len)
1161 			read_len = entry->rsp.read_len;
1162 	}
1163 
1164 	if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
1165 		transport_copy_sense_to_cmd(se_cmd, entry->rsp.sense_buffer);
1166 		if (!read_len_valid )
1167 			goto done;
1168 		else
1169 			se_cmd->se_cmd_flags |= SCF_TREAT_READ_AS_NORMAL;
1170 	}
1171 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
1172 		/* Get Data-In buffer before clean up */
1173 		gather_data_area(udev, cmd, true, read_len);
1174 	} else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
1175 		gather_data_area(udev, cmd, false, read_len);
1176 	} else if (se_cmd->data_direction == DMA_TO_DEVICE) {
1177 		/* TODO: */
1178 	} else if (se_cmd->data_direction != DMA_NONE) {
1179 		pr_warn("TCMU: data direction was %d!\n",
1180 			se_cmd->data_direction);
1181 	}
1182 
1183 done:
1184 	if (read_len_valid) {
1185 		pr_debug("read_len = %d\n", read_len);
1186 		target_complete_cmd_with_length(cmd->se_cmd,
1187 					entry->rsp.scsi_status, read_len);
1188 	} else
1189 		target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
1190 
1191 out:
1192 	cmd->se_cmd = NULL;
1193 	tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
1194 	tcmu_free_cmd(cmd);
1195 }
1196 
1197 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
1198 {
1199 	struct tcmu_mailbox *mb;
1200 	int handled = 0;
1201 
1202 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
1203 		pr_err("ring broken, not handling completions\n");
1204 		return 0;
1205 	}
1206 
1207 	mb = udev->mb_addr;
1208 	tcmu_flush_dcache_range(mb, sizeof(*mb));
1209 
1210 	while (udev->cmdr_last_cleaned != READ_ONCE(mb->cmd_tail)) {
1211 
1212 		struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
1213 		struct tcmu_cmd *cmd;
1214 
1215 		tcmu_flush_dcache_range(entry, sizeof(*entry));
1216 
1217 		if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
1218 			UPDATE_HEAD(udev->cmdr_last_cleaned,
1219 				    tcmu_hdr_get_len(entry->hdr.len_op),
1220 				    udev->cmdr_size);
1221 			continue;
1222 		}
1223 		WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
1224 
1225 		cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
1226 		if (!cmd) {
1227 			pr_err("cmd_id %u not found, ring is broken\n",
1228 			       entry->hdr.cmd_id);
1229 			set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
1230 			break;
1231 		}
1232 
1233 		tcmu_handle_completion(cmd, entry);
1234 
1235 		UPDATE_HEAD(udev->cmdr_last_cleaned,
1236 			    tcmu_hdr_get_len(entry->hdr.len_op),
1237 			    udev->cmdr_size);
1238 
1239 		handled++;
1240 	}
1241 
1242 	if (mb->cmd_tail == mb->cmd_head) {
1243 		/* no more pending commands */
1244 		del_timer(&udev->cmd_timer);
1245 
1246 		if (list_empty(&udev->cmdr_queue)) {
1247 			/*
1248 			 * no more pending or waiting commands so try to
1249 			 * reclaim blocks if needed.
1250 			 */
1251 			if (atomic_read(&global_db_count) >
1252 			    tcmu_global_max_blocks)
1253 				schedule_delayed_work(&tcmu_unmap_work, 0);
1254 		}
1255 	}
1256 
1257 	return handled;
1258 }
1259 
1260 static int tcmu_check_expired_cmd(int id, void *p, void *data)
1261 {
1262 	struct tcmu_cmd *cmd = p;
1263 	struct tcmu_dev *udev = cmd->tcmu_dev;
1264 	u8 scsi_status;
1265 	struct se_cmd *se_cmd;
1266 	bool is_running;
1267 
1268 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
1269 		return 0;
1270 
1271 	if (!time_after(jiffies, cmd->deadline))
1272 		return 0;
1273 
1274 	is_running = list_empty(&cmd->cmdr_queue_entry);
1275 	se_cmd = cmd->se_cmd;
1276 
1277 	if (is_running) {
1278 		/*
1279 		 * If cmd_time_out is disabled but qfull is set deadline
1280 		 * will only reflect the qfull timeout. Ignore it.
1281 		 */
1282 		if (!udev->cmd_time_out)
1283 			return 0;
1284 
1285 		set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
1286 		/*
1287 		 * target_complete_cmd will translate this to LUN COMM FAILURE
1288 		 */
1289 		scsi_status = SAM_STAT_CHECK_CONDITION;
1290 	} else {
1291 		list_del_init(&cmd->cmdr_queue_entry);
1292 
1293 		idr_remove(&udev->commands, id);
1294 		tcmu_free_cmd(cmd);
1295 		scsi_status = SAM_STAT_TASK_SET_FULL;
1296 	}
1297 
1298 	pr_debug("Timing out cmd %u on dev %s that is %s.\n",
1299 		 id, udev->name, is_running ? "inflight" : "queued");
1300 
1301 	target_complete_cmd(se_cmd, scsi_status);
1302 	return 0;
1303 }
1304 
1305 static void tcmu_device_timedout(struct tcmu_dev *udev)
1306 {
1307 	spin_lock(&timed_out_udevs_lock);
1308 	if (list_empty(&udev->timedout_entry))
1309 		list_add_tail(&udev->timedout_entry, &timed_out_udevs);
1310 	spin_unlock(&timed_out_udevs_lock);
1311 
1312 	schedule_delayed_work(&tcmu_unmap_work, 0);
1313 }
1314 
1315 static void tcmu_cmd_timedout(struct timer_list *t)
1316 {
1317 	struct tcmu_dev *udev = from_timer(udev, t, cmd_timer);
1318 
1319 	pr_debug("%s cmd timeout has expired\n", udev->name);
1320 	tcmu_device_timedout(udev);
1321 }
1322 
1323 static void tcmu_qfull_timedout(struct timer_list *t)
1324 {
1325 	struct tcmu_dev *udev = from_timer(udev, t, qfull_timer);
1326 
1327 	pr_debug("%s qfull timeout has expired\n", udev->name);
1328 	tcmu_device_timedout(udev);
1329 }
1330 
1331 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
1332 {
1333 	struct tcmu_hba *tcmu_hba;
1334 
1335 	tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
1336 	if (!tcmu_hba)
1337 		return -ENOMEM;
1338 
1339 	tcmu_hba->host_id = host_id;
1340 	hba->hba_ptr = tcmu_hba;
1341 
1342 	return 0;
1343 }
1344 
1345 static void tcmu_detach_hba(struct se_hba *hba)
1346 {
1347 	kfree(hba->hba_ptr);
1348 	hba->hba_ptr = NULL;
1349 }
1350 
1351 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
1352 {
1353 	struct tcmu_dev *udev;
1354 
1355 	udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
1356 	if (!udev)
1357 		return NULL;
1358 	kref_init(&udev->kref);
1359 
1360 	udev->name = kstrdup(name, GFP_KERNEL);
1361 	if (!udev->name) {
1362 		kfree(udev);
1363 		return NULL;
1364 	}
1365 
1366 	udev->hba = hba;
1367 	udev->cmd_time_out = TCMU_TIME_OUT;
1368 	udev->qfull_time_out = -1;
1369 
1370 	udev->max_blocks = DATA_BLOCK_BITS_DEF;
1371 	mutex_init(&udev->cmdr_lock);
1372 
1373 	INIT_LIST_HEAD(&udev->node);
1374 	INIT_LIST_HEAD(&udev->timedout_entry);
1375 	INIT_LIST_HEAD(&udev->cmdr_queue);
1376 	idr_init(&udev->commands);
1377 
1378 	timer_setup(&udev->qfull_timer, tcmu_qfull_timedout, 0);
1379 	timer_setup(&udev->cmd_timer, tcmu_cmd_timedout, 0);
1380 
1381 	INIT_RADIX_TREE(&udev->data_blocks, GFP_KERNEL);
1382 
1383 	return &udev->se_dev;
1384 }
1385 
1386 static bool run_cmdr_queue(struct tcmu_dev *udev, bool fail)
1387 {
1388 	struct tcmu_cmd *tcmu_cmd, *tmp_cmd;
1389 	LIST_HEAD(cmds);
1390 	bool drained = true;
1391 	sense_reason_t scsi_ret;
1392 	int ret;
1393 
1394 	if (list_empty(&udev->cmdr_queue))
1395 		return true;
1396 
1397 	pr_debug("running %s's cmdr queue forcefail %d\n", udev->name, fail);
1398 
1399 	list_splice_init(&udev->cmdr_queue, &cmds);
1400 
1401 	list_for_each_entry_safe(tcmu_cmd, tmp_cmd, &cmds, cmdr_queue_entry) {
1402 		list_del_init(&tcmu_cmd->cmdr_queue_entry);
1403 
1404 	        pr_debug("removing cmd %u on dev %s from queue\n",
1405 		         tcmu_cmd->cmd_id, udev->name);
1406 
1407 		if (fail) {
1408 			idr_remove(&udev->commands, tcmu_cmd->cmd_id);
1409 			/*
1410 			 * We were not able to even start the command, so
1411 			 * fail with busy to allow a retry in case runner
1412 			 * was only temporarily down. If the device is being
1413 			 * removed then LIO core will do the right thing and
1414 			 * fail the retry.
1415 			 */
1416 			target_complete_cmd(tcmu_cmd->se_cmd, SAM_STAT_BUSY);
1417 			tcmu_free_cmd(tcmu_cmd);
1418 			continue;
1419 		}
1420 
1421 		ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1422 		if (ret < 0) {
1423 		        pr_debug("cmd %u on dev %s failed with %u\n",
1424 			         tcmu_cmd->cmd_id, udev->name, scsi_ret);
1425 
1426 			idr_remove(&udev->commands, tcmu_cmd->cmd_id);
1427 			/*
1428 			 * Ignore scsi_ret for now. target_complete_cmd
1429 			 * drops it.
1430 			 */
1431 			target_complete_cmd(tcmu_cmd->se_cmd,
1432 					    SAM_STAT_CHECK_CONDITION);
1433 			tcmu_free_cmd(tcmu_cmd);
1434 		} else if (ret > 0) {
1435 			pr_debug("ran out of space during cmdr queue run\n");
1436 			/*
1437 			 * cmd was requeued, so just put all cmds back in
1438 			 * the queue
1439 			 */
1440 			list_splice_tail(&cmds, &udev->cmdr_queue);
1441 			drained = false;
1442 			goto done;
1443 		}
1444 	}
1445 	if (list_empty(&udev->cmdr_queue))
1446 		del_timer(&udev->qfull_timer);
1447 done:
1448 	return drained;
1449 }
1450 
1451 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
1452 {
1453 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1454 
1455 	mutex_lock(&udev->cmdr_lock);
1456 	tcmu_handle_completions(udev);
1457 	run_cmdr_queue(udev, false);
1458 	mutex_unlock(&udev->cmdr_lock);
1459 
1460 	return 0;
1461 }
1462 
1463 /*
1464  * mmap code from uio.c. Copied here because we want to hook mmap()
1465  * and this stuff must come along.
1466  */
1467 static int tcmu_find_mem_index(struct vm_area_struct *vma)
1468 {
1469 	struct tcmu_dev *udev = vma->vm_private_data;
1470 	struct uio_info *info = &udev->uio_info;
1471 
1472 	if (vma->vm_pgoff < MAX_UIO_MAPS) {
1473 		if (info->mem[vma->vm_pgoff].size == 0)
1474 			return -1;
1475 		return (int)vma->vm_pgoff;
1476 	}
1477 	return -1;
1478 }
1479 
1480 static struct page *tcmu_try_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
1481 {
1482 	struct page *page;
1483 
1484 	mutex_lock(&udev->cmdr_lock);
1485 	page = tcmu_get_block_page(udev, dbi);
1486 	if (likely(page)) {
1487 		mutex_unlock(&udev->cmdr_lock);
1488 		return page;
1489 	}
1490 
1491 	/*
1492 	 * Userspace messed up and passed in a address not in the
1493 	 * data iov passed to it.
1494 	 */
1495 	pr_err("Invalid addr to data block mapping  (dbi %u) on device %s\n",
1496 	       dbi, udev->name);
1497 	page = NULL;
1498 	mutex_unlock(&udev->cmdr_lock);
1499 
1500 	return page;
1501 }
1502 
1503 static vm_fault_t tcmu_vma_fault(struct vm_fault *vmf)
1504 {
1505 	struct tcmu_dev *udev = vmf->vma->vm_private_data;
1506 	struct uio_info *info = &udev->uio_info;
1507 	struct page *page;
1508 	unsigned long offset;
1509 	void *addr;
1510 
1511 	int mi = tcmu_find_mem_index(vmf->vma);
1512 	if (mi < 0)
1513 		return VM_FAULT_SIGBUS;
1514 
1515 	/*
1516 	 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
1517 	 * to use mem[N].
1518 	 */
1519 	offset = (vmf->pgoff - mi) << PAGE_SHIFT;
1520 
1521 	if (offset < udev->data_off) {
1522 		/* For the vmalloc()ed cmd area pages */
1523 		addr = (void *)(unsigned long)info->mem[mi].addr + offset;
1524 		page = vmalloc_to_page(addr);
1525 	} else {
1526 		uint32_t dbi;
1527 
1528 		/* For the dynamically growing data area pages */
1529 		dbi = (offset - udev->data_off) / DATA_BLOCK_SIZE;
1530 		page = tcmu_try_get_block_page(udev, dbi);
1531 		if (!page)
1532 			return VM_FAULT_SIGBUS;
1533 	}
1534 
1535 	get_page(page);
1536 	vmf->page = page;
1537 	return 0;
1538 }
1539 
1540 static const struct vm_operations_struct tcmu_vm_ops = {
1541 	.fault = tcmu_vma_fault,
1542 };
1543 
1544 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
1545 {
1546 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1547 
1548 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1549 	vma->vm_ops = &tcmu_vm_ops;
1550 
1551 	vma->vm_private_data = udev;
1552 
1553 	/* Ensure the mmap is exactly the right size */
1554 	if (vma_pages(vma) != (udev->ring_size >> PAGE_SHIFT))
1555 		return -EINVAL;
1556 
1557 	return 0;
1558 }
1559 
1560 static int tcmu_open(struct uio_info *info, struct inode *inode)
1561 {
1562 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1563 
1564 	/* O_EXCL not supported for char devs, so fake it? */
1565 	if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
1566 		return -EBUSY;
1567 
1568 	udev->inode = inode;
1569 	kref_get(&udev->kref);
1570 
1571 	pr_debug("open\n");
1572 
1573 	return 0;
1574 }
1575 
1576 static void tcmu_dev_call_rcu(struct rcu_head *p)
1577 {
1578 	struct se_device *dev = container_of(p, struct se_device, rcu_head);
1579 	struct tcmu_dev *udev = TCMU_DEV(dev);
1580 
1581 	kfree(udev->uio_info.name);
1582 	kfree(udev->name);
1583 	kfree(udev);
1584 }
1585 
1586 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1587 {
1588 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1589 		kmem_cache_free(tcmu_cmd_cache, cmd);
1590 		return 0;
1591 	}
1592 	return -EINVAL;
1593 }
1594 
1595 static void tcmu_blocks_release(struct radix_tree_root *blocks,
1596 				int start, int end)
1597 {
1598 	int i;
1599 	struct page *page;
1600 
1601 	for (i = start; i < end; i++) {
1602 		page = radix_tree_delete(blocks, i);
1603 		if (page) {
1604 			__free_page(page);
1605 			atomic_dec(&global_db_count);
1606 		}
1607 	}
1608 }
1609 
1610 static void tcmu_dev_kref_release(struct kref *kref)
1611 {
1612 	struct tcmu_dev *udev = container_of(kref, struct tcmu_dev, kref);
1613 	struct se_device *dev = &udev->se_dev;
1614 	struct tcmu_cmd *cmd;
1615 	bool all_expired = true;
1616 	int i;
1617 
1618 	vfree(udev->mb_addr);
1619 	udev->mb_addr = NULL;
1620 
1621 	spin_lock_bh(&timed_out_udevs_lock);
1622 	if (!list_empty(&udev->timedout_entry))
1623 		list_del(&udev->timedout_entry);
1624 	spin_unlock_bh(&timed_out_udevs_lock);
1625 
1626 	/* Upper layer should drain all requests before calling this */
1627 	mutex_lock(&udev->cmdr_lock);
1628 	idr_for_each_entry(&udev->commands, cmd, i) {
1629 		if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1630 			all_expired = false;
1631 	}
1632 	idr_destroy(&udev->commands);
1633 	WARN_ON(!all_expired);
1634 
1635 	tcmu_blocks_release(&udev->data_blocks, 0, udev->dbi_max + 1);
1636 	kfree(udev->data_bitmap);
1637 	mutex_unlock(&udev->cmdr_lock);
1638 
1639 	call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1640 }
1641 
1642 static int tcmu_release(struct uio_info *info, struct inode *inode)
1643 {
1644 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1645 
1646 	clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
1647 
1648 	pr_debug("close\n");
1649 	/* release ref from open */
1650 	kref_put(&udev->kref, tcmu_dev_kref_release);
1651 	return 0;
1652 }
1653 
1654 static int tcmu_init_genl_cmd_reply(struct tcmu_dev *udev, int cmd)
1655 {
1656 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1657 
1658 	if (!tcmu_kern_cmd_reply_supported)
1659 		return 0;
1660 
1661 	if (udev->nl_reply_supported <= 0)
1662 		return 0;
1663 
1664 	mutex_lock(&tcmu_nl_cmd_mutex);
1665 
1666 	if (tcmu_netlink_blocked) {
1667 		mutex_unlock(&tcmu_nl_cmd_mutex);
1668 		pr_warn("Failing nl cmd %d on %s. Interface is blocked.\n", cmd,
1669 			udev->name);
1670 		return -EAGAIN;
1671 	}
1672 
1673 	if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
1674 		mutex_unlock(&tcmu_nl_cmd_mutex);
1675 		pr_warn("netlink cmd %d already executing on %s\n",
1676 			 nl_cmd->cmd, udev->name);
1677 		return -EBUSY;
1678 	}
1679 
1680 	memset(nl_cmd, 0, sizeof(*nl_cmd));
1681 	nl_cmd->cmd = cmd;
1682 	nl_cmd->udev = udev;
1683 	init_completion(&nl_cmd->complete);
1684 	INIT_LIST_HEAD(&nl_cmd->nl_list);
1685 
1686 	list_add_tail(&nl_cmd->nl_list, &tcmu_nl_cmd_list);
1687 
1688 	mutex_unlock(&tcmu_nl_cmd_mutex);
1689 	return 0;
1690 }
1691 
1692 static int tcmu_wait_genl_cmd_reply(struct tcmu_dev *udev)
1693 {
1694 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1695 	int ret;
1696 
1697 	if (!tcmu_kern_cmd_reply_supported)
1698 		return 0;
1699 
1700 	if (udev->nl_reply_supported <= 0)
1701 		return 0;
1702 
1703 	pr_debug("sleeping for nl reply\n");
1704 	wait_for_completion(&nl_cmd->complete);
1705 
1706 	mutex_lock(&tcmu_nl_cmd_mutex);
1707 	nl_cmd->cmd = TCMU_CMD_UNSPEC;
1708 	ret = nl_cmd->status;
1709 	mutex_unlock(&tcmu_nl_cmd_mutex);
1710 
1711 	return ret;
1712 }
1713 
1714 static int tcmu_netlink_event_init(struct tcmu_dev *udev,
1715 				   enum tcmu_genl_cmd cmd,
1716 				   struct sk_buff **buf, void **hdr)
1717 {
1718 	struct sk_buff *skb;
1719 	void *msg_header;
1720 	int ret = -ENOMEM;
1721 
1722 	skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1723 	if (!skb)
1724 		return ret;
1725 
1726 	msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
1727 	if (!msg_header)
1728 		goto free_skb;
1729 
1730 	ret = nla_put_string(skb, TCMU_ATTR_DEVICE, udev->uio_info.name);
1731 	if (ret < 0)
1732 		goto free_skb;
1733 
1734 	ret = nla_put_u32(skb, TCMU_ATTR_MINOR, udev->uio_info.uio_dev->minor);
1735 	if (ret < 0)
1736 		goto free_skb;
1737 
1738 	ret = nla_put_u32(skb, TCMU_ATTR_DEVICE_ID, udev->se_dev.dev_index);
1739 	if (ret < 0)
1740 		goto free_skb;
1741 
1742 	*buf = skb;
1743 	*hdr = msg_header;
1744 	return ret;
1745 
1746 free_skb:
1747 	nlmsg_free(skb);
1748 	return ret;
1749 }
1750 
1751 static int tcmu_netlink_event_send(struct tcmu_dev *udev,
1752 				   enum tcmu_genl_cmd cmd,
1753 				   struct sk_buff *skb, void *msg_header)
1754 {
1755 	int ret;
1756 
1757 	genlmsg_end(skb, msg_header);
1758 
1759 	ret = tcmu_init_genl_cmd_reply(udev, cmd);
1760 	if (ret) {
1761 		nlmsg_free(skb);
1762 		return ret;
1763 	}
1764 
1765 	ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
1766 				      TCMU_MCGRP_CONFIG, GFP_KERNEL);
1767 	/* We don't care if no one is listening */
1768 	if (ret == -ESRCH)
1769 		ret = 0;
1770 	if (!ret)
1771 		ret = tcmu_wait_genl_cmd_reply(udev);
1772 	return ret;
1773 }
1774 
1775 static int tcmu_send_dev_add_event(struct tcmu_dev *udev)
1776 {
1777 	struct sk_buff *skb = NULL;
1778 	void *msg_header = NULL;
1779 	int ret = 0;
1780 
1781 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_ADDED_DEVICE, &skb,
1782 				      &msg_header);
1783 	if (ret < 0)
1784 		return ret;
1785 	return tcmu_netlink_event_send(udev, TCMU_CMD_ADDED_DEVICE, skb,
1786 				       msg_header);
1787 }
1788 
1789 static int tcmu_send_dev_remove_event(struct tcmu_dev *udev)
1790 {
1791 	struct sk_buff *skb = NULL;
1792 	void *msg_header = NULL;
1793 	int ret = 0;
1794 
1795 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_REMOVED_DEVICE,
1796 				      &skb, &msg_header);
1797 	if (ret < 0)
1798 		return ret;
1799 	return tcmu_netlink_event_send(udev, TCMU_CMD_REMOVED_DEVICE,
1800 				       skb, msg_header);
1801 }
1802 
1803 static int tcmu_update_uio_info(struct tcmu_dev *udev)
1804 {
1805 	struct tcmu_hba *hba = udev->hba->hba_ptr;
1806 	struct uio_info *info;
1807 	size_t size, used;
1808 	char *str;
1809 
1810 	info = &udev->uio_info;
1811 	size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
1812 			udev->dev_config);
1813 	size += 1; /* for \0 */
1814 	str = kmalloc(size, GFP_KERNEL);
1815 	if (!str)
1816 		return -ENOMEM;
1817 
1818 	used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
1819 	if (udev->dev_config[0])
1820 		snprintf(str + used, size - used, "/%s", udev->dev_config);
1821 
1822 	/* If the old string exists, free it */
1823 	kfree(info->name);
1824 	info->name = str;
1825 
1826 	return 0;
1827 }
1828 
1829 static int tcmu_configure_device(struct se_device *dev)
1830 {
1831 	struct tcmu_dev *udev = TCMU_DEV(dev);
1832 	struct uio_info *info;
1833 	struct tcmu_mailbox *mb;
1834 	int ret = 0;
1835 
1836 	ret = tcmu_update_uio_info(udev);
1837 	if (ret)
1838 		return ret;
1839 
1840 	info = &udev->uio_info;
1841 
1842 	mutex_lock(&udev->cmdr_lock);
1843 	udev->data_bitmap = kcalloc(BITS_TO_LONGS(udev->max_blocks),
1844 				    sizeof(unsigned long),
1845 				    GFP_KERNEL);
1846 	mutex_unlock(&udev->cmdr_lock);
1847 	if (!udev->data_bitmap) {
1848 		ret = -ENOMEM;
1849 		goto err_bitmap_alloc;
1850 	}
1851 
1852 	udev->mb_addr = vzalloc(CMDR_SIZE);
1853 	if (!udev->mb_addr) {
1854 		ret = -ENOMEM;
1855 		goto err_vzalloc;
1856 	}
1857 
1858 	/* mailbox fits in first part of CMDR space */
1859 	udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
1860 	udev->data_off = CMDR_SIZE;
1861 	udev->data_size = udev->max_blocks * DATA_BLOCK_SIZE;
1862 	udev->dbi_thresh = 0; /* Default in Idle state */
1863 
1864 	/* Initialise the mailbox of the ring buffer */
1865 	mb = udev->mb_addr;
1866 	mb->version = TCMU_MAILBOX_VERSION;
1867 	mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC | TCMU_MAILBOX_FLAG_CAP_READ_LEN;
1868 	mb->cmdr_off = CMDR_OFF;
1869 	mb->cmdr_size = udev->cmdr_size;
1870 
1871 	WARN_ON(!PAGE_ALIGNED(udev->data_off));
1872 	WARN_ON(udev->data_size % PAGE_SIZE);
1873 	WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
1874 
1875 	info->version = __stringify(TCMU_MAILBOX_VERSION);
1876 
1877 	info->mem[0].name = "tcm-user command & data buffer";
1878 	info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
1879 	info->mem[0].size = udev->ring_size = udev->data_size + CMDR_SIZE;
1880 	info->mem[0].memtype = UIO_MEM_NONE;
1881 
1882 	info->irqcontrol = tcmu_irqcontrol;
1883 	info->irq = UIO_IRQ_CUSTOM;
1884 
1885 	info->mmap = tcmu_mmap;
1886 	info->open = tcmu_open;
1887 	info->release = tcmu_release;
1888 
1889 	ret = uio_register_device(tcmu_root_device, info);
1890 	if (ret)
1891 		goto err_register;
1892 
1893 	/* User can set hw_block_size before enable the device */
1894 	if (dev->dev_attrib.hw_block_size == 0)
1895 		dev->dev_attrib.hw_block_size = 512;
1896 	/* Other attributes can be configured in userspace */
1897 	if (!dev->dev_attrib.hw_max_sectors)
1898 		dev->dev_attrib.hw_max_sectors = 128;
1899 	if (!dev->dev_attrib.emulate_write_cache)
1900 		dev->dev_attrib.emulate_write_cache = 0;
1901 	dev->dev_attrib.hw_queue_depth = 128;
1902 
1903 	/* If user didn't explicitly disable netlink reply support, use
1904 	 * module scope setting.
1905 	 */
1906 	if (udev->nl_reply_supported >= 0)
1907 		udev->nl_reply_supported = tcmu_kern_cmd_reply_supported;
1908 
1909 	/*
1910 	 * Get a ref incase userspace does a close on the uio device before
1911 	 * LIO has initiated tcmu_free_device.
1912 	 */
1913 	kref_get(&udev->kref);
1914 
1915 	ret = tcmu_send_dev_add_event(udev);
1916 	if (ret)
1917 		goto err_netlink;
1918 
1919 	mutex_lock(&root_udev_mutex);
1920 	list_add(&udev->node, &root_udev);
1921 	mutex_unlock(&root_udev_mutex);
1922 
1923 	return 0;
1924 
1925 err_netlink:
1926 	kref_put(&udev->kref, tcmu_dev_kref_release);
1927 	uio_unregister_device(&udev->uio_info);
1928 err_register:
1929 	vfree(udev->mb_addr);
1930 	udev->mb_addr = NULL;
1931 err_vzalloc:
1932 	kfree(udev->data_bitmap);
1933 	udev->data_bitmap = NULL;
1934 err_bitmap_alloc:
1935 	kfree(info->name);
1936 	info->name = NULL;
1937 
1938 	return ret;
1939 }
1940 
1941 static void tcmu_free_device(struct se_device *dev)
1942 {
1943 	struct tcmu_dev *udev = TCMU_DEV(dev);
1944 
1945 	/* release ref from init */
1946 	kref_put(&udev->kref, tcmu_dev_kref_release);
1947 }
1948 
1949 static void tcmu_destroy_device(struct se_device *dev)
1950 {
1951 	struct tcmu_dev *udev = TCMU_DEV(dev);
1952 
1953 	del_timer_sync(&udev->cmd_timer);
1954 	del_timer_sync(&udev->qfull_timer);
1955 
1956 	mutex_lock(&root_udev_mutex);
1957 	list_del(&udev->node);
1958 	mutex_unlock(&root_udev_mutex);
1959 
1960 	tcmu_send_dev_remove_event(udev);
1961 
1962 	uio_unregister_device(&udev->uio_info);
1963 
1964 	/* release ref from configure */
1965 	kref_put(&udev->kref, tcmu_dev_kref_release);
1966 }
1967 
1968 static void tcmu_unblock_dev(struct tcmu_dev *udev)
1969 {
1970 	mutex_lock(&udev->cmdr_lock);
1971 	clear_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags);
1972 	mutex_unlock(&udev->cmdr_lock);
1973 }
1974 
1975 static void tcmu_block_dev(struct tcmu_dev *udev)
1976 {
1977 	mutex_lock(&udev->cmdr_lock);
1978 
1979 	if (test_and_set_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
1980 		goto unlock;
1981 
1982 	/* complete IO that has executed successfully */
1983 	tcmu_handle_completions(udev);
1984 	/* fail IO waiting to be queued */
1985 	run_cmdr_queue(udev, true);
1986 
1987 unlock:
1988 	mutex_unlock(&udev->cmdr_lock);
1989 }
1990 
1991 static void tcmu_reset_ring(struct tcmu_dev *udev, u8 err_level)
1992 {
1993 	struct tcmu_mailbox *mb;
1994 	struct tcmu_cmd *cmd;
1995 	int i;
1996 
1997 	mutex_lock(&udev->cmdr_lock);
1998 
1999 	idr_for_each_entry(&udev->commands, cmd, i) {
2000 		if (!list_empty(&cmd->cmdr_queue_entry))
2001 			continue;
2002 
2003 		pr_debug("removing cmd %u on dev %s from ring (is expired %d)\n",
2004 			  cmd->cmd_id, udev->name,
2005 			  test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags));
2006 
2007 		idr_remove(&udev->commands, i);
2008 		if (!test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
2009 			if (err_level == 1) {
2010 				/*
2011 				 * Userspace was not able to start the
2012 				 * command or it is retryable.
2013 				 */
2014 				target_complete_cmd(cmd->se_cmd, SAM_STAT_BUSY);
2015 			} else {
2016 				/* hard failure */
2017 				target_complete_cmd(cmd->se_cmd,
2018 						    SAM_STAT_CHECK_CONDITION);
2019 			}
2020 		}
2021 		tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
2022 		tcmu_free_cmd(cmd);
2023 	}
2024 
2025 	mb = udev->mb_addr;
2026 	tcmu_flush_dcache_range(mb, sizeof(*mb));
2027 	pr_debug("mb last %u head %u tail %u\n", udev->cmdr_last_cleaned,
2028 		 mb->cmd_tail, mb->cmd_head);
2029 
2030 	udev->cmdr_last_cleaned = 0;
2031 	mb->cmd_tail = 0;
2032 	mb->cmd_head = 0;
2033 	tcmu_flush_dcache_range(mb, sizeof(*mb));
2034 
2035 	del_timer(&udev->cmd_timer);
2036 
2037 	mutex_unlock(&udev->cmdr_lock);
2038 }
2039 
2040 enum {
2041 	Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
2042 	Opt_nl_reply_supported, Opt_max_data_area_mb, Opt_err,
2043 };
2044 
2045 static match_table_t tokens = {
2046 	{Opt_dev_config, "dev_config=%s"},
2047 	{Opt_dev_size, "dev_size=%s"},
2048 	{Opt_hw_block_size, "hw_block_size=%d"},
2049 	{Opt_hw_max_sectors, "hw_max_sectors=%d"},
2050 	{Opt_nl_reply_supported, "nl_reply_supported=%d"},
2051 	{Opt_max_data_area_mb, "max_data_area_mb=%d"},
2052 	{Opt_err, NULL}
2053 };
2054 
2055 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
2056 {
2057 	int val, ret;
2058 
2059 	ret = match_int(arg, &val);
2060 	if (ret < 0) {
2061 		pr_err("match_int() failed for dev attrib. Error %d.\n",
2062 		       ret);
2063 		return ret;
2064 	}
2065 
2066 	if (val <= 0) {
2067 		pr_err("Invalid dev attrib value %d. Must be greater than zero.\n",
2068 		       val);
2069 		return -EINVAL;
2070 	}
2071 	*dev_attrib = val;
2072 	return 0;
2073 }
2074 
2075 static int tcmu_set_max_blocks_param(struct tcmu_dev *udev, substring_t *arg)
2076 {
2077 	int val, ret;
2078 
2079 	ret = match_int(arg, &val);
2080 	if (ret < 0) {
2081 		pr_err("match_int() failed for max_data_area_mb=. Error %d.\n",
2082 		       ret);
2083 		return ret;
2084 	}
2085 
2086 	if (val <= 0) {
2087 		pr_err("Invalid max_data_area %d.\n", val);
2088 		return -EINVAL;
2089 	}
2090 
2091 	mutex_lock(&udev->cmdr_lock);
2092 	if (udev->data_bitmap) {
2093 		pr_err("Cannot set max_data_area_mb after it has been enabled.\n");
2094 		ret = -EINVAL;
2095 		goto unlock;
2096 	}
2097 
2098 	udev->max_blocks = TCMU_MBS_TO_BLOCKS(val);
2099 	if (udev->max_blocks > tcmu_global_max_blocks) {
2100 		pr_err("%d is too large. Adjusting max_data_area_mb to global limit of %u\n",
2101 		       val, TCMU_BLOCKS_TO_MBS(tcmu_global_max_blocks));
2102 		udev->max_blocks = tcmu_global_max_blocks;
2103 	}
2104 
2105 unlock:
2106 	mutex_unlock(&udev->cmdr_lock);
2107 	return ret;
2108 }
2109 
2110 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
2111 		const char *page, ssize_t count)
2112 {
2113 	struct tcmu_dev *udev = TCMU_DEV(dev);
2114 	char *orig, *ptr, *opts;
2115 	substring_t args[MAX_OPT_ARGS];
2116 	int ret = 0, token;
2117 
2118 	opts = kstrdup(page, GFP_KERNEL);
2119 	if (!opts)
2120 		return -ENOMEM;
2121 
2122 	orig = opts;
2123 
2124 	while ((ptr = strsep(&opts, ",\n")) != NULL) {
2125 		if (!*ptr)
2126 			continue;
2127 
2128 		token = match_token(ptr, tokens, args);
2129 		switch (token) {
2130 		case Opt_dev_config:
2131 			if (match_strlcpy(udev->dev_config, &args[0],
2132 					  TCMU_CONFIG_LEN) == 0) {
2133 				ret = -EINVAL;
2134 				break;
2135 			}
2136 			pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
2137 			break;
2138 		case Opt_dev_size:
2139 			ret = match_u64(&args[0], &udev->dev_size);
2140 			if (ret < 0)
2141 				pr_err("match_u64() failed for dev_size=. Error %d.\n",
2142 				       ret);
2143 			break;
2144 		case Opt_hw_block_size:
2145 			ret = tcmu_set_dev_attrib(&args[0],
2146 					&(dev->dev_attrib.hw_block_size));
2147 			break;
2148 		case Opt_hw_max_sectors:
2149 			ret = tcmu_set_dev_attrib(&args[0],
2150 					&(dev->dev_attrib.hw_max_sectors));
2151 			break;
2152 		case Opt_nl_reply_supported:
2153 			ret = match_int(&args[0], &udev->nl_reply_supported);
2154 			if (ret < 0)
2155 				pr_err("match_int() failed for nl_reply_supported=. Error %d.\n",
2156 				       ret);
2157 			break;
2158 		case Opt_max_data_area_mb:
2159 			ret = tcmu_set_max_blocks_param(udev, &args[0]);
2160 			break;
2161 		default:
2162 			break;
2163 		}
2164 
2165 		if (ret)
2166 			break;
2167 	}
2168 
2169 	kfree(orig);
2170 	return (!ret) ? count : ret;
2171 }
2172 
2173 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
2174 {
2175 	struct tcmu_dev *udev = TCMU_DEV(dev);
2176 	ssize_t bl = 0;
2177 
2178 	bl = sprintf(b + bl, "Config: %s ",
2179 		     udev->dev_config[0] ? udev->dev_config : "NULL");
2180 	bl += sprintf(b + bl, "Size: %llu ", udev->dev_size);
2181 	bl += sprintf(b + bl, "MaxDataAreaMB: %u\n",
2182 		      TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2183 
2184 	return bl;
2185 }
2186 
2187 static sector_t tcmu_get_blocks(struct se_device *dev)
2188 {
2189 	struct tcmu_dev *udev = TCMU_DEV(dev);
2190 
2191 	return div_u64(udev->dev_size - dev->dev_attrib.block_size,
2192 		       dev->dev_attrib.block_size);
2193 }
2194 
2195 static sense_reason_t
2196 tcmu_parse_cdb(struct se_cmd *cmd)
2197 {
2198 	return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
2199 }
2200 
2201 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
2202 {
2203 	struct se_dev_attrib *da = container_of(to_config_group(item),
2204 					struct se_dev_attrib, da_group);
2205 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2206 
2207 	return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
2208 }
2209 
2210 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
2211 				       size_t count)
2212 {
2213 	struct se_dev_attrib *da = container_of(to_config_group(item),
2214 					struct se_dev_attrib, da_group);
2215 	struct tcmu_dev *udev = container_of(da->da_dev,
2216 					struct tcmu_dev, se_dev);
2217 	u32 val;
2218 	int ret;
2219 
2220 	if (da->da_dev->export_count) {
2221 		pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
2222 		return -EINVAL;
2223 	}
2224 
2225 	ret = kstrtou32(page, 0, &val);
2226 	if (ret < 0)
2227 		return ret;
2228 
2229 	udev->cmd_time_out = val * MSEC_PER_SEC;
2230 	return count;
2231 }
2232 CONFIGFS_ATTR(tcmu_, cmd_time_out);
2233 
2234 static ssize_t tcmu_qfull_time_out_show(struct config_item *item, char *page)
2235 {
2236 	struct se_dev_attrib *da = container_of(to_config_group(item),
2237 						struct se_dev_attrib, da_group);
2238 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2239 
2240 	return snprintf(page, PAGE_SIZE, "%ld\n", udev->qfull_time_out <= 0 ?
2241 			udev->qfull_time_out :
2242 			udev->qfull_time_out / MSEC_PER_SEC);
2243 }
2244 
2245 static ssize_t tcmu_qfull_time_out_store(struct config_item *item,
2246 					 const char *page, size_t count)
2247 {
2248 	struct se_dev_attrib *da = container_of(to_config_group(item),
2249 					struct se_dev_attrib, da_group);
2250 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2251 	s32 val;
2252 	int ret;
2253 
2254 	ret = kstrtos32(page, 0, &val);
2255 	if (ret < 0)
2256 		return ret;
2257 
2258 	if (val >= 0) {
2259 		udev->qfull_time_out = val * MSEC_PER_SEC;
2260 	} else if (val == -1) {
2261 		udev->qfull_time_out = val;
2262 	} else {
2263 		printk(KERN_ERR "Invalid qfull timeout value %d\n", val);
2264 		return -EINVAL;
2265 	}
2266 	return count;
2267 }
2268 CONFIGFS_ATTR(tcmu_, qfull_time_out);
2269 
2270 static ssize_t tcmu_max_data_area_mb_show(struct config_item *item, char *page)
2271 {
2272 	struct se_dev_attrib *da = container_of(to_config_group(item),
2273 						struct se_dev_attrib, da_group);
2274 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2275 
2276 	return snprintf(page, PAGE_SIZE, "%u\n",
2277 			TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2278 }
2279 CONFIGFS_ATTR_RO(tcmu_, max_data_area_mb);
2280 
2281 static ssize_t tcmu_dev_config_show(struct config_item *item, char *page)
2282 {
2283 	struct se_dev_attrib *da = container_of(to_config_group(item),
2284 						struct se_dev_attrib, da_group);
2285 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2286 
2287 	return snprintf(page, PAGE_SIZE, "%s\n", udev->dev_config);
2288 }
2289 
2290 static int tcmu_send_dev_config_event(struct tcmu_dev *udev,
2291 				      const char *reconfig_data)
2292 {
2293 	struct sk_buff *skb = NULL;
2294 	void *msg_header = NULL;
2295 	int ret = 0;
2296 
2297 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2298 				      &skb, &msg_header);
2299 	if (ret < 0)
2300 		return ret;
2301 	ret = nla_put_string(skb, TCMU_ATTR_DEV_CFG, reconfig_data);
2302 	if (ret < 0) {
2303 		nlmsg_free(skb);
2304 		return ret;
2305 	}
2306 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2307 				       skb, msg_header);
2308 }
2309 
2310 
2311 static ssize_t tcmu_dev_config_store(struct config_item *item, const char *page,
2312 				     size_t count)
2313 {
2314 	struct se_dev_attrib *da = container_of(to_config_group(item),
2315 						struct se_dev_attrib, da_group);
2316 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2317 	int ret, len;
2318 
2319 	len = strlen(page);
2320 	if (!len || len > TCMU_CONFIG_LEN - 1)
2321 		return -EINVAL;
2322 
2323 	/* Check if device has been configured before */
2324 	if (target_dev_configured(&udev->se_dev)) {
2325 		ret = tcmu_send_dev_config_event(udev, page);
2326 		if (ret) {
2327 			pr_err("Unable to reconfigure device\n");
2328 			return ret;
2329 		}
2330 		strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2331 
2332 		ret = tcmu_update_uio_info(udev);
2333 		if (ret)
2334 			return ret;
2335 		return count;
2336 	}
2337 	strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2338 
2339 	return count;
2340 }
2341 CONFIGFS_ATTR(tcmu_, dev_config);
2342 
2343 static ssize_t tcmu_dev_size_show(struct config_item *item, char *page)
2344 {
2345 	struct se_dev_attrib *da = container_of(to_config_group(item),
2346 						struct se_dev_attrib, da_group);
2347 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2348 
2349 	return snprintf(page, PAGE_SIZE, "%llu\n", udev->dev_size);
2350 }
2351 
2352 static int tcmu_send_dev_size_event(struct tcmu_dev *udev, u64 size)
2353 {
2354 	struct sk_buff *skb = NULL;
2355 	void *msg_header = NULL;
2356 	int ret = 0;
2357 
2358 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2359 				      &skb, &msg_header);
2360 	if (ret < 0)
2361 		return ret;
2362 	ret = nla_put_u64_64bit(skb, TCMU_ATTR_DEV_SIZE,
2363 				size, TCMU_ATTR_PAD);
2364 	if (ret < 0) {
2365 		nlmsg_free(skb);
2366 		return ret;
2367 	}
2368 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2369 				       skb, msg_header);
2370 }
2371 
2372 static ssize_t tcmu_dev_size_store(struct config_item *item, const char *page,
2373 				   size_t count)
2374 {
2375 	struct se_dev_attrib *da = container_of(to_config_group(item),
2376 						struct se_dev_attrib, da_group);
2377 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2378 	u64 val;
2379 	int ret;
2380 
2381 	ret = kstrtou64(page, 0, &val);
2382 	if (ret < 0)
2383 		return ret;
2384 
2385 	/* Check if device has been configured before */
2386 	if (target_dev_configured(&udev->se_dev)) {
2387 		ret = tcmu_send_dev_size_event(udev, val);
2388 		if (ret) {
2389 			pr_err("Unable to reconfigure device\n");
2390 			return ret;
2391 		}
2392 	}
2393 	udev->dev_size = val;
2394 	return count;
2395 }
2396 CONFIGFS_ATTR(tcmu_, dev_size);
2397 
2398 static ssize_t tcmu_nl_reply_supported_show(struct config_item *item,
2399 		char *page)
2400 {
2401 	struct se_dev_attrib *da = container_of(to_config_group(item),
2402 						struct se_dev_attrib, da_group);
2403 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2404 
2405 	return snprintf(page, PAGE_SIZE, "%d\n", udev->nl_reply_supported);
2406 }
2407 
2408 static ssize_t tcmu_nl_reply_supported_store(struct config_item *item,
2409 		const char *page, size_t count)
2410 {
2411 	struct se_dev_attrib *da = container_of(to_config_group(item),
2412 						struct se_dev_attrib, da_group);
2413 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2414 	s8 val;
2415 	int ret;
2416 
2417 	ret = kstrtos8(page, 0, &val);
2418 	if (ret < 0)
2419 		return ret;
2420 
2421 	udev->nl_reply_supported = val;
2422 	return count;
2423 }
2424 CONFIGFS_ATTR(tcmu_, nl_reply_supported);
2425 
2426 static ssize_t tcmu_emulate_write_cache_show(struct config_item *item,
2427 					     char *page)
2428 {
2429 	struct se_dev_attrib *da = container_of(to_config_group(item),
2430 					struct se_dev_attrib, da_group);
2431 
2432 	return snprintf(page, PAGE_SIZE, "%i\n", da->emulate_write_cache);
2433 }
2434 
2435 static int tcmu_send_emulate_write_cache(struct tcmu_dev *udev, u8 val)
2436 {
2437 	struct sk_buff *skb = NULL;
2438 	void *msg_header = NULL;
2439 	int ret = 0;
2440 
2441 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2442 				      &skb, &msg_header);
2443 	if (ret < 0)
2444 		return ret;
2445 	ret = nla_put_u8(skb, TCMU_ATTR_WRITECACHE, val);
2446 	if (ret < 0) {
2447 		nlmsg_free(skb);
2448 		return ret;
2449 	}
2450 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2451 				       skb, msg_header);
2452 }
2453 
2454 static ssize_t tcmu_emulate_write_cache_store(struct config_item *item,
2455 					      const char *page, size_t count)
2456 {
2457 	struct se_dev_attrib *da = container_of(to_config_group(item),
2458 					struct se_dev_attrib, da_group);
2459 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2460 	u8 val;
2461 	int ret;
2462 
2463 	ret = kstrtou8(page, 0, &val);
2464 	if (ret < 0)
2465 		return ret;
2466 
2467 	/* Check if device has been configured before */
2468 	if (target_dev_configured(&udev->se_dev)) {
2469 		ret = tcmu_send_emulate_write_cache(udev, val);
2470 		if (ret) {
2471 			pr_err("Unable to reconfigure device\n");
2472 			return ret;
2473 		}
2474 	}
2475 
2476 	da->emulate_write_cache = val;
2477 	return count;
2478 }
2479 CONFIGFS_ATTR(tcmu_, emulate_write_cache);
2480 
2481 static ssize_t tcmu_block_dev_show(struct config_item *item, char *page)
2482 {
2483 	struct se_device *se_dev = container_of(to_config_group(item),
2484 						struct se_device,
2485 						dev_action_group);
2486 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2487 
2488 	if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
2489 		return snprintf(page, PAGE_SIZE, "%s\n", "blocked");
2490 	else
2491 		return snprintf(page, PAGE_SIZE, "%s\n", "unblocked");
2492 }
2493 
2494 static ssize_t tcmu_block_dev_store(struct config_item *item, const char *page,
2495 				    size_t count)
2496 {
2497 	struct se_device *se_dev = container_of(to_config_group(item),
2498 						struct se_device,
2499 						dev_action_group);
2500 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2501 	u8 val;
2502 	int ret;
2503 
2504 	if (!target_dev_configured(&udev->se_dev)) {
2505 		pr_err("Device is not configured.\n");
2506 		return -EINVAL;
2507 	}
2508 
2509 	ret = kstrtou8(page, 0, &val);
2510 	if (ret < 0)
2511 		return ret;
2512 
2513 	if (val > 1) {
2514 		pr_err("Invalid block value %d\n", val);
2515 		return -EINVAL;
2516 	}
2517 
2518 	if (!val)
2519 		tcmu_unblock_dev(udev);
2520 	else
2521 		tcmu_block_dev(udev);
2522 	return count;
2523 }
2524 CONFIGFS_ATTR(tcmu_, block_dev);
2525 
2526 static ssize_t tcmu_reset_ring_store(struct config_item *item, const char *page,
2527 				     size_t count)
2528 {
2529 	struct se_device *se_dev = container_of(to_config_group(item),
2530 						struct se_device,
2531 						dev_action_group);
2532 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2533 	u8 val;
2534 	int ret;
2535 
2536 	if (!target_dev_configured(&udev->se_dev)) {
2537 		pr_err("Device is not configured.\n");
2538 		return -EINVAL;
2539 	}
2540 
2541 	ret = kstrtou8(page, 0, &val);
2542 	if (ret < 0)
2543 		return ret;
2544 
2545 	if (val != 1 && val != 2) {
2546 		pr_err("Invalid reset ring value %d\n", val);
2547 		return -EINVAL;
2548 	}
2549 
2550 	tcmu_reset_ring(udev, val);
2551 	return count;
2552 }
2553 CONFIGFS_ATTR_WO(tcmu_, reset_ring);
2554 
2555 static struct configfs_attribute *tcmu_attrib_attrs[] = {
2556 	&tcmu_attr_cmd_time_out,
2557 	&tcmu_attr_qfull_time_out,
2558 	&tcmu_attr_max_data_area_mb,
2559 	&tcmu_attr_dev_config,
2560 	&tcmu_attr_dev_size,
2561 	&tcmu_attr_emulate_write_cache,
2562 	&tcmu_attr_nl_reply_supported,
2563 	NULL,
2564 };
2565 
2566 static struct configfs_attribute **tcmu_attrs;
2567 
2568 static struct configfs_attribute *tcmu_action_attrs[] = {
2569 	&tcmu_attr_block_dev,
2570 	&tcmu_attr_reset_ring,
2571 	NULL,
2572 };
2573 
2574 static struct target_backend_ops tcmu_ops = {
2575 	.name			= "user",
2576 	.owner			= THIS_MODULE,
2577 	.transport_flags	= TRANSPORT_FLAG_PASSTHROUGH,
2578 	.attach_hba		= tcmu_attach_hba,
2579 	.detach_hba		= tcmu_detach_hba,
2580 	.alloc_device		= tcmu_alloc_device,
2581 	.configure_device	= tcmu_configure_device,
2582 	.destroy_device		= tcmu_destroy_device,
2583 	.free_device		= tcmu_free_device,
2584 	.parse_cdb		= tcmu_parse_cdb,
2585 	.set_configfs_dev_params = tcmu_set_configfs_dev_params,
2586 	.show_configfs_dev_params = tcmu_show_configfs_dev_params,
2587 	.get_device_type	= sbc_get_device_type,
2588 	.get_blocks		= tcmu_get_blocks,
2589 	.tb_dev_action_attrs	= tcmu_action_attrs,
2590 };
2591 
2592 static void find_free_blocks(void)
2593 {
2594 	struct tcmu_dev *udev;
2595 	loff_t off;
2596 	u32 start, end, block, total_freed = 0;
2597 
2598 	if (atomic_read(&global_db_count) <= tcmu_global_max_blocks)
2599 		return;
2600 
2601 	mutex_lock(&root_udev_mutex);
2602 	list_for_each_entry(udev, &root_udev, node) {
2603 		mutex_lock(&udev->cmdr_lock);
2604 
2605 		if (!target_dev_configured(&udev->se_dev)) {
2606 			mutex_unlock(&udev->cmdr_lock);
2607 			continue;
2608 		}
2609 
2610 		/* Try to complete the finished commands first */
2611 		tcmu_handle_completions(udev);
2612 
2613 		/* Skip the udevs in idle */
2614 		if (!udev->dbi_thresh) {
2615 			mutex_unlock(&udev->cmdr_lock);
2616 			continue;
2617 		}
2618 
2619 		end = udev->dbi_max + 1;
2620 		block = find_last_bit(udev->data_bitmap, end);
2621 		if (block == udev->dbi_max) {
2622 			/*
2623 			 * The last bit is dbi_max, so it is not possible
2624 			 * reclaim any blocks.
2625 			 */
2626 			mutex_unlock(&udev->cmdr_lock);
2627 			continue;
2628 		} else if (block == end) {
2629 			/* The current udev will goto idle state */
2630 			udev->dbi_thresh = start = 0;
2631 			udev->dbi_max = 0;
2632 		} else {
2633 			udev->dbi_thresh = start = block + 1;
2634 			udev->dbi_max = block;
2635 		}
2636 
2637 		/* Here will truncate the data area from off */
2638 		off = udev->data_off + start * DATA_BLOCK_SIZE;
2639 		unmap_mapping_range(udev->inode->i_mapping, off, 0, 1);
2640 
2641 		/* Release the block pages */
2642 		tcmu_blocks_release(&udev->data_blocks, start, end);
2643 		mutex_unlock(&udev->cmdr_lock);
2644 
2645 		total_freed += end - start;
2646 		pr_debug("Freed %u blocks (total %u) from %s.\n", end - start,
2647 			 total_freed, udev->name);
2648 	}
2649 	mutex_unlock(&root_udev_mutex);
2650 
2651 	if (atomic_read(&global_db_count) > tcmu_global_max_blocks)
2652 		schedule_delayed_work(&tcmu_unmap_work, msecs_to_jiffies(5000));
2653 }
2654 
2655 static void check_timedout_devices(void)
2656 {
2657 	struct tcmu_dev *udev, *tmp_dev;
2658 	LIST_HEAD(devs);
2659 
2660 	spin_lock_bh(&timed_out_udevs_lock);
2661 	list_splice_init(&timed_out_udevs, &devs);
2662 
2663 	list_for_each_entry_safe(udev, tmp_dev, &devs, timedout_entry) {
2664 		list_del_init(&udev->timedout_entry);
2665 		spin_unlock_bh(&timed_out_udevs_lock);
2666 
2667 		mutex_lock(&udev->cmdr_lock);
2668 		idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
2669 		mutex_unlock(&udev->cmdr_lock);
2670 
2671 		spin_lock_bh(&timed_out_udevs_lock);
2672 	}
2673 
2674 	spin_unlock_bh(&timed_out_udevs_lock);
2675 }
2676 
2677 static void tcmu_unmap_work_fn(struct work_struct *work)
2678 {
2679 	check_timedout_devices();
2680 	find_free_blocks();
2681 }
2682 
2683 static int __init tcmu_module_init(void)
2684 {
2685 	int ret, i, k, len = 0;
2686 
2687 	BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
2688 
2689 	INIT_DELAYED_WORK(&tcmu_unmap_work, tcmu_unmap_work_fn);
2690 
2691 	tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
2692 				sizeof(struct tcmu_cmd),
2693 				__alignof__(struct tcmu_cmd),
2694 				0, NULL);
2695 	if (!tcmu_cmd_cache)
2696 		return -ENOMEM;
2697 
2698 	tcmu_root_device = root_device_register("tcm_user");
2699 	if (IS_ERR(tcmu_root_device)) {
2700 		ret = PTR_ERR(tcmu_root_device);
2701 		goto out_free_cache;
2702 	}
2703 
2704 	ret = genl_register_family(&tcmu_genl_family);
2705 	if (ret < 0) {
2706 		goto out_unreg_device;
2707 	}
2708 
2709 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2710 		len += sizeof(struct configfs_attribute *);
2711 	}
2712 	for (i = 0; tcmu_attrib_attrs[i] != NULL; i++) {
2713 		len += sizeof(struct configfs_attribute *);
2714 	}
2715 	len += sizeof(struct configfs_attribute *);
2716 
2717 	tcmu_attrs = kzalloc(len, GFP_KERNEL);
2718 	if (!tcmu_attrs) {
2719 		ret = -ENOMEM;
2720 		goto out_unreg_genl;
2721 	}
2722 
2723 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2724 		tcmu_attrs[i] = passthrough_attrib_attrs[i];
2725 	}
2726 	for (k = 0; tcmu_attrib_attrs[k] != NULL; k++) {
2727 		tcmu_attrs[i] = tcmu_attrib_attrs[k];
2728 		i++;
2729 	}
2730 	tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
2731 
2732 	ret = transport_backend_register(&tcmu_ops);
2733 	if (ret)
2734 		goto out_attrs;
2735 
2736 	return 0;
2737 
2738 out_attrs:
2739 	kfree(tcmu_attrs);
2740 out_unreg_genl:
2741 	genl_unregister_family(&tcmu_genl_family);
2742 out_unreg_device:
2743 	root_device_unregister(tcmu_root_device);
2744 out_free_cache:
2745 	kmem_cache_destroy(tcmu_cmd_cache);
2746 
2747 	return ret;
2748 }
2749 
2750 static void __exit tcmu_module_exit(void)
2751 {
2752 	cancel_delayed_work_sync(&tcmu_unmap_work);
2753 	target_backend_unregister(&tcmu_ops);
2754 	kfree(tcmu_attrs);
2755 	genl_unregister_family(&tcmu_genl_family);
2756 	root_device_unregister(tcmu_root_device);
2757 	kmem_cache_destroy(tcmu_cmd_cache);
2758 }
2759 
2760 MODULE_DESCRIPTION("TCM USER subsystem plugin");
2761 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
2762 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
2763 MODULE_LICENSE("GPL");
2764 
2765 module_init(tcmu_module_init);
2766 module_exit(tcmu_module_exit);
2767