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 	if (tcmu_cmd->se_cmd)
566 		tcmu_cmd->se_cmd->priv = NULL;
567 	kfree(tcmu_cmd->dbi);
568 	kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
569 }
570 
571 static inline void tcmu_cmd_set_block_cnts(struct tcmu_cmd *cmd)
572 {
573 	int i, len;
574 	struct se_cmd *se_cmd = cmd->se_cmd;
575 
576 	cmd->dbi_cnt = DIV_ROUND_UP(se_cmd->data_length, DATA_BLOCK_SIZE);
577 
578 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
579 		BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
580 		for (i = 0, len = 0; i < se_cmd->t_bidi_data_nents; i++)
581 			len += se_cmd->t_bidi_data_sg[i].length;
582 		cmd->dbi_bidi_cnt = DIV_ROUND_UP(len, DATA_BLOCK_SIZE);
583 		cmd->dbi_cnt += cmd->dbi_bidi_cnt;
584 		cmd->data_len_bidi = len;
585 	}
586 }
587 
588 static int new_block_to_iov(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
589 			    struct iovec **iov, int prev_dbi, int len)
590 {
591 	/* Get the next dbi */
592 	int dbi = tcmu_cmd_get_dbi(cmd);
593 
594 	/* Do not add more than DATA_BLOCK_SIZE to iov */
595 	if (len > DATA_BLOCK_SIZE)
596 		len = DATA_BLOCK_SIZE;
597 
598 	/*
599 	 * The following code will gather and map the blocks to the same iovec
600 	 * when the blocks are all next to each other.
601 	 */
602 	if (dbi != prev_dbi + 1) {
603 		/* dbi is not next to previous dbi, so start new iov */
604 		if (prev_dbi >= 0)
605 			(*iov)++;
606 		/* write offset relative to mb_addr */
607 		(*iov)->iov_base = (void __user *)
608 				(udev->data_off + dbi * DATA_BLOCK_SIZE);
609 	}
610 	(*iov)->iov_len += len;
611 
612 	return dbi;
613 }
614 
615 static void tcmu_setup_iovs(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
616 			    struct iovec **iov, int data_length)
617 {
618 	/* start value of dbi + 1 must not be a valid dbi */
619 	int dbi = -2;
620 
621 	/* We prepare the IOVs for DMA_FROM_DEVICE transfer direction */
622 	for (; data_length > 0; data_length -= DATA_BLOCK_SIZE)
623 		dbi = new_block_to_iov(udev, cmd, iov, dbi, data_length);
624 }
625 
626 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
627 {
628 	struct se_device *se_dev = se_cmd->se_dev;
629 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
630 	struct tcmu_cmd *tcmu_cmd;
631 
632 	tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_NOIO);
633 	if (!tcmu_cmd)
634 		return NULL;
635 
636 	INIT_LIST_HEAD(&tcmu_cmd->queue_entry);
637 	tcmu_cmd->se_cmd = se_cmd;
638 	tcmu_cmd->tcmu_dev = udev;
639 
640 	tcmu_cmd_set_block_cnts(tcmu_cmd);
641 	tcmu_cmd->dbi = kcalloc(tcmu_cmd->dbi_cnt, sizeof(uint32_t),
642 				GFP_NOIO);
643 	if (!tcmu_cmd->dbi) {
644 		kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
645 		return NULL;
646 	}
647 
648 	return tcmu_cmd;
649 }
650 
651 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
652 {
653 	unsigned long offset = offset_in_page(vaddr);
654 	void *start = vaddr - offset;
655 
656 	size = round_up(size+offset, PAGE_SIZE);
657 
658 	while (size) {
659 		flush_dcache_page(vmalloc_to_page(start));
660 		start += PAGE_SIZE;
661 		size -= PAGE_SIZE;
662 	}
663 }
664 
665 /*
666  * Some ring helper functions. We don't assume size is a power of 2 so
667  * we can't use circ_buf.h.
668  */
669 static inline size_t spc_used(size_t head, size_t tail, size_t size)
670 {
671 	int diff = head - tail;
672 
673 	if (diff >= 0)
674 		return diff;
675 	else
676 		return size + diff;
677 }
678 
679 static inline size_t spc_free(size_t head, size_t tail, size_t size)
680 {
681 	/* Keep 1 byte unused or we can't tell full from empty */
682 	return (size - spc_used(head, tail, size) - 1);
683 }
684 
685 static inline size_t head_to_end(size_t head, size_t size)
686 {
687 	return size - head;
688 }
689 
690 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
691 
692 #define TCMU_SG_TO_DATA_AREA 1
693 #define TCMU_DATA_AREA_TO_SG 2
694 
695 static inline void tcmu_copy_data(struct tcmu_dev *udev,
696 				  struct tcmu_cmd *tcmu_cmd, uint32_t direction,
697 				  struct scatterlist *sg, unsigned int sg_nents,
698 				  struct iovec **iov, size_t data_len)
699 {
700 	/* start value of dbi + 1 must not be a valid dbi */
701 	int dbi = -2;
702 	size_t block_remaining, cp_len;
703 	struct sg_mapping_iter sg_iter;
704 	unsigned int sg_flags;
705 	struct page *page;
706 	void *data_page_start, *data_addr;
707 
708 	if (direction == TCMU_SG_TO_DATA_AREA)
709 		sg_flags = SG_MITER_ATOMIC | SG_MITER_FROM_SG;
710 	else
711 		sg_flags = SG_MITER_ATOMIC | SG_MITER_TO_SG;
712 	sg_miter_start(&sg_iter, sg, sg_nents, sg_flags);
713 
714 	while (data_len) {
715 		if (direction == TCMU_SG_TO_DATA_AREA)
716 			dbi = new_block_to_iov(udev, tcmu_cmd, iov, dbi,
717 					       data_len);
718 		else
719 			dbi = tcmu_cmd_get_dbi(tcmu_cmd);
720 		page = tcmu_get_block_page(udev, dbi);
721 		if (direction == TCMU_DATA_AREA_TO_SG)
722 			flush_dcache_page(page);
723 		data_page_start = kmap_atomic(page);
724 		block_remaining = DATA_BLOCK_SIZE;
725 
726 		while (block_remaining && data_len) {
727 			if (!sg_miter_next(&sg_iter)) {
728 				/* set length to 0 to abort outer loop */
729 				data_len = 0;
730 				pr_debug("tcmu_move_data: aborting data copy due to exhausted sg_list\n");
731 				break;
732 			}
733 			cp_len = min3(sg_iter.length, block_remaining, data_len);
734 
735 			data_addr = data_page_start +
736 				    DATA_BLOCK_SIZE - block_remaining;
737 			if (direction == TCMU_SG_TO_DATA_AREA)
738 				memcpy(data_addr, sg_iter.addr, cp_len);
739 			else
740 				memcpy(sg_iter.addr, data_addr, cp_len);
741 
742 			data_len -= cp_len;
743 			block_remaining -= cp_len;
744 			sg_iter.consumed = cp_len;
745 		}
746 		sg_miter_stop(&sg_iter);
747 
748 		kunmap_atomic(data_page_start);
749 		if (direction == TCMU_SG_TO_DATA_AREA)
750 			flush_dcache_page(page);
751 	}
752 }
753 
754 static void scatter_data_area(struct tcmu_dev *udev, struct tcmu_cmd *tcmu_cmd,
755 			      struct iovec **iov)
756 {
757 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
758 
759 	tcmu_copy_data(udev, tcmu_cmd, TCMU_SG_TO_DATA_AREA, se_cmd->t_data_sg,
760 		       se_cmd->t_data_nents, iov, se_cmd->data_length);
761 }
762 
763 static void gather_data_area(struct tcmu_dev *udev, struct tcmu_cmd *tcmu_cmd,
764 			     bool bidi, uint32_t read_len)
765 {
766 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
767 	struct scatterlist *data_sg;
768 	unsigned int data_nents;
769 
770 	if (!bidi) {
771 		data_sg = se_cmd->t_data_sg;
772 		data_nents = se_cmd->t_data_nents;
773 	} else {
774 		/*
775 		 * For bidi case, the first count blocks are for Data-Out
776 		 * buffer blocks, and before gathering the Data-In buffer
777 		 * the Data-Out buffer blocks should be skipped.
778 		 */
779 		tcmu_cmd_set_dbi_cur(tcmu_cmd,
780 				     tcmu_cmd->dbi_cnt - tcmu_cmd->dbi_bidi_cnt);
781 
782 		data_sg = se_cmd->t_bidi_data_sg;
783 		data_nents = se_cmd->t_bidi_data_nents;
784 	}
785 
786 	tcmu_copy_data(udev, tcmu_cmd, TCMU_DATA_AREA_TO_SG, data_sg,
787 		       data_nents, NULL, read_len);
788 }
789 
790 static inline size_t spc_bitmap_free(unsigned long *bitmap, uint32_t thresh)
791 {
792 	return thresh - bitmap_weight(bitmap, thresh);
793 }
794 
795 /*
796  * We can't queue a command until we have space available on the cmd ring.
797  *
798  * Called with ring lock held.
799  */
800 static bool is_ring_space_avail(struct tcmu_dev *udev, size_t cmd_size)
801 {
802 	struct tcmu_mailbox *mb = udev->mb_addr;
803 	size_t space, cmd_needed;
804 	u32 cmd_head;
805 
806 	tcmu_flush_dcache_range(mb, sizeof(*mb));
807 
808 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
809 
810 	/*
811 	 * If cmd end-of-ring space is too small then we need space for a NOP plus
812 	 * original cmd - cmds are internally contiguous.
813 	 */
814 	if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
815 		cmd_needed = cmd_size;
816 	else
817 		cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
818 
819 	space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
820 	if (space < cmd_needed) {
821 		pr_debug("no cmd space: %u %u %u\n", cmd_head,
822 		       udev->cmdr_last_cleaned, udev->cmdr_size);
823 		return false;
824 	}
825 	return true;
826 }
827 
828 /*
829  * We have to allocate data buffers before we can queue a command.
830  * Returns -1 on error (not enough space) or number of needed iovs on success
831  *
832  * Called with ring lock held.
833  */
834 static int tcmu_alloc_data_space(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
835 				  int *iov_bidi_cnt)
836 {
837 	int space, iov_cnt = 0, ret = 0;
838 
839 	if (!cmd->dbi_cnt)
840 		goto wr_iov_cnts;
841 
842 	/* try to check and get the data blocks as needed */
843 	space = spc_bitmap_free(udev->data_bitmap, udev->dbi_thresh);
844 	if (space < cmd->dbi_cnt) {
845 		unsigned long blocks_left =
846 				(udev->max_blocks - udev->dbi_thresh) + space;
847 
848 		if (blocks_left < cmd->dbi_cnt) {
849 			pr_debug("no data space: only %lu available, but ask for %lu\n",
850 					blocks_left * DATA_BLOCK_SIZE,
851 					cmd->dbi_cnt * DATA_BLOCK_SIZE);
852 			return -1;
853 		}
854 
855 		udev->dbi_thresh += cmd->dbi_cnt;
856 		if (udev->dbi_thresh > udev->max_blocks)
857 			udev->dbi_thresh = udev->max_blocks;
858 	}
859 
860 	iov_cnt = tcmu_get_empty_blocks(udev, cmd,
861 					cmd->dbi_cnt - cmd->dbi_bidi_cnt);
862 	if (iov_cnt < 0)
863 		return -1;
864 
865 	if (cmd->dbi_bidi_cnt) {
866 		ret = tcmu_get_empty_blocks(udev, cmd, cmd->dbi_bidi_cnt);
867 		if (ret < 0)
868 			return -1;
869 	}
870 wr_iov_cnts:
871 	*iov_bidi_cnt = ret;
872 	return iov_cnt + ret;
873 }
874 
875 static inline size_t tcmu_cmd_get_base_cmd_size(size_t iov_cnt)
876 {
877 	return max(offsetof(struct tcmu_cmd_entry, req.iov[iov_cnt]),
878 			sizeof(struct tcmu_cmd_entry));
879 }
880 
881 static inline size_t tcmu_cmd_get_cmd_size(struct tcmu_cmd *tcmu_cmd,
882 					   size_t base_command_size)
883 {
884 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
885 	size_t command_size;
886 
887 	command_size = base_command_size +
888 		round_up(scsi_command_size(se_cmd->t_task_cdb),
889 				TCMU_OP_ALIGN_SIZE);
890 
891 	WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
892 
893 	return command_size;
894 }
895 
896 static void tcmu_setup_cmd_timer(struct tcmu_cmd *tcmu_cmd, unsigned int tmo,
897 				 struct timer_list *timer)
898 {
899 	if (!tmo)
900 		return;
901 
902 	tcmu_cmd->deadline = round_jiffies_up(jiffies + msecs_to_jiffies(tmo));
903 	if (!timer_pending(timer))
904 		mod_timer(timer, tcmu_cmd->deadline);
905 
906 	pr_debug("Timeout set up for cmd %p, dev = %s, tmo = %lu\n", tcmu_cmd,
907 		 tcmu_cmd->tcmu_dev->name, tmo / MSEC_PER_SEC);
908 }
909 
910 static int add_to_qfull_queue(struct tcmu_cmd *tcmu_cmd)
911 {
912 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
913 	unsigned int tmo;
914 
915 	/*
916 	 * For backwards compat if qfull_time_out is not set use
917 	 * cmd_time_out and if that's not set use the default time out.
918 	 */
919 	if (!udev->qfull_time_out)
920 		return -ETIMEDOUT;
921 	else if (udev->qfull_time_out > 0)
922 		tmo = udev->qfull_time_out;
923 	else if (udev->cmd_time_out)
924 		tmo = udev->cmd_time_out;
925 	else
926 		tmo = TCMU_TIME_OUT;
927 
928 	tcmu_setup_cmd_timer(tcmu_cmd, tmo, &udev->qfull_timer);
929 
930 	list_add_tail(&tcmu_cmd->queue_entry, &udev->qfull_queue);
931 	pr_debug("adding cmd %p on dev %s to ring space wait queue\n",
932 		 tcmu_cmd, udev->name);
933 	return 0;
934 }
935 
936 static uint32_t ring_insert_padding(struct tcmu_dev *udev, size_t cmd_size)
937 {
938 	struct tcmu_cmd_entry_hdr *hdr;
939 	struct tcmu_mailbox *mb = udev->mb_addr;
940 	uint32_t cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
941 
942 	/* Insert a PAD if end-of-ring space is too small */
943 	if (head_to_end(cmd_head, udev->cmdr_size) < cmd_size) {
944 		size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
945 
946 		hdr = (void *) mb + CMDR_OFF + cmd_head;
947 		tcmu_hdr_set_op(&hdr->len_op, TCMU_OP_PAD);
948 		tcmu_hdr_set_len(&hdr->len_op, pad_size);
949 		hdr->cmd_id = 0; /* not used for PAD */
950 		hdr->kflags = 0;
951 		hdr->uflags = 0;
952 		tcmu_flush_dcache_range(hdr, sizeof(*hdr));
953 
954 		UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
955 		tcmu_flush_dcache_range(mb, sizeof(*mb));
956 
957 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
958 		WARN_ON(cmd_head != 0);
959 	}
960 
961 	return cmd_head;
962 }
963 
964 /**
965  * queue_cmd_ring - queue cmd to ring or internally
966  * @tcmu_cmd: cmd to queue
967  * @scsi_err: TCM error code if failure (-1) returned.
968  *
969  * Returns:
970  * -1 we cannot queue internally or to the ring.
971  *  0 success
972  *  1 internally queued to wait for ring memory to free.
973  */
974 static int queue_cmd_ring(struct tcmu_cmd *tcmu_cmd, sense_reason_t *scsi_err)
975 {
976 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
977 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
978 	size_t base_command_size, command_size;
979 	struct tcmu_mailbox *mb = udev->mb_addr;
980 	struct tcmu_cmd_entry *entry;
981 	struct iovec *iov;
982 	int iov_cnt, iov_bidi_cnt, cmd_id;
983 	uint32_t cmd_head;
984 	uint64_t cdb_off;
985 	/* size of data buffer needed */
986 	size_t data_length = (size_t)tcmu_cmd->dbi_cnt * DATA_BLOCK_SIZE;
987 
988 	*scsi_err = TCM_NO_SENSE;
989 
990 	if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags)) {
991 		*scsi_err = TCM_LUN_BUSY;
992 		return -1;
993 	}
994 
995 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
996 		*scsi_err = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
997 		return -1;
998 	}
999 
1000 	if (!list_empty(&udev->qfull_queue))
1001 		goto queue;
1002 
1003 	if (data_length > udev->data_size) {
1004 		pr_warn("TCMU: Request of size %zu is too big for %zu data area\n",
1005 			data_length, udev->data_size);
1006 		*scsi_err = TCM_INVALID_CDB_FIELD;
1007 		return -1;
1008 	}
1009 
1010 	iov_cnt = tcmu_alloc_data_space(udev, tcmu_cmd, &iov_bidi_cnt);
1011 	if (iov_cnt < 0)
1012 		goto free_and_queue;
1013 
1014 	/*
1015 	 * Must be a certain minimum size for response sense info, but
1016 	 * also may be larger if the iov array is large.
1017 	 */
1018 	base_command_size = tcmu_cmd_get_base_cmd_size(iov_cnt);
1019 	command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
1020 
1021 	if (command_size > (udev->cmdr_size / 2)) {
1022 		pr_warn("TCMU: Request of size %zu is too big for %u cmd ring\n",
1023 			command_size, udev->cmdr_size);
1024 		tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
1025 		*scsi_err = TCM_INVALID_CDB_FIELD;
1026 		return -1;
1027 	}
1028 
1029 	if (!is_ring_space_avail(udev, command_size))
1030 		/*
1031 		 * Don't leave commands partially setup because the unmap
1032 		 * thread might need the blocks to make forward progress.
1033 		 */
1034 		goto free_and_queue;
1035 
1036 	cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 1, USHRT_MAX, GFP_NOWAIT);
1037 	if (cmd_id < 0) {
1038 		pr_err("tcmu: Could not allocate cmd id.\n");
1039 
1040 		tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
1041 		*scsi_err = TCM_OUT_OF_RESOURCES;
1042 		return -1;
1043 	}
1044 	tcmu_cmd->cmd_id = cmd_id;
1045 
1046 	pr_debug("allocated cmd id %u for cmd %p dev %s\n", tcmu_cmd->cmd_id,
1047 		 tcmu_cmd, udev->name);
1048 
1049 	cmd_head = ring_insert_padding(udev, command_size);
1050 
1051 	entry = (void *) mb + CMDR_OFF + cmd_head;
1052 	memset(entry, 0, command_size);
1053 	tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
1054 
1055 	/* prepare iov list and copy data to data area if necessary */
1056 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1057 	iov = &entry->req.iov[0];
1058 
1059 	if (se_cmd->data_direction == DMA_TO_DEVICE ||
1060 	    se_cmd->se_cmd_flags & SCF_BIDI)
1061 		scatter_data_area(udev, tcmu_cmd, &iov);
1062 	else
1063 		tcmu_setup_iovs(udev, tcmu_cmd, &iov, se_cmd->data_length);
1064 
1065 	entry->req.iov_cnt = iov_cnt - iov_bidi_cnt;
1066 
1067 	/* Handle BIDI commands */
1068 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
1069 		iov++;
1070 		tcmu_setup_iovs(udev, tcmu_cmd, &iov, tcmu_cmd->data_len_bidi);
1071 		entry->req.iov_bidi_cnt = iov_bidi_cnt;
1072 	}
1073 
1074 	tcmu_setup_cmd_timer(tcmu_cmd, udev->cmd_time_out, &udev->cmd_timer);
1075 
1076 	entry->hdr.cmd_id = tcmu_cmd->cmd_id;
1077 
1078 	tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
1079 
1080 	/* All offsets relative to mb_addr, not start of entry! */
1081 	cdb_off = CMDR_OFF + cmd_head + base_command_size;
1082 	memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
1083 	entry->req.cdb_off = cdb_off;
1084 	tcmu_flush_dcache_range(entry, command_size);
1085 
1086 	UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
1087 	tcmu_flush_dcache_range(mb, sizeof(*mb));
1088 
1089 	list_add_tail(&tcmu_cmd->queue_entry, &udev->inflight_queue);
1090 
1091 	/* TODO: only if FLUSH and FUA? */
1092 	uio_event_notify(&udev->uio_info);
1093 
1094 	return 0;
1095 
1096 free_and_queue:
1097 	tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
1098 	tcmu_cmd_reset_dbi_cur(tcmu_cmd);
1099 
1100 queue:
1101 	if (add_to_qfull_queue(tcmu_cmd)) {
1102 		*scsi_err = TCM_OUT_OF_RESOURCES;
1103 		return -1;
1104 	}
1105 
1106 	return 1;
1107 }
1108 
1109 /**
1110  * queue_tmr_ring - queue tmr info to ring or internally
1111  * @udev: related tcmu_dev
1112  * @tmr: tcmu_tmr containing tmr info to queue
1113  *
1114  * Returns:
1115  *  0 success
1116  *  1 internally queued to wait for ring memory to free.
1117  */
1118 static int
1119 queue_tmr_ring(struct tcmu_dev *udev, struct tcmu_tmr *tmr)
1120 {
1121 	struct tcmu_tmr_entry *entry;
1122 	int cmd_size;
1123 	int id_list_sz;
1124 	struct tcmu_mailbox *mb = udev->mb_addr;
1125 	uint32_t cmd_head;
1126 
1127 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
1128 		goto out_free;
1129 
1130 	id_list_sz = sizeof(tmr->tmr_cmd_ids[0]) * tmr->tmr_cmd_cnt;
1131 	cmd_size = round_up(sizeof(*entry) + id_list_sz, TCMU_OP_ALIGN_SIZE);
1132 
1133 	if (!list_empty(&udev->tmr_queue) ||
1134 	    !is_ring_space_avail(udev, cmd_size)) {
1135 		list_add_tail(&tmr->queue_entry, &udev->tmr_queue);
1136 		pr_debug("adding tmr %p on dev %s to TMR ring space wait queue\n",
1137 			 tmr, udev->name);
1138 		return 1;
1139 	}
1140 
1141 	cmd_head = ring_insert_padding(udev, cmd_size);
1142 
1143 	entry = (void *)mb + CMDR_OFF + cmd_head;
1144 	memset(entry, 0, cmd_size);
1145 	tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_TMR);
1146 	tcmu_hdr_set_len(&entry->hdr.len_op, cmd_size);
1147 	entry->tmr_type = tmr->tmr_type;
1148 	entry->cmd_cnt = tmr->tmr_cmd_cnt;
1149 	memcpy(&entry->cmd_ids[0], &tmr->tmr_cmd_ids[0], id_list_sz);
1150 	tcmu_flush_dcache_range(entry, cmd_size);
1151 
1152 	UPDATE_HEAD(mb->cmd_head, cmd_size, udev->cmdr_size);
1153 	tcmu_flush_dcache_range(mb, sizeof(*mb));
1154 
1155 	uio_event_notify(&udev->uio_info);
1156 
1157 out_free:
1158 	kfree(tmr);
1159 
1160 	return 0;
1161 }
1162 
1163 static sense_reason_t
1164 tcmu_queue_cmd(struct se_cmd *se_cmd)
1165 {
1166 	struct se_device *se_dev = se_cmd->se_dev;
1167 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
1168 	struct tcmu_cmd *tcmu_cmd;
1169 	sense_reason_t scsi_ret = TCM_CHECK_CONDITION_ABORT_CMD;
1170 	int ret = -1;
1171 
1172 	tcmu_cmd = tcmu_alloc_cmd(se_cmd);
1173 	if (!tcmu_cmd)
1174 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1175 
1176 	mutex_lock(&udev->cmdr_lock);
1177 	se_cmd->priv = tcmu_cmd;
1178 	if (!(se_cmd->transport_state & CMD_T_ABORTED))
1179 		ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1180 	if (ret < 0)
1181 		tcmu_free_cmd(tcmu_cmd);
1182 	mutex_unlock(&udev->cmdr_lock);
1183 	return scsi_ret;
1184 }
1185 
1186 static void tcmu_set_next_deadline(struct list_head *queue,
1187 				   struct timer_list *timer)
1188 {
1189 	struct tcmu_cmd *cmd;
1190 
1191 	if (!list_empty(queue)) {
1192 		cmd = list_first_entry(queue, struct tcmu_cmd, queue_entry);
1193 		mod_timer(timer, cmd->deadline);
1194 	} else
1195 		del_timer(timer);
1196 }
1197 
1198 static int
1199 tcmu_tmr_type(enum tcm_tmreq_table tmf)
1200 {
1201 	switch (tmf) {
1202 	case TMR_ABORT_TASK:		return TCMU_TMR_ABORT_TASK;
1203 	case TMR_ABORT_TASK_SET:	return TCMU_TMR_ABORT_TASK_SET;
1204 	case TMR_CLEAR_ACA:		return TCMU_TMR_CLEAR_ACA;
1205 	case TMR_CLEAR_TASK_SET:	return TCMU_TMR_CLEAR_TASK_SET;
1206 	case TMR_LUN_RESET:		return TCMU_TMR_LUN_RESET;
1207 	case TMR_TARGET_WARM_RESET:	return TCMU_TMR_TARGET_WARM_RESET;
1208 	case TMR_TARGET_COLD_RESET:	return TCMU_TMR_TARGET_COLD_RESET;
1209 	case TMR_LUN_RESET_PRO:		return TCMU_TMR_LUN_RESET_PRO;
1210 	default:			return TCMU_TMR_UNKNOWN;
1211 	}
1212 }
1213 
1214 static void
1215 tcmu_tmr_notify(struct se_device *se_dev, enum tcm_tmreq_table tmf,
1216 		struct list_head *cmd_list)
1217 {
1218 	int i = 0, cmd_cnt = 0;
1219 	bool unqueued = false;
1220 	uint16_t *cmd_ids = NULL;
1221 	struct tcmu_cmd *cmd;
1222 	struct se_cmd *se_cmd;
1223 	struct tcmu_tmr *tmr;
1224 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
1225 
1226 	mutex_lock(&udev->cmdr_lock);
1227 
1228 	/* First we check for aborted commands in qfull_queue */
1229 	list_for_each_entry(se_cmd, cmd_list, state_list) {
1230 		i++;
1231 		if (!se_cmd->priv)
1232 			continue;
1233 		cmd = se_cmd->priv;
1234 		/* Commands on qfull queue have no id yet */
1235 		if (cmd->cmd_id) {
1236 			cmd_cnt++;
1237 			continue;
1238 		}
1239 		pr_debug("Removing aborted command %p from queue on dev %s.\n",
1240 			 cmd, udev->name);
1241 
1242 		list_del_init(&cmd->queue_entry);
1243 		tcmu_free_cmd(cmd);
1244 		target_complete_cmd(se_cmd, SAM_STAT_TASK_ABORTED);
1245 		unqueued = true;
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 	if (read_len_valid) {
1336 		pr_debug("read_len = %d\n", read_len);
1337 		target_complete_cmd_with_length(cmd->se_cmd,
1338 					entry->rsp.scsi_status, read_len);
1339 	} else
1340 		target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
1341 
1342 out:
1343 	tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
1344 	tcmu_free_cmd(cmd);
1345 }
1346 
1347 static int tcmu_run_tmr_queue(struct tcmu_dev *udev)
1348 {
1349 	struct tcmu_tmr *tmr, *tmp;
1350 	LIST_HEAD(tmrs);
1351 
1352 	if (list_empty(&udev->tmr_queue))
1353 		return 1;
1354 
1355 	pr_debug("running %s's tmr queue\n", udev->name);
1356 
1357 	list_splice_init(&udev->tmr_queue, &tmrs);
1358 
1359 	list_for_each_entry_safe(tmr, tmp, &tmrs, queue_entry) {
1360 		list_del_init(&tmr->queue_entry);
1361 
1362 		pr_debug("removing tmr %p on dev %s from queue\n",
1363 			 tmr, udev->name);
1364 
1365 		if (queue_tmr_ring(udev, tmr)) {
1366 			pr_debug("ran out of space during tmr queue run\n");
1367 			/*
1368 			 * tmr was requeued, so just put all tmrs back in
1369 			 * the queue
1370 			 */
1371 			list_splice_tail(&tmrs, &udev->tmr_queue);
1372 			return 0;
1373 		}
1374 	}
1375 
1376 	return 1;
1377 }
1378 
1379 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
1380 {
1381 	struct tcmu_mailbox *mb;
1382 	struct tcmu_cmd *cmd;
1383 	bool free_space = false;
1384 
1385 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
1386 		pr_err("ring broken, not handling completions\n");
1387 		return 0;
1388 	}
1389 
1390 	mb = udev->mb_addr;
1391 	tcmu_flush_dcache_range(mb, sizeof(*mb));
1392 
1393 	while (udev->cmdr_last_cleaned != READ_ONCE(mb->cmd_tail)) {
1394 
1395 		struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
1396 
1397 		/*
1398 		 * Flush max. up to end of cmd ring since current entry might
1399 		 * be a padding that is shorter than sizeof(*entry)
1400 		 */
1401 		size_t ring_left = head_to_end(udev->cmdr_last_cleaned,
1402 					       udev->cmdr_size);
1403 		tcmu_flush_dcache_range(entry, ring_left < sizeof(*entry) ?
1404 					ring_left : sizeof(*entry));
1405 
1406 		free_space = true;
1407 
1408 		if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD ||
1409 		    tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_TMR) {
1410 			UPDATE_HEAD(udev->cmdr_last_cleaned,
1411 				    tcmu_hdr_get_len(entry->hdr.len_op),
1412 				    udev->cmdr_size);
1413 			continue;
1414 		}
1415 		WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
1416 
1417 		cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
1418 		if (!cmd) {
1419 			pr_err("cmd_id %u not found, ring is broken\n",
1420 			       entry->hdr.cmd_id);
1421 			set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
1422 			break;
1423 		}
1424 
1425 		tcmu_handle_completion(cmd, entry);
1426 
1427 		UPDATE_HEAD(udev->cmdr_last_cleaned,
1428 			    tcmu_hdr_get_len(entry->hdr.len_op),
1429 			    udev->cmdr_size);
1430 	}
1431 	if (free_space)
1432 		free_space = tcmu_run_tmr_queue(udev);
1433 
1434 	if (atomic_read(&global_db_count) > tcmu_global_max_blocks &&
1435 	    idr_is_empty(&udev->commands) && list_empty(&udev->qfull_queue)) {
1436 		/*
1437 		 * Allocated blocks exceeded global block limit, currently no
1438 		 * more pending or waiting commands so try to reclaim blocks.
1439 		 */
1440 		schedule_delayed_work(&tcmu_unmap_work, 0);
1441 	}
1442 	if (udev->cmd_time_out)
1443 		tcmu_set_next_deadline(&udev->inflight_queue, &udev->cmd_timer);
1444 
1445 	return free_space;
1446 }
1447 
1448 static void tcmu_check_expired_ring_cmd(struct tcmu_cmd *cmd)
1449 {
1450 	struct se_cmd *se_cmd;
1451 
1452 	if (!time_after_eq(jiffies, cmd->deadline))
1453 		return;
1454 
1455 	set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
1456 	list_del_init(&cmd->queue_entry);
1457 	se_cmd = cmd->se_cmd;
1458 	se_cmd->priv = NULL;
1459 	cmd->se_cmd = NULL;
1460 
1461 	pr_debug("Timing out inflight cmd %u on dev %s.\n",
1462 		 cmd->cmd_id, cmd->tcmu_dev->name);
1463 
1464 	target_complete_cmd(se_cmd, SAM_STAT_CHECK_CONDITION);
1465 }
1466 
1467 static void tcmu_check_expired_queue_cmd(struct tcmu_cmd *cmd)
1468 {
1469 	struct se_cmd *se_cmd;
1470 
1471 	if (!time_after_eq(jiffies, cmd->deadline))
1472 		return;
1473 
1474 	pr_debug("Timing out queued cmd %p on dev %s.\n",
1475 		  cmd, cmd->tcmu_dev->name);
1476 
1477 	list_del_init(&cmd->queue_entry);
1478 	se_cmd = cmd->se_cmd;
1479 	tcmu_free_cmd(cmd);
1480 
1481 	target_complete_cmd(se_cmd, SAM_STAT_TASK_SET_FULL);
1482 }
1483 
1484 static void tcmu_device_timedout(struct tcmu_dev *udev)
1485 {
1486 	spin_lock(&timed_out_udevs_lock);
1487 	if (list_empty(&udev->timedout_entry))
1488 		list_add_tail(&udev->timedout_entry, &timed_out_udevs);
1489 	spin_unlock(&timed_out_udevs_lock);
1490 
1491 	schedule_delayed_work(&tcmu_unmap_work, 0);
1492 }
1493 
1494 static void tcmu_cmd_timedout(struct timer_list *t)
1495 {
1496 	struct tcmu_dev *udev = from_timer(udev, t, cmd_timer);
1497 
1498 	pr_debug("%s cmd timeout has expired\n", udev->name);
1499 	tcmu_device_timedout(udev);
1500 }
1501 
1502 static void tcmu_qfull_timedout(struct timer_list *t)
1503 {
1504 	struct tcmu_dev *udev = from_timer(udev, t, qfull_timer);
1505 
1506 	pr_debug("%s qfull timeout has expired\n", udev->name);
1507 	tcmu_device_timedout(udev);
1508 }
1509 
1510 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
1511 {
1512 	struct tcmu_hba *tcmu_hba;
1513 
1514 	tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
1515 	if (!tcmu_hba)
1516 		return -ENOMEM;
1517 
1518 	tcmu_hba->host_id = host_id;
1519 	hba->hba_ptr = tcmu_hba;
1520 
1521 	return 0;
1522 }
1523 
1524 static void tcmu_detach_hba(struct se_hba *hba)
1525 {
1526 	kfree(hba->hba_ptr);
1527 	hba->hba_ptr = NULL;
1528 }
1529 
1530 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
1531 {
1532 	struct tcmu_dev *udev;
1533 
1534 	udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
1535 	if (!udev)
1536 		return NULL;
1537 	kref_init(&udev->kref);
1538 
1539 	udev->name = kstrdup(name, GFP_KERNEL);
1540 	if (!udev->name) {
1541 		kfree(udev);
1542 		return NULL;
1543 	}
1544 
1545 	udev->hba = hba;
1546 	udev->cmd_time_out = TCMU_TIME_OUT;
1547 	udev->qfull_time_out = -1;
1548 
1549 	udev->max_blocks = DATA_BLOCK_BITS_DEF;
1550 	mutex_init(&udev->cmdr_lock);
1551 
1552 	INIT_LIST_HEAD(&udev->node);
1553 	INIT_LIST_HEAD(&udev->timedout_entry);
1554 	INIT_LIST_HEAD(&udev->qfull_queue);
1555 	INIT_LIST_HEAD(&udev->tmr_queue);
1556 	INIT_LIST_HEAD(&udev->inflight_queue);
1557 	idr_init(&udev->commands);
1558 
1559 	timer_setup(&udev->qfull_timer, tcmu_qfull_timedout, 0);
1560 	timer_setup(&udev->cmd_timer, tcmu_cmd_timedout, 0);
1561 
1562 	INIT_RADIX_TREE(&udev->data_blocks, GFP_KERNEL);
1563 
1564 	return &udev->se_dev;
1565 }
1566 
1567 static void run_qfull_queue(struct tcmu_dev *udev, bool fail)
1568 {
1569 	struct tcmu_cmd *tcmu_cmd, *tmp_cmd;
1570 	LIST_HEAD(cmds);
1571 	sense_reason_t scsi_ret;
1572 	int ret;
1573 
1574 	if (list_empty(&udev->qfull_queue))
1575 		return;
1576 
1577 	pr_debug("running %s's cmdr queue forcefail %d\n", udev->name, fail);
1578 
1579 	list_splice_init(&udev->qfull_queue, &cmds);
1580 
1581 	list_for_each_entry_safe(tcmu_cmd, tmp_cmd, &cmds, queue_entry) {
1582 		list_del_init(&tcmu_cmd->queue_entry);
1583 
1584 		pr_debug("removing cmd %p on dev %s from queue\n",
1585 			 tcmu_cmd, udev->name);
1586 
1587 		if (fail) {
1588 			/*
1589 			 * We were not able to even start the command, so
1590 			 * fail with busy to allow a retry in case runner
1591 			 * was only temporarily down. If the device is being
1592 			 * removed then LIO core will do the right thing and
1593 			 * fail the retry.
1594 			 */
1595 			target_complete_cmd(tcmu_cmd->se_cmd, SAM_STAT_BUSY);
1596 			tcmu_free_cmd(tcmu_cmd);
1597 			continue;
1598 		}
1599 
1600 		ret = queue_cmd_ring(tcmu_cmd, &scsi_ret);
1601 		if (ret < 0) {
1602 			pr_debug("cmd %p on dev %s failed with %u\n",
1603 				 tcmu_cmd, udev->name, scsi_ret);
1604 			/*
1605 			 * Ignore scsi_ret for now. target_complete_cmd
1606 			 * drops it.
1607 			 */
1608 			target_complete_cmd(tcmu_cmd->se_cmd,
1609 					    SAM_STAT_CHECK_CONDITION);
1610 			tcmu_free_cmd(tcmu_cmd);
1611 		} else if (ret > 0) {
1612 			pr_debug("ran out of space during cmdr queue run\n");
1613 			/*
1614 			 * cmd was requeued, so just put all cmds back in
1615 			 * the queue
1616 			 */
1617 			list_splice_tail(&cmds, &udev->qfull_queue);
1618 			break;
1619 		}
1620 	}
1621 
1622 	tcmu_set_next_deadline(&udev->qfull_queue, &udev->qfull_timer);
1623 }
1624 
1625 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
1626 {
1627 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1628 
1629 	mutex_lock(&udev->cmdr_lock);
1630 	if (tcmu_handle_completions(udev))
1631 		run_qfull_queue(udev, false);
1632 	mutex_unlock(&udev->cmdr_lock);
1633 
1634 	return 0;
1635 }
1636 
1637 /*
1638  * mmap code from uio.c. Copied here because we want to hook mmap()
1639  * and this stuff must come along.
1640  */
1641 static int tcmu_find_mem_index(struct vm_area_struct *vma)
1642 {
1643 	struct tcmu_dev *udev = vma->vm_private_data;
1644 	struct uio_info *info = &udev->uio_info;
1645 
1646 	if (vma->vm_pgoff < MAX_UIO_MAPS) {
1647 		if (info->mem[vma->vm_pgoff].size == 0)
1648 			return -1;
1649 		return (int)vma->vm_pgoff;
1650 	}
1651 	return -1;
1652 }
1653 
1654 static struct page *tcmu_try_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
1655 {
1656 	struct page *page;
1657 
1658 	mutex_lock(&udev->cmdr_lock);
1659 	page = tcmu_get_block_page(udev, dbi);
1660 	if (likely(page)) {
1661 		mutex_unlock(&udev->cmdr_lock);
1662 		return page;
1663 	}
1664 
1665 	/*
1666 	 * Userspace messed up and passed in a address not in the
1667 	 * data iov passed to it.
1668 	 */
1669 	pr_err("Invalid addr to data block mapping  (dbi %u) on device %s\n",
1670 	       dbi, udev->name);
1671 	page = NULL;
1672 	mutex_unlock(&udev->cmdr_lock);
1673 
1674 	return page;
1675 }
1676 
1677 static vm_fault_t tcmu_vma_fault(struct vm_fault *vmf)
1678 {
1679 	struct tcmu_dev *udev = vmf->vma->vm_private_data;
1680 	struct uio_info *info = &udev->uio_info;
1681 	struct page *page;
1682 	unsigned long offset;
1683 	void *addr;
1684 
1685 	int mi = tcmu_find_mem_index(vmf->vma);
1686 	if (mi < 0)
1687 		return VM_FAULT_SIGBUS;
1688 
1689 	/*
1690 	 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
1691 	 * to use mem[N].
1692 	 */
1693 	offset = (vmf->pgoff - mi) << PAGE_SHIFT;
1694 
1695 	if (offset < udev->data_off) {
1696 		/* For the vmalloc()ed cmd area pages */
1697 		addr = (void *)(unsigned long)info->mem[mi].addr + offset;
1698 		page = vmalloc_to_page(addr);
1699 	} else {
1700 		uint32_t dbi;
1701 
1702 		/* For the dynamically growing data area pages */
1703 		dbi = (offset - udev->data_off) / DATA_BLOCK_SIZE;
1704 		page = tcmu_try_get_block_page(udev, dbi);
1705 		if (!page)
1706 			return VM_FAULT_SIGBUS;
1707 	}
1708 
1709 	get_page(page);
1710 	vmf->page = page;
1711 	return 0;
1712 }
1713 
1714 static const struct vm_operations_struct tcmu_vm_ops = {
1715 	.fault = tcmu_vma_fault,
1716 };
1717 
1718 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
1719 {
1720 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1721 
1722 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1723 	vma->vm_ops = &tcmu_vm_ops;
1724 
1725 	vma->vm_private_data = udev;
1726 
1727 	/* Ensure the mmap is exactly the right size */
1728 	if (vma_pages(vma) != (udev->ring_size >> PAGE_SHIFT))
1729 		return -EINVAL;
1730 
1731 	return 0;
1732 }
1733 
1734 static int tcmu_open(struct uio_info *info, struct inode *inode)
1735 {
1736 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1737 
1738 	/* O_EXCL not supported for char devs, so fake it? */
1739 	if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
1740 		return -EBUSY;
1741 
1742 	udev->inode = inode;
1743 	kref_get(&udev->kref);
1744 
1745 	pr_debug("open\n");
1746 
1747 	return 0;
1748 }
1749 
1750 static void tcmu_dev_call_rcu(struct rcu_head *p)
1751 {
1752 	struct se_device *dev = container_of(p, struct se_device, rcu_head);
1753 	struct tcmu_dev *udev = TCMU_DEV(dev);
1754 
1755 	kfree(udev->uio_info.name);
1756 	kfree(udev->name);
1757 	kfree(udev);
1758 }
1759 
1760 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1761 {
1762 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1763 		kmem_cache_free(tcmu_cmd_cache, cmd);
1764 		return 0;
1765 	}
1766 	return -EINVAL;
1767 }
1768 
1769 static void tcmu_blocks_release(struct radix_tree_root *blocks,
1770 				int start, int end)
1771 {
1772 	int i;
1773 	struct page *page;
1774 
1775 	for (i = start; i < end; i++) {
1776 		page = radix_tree_delete(blocks, i);
1777 		if (page) {
1778 			__free_page(page);
1779 			atomic_dec(&global_db_count);
1780 		}
1781 	}
1782 }
1783 
1784 static void tcmu_remove_all_queued_tmr(struct tcmu_dev *udev)
1785 {
1786 	struct tcmu_tmr *tmr, *tmp;
1787 
1788 	list_for_each_entry_safe(tmr, tmp, &udev->tmr_queue, queue_entry) {
1789 		list_del_init(&tmr->queue_entry);
1790 		kfree(tmr);
1791 	}
1792 }
1793 
1794 static void tcmu_dev_kref_release(struct kref *kref)
1795 {
1796 	struct tcmu_dev *udev = container_of(kref, struct tcmu_dev, kref);
1797 	struct se_device *dev = &udev->se_dev;
1798 	struct tcmu_cmd *cmd;
1799 	bool all_expired = true;
1800 	int i;
1801 
1802 	vfree(udev->mb_addr);
1803 	udev->mb_addr = NULL;
1804 
1805 	spin_lock_bh(&timed_out_udevs_lock);
1806 	if (!list_empty(&udev->timedout_entry))
1807 		list_del(&udev->timedout_entry);
1808 	spin_unlock_bh(&timed_out_udevs_lock);
1809 
1810 	/* Upper layer should drain all requests before calling this */
1811 	mutex_lock(&udev->cmdr_lock);
1812 	idr_for_each_entry(&udev->commands, cmd, i) {
1813 		if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1814 			all_expired = false;
1815 	}
1816 	/* There can be left over TMR cmds. Remove them. */
1817 	tcmu_remove_all_queued_tmr(udev);
1818 	if (!list_empty(&udev->qfull_queue))
1819 		all_expired = false;
1820 	idr_destroy(&udev->commands);
1821 	WARN_ON(!all_expired);
1822 
1823 	tcmu_blocks_release(&udev->data_blocks, 0, udev->dbi_max + 1);
1824 	bitmap_free(udev->data_bitmap);
1825 	mutex_unlock(&udev->cmdr_lock);
1826 
1827 	call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1828 }
1829 
1830 static int tcmu_release(struct uio_info *info, struct inode *inode)
1831 {
1832 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1833 
1834 	clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
1835 
1836 	pr_debug("close\n");
1837 	/* release ref from open */
1838 	kref_put(&udev->kref, tcmu_dev_kref_release);
1839 	return 0;
1840 }
1841 
1842 static int tcmu_init_genl_cmd_reply(struct tcmu_dev *udev, int cmd)
1843 {
1844 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1845 
1846 	if (!tcmu_kern_cmd_reply_supported)
1847 		return 0;
1848 
1849 	if (udev->nl_reply_supported <= 0)
1850 		return 0;
1851 
1852 	mutex_lock(&tcmu_nl_cmd_mutex);
1853 
1854 	if (tcmu_netlink_blocked) {
1855 		mutex_unlock(&tcmu_nl_cmd_mutex);
1856 		pr_warn("Failing nl cmd %d on %s. Interface is blocked.\n", cmd,
1857 			udev->name);
1858 		return -EAGAIN;
1859 	}
1860 
1861 	if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
1862 		mutex_unlock(&tcmu_nl_cmd_mutex);
1863 		pr_warn("netlink cmd %d already executing on %s\n",
1864 			 nl_cmd->cmd, udev->name);
1865 		return -EBUSY;
1866 	}
1867 
1868 	memset(nl_cmd, 0, sizeof(*nl_cmd));
1869 	nl_cmd->cmd = cmd;
1870 	nl_cmd->udev = udev;
1871 	init_completion(&nl_cmd->complete);
1872 	INIT_LIST_HEAD(&nl_cmd->nl_list);
1873 
1874 	list_add_tail(&nl_cmd->nl_list, &tcmu_nl_cmd_list);
1875 
1876 	mutex_unlock(&tcmu_nl_cmd_mutex);
1877 	return 0;
1878 }
1879 
1880 static void tcmu_destroy_genl_cmd_reply(struct tcmu_dev *udev)
1881 {
1882 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1883 
1884 	if (!tcmu_kern_cmd_reply_supported)
1885 		return;
1886 
1887 	if (udev->nl_reply_supported <= 0)
1888 		return;
1889 
1890 	mutex_lock(&tcmu_nl_cmd_mutex);
1891 
1892 	list_del(&nl_cmd->nl_list);
1893 	memset(nl_cmd, 0, sizeof(*nl_cmd));
1894 
1895 	mutex_unlock(&tcmu_nl_cmd_mutex);
1896 }
1897 
1898 static int tcmu_wait_genl_cmd_reply(struct tcmu_dev *udev)
1899 {
1900 	struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1901 	int ret;
1902 
1903 	if (!tcmu_kern_cmd_reply_supported)
1904 		return 0;
1905 
1906 	if (udev->nl_reply_supported <= 0)
1907 		return 0;
1908 
1909 	pr_debug("sleeping for nl reply\n");
1910 	wait_for_completion(&nl_cmd->complete);
1911 
1912 	mutex_lock(&tcmu_nl_cmd_mutex);
1913 	nl_cmd->cmd = TCMU_CMD_UNSPEC;
1914 	ret = nl_cmd->status;
1915 	mutex_unlock(&tcmu_nl_cmd_mutex);
1916 
1917 	return ret;
1918 }
1919 
1920 static int tcmu_netlink_event_init(struct tcmu_dev *udev,
1921 				   enum tcmu_genl_cmd cmd,
1922 				   struct sk_buff **buf, void **hdr)
1923 {
1924 	struct sk_buff *skb;
1925 	void *msg_header;
1926 	int ret = -ENOMEM;
1927 
1928 	skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1929 	if (!skb)
1930 		return ret;
1931 
1932 	msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
1933 	if (!msg_header)
1934 		goto free_skb;
1935 
1936 	ret = nla_put_string(skb, TCMU_ATTR_DEVICE, udev->uio_info.name);
1937 	if (ret < 0)
1938 		goto free_skb;
1939 
1940 	ret = nla_put_u32(skb, TCMU_ATTR_MINOR, udev->uio_info.uio_dev->minor);
1941 	if (ret < 0)
1942 		goto free_skb;
1943 
1944 	ret = nla_put_u32(skb, TCMU_ATTR_DEVICE_ID, udev->se_dev.dev_index);
1945 	if (ret < 0)
1946 		goto free_skb;
1947 
1948 	*buf = skb;
1949 	*hdr = msg_header;
1950 	return ret;
1951 
1952 free_skb:
1953 	nlmsg_free(skb);
1954 	return ret;
1955 }
1956 
1957 static int tcmu_netlink_event_send(struct tcmu_dev *udev,
1958 				   enum tcmu_genl_cmd cmd,
1959 				   struct sk_buff *skb, void *msg_header)
1960 {
1961 	int ret;
1962 
1963 	genlmsg_end(skb, msg_header);
1964 
1965 	ret = tcmu_init_genl_cmd_reply(udev, cmd);
1966 	if (ret) {
1967 		nlmsg_free(skb);
1968 		return ret;
1969 	}
1970 
1971 	ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
1972 				      TCMU_MCGRP_CONFIG, GFP_KERNEL);
1973 
1974 	/* Wait during an add as the listener may not be up yet */
1975 	if (ret == 0 ||
1976 	   (ret == -ESRCH && cmd == TCMU_CMD_ADDED_DEVICE))
1977 		return tcmu_wait_genl_cmd_reply(udev);
1978 	else
1979 		tcmu_destroy_genl_cmd_reply(udev);
1980 
1981 	return ret;
1982 }
1983 
1984 static int tcmu_send_dev_add_event(struct tcmu_dev *udev)
1985 {
1986 	struct sk_buff *skb = NULL;
1987 	void *msg_header = NULL;
1988 	int ret = 0;
1989 
1990 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_ADDED_DEVICE, &skb,
1991 				      &msg_header);
1992 	if (ret < 0)
1993 		return ret;
1994 	return tcmu_netlink_event_send(udev, TCMU_CMD_ADDED_DEVICE, skb,
1995 				       msg_header);
1996 }
1997 
1998 static int tcmu_send_dev_remove_event(struct tcmu_dev *udev)
1999 {
2000 	struct sk_buff *skb = NULL;
2001 	void *msg_header = NULL;
2002 	int ret = 0;
2003 
2004 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_REMOVED_DEVICE,
2005 				      &skb, &msg_header);
2006 	if (ret < 0)
2007 		return ret;
2008 	return tcmu_netlink_event_send(udev, TCMU_CMD_REMOVED_DEVICE,
2009 				       skb, msg_header);
2010 }
2011 
2012 static int tcmu_update_uio_info(struct tcmu_dev *udev)
2013 {
2014 	struct tcmu_hba *hba = udev->hba->hba_ptr;
2015 	struct uio_info *info;
2016 	char *str;
2017 
2018 	info = &udev->uio_info;
2019 
2020 	if (udev->dev_config[0])
2021 		str = kasprintf(GFP_KERNEL, "tcm-user/%u/%s/%s", hba->host_id,
2022 				udev->name, udev->dev_config);
2023 	else
2024 		str = kasprintf(GFP_KERNEL, "tcm-user/%u/%s", hba->host_id,
2025 				udev->name);
2026 	if (!str)
2027 		return -ENOMEM;
2028 
2029 	/* If the old string exists, free it */
2030 	kfree(info->name);
2031 	info->name = str;
2032 
2033 	return 0;
2034 }
2035 
2036 static int tcmu_configure_device(struct se_device *dev)
2037 {
2038 	struct tcmu_dev *udev = TCMU_DEV(dev);
2039 	struct uio_info *info;
2040 	struct tcmu_mailbox *mb;
2041 	int ret = 0;
2042 
2043 	ret = tcmu_update_uio_info(udev);
2044 	if (ret)
2045 		return ret;
2046 
2047 	info = &udev->uio_info;
2048 
2049 	mutex_lock(&udev->cmdr_lock);
2050 	udev->data_bitmap = bitmap_zalloc(udev->max_blocks, GFP_KERNEL);
2051 	mutex_unlock(&udev->cmdr_lock);
2052 	if (!udev->data_bitmap) {
2053 		ret = -ENOMEM;
2054 		goto err_bitmap_alloc;
2055 	}
2056 
2057 	udev->mb_addr = vzalloc(CMDR_SIZE);
2058 	if (!udev->mb_addr) {
2059 		ret = -ENOMEM;
2060 		goto err_vzalloc;
2061 	}
2062 
2063 	/* mailbox fits in first part of CMDR space */
2064 	udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
2065 	udev->data_off = CMDR_SIZE;
2066 	udev->data_size = udev->max_blocks * DATA_BLOCK_SIZE;
2067 	udev->dbi_thresh = 0; /* Default in Idle state */
2068 
2069 	/* Initialise the mailbox of the ring buffer */
2070 	mb = udev->mb_addr;
2071 	mb->version = TCMU_MAILBOX_VERSION;
2072 	mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC |
2073 		    TCMU_MAILBOX_FLAG_CAP_READ_LEN |
2074 		    TCMU_MAILBOX_FLAG_CAP_TMR;
2075 	mb->cmdr_off = CMDR_OFF;
2076 	mb->cmdr_size = udev->cmdr_size;
2077 
2078 	WARN_ON(!PAGE_ALIGNED(udev->data_off));
2079 	WARN_ON(udev->data_size % PAGE_SIZE);
2080 	WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
2081 
2082 	info->version = __stringify(TCMU_MAILBOX_VERSION);
2083 
2084 	info->mem[0].name = "tcm-user command & data buffer";
2085 	info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
2086 	info->mem[0].size = udev->ring_size = udev->data_size + CMDR_SIZE;
2087 	info->mem[0].memtype = UIO_MEM_NONE;
2088 
2089 	info->irqcontrol = tcmu_irqcontrol;
2090 	info->irq = UIO_IRQ_CUSTOM;
2091 
2092 	info->mmap = tcmu_mmap;
2093 	info->open = tcmu_open;
2094 	info->release = tcmu_release;
2095 
2096 	ret = uio_register_device(tcmu_root_device, info);
2097 	if (ret)
2098 		goto err_register;
2099 
2100 	/* User can set hw_block_size before enable the device */
2101 	if (dev->dev_attrib.hw_block_size == 0)
2102 		dev->dev_attrib.hw_block_size = 512;
2103 	/* Other attributes can be configured in userspace */
2104 	if (!dev->dev_attrib.hw_max_sectors)
2105 		dev->dev_attrib.hw_max_sectors = 128;
2106 	if (!dev->dev_attrib.emulate_write_cache)
2107 		dev->dev_attrib.emulate_write_cache = 0;
2108 	dev->dev_attrib.hw_queue_depth = 128;
2109 
2110 	/* If user didn't explicitly disable netlink reply support, use
2111 	 * module scope setting.
2112 	 */
2113 	if (udev->nl_reply_supported >= 0)
2114 		udev->nl_reply_supported = tcmu_kern_cmd_reply_supported;
2115 
2116 	/*
2117 	 * Get a ref incase userspace does a close on the uio device before
2118 	 * LIO has initiated tcmu_free_device.
2119 	 */
2120 	kref_get(&udev->kref);
2121 
2122 	ret = tcmu_send_dev_add_event(udev);
2123 	if (ret)
2124 		goto err_netlink;
2125 
2126 	mutex_lock(&root_udev_mutex);
2127 	list_add(&udev->node, &root_udev);
2128 	mutex_unlock(&root_udev_mutex);
2129 
2130 	return 0;
2131 
2132 err_netlink:
2133 	kref_put(&udev->kref, tcmu_dev_kref_release);
2134 	uio_unregister_device(&udev->uio_info);
2135 err_register:
2136 	vfree(udev->mb_addr);
2137 	udev->mb_addr = NULL;
2138 err_vzalloc:
2139 	bitmap_free(udev->data_bitmap);
2140 	udev->data_bitmap = NULL;
2141 err_bitmap_alloc:
2142 	kfree(info->name);
2143 	info->name = NULL;
2144 
2145 	return ret;
2146 }
2147 
2148 static void tcmu_free_device(struct se_device *dev)
2149 {
2150 	struct tcmu_dev *udev = TCMU_DEV(dev);
2151 
2152 	/* release ref from init */
2153 	kref_put(&udev->kref, tcmu_dev_kref_release);
2154 }
2155 
2156 static void tcmu_destroy_device(struct se_device *dev)
2157 {
2158 	struct tcmu_dev *udev = TCMU_DEV(dev);
2159 
2160 	del_timer_sync(&udev->cmd_timer);
2161 	del_timer_sync(&udev->qfull_timer);
2162 
2163 	mutex_lock(&root_udev_mutex);
2164 	list_del(&udev->node);
2165 	mutex_unlock(&root_udev_mutex);
2166 
2167 	tcmu_send_dev_remove_event(udev);
2168 
2169 	uio_unregister_device(&udev->uio_info);
2170 
2171 	/* release ref from configure */
2172 	kref_put(&udev->kref, tcmu_dev_kref_release);
2173 }
2174 
2175 static void tcmu_unblock_dev(struct tcmu_dev *udev)
2176 {
2177 	mutex_lock(&udev->cmdr_lock);
2178 	clear_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags);
2179 	mutex_unlock(&udev->cmdr_lock);
2180 }
2181 
2182 static void tcmu_block_dev(struct tcmu_dev *udev)
2183 {
2184 	mutex_lock(&udev->cmdr_lock);
2185 
2186 	if (test_and_set_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
2187 		goto unlock;
2188 
2189 	/* complete IO that has executed successfully */
2190 	tcmu_handle_completions(udev);
2191 	/* fail IO waiting to be queued */
2192 	run_qfull_queue(udev, true);
2193 
2194 unlock:
2195 	mutex_unlock(&udev->cmdr_lock);
2196 }
2197 
2198 static void tcmu_reset_ring(struct tcmu_dev *udev, u8 err_level)
2199 {
2200 	struct tcmu_mailbox *mb;
2201 	struct tcmu_cmd *cmd;
2202 	int i;
2203 
2204 	mutex_lock(&udev->cmdr_lock);
2205 
2206 	idr_for_each_entry(&udev->commands, cmd, i) {
2207 		pr_debug("removing cmd %u on dev %s from ring (is expired %d)\n",
2208 			  cmd->cmd_id, udev->name,
2209 			  test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags));
2210 
2211 		idr_remove(&udev->commands, i);
2212 		if (!test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
2213 			WARN_ON(!cmd->se_cmd);
2214 			list_del_init(&cmd->queue_entry);
2215 			if (err_level == 1) {
2216 				/*
2217 				 * Userspace was not able to start the
2218 				 * command or it is retryable.
2219 				 */
2220 				target_complete_cmd(cmd->se_cmd, SAM_STAT_BUSY);
2221 			} else {
2222 				/* hard failure */
2223 				target_complete_cmd(cmd->se_cmd,
2224 						    SAM_STAT_CHECK_CONDITION);
2225 			}
2226 		}
2227 		tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
2228 		tcmu_free_cmd(cmd);
2229 	}
2230 
2231 	mb = udev->mb_addr;
2232 	tcmu_flush_dcache_range(mb, sizeof(*mb));
2233 	pr_debug("mb last %u head %u tail %u\n", udev->cmdr_last_cleaned,
2234 		 mb->cmd_tail, mb->cmd_head);
2235 
2236 	udev->cmdr_last_cleaned = 0;
2237 	mb->cmd_tail = 0;
2238 	mb->cmd_head = 0;
2239 	tcmu_flush_dcache_range(mb, sizeof(*mb));
2240 	clear_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
2241 
2242 	del_timer(&udev->cmd_timer);
2243 
2244 	/*
2245 	 * ring is empty and qfull queue never contains aborted commands.
2246 	 * So TMRs in tmr queue do not contain relevant cmd_ids.
2247 	 * After a ring reset userspace should do a fresh start, so
2248 	 * even LUN RESET message is no longer relevant.
2249 	 * Therefore remove all TMRs from qfull queue
2250 	 */
2251 	tcmu_remove_all_queued_tmr(udev);
2252 
2253 	run_qfull_queue(udev, false);
2254 
2255 	mutex_unlock(&udev->cmdr_lock);
2256 }
2257 
2258 enum {
2259 	Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
2260 	Opt_nl_reply_supported, Opt_max_data_area_mb, Opt_err,
2261 };
2262 
2263 static match_table_t tokens = {
2264 	{Opt_dev_config, "dev_config=%s"},
2265 	{Opt_dev_size, "dev_size=%s"},
2266 	{Opt_hw_block_size, "hw_block_size=%d"},
2267 	{Opt_hw_max_sectors, "hw_max_sectors=%d"},
2268 	{Opt_nl_reply_supported, "nl_reply_supported=%d"},
2269 	{Opt_max_data_area_mb, "max_data_area_mb=%d"},
2270 	{Opt_err, NULL}
2271 };
2272 
2273 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
2274 {
2275 	int val, ret;
2276 
2277 	ret = match_int(arg, &val);
2278 	if (ret < 0) {
2279 		pr_err("match_int() failed for dev attrib. Error %d.\n",
2280 		       ret);
2281 		return ret;
2282 	}
2283 
2284 	if (val <= 0) {
2285 		pr_err("Invalid dev attrib value %d. Must be greater than zero.\n",
2286 		       val);
2287 		return -EINVAL;
2288 	}
2289 	*dev_attrib = val;
2290 	return 0;
2291 }
2292 
2293 static int tcmu_set_max_blocks_param(struct tcmu_dev *udev, substring_t *arg)
2294 {
2295 	int val, ret;
2296 
2297 	ret = match_int(arg, &val);
2298 	if (ret < 0) {
2299 		pr_err("match_int() failed for max_data_area_mb=. Error %d.\n",
2300 		       ret);
2301 		return ret;
2302 	}
2303 
2304 	if (val <= 0) {
2305 		pr_err("Invalid max_data_area %d.\n", val);
2306 		return -EINVAL;
2307 	}
2308 
2309 	mutex_lock(&udev->cmdr_lock);
2310 	if (udev->data_bitmap) {
2311 		pr_err("Cannot set max_data_area_mb after it has been enabled.\n");
2312 		ret = -EINVAL;
2313 		goto unlock;
2314 	}
2315 
2316 	udev->max_blocks = TCMU_MBS_TO_BLOCKS(val);
2317 	if (udev->max_blocks > tcmu_global_max_blocks) {
2318 		pr_err("%d is too large. Adjusting max_data_area_mb to global limit of %u\n",
2319 		       val, TCMU_BLOCKS_TO_MBS(tcmu_global_max_blocks));
2320 		udev->max_blocks = tcmu_global_max_blocks;
2321 	}
2322 
2323 unlock:
2324 	mutex_unlock(&udev->cmdr_lock);
2325 	return ret;
2326 }
2327 
2328 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
2329 		const char *page, ssize_t count)
2330 {
2331 	struct tcmu_dev *udev = TCMU_DEV(dev);
2332 	char *orig, *ptr, *opts;
2333 	substring_t args[MAX_OPT_ARGS];
2334 	int ret = 0, token;
2335 
2336 	opts = kstrdup(page, GFP_KERNEL);
2337 	if (!opts)
2338 		return -ENOMEM;
2339 
2340 	orig = opts;
2341 
2342 	while ((ptr = strsep(&opts, ",\n")) != NULL) {
2343 		if (!*ptr)
2344 			continue;
2345 
2346 		token = match_token(ptr, tokens, args);
2347 		switch (token) {
2348 		case Opt_dev_config:
2349 			if (match_strlcpy(udev->dev_config, &args[0],
2350 					  TCMU_CONFIG_LEN) == 0) {
2351 				ret = -EINVAL;
2352 				break;
2353 			}
2354 			pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
2355 			break;
2356 		case Opt_dev_size:
2357 			ret = match_u64(&args[0], &udev->dev_size);
2358 			if (ret < 0)
2359 				pr_err("match_u64() failed for dev_size=. Error %d.\n",
2360 				       ret);
2361 			break;
2362 		case Opt_hw_block_size:
2363 			ret = tcmu_set_dev_attrib(&args[0],
2364 					&(dev->dev_attrib.hw_block_size));
2365 			break;
2366 		case Opt_hw_max_sectors:
2367 			ret = tcmu_set_dev_attrib(&args[0],
2368 					&(dev->dev_attrib.hw_max_sectors));
2369 			break;
2370 		case Opt_nl_reply_supported:
2371 			ret = match_int(&args[0], &udev->nl_reply_supported);
2372 			if (ret < 0)
2373 				pr_err("match_int() failed for nl_reply_supported=. Error %d.\n",
2374 				       ret);
2375 			break;
2376 		case Opt_max_data_area_mb:
2377 			ret = tcmu_set_max_blocks_param(udev, &args[0]);
2378 			break;
2379 		default:
2380 			break;
2381 		}
2382 
2383 		if (ret)
2384 			break;
2385 	}
2386 
2387 	kfree(orig);
2388 	return (!ret) ? count : ret;
2389 }
2390 
2391 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
2392 {
2393 	struct tcmu_dev *udev = TCMU_DEV(dev);
2394 	ssize_t bl = 0;
2395 
2396 	bl = sprintf(b + bl, "Config: %s ",
2397 		     udev->dev_config[0] ? udev->dev_config : "NULL");
2398 	bl += sprintf(b + bl, "Size: %llu ", udev->dev_size);
2399 	bl += sprintf(b + bl, "MaxDataAreaMB: %u\n",
2400 		      TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2401 
2402 	return bl;
2403 }
2404 
2405 static sector_t tcmu_get_blocks(struct se_device *dev)
2406 {
2407 	struct tcmu_dev *udev = TCMU_DEV(dev);
2408 
2409 	return div_u64(udev->dev_size - dev->dev_attrib.block_size,
2410 		       dev->dev_attrib.block_size);
2411 }
2412 
2413 static sense_reason_t
2414 tcmu_parse_cdb(struct se_cmd *cmd)
2415 {
2416 	return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
2417 }
2418 
2419 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
2420 {
2421 	struct se_dev_attrib *da = container_of(to_config_group(item),
2422 					struct se_dev_attrib, da_group);
2423 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2424 
2425 	return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
2426 }
2427 
2428 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
2429 				       size_t count)
2430 {
2431 	struct se_dev_attrib *da = container_of(to_config_group(item),
2432 					struct se_dev_attrib, da_group);
2433 	struct tcmu_dev *udev = container_of(da->da_dev,
2434 					struct tcmu_dev, se_dev);
2435 	u32 val;
2436 	int ret;
2437 
2438 	if (da->da_dev->export_count) {
2439 		pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
2440 		return -EINVAL;
2441 	}
2442 
2443 	ret = kstrtou32(page, 0, &val);
2444 	if (ret < 0)
2445 		return ret;
2446 
2447 	udev->cmd_time_out = val * MSEC_PER_SEC;
2448 	return count;
2449 }
2450 CONFIGFS_ATTR(tcmu_, cmd_time_out);
2451 
2452 static ssize_t tcmu_qfull_time_out_show(struct config_item *item, char *page)
2453 {
2454 	struct se_dev_attrib *da = container_of(to_config_group(item),
2455 						struct se_dev_attrib, da_group);
2456 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2457 
2458 	return snprintf(page, PAGE_SIZE, "%ld\n", udev->qfull_time_out <= 0 ?
2459 			udev->qfull_time_out :
2460 			udev->qfull_time_out / MSEC_PER_SEC);
2461 }
2462 
2463 static ssize_t tcmu_qfull_time_out_store(struct config_item *item,
2464 					 const char *page, size_t count)
2465 {
2466 	struct se_dev_attrib *da = container_of(to_config_group(item),
2467 					struct se_dev_attrib, da_group);
2468 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2469 	s32 val;
2470 	int ret;
2471 
2472 	ret = kstrtos32(page, 0, &val);
2473 	if (ret < 0)
2474 		return ret;
2475 
2476 	if (val >= 0) {
2477 		udev->qfull_time_out = val * MSEC_PER_SEC;
2478 	} else if (val == -1) {
2479 		udev->qfull_time_out = val;
2480 	} else {
2481 		printk(KERN_ERR "Invalid qfull timeout value %d\n", val);
2482 		return -EINVAL;
2483 	}
2484 	return count;
2485 }
2486 CONFIGFS_ATTR(tcmu_, qfull_time_out);
2487 
2488 static ssize_t tcmu_max_data_area_mb_show(struct config_item *item, char *page)
2489 {
2490 	struct se_dev_attrib *da = container_of(to_config_group(item),
2491 						struct se_dev_attrib, da_group);
2492 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2493 
2494 	return snprintf(page, PAGE_SIZE, "%u\n",
2495 			TCMU_BLOCKS_TO_MBS(udev->max_blocks));
2496 }
2497 CONFIGFS_ATTR_RO(tcmu_, max_data_area_mb);
2498 
2499 static ssize_t tcmu_dev_config_show(struct config_item *item, char *page)
2500 {
2501 	struct se_dev_attrib *da = container_of(to_config_group(item),
2502 						struct se_dev_attrib, da_group);
2503 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2504 
2505 	return snprintf(page, PAGE_SIZE, "%s\n", udev->dev_config);
2506 }
2507 
2508 static int tcmu_send_dev_config_event(struct tcmu_dev *udev,
2509 				      const char *reconfig_data)
2510 {
2511 	struct sk_buff *skb = NULL;
2512 	void *msg_header = NULL;
2513 	int ret = 0;
2514 
2515 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2516 				      &skb, &msg_header);
2517 	if (ret < 0)
2518 		return ret;
2519 	ret = nla_put_string(skb, TCMU_ATTR_DEV_CFG, reconfig_data);
2520 	if (ret < 0) {
2521 		nlmsg_free(skb);
2522 		return ret;
2523 	}
2524 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2525 				       skb, msg_header);
2526 }
2527 
2528 
2529 static ssize_t tcmu_dev_config_store(struct config_item *item, const char *page,
2530 				     size_t count)
2531 {
2532 	struct se_dev_attrib *da = container_of(to_config_group(item),
2533 						struct se_dev_attrib, da_group);
2534 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2535 	int ret, len;
2536 
2537 	len = strlen(page);
2538 	if (!len || len > TCMU_CONFIG_LEN - 1)
2539 		return -EINVAL;
2540 
2541 	/* Check if device has been configured before */
2542 	if (target_dev_configured(&udev->se_dev)) {
2543 		ret = tcmu_send_dev_config_event(udev, page);
2544 		if (ret) {
2545 			pr_err("Unable to reconfigure device\n");
2546 			return ret;
2547 		}
2548 		strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2549 
2550 		ret = tcmu_update_uio_info(udev);
2551 		if (ret)
2552 			return ret;
2553 		return count;
2554 	}
2555 	strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
2556 
2557 	return count;
2558 }
2559 CONFIGFS_ATTR(tcmu_, dev_config);
2560 
2561 static ssize_t tcmu_dev_size_show(struct config_item *item, char *page)
2562 {
2563 	struct se_dev_attrib *da = container_of(to_config_group(item),
2564 						struct se_dev_attrib, da_group);
2565 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2566 
2567 	return snprintf(page, PAGE_SIZE, "%llu\n", udev->dev_size);
2568 }
2569 
2570 static int tcmu_send_dev_size_event(struct tcmu_dev *udev, u64 size)
2571 {
2572 	struct sk_buff *skb = NULL;
2573 	void *msg_header = NULL;
2574 	int ret = 0;
2575 
2576 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2577 				      &skb, &msg_header);
2578 	if (ret < 0)
2579 		return ret;
2580 	ret = nla_put_u64_64bit(skb, TCMU_ATTR_DEV_SIZE,
2581 				size, TCMU_ATTR_PAD);
2582 	if (ret < 0) {
2583 		nlmsg_free(skb);
2584 		return ret;
2585 	}
2586 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2587 				       skb, msg_header);
2588 }
2589 
2590 static ssize_t tcmu_dev_size_store(struct config_item *item, const char *page,
2591 				   size_t count)
2592 {
2593 	struct se_dev_attrib *da = container_of(to_config_group(item),
2594 						struct se_dev_attrib, da_group);
2595 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2596 	u64 val;
2597 	int ret;
2598 
2599 	ret = kstrtou64(page, 0, &val);
2600 	if (ret < 0)
2601 		return ret;
2602 
2603 	/* Check if device has been configured before */
2604 	if (target_dev_configured(&udev->se_dev)) {
2605 		ret = tcmu_send_dev_size_event(udev, val);
2606 		if (ret) {
2607 			pr_err("Unable to reconfigure device\n");
2608 			return ret;
2609 		}
2610 	}
2611 	udev->dev_size = val;
2612 	return count;
2613 }
2614 CONFIGFS_ATTR(tcmu_, dev_size);
2615 
2616 static ssize_t tcmu_nl_reply_supported_show(struct config_item *item,
2617 		char *page)
2618 {
2619 	struct se_dev_attrib *da = container_of(to_config_group(item),
2620 						struct se_dev_attrib, da_group);
2621 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2622 
2623 	return snprintf(page, PAGE_SIZE, "%d\n", udev->nl_reply_supported);
2624 }
2625 
2626 static ssize_t tcmu_nl_reply_supported_store(struct config_item *item,
2627 		const char *page, size_t count)
2628 {
2629 	struct se_dev_attrib *da = container_of(to_config_group(item),
2630 						struct se_dev_attrib, da_group);
2631 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2632 	s8 val;
2633 	int ret;
2634 
2635 	ret = kstrtos8(page, 0, &val);
2636 	if (ret < 0)
2637 		return ret;
2638 
2639 	udev->nl_reply_supported = val;
2640 	return count;
2641 }
2642 CONFIGFS_ATTR(tcmu_, nl_reply_supported);
2643 
2644 static ssize_t tcmu_emulate_write_cache_show(struct config_item *item,
2645 					     char *page)
2646 {
2647 	struct se_dev_attrib *da = container_of(to_config_group(item),
2648 					struct se_dev_attrib, da_group);
2649 
2650 	return snprintf(page, PAGE_SIZE, "%i\n", da->emulate_write_cache);
2651 }
2652 
2653 static int tcmu_send_emulate_write_cache(struct tcmu_dev *udev, u8 val)
2654 {
2655 	struct sk_buff *skb = NULL;
2656 	void *msg_header = NULL;
2657 	int ret = 0;
2658 
2659 	ret = tcmu_netlink_event_init(udev, TCMU_CMD_RECONFIG_DEVICE,
2660 				      &skb, &msg_header);
2661 	if (ret < 0)
2662 		return ret;
2663 	ret = nla_put_u8(skb, TCMU_ATTR_WRITECACHE, val);
2664 	if (ret < 0) {
2665 		nlmsg_free(skb);
2666 		return ret;
2667 	}
2668 	return tcmu_netlink_event_send(udev, TCMU_CMD_RECONFIG_DEVICE,
2669 				       skb, msg_header);
2670 }
2671 
2672 static ssize_t tcmu_emulate_write_cache_store(struct config_item *item,
2673 					      const char *page, size_t count)
2674 {
2675 	struct se_dev_attrib *da = container_of(to_config_group(item),
2676 					struct se_dev_attrib, da_group);
2677 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2678 	u8 val;
2679 	int ret;
2680 
2681 	ret = kstrtou8(page, 0, &val);
2682 	if (ret < 0)
2683 		return ret;
2684 
2685 	/* Check if device has been configured before */
2686 	if (target_dev_configured(&udev->se_dev)) {
2687 		ret = tcmu_send_emulate_write_cache(udev, val);
2688 		if (ret) {
2689 			pr_err("Unable to reconfigure device\n");
2690 			return ret;
2691 		}
2692 	}
2693 
2694 	da->emulate_write_cache = val;
2695 	return count;
2696 }
2697 CONFIGFS_ATTR(tcmu_, emulate_write_cache);
2698 
2699 static ssize_t tcmu_tmr_notification_show(struct config_item *item, char *page)
2700 {
2701 	struct se_dev_attrib *da = container_of(to_config_group(item),
2702 					struct se_dev_attrib, da_group);
2703 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2704 
2705 	return snprintf(page, PAGE_SIZE, "%i\n",
2706 			test_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags));
2707 }
2708 
2709 static ssize_t tcmu_tmr_notification_store(struct config_item *item,
2710 					   const char *page, size_t count)
2711 {
2712 	struct se_dev_attrib *da = container_of(to_config_group(item),
2713 					struct se_dev_attrib, da_group);
2714 	struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
2715 	u8 val;
2716 	int ret;
2717 
2718 	ret = kstrtou8(page, 0, &val);
2719 	if (ret < 0)
2720 		return ret;
2721 	if (val > 1)
2722 		return -EINVAL;
2723 
2724 	if (val)
2725 		set_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags);
2726 	else
2727 		clear_bit(TCMU_DEV_BIT_TMR_NOTIFY, &udev->flags);
2728 	return count;
2729 }
2730 CONFIGFS_ATTR(tcmu_, tmr_notification);
2731 
2732 static ssize_t tcmu_block_dev_show(struct config_item *item, char *page)
2733 {
2734 	struct se_device *se_dev = container_of(to_config_group(item),
2735 						struct se_device,
2736 						dev_action_group);
2737 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2738 
2739 	if (test_bit(TCMU_DEV_BIT_BLOCKED, &udev->flags))
2740 		return snprintf(page, PAGE_SIZE, "%s\n", "blocked");
2741 	else
2742 		return snprintf(page, PAGE_SIZE, "%s\n", "unblocked");
2743 }
2744 
2745 static ssize_t tcmu_block_dev_store(struct config_item *item, const char *page,
2746 				    size_t count)
2747 {
2748 	struct se_device *se_dev = container_of(to_config_group(item),
2749 						struct se_device,
2750 						dev_action_group);
2751 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2752 	u8 val;
2753 	int ret;
2754 
2755 	if (!target_dev_configured(&udev->se_dev)) {
2756 		pr_err("Device is not configured.\n");
2757 		return -EINVAL;
2758 	}
2759 
2760 	ret = kstrtou8(page, 0, &val);
2761 	if (ret < 0)
2762 		return ret;
2763 
2764 	if (val > 1) {
2765 		pr_err("Invalid block value %d\n", val);
2766 		return -EINVAL;
2767 	}
2768 
2769 	if (!val)
2770 		tcmu_unblock_dev(udev);
2771 	else
2772 		tcmu_block_dev(udev);
2773 	return count;
2774 }
2775 CONFIGFS_ATTR(tcmu_, block_dev);
2776 
2777 static ssize_t tcmu_reset_ring_store(struct config_item *item, const char *page,
2778 				     size_t count)
2779 {
2780 	struct se_device *se_dev = container_of(to_config_group(item),
2781 						struct se_device,
2782 						dev_action_group);
2783 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
2784 	u8 val;
2785 	int ret;
2786 
2787 	if (!target_dev_configured(&udev->se_dev)) {
2788 		pr_err("Device is not configured.\n");
2789 		return -EINVAL;
2790 	}
2791 
2792 	ret = kstrtou8(page, 0, &val);
2793 	if (ret < 0)
2794 		return ret;
2795 
2796 	if (val != 1 && val != 2) {
2797 		pr_err("Invalid reset ring value %d\n", val);
2798 		return -EINVAL;
2799 	}
2800 
2801 	tcmu_reset_ring(udev, val);
2802 	return count;
2803 }
2804 CONFIGFS_ATTR_WO(tcmu_, reset_ring);
2805 
2806 static struct configfs_attribute *tcmu_attrib_attrs[] = {
2807 	&tcmu_attr_cmd_time_out,
2808 	&tcmu_attr_qfull_time_out,
2809 	&tcmu_attr_max_data_area_mb,
2810 	&tcmu_attr_dev_config,
2811 	&tcmu_attr_dev_size,
2812 	&tcmu_attr_emulate_write_cache,
2813 	&tcmu_attr_tmr_notification,
2814 	&tcmu_attr_nl_reply_supported,
2815 	NULL,
2816 };
2817 
2818 static struct configfs_attribute **tcmu_attrs;
2819 
2820 static struct configfs_attribute *tcmu_action_attrs[] = {
2821 	&tcmu_attr_block_dev,
2822 	&tcmu_attr_reset_ring,
2823 	NULL,
2824 };
2825 
2826 static struct target_backend_ops tcmu_ops = {
2827 	.name			= "user",
2828 	.owner			= THIS_MODULE,
2829 	.transport_flags_default = TRANSPORT_FLAG_PASSTHROUGH,
2830 	.transport_flags_changeable = TRANSPORT_FLAG_PASSTHROUGH_PGR |
2831 				      TRANSPORT_FLAG_PASSTHROUGH_ALUA,
2832 	.attach_hba		= tcmu_attach_hba,
2833 	.detach_hba		= tcmu_detach_hba,
2834 	.alloc_device		= tcmu_alloc_device,
2835 	.configure_device	= tcmu_configure_device,
2836 	.destroy_device		= tcmu_destroy_device,
2837 	.free_device		= tcmu_free_device,
2838 	.parse_cdb		= tcmu_parse_cdb,
2839 	.tmr_notify		= tcmu_tmr_notify,
2840 	.set_configfs_dev_params = tcmu_set_configfs_dev_params,
2841 	.show_configfs_dev_params = tcmu_show_configfs_dev_params,
2842 	.get_device_type	= sbc_get_device_type,
2843 	.get_blocks		= tcmu_get_blocks,
2844 	.tb_dev_action_attrs	= tcmu_action_attrs,
2845 };
2846 
2847 static void find_free_blocks(void)
2848 {
2849 	struct tcmu_dev *udev;
2850 	loff_t off;
2851 	u32 start, end, block, total_freed = 0;
2852 
2853 	if (atomic_read(&global_db_count) <= tcmu_global_max_blocks)
2854 		return;
2855 
2856 	mutex_lock(&root_udev_mutex);
2857 	list_for_each_entry(udev, &root_udev, node) {
2858 		mutex_lock(&udev->cmdr_lock);
2859 
2860 		if (!target_dev_configured(&udev->se_dev)) {
2861 			mutex_unlock(&udev->cmdr_lock);
2862 			continue;
2863 		}
2864 
2865 		/* Try to complete the finished commands first */
2866 		if (tcmu_handle_completions(udev))
2867 			run_qfull_queue(udev, false);
2868 
2869 		/* Skip the udevs in idle */
2870 		if (!udev->dbi_thresh) {
2871 			mutex_unlock(&udev->cmdr_lock);
2872 			continue;
2873 		}
2874 
2875 		end = udev->dbi_max + 1;
2876 		block = find_last_bit(udev->data_bitmap, end);
2877 		if (block == udev->dbi_max) {
2878 			/*
2879 			 * The last bit is dbi_max, so it is not possible
2880 			 * reclaim any blocks.
2881 			 */
2882 			mutex_unlock(&udev->cmdr_lock);
2883 			continue;
2884 		} else if (block == end) {
2885 			/* The current udev will goto idle state */
2886 			udev->dbi_thresh = start = 0;
2887 			udev->dbi_max = 0;
2888 		} else {
2889 			udev->dbi_thresh = start = block + 1;
2890 			udev->dbi_max = block;
2891 		}
2892 
2893 		/* Here will truncate the data area from off */
2894 		off = udev->data_off + start * DATA_BLOCK_SIZE;
2895 		unmap_mapping_range(udev->inode->i_mapping, off, 0, 1);
2896 
2897 		/* Release the block pages */
2898 		tcmu_blocks_release(&udev->data_blocks, start, end);
2899 		mutex_unlock(&udev->cmdr_lock);
2900 
2901 		total_freed += end - start;
2902 		pr_debug("Freed %u blocks (total %u) from %s.\n", end - start,
2903 			 total_freed, udev->name);
2904 	}
2905 	mutex_unlock(&root_udev_mutex);
2906 
2907 	if (atomic_read(&global_db_count) > tcmu_global_max_blocks)
2908 		schedule_delayed_work(&tcmu_unmap_work, msecs_to_jiffies(5000));
2909 }
2910 
2911 static void check_timedout_devices(void)
2912 {
2913 	struct tcmu_dev *udev, *tmp_dev;
2914 	struct tcmu_cmd *cmd, *tmp_cmd;
2915 	LIST_HEAD(devs);
2916 
2917 	spin_lock_bh(&timed_out_udevs_lock);
2918 	list_splice_init(&timed_out_udevs, &devs);
2919 
2920 	list_for_each_entry_safe(udev, tmp_dev, &devs, timedout_entry) {
2921 		list_del_init(&udev->timedout_entry);
2922 		spin_unlock_bh(&timed_out_udevs_lock);
2923 
2924 		mutex_lock(&udev->cmdr_lock);
2925 
2926 		/*
2927 		 * If cmd_time_out is disabled but qfull is set deadline
2928 		 * will only reflect the qfull timeout. Ignore it.
2929 		 */
2930 		if (udev->cmd_time_out) {
2931 			list_for_each_entry_safe(cmd, tmp_cmd,
2932 						 &udev->inflight_queue,
2933 						 queue_entry) {
2934 				tcmu_check_expired_ring_cmd(cmd);
2935 			}
2936 			tcmu_set_next_deadline(&udev->inflight_queue,
2937 					       &udev->cmd_timer);
2938 		}
2939 		list_for_each_entry_safe(cmd, tmp_cmd, &udev->qfull_queue,
2940 					 queue_entry) {
2941 			tcmu_check_expired_queue_cmd(cmd);
2942 		}
2943 		tcmu_set_next_deadline(&udev->qfull_queue, &udev->qfull_timer);
2944 
2945 		mutex_unlock(&udev->cmdr_lock);
2946 
2947 		spin_lock_bh(&timed_out_udevs_lock);
2948 	}
2949 
2950 	spin_unlock_bh(&timed_out_udevs_lock);
2951 }
2952 
2953 static void tcmu_unmap_work_fn(struct work_struct *work)
2954 {
2955 	check_timedout_devices();
2956 	find_free_blocks();
2957 }
2958 
2959 static int __init tcmu_module_init(void)
2960 {
2961 	int ret, i, k, len = 0;
2962 
2963 	BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
2964 
2965 	INIT_DELAYED_WORK(&tcmu_unmap_work, tcmu_unmap_work_fn);
2966 
2967 	tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
2968 				sizeof(struct tcmu_cmd),
2969 				__alignof__(struct tcmu_cmd),
2970 				0, NULL);
2971 	if (!tcmu_cmd_cache)
2972 		return -ENOMEM;
2973 
2974 	tcmu_root_device = root_device_register("tcm_user");
2975 	if (IS_ERR(tcmu_root_device)) {
2976 		ret = PTR_ERR(tcmu_root_device);
2977 		goto out_free_cache;
2978 	}
2979 
2980 	ret = genl_register_family(&tcmu_genl_family);
2981 	if (ret < 0) {
2982 		goto out_unreg_device;
2983 	}
2984 
2985 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++)
2986 		len += sizeof(struct configfs_attribute *);
2987 	for (i = 0; passthrough_pr_attrib_attrs[i] != NULL; i++)
2988 		len += sizeof(struct configfs_attribute *);
2989 	for (i = 0; tcmu_attrib_attrs[i] != NULL; i++)
2990 		len += sizeof(struct configfs_attribute *);
2991 	len += sizeof(struct configfs_attribute *);
2992 
2993 	tcmu_attrs = kzalloc(len, GFP_KERNEL);
2994 	if (!tcmu_attrs) {
2995 		ret = -ENOMEM;
2996 		goto out_unreg_genl;
2997 	}
2998 
2999 	for (i = 0; passthrough_attrib_attrs[i] != NULL; i++)
3000 		tcmu_attrs[i] = passthrough_attrib_attrs[i];
3001 	for (k = 0; passthrough_pr_attrib_attrs[k] != NULL; k++)
3002 		tcmu_attrs[i++] = passthrough_pr_attrib_attrs[k];
3003 	for (k = 0; tcmu_attrib_attrs[k] != NULL; k++)
3004 		tcmu_attrs[i++] = tcmu_attrib_attrs[k];
3005 	tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
3006 
3007 	ret = transport_backend_register(&tcmu_ops);
3008 	if (ret)
3009 		goto out_attrs;
3010 
3011 	return 0;
3012 
3013 out_attrs:
3014 	kfree(tcmu_attrs);
3015 out_unreg_genl:
3016 	genl_unregister_family(&tcmu_genl_family);
3017 out_unreg_device:
3018 	root_device_unregister(tcmu_root_device);
3019 out_free_cache:
3020 	kmem_cache_destroy(tcmu_cmd_cache);
3021 
3022 	return ret;
3023 }
3024 
3025 static void __exit tcmu_module_exit(void)
3026 {
3027 	cancel_delayed_work_sync(&tcmu_unmap_work);
3028 	target_backend_unregister(&tcmu_ops);
3029 	kfree(tcmu_attrs);
3030 	genl_unregister_family(&tcmu_genl_family);
3031 	root_device_unregister(tcmu_root_device);
3032 	kmem_cache_destroy(tcmu_cmd_cache);
3033 }
3034 
3035 MODULE_DESCRIPTION("TCM USER subsystem plugin");
3036 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
3037 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
3038 MODULE_LICENSE("GPL");
3039 
3040 module_init(tcmu_module_init);
3041 module_exit(tcmu_module_exit);
3042