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