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/kthread.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  * Define a shared-memory interface for LIO to pass SCSI commands and
47  * data to userspace for processing. This is to allow backends that
48  * are too complex for in-kernel support to be possible.
49  *
50  * It uses the UIO framework to do a lot of the device-creation and
51  * introspection work for us.
52  *
53  * See the .h file for how the ring is laid out. Note that while the
54  * command ring is defined, the particulars of the data area are
55  * not. Offset values in the command entry point to other locations
56  * internal to the mmap()ed area. There is separate space outside the
57  * command ring for data buffers. This leaves maximum flexibility for
58  * moving buffer allocations, or even page flipping or other
59  * allocation techniques, without altering the command ring layout.
60  *
61  * SECURITY:
62  * The user process must be assumed to be malicious. There's no way to
63  * prevent it breaking the command ring protocol if it wants, but in
64  * order to prevent other issues we must only ever read *data* from
65  * the shared memory area, not offsets or sizes. This applies to
66  * command ring entries as well as the mailbox. Extra code needed for
67  * this may have a 'UAM' comment.
68  */
69 
70 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
71 
72 /* For cmd area, the size is fixed 8MB */
73 #define CMDR_SIZE (8 * 1024 * 1024)
74 
75 /*
76  * For data area, the block size is PAGE_SIZE and
77  * the total size is 256K * PAGE_SIZE.
78  */
79 #define DATA_BLOCK_SIZE PAGE_SIZE
80 #define DATA_BLOCK_BITS (256 * 1024)
81 #define DATA_SIZE (DATA_BLOCK_BITS * DATA_BLOCK_SIZE)
82 #define DATA_BLOCK_INIT_BITS 128
83 
84 /* The total size of the ring is 8M + 256K * PAGE_SIZE */
85 #define TCMU_RING_SIZE (CMDR_SIZE + DATA_SIZE)
86 
87 /* Default maximum of the global data blocks(512K * PAGE_SIZE) */
88 #define TCMU_GLOBAL_MAX_BLOCKS (512 * 1024)
89 
90 static u8 tcmu_kern_cmd_reply_supported;
91 
92 static struct device *tcmu_root_device;
93 
94 struct tcmu_hba {
95 	u32 host_id;
96 };
97 
98 #define TCMU_CONFIG_LEN 256
99 
100 struct tcmu_nl_cmd {
101 	/* wake up thread waiting for reply */
102 	struct completion complete;
103 	int cmd;
104 	int status;
105 };
106 
107 struct tcmu_dev {
108 	struct list_head node;
109 	struct kref kref;
110 	struct se_device se_dev;
111 
112 	char *name;
113 	struct se_hba *hba;
114 
115 #define TCMU_DEV_BIT_OPEN 0
116 #define TCMU_DEV_BIT_BROKEN 1
117 	unsigned long flags;
118 
119 	struct uio_info uio_info;
120 
121 	struct inode *inode;
122 
123 	struct tcmu_mailbox *mb_addr;
124 	size_t dev_size;
125 	u32 cmdr_size;
126 	u32 cmdr_last_cleaned;
127 	/* Offset of data area from start of mb */
128 	/* Must add data_off and mb_addr to get the address */
129 	size_t data_off;
130 	size_t data_size;
131 
132 	wait_queue_head_t wait_cmdr;
133 	struct mutex cmdr_lock;
134 
135 	bool waiting_global;
136 	uint32_t dbi_max;
137 	uint32_t dbi_thresh;
138 	DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
139 	struct radix_tree_root data_blocks;
140 
141 	struct idr commands;
142 	spinlock_t commands_lock;
143 
144 	struct timer_list timeout;
145 	unsigned int cmd_time_out;
146 
147 	spinlock_t nl_cmd_lock;
148 	struct tcmu_nl_cmd curr_nl_cmd;
149 	/* wake up threads waiting on curr_nl_cmd */
150 	wait_queue_head_t nl_cmd_wq;
151 
152 	char dev_config[TCMU_CONFIG_LEN];
153 };
154 
155 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
156 
157 #define CMDR_OFF sizeof(struct tcmu_mailbox)
158 
159 struct tcmu_cmd {
160 	struct se_cmd *se_cmd;
161 	struct tcmu_dev *tcmu_dev;
162 
163 	uint16_t cmd_id;
164 
165 	/* Can't use se_cmd when cleaning up expired cmds, because if
166 	   cmd has been completed then accessing se_cmd is off limits */
167 	uint32_t dbi_cnt;
168 	uint32_t dbi_cur;
169 	uint32_t *dbi;
170 
171 	unsigned long deadline;
172 
173 #define TCMU_CMD_BIT_EXPIRED 0
174 	unsigned long flags;
175 };
176 
177 static struct task_struct *unmap_thread;
178 static wait_queue_head_t unmap_wait;
179 static DEFINE_MUTEX(root_udev_mutex);
180 static LIST_HEAD(root_udev);
181 
182 static atomic_t global_db_count = ATOMIC_INIT(0);
183 
184 static struct kmem_cache *tcmu_cmd_cache;
185 
186 /* multicast group */
187 enum tcmu_multicast_groups {
188 	TCMU_MCGRP_CONFIG,
189 };
190 
191 static const struct genl_multicast_group tcmu_mcgrps[] = {
192 	[TCMU_MCGRP_CONFIG] = { .name = "config", },
193 };
194 
195 static struct nla_policy tcmu_attr_policy[TCMU_ATTR_MAX+1] = {
196 	[TCMU_ATTR_DEVICE]	= { .type = NLA_STRING },
197 	[TCMU_ATTR_MINOR]	= { .type = NLA_U32 },
198 	[TCMU_ATTR_CMD_STATUS]	= { .type = NLA_S32 },
199 	[TCMU_ATTR_DEVICE_ID]	= { .type = NLA_U32 },
200 	[TCMU_ATTR_SUPP_KERN_CMD_REPLY] = { .type = NLA_U8 },
201 };
202 
203 static int tcmu_genl_cmd_done(struct genl_info *info, int completed_cmd)
204 {
205 	struct se_device *dev;
206 	struct tcmu_dev *udev;
207 	struct tcmu_nl_cmd *nl_cmd;
208 	int dev_id, rc, ret = 0;
209 	bool is_removed = (completed_cmd == TCMU_CMD_REMOVED_DEVICE);
210 
211 	if (!info->attrs[TCMU_ATTR_CMD_STATUS] ||
212 	    !info->attrs[TCMU_ATTR_DEVICE_ID]) {
213 		printk(KERN_ERR "TCMU_ATTR_CMD_STATUS or TCMU_ATTR_DEVICE_ID not set, doing nothing\n");
214                 return -EINVAL;
215         }
216 
217 	dev_id = nla_get_u32(info->attrs[TCMU_ATTR_DEVICE_ID]);
218 	rc = nla_get_s32(info->attrs[TCMU_ATTR_CMD_STATUS]);
219 
220 	dev = target_find_device(dev_id, !is_removed);
221 	if (!dev) {
222 		printk(KERN_ERR "tcmu nl cmd %u/%u completion could not find device with dev id %u.\n",
223 		       completed_cmd, rc, dev_id);
224 		return -ENODEV;
225 	}
226 	udev = TCMU_DEV(dev);
227 
228 	spin_lock(&udev->nl_cmd_lock);
229 	nl_cmd = &udev->curr_nl_cmd;
230 
231 	pr_debug("genl cmd done got id %d curr %d done %d rc %d\n", dev_id,
232 		 nl_cmd->cmd, completed_cmd, rc);
233 
234 	if (nl_cmd->cmd != completed_cmd) {
235 		printk(KERN_ERR "Mismatched commands (Expecting reply for %d. Current %d).\n",
236 		       completed_cmd, nl_cmd->cmd);
237 		ret = -EINVAL;
238 	} else {
239 		nl_cmd->status = rc;
240 	}
241 
242 	spin_unlock(&udev->nl_cmd_lock);
243 	if (!is_removed)
244 		 target_undepend_item(&dev->dev_group.cg_item);
245 	if (!ret)
246 		complete(&nl_cmd->complete);
247 	return ret;
248 }
249 
250 static int tcmu_genl_rm_dev_done(struct sk_buff *skb, struct genl_info *info)
251 {
252 	return tcmu_genl_cmd_done(info, TCMU_CMD_REMOVED_DEVICE);
253 }
254 
255 static int tcmu_genl_add_dev_done(struct sk_buff *skb, struct genl_info *info)
256 {
257 	return tcmu_genl_cmd_done(info, TCMU_CMD_ADDED_DEVICE);
258 }
259 
260 static int tcmu_genl_reconfig_dev_done(struct sk_buff *skb,
261 				       struct genl_info *info)
262 {
263 	return tcmu_genl_cmd_done(info, TCMU_CMD_RECONFIG_DEVICE);
264 }
265 
266 static int tcmu_genl_set_features(struct sk_buff *skb, struct genl_info *info)
267 {
268 	if (info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]) {
269 		tcmu_kern_cmd_reply_supported  =
270 			nla_get_u8(info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]);
271 		printk(KERN_INFO "tcmu daemon: command reply support %u.\n",
272 		       tcmu_kern_cmd_reply_supported);
273 	}
274 
275 	return 0;
276 }
277 
278 static const struct genl_ops tcmu_genl_ops[] = {
279 	{
280 		.cmd	= TCMU_CMD_SET_FEATURES,
281 		.flags	= GENL_ADMIN_PERM,
282 		.policy	= tcmu_attr_policy,
283 		.doit	= tcmu_genl_set_features,
284 	},
285 	{
286 		.cmd	= TCMU_CMD_ADDED_DEVICE_DONE,
287 		.flags	= GENL_ADMIN_PERM,
288 		.policy	= tcmu_attr_policy,
289 		.doit	= tcmu_genl_add_dev_done,
290 	},
291 	{
292 		.cmd	= TCMU_CMD_REMOVED_DEVICE_DONE,
293 		.flags	= GENL_ADMIN_PERM,
294 		.policy	= tcmu_attr_policy,
295 		.doit	= tcmu_genl_rm_dev_done,
296 	},
297 	{
298 		.cmd	= TCMU_CMD_RECONFIG_DEVICE_DONE,
299 		.flags	= GENL_ADMIN_PERM,
300 		.policy	= tcmu_attr_policy,
301 		.doit	= tcmu_genl_reconfig_dev_done,
302 	},
303 };
304 
305 /* Our generic netlink family */
306 static struct genl_family tcmu_genl_family __ro_after_init = {
307 	.module = THIS_MODULE,
308 	.hdrsize = 0,
309 	.name = "TCM-USER",
310 	.version = 2,
311 	.maxattr = TCMU_ATTR_MAX,
312 	.mcgrps = tcmu_mcgrps,
313 	.n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
314 	.netnsok = true,
315 	.ops = tcmu_genl_ops,
316 	.n_ops = ARRAY_SIZE(tcmu_genl_ops),
317 };
318 
319 #define tcmu_cmd_set_dbi_cur(cmd, index) ((cmd)->dbi_cur = (index))
320 #define tcmu_cmd_reset_dbi_cur(cmd) tcmu_cmd_set_dbi_cur(cmd, 0)
321 #define tcmu_cmd_set_dbi(cmd, index) ((cmd)->dbi[(cmd)->dbi_cur++] = (index))
322 #define tcmu_cmd_get_dbi(cmd) ((cmd)->dbi[(cmd)->dbi_cur++])
323 
324 static void tcmu_cmd_free_data(struct tcmu_cmd *tcmu_cmd, uint32_t len)
325 {
326 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
327 	uint32_t i;
328 
329 	for (i = 0; i < len; i++)
330 		clear_bit(tcmu_cmd->dbi[i], udev->data_bitmap);
331 }
332 
333 static inline bool tcmu_get_empty_block(struct tcmu_dev *udev,
334 					struct tcmu_cmd *tcmu_cmd)
335 {
336 	struct page *page;
337 	int ret, dbi;
338 
339 	dbi = find_first_zero_bit(udev->data_bitmap, udev->dbi_thresh);
340 	if (dbi == udev->dbi_thresh)
341 		return false;
342 
343 	page = radix_tree_lookup(&udev->data_blocks, dbi);
344 	if (!page) {
345 		if (atomic_add_return(1, &global_db_count) >
346 					TCMU_GLOBAL_MAX_BLOCKS) {
347 			atomic_dec(&global_db_count);
348 			return false;
349 		}
350 
351 		/* try to get new page from the mm */
352 		page = alloc_page(GFP_KERNEL);
353 		if (!page)
354 			goto err_alloc;
355 
356 		ret = radix_tree_insert(&udev->data_blocks, dbi, page);
357 		if (ret)
358 			goto err_insert;
359 	}
360 
361 	if (dbi > udev->dbi_max)
362 		udev->dbi_max = dbi;
363 
364 	set_bit(dbi, udev->data_bitmap);
365 	tcmu_cmd_set_dbi(tcmu_cmd, dbi);
366 
367 	return true;
368 err_insert:
369 	__free_page(page);
370 err_alloc:
371 	atomic_dec(&global_db_count);
372 	return false;
373 }
374 
375 static bool tcmu_get_empty_blocks(struct tcmu_dev *udev,
376 				  struct tcmu_cmd *tcmu_cmd)
377 {
378 	int i;
379 
380 	udev->waiting_global = false;
381 
382 	for (i = tcmu_cmd->dbi_cur; i < tcmu_cmd->dbi_cnt; i++) {
383 		if (!tcmu_get_empty_block(udev, tcmu_cmd))
384 			goto err;
385 	}
386 	return true;
387 
388 err:
389 	udev->waiting_global = true;
390 	/* Try to wake up the unmap thread */
391 	wake_up(&unmap_wait);
392 	return false;
393 }
394 
395 static inline struct page *
396 tcmu_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
397 {
398 	return radix_tree_lookup(&udev->data_blocks, dbi);
399 }
400 
401 static inline void tcmu_free_cmd(struct tcmu_cmd *tcmu_cmd)
402 {
403 	kfree(tcmu_cmd->dbi);
404 	kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
405 }
406 
407 static inline size_t tcmu_cmd_get_data_length(struct tcmu_cmd *tcmu_cmd)
408 {
409 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
410 	size_t data_length = round_up(se_cmd->data_length, DATA_BLOCK_SIZE);
411 
412 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
413 		BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
414 		data_length += round_up(se_cmd->t_bidi_data_sg->length,
415 				DATA_BLOCK_SIZE);
416 	}
417 
418 	return data_length;
419 }
420 
421 static inline uint32_t tcmu_cmd_get_block_cnt(struct tcmu_cmd *tcmu_cmd)
422 {
423 	size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
424 
425 	return data_length / DATA_BLOCK_SIZE;
426 }
427 
428 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
429 {
430 	struct se_device *se_dev = se_cmd->se_dev;
431 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
432 	struct tcmu_cmd *tcmu_cmd;
433 	int cmd_id;
434 
435 	tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
436 	if (!tcmu_cmd)
437 		return NULL;
438 
439 	tcmu_cmd->se_cmd = se_cmd;
440 	tcmu_cmd->tcmu_dev = udev;
441 	if (udev->cmd_time_out)
442 		tcmu_cmd->deadline = jiffies +
443 					msecs_to_jiffies(udev->cmd_time_out);
444 
445 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
446 	tcmu_cmd->dbi_cnt = tcmu_cmd_get_block_cnt(tcmu_cmd);
447 	tcmu_cmd->dbi = kcalloc(tcmu_cmd->dbi_cnt, sizeof(uint32_t),
448 				GFP_KERNEL);
449 	if (!tcmu_cmd->dbi) {
450 		kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
451 		return NULL;
452 	}
453 
454 	idr_preload(GFP_KERNEL);
455 	spin_lock_irq(&udev->commands_lock);
456 	cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 0,
457 		USHRT_MAX, GFP_NOWAIT);
458 	spin_unlock_irq(&udev->commands_lock);
459 	idr_preload_end();
460 
461 	if (cmd_id < 0) {
462 		tcmu_free_cmd(tcmu_cmd);
463 		return NULL;
464 	}
465 	tcmu_cmd->cmd_id = cmd_id;
466 
467 	return tcmu_cmd;
468 }
469 
470 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
471 {
472 	unsigned long offset = offset_in_page(vaddr);
473 
474 	size = round_up(size+offset, PAGE_SIZE);
475 	vaddr -= offset;
476 
477 	while (size) {
478 		flush_dcache_page(virt_to_page(vaddr));
479 		size -= PAGE_SIZE;
480 	}
481 }
482 
483 /*
484  * Some ring helper functions. We don't assume size is a power of 2 so
485  * we can't use circ_buf.h.
486  */
487 static inline size_t spc_used(size_t head, size_t tail, size_t size)
488 {
489 	int diff = head - tail;
490 
491 	if (diff >= 0)
492 		return diff;
493 	else
494 		return size + diff;
495 }
496 
497 static inline size_t spc_free(size_t head, size_t tail, size_t size)
498 {
499 	/* Keep 1 byte unused or we can't tell full from empty */
500 	return (size - spc_used(head, tail, size) - 1);
501 }
502 
503 static inline size_t head_to_end(size_t head, size_t size)
504 {
505 	return size - head;
506 }
507 
508 static inline void new_iov(struct iovec **iov, int *iov_cnt,
509 			   struct tcmu_dev *udev)
510 {
511 	struct iovec *iovec;
512 
513 	if (*iov_cnt != 0)
514 		(*iov)++;
515 	(*iov_cnt)++;
516 
517 	iovec = *iov;
518 	memset(iovec, 0, sizeof(struct iovec));
519 }
520 
521 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
522 
523 /* offset is relative to mb_addr */
524 static inline size_t get_block_offset_user(struct tcmu_dev *dev,
525 		int dbi, int remaining)
526 {
527 	return dev->data_off + dbi * DATA_BLOCK_SIZE +
528 		DATA_BLOCK_SIZE - remaining;
529 }
530 
531 static inline size_t iov_tail(struct iovec *iov)
532 {
533 	return (size_t)iov->iov_base + iov->iov_len;
534 }
535 
536 static int scatter_data_area(struct tcmu_dev *udev,
537 	struct tcmu_cmd *tcmu_cmd, struct scatterlist *data_sg,
538 	unsigned int data_nents, struct iovec **iov,
539 	int *iov_cnt, bool copy_data)
540 {
541 	int i, dbi;
542 	int block_remaining = 0;
543 	void *from, *to = NULL;
544 	size_t copy_bytes, to_offset, offset;
545 	struct scatterlist *sg;
546 	struct page *page;
547 
548 	for_each_sg(data_sg, sg, data_nents, i) {
549 		int sg_remaining = sg->length;
550 		from = kmap_atomic(sg_page(sg)) + sg->offset;
551 		while (sg_remaining > 0) {
552 			if (block_remaining == 0) {
553 				if (to)
554 					kunmap_atomic(to);
555 
556 				block_remaining = DATA_BLOCK_SIZE;
557 				dbi = tcmu_cmd_get_dbi(tcmu_cmd);
558 				page = tcmu_get_block_page(udev, dbi);
559 				to = kmap_atomic(page);
560 			}
561 
562 			copy_bytes = min_t(size_t, sg_remaining,
563 					block_remaining);
564 			to_offset = get_block_offset_user(udev, dbi,
565 					block_remaining);
566 			offset = DATA_BLOCK_SIZE - block_remaining;
567 			to += offset;
568 
569 			if (*iov_cnt != 0 &&
570 			    to_offset == iov_tail(*iov)) {
571 				(*iov)->iov_len += copy_bytes;
572 			} else {
573 				new_iov(iov, iov_cnt, udev);
574 				(*iov)->iov_base = (void __user *)to_offset;
575 				(*iov)->iov_len = copy_bytes;
576 			}
577 			if (copy_data) {
578 				memcpy(to, from + sg->length - sg_remaining,
579 					copy_bytes);
580 				tcmu_flush_dcache_range(to, copy_bytes);
581 			}
582 			sg_remaining -= copy_bytes;
583 			block_remaining -= copy_bytes;
584 		}
585 		kunmap_atomic(from - sg->offset);
586 	}
587 	if (to)
588 		kunmap_atomic(to);
589 
590 	return 0;
591 }
592 
593 static void gather_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
594 			     bool bidi)
595 {
596 	struct se_cmd *se_cmd = cmd->se_cmd;
597 	int i, dbi;
598 	int block_remaining = 0;
599 	void *from = NULL, *to;
600 	size_t copy_bytes, offset;
601 	struct scatterlist *sg, *data_sg;
602 	struct page *page;
603 	unsigned int data_nents;
604 	uint32_t count = 0;
605 
606 	if (!bidi) {
607 		data_sg = se_cmd->t_data_sg;
608 		data_nents = se_cmd->t_data_nents;
609 	} else {
610 
611 		/*
612 		 * For bidi case, the first count blocks are for Data-Out
613 		 * buffer blocks, and before gathering the Data-In buffer
614 		 * the Data-Out buffer blocks should be discarded.
615 		 */
616 		count = DIV_ROUND_UP(se_cmd->data_length, DATA_BLOCK_SIZE);
617 
618 		data_sg = se_cmd->t_bidi_data_sg;
619 		data_nents = se_cmd->t_bidi_data_nents;
620 	}
621 
622 	tcmu_cmd_set_dbi_cur(cmd, count);
623 
624 	for_each_sg(data_sg, sg, data_nents, i) {
625 		int sg_remaining = sg->length;
626 		to = kmap_atomic(sg_page(sg)) + sg->offset;
627 		while (sg_remaining > 0) {
628 			if (block_remaining == 0) {
629 				if (from)
630 					kunmap_atomic(from);
631 
632 				block_remaining = DATA_BLOCK_SIZE;
633 				dbi = tcmu_cmd_get_dbi(cmd);
634 				page = tcmu_get_block_page(udev, dbi);
635 				from = kmap_atomic(page);
636 			}
637 			copy_bytes = min_t(size_t, sg_remaining,
638 					block_remaining);
639 			offset = DATA_BLOCK_SIZE - block_remaining;
640 			from += offset;
641 			tcmu_flush_dcache_range(from, copy_bytes);
642 			memcpy(to + sg->length - sg_remaining, from,
643 					copy_bytes);
644 
645 			sg_remaining -= copy_bytes;
646 			block_remaining -= copy_bytes;
647 		}
648 		kunmap_atomic(to - sg->offset);
649 	}
650 	if (from)
651 		kunmap_atomic(from);
652 }
653 
654 static inline size_t spc_bitmap_free(unsigned long *bitmap, uint32_t thresh)
655 {
656 	return DATA_BLOCK_SIZE * (thresh - bitmap_weight(bitmap, thresh));
657 }
658 
659 /*
660  * We can't queue a command until we have space available on the cmd ring *and*
661  * space available on the data area.
662  *
663  * Called with ring lock held.
664  */
665 static bool is_ring_space_avail(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
666 		size_t cmd_size, size_t data_needed)
667 {
668 	struct tcmu_mailbox *mb = udev->mb_addr;
669 	uint32_t blocks_needed = (data_needed + DATA_BLOCK_SIZE - 1)
670 				/ DATA_BLOCK_SIZE;
671 	size_t space, cmd_needed;
672 	u32 cmd_head;
673 
674 	tcmu_flush_dcache_range(mb, sizeof(*mb));
675 
676 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
677 
678 	/*
679 	 * If cmd end-of-ring space is too small then we need space for a NOP plus
680 	 * original cmd - cmds are internally contiguous.
681 	 */
682 	if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
683 		cmd_needed = cmd_size;
684 	else
685 		cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
686 
687 	space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
688 	if (space < cmd_needed) {
689 		pr_debug("no cmd space: %u %u %u\n", cmd_head,
690 		       udev->cmdr_last_cleaned, udev->cmdr_size);
691 		return false;
692 	}
693 
694 	/* try to check and get the data blocks as needed */
695 	space = spc_bitmap_free(udev->data_bitmap, udev->dbi_thresh);
696 	if (space < data_needed) {
697 		unsigned long blocks_left = DATA_BLOCK_BITS - udev->dbi_thresh;
698 		unsigned long grow;
699 
700 		if (blocks_left < blocks_needed) {
701 			pr_debug("no data space: only %lu available, but ask for %zu\n",
702 					blocks_left * DATA_BLOCK_SIZE,
703 					data_needed);
704 			return false;
705 		}
706 
707 		/* Try to expand the thresh */
708 		if (!udev->dbi_thresh) {
709 			/* From idle state */
710 			uint32_t init_thresh = DATA_BLOCK_INIT_BITS;
711 
712 			udev->dbi_thresh = max(blocks_needed, init_thresh);
713 		} else {
714 			/*
715 			 * Grow the data area by max(blocks needed,
716 			 * dbi_thresh / 2), but limited to the max
717 			 * DATA_BLOCK_BITS size.
718 			 */
719 			grow = max(blocks_needed, udev->dbi_thresh / 2);
720 			udev->dbi_thresh += grow;
721 			if (udev->dbi_thresh > DATA_BLOCK_BITS)
722 				udev->dbi_thresh = DATA_BLOCK_BITS;
723 		}
724 	}
725 
726 	return tcmu_get_empty_blocks(udev, cmd);
727 }
728 
729 static inline size_t tcmu_cmd_get_base_cmd_size(size_t iov_cnt)
730 {
731 	return max(offsetof(struct tcmu_cmd_entry, req.iov[iov_cnt]),
732 			sizeof(struct tcmu_cmd_entry));
733 }
734 
735 static inline size_t tcmu_cmd_get_cmd_size(struct tcmu_cmd *tcmu_cmd,
736 					   size_t base_command_size)
737 {
738 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
739 	size_t command_size;
740 
741 	command_size = base_command_size +
742 		round_up(scsi_command_size(se_cmd->t_task_cdb),
743 				TCMU_OP_ALIGN_SIZE);
744 
745 	WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
746 
747 	return command_size;
748 }
749 
750 static sense_reason_t
751 tcmu_queue_cmd_ring(struct tcmu_cmd *tcmu_cmd)
752 {
753 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
754 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
755 	size_t base_command_size, command_size;
756 	struct tcmu_mailbox *mb;
757 	struct tcmu_cmd_entry *entry;
758 	struct iovec *iov;
759 	int iov_cnt, ret;
760 	uint32_t cmd_head;
761 	uint64_t cdb_off;
762 	bool copy_to_data_area;
763 	size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
764 
765 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
766 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
767 
768 	/*
769 	 * Must be a certain minimum size for response sense info, but
770 	 * also may be larger if the iov array is large.
771 	 *
772 	 * We prepare as many iovs as possbile for potential uses here,
773 	 * because it's expensive to tell how many regions are freed in
774 	 * the bitmap & global data pool, as the size calculated here
775 	 * will only be used to do the checks.
776 	 *
777 	 * The size will be recalculated later as actually needed to save
778 	 * cmd area memories.
779 	 */
780 	base_command_size = tcmu_cmd_get_base_cmd_size(tcmu_cmd->dbi_cnt);
781 	command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
782 
783 	mutex_lock(&udev->cmdr_lock);
784 
785 	mb = udev->mb_addr;
786 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
787 	if ((command_size > (udev->cmdr_size / 2)) ||
788 	    data_length > udev->data_size) {
789 		pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
790 			"cmd ring/data area\n", command_size, data_length,
791 			udev->cmdr_size, udev->data_size);
792 		mutex_unlock(&udev->cmdr_lock);
793 		return TCM_INVALID_CDB_FIELD;
794 	}
795 
796 	while (!is_ring_space_avail(udev, tcmu_cmd, command_size, data_length)) {
797 		int ret;
798 		DEFINE_WAIT(__wait);
799 
800 		prepare_to_wait(&udev->wait_cmdr, &__wait, TASK_INTERRUPTIBLE);
801 
802 		pr_debug("sleeping for ring space\n");
803 		mutex_unlock(&udev->cmdr_lock);
804 		if (udev->cmd_time_out)
805 			ret = schedule_timeout(
806 					msecs_to_jiffies(udev->cmd_time_out));
807 		else
808 			ret = schedule_timeout(msecs_to_jiffies(TCMU_TIME_OUT));
809 		finish_wait(&udev->wait_cmdr, &__wait);
810 		if (!ret) {
811 			pr_warn("tcmu: command timed out\n");
812 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
813 		}
814 
815 		mutex_lock(&udev->cmdr_lock);
816 
817 		/* We dropped cmdr_lock, cmd_head is stale */
818 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
819 	}
820 
821 	/* Insert a PAD if end-of-ring space is too small */
822 	if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
823 		size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
824 
825 		entry = (void *) mb + CMDR_OFF + cmd_head;
826 		tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
827 		tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
828 		entry->hdr.cmd_id = 0; /* not used for PAD */
829 		entry->hdr.kflags = 0;
830 		entry->hdr.uflags = 0;
831 		tcmu_flush_dcache_range(entry, sizeof(*entry));
832 
833 		UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
834 		tcmu_flush_dcache_range(mb, sizeof(*mb));
835 
836 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
837 		WARN_ON(cmd_head != 0);
838 	}
839 
840 	entry = (void *) mb + CMDR_OFF + cmd_head;
841 	memset(entry, 0, command_size);
842 	tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
843 	entry->hdr.cmd_id = tcmu_cmd->cmd_id;
844 
845 	/* Handle allocating space from the data area */
846 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
847 	iov = &entry->req.iov[0];
848 	iov_cnt = 0;
849 	copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
850 		|| se_cmd->se_cmd_flags & SCF_BIDI);
851 	ret = scatter_data_area(udev, tcmu_cmd, se_cmd->t_data_sg,
852 				se_cmd->t_data_nents, &iov, &iov_cnt,
853 				copy_to_data_area);
854 	if (ret) {
855 		tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
856 		mutex_unlock(&udev->cmdr_lock);
857 
858 		pr_err("tcmu: alloc and scatter data failed\n");
859 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
860 	}
861 	entry->req.iov_cnt = iov_cnt;
862 
863 	/* Handle BIDI commands */
864 	iov_cnt = 0;
865 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
866 		iov++;
867 		ret = scatter_data_area(udev, tcmu_cmd,
868 					se_cmd->t_bidi_data_sg,
869 					se_cmd->t_bidi_data_nents,
870 					&iov, &iov_cnt, false);
871 		if (ret) {
872 			tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
873 			mutex_unlock(&udev->cmdr_lock);
874 
875 			pr_err("tcmu: alloc and scatter bidi data failed\n");
876 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
877 		}
878 	}
879 	entry->req.iov_bidi_cnt = iov_cnt;
880 
881 	/*
882 	 * Recalaulate the command's base size and size according
883 	 * to the actual needs
884 	 */
885 	base_command_size = tcmu_cmd_get_base_cmd_size(entry->req.iov_cnt +
886 						       entry->req.iov_bidi_cnt);
887 	command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
888 
889 	tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
890 
891 	/* All offsets relative to mb_addr, not start of entry! */
892 	cdb_off = CMDR_OFF + cmd_head + base_command_size;
893 	memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
894 	entry->req.cdb_off = cdb_off;
895 	tcmu_flush_dcache_range(entry, sizeof(*entry));
896 
897 	UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
898 	tcmu_flush_dcache_range(mb, sizeof(*mb));
899 	mutex_unlock(&udev->cmdr_lock);
900 
901 	/* TODO: only if FLUSH and FUA? */
902 	uio_event_notify(&udev->uio_info);
903 
904 	if (udev->cmd_time_out)
905 		mod_timer(&udev->timeout, round_jiffies_up(jiffies +
906 			  msecs_to_jiffies(udev->cmd_time_out)));
907 
908 	return TCM_NO_SENSE;
909 }
910 
911 static sense_reason_t
912 tcmu_queue_cmd(struct se_cmd *se_cmd)
913 {
914 	struct se_device *se_dev = se_cmd->se_dev;
915 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
916 	struct tcmu_cmd *tcmu_cmd;
917 	sense_reason_t ret;
918 
919 	tcmu_cmd = tcmu_alloc_cmd(se_cmd);
920 	if (!tcmu_cmd)
921 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
922 
923 	ret = tcmu_queue_cmd_ring(tcmu_cmd);
924 	if (ret != TCM_NO_SENSE) {
925 		pr_err("TCMU: Could not queue command\n");
926 		spin_lock_irq(&udev->commands_lock);
927 		idr_remove(&udev->commands, tcmu_cmd->cmd_id);
928 		spin_unlock_irq(&udev->commands_lock);
929 
930 		tcmu_free_cmd(tcmu_cmd);
931 	}
932 
933 	return ret;
934 }
935 
936 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
937 {
938 	struct se_cmd *se_cmd = cmd->se_cmd;
939 	struct tcmu_dev *udev = cmd->tcmu_dev;
940 
941 	/*
942 	 * cmd has been completed already from timeout, just reclaim
943 	 * data area space and free cmd
944 	 */
945 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
946 		goto out;
947 
948 	tcmu_cmd_reset_dbi_cur(cmd);
949 
950 	if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
951 		pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
952 			cmd->se_cmd);
953 		entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
954 	} else if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
955 		transport_copy_sense_to_cmd(se_cmd, entry->rsp.sense_buffer);
956 	} else if (se_cmd->se_cmd_flags & SCF_BIDI) {
957 		/* Get Data-In buffer before clean up */
958 		gather_data_area(udev, cmd, true);
959 	} else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
960 		gather_data_area(udev, cmd, false);
961 	} else if (se_cmd->data_direction == DMA_TO_DEVICE) {
962 		/* TODO: */
963 	} else if (se_cmd->data_direction != DMA_NONE) {
964 		pr_warn("TCMU: data direction was %d!\n",
965 			se_cmd->data_direction);
966 	}
967 
968 	target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
969 
970 out:
971 	cmd->se_cmd = NULL;
972 	tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
973 	tcmu_free_cmd(cmd);
974 }
975 
976 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
977 {
978 	struct tcmu_mailbox *mb;
979 	int handled = 0;
980 
981 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
982 		pr_err("ring broken, not handling completions\n");
983 		return 0;
984 	}
985 
986 	mb = udev->mb_addr;
987 	tcmu_flush_dcache_range(mb, sizeof(*mb));
988 
989 	while (udev->cmdr_last_cleaned != ACCESS_ONCE(mb->cmd_tail)) {
990 
991 		struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
992 		struct tcmu_cmd *cmd;
993 
994 		tcmu_flush_dcache_range(entry, sizeof(*entry));
995 
996 		if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
997 			UPDATE_HEAD(udev->cmdr_last_cleaned,
998 				    tcmu_hdr_get_len(entry->hdr.len_op),
999 				    udev->cmdr_size);
1000 			continue;
1001 		}
1002 		WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
1003 
1004 		spin_lock(&udev->commands_lock);
1005 		cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
1006 		spin_unlock(&udev->commands_lock);
1007 
1008 		if (!cmd) {
1009 			pr_err("cmd_id not found, ring is broken\n");
1010 			set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
1011 			break;
1012 		}
1013 
1014 		tcmu_handle_completion(cmd, entry);
1015 
1016 		UPDATE_HEAD(udev->cmdr_last_cleaned,
1017 			    tcmu_hdr_get_len(entry->hdr.len_op),
1018 			    udev->cmdr_size);
1019 
1020 		handled++;
1021 	}
1022 
1023 	if (mb->cmd_tail == mb->cmd_head)
1024 		del_timer(&udev->timeout); /* no more pending cmds */
1025 
1026 	wake_up(&udev->wait_cmdr);
1027 
1028 	return handled;
1029 }
1030 
1031 static int tcmu_check_expired_cmd(int id, void *p, void *data)
1032 {
1033 	struct tcmu_cmd *cmd = p;
1034 
1035 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
1036 		return 0;
1037 
1038 	if (!time_after(jiffies, cmd->deadline))
1039 		return 0;
1040 
1041 	set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
1042 	target_complete_cmd(cmd->se_cmd, SAM_STAT_CHECK_CONDITION);
1043 	cmd->se_cmd = NULL;
1044 
1045 	return 0;
1046 }
1047 
1048 static void tcmu_device_timedout(unsigned long data)
1049 {
1050 	struct tcmu_dev *udev = (struct tcmu_dev *)data;
1051 	unsigned long flags;
1052 
1053 	spin_lock_irqsave(&udev->commands_lock, flags);
1054 	idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
1055 	spin_unlock_irqrestore(&udev->commands_lock, flags);
1056 
1057 	/* Try to wake up the ummap thread */
1058 	wake_up(&unmap_wait);
1059 
1060 	/*
1061 	 * We don't need to wakeup threads on wait_cmdr since they have their
1062 	 * own timeout.
1063 	 */
1064 }
1065 
1066 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
1067 {
1068 	struct tcmu_hba *tcmu_hba;
1069 
1070 	tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
1071 	if (!tcmu_hba)
1072 		return -ENOMEM;
1073 
1074 	tcmu_hba->host_id = host_id;
1075 	hba->hba_ptr = tcmu_hba;
1076 
1077 	return 0;
1078 }
1079 
1080 static void tcmu_detach_hba(struct se_hba *hba)
1081 {
1082 	kfree(hba->hba_ptr);
1083 	hba->hba_ptr = NULL;
1084 }
1085 
1086 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
1087 {
1088 	struct tcmu_dev *udev;
1089 
1090 	udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
1091 	if (!udev)
1092 		return NULL;
1093 	kref_init(&udev->kref);
1094 
1095 	udev->name = kstrdup(name, GFP_KERNEL);
1096 	if (!udev->name) {
1097 		kfree(udev);
1098 		return NULL;
1099 	}
1100 
1101 	udev->hba = hba;
1102 	udev->cmd_time_out = TCMU_TIME_OUT;
1103 
1104 	init_waitqueue_head(&udev->wait_cmdr);
1105 	mutex_init(&udev->cmdr_lock);
1106 
1107 	idr_init(&udev->commands);
1108 	spin_lock_init(&udev->commands_lock);
1109 
1110 	setup_timer(&udev->timeout, tcmu_device_timedout,
1111 		(unsigned long)udev);
1112 
1113 	init_waitqueue_head(&udev->nl_cmd_wq);
1114 	spin_lock_init(&udev->nl_cmd_lock);
1115 
1116 	return &udev->se_dev;
1117 }
1118 
1119 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
1120 {
1121 	struct tcmu_dev *tcmu_dev = container_of(info, struct tcmu_dev, uio_info);
1122 
1123 	mutex_lock(&tcmu_dev->cmdr_lock);
1124 	tcmu_handle_completions(tcmu_dev);
1125 	mutex_unlock(&tcmu_dev->cmdr_lock);
1126 
1127 	return 0;
1128 }
1129 
1130 /*
1131  * mmap code from uio.c. Copied here because we want to hook mmap()
1132  * and this stuff must come along.
1133  */
1134 static int tcmu_find_mem_index(struct vm_area_struct *vma)
1135 {
1136 	struct tcmu_dev *udev = vma->vm_private_data;
1137 	struct uio_info *info = &udev->uio_info;
1138 
1139 	if (vma->vm_pgoff < MAX_UIO_MAPS) {
1140 		if (info->mem[vma->vm_pgoff].size == 0)
1141 			return -1;
1142 		return (int)vma->vm_pgoff;
1143 	}
1144 	return -1;
1145 }
1146 
1147 static struct page *tcmu_try_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
1148 {
1149 	struct page *page;
1150 	int ret;
1151 
1152 	mutex_lock(&udev->cmdr_lock);
1153 	page = tcmu_get_block_page(udev, dbi);
1154 	if (likely(page)) {
1155 		mutex_unlock(&udev->cmdr_lock);
1156 		return page;
1157 	}
1158 
1159 	/*
1160 	 * Normally it shouldn't be here:
1161 	 * Only when the userspace has touched the blocks which
1162 	 * are out of the tcmu_cmd's data iov[], and will return
1163 	 * one zeroed page.
1164 	 */
1165 	pr_warn("Block(%u) out of cmd's iov[] has been touched!\n", dbi);
1166 	pr_warn("Mostly it will be a bug of userspace, please have a check!\n");
1167 
1168 	if (dbi >= udev->dbi_thresh) {
1169 		/* Extern the udev->dbi_thresh to dbi + 1 */
1170 		udev->dbi_thresh = dbi + 1;
1171 		udev->dbi_max = dbi;
1172 	}
1173 
1174 	page = radix_tree_lookup(&udev->data_blocks, dbi);
1175 	if (!page) {
1176 		page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1177 		if (!page) {
1178 			mutex_unlock(&udev->cmdr_lock);
1179 			return NULL;
1180 		}
1181 
1182 		ret = radix_tree_insert(&udev->data_blocks, dbi, page);
1183 		if (ret) {
1184 			mutex_unlock(&udev->cmdr_lock);
1185 			__free_page(page);
1186 			return NULL;
1187 		}
1188 
1189 		/*
1190 		 * Since this case is rare in page fault routine, here we
1191 		 * will allow the global_db_count >= TCMU_GLOBAL_MAX_BLOCKS
1192 		 * to reduce possible page fault call trace.
1193 		 */
1194 		atomic_inc(&global_db_count);
1195 	}
1196 	mutex_unlock(&udev->cmdr_lock);
1197 
1198 	return page;
1199 }
1200 
1201 static int tcmu_vma_fault(struct vm_fault *vmf)
1202 {
1203 	struct tcmu_dev *udev = vmf->vma->vm_private_data;
1204 	struct uio_info *info = &udev->uio_info;
1205 	struct page *page;
1206 	unsigned long offset;
1207 	void *addr;
1208 
1209 	int mi = tcmu_find_mem_index(vmf->vma);
1210 	if (mi < 0)
1211 		return VM_FAULT_SIGBUS;
1212 
1213 	/*
1214 	 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
1215 	 * to use mem[N].
1216 	 */
1217 	offset = (vmf->pgoff - mi) << PAGE_SHIFT;
1218 
1219 	if (offset < udev->data_off) {
1220 		/* For the vmalloc()ed cmd area pages */
1221 		addr = (void *)(unsigned long)info->mem[mi].addr + offset;
1222 		page = vmalloc_to_page(addr);
1223 	} else {
1224 		uint32_t dbi;
1225 
1226 		/* For the dynamically growing data area pages */
1227 		dbi = (offset - udev->data_off) / DATA_BLOCK_SIZE;
1228 		page = tcmu_try_get_block_page(udev, dbi);
1229 		if (!page)
1230 			return VM_FAULT_NOPAGE;
1231 	}
1232 
1233 	get_page(page);
1234 	vmf->page = page;
1235 	return 0;
1236 }
1237 
1238 static const struct vm_operations_struct tcmu_vm_ops = {
1239 	.fault = tcmu_vma_fault,
1240 };
1241 
1242 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
1243 {
1244 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1245 
1246 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1247 	vma->vm_ops = &tcmu_vm_ops;
1248 
1249 	vma->vm_private_data = udev;
1250 
1251 	/* Ensure the mmap is exactly the right size */
1252 	if (vma_pages(vma) != (TCMU_RING_SIZE >> PAGE_SHIFT))
1253 		return -EINVAL;
1254 
1255 	return 0;
1256 }
1257 
1258 static int tcmu_open(struct uio_info *info, struct inode *inode)
1259 {
1260 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1261 
1262 	/* O_EXCL not supported for char devs, so fake it? */
1263 	if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
1264 		return -EBUSY;
1265 
1266 	udev->inode = inode;
1267 	kref_get(&udev->kref);
1268 
1269 	pr_debug("open\n");
1270 
1271 	return 0;
1272 }
1273 
1274 static void tcmu_dev_call_rcu(struct rcu_head *p)
1275 {
1276 	struct se_device *dev = container_of(p, struct se_device, rcu_head);
1277 	struct tcmu_dev *udev = TCMU_DEV(dev);
1278 
1279 	kfree(udev->uio_info.name);
1280 	kfree(udev->name);
1281 	kfree(udev);
1282 }
1283 
1284 static void tcmu_dev_kref_release(struct kref *kref)
1285 {
1286 	struct tcmu_dev *udev = container_of(kref, struct tcmu_dev, kref);
1287 	struct se_device *dev = &udev->se_dev;
1288 
1289 	call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1290 }
1291 
1292 static int tcmu_release(struct uio_info *info, struct inode *inode)
1293 {
1294 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1295 
1296 	clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
1297 
1298 	pr_debug("close\n");
1299 	/* release ref from open */
1300 	kref_put(&udev->kref, tcmu_dev_kref_release);
1301 	return 0;
1302 }
1303 
1304 static void tcmu_init_genl_cmd_reply(struct tcmu_dev *udev, int cmd)
1305 {
1306 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1307 
1308 	if (!tcmu_kern_cmd_reply_supported)
1309 		return;
1310 relock:
1311 	spin_lock(&udev->nl_cmd_lock);
1312 
1313 	if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
1314 		spin_unlock(&udev->nl_cmd_lock);
1315 		pr_debug("sleeping for open nl cmd\n");
1316 		wait_event(udev->nl_cmd_wq, (nl_cmd->cmd == TCMU_CMD_UNSPEC));
1317 		goto relock;
1318 	}
1319 
1320 	memset(nl_cmd, 0, sizeof(*nl_cmd));
1321 	nl_cmd->cmd = cmd;
1322 	init_completion(&nl_cmd->complete);
1323 
1324 	spin_unlock(&udev->nl_cmd_lock);
1325 }
1326 
1327 static int tcmu_wait_genl_cmd_reply(struct tcmu_dev *udev)
1328 {
1329 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1330 	int ret;
1331 	DEFINE_WAIT(__wait);
1332 
1333 	if (!tcmu_kern_cmd_reply_supported)
1334 		return 0;
1335 
1336 	pr_debug("sleeping for nl reply\n");
1337 	wait_for_completion(&nl_cmd->complete);
1338 
1339 	spin_lock(&udev->nl_cmd_lock);
1340 	nl_cmd->cmd = TCMU_CMD_UNSPEC;
1341 	ret = nl_cmd->status;
1342 	nl_cmd->status = 0;
1343 	spin_unlock(&udev->nl_cmd_lock);
1344 
1345 	wake_up_all(&udev->nl_cmd_wq);
1346 
1347 	return ret;;
1348 }
1349 
1350 static int tcmu_netlink_event(struct tcmu_dev *udev, enum tcmu_genl_cmd cmd,
1351 			      int reconfig_attr, const void *reconfig_data)
1352 {
1353 	struct sk_buff *skb;
1354 	void *msg_header;
1355 	int ret = -ENOMEM;
1356 
1357 	skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1358 	if (!skb)
1359 		return ret;
1360 
1361 	msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
1362 	if (!msg_header)
1363 		goto free_skb;
1364 
1365 	ret = nla_put_string(skb, TCMU_ATTR_DEVICE, udev->uio_info.name);
1366 	if (ret < 0)
1367 		goto free_skb;
1368 
1369 	ret = nla_put_u32(skb, TCMU_ATTR_MINOR, udev->uio_info.uio_dev->minor);
1370 	if (ret < 0)
1371 		goto free_skb;
1372 
1373 	ret = nla_put_u32(skb, TCMU_ATTR_DEVICE_ID, udev->se_dev.dev_index);
1374 	if (ret < 0)
1375 		goto free_skb;
1376 
1377 	if (cmd == TCMU_CMD_RECONFIG_DEVICE) {
1378 		switch (reconfig_attr) {
1379 		case TCMU_ATTR_DEV_CFG:
1380 			ret = nla_put_string(skb, reconfig_attr, reconfig_data);
1381 			break;
1382 		case TCMU_ATTR_DEV_SIZE:
1383 			ret = nla_put_u64_64bit(skb, reconfig_attr,
1384 						*((u64 *)reconfig_data),
1385 						TCMU_ATTR_PAD);
1386 			break;
1387 		case TCMU_ATTR_WRITECACHE:
1388 			ret = nla_put_u8(skb, reconfig_attr,
1389 					  *((u8 *)reconfig_data));
1390 			break;
1391 		default:
1392 			BUG();
1393 		}
1394 
1395 		if (ret < 0)
1396 			goto free_skb;
1397 	}
1398 
1399 	genlmsg_end(skb, msg_header);
1400 
1401 	tcmu_init_genl_cmd_reply(udev, cmd);
1402 
1403 	ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
1404 				TCMU_MCGRP_CONFIG, GFP_KERNEL);
1405 	/* We don't care if no one is listening */
1406 	if (ret == -ESRCH)
1407 		ret = 0;
1408 	if (!ret)
1409 		ret = tcmu_wait_genl_cmd_reply(udev);
1410 
1411 	return ret;
1412 free_skb:
1413 	nlmsg_free(skb);
1414 	return ret;
1415 }
1416 
1417 static int tcmu_update_uio_info(struct tcmu_dev *udev)
1418 {
1419 	struct tcmu_hba *hba = udev->hba->hba_ptr;
1420 	struct uio_info *info;
1421 	size_t size, used;
1422 	char *str;
1423 
1424 	info = &udev->uio_info;
1425 	size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
1426 			udev->dev_config);
1427 	size += 1; /* for \0 */
1428 	str = kmalloc(size, GFP_KERNEL);
1429 	if (!str)
1430 		return -ENOMEM;
1431 
1432 	used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
1433 	if (udev->dev_config[0])
1434 		snprintf(str + used, size - used, "/%s", udev->dev_config);
1435 
1436 	info->name = str;
1437 
1438 	return 0;
1439 }
1440 
1441 static int tcmu_configure_device(struct se_device *dev)
1442 {
1443 	struct tcmu_dev *udev = TCMU_DEV(dev);
1444 	struct uio_info *info;
1445 	struct tcmu_mailbox *mb;
1446 	int ret = 0;
1447 
1448 	ret = tcmu_update_uio_info(udev);
1449 	if (ret)
1450 		return ret;
1451 
1452 	info = &udev->uio_info;
1453 
1454 	udev->mb_addr = vzalloc(CMDR_SIZE);
1455 	if (!udev->mb_addr) {
1456 		ret = -ENOMEM;
1457 		goto err_vzalloc;
1458 	}
1459 
1460 	/* mailbox fits in first part of CMDR space */
1461 	udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
1462 	udev->data_off = CMDR_SIZE;
1463 	udev->data_size = DATA_SIZE;
1464 	udev->dbi_thresh = 0; /* Default in Idle state */
1465 	udev->waiting_global = false;
1466 
1467 	/* Initialise the mailbox of the ring buffer */
1468 	mb = udev->mb_addr;
1469 	mb->version = TCMU_MAILBOX_VERSION;
1470 	mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC;
1471 	mb->cmdr_off = CMDR_OFF;
1472 	mb->cmdr_size = udev->cmdr_size;
1473 
1474 	WARN_ON(!PAGE_ALIGNED(udev->data_off));
1475 	WARN_ON(udev->data_size % PAGE_SIZE);
1476 	WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
1477 
1478 	INIT_RADIX_TREE(&udev->data_blocks, GFP_KERNEL);
1479 
1480 	info->version = __stringify(TCMU_MAILBOX_VERSION);
1481 
1482 	info->mem[0].name = "tcm-user command & data buffer";
1483 	info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
1484 	info->mem[0].size = TCMU_RING_SIZE;
1485 	info->mem[0].memtype = UIO_MEM_NONE;
1486 
1487 	info->irqcontrol = tcmu_irqcontrol;
1488 	info->irq = UIO_IRQ_CUSTOM;
1489 
1490 	info->mmap = tcmu_mmap;
1491 	info->open = tcmu_open;
1492 	info->release = tcmu_release;
1493 
1494 	ret = uio_register_device(tcmu_root_device, info);
1495 	if (ret)
1496 		goto err_register;
1497 
1498 	/* User can set hw_block_size before enable the device */
1499 	if (dev->dev_attrib.hw_block_size == 0)
1500 		dev->dev_attrib.hw_block_size = 512;
1501 	/* Other attributes can be configured in userspace */
1502 	if (!dev->dev_attrib.hw_max_sectors)
1503 		dev->dev_attrib.hw_max_sectors = 128;
1504 	if (!dev->dev_attrib.emulate_write_cache)
1505 		dev->dev_attrib.emulate_write_cache = 0;
1506 	dev->dev_attrib.hw_queue_depth = 128;
1507 
1508 	/*
1509 	 * Get a ref incase userspace does a close on the uio device before
1510 	 * LIO has initiated tcmu_free_device.
1511 	 */
1512 	kref_get(&udev->kref);
1513 
1514 	ret = tcmu_netlink_event(udev, TCMU_CMD_ADDED_DEVICE, 0, NULL);
1515 	if (ret)
1516 		goto err_netlink;
1517 
1518 	mutex_lock(&root_udev_mutex);
1519 	list_add(&udev->node, &root_udev);
1520 	mutex_unlock(&root_udev_mutex);
1521 
1522 	return 0;
1523 
1524 err_netlink:
1525 	kref_put(&udev->kref, tcmu_dev_kref_release);
1526 	uio_unregister_device(&udev->uio_info);
1527 err_register:
1528 	vfree(udev->mb_addr);
1529 err_vzalloc:
1530 	kfree(info->name);
1531 	info->name = NULL;
1532 
1533 	return ret;
1534 }
1535 
1536 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1537 {
1538 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1539 		kmem_cache_free(tcmu_cmd_cache, cmd);
1540 		return 0;
1541 	}
1542 	return -EINVAL;
1543 }
1544 
1545 static bool tcmu_dev_configured(struct tcmu_dev *udev)
1546 {
1547 	return udev->uio_info.uio_dev ? true : false;
1548 }
1549 
1550 static void tcmu_blocks_release(struct tcmu_dev *udev)
1551 {
1552 	int i;
1553 	struct page *page;
1554 
1555 	/* Try to release all block pages */
1556 	mutex_lock(&udev->cmdr_lock);
1557 	for (i = 0; i <= udev->dbi_max; i++) {
1558 		page = radix_tree_delete(&udev->data_blocks, i);
1559 		if (page) {
1560 			__free_page(page);
1561 			atomic_dec(&global_db_count);
1562 		}
1563 	}
1564 	mutex_unlock(&udev->cmdr_lock);
1565 }
1566 
1567 static void tcmu_free_device(struct se_device *dev)
1568 {
1569 	struct tcmu_dev *udev = TCMU_DEV(dev);
1570 
1571 	/* release ref from init */
1572 	kref_put(&udev->kref, tcmu_dev_kref_release);
1573 }
1574 
1575 static void tcmu_destroy_device(struct se_device *dev)
1576 {
1577 	struct tcmu_dev *udev = TCMU_DEV(dev);
1578 	struct tcmu_cmd *cmd;
1579 	bool all_expired = true;
1580 	int i;
1581 
1582 	del_timer_sync(&udev->timeout);
1583 
1584 	mutex_lock(&root_udev_mutex);
1585 	list_del(&udev->node);
1586 	mutex_unlock(&root_udev_mutex);
1587 
1588 	vfree(udev->mb_addr);
1589 
1590 	/* Upper layer should drain all requests before calling this */
1591 	spin_lock_irq(&udev->commands_lock);
1592 	idr_for_each_entry(&udev->commands, cmd, i) {
1593 		if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1594 			all_expired = false;
1595 	}
1596 	idr_destroy(&udev->commands);
1597 	spin_unlock_irq(&udev->commands_lock);
1598 	WARN_ON(!all_expired);
1599 
1600 	tcmu_blocks_release(udev);
1601 
1602 	tcmu_netlink_event(udev, TCMU_CMD_REMOVED_DEVICE, 0, NULL);
1603 
1604 	uio_unregister_device(&udev->uio_info);
1605 
1606 	/* release ref from configure */
1607 	kref_put(&udev->kref, tcmu_dev_kref_release);
1608 }
1609 
1610 enum {
1611 	Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
1612 	Opt_err,
1613 };
1614 
1615 static match_table_t tokens = {
1616 	{Opt_dev_config, "dev_config=%s"},
1617 	{Opt_dev_size, "dev_size=%u"},
1618 	{Opt_hw_block_size, "hw_block_size=%u"},
1619 	{Opt_hw_max_sectors, "hw_max_sectors=%u"},
1620 	{Opt_err, NULL}
1621 };
1622 
1623 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
1624 {
1625 	unsigned long tmp_ul;
1626 	char *arg_p;
1627 	int ret;
1628 
1629 	arg_p = match_strdup(arg);
1630 	if (!arg_p)
1631 		return -ENOMEM;
1632 
1633 	ret = kstrtoul(arg_p, 0, &tmp_ul);
1634 	kfree(arg_p);
1635 	if (ret < 0) {
1636 		pr_err("kstrtoul() failed for dev attrib\n");
1637 		return ret;
1638 	}
1639 	if (!tmp_ul) {
1640 		pr_err("dev attrib must be nonzero\n");
1641 		return -EINVAL;
1642 	}
1643 	*dev_attrib = tmp_ul;
1644 	return 0;
1645 }
1646 
1647 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
1648 		const char *page, ssize_t count)
1649 {
1650 	struct tcmu_dev *udev = TCMU_DEV(dev);
1651 	char *orig, *ptr, *opts, *arg_p;
1652 	substring_t args[MAX_OPT_ARGS];
1653 	int ret = 0, token;
1654 
1655 	opts = kstrdup(page, GFP_KERNEL);
1656 	if (!opts)
1657 		return -ENOMEM;
1658 
1659 	orig = opts;
1660 
1661 	while ((ptr = strsep(&opts, ",\n")) != NULL) {
1662 		if (!*ptr)
1663 			continue;
1664 
1665 		token = match_token(ptr, tokens, args);
1666 		switch (token) {
1667 		case Opt_dev_config:
1668 			if (match_strlcpy(udev->dev_config, &args[0],
1669 					  TCMU_CONFIG_LEN) == 0) {
1670 				ret = -EINVAL;
1671 				break;
1672 			}
1673 			pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
1674 			break;
1675 		case Opt_dev_size:
1676 			arg_p = match_strdup(&args[0]);
1677 			if (!arg_p) {
1678 				ret = -ENOMEM;
1679 				break;
1680 			}
1681 			ret = kstrtoul(arg_p, 0, (unsigned long *) &udev->dev_size);
1682 			kfree(arg_p);
1683 			if (ret < 0)
1684 				pr_err("kstrtoul() failed for dev_size=\n");
1685 			break;
1686 		case Opt_hw_block_size:
1687 			ret = tcmu_set_dev_attrib(&args[0],
1688 					&(dev->dev_attrib.hw_block_size));
1689 			break;
1690 		case Opt_hw_max_sectors:
1691 			ret = tcmu_set_dev_attrib(&args[0],
1692 					&(dev->dev_attrib.hw_max_sectors));
1693 			break;
1694 		default:
1695 			break;
1696 		}
1697 
1698 		if (ret)
1699 			break;
1700 	}
1701 
1702 	kfree(orig);
1703 	return (!ret) ? count : ret;
1704 }
1705 
1706 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
1707 {
1708 	struct tcmu_dev *udev = TCMU_DEV(dev);
1709 	ssize_t bl = 0;
1710 
1711 	bl = sprintf(b + bl, "Config: %s ",
1712 		     udev->dev_config[0] ? udev->dev_config : "NULL");
1713 	bl += sprintf(b + bl, "Size: %zu\n", udev->dev_size);
1714 
1715 	return bl;
1716 }
1717 
1718 static sector_t tcmu_get_blocks(struct se_device *dev)
1719 {
1720 	struct tcmu_dev *udev = TCMU_DEV(dev);
1721 
1722 	return div_u64(udev->dev_size - dev->dev_attrib.block_size,
1723 		       dev->dev_attrib.block_size);
1724 }
1725 
1726 static sense_reason_t
1727 tcmu_parse_cdb(struct se_cmd *cmd)
1728 {
1729 	return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
1730 }
1731 
1732 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
1733 {
1734 	struct se_dev_attrib *da = container_of(to_config_group(item),
1735 					struct se_dev_attrib, da_group);
1736 	struct tcmu_dev *udev = container_of(da->da_dev,
1737 					struct tcmu_dev, se_dev);
1738 
1739 	return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
1740 }
1741 
1742 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
1743 				       size_t count)
1744 {
1745 	struct se_dev_attrib *da = container_of(to_config_group(item),
1746 					struct se_dev_attrib, da_group);
1747 	struct tcmu_dev *udev = container_of(da->da_dev,
1748 					struct tcmu_dev, se_dev);
1749 	u32 val;
1750 	int ret;
1751 
1752 	if (da->da_dev->export_count) {
1753 		pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
1754 		return -EINVAL;
1755 	}
1756 
1757 	ret = kstrtou32(page, 0, &val);
1758 	if (ret < 0)
1759 		return ret;
1760 
1761 	udev->cmd_time_out = val * MSEC_PER_SEC;
1762 	return count;
1763 }
1764 CONFIGFS_ATTR(tcmu_, cmd_time_out);
1765 
1766 static ssize_t tcmu_dev_config_show(struct config_item *item, char *page)
1767 {
1768 	struct se_dev_attrib *da = container_of(to_config_group(item),
1769 						struct se_dev_attrib, da_group);
1770 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1771 
1772 	return snprintf(page, PAGE_SIZE, "%s\n", udev->dev_config);
1773 }
1774 
1775 static ssize_t tcmu_dev_config_store(struct config_item *item, const char *page,
1776 				     size_t count)
1777 {
1778 	struct se_dev_attrib *da = container_of(to_config_group(item),
1779 						struct se_dev_attrib, da_group);
1780 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1781 	int ret, len;
1782 
1783 	len = strlen(page);
1784 	if (!len || len > TCMU_CONFIG_LEN - 1)
1785 		return -EINVAL;
1786 
1787 	/* Check if device has been configured before */
1788 	if (tcmu_dev_configured(udev)) {
1789 		ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1790 					 TCMU_ATTR_DEV_CFG, page);
1791 		if (ret) {
1792 			pr_err("Unable to reconfigure device\n");
1793 			return ret;
1794 		}
1795 		strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
1796 
1797 		ret = tcmu_update_uio_info(udev);
1798 		if (ret)
1799 			return ret;
1800 		return count;
1801 	}
1802 	strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
1803 
1804 	return count;
1805 }
1806 CONFIGFS_ATTR(tcmu_, dev_config);
1807 
1808 static ssize_t tcmu_dev_size_show(struct config_item *item, char *page)
1809 {
1810 	struct se_dev_attrib *da = container_of(to_config_group(item),
1811 						struct se_dev_attrib, da_group);
1812 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1813 
1814 	return snprintf(page, PAGE_SIZE, "%zu\n", udev->dev_size);
1815 }
1816 
1817 static ssize_t tcmu_dev_size_store(struct config_item *item, const char *page,
1818 				   size_t count)
1819 {
1820 	struct se_dev_attrib *da = container_of(to_config_group(item),
1821 						struct se_dev_attrib, da_group);
1822 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1823 	u64 val;
1824 	int ret;
1825 
1826 	ret = kstrtou64(page, 0, &val);
1827 	if (ret < 0)
1828 		return ret;
1829 
1830 	/* Check if device has been configured before */
1831 	if (tcmu_dev_configured(udev)) {
1832 		ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1833 					 TCMU_ATTR_DEV_SIZE, &val);
1834 		if (ret) {
1835 			pr_err("Unable to reconfigure device\n");
1836 			return ret;
1837 		}
1838 	}
1839 	udev->dev_size = val;
1840 	return count;
1841 }
1842 CONFIGFS_ATTR(tcmu_, dev_size);
1843 
1844 static ssize_t tcmu_emulate_write_cache_show(struct config_item *item,
1845 					     char *page)
1846 {
1847 	struct se_dev_attrib *da = container_of(to_config_group(item),
1848 					struct se_dev_attrib, da_group);
1849 
1850 	return snprintf(page, PAGE_SIZE, "%i\n", da->emulate_write_cache);
1851 }
1852 
1853 static ssize_t tcmu_emulate_write_cache_store(struct config_item *item,
1854 					      const char *page, size_t count)
1855 {
1856 	struct se_dev_attrib *da = container_of(to_config_group(item),
1857 					struct se_dev_attrib, da_group);
1858 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1859 	u8 val;
1860 	int ret;
1861 
1862 	ret = kstrtou8(page, 0, &val);
1863 	if (ret < 0)
1864 		return ret;
1865 
1866 	/* Check if device has been configured before */
1867 	if (tcmu_dev_configured(udev)) {
1868 		ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1869 					 TCMU_ATTR_WRITECACHE, &val);
1870 		if (ret) {
1871 			pr_err("Unable to reconfigure device\n");
1872 			return ret;
1873 		}
1874 	}
1875 
1876 	da->emulate_write_cache = val;
1877 	return count;
1878 }
1879 CONFIGFS_ATTR(tcmu_, emulate_write_cache);
1880 
1881 static struct configfs_attribute *tcmu_attrib_attrs[] = {
1882 	&tcmu_attr_cmd_time_out,
1883 	&tcmu_attr_dev_config,
1884 	&tcmu_attr_dev_size,
1885 	&tcmu_attr_emulate_write_cache,
1886 	NULL,
1887 };
1888 
1889 static struct configfs_attribute **tcmu_attrs;
1890 
1891 static struct target_backend_ops tcmu_ops = {
1892 	.name			= "user",
1893 	.owner			= THIS_MODULE,
1894 	.transport_flags	= TRANSPORT_FLAG_PASSTHROUGH,
1895 	.attach_hba		= tcmu_attach_hba,
1896 	.detach_hba		= tcmu_detach_hba,
1897 	.alloc_device		= tcmu_alloc_device,
1898 	.configure_device	= tcmu_configure_device,
1899 	.destroy_device		= tcmu_destroy_device,
1900 	.free_device		= tcmu_free_device,
1901 	.parse_cdb		= tcmu_parse_cdb,
1902 	.set_configfs_dev_params = tcmu_set_configfs_dev_params,
1903 	.show_configfs_dev_params = tcmu_show_configfs_dev_params,
1904 	.get_device_type	= sbc_get_device_type,
1905 	.get_blocks		= tcmu_get_blocks,
1906 	.tb_dev_attrib_attrs	= NULL,
1907 };
1908 
1909 static int unmap_thread_fn(void *data)
1910 {
1911 	struct tcmu_dev *udev;
1912 	loff_t off;
1913 	uint32_t start, end, block;
1914 	struct page *page;
1915 	int i;
1916 
1917 	while (!kthread_should_stop()) {
1918 		DEFINE_WAIT(__wait);
1919 
1920 		prepare_to_wait(&unmap_wait, &__wait, TASK_INTERRUPTIBLE);
1921 		schedule();
1922 		finish_wait(&unmap_wait, &__wait);
1923 
1924 		if (kthread_should_stop())
1925 			break;
1926 
1927 		mutex_lock(&root_udev_mutex);
1928 		list_for_each_entry(udev, &root_udev, node) {
1929 			mutex_lock(&udev->cmdr_lock);
1930 
1931 			/* Try to complete the finished commands first */
1932 			tcmu_handle_completions(udev);
1933 
1934 			/* Skip the udevs waiting the global pool or in idle */
1935 			if (udev->waiting_global || !udev->dbi_thresh) {
1936 				mutex_unlock(&udev->cmdr_lock);
1937 				continue;
1938 			}
1939 
1940 			end = udev->dbi_max + 1;
1941 			block = find_last_bit(udev->data_bitmap, end);
1942 			if (block == udev->dbi_max) {
1943 				/*
1944 				 * The last bit is dbi_max, so there is
1945 				 * no need to shrink any blocks.
1946 				 */
1947 				mutex_unlock(&udev->cmdr_lock);
1948 				continue;
1949 			} else if (block == end) {
1950 				/* The current udev will goto idle state */
1951 				udev->dbi_thresh = start = 0;
1952 				udev->dbi_max = 0;
1953 			} else {
1954 				udev->dbi_thresh = start = block + 1;
1955 				udev->dbi_max = block;
1956 			}
1957 
1958 			/* Here will truncate the data area from off */
1959 			off = udev->data_off + start * DATA_BLOCK_SIZE;
1960 			unmap_mapping_range(udev->inode->i_mapping, off, 0, 1);
1961 
1962 			/* Release the block pages */
1963 			for (i = start; i < end; i++) {
1964 				page = radix_tree_delete(&udev->data_blocks, i);
1965 				if (page) {
1966 					__free_page(page);
1967 					atomic_dec(&global_db_count);
1968 				}
1969 			}
1970 			mutex_unlock(&udev->cmdr_lock);
1971 		}
1972 
1973 		/*
1974 		 * Try to wake up the udevs who are waiting
1975 		 * for the global data pool.
1976 		 */
1977 		list_for_each_entry(udev, &root_udev, node) {
1978 			if (udev->waiting_global)
1979 				wake_up(&udev->wait_cmdr);
1980 		}
1981 		mutex_unlock(&root_udev_mutex);
1982 	}
1983 
1984 	return 0;
1985 }
1986 
1987 static int __init tcmu_module_init(void)
1988 {
1989 	int ret, i, k, len = 0;
1990 
1991 	BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
1992 
1993 	tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
1994 				sizeof(struct tcmu_cmd),
1995 				__alignof__(struct tcmu_cmd),
1996 				0, NULL);
1997 	if (!tcmu_cmd_cache)
1998 		return -ENOMEM;
1999 
2000 	tcmu_root_device = root_device_register("tcm_user");
2001 	if (IS_ERR(tcmu_root_device)) {
2002 		ret = PTR_ERR(tcmu_root_device);
2003 		goto out_free_cache;
2004 	}
2005 
2006 	ret = genl_register_family(&tcmu_genl_family);
2007 	if (ret < 0) {
2008 		goto out_unreg_device;
2009 	}
2010 
2011 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2012 		len += sizeof(struct configfs_attribute *);
2013 	}
2014 	for (i = 0; tcmu_attrib_attrs[i] != NULL; i++) {
2015 		len += sizeof(struct configfs_attribute *);
2016 	}
2017 	len += sizeof(struct configfs_attribute *);
2018 
2019 	tcmu_attrs = kzalloc(len, GFP_KERNEL);
2020 	if (!tcmu_attrs) {
2021 		ret = -ENOMEM;
2022 		goto out_unreg_genl;
2023 	}
2024 
2025 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2026 		tcmu_attrs[i] = passthrough_attrib_attrs[i];
2027 	}
2028 	for (k = 0; tcmu_attrib_attrs[k] != NULL; k++) {
2029 		tcmu_attrs[i] = tcmu_attrib_attrs[k];
2030 		i++;
2031 	}
2032 	tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
2033 
2034 	ret = transport_backend_register(&tcmu_ops);
2035 	if (ret)
2036 		goto out_attrs;
2037 
2038 	init_waitqueue_head(&unmap_wait);
2039 	unmap_thread = kthread_run(unmap_thread_fn, NULL, "tcmu_unmap");
2040 	if (IS_ERR(unmap_thread)) {
2041 		ret = PTR_ERR(unmap_thread);
2042 		goto out_unreg_transport;
2043 	}
2044 
2045 	return 0;
2046 
2047 out_unreg_transport:
2048 	target_backend_unregister(&tcmu_ops);
2049 out_attrs:
2050 	kfree(tcmu_attrs);
2051 out_unreg_genl:
2052 	genl_unregister_family(&tcmu_genl_family);
2053 out_unreg_device:
2054 	root_device_unregister(tcmu_root_device);
2055 out_free_cache:
2056 	kmem_cache_destroy(tcmu_cmd_cache);
2057 
2058 	return ret;
2059 }
2060 
2061 static void __exit tcmu_module_exit(void)
2062 {
2063 	kthread_stop(unmap_thread);
2064 	target_backend_unregister(&tcmu_ops);
2065 	kfree(tcmu_attrs);
2066 	genl_unregister_family(&tcmu_genl_family);
2067 	root_device_unregister(tcmu_root_device);
2068 	kmem_cache_destroy(tcmu_cmd_cache);
2069 }
2070 
2071 MODULE_DESCRIPTION("TCM USER subsystem plugin");
2072 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
2073 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
2074 MODULE_LICENSE("GPL");
2075 
2076 module_init(tcmu_module_init);
2077 module_exit(tcmu_module_exit);
2078