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