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