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