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