1 /*
2  * Copyright (C) 2013 Shaohua Li <shli@kernel.org>
3  * Copyright (C) 2014 Red Hat, Inc.
4  * Copyright (C) 2015 Arrikto, Inc.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #include <linux/spinlock.h>
21 #include <linux/module.h>
22 #include <linux/idr.h>
23 #include <linux/kernel.h>
24 #include <linux/timer.h>
25 #include <linux/parser.h>
26 #include <linux/vmalloc.h>
27 #include <linux/uio_driver.h>
28 #include <linux/stringify.h>
29 #include <linux/bitops.h>
30 #include <linux/highmem.h>
31 #include <net/genetlink.h>
32 #include <scsi/scsi_common.h>
33 #include <scsi/scsi_proto.h>
34 #include <target/target_core_base.h>
35 #include <target/target_core_fabric.h>
36 #include <target/target_core_backend.h>
37 
38 #include <linux/target_core_user.h>
39 
40 /*
41  * Define a shared-memory interface for LIO to pass SCSI commands and
42  * data to userspace for processing. This is to allow backends that
43  * are too complex for in-kernel support to be possible.
44  *
45  * It uses the UIO framework to do a lot of the device-creation and
46  * introspection work for us.
47  *
48  * See the .h file for how the ring is laid out. Note that while the
49  * command ring is defined, the particulars of the data area are
50  * not. Offset values in the command entry point to other locations
51  * internal to the mmap()ed area. There is separate space outside the
52  * command ring for data buffers. This leaves maximum flexibility for
53  * moving buffer allocations, or even page flipping or other
54  * allocation techniques, without altering the command ring layout.
55  *
56  * SECURITY:
57  * The user process must be assumed to be malicious. There's no way to
58  * prevent it breaking the command ring protocol if it wants, but in
59  * order to prevent other issues we must only ever read *data* from
60  * the shared memory area, not offsets or sizes. This applies to
61  * command ring entries as well as the mailbox. Extra code needed for
62  * this may have a 'UAM' comment.
63  */
64 
65 
66 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
67 
68 #define DATA_BLOCK_BITS 256
69 #define DATA_BLOCK_SIZE 4096
70 
71 #define CMDR_SIZE (16 * 4096)
72 #define DATA_SIZE (DATA_BLOCK_BITS * DATA_BLOCK_SIZE)
73 
74 #define TCMU_RING_SIZE (CMDR_SIZE + DATA_SIZE)
75 
76 static struct device *tcmu_root_device;
77 
78 struct tcmu_hba {
79 	u32 host_id;
80 };
81 
82 #define TCMU_CONFIG_LEN 256
83 
84 struct tcmu_dev {
85 	struct se_device se_dev;
86 
87 	char *name;
88 	struct se_hba *hba;
89 
90 #define TCMU_DEV_BIT_OPEN 0
91 #define TCMU_DEV_BIT_BROKEN 1
92 	unsigned long flags;
93 
94 	struct uio_info uio_info;
95 
96 	struct tcmu_mailbox *mb_addr;
97 	size_t dev_size;
98 	u32 cmdr_size;
99 	u32 cmdr_last_cleaned;
100 	/* Offset of data area from start of mb */
101 	/* Must add data_off and mb_addr to get the address */
102 	size_t data_off;
103 	size_t data_size;
104 
105 	DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
106 
107 	wait_queue_head_t wait_cmdr;
108 	/* TODO should this be a mutex? */
109 	spinlock_t cmdr_lock;
110 
111 	struct idr commands;
112 	spinlock_t commands_lock;
113 
114 	struct timer_list timeout;
115 
116 	char dev_config[TCMU_CONFIG_LEN];
117 };
118 
119 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
120 
121 #define CMDR_OFF sizeof(struct tcmu_mailbox)
122 
123 struct tcmu_cmd {
124 	struct se_cmd *se_cmd;
125 	struct tcmu_dev *tcmu_dev;
126 
127 	uint16_t cmd_id;
128 
129 	/* Can't use se_cmd when cleaning up expired cmds, because if
130 	   cmd has been completed then accessing se_cmd is off limits */
131 	DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
132 
133 	unsigned long deadline;
134 
135 #define TCMU_CMD_BIT_EXPIRED 0
136 	unsigned long flags;
137 };
138 
139 static struct kmem_cache *tcmu_cmd_cache;
140 
141 /* multicast group */
142 enum tcmu_multicast_groups {
143 	TCMU_MCGRP_CONFIG,
144 };
145 
146 static const struct genl_multicast_group tcmu_mcgrps[] = {
147 	[TCMU_MCGRP_CONFIG] = { .name = "config", },
148 };
149 
150 /* Our generic netlink family */
151 static struct genl_family tcmu_genl_family __ro_after_init = {
152 	.module = THIS_MODULE,
153 	.hdrsize = 0,
154 	.name = "TCM-USER",
155 	.version = 1,
156 	.maxattr = TCMU_ATTR_MAX,
157 	.mcgrps = tcmu_mcgrps,
158 	.n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
159 	.netnsok = true,
160 };
161 
162 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
163 {
164 	struct se_device *se_dev = se_cmd->se_dev;
165 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
166 	struct tcmu_cmd *tcmu_cmd;
167 	int cmd_id;
168 
169 	tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
170 	if (!tcmu_cmd)
171 		return NULL;
172 
173 	tcmu_cmd->se_cmd = se_cmd;
174 	tcmu_cmd->tcmu_dev = udev;
175 	tcmu_cmd->deadline = jiffies + msecs_to_jiffies(TCMU_TIME_OUT);
176 
177 	idr_preload(GFP_KERNEL);
178 	spin_lock_irq(&udev->commands_lock);
179 	cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 0,
180 		USHRT_MAX, GFP_NOWAIT);
181 	spin_unlock_irq(&udev->commands_lock);
182 	idr_preload_end();
183 
184 	if (cmd_id < 0) {
185 		kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
186 		return NULL;
187 	}
188 	tcmu_cmd->cmd_id = cmd_id;
189 
190 	return tcmu_cmd;
191 }
192 
193 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
194 {
195 	unsigned long offset = offset_in_page(vaddr);
196 
197 	size = round_up(size+offset, PAGE_SIZE);
198 	vaddr -= offset;
199 
200 	while (size) {
201 		flush_dcache_page(virt_to_page(vaddr));
202 		size -= PAGE_SIZE;
203 	}
204 }
205 
206 /*
207  * Some ring helper functions. We don't assume size is a power of 2 so
208  * we can't use circ_buf.h.
209  */
210 static inline size_t spc_used(size_t head, size_t tail, size_t size)
211 {
212 	int diff = head - tail;
213 
214 	if (diff >= 0)
215 		return diff;
216 	else
217 		return size + diff;
218 }
219 
220 static inline size_t spc_free(size_t head, size_t tail, size_t size)
221 {
222 	/* Keep 1 byte unused or we can't tell full from empty */
223 	return (size - spc_used(head, tail, size) - 1);
224 }
225 
226 static inline size_t head_to_end(size_t head, size_t size)
227 {
228 	return size - head;
229 }
230 
231 static inline void new_iov(struct iovec **iov, int *iov_cnt,
232 			   struct tcmu_dev *udev)
233 {
234 	struct iovec *iovec;
235 
236 	if (*iov_cnt != 0)
237 		(*iov)++;
238 	(*iov_cnt)++;
239 
240 	iovec = *iov;
241 	memset(iovec, 0, sizeof(struct iovec));
242 }
243 
244 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
245 
246 /* offset is relative to mb_addr */
247 static inline size_t get_block_offset(struct tcmu_dev *dev,
248 		int block, int remaining)
249 {
250 	return dev->data_off + block * DATA_BLOCK_SIZE +
251 		DATA_BLOCK_SIZE - remaining;
252 }
253 
254 static inline size_t iov_tail(struct tcmu_dev *udev, struct iovec *iov)
255 {
256 	return (size_t)iov->iov_base + iov->iov_len;
257 }
258 
259 static void alloc_and_scatter_data_area(struct tcmu_dev *udev,
260 	struct scatterlist *data_sg, unsigned int data_nents,
261 	struct iovec **iov, int *iov_cnt, bool copy_data)
262 {
263 	int i, block;
264 	int block_remaining = 0;
265 	void *from, *to;
266 	size_t copy_bytes, to_offset;
267 	struct scatterlist *sg;
268 
269 	for_each_sg(data_sg, sg, data_nents, i) {
270 		int sg_remaining = sg->length;
271 		from = kmap_atomic(sg_page(sg)) + sg->offset;
272 		while (sg_remaining > 0) {
273 			if (block_remaining == 0) {
274 				block = find_first_zero_bit(udev->data_bitmap,
275 						DATA_BLOCK_BITS);
276 				block_remaining = DATA_BLOCK_SIZE;
277 				set_bit(block, udev->data_bitmap);
278 			}
279 			copy_bytes = min_t(size_t, sg_remaining,
280 					block_remaining);
281 			to_offset = get_block_offset(udev, block,
282 					block_remaining);
283 			to = (void *)udev->mb_addr + to_offset;
284 			if (*iov_cnt != 0 &&
285 			    to_offset == iov_tail(udev, *iov)) {
286 				(*iov)->iov_len += copy_bytes;
287 			} else {
288 				new_iov(iov, iov_cnt, udev);
289 				(*iov)->iov_base = (void __user *) to_offset;
290 				(*iov)->iov_len = copy_bytes;
291 			}
292 			if (copy_data) {
293 				memcpy(to, from + sg->length - sg_remaining,
294 					copy_bytes);
295 				tcmu_flush_dcache_range(to, copy_bytes);
296 			}
297 			sg_remaining -= copy_bytes;
298 			block_remaining -= copy_bytes;
299 		}
300 		kunmap_atomic(from - sg->offset);
301 	}
302 }
303 
304 static void free_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd)
305 {
306 	bitmap_xor(udev->data_bitmap, udev->data_bitmap, cmd->data_bitmap,
307 		   DATA_BLOCK_BITS);
308 }
309 
310 static void gather_data_area(struct tcmu_dev *udev, unsigned long *cmd_bitmap,
311 		struct scatterlist *data_sg, unsigned int data_nents)
312 {
313 	int i, block;
314 	int block_remaining = 0;
315 	void *from, *to;
316 	size_t copy_bytes, from_offset;
317 	struct scatterlist *sg;
318 
319 	for_each_sg(data_sg, sg, data_nents, i) {
320 		int sg_remaining = sg->length;
321 		to = kmap_atomic(sg_page(sg)) + sg->offset;
322 		while (sg_remaining > 0) {
323 			if (block_remaining == 0) {
324 				block = find_first_bit(cmd_bitmap,
325 						DATA_BLOCK_BITS);
326 				block_remaining = DATA_BLOCK_SIZE;
327 				clear_bit(block, cmd_bitmap);
328 			}
329 			copy_bytes = min_t(size_t, sg_remaining,
330 					block_remaining);
331 			from_offset = get_block_offset(udev, block,
332 					block_remaining);
333 			from = (void *) udev->mb_addr + from_offset;
334 			tcmu_flush_dcache_range(from, copy_bytes);
335 			memcpy(to + sg->length - sg_remaining, from,
336 					copy_bytes);
337 
338 			sg_remaining -= copy_bytes;
339 			block_remaining -= copy_bytes;
340 		}
341 		kunmap_atomic(to - sg->offset);
342 	}
343 }
344 
345 static inline size_t spc_bitmap_free(unsigned long *bitmap)
346 {
347 	return DATA_BLOCK_SIZE * (DATA_BLOCK_BITS -
348 			bitmap_weight(bitmap, DATA_BLOCK_BITS));
349 }
350 
351 /*
352  * We can't queue a command until we have space available on the cmd ring *and*
353  * space available on the data area.
354  *
355  * Called with ring lock held.
356  */
357 static bool is_ring_space_avail(struct tcmu_dev *udev, size_t cmd_size, size_t data_needed)
358 {
359 	struct tcmu_mailbox *mb = udev->mb_addr;
360 	size_t space, cmd_needed;
361 	u32 cmd_head;
362 
363 	tcmu_flush_dcache_range(mb, sizeof(*mb));
364 
365 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
366 
367 	/*
368 	 * If cmd end-of-ring space is too small then we need space for a NOP plus
369 	 * original cmd - cmds are internally contiguous.
370 	 */
371 	if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
372 		cmd_needed = cmd_size;
373 	else
374 		cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
375 
376 	space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
377 	if (space < cmd_needed) {
378 		pr_debug("no cmd space: %u %u %u\n", cmd_head,
379 		       udev->cmdr_last_cleaned, udev->cmdr_size);
380 		return false;
381 	}
382 
383 	space = spc_bitmap_free(udev->data_bitmap);
384 	if (space < data_needed) {
385 		pr_debug("no data space: only %zu available, but ask for %zu\n",
386 				space, data_needed);
387 		return false;
388 	}
389 
390 	return true;
391 }
392 
393 static sense_reason_t
394 tcmu_queue_cmd_ring(struct tcmu_cmd *tcmu_cmd)
395 {
396 	struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
397 	struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
398 	size_t base_command_size, command_size;
399 	struct tcmu_mailbox *mb;
400 	struct tcmu_cmd_entry *entry;
401 	struct iovec *iov;
402 	int iov_cnt;
403 	uint32_t cmd_head;
404 	uint64_t cdb_off;
405 	bool copy_to_data_area;
406 	size_t data_length;
407 	DECLARE_BITMAP(old_bitmap, DATA_BLOCK_BITS);
408 
409 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
410 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
411 
412 	/*
413 	 * Must be a certain minimum size for response sense info, but
414 	 * also may be larger if the iov array is large.
415 	 *
416 	 * We prepare way too many iovs for potential uses here, because it's
417 	 * expensive to tell how many regions are freed in the bitmap
418 	*/
419 	base_command_size = max(offsetof(struct tcmu_cmd_entry,
420 				req.iov[se_cmd->t_bidi_data_nents +
421 					se_cmd->t_data_nents]),
422 				sizeof(struct tcmu_cmd_entry));
423 	command_size = base_command_size
424 		+ round_up(scsi_command_size(se_cmd->t_task_cdb), TCMU_OP_ALIGN_SIZE);
425 
426 	WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
427 
428 	spin_lock_irq(&udev->cmdr_lock);
429 
430 	mb = udev->mb_addr;
431 	cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
432 	data_length = se_cmd->data_length;
433 	if (se_cmd->se_cmd_flags & SCF_BIDI) {
434 		BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
435 		data_length += se_cmd->t_bidi_data_sg->length;
436 	}
437 	if ((command_size > (udev->cmdr_size / 2)) ||
438 	    data_length > udev->data_size) {
439 		pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
440 			"cmd ring/data area\n", command_size, data_length,
441 			udev->cmdr_size, udev->data_size);
442 		spin_unlock_irq(&udev->cmdr_lock);
443 		return TCM_INVALID_CDB_FIELD;
444 	}
445 
446 	while (!is_ring_space_avail(udev, command_size, data_length)) {
447 		int ret;
448 		DEFINE_WAIT(__wait);
449 
450 		prepare_to_wait(&udev->wait_cmdr, &__wait, TASK_INTERRUPTIBLE);
451 
452 		pr_debug("sleeping for ring space\n");
453 		spin_unlock_irq(&udev->cmdr_lock);
454 		ret = schedule_timeout(msecs_to_jiffies(TCMU_TIME_OUT));
455 		finish_wait(&udev->wait_cmdr, &__wait);
456 		if (!ret) {
457 			pr_warn("tcmu: command timed out\n");
458 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
459 		}
460 
461 		spin_lock_irq(&udev->cmdr_lock);
462 
463 		/* We dropped cmdr_lock, cmd_head is stale */
464 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
465 	}
466 
467 	/* Insert a PAD if end-of-ring space is too small */
468 	if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
469 		size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
470 
471 		entry = (void *) mb + CMDR_OFF + cmd_head;
472 		tcmu_flush_dcache_range(entry, sizeof(*entry));
473 		tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
474 		tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
475 		entry->hdr.cmd_id = 0; /* not used for PAD */
476 		entry->hdr.kflags = 0;
477 		entry->hdr.uflags = 0;
478 
479 		UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
480 
481 		cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
482 		WARN_ON(cmd_head != 0);
483 	}
484 
485 	entry = (void *) mb + CMDR_OFF + cmd_head;
486 	tcmu_flush_dcache_range(entry, sizeof(*entry));
487 	tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
488 	tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
489 	entry->hdr.cmd_id = tcmu_cmd->cmd_id;
490 	entry->hdr.kflags = 0;
491 	entry->hdr.uflags = 0;
492 
493 	bitmap_copy(old_bitmap, udev->data_bitmap, DATA_BLOCK_BITS);
494 
495 	/* Handle allocating space from the data area */
496 	iov = &entry->req.iov[0];
497 	iov_cnt = 0;
498 	copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
499 		|| se_cmd->se_cmd_flags & SCF_BIDI);
500 	alloc_and_scatter_data_area(udev, se_cmd->t_data_sg,
501 		se_cmd->t_data_nents, &iov, &iov_cnt, copy_to_data_area);
502 	entry->req.iov_cnt = iov_cnt;
503 	entry->req.iov_dif_cnt = 0;
504 
505 	/* Handle BIDI commands */
506 	iov_cnt = 0;
507 	alloc_and_scatter_data_area(udev, se_cmd->t_bidi_data_sg,
508 		se_cmd->t_bidi_data_nents, &iov, &iov_cnt, false);
509 	entry->req.iov_bidi_cnt = iov_cnt;
510 
511 	/* cmd's data_bitmap is what changed in process */
512 	bitmap_xor(tcmu_cmd->data_bitmap, old_bitmap, udev->data_bitmap,
513 			DATA_BLOCK_BITS);
514 
515 	/* All offsets relative to mb_addr, not start of entry! */
516 	cdb_off = CMDR_OFF + cmd_head + base_command_size;
517 	memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
518 	entry->req.cdb_off = cdb_off;
519 	tcmu_flush_dcache_range(entry, sizeof(*entry));
520 
521 	UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
522 	tcmu_flush_dcache_range(mb, sizeof(*mb));
523 
524 	spin_unlock_irq(&udev->cmdr_lock);
525 
526 	/* TODO: only if FLUSH and FUA? */
527 	uio_event_notify(&udev->uio_info);
528 
529 	mod_timer(&udev->timeout,
530 		round_jiffies_up(jiffies + msecs_to_jiffies(TCMU_TIME_OUT)));
531 
532 	return TCM_NO_SENSE;
533 }
534 
535 static sense_reason_t
536 tcmu_queue_cmd(struct se_cmd *se_cmd)
537 {
538 	struct se_device *se_dev = se_cmd->se_dev;
539 	struct tcmu_dev *udev = TCMU_DEV(se_dev);
540 	struct tcmu_cmd *tcmu_cmd;
541 	sense_reason_t ret;
542 
543 	tcmu_cmd = tcmu_alloc_cmd(se_cmd);
544 	if (!tcmu_cmd)
545 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
546 
547 	ret = tcmu_queue_cmd_ring(tcmu_cmd);
548 	if (ret != TCM_NO_SENSE) {
549 		pr_err("TCMU: Could not queue command\n");
550 		spin_lock_irq(&udev->commands_lock);
551 		idr_remove(&udev->commands, tcmu_cmd->cmd_id);
552 		spin_unlock_irq(&udev->commands_lock);
553 
554 		kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
555 	}
556 
557 	return ret;
558 }
559 
560 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
561 {
562 	struct se_cmd *se_cmd = cmd->se_cmd;
563 	struct tcmu_dev *udev = cmd->tcmu_dev;
564 
565 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
566 		/*
567 		 * cmd has been completed already from timeout, just reclaim
568 		 * data area space and free cmd
569 		 */
570 		free_data_area(udev, cmd);
571 
572 		kmem_cache_free(tcmu_cmd_cache, cmd);
573 		return;
574 	}
575 
576 	if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
577 		free_data_area(udev, cmd);
578 		pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
579 			cmd->se_cmd);
580 		entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
581 	} else if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
582 		memcpy(se_cmd->sense_buffer, entry->rsp.sense_buffer,
583 			       se_cmd->scsi_sense_length);
584 		free_data_area(udev, cmd);
585 	} else if (se_cmd->se_cmd_flags & SCF_BIDI) {
586 		DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
587 
588 		/* Get Data-In buffer before clean up */
589 		bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
590 		gather_data_area(udev, bitmap,
591 			se_cmd->t_bidi_data_sg, se_cmd->t_bidi_data_nents);
592 		free_data_area(udev, cmd);
593 	} else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
594 		DECLARE_BITMAP(bitmap, DATA_BLOCK_BITS);
595 
596 		bitmap_copy(bitmap, cmd->data_bitmap, DATA_BLOCK_BITS);
597 		gather_data_area(udev, bitmap,
598 			se_cmd->t_data_sg, se_cmd->t_data_nents);
599 		free_data_area(udev, cmd);
600 	} else if (se_cmd->data_direction == DMA_TO_DEVICE) {
601 		free_data_area(udev, cmd);
602 	} else if (se_cmd->data_direction != DMA_NONE) {
603 		pr_warn("TCMU: data direction was %d!\n",
604 			se_cmd->data_direction);
605 	}
606 
607 	target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
608 	cmd->se_cmd = NULL;
609 
610 	kmem_cache_free(tcmu_cmd_cache, cmd);
611 }
612 
613 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
614 {
615 	struct tcmu_mailbox *mb;
616 	unsigned long flags;
617 	int handled = 0;
618 
619 	if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
620 		pr_err("ring broken, not handling completions\n");
621 		return 0;
622 	}
623 
624 	spin_lock_irqsave(&udev->cmdr_lock, flags);
625 
626 	mb = udev->mb_addr;
627 	tcmu_flush_dcache_range(mb, sizeof(*mb));
628 
629 	while (udev->cmdr_last_cleaned != ACCESS_ONCE(mb->cmd_tail)) {
630 
631 		struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
632 		struct tcmu_cmd *cmd;
633 
634 		tcmu_flush_dcache_range(entry, sizeof(*entry));
635 
636 		if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
637 			UPDATE_HEAD(udev->cmdr_last_cleaned,
638 				    tcmu_hdr_get_len(entry->hdr.len_op),
639 				    udev->cmdr_size);
640 			continue;
641 		}
642 		WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
643 
644 		spin_lock(&udev->commands_lock);
645 		cmd = idr_find(&udev->commands, entry->hdr.cmd_id);
646 		if (cmd)
647 			idr_remove(&udev->commands, cmd->cmd_id);
648 		spin_unlock(&udev->commands_lock);
649 
650 		if (!cmd) {
651 			pr_err("cmd_id not found, ring is broken\n");
652 			set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
653 			break;
654 		}
655 
656 		tcmu_handle_completion(cmd, entry);
657 
658 		UPDATE_HEAD(udev->cmdr_last_cleaned,
659 			    tcmu_hdr_get_len(entry->hdr.len_op),
660 			    udev->cmdr_size);
661 
662 		handled++;
663 	}
664 
665 	if (mb->cmd_tail == mb->cmd_head)
666 		del_timer(&udev->timeout); /* no more pending cmds */
667 
668 	spin_unlock_irqrestore(&udev->cmdr_lock, flags);
669 
670 	wake_up(&udev->wait_cmdr);
671 
672 	return handled;
673 }
674 
675 static int tcmu_check_expired_cmd(int id, void *p, void *data)
676 {
677 	struct tcmu_cmd *cmd = p;
678 
679 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
680 		return 0;
681 
682 	if (!time_after(jiffies, cmd->deadline))
683 		return 0;
684 
685 	set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
686 	target_complete_cmd(cmd->se_cmd, SAM_STAT_CHECK_CONDITION);
687 	cmd->se_cmd = NULL;
688 
689 	return 0;
690 }
691 
692 static void tcmu_device_timedout(unsigned long data)
693 {
694 	struct tcmu_dev *udev = (struct tcmu_dev *)data;
695 	unsigned long flags;
696 	int handled;
697 
698 	handled = tcmu_handle_completions(udev);
699 
700 	pr_warn("%d completions handled from timeout\n", handled);
701 
702 	spin_lock_irqsave(&udev->commands_lock, flags);
703 	idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
704 	spin_unlock_irqrestore(&udev->commands_lock, flags);
705 
706 	/*
707 	 * We don't need to wakeup threads on wait_cmdr since they have their
708 	 * own timeout.
709 	 */
710 }
711 
712 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
713 {
714 	struct tcmu_hba *tcmu_hba;
715 
716 	tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
717 	if (!tcmu_hba)
718 		return -ENOMEM;
719 
720 	tcmu_hba->host_id = host_id;
721 	hba->hba_ptr = tcmu_hba;
722 
723 	return 0;
724 }
725 
726 static void tcmu_detach_hba(struct se_hba *hba)
727 {
728 	kfree(hba->hba_ptr);
729 	hba->hba_ptr = NULL;
730 }
731 
732 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
733 {
734 	struct tcmu_dev *udev;
735 
736 	udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
737 	if (!udev)
738 		return NULL;
739 
740 	udev->name = kstrdup(name, GFP_KERNEL);
741 	if (!udev->name) {
742 		kfree(udev);
743 		return NULL;
744 	}
745 
746 	udev->hba = hba;
747 
748 	init_waitqueue_head(&udev->wait_cmdr);
749 	spin_lock_init(&udev->cmdr_lock);
750 
751 	idr_init(&udev->commands);
752 	spin_lock_init(&udev->commands_lock);
753 
754 	setup_timer(&udev->timeout, tcmu_device_timedout,
755 		(unsigned long)udev);
756 
757 	return &udev->se_dev;
758 }
759 
760 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
761 {
762 	struct tcmu_dev *tcmu_dev = container_of(info, struct tcmu_dev, uio_info);
763 
764 	tcmu_handle_completions(tcmu_dev);
765 
766 	return 0;
767 }
768 
769 /*
770  * mmap code from uio.c. Copied here because we want to hook mmap()
771  * and this stuff must come along.
772  */
773 static int tcmu_find_mem_index(struct vm_area_struct *vma)
774 {
775 	struct tcmu_dev *udev = vma->vm_private_data;
776 	struct uio_info *info = &udev->uio_info;
777 
778 	if (vma->vm_pgoff < MAX_UIO_MAPS) {
779 		if (info->mem[vma->vm_pgoff].size == 0)
780 			return -1;
781 		return (int)vma->vm_pgoff;
782 	}
783 	return -1;
784 }
785 
786 static int tcmu_vma_fault(struct vm_fault *vmf)
787 {
788 	struct tcmu_dev *udev = vmf->vma->vm_private_data;
789 	struct uio_info *info = &udev->uio_info;
790 	struct page *page;
791 	unsigned long offset;
792 	void *addr;
793 
794 	int mi = tcmu_find_mem_index(vmf->vma);
795 	if (mi < 0)
796 		return VM_FAULT_SIGBUS;
797 
798 	/*
799 	 * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
800 	 * to use mem[N].
801 	 */
802 	offset = (vmf->pgoff - mi) << PAGE_SHIFT;
803 
804 	addr = (void *)(unsigned long)info->mem[mi].addr + offset;
805 	if (info->mem[mi].memtype == UIO_MEM_LOGICAL)
806 		page = virt_to_page(addr);
807 	else
808 		page = vmalloc_to_page(addr);
809 	get_page(page);
810 	vmf->page = page;
811 	return 0;
812 }
813 
814 static const struct vm_operations_struct tcmu_vm_ops = {
815 	.fault = tcmu_vma_fault,
816 };
817 
818 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
819 {
820 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
821 
822 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
823 	vma->vm_ops = &tcmu_vm_ops;
824 
825 	vma->vm_private_data = udev;
826 
827 	/* Ensure the mmap is exactly the right size */
828 	if (vma_pages(vma) != (TCMU_RING_SIZE >> PAGE_SHIFT))
829 		return -EINVAL;
830 
831 	return 0;
832 }
833 
834 static int tcmu_open(struct uio_info *info, struct inode *inode)
835 {
836 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
837 
838 	/* O_EXCL not supported for char devs, so fake it? */
839 	if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
840 		return -EBUSY;
841 
842 	pr_debug("open\n");
843 
844 	return 0;
845 }
846 
847 static int tcmu_release(struct uio_info *info, struct inode *inode)
848 {
849 	struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
850 
851 	clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
852 
853 	pr_debug("close\n");
854 
855 	return 0;
856 }
857 
858 static int tcmu_netlink_event(enum tcmu_genl_cmd cmd, const char *name, int minor)
859 {
860 	struct sk_buff *skb;
861 	void *msg_header;
862 	int ret = -ENOMEM;
863 
864 	skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
865 	if (!skb)
866 		return ret;
867 
868 	msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
869 	if (!msg_header)
870 		goto free_skb;
871 
872 	ret = nla_put_string(skb, TCMU_ATTR_DEVICE, name);
873 	if (ret < 0)
874 		goto free_skb;
875 
876 	ret = nla_put_u32(skb, TCMU_ATTR_MINOR, minor);
877 	if (ret < 0)
878 		goto free_skb;
879 
880 	genlmsg_end(skb, msg_header);
881 
882 	ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
883 				TCMU_MCGRP_CONFIG, GFP_KERNEL);
884 
885 	/* We don't care if no one is listening */
886 	if (ret == -ESRCH)
887 		ret = 0;
888 
889 	return ret;
890 free_skb:
891 	nlmsg_free(skb);
892 	return ret;
893 }
894 
895 static int tcmu_configure_device(struct se_device *dev)
896 {
897 	struct tcmu_dev *udev = TCMU_DEV(dev);
898 	struct tcmu_hba *hba = udev->hba->hba_ptr;
899 	struct uio_info *info;
900 	struct tcmu_mailbox *mb;
901 	size_t size;
902 	size_t used;
903 	int ret = 0;
904 	char *str;
905 
906 	info = &udev->uio_info;
907 
908 	size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
909 			udev->dev_config);
910 	size += 1; /* for \0 */
911 	str = kmalloc(size, GFP_KERNEL);
912 	if (!str)
913 		return -ENOMEM;
914 
915 	used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
916 
917 	if (udev->dev_config[0])
918 		snprintf(str + used, size - used, "/%s", udev->dev_config);
919 
920 	info->name = str;
921 
922 	udev->mb_addr = vzalloc(TCMU_RING_SIZE);
923 	if (!udev->mb_addr) {
924 		ret = -ENOMEM;
925 		goto err_vzalloc;
926 	}
927 
928 	/* mailbox fits in first part of CMDR space */
929 	udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
930 	udev->data_off = CMDR_SIZE;
931 	udev->data_size = TCMU_RING_SIZE - CMDR_SIZE;
932 
933 	mb = udev->mb_addr;
934 	mb->version = TCMU_MAILBOX_VERSION;
935 	mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC;
936 	mb->cmdr_off = CMDR_OFF;
937 	mb->cmdr_size = udev->cmdr_size;
938 
939 	WARN_ON(!PAGE_ALIGNED(udev->data_off));
940 	WARN_ON(udev->data_size % PAGE_SIZE);
941 	WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
942 
943 	info->version = __stringify(TCMU_MAILBOX_VERSION);
944 
945 	info->mem[0].name = "tcm-user command & data buffer";
946 	info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
947 	info->mem[0].size = TCMU_RING_SIZE;
948 	info->mem[0].memtype = UIO_MEM_VIRTUAL;
949 
950 	info->irqcontrol = tcmu_irqcontrol;
951 	info->irq = UIO_IRQ_CUSTOM;
952 
953 	info->mmap = tcmu_mmap;
954 	info->open = tcmu_open;
955 	info->release = tcmu_release;
956 
957 	ret = uio_register_device(tcmu_root_device, info);
958 	if (ret)
959 		goto err_register;
960 
961 	/* User can set hw_block_size before enable the device */
962 	if (dev->dev_attrib.hw_block_size == 0)
963 		dev->dev_attrib.hw_block_size = 512;
964 	/* Other attributes can be configured in userspace */
965 	dev->dev_attrib.hw_max_sectors = 128;
966 	dev->dev_attrib.hw_queue_depth = 128;
967 
968 	ret = tcmu_netlink_event(TCMU_CMD_ADDED_DEVICE, udev->uio_info.name,
969 				 udev->uio_info.uio_dev->minor);
970 	if (ret)
971 		goto err_netlink;
972 
973 	return 0;
974 
975 err_netlink:
976 	uio_unregister_device(&udev->uio_info);
977 err_register:
978 	vfree(udev->mb_addr);
979 err_vzalloc:
980 	kfree(info->name);
981 
982 	return ret;
983 }
984 
985 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
986 {
987 	if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
988 		kmem_cache_free(tcmu_cmd_cache, cmd);
989 		return 0;
990 	}
991 	return -EINVAL;
992 }
993 
994 static void tcmu_dev_call_rcu(struct rcu_head *p)
995 {
996 	struct se_device *dev = container_of(p, struct se_device, rcu_head);
997 	struct tcmu_dev *udev = TCMU_DEV(dev);
998 
999 	kfree(udev);
1000 }
1001 
1002 static void tcmu_free_device(struct se_device *dev)
1003 {
1004 	struct tcmu_dev *udev = TCMU_DEV(dev);
1005 	struct tcmu_cmd *cmd;
1006 	bool all_expired = true;
1007 	int i;
1008 
1009 	del_timer_sync(&udev->timeout);
1010 
1011 	vfree(udev->mb_addr);
1012 
1013 	/* Upper layer should drain all requests before calling this */
1014 	spin_lock_irq(&udev->commands_lock);
1015 	idr_for_each_entry(&udev->commands, cmd, i) {
1016 		if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1017 			all_expired = false;
1018 	}
1019 	idr_destroy(&udev->commands);
1020 	spin_unlock_irq(&udev->commands_lock);
1021 	WARN_ON(!all_expired);
1022 
1023 	/* Device was configured */
1024 	if (udev->uio_info.uio_dev) {
1025 		tcmu_netlink_event(TCMU_CMD_REMOVED_DEVICE, udev->uio_info.name,
1026 				   udev->uio_info.uio_dev->minor);
1027 
1028 		uio_unregister_device(&udev->uio_info);
1029 		kfree(udev->uio_info.name);
1030 		kfree(udev->name);
1031 	}
1032 	call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1033 }
1034 
1035 enum {
1036 	Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_err,
1037 };
1038 
1039 static match_table_t tokens = {
1040 	{Opt_dev_config, "dev_config=%s"},
1041 	{Opt_dev_size, "dev_size=%u"},
1042 	{Opt_hw_block_size, "hw_block_size=%u"},
1043 	{Opt_err, NULL}
1044 };
1045 
1046 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
1047 		const char *page, ssize_t count)
1048 {
1049 	struct tcmu_dev *udev = TCMU_DEV(dev);
1050 	char *orig, *ptr, *opts, *arg_p;
1051 	substring_t args[MAX_OPT_ARGS];
1052 	int ret = 0, token;
1053 	unsigned long tmp_ul;
1054 
1055 	opts = kstrdup(page, GFP_KERNEL);
1056 	if (!opts)
1057 		return -ENOMEM;
1058 
1059 	orig = opts;
1060 
1061 	while ((ptr = strsep(&opts, ",\n")) != NULL) {
1062 		if (!*ptr)
1063 			continue;
1064 
1065 		token = match_token(ptr, tokens, args);
1066 		switch (token) {
1067 		case Opt_dev_config:
1068 			if (match_strlcpy(udev->dev_config, &args[0],
1069 					  TCMU_CONFIG_LEN) == 0) {
1070 				ret = -EINVAL;
1071 				break;
1072 			}
1073 			pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
1074 			break;
1075 		case Opt_dev_size:
1076 			arg_p = match_strdup(&args[0]);
1077 			if (!arg_p) {
1078 				ret = -ENOMEM;
1079 				break;
1080 			}
1081 			ret = kstrtoul(arg_p, 0, (unsigned long *) &udev->dev_size);
1082 			kfree(arg_p);
1083 			if (ret < 0)
1084 				pr_err("kstrtoul() failed for dev_size=\n");
1085 			break;
1086 		case Opt_hw_block_size:
1087 			arg_p = match_strdup(&args[0]);
1088 			if (!arg_p) {
1089 				ret = -ENOMEM;
1090 				break;
1091 			}
1092 			ret = kstrtoul(arg_p, 0, &tmp_ul);
1093 			kfree(arg_p);
1094 			if (ret < 0) {
1095 				pr_err("kstrtoul() failed for hw_block_size=\n");
1096 				break;
1097 			}
1098 			if (!tmp_ul) {
1099 				pr_err("hw_block_size must be nonzero\n");
1100 				break;
1101 			}
1102 			dev->dev_attrib.hw_block_size = tmp_ul;
1103 			break;
1104 		default:
1105 			break;
1106 		}
1107 	}
1108 
1109 	kfree(orig);
1110 	return (!ret) ? count : ret;
1111 }
1112 
1113 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
1114 {
1115 	struct tcmu_dev *udev = TCMU_DEV(dev);
1116 	ssize_t bl = 0;
1117 
1118 	bl = sprintf(b + bl, "Config: %s ",
1119 		     udev->dev_config[0] ? udev->dev_config : "NULL");
1120 	bl += sprintf(b + bl, "Size: %zu\n", udev->dev_size);
1121 
1122 	return bl;
1123 }
1124 
1125 static sector_t tcmu_get_blocks(struct se_device *dev)
1126 {
1127 	struct tcmu_dev *udev = TCMU_DEV(dev);
1128 
1129 	return div_u64(udev->dev_size - dev->dev_attrib.block_size,
1130 		       dev->dev_attrib.block_size);
1131 }
1132 
1133 static sense_reason_t
1134 tcmu_parse_cdb(struct se_cmd *cmd)
1135 {
1136 	return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
1137 }
1138 
1139 static const struct target_backend_ops tcmu_ops = {
1140 	.name			= "user",
1141 	.owner			= THIS_MODULE,
1142 	.transport_flags	= TRANSPORT_FLAG_PASSTHROUGH,
1143 	.attach_hba		= tcmu_attach_hba,
1144 	.detach_hba		= tcmu_detach_hba,
1145 	.alloc_device		= tcmu_alloc_device,
1146 	.configure_device	= tcmu_configure_device,
1147 	.free_device		= tcmu_free_device,
1148 	.parse_cdb		= tcmu_parse_cdb,
1149 	.set_configfs_dev_params = tcmu_set_configfs_dev_params,
1150 	.show_configfs_dev_params = tcmu_show_configfs_dev_params,
1151 	.get_device_type	= sbc_get_device_type,
1152 	.get_blocks		= tcmu_get_blocks,
1153 	.tb_dev_attrib_attrs	= passthrough_attrib_attrs,
1154 };
1155 
1156 static int __init tcmu_module_init(void)
1157 {
1158 	int ret;
1159 
1160 	BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
1161 
1162 	tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
1163 				sizeof(struct tcmu_cmd),
1164 				__alignof__(struct tcmu_cmd),
1165 				0, NULL);
1166 	if (!tcmu_cmd_cache)
1167 		return -ENOMEM;
1168 
1169 	tcmu_root_device = root_device_register("tcm_user");
1170 	if (IS_ERR(tcmu_root_device)) {
1171 		ret = PTR_ERR(tcmu_root_device);
1172 		goto out_free_cache;
1173 	}
1174 
1175 	ret = genl_register_family(&tcmu_genl_family);
1176 	if (ret < 0) {
1177 		goto out_unreg_device;
1178 	}
1179 
1180 	ret = transport_backend_register(&tcmu_ops);
1181 	if (ret)
1182 		goto out_unreg_genl;
1183 
1184 	return 0;
1185 
1186 out_unreg_genl:
1187 	genl_unregister_family(&tcmu_genl_family);
1188 out_unreg_device:
1189 	root_device_unregister(tcmu_root_device);
1190 out_free_cache:
1191 	kmem_cache_destroy(tcmu_cmd_cache);
1192 
1193 	return ret;
1194 }
1195 
1196 static void __exit tcmu_module_exit(void)
1197 {
1198 	target_backend_unregister(&tcmu_ops);
1199 	genl_unregister_family(&tcmu_genl_family);
1200 	root_device_unregister(tcmu_root_device);
1201 	kmem_cache_destroy(tcmu_cmd_cache);
1202 }
1203 
1204 MODULE_DESCRIPTION("TCM USER subsystem plugin");
1205 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
1206 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
1207 MODULE_LICENSE("GPL");
1208 
1209 module_init(tcmu_module_init);
1210 module_exit(tcmu_module_exit);
1211