]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/target/target_core_user.c
tcmu: simplify scatter_data_area error handling
[linux.git] / drivers / target / target_core_user.c
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  * Define a shared-memory interface for LIO to pass SCSI commands and
47  * data to userspace for processing. This is to allow backends that
48  * are too complex for in-kernel support to be possible.
49  *
50  * It uses the UIO framework to do a lot of the device-creation and
51  * introspection work for us.
52  *
53  * See the .h file for how the ring is laid out. Note that while the
54  * command ring is defined, the particulars of the data area are
55  * not. Offset values in the command entry point to other locations
56  * internal to the mmap()ed area. There is separate space outside the
57  * command ring for data buffers. This leaves maximum flexibility for
58  * moving buffer allocations, or even page flipping or other
59  * allocation techniques, without altering the command ring layout.
60  *
61  * SECURITY:
62  * The user process must be assumed to be malicious. There's no way to
63  * prevent it breaking the command ring protocol if it wants, but in
64  * order to prevent other issues we must only ever read *data* from
65  * the shared memory area, not offsets or sizes. This applies to
66  * command ring entries as well as the mailbox. Extra code needed for
67  * this may have a 'UAM' comment.
68  */
69
70 #define TCMU_TIME_OUT (30 * MSEC_PER_SEC)
71
72 /* For cmd area, the size is fixed 8MB */
73 #define CMDR_SIZE (8 * 1024 * 1024)
74
75 /*
76  * For data area, the block size is PAGE_SIZE and
77  * the total size is 256K * PAGE_SIZE.
78  */
79 #define DATA_BLOCK_SIZE PAGE_SIZE
80 #define DATA_BLOCK_BITS (256 * 1024)
81 #define DATA_SIZE (DATA_BLOCK_BITS * DATA_BLOCK_SIZE)
82 #define DATA_BLOCK_INIT_BITS 128
83
84 /* The total size of the ring is 8M + 256K * PAGE_SIZE */
85 #define TCMU_RING_SIZE (CMDR_SIZE + DATA_SIZE)
86
87 /* Default maximum of the global data blocks(512K * PAGE_SIZE) */
88 #define TCMU_GLOBAL_MAX_BLOCKS (512 * 1024)
89
90 static u8 tcmu_kern_cmd_reply_supported;
91
92 static struct device *tcmu_root_device;
93
94 struct tcmu_hba {
95         u32 host_id;
96 };
97
98 #define TCMU_CONFIG_LEN 256
99
100 struct tcmu_nl_cmd {
101         /* wake up thread waiting for reply */
102         struct completion complete;
103         int cmd;
104         int status;
105 };
106
107 struct tcmu_dev {
108         struct list_head node;
109         struct kref kref;
110         struct se_device se_dev;
111
112         char *name;
113         struct se_hba *hba;
114
115 #define TCMU_DEV_BIT_OPEN 0
116 #define TCMU_DEV_BIT_BROKEN 1
117         unsigned long flags;
118
119         struct uio_info uio_info;
120
121         struct inode *inode;
122
123         struct tcmu_mailbox *mb_addr;
124         size_t dev_size;
125         u32 cmdr_size;
126         u32 cmdr_last_cleaned;
127         /* Offset of data area from start of mb */
128         /* Must add data_off and mb_addr to get the address */
129         size_t data_off;
130         size_t data_size;
131
132         wait_queue_head_t wait_cmdr;
133         struct mutex cmdr_lock;
134
135         bool waiting_global;
136         uint32_t dbi_max;
137         uint32_t dbi_thresh;
138         DECLARE_BITMAP(data_bitmap, DATA_BLOCK_BITS);
139         struct radix_tree_root data_blocks;
140
141         struct idr commands;
142
143         struct timer_list timeout;
144         unsigned int cmd_time_out;
145         struct list_head timedout_entry;
146
147         spinlock_t nl_cmd_lock;
148         struct tcmu_nl_cmd curr_nl_cmd;
149         /* wake up threads waiting on curr_nl_cmd */
150         wait_queue_head_t nl_cmd_wq;
151
152         char dev_config[TCMU_CONFIG_LEN];
153
154         int nl_reply_supported;
155 };
156
157 #define TCMU_DEV(_se_dev) container_of(_se_dev, struct tcmu_dev, se_dev)
158
159 #define CMDR_OFF sizeof(struct tcmu_mailbox)
160
161 struct tcmu_cmd {
162         struct se_cmd *se_cmd;
163         struct tcmu_dev *tcmu_dev;
164
165         uint16_t cmd_id;
166
167         /* Can't use se_cmd when cleaning up expired cmds, because if
168            cmd has been completed then accessing se_cmd is off limits */
169         uint32_t dbi_cnt;
170         uint32_t dbi_cur;
171         uint32_t *dbi;
172
173         unsigned long deadline;
174
175 #define TCMU_CMD_BIT_EXPIRED 0
176         unsigned long flags;
177 };
178
179 static DEFINE_MUTEX(root_udev_mutex);
180 static LIST_HEAD(root_udev);
181
182 static DEFINE_SPINLOCK(timed_out_udevs_lock);
183 static LIST_HEAD(timed_out_udevs);
184
185 static atomic_t global_db_count = ATOMIC_INIT(0);
186 static struct work_struct tcmu_unmap_work;
187
188 static struct kmem_cache *tcmu_cmd_cache;
189
190 /* multicast group */
191 enum tcmu_multicast_groups {
192         TCMU_MCGRP_CONFIG,
193 };
194
195 static const struct genl_multicast_group tcmu_mcgrps[] = {
196         [TCMU_MCGRP_CONFIG] = { .name = "config", },
197 };
198
199 static struct nla_policy tcmu_attr_policy[TCMU_ATTR_MAX+1] = {
200         [TCMU_ATTR_DEVICE]      = { .type = NLA_STRING },
201         [TCMU_ATTR_MINOR]       = { .type = NLA_U32 },
202         [TCMU_ATTR_CMD_STATUS]  = { .type = NLA_S32 },
203         [TCMU_ATTR_DEVICE_ID]   = { .type = NLA_U32 },
204         [TCMU_ATTR_SUPP_KERN_CMD_REPLY] = { .type = NLA_U8 },
205 };
206
207 static int tcmu_genl_cmd_done(struct genl_info *info, int completed_cmd)
208 {
209         struct se_device *dev;
210         struct tcmu_dev *udev;
211         struct tcmu_nl_cmd *nl_cmd;
212         int dev_id, rc, ret = 0;
213         bool is_removed = (completed_cmd == TCMU_CMD_REMOVED_DEVICE);
214
215         if (!info->attrs[TCMU_ATTR_CMD_STATUS] ||
216             !info->attrs[TCMU_ATTR_DEVICE_ID]) {
217                 printk(KERN_ERR "TCMU_ATTR_CMD_STATUS or TCMU_ATTR_DEVICE_ID not set, doing nothing\n");
218                 return -EINVAL;
219         }
220
221         dev_id = nla_get_u32(info->attrs[TCMU_ATTR_DEVICE_ID]);
222         rc = nla_get_s32(info->attrs[TCMU_ATTR_CMD_STATUS]);
223
224         dev = target_find_device(dev_id, !is_removed);
225         if (!dev) {
226                 printk(KERN_ERR "tcmu nl cmd %u/%u completion could not find device with dev id %u.\n",
227                        completed_cmd, rc, dev_id);
228                 return -ENODEV;
229         }
230         udev = TCMU_DEV(dev);
231
232         spin_lock(&udev->nl_cmd_lock);
233         nl_cmd = &udev->curr_nl_cmd;
234
235         pr_debug("genl cmd done got id %d curr %d done %d rc %d\n", dev_id,
236                  nl_cmd->cmd, completed_cmd, rc);
237
238         if (nl_cmd->cmd != completed_cmd) {
239                 printk(KERN_ERR "Mismatched commands (Expecting reply for %d. Current %d).\n",
240                        completed_cmd, nl_cmd->cmd);
241                 ret = -EINVAL;
242         } else {
243                 nl_cmd->status = rc;
244         }
245
246         spin_unlock(&udev->nl_cmd_lock);
247         if (!is_removed)
248                  target_undepend_item(&dev->dev_group.cg_item);
249         if (!ret)
250                 complete(&nl_cmd->complete);
251         return ret;
252 }
253
254 static int tcmu_genl_rm_dev_done(struct sk_buff *skb, struct genl_info *info)
255 {
256         return tcmu_genl_cmd_done(info, TCMU_CMD_REMOVED_DEVICE);
257 }
258
259 static int tcmu_genl_add_dev_done(struct sk_buff *skb, struct genl_info *info)
260 {
261         return tcmu_genl_cmd_done(info, TCMU_CMD_ADDED_DEVICE);
262 }
263
264 static int tcmu_genl_reconfig_dev_done(struct sk_buff *skb,
265                                        struct genl_info *info)
266 {
267         return tcmu_genl_cmd_done(info, TCMU_CMD_RECONFIG_DEVICE);
268 }
269
270 static int tcmu_genl_set_features(struct sk_buff *skb, struct genl_info *info)
271 {
272         if (info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]) {
273                 tcmu_kern_cmd_reply_supported  =
274                         nla_get_u8(info->attrs[TCMU_ATTR_SUPP_KERN_CMD_REPLY]);
275                 printk(KERN_INFO "tcmu daemon: command reply support %u.\n",
276                        tcmu_kern_cmd_reply_supported);
277         }
278
279         return 0;
280 }
281
282 static const struct genl_ops tcmu_genl_ops[] = {
283         {
284                 .cmd    = TCMU_CMD_SET_FEATURES,
285                 .flags  = GENL_ADMIN_PERM,
286                 .policy = tcmu_attr_policy,
287                 .doit   = tcmu_genl_set_features,
288         },
289         {
290                 .cmd    = TCMU_CMD_ADDED_DEVICE_DONE,
291                 .flags  = GENL_ADMIN_PERM,
292                 .policy = tcmu_attr_policy,
293                 .doit   = tcmu_genl_add_dev_done,
294         },
295         {
296                 .cmd    = TCMU_CMD_REMOVED_DEVICE_DONE,
297                 .flags  = GENL_ADMIN_PERM,
298                 .policy = tcmu_attr_policy,
299                 .doit   = tcmu_genl_rm_dev_done,
300         },
301         {
302                 .cmd    = TCMU_CMD_RECONFIG_DEVICE_DONE,
303                 .flags  = GENL_ADMIN_PERM,
304                 .policy = tcmu_attr_policy,
305                 .doit   = tcmu_genl_reconfig_dev_done,
306         },
307 };
308
309 /* Our generic netlink family */
310 static struct genl_family tcmu_genl_family __ro_after_init = {
311         .module = THIS_MODULE,
312         .hdrsize = 0,
313         .name = "TCM-USER",
314         .version = 2,
315         .maxattr = TCMU_ATTR_MAX,
316         .mcgrps = tcmu_mcgrps,
317         .n_mcgrps = ARRAY_SIZE(tcmu_mcgrps),
318         .netnsok = true,
319         .ops = tcmu_genl_ops,
320         .n_ops = ARRAY_SIZE(tcmu_genl_ops),
321 };
322
323 #define tcmu_cmd_set_dbi_cur(cmd, index) ((cmd)->dbi_cur = (index))
324 #define tcmu_cmd_reset_dbi_cur(cmd) tcmu_cmd_set_dbi_cur(cmd, 0)
325 #define tcmu_cmd_set_dbi(cmd, index) ((cmd)->dbi[(cmd)->dbi_cur++] = (index))
326 #define tcmu_cmd_get_dbi(cmd) ((cmd)->dbi[(cmd)->dbi_cur++])
327
328 static void tcmu_cmd_free_data(struct tcmu_cmd *tcmu_cmd, uint32_t len)
329 {
330         struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
331         uint32_t i;
332
333         for (i = 0; i < len; i++)
334                 clear_bit(tcmu_cmd->dbi[i], udev->data_bitmap);
335 }
336
337 static inline bool tcmu_get_empty_block(struct tcmu_dev *udev,
338                                         struct tcmu_cmd *tcmu_cmd)
339 {
340         struct page *page;
341         int ret, dbi;
342
343         dbi = find_first_zero_bit(udev->data_bitmap, udev->dbi_thresh);
344         if (dbi == udev->dbi_thresh)
345                 return false;
346
347         page = radix_tree_lookup(&udev->data_blocks, dbi);
348         if (!page) {
349                 if (atomic_add_return(1, &global_db_count) >
350                                         TCMU_GLOBAL_MAX_BLOCKS) {
351                         atomic_dec(&global_db_count);
352                         return false;
353                 }
354
355                 /* try to get new page from the mm */
356                 page = alloc_page(GFP_KERNEL);
357                 if (!page)
358                         goto err_alloc;
359
360                 ret = radix_tree_insert(&udev->data_blocks, dbi, page);
361                 if (ret)
362                         goto err_insert;
363         }
364
365         if (dbi > udev->dbi_max)
366                 udev->dbi_max = dbi;
367
368         set_bit(dbi, udev->data_bitmap);
369         tcmu_cmd_set_dbi(tcmu_cmd, dbi);
370
371         return true;
372 err_insert:
373         __free_page(page);
374 err_alloc:
375         atomic_dec(&global_db_count);
376         return false;
377 }
378
379 static bool tcmu_get_empty_blocks(struct tcmu_dev *udev,
380                                   struct tcmu_cmd *tcmu_cmd)
381 {
382         int i;
383
384         udev->waiting_global = false;
385
386         for (i = tcmu_cmd->dbi_cur; i < tcmu_cmd->dbi_cnt; i++) {
387                 if (!tcmu_get_empty_block(udev, tcmu_cmd))
388                         goto err;
389         }
390         return true;
391
392 err:
393         udev->waiting_global = true;
394         schedule_work(&tcmu_unmap_work);
395         return false;
396 }
397
398 static inline struct page *
399 tcmu_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
400 {
401         return radix_tree_lookup(&udev->data_blocks, dbi);
402 }
403
404 static inline void tcmu_free_cmd(struct tcmu_cmd *tcmu_cmd)
405 {
406         kfree(tcmu_cmd->dbi);
407         kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
408 }
409
410 static inline size_t tcmu_cmd_get_data_length(struct tcmu_cmd *tcmu_cmd)
411 {
412         struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
413         size_t data_length = round_up(se_cmd->data_length, DATA_BLOCK_SIZE);
414
415         if (se_cmd->se_cmd_flags & SCF_BIDI) {
416                 BUG_ON(!(se_cmd->t_bidi_data_sg && se_cmd->t_bidi_data_nents));
417                 data_length += round_up(se_cmd->t_bidi_data_sg->length,
418                                 DATA_BLOCK_SIZE);
419         }
420
421         return data_length;
422 }
423
424 static inline uint32_t tcmu_cmd_get_block_cnt(struct tcmu_cmd *tcmu_cmd)
425 {
426         size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
427
428         return data_length / DATA_BLOCK_SIZE;
429 }
430
431 static struct tcmu_cmd *tcmu_alloc_cmd(struct se_cmd *se_cmd)
432 {
433         struct se_device *se_dev = se_cmd->se_dev;
434         struct tcmu_dev *udev = TCMU_DEV(se_dev);
435         struct tcmu_cmd *tcmu_cmd;
436
437         tcmu_cmd = kmem_cache_zalloc(tcmu_cmd_cache, GFP_KERNEL);
438         if (!tcmu_cmd)
439                 return NULL;
440
441         tcmu_cmd->se_cmd = se_cmd;
442         tcmu_cmd->tcmu_dev = udev;
443
444         tcmu_cmd_reset_dbi_cur(tcmu_cmd);
445         tcmu_cmd->dbi_cnt = tcmu_cmd_get_block_cnt(tcmu_cmd);
446         tcmu_cmd->dbi = kcalloc(tcmu_cmd->dbi_cnt, sizeof(uint32_t),
447                                 GFP_KERNEL);
448         if (!tcmu_cmd->dbi) {
449                 kmem_cache_free(tcmu_cmd_cache, tcmu_cmd);
450                 return NULL;
451         }
452
453         return tcmu_cmd;
454 }
455
456 static inline void tcmu_flush_dcache_range(void *vaddr, size_t size)
457 {
458         unsigned long offset = offset_in_page(vaddr);
459         void *start = vaddr - offset;
460
461         size = round_up(size+offset, PAGE_SIZE);
462
463         while (size) {
464                 flush_dcache_page(virt_to_page(start));
465                 start += PAGE_SIZE;
466                 size -= PAGE_SIZE;
467         }
468 }
469
470 /*
471  * Some ring helper functions. We don't assume size is a power of 2 so
472  * we can't use circ_buf.h.
473  */
474 static inline size_t spc_used(size_t head, size_t tail, size_t size)
475 {
476         int diff = head - tail;
477
478         if (diff >= 0)
479                 return diff;
480         else
481                 return size + diff;
482 }
483
484 static inline size_t spc_free(size_t head, size_t tail, size_t size)
485 {
486         /* Keep 1 byte unused or we can't tell full from empty */
487         return (size - spc_used(head, tail, size) - 1);
488 }
489
490 static inline size_t head_to_end(size_t head, size_t size)
491 {
492         return size - head;
493 }
494
495 static inline void new_iov(struct iovec **iov, int *iov_cnt,
496                            struct tcmu_dev *udev)
497 {
498         struct iovec *iovec;
499
500         if (*iov_cnt != 0)
501                 (*iov)++;
502         (*iov_cnt)++;
503
504         iovec = *iov;
505         memset(iovec, 0, sizeof(struct iovec));
506 }
507
508 #define UPDATE_HEAD(head, used, size) smp_store_release(&head, ((head % size) + used) % size)
509
510 /* offset is relative to mb_addr */
511 static inline size_t get_block_offset_user(struct tcmu_dev *dev,
512                 int dbi, int remaining)
513 {
514         return dev->data_off + dbi * DATA_BLOCK_SIZE +
515                 DATA_BLOCK_SIZE - remaining;
516 }
517
518 static inline size_t iov_tail(struct iovec *iov)
519 {
520         return (size_t)iov->iov_base + iov->iov_len;
521 }
522
523 static void scatter_data_area(struct tcmu_dev *udev,
524         struct tcmu_cmd *tcmu_cmd, struct scatterlist *data_sg,
525         unsigned int data_nents, struct iovec **iov,
526         int *iov_cnt, bool copy_data)
527 {
528         int i, dbi;
529         int block_remaining = 0;
530         void *from, *to = NULL;
531         size_t copy_bytes, to_offset, offset;
532         struct scatterlist *sg;
533         struct page *page;
534
535         for_each_sg(data_sg, sg, data_nents, i) {
536                 int sg_remaining = sg->length;
537                 from = kmap_atomic(sg_page(sg)) + sg->offset;
538                 while (sg_remaining > 0) {
539                         if (block_remaining == 0) {
540                                 if (to)
541                                         kunmap_atomic(to);
542
543                                 block_remaining = DATA_BLOCK_SIZE;
544                                 dbi = tcmu_cmd_get_dbi(tcmu_cmd);
545                                 page = tcmu_get_block_page(udev, dbi);
546                                 to = kmap_atomic(page);
547                         }
548
549                         copy_bytes = min_t(size_t, sg_remaining,
550                                         block_remaining);
551                         to_offset = get_block_offset_user(udev, dbi,
552                                         block_remaining);
553
554                         if (*iov_cnt != 0 &&
555                             to_offset == iov_tail(*iov)) {
556                                 (*iov)->iov_len += copy_bytes;
557                         } else {
558                                 new_iov(iov, iov_cnt, udev);
559                                 (*iov)->iov_base = (void __user *)to_offset;
560                                 (*iov)->iov_len = copy_bytes;
561                         }
562                         if (copy_data) {
563                                 offset = DATA_BLOCK_SIZE - block_remaining;
564                                 memcpy(to + offset,
565                                        from + sg->length - sg_remaining,
566                                        copy_bytes);
567                                 tcmu_flush_dcache_range(to, copy_bytes);
568                         }
569                         sg_remaining -= copy_bytes;
570                         block_remaining -= copy_bytes;
571                 }
572                 kunmap_atomic(from - sg->offset);
573         }
574         if (to)
575                 kunmap_atomic(to);
576 }
577
578 static void gather_data_area(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
579                              bool bidi)
580 {
581         struct se_cmd *se_cmd = cmd->se_cmd;
582         int i, dbi;
583         int block_remaining = 0;
584         void *from = NULL, *to;
585         size_t copy_bytes, offset;
586         struct scatterlist *sg, *data_sg;
587         struct page *page;
588         unsigned int data_nents;
589         uint32_t count = 0;
590
591         if (!bidi) {
592                 data_sg = se_cmd->t_data_sg;
593                 data_nents = se_cmd->t_data_nents;
594         } else {
595
596                 /*
597                  * For bidi case, the first count blocks are for Data-Out
598                  * buffer blocks, and before gathering the Data-In buffer
599                  * the Data-Out buffer blocks should be discarded.
600                  */
601                 count = DIV_ROUND_UP(se_cmd->data_length, DATA_BLOCK_SIZE);
602
603                 data_sg = se_cmd->t_bidi_data_sg;
604                 data_nents = se_cmd->t_bidi_data_nents;
605         }
606
607         tcmu_cmd_set_dbi_cur(cmd, count);
608
609         for_each_sg(data_sg, sg, data_nents, i) {
610                 int sg_remaining = sg->length;
611                 to = kmap_atomic(sg_page(sg)) + sg->offset;
612                 while (sg_remaining > 0) {
613                         if (block_remaining == 0) {
614                                 if (from)
615                                         kunmap_atomic(from);
616
617                                 block_remaining = DATA_BLOCK_SIZE;
618                                 dbi = tcmu_cmd_get_dbi(cmd);
619                                 page = tcmu_get_block_page(udev, dbi);
620                                 from = kmap_atomic(page);
621                         }
622                         copy_bytes = min_t(size_t, sg_remaining,
623                                         block_remaining);
624                         offset = DATA_BLOCK_SIZE - block_remaining;
625                         tcmu_flush_dcache_range(from, copy_bytes);
626                         memcpy(to + sg->length - sg_remaining, from + offset,
627                                         copy_bytes);
628
629                         sg_remaining -= copy_bytes;
630                         block_remaining -= copy_bytes;
631                 }
632                 kunmap_atomic(to - sg->offset);
633         }
634         if (from)
635                 kunmap_atomic(from);
636 }
637
638 static inline size_t spc_bitmap_free(unsigned long *bitmap, uint32_t thresh)
639 {
640         return DATA_BLOCK_SIZE * (thresh - bitmap_weight(bitmap, thresh));
641 }
642
643 /*
644  * We can't queue a command until we have space available on the cmd ring *and*
645  * space available on the data area.
646  *
647  * Called with ring lock held.
648  */
649 static bool is_ring_space_avail(struct tcmu_dev *udev, struct tcmu_cmd *cmd,
650                 size_t cmd_size, size_t data_needed)
651 {
652         struct tcmu_mailbox *mb = udev->mb_addr;
653         uint32_t blocks_needed = (data_needed + DATA_BLOCK_SIZE - 1)
654                                 / DATA_BLOCK_SIZE;
655         size_t space, cmd_needed;
656         u32 cmd_head;
657
658         tcmu_flush_dcache_range(mb, sizeof(*mb));
659
660         cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
661
662         /*
663          * If cmd end-of-ring space is too small then we need space for a NOP plus
664          * original cmd - cmds are internally contiguous.
665          */
666         if (head_to_end(cmd_head, udev->cmdr_size) >= cmd_size)
667                 cmd_needed = cmd_size;
668         else
669                 cmd_needed = cmd_size + head_to_end(cmd_head, udev->cmdr_size);
670
671         space = spc_free(cmd_head, udev->cmdr_last_cleaned, udev->cmdr_size);
672         if (space < cmd_needed) {
673                 pr_debug("no cmd space: %u %u %u\n", cmd_head,
674                        udev->cmdr_last_cleaned, udev->cmdr_size);
675                 return false;
676         }
677
678         /* try to check and get the data blocks as needed */
679         space = spc_bitmap_free(udev->data_bitmap, udev->dbi_thresh);
680         if (space < data_needed) {
681                 unsigned long blocks_left = DATA_BLOCK_BITS - udev->dbi_thresh;
682                 unsigned long grow;
683
684                 if (blocks_left < blocks_needed) {
685                         pr_debug("no data space: only %lu available, but ask for %zu\n",
686                                         blocks_left * DATA_BLOCK_SIZE,
687                                         data_needed);
688                         return false;
689                 }
690
691                 /* Try to expand the thresh */
692                 if (!udev->dbi_thresh) {
693                         /* From idle state */
694                         uint32_t init_thresh = DATA_BLOCK_INIT_BITS;
695
696                         udev->dbi_thresh = max(blocks_needed, init_thresh);
697                 } else {
698                         /*
699                          * Grow the data area by max(blocks needed,
700                          * dbi_thresh / 2), but limited to the max
701                          * DATA_BLOCK_BITS size.
702                          */
703                         grow = max(blocks_needed, udev->dbi_thresh / 2);
704                         udev->dbi_thresh += grow;
705                         if (udev->dbi_thresh > DATA_BLOCK_BITS)
706                                 udev->dbi_thresh = DATA_BLOCK_BITS;
707                 }
708         }
709
710         return tcmu_get_empty_blocks(udev, cmd);
711 }
712
713 static inline size_t tcmu_cmd_get_base_cmd_size(size_t iov_cnt)
714 {
715         return max(offsetof(struct tcmu_cmd_entry, req.iov[iov_cnt]),
716                         sizeof(struct tcmu_cmd_entry));
717 }
718
719 static inline size_t tcmu_cmd_get_cmd_size(struct tcmu_cmd *tcmu_cmd,
720                                            size_t base_command_size)
721 {
722         struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
723         size_t command_size;
724
725         command_size = base_command_size +
726                 round_up(scsi_command_size(se_cmd->t_task_cdb),
727                                 TCMU_OP_ALIGN_SIZE);
728
729         WARN_ON(command_size & (TCMU_OP_ALIGN_SIZE-1));
730
731         return command_size;
732 }
733
734 static int tcmu_setup_cmd_timer(struct tcmu_cmd *tcmu_cmd)
735 {
736         struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
737         unsigned long tmo = udev->cmd_time_out;
738         int cmd_id;
739
740         if (tcmu_cmd->cmd_id)
741                 return 0;
742
743         cmd_id = idr_alloc(&udev->commands, tcmu_cmd, 1, USHRT_MAX, GFP_NOWAIT);
744         if (cmd_id < 0) {
745                 pr_err("tcmu: Could not allocate cmd id.\n");
746                 return cmd_id;
747         }
748         tcmu_cmd->cmd_id = cmd_id;
749
750         if (!tmo)
751                 return 0;
752
753         tcmu_cmd->deadline = round_jiffies_up(jiffies + msecs_to_jiffies(tmo));
754         mod_timer(&udev->timeout, tcmu_cmd->deadline);
755         return 0;
756 }
757
758 static sense_reason_t
759 tcmu_queue_cmd_ring(struct tcmu_cmd *tcmu_cmd)
760 {
761         struct tcmu_dev *udev = tcmu_cmd->tcmu_dev;
762         struct se_cmd *se_cmd = tcmu_cmd->se_cmd;
763         size_t base_command_size, command_size;
764         struct tcmu_mailbox *mb;
765         struct tcmu_cmd_entry *entry;
766         struct iovec *iov;
767         int iov_cnt, ret;
768         uint32_t cmd_head;
769         uint64_t cdb_off;
770         bool copy_to_data_area;
771         size_t data_length = tcmu_cmd_get_data_length(tcmu_cmd);
772
773         if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags))
774                 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
775
776         /*
777          * Must be a certain minimum size for response sense info, but
778          * also may be larger if the iov array is large.
779          *
780          * We prepare as many iovs as possbile for potential uses here,
781          * because it's expensive to tell how many regions are freed in
782          * the bitmap & global data pool, as the size calculated here
783          * will only be used to do the checks.
784          *
785          * The size will be recalculated later as actually needed to save
786          * cmd area memories.
787          */
788         base_command_size = tcmu_cmd_get_base_cmd_size(tcmu_cmd->dbi_cnt);
789         command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
790
791         mutex_lock(&udev->cmdr_lock);
792
793         mb = udev->mb_addr;
794         cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
795         if ((command_size > (udev->cmdr_size / 2)) ||
796             data_length > udev->data_size) {
797                 pr_warn("TCMU: Request of size %zu/%zu is too big for %u/%zu "
798                         "cmd ring/data area\n", command_size, data_length,
799                         udev->cmdr_size, udev->data_size);
800                 mutex_unlock(&udev->cmdr_lock);
801                 return TCM_INVALID_CDB_FIELD;
802         }
803
804         while (!is_ring_space_avail(udev, tcmu_cmd, command_size, data_length)) {
805                 int ret;
806                 DEFINE_WAIT(__wait);
807
808                 /*
809                  * Don't leave commands partially setup because the unmap
810                  * thread might need the blocks to make forward progress.
811                  */
812                 tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cur);
813                 tcmu_cmd_reset_dbi_cur(tcmu_cmd);
814
815                 prepare_to_wait(&udev->wait_cmdr, &__wait, TASK_INTERRUPTIBLE);
816
817                 pr_debug("sleeping for ring space\n");
818                 mutex_unlock(&udev->cmdr_lock);
819                 if (udev->cmd_time_out)
820                         ret = schedule_timeout(
821                                         msecs_to_jiffies(udev->cmd_time_out));
822                 else
823                         ret = schedule_timeout(msecs_to_jiffies(TCMU_TIME_OUT));
824                 finish_wait(&udev->wait_cmdr, &__wait);
825                 if (!ret) {
826                         pr_warn("tcmu: command timed out\n");
827                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
828                 }
829
830                 mutex_lock(&udev->cmdr_lock);
831
832                 /* We dropped cmdr_lock, cmd_head is stale */
833                 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
834         }
835
836         /* Insert a PAD if end-of-ring space is too small */
837         if (head_to_end(cmd_head, udev->cmdr_size) < command_size) {
838                 size_t pad_size = head_to_end(cmd_head, udev->cmdr_size);
839
840                 entry = (void *) mb + CMDR_OFF + cmd_head;
841                 tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_PAD);
842                 tcmu_hdr_set_len(&entry->hdr.len_op, pad_size);
843                 entry->hdr.cmd_id = 0; /* not used for PAD */
844                 entry->hdr.kflags = 0;
845                 entry->hdr.uflags = 0;
846                 tcmu_flush_dcache_range(entry, sizeof(*entry));
847
848                 UPDATE_HEAD(mb->cmd_head, pad_size, udev->cmdr_size);
849                 tcmu_flush_dcache_range(mb, sizeof(*mb));
850
851                 cmd_head = mb->cmd_head % udev->cmdr_size; /* UAM */
852                 WARN_ON(cmd_head != 0);
853         }
854
855         entry = (void *) mb + CMDR_OFF + cmd_head;
856         memset(entry, 0, command_size);
857         tcmu_hdr_set_op(&entry->hdr.len_op, TCMU_OP_CMD);
858
859         /* Handle allocating space from the data area */
860         tcmu_cmd_reset_dbi_cur(tcmu_cmd);
861         iov = &entry->req.iov[0];
862         iov_cnt = 0;
863         copy_to_data_area = (se_cmd->data_direction == DMA_TO_DEVICE
864                 || se_cmd->se_cmd_flags & SCF_BIDI);
865         scatter_data_area(udev, tcmu_cmd, se_cmd->t_data_sg,
866                           se_cmd->t_data_nents, &iov, &iov_cnt,
867                           copy_to_data_area);
868         entry->req.iov_cnt = iov_cnt;
869
870         /* Handle BIDI commands */
871         iov_cnt = 0;
872         if (se_cmd->se_cmd_flags & SCF_BIDI) {
873                 iov++;
874                 scatter_data_area(udev, tcmu_cmd, se_cmd->t_bidi_data_sg,
875                                   se_cmd->t_bidi_data_nents, &iov, &iov_cnt,
876                                   false);
877         }
878         entry->req.iov_bidi_cnt = iov_cnt;
879
880         ret = tcmu_setup_cmd_timer(tcmu_cmd);
881         if (ret) {
882                 tcmu_cmd_free_data(tcmu_cmd, tcmu_cmd->dbi_cnt);
883                 mutex_unlock(&udev->cmdr_lock);
884                 return TCM_OUT_OF_RESOURCES;
885         }
886         entry->hdr.cmd_id = tcmu_cmd->cmd_id;
887
888         /*
889          * Recalaulate the command's base size and size according
890          * to the actual needs
891          */
892         base_command_size = tcmu_cmd_get_base_cmd_size(entry->req.iov_cnt +
893                                                        entry->req.iov_bidi_cnt);
894         command_size = tcmu_cmd_get_cmd_size(tcmu_cmd, base_command_size);
895
896         tcmu_hdr_set_len(&entry->hdr.len_op, command_size);
897
898         /* All offsets relative to mb_addr, not start of entry! */
899         cdb_off = CMDR_OFF + cmd_head + base_command_size;
900         memcpy((void *) mb + cdb_off, se_cmd->t_task_cdb, scsi_command_size(se_cmd->t_task_cdb));
901         entry->req.cdb_off = cdb_off;
902         tcmu_flush_dcache_range(entry, sizeof(*entry));
903
904         UPDATE_HEAD(mb->cmd_head, command_size, udev->cmdr_size);
905         tcmu_flush_dcache_range(mb, sizeof(*mb));
906         mutex_unlock(&udev->cmdr_lock);
907
908         /* TODO: only if FLUSH and FUA? */
909         uio_event_notify(&udev->uio_info);
910
911         if (udev->cmd_time_out)
912                 mod_timer(&udev->timeout, round_jiffies_up(jiffies +
913                           msecs_to_jiffies(udev->cmd_time_out)));
914
915         return TCM_NO_SENSE;
916 }
917
918 static sense_reason_t
919 tcmu_queue_cmd(struct se_cmd *se_cmd)
920 {
921         struct tcmu_cmd *tcmu_cmd;
922         sense_reason_t ret;
923
924         tcmu_cmd = tcmu_alloc_cmd(se_cmd);
925         if (!tcmu_cmd)
926                 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
927
928         ret = tcmu_queue_cmd_ring(tcmu_cmd);
929         if (ret != TCM_NO_SENSE) {
930                 pr_err("TCMU: Could not queue command\n");
931
932                 tcmu_free_cmd(tcmu_cmd);
933         }
934
935         return ret;
936 }
937
938 static void tcmu_handle_completion(struct tcmu_cmd *cmd, struct tcmu_cmd_entry *entry)
939 {
940         struct se_cmd *se_cmd = cmd->se_cmd;
941         struct tcmu_dev *udev = cmd->tcmu_dev;
942
943         /*
944          * cmd has been completed already from timeout, just reclaim
945          * data area space and free cmd
946          */
947         if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
948                 goto out;
949
950         tcmu_cmd_reset_dbi_cur(cmd);
951
952         if (entry->hdr.uflags & TCMU_UFLAG_UNKNOWN_OP) {
953                 pr_warn("TCMU: Userspace set UNKNOWN_OP flag on se_cmd %p\n",
954                         cmd->se_cmd);
955                 entry->rsp.scsi_status = SAM_STAT_CHECK_CONDITION;
956         } else if (entry->rsp.scsi_status == SAM_STAT_CHECK_CONDITION) {
957                 transport_copy_sense_to_cmd(se_cmd, entry->rsp.sense_buffer);
958         } else if (se_cmd->se_cmd_flags & SCF_BIDI) {
959                 /* Get Data-In buffer before clean up */
960                 gather_data_area(udev, cmd, true);
961         } else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
962                 gather_data_area(udev, cmd, false);
963         } else if (se_cmd->data_direction == DMA_TO_DEVICE) {
964                 /* TODO: */
965         } else if (se_cmd->data_direction != DMA_NONE) {
966                 pr_warn("TCMU: data direction was %d!\n",
967                         se_cmd->data_direction);
968         }
969
970         target_complete_cmd(cmd->se_cmd, entry->rsp.scsi_status);
971
972 out:
973         cmd->se_cmd = NULL;
974         tcmu_cmd_free_data(cmd, cmd->dbi_cnt);
975         tcmu_free_cmd(cmd);
976 }
977
978 static unsigned int tcmu_handle_completions(struct tcmu_dev *udev)
979 {
980         struct tcmu_mailbox *mb;
981         int handled = 0;
982
983         if (test_bit(TCMU_DEV_BIT_BROKEN, &udev->flags)) {
984                 pr_err("ring broken, not handling completions\n");
985                 return 0;
986         }
987
988         mb = udev->mb_addr;
989         tcmu_flush_dcache_range(mb, sizeof(*mb));
990
991         while (udev->cmdr_last_cleaned != READ_ONCE(mb->cmd_tail)) {
992
993                 struct tcmu_cmd_entry *entry = (void *) mb + CMDR_OFF + udev->cmdr_last_cleaned;
994                 struct tcmu_cmd *cmd;
995
996                 tcmu_flush_dcache_range(entry, sizeof(*entry));
997
998                 if (tcmu_hdr_get_op(entry->hdr.len_op) == TCMU_OP_PAD) {
999                         UPDATE_HEAD(udev->cmdr_last_cleaned,
1000                                     tcmu_hdr_get_len(entry->hdr.len_op),
1001                                     udev->cmdr_size);
1002                         continue;
1003                 }
1004                 WARN_ON(tcmu_hdr_get_op(entry->hdr.len_op) != TCMU_OP_CMD);
1005
1006                 cmd = idr_remove(&udev->commands, entry->hdr.cmd_id);
1007                 if (!cmd) {
1008                         pr_err("cmd_id not found, ring is broken\n");
1009                         set_bit(TCMU_DEV_BIT_BROKEN, &udev->flags);
1010                         break;
1011                 }
1012
1013                 tcmu_handle_completion(cmd, entry);
1014
1015                 UPDATE_HEAD(udev->cmdr_last_cleaned,
1016                             tcmu_hdr_get_len(entry->hdr.len_op),
1017                             udev->cmdr_size);
1018
1019                 handled++;
1020         }
1021
1022         if (mb->cmd_tail == mb->cmd_head)
1023                 del_timer(&udev->timeout); /* no more pending cmds */
1024
1025         wake_up(&udev->wait_cmdr);
1026
1027         return handled;
1028 }
1029
1030 static int tcmu_check_expired_cmd(int id, void *p, void *data)
1031 {
1032         struct tcmu_cmd *cmd = p;
1033
1034         if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags))
1035                 return 0;
1036
1037         if (!time_after(jiffies, cmd->deadline))
1038                 return 0;
1039
1040         set_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags);
1041         target_complete_cmd(cmd->se_cmd, SAM_STAT_CHECK_CONDITION);
1042         cmd->se_cmd = NULL;
1043
1044         return 0;
1045 }
1046
1047 static void tcmu_device_timedout(struct timer_list *t)
1048 {
1049         struct tcmu_dev *udev = from_timer(udev, t, timeout);
1050
1051         pr_debug("%s cmd timeout has expired\n", udev->name);
1052
1053         spin_lock(&timed_out_udevs_lock);
1054         if (list_empty(&udev->timedout_entry))
1055                 list_add_tail(&udev->timedout_entry, &timed_out_udevs);
1056         spin_unlock(&timed_out_udevs_lock);
1057
1058         schedule_work(&tcmu_unmap_work);
1059 }
1060
1061 static int tcmu_attach_hba(struct se_hba *hba, u32 host_id)
1062 {
1063         struct tcmu_hba *tcmu_hba;
1064
1065         tcmu_hba = kzalloc(sizeof(struct tcmu_hba), GFP_KERNEL);
1066         if (!tcmu_hba)
1067                 return -ENOMEM;
1068
1069         tcmu_hba->host_id = host_id;
1070         hba->hba_ptr = tcmu_hba;
1071
1072         return 0;
1073 }
1074
1075 static void tcmu_detach_hba(struct se_hba *hba)
1076 {
1077         kfree(hba->hba_ptr);
1078         hba->hba_ptr = NULL;
1079 }
1080
1081 static struct se_device *tcmu_alloc_device(struct se_hba *hba, const char *name)
1082 {
1083         struct tcmu_dev *udev;
1084
1085         udev = kzalloc(sizeof(struct tcmu_dev), GFP_KERNEL);
1086         if (!udev)
1087                 return NULL;
1088         kref_init(&udev->kref);
1089
1090         udev->name = kstrdup(name, GFP_KERNEL);
1091         if (!udev->name) {
1092                 kfree(udev);
1093                 return NULL;
1094         }
1095
1096         udev->hba = hba;
1097         udev->cmd_time_out = TCMU_TIME_OUT;
1098
1099         init_waitqueue_head(&udev->wait_cmdr);
1100         mutex_init(&udev->cmdr_lock);
1101
1102         INIT_LIST_HEAD(&udev->timedout_entry);
1103         idr_init(&udev->commands);
1104
1105         timer_setup(&udev->timeout, tcmu_device_timedout, 0);
1106
1107         init_waitqueue_head(&udev->nl_cmd_wq);
1108         spin_lock_init(&udev->nl_cmd_lock);
1109
1110         INIT_RADIX_TREE(&udev->data_blocks, GFP_KERNEL);
1111
1112         return &udev->se_dev;
1113 }
1114
1115 static int tcmu_irqcontrol(struct uio_info *info, s32 irq_on)
1116 {
1117         struct tcmu_dev *tcmu_dev = container_of(info, struct tcmu_dev, uio_info);
1118
1119         mutex_lock(&tcmu_dev->cmdr_lock);
1120         tcmu_handle_completions(tcmu_dev);
1121         mutex_unlock(&tcmu_dev->cmdr_lock);
1122
1123         return 0;
1124 }
1125
1126 /*
1127  * mmap code from uio.c. Copied here because we want to hook mmap()
1128  * and this stuff must come along.
1129  */
1130 static int tcmu_find_mem_index(struct vm_area_struct *vma)
1131 {
1132         struct tcmu_dev *udev = vma->vm_private_data;
1133         struct uio_info *info = &udev->uio_info;
1134
1135         if (vma->vm_pgoff < MAX_UIO_MAPS) {
1136                 if (info->mem[vma->vm_pgoff].size == 0)
1137                         return -1;
1138                 return (int)vma->vm_pgoff;
1139         }
1140         return -1;
1141 }
1142
1143 static struct page *tcmu_try_get_block_page(struct tcmu_dev *udev, uint32_t dbi)
1144 {
1145         struct page *page;
1146         int ret;
1147
1148         mutex_lock(&udev->cmdr_lock);
1149         page = tcmu_get_block_page(udev, dbi);
1150         if (likely(page)) {
1151                 mutex_unlock(&udev->cmdr_lock);
1152                 return page;
1153         }
1154
1155         /*
1156          * Normally it shouldn't be here:
1157          * Only when the userspace has touched the blocks which
1158          * are out of the tcmu_cmd's data iov[], and will return
1159          * one zeroed page.
1160          */
1161         pr_warn("Block(%u) out of cmd's iov[] has been touched!\n", dbi);
1162         pr_warn("Mostly it will be a bug of userspace, please have a check!\n");
1163
1164         if (dbi >= udev->dbi_thresh) {
1165                 /* Extern the udev->dbi_thresh to dbi + 1 */
1166                 udev->dbi_thresh = dbi + 1;
1167                 udev->dbi_max = dbi;
1168         }
1169
1170         page = radix_tree_lookup(&udev->data_blocks, dbi);
1171         if (!page) {
1172                 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1173                 if (!page) {
1174                         mutex_unlock(&udev->cmdr_lock);
1175                         return NULL;
1176                 }
1177
1178                 ret = radix_tree_insert(&udev->data_blocks, dbi, page);
1179                 if (ret) {
1180                         mutex_unlock(&udev->cmdr_lock);
1181                         __free_page(page);
1182                         return NULL;
1183                 }
1184
1185                 /*
1186                  * Since this case is rare in page fault routine, here we
1187                  * will allow the global_db_count >= TCMU_GLOBAL_MAX_BLOCKS
1188                  * to reduce possible page fault call trace.
1189                  */
1190                 atomic_inc(&global_db_count);
1191         }
1192         mutex_unlock(&udev->cmdr_lock);
1193
1194         return page;
1195 }
1196
1197 static int tcmu_vma_fault(struct vm_fault *vmf)
1198 {
1199         struct tcmu_dev *udev = vmf->vma->vm_private_data;
1200         struct uio_info *info = &udev->uio_info;
1201         struct page *page;
1202         unsigned long offset;
1203         void *addr;
1204
1205         int mi = tcmu_find_mem_index(vmf->vma);
1206         if (mi < 0)
1207                 return VM_FAULT_SIGBUS;
1208
1209         /*
1210          * We need to subtract mi because userspace uses offset = N*PAGE_SIZE
1211          * to use mem[N].
1212          */
1213         offset = (vmf->pgoff - mi) << PAGE_SHIFT;
1214
1215         if (offset < udev->data_off) {
1216                 /* For the vmalloc()ed cmd area pages */
1217                 addr = (void *)(unsigned long)info->mem[mi].addr + offset;
1218                 page = vmalloc_to_page(addr);
1219         } else {
1220                 uint32_t dbi;
1221
1222                 /* For the dynamically growing data area pages */
1223                 dbi = (offset - udev->data_off) / DATA_BLOCK_SIZE;
1224                 page = tcmu_try_get_block_page(udev, dbi);
1225                 if (!page)
1226                         return VM_FAULT_NOPAGE;
1227         }
1228
1229         get_page(page);
1230         vmf->page = page;
1231         return 0;
1232 }
1233
1234 static const struct vm_operations_struct tcmu_vm_ops = {
1235         .fault = tcmu_vma_fault,
1236 };
1237
1238 static int tcmu_mmap(struct uio_info *info, struct vm_area_struct *vma)
1239 {
1240         struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1241
1242         vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1243         vma->vm_ops = &tcmu_vm_ops;
1244
1245         vma->vm_private_data = udev;
1246
1247         /* Ensure the mmap is exactly the right size */
1248         if (vma_pages(vma) != (TCMU_RING_SIZE >> PAGE_SHIFT))
1249                 return -EINVAL;
1250
1251         return 0;
1252 }
1253
1254 static int tcmu_open(struct uio_info *info, struct inode *inode)
1255 {
1256         struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1257
1258         /* O_EXCL not supported for char devs, so fake it? */
1259         if (test_and_set_bit(TCMU_DEV_BIT_OPEN, &udev->flags))
1260                 return -EBUSY;
1261
1262         udev->inode = inode;
1263         kref_get(&udev->kref);
1264
1265         pr_debug("open\n");
1266
1267         return 0;
1268 }
1269
1270 static void tcmu_dev_call_rcu(struct rcu_head *p)
1271 {
1272         struct se_device *dev = container_of(p, struct se_device, rcu_head);
1273         struct tcmu_dev *udev = TCMU_DEV(dev);
1274
1275         kfree(udev->uio_info.name);
1276         kfree(udev->name);
1277         kfree(udev);
1278 }
1279
1280 static int tcmu_check_and_free_pending_cmd(struct tcmu_cmd *cmd)
1281 {
1282         if (test_bit(TCMU_CMD_BIT_EXPIRED, &cmd->flags)) {
1283                 kmem_cache_free(tcmu_cmd_cache, cmd);
1284                 return 0;
1285         }
1286         return -EINVAL;
1287 }
1288
1289 static void tcmu_blocks_release(struct radix_tree_root *blocks,
1290                                 int start, int end)
1291 {
1292         int i;
1293         struct page *page;
1294
1295         for (i = start; i < end; i++) {
1296                 page = radix_tree_delete(blocks, i);
1297                 if (page) {
1298                         __free_page(page);
1299                         atomic_dec(&global_db_count);
1300                 }
1301         }
1302 }
1303
1304 static void tcmu_dev_kref_release(struct kref *kref)
1305 {
1306         struct tcmu_dev *udev = container_of(kref, struct tcmu_dev, kref);
1307         struct se_device *dev = &udev->se_dev;
1308         struct tcmu_cmd *cmd;
1309         bool all_expired = true;
1310         int i;
1311
1312         vfree(udev->mb_addr);
1313         udev->mb_addr = NULL;
1314
1315         spin_lock_bh(&timed_out_udevs_lock);
1316         if (!list_empty(&udev->timedout_entry))
1317                 list_del(&udev->timedout_entry);
1318         spin_unlock_bh(&timed_out_udevs_lock);
1319
1320         /* Upper layer should drain all requests before calling this */
1321         mutex_lock(&udev->cmdr_lock);
1322         idr_for_each_entry(&udev->commands, cmd, i) {
1323                 if (tcmu_check_and_free_pending_cmd(cmd) != 0)
1324                         all_expired = false;
1325         }
1326         idr_destroy(&udev->commands);
1327         WARN_ON(!all_expired);
1328
1329         tcmu_blocks_release(&udev->data_blocks, 0, udev->dbi_max + 1);
1330         mutex_unlock(&udev->cmdr_lock);
1331
1332         call_rcu(&dev->rcu_head, tcmu_dev_call_rcu);
1333 }
1334
1335 static int tcmu_release(struct uio_info *info, struct inode *inode)
1336 {
1337         struct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);
1338
1339         clear_bit(TCMU_DEV_BIT_OPEN, &udev->flags);
1340
1341         pr_debug("close\n");
1342         /* release ref from open */
1343         kref_put(&udev->kref, tcmu_dev_kref_release);
1344         return 0;
1345 }
1346
1347 static void tcmu_init_genl_cmd_reply(struct tcmu_dev *udev, int cmd)
1348 {
1349         struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1350
1351         if (!tcmu_kern_cmd_reply_supported)
1352                 return;
1353
1354         if (udev->nl_reply_supported <= 0)
1355                 return;
1356
1357 relock:
1358         spin_lock(&udev->nl_cmd_lock);
1359
1360         if (nl_cmd->cmd != TCMU_CMD_UNSPEC) {
1361                 spin_unlock(&udev->nl_cmd_lock);
1362                 pr_debug("sleeping for open nl cmd\n");
1363                 wait_event(udev->nl_cmd_wq, (nl_cmd->cmd == TCMU_CMD_UNSPEC));
1364                 goto relock;
1365         }
1366
1367         memset(nl_cmd, 0, sizeof(*nl_cmd));
1368         nl_cmd->cmd = cmd;
1369         init_completion(&nl_cmd->complete);
1370
1371         spin_unlock(&udev->nl_cmd_lock);
1372 }
1373
1374 static int tcmu_wait_genl_cmd_reply(struct tcmu_dev *udev)
1375 {
1376         struct tcmu_nl_cmd *nl_cmd = &udev->curr_nl_cmd;
1377         int ret;
1378         DEFINE_WAIT(__wait);
1379
1380         if (!tcmu_kern_cmd_reply_supported)
1381                 return 0;
1382
1383         if (udev->nl_reply_supported <= 0)
1384                 return 0;
1385
1386         pr_debug("sleeping for nl reply\n");
1387         wait_for_completion(&nl_cmd->complete);
1388
1389         spin_lock(&udev->nl_cmd_lock);
1390         nl_cmd->cmd = TCMU_CMD_UNSPEC;
1391         ret = nl_cmd->status;
1392         nl_cmd->status = 0;
1393         spin_unlock(&udev->nl_cmd_lock);
1394
1395         wake_up_all(&udev->nl_cmd_wq);
1396
1397         return ret;;
1398 }
1399
1400 static int tcmu_netlink_event(struct tcmu_dev *udev, enum tcmu_genl_cmd cmd,
1401                               int reconfig_attr, const void *reconfig_data)
1402 {
1403         struct sk_buff *skb;
1404         void *msg_header;
1405         int ret = -ENOMEM;
1406
1407         skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1408         if (!skb)
1409                 return ret;
1410
1411         msg_header = genlmsg_put(skb, 0, 0, &tcmu_genl_family, 0, cmd);
1412         if (!msg_header)
1413                 goto free_skb;
1414
1415         ret = nla_put_string(skb, TCMU_ATTR_DEVICE, udev->uio_info.name);
1416         if (ret < 0)
1417                 goto free_skb;
1418
1419         ret = nla_put_u32(skb, TCMU_ATTR_MINOR, udev->uio_info.uio_dev->minor);
1420         if (ret < 0)
1421                 goto free_skb;
1422
1423         ret = nla_put_u32(skb, TCMU_ATTR_DEVICE_ID, udev->se_dev.dev_index);
1424         if (ret < 0)
1425                 goto free_skb;
1426
1427         if (cmd == TCMU_CMD_RECONFIG_DEVICE) {
1428                 switch (reconfig_attr) {
1429                 case TCMU_ATTR_DEV_CFG:
1430                         ret = nla_put_string(skb, reconfig_attr, reconfig_data);
1431                         break;
1432                 case TCMU_ATTR_DEV_SIZE:
1433                         ret = nla_put_u64_64bit(skb, reconfig_attr,
1434                                                 *((u64 *)reconfig_data),
1435                                                 TCMU_ATTR_PAD);
1436                         break;
1437                 case TCMU_ATTR_WRITECACHE:
1438                         ret = nla_put_u8(skb, reconfig_attr,
1439                                           *((u8 *)reconfig_data));
1440                         break;
1441                 default:
1442                         BUG();
1443                 }
1444
1445                 if (ret < 0)
1446                         goto free_skb;
1447         }
1448
1449         genlmsg_end(skb, msg_header);
1450
1451         tcmu_init_genl_cmd_reply(udev, cmd);
1452
1453         ret = genlmsg_multicast_allns(&tcmu_genl_family, skb, 0,
1454                                 TCMU_MCGRP_CONFIG, GFP_KERNEL);
1455         /* We don't care if no one is listening */
1456         if (ret == -ESRCH)
1457                 ret = 0;
1458         if (!ret)
1459                 ret = tcmu_wait_genl_cmd_reply(udev);
1460
1461         return ret;
1462 free_skb:
1463         nlmsg_free(skb);
1464         return ret;
1465 }
1466
1467 static int tcmu_update_uio_info(struct tcmu_dev *udev)
1468 {
1469         struct tcmu_hba *hba = udev->hba->hba_ptr;
1470         struct uio_info *info;
1471         size_t size, used;
1472         char *str;
1473
1474         info = &udev->uio_info;
1475         size = snprintf(NULL, 0, "tcm-user/%u/%s/%s", hba->host_id, udev->name,
1476                         udev->dev_config);
1477         size += 1; /* for \0 */
1478         str = kmalloc(size, GFP_KERNEL);
1479         if (!str)
1480                 return -ENOMEM;
1481
1482         used = snprintf(str, size, "tcm-user/%u/%s", hba->host_id, udev->name);
1483         if (udev->dev_config[0])
1484                 snprintf(str + used, size - used, "/%s", udev->dev_config);
1485
1486         /* If the old string exists, free it */
1487         kfree(info->name);
1488         info->name = str;
1489
1490         return 0;
1491 }
1492
1493 static int tcmu_configure_device(struct se_device *dev)
1494 {
1495         struct tcmu_dev *udev = TCMU_DEV(dev);
1496         struct uio_info *info;
1497         struct tcmu_mailbox *mb;
1498         int ret = 0;
1499
1500         ret = tcmu_update_uio_info(udev);
1501         if (ret)
1502                 return ret;
1503
1504         info = &udev->uio_info;
1505
1506         udev->mb_addr = vzalloc(CMDR_SIZE);
1507         if (!udev->mb_addr) {
1508                 ret = -ENOMEM;
1509                 goto err_vzalloc;
1510         }
1511
1512         /* mailbox fits in first part of CMDR space */
1513         udev->cmdr_size = CMDR_SIZE - CMDR_OFF;
1514         udev->data_off = CMDR_SIZE;
1515         udev->data_size = DATA_SIZE;
1516         udev->dbi_thresh = 0; /* Default in Idle state */
1517         udev->waiting_global = false;
1518
1519         /* Initialise the mailbox of the ring buffer */
1520         mb = udev->mb_addr;
1521         mb->version = TCMU_MAILBOX_VERSION;
1522         mb->flags = TCMU_MAILBOX_FLAG_CAP_OOOC;
1523         mb->cmdr_off = CMDR_OFF;
1524         mb->cmdr_size = udev->cmdr_size;
1525
1526         WARN_ON(!PAGE_ALIGNED(udev->data_off));
1527         WARN_ON(udev->data_size % PAGE_SIZE);
1528         WARN_ON(udev->data_size % DATA_BLOCK_SIZE);
1529
1530         info->version = __stringify(TCMU_MAILBOX_VERSION);
1531
1532         info->mem[0].name = "tcm-user command & data buffer";
1533         info->mem[0].addr = (phys_addr_t)(uintptr_t)udev->mb_addr;
1534         info->mem[0].size = TCMU_RING_SIZE;
1535         info->mem[0].memtype = UIO_MEM_NONE;
1536
1537         info->irqcontrol = tcmu_irqcontrol;
1538         info->irq = UIO_IRQ_CUSTOM;
1539
1540         info->mmap = tcmu_mmap;
1541         info->open = tcmu_open;
1542         info->release = tcmu_release;
1543
1544         ret = uio_register_device(tcmu_root_device, info);
1545         if (ret)
1546                 goto err_register;
1547
1548         /* User can set hw_block_size before enable the device */
1549         if (dev->dev_attrib.hw_block_size == 0)
1550                 dev->dev_attrib.hw_block_size = 512;
1551         /* Other attributes can be configured in userspace */
1552         if (!dev->dev_attrib.hw_max_sectors)
1553                 dev->dev_attrib.hw_max_sectors = 128;
1554         if (!dev->dev_attrib.emulate_write_cache)
1555                 dev->dev_attrib.emulate_write_cache = 0;
1556         dev->dev_attrib.hw_queue_depth = 128;
1557
1558         /* If user didn't explicitly disable netlink reply support, use
1559          * module scope setting.
1560          */
1561         if (udev->nl_reply_supported >= 0)
1562                 udev->nl_reply_supported = tcmu_kern_cmd_reply_supported;
1563
1564         /*
1565          * Get a ref incase userspace does a close on the uio device before
1566          * LIO has initiated tcmu_free_device.
1567          */
1568         kref_get(&udev->kref);
1569
1570         ret = tcmu_netlink_event(udev, TCMU_CMD_ADDED_DEVICE, 0, NULL);
1571         if (ret)
1572                 goto err_netlink;
1573
1574         mutex_lock(&root_udev_mutex);
1575         list_add(&udev->node, &root_udev);
1576         mutex_unlock(&root_udev_mutex);
1577
1578         return 0;
1579
1580 err_netlink:
1581         kref_put(&udev->kref, tcmu_dev_kref_release);
1582         uio_unregister_device(&udev->uio_info);
1583 err_register:
1584         vfree(udev->mb_addr);
1585         udev->mb_addr = NULL;
1586 err_vzalloc:
1587         kfree(info->name);
1588         info->name = NULL;
1589
1590         return ret;
1591 }
1592
1593 static bool tcmu_dev_configured(struct tcmu_dev *udev)
1594 {
1595         return udev->uio_info.uio_dev ? true : false;
1596 }
1597
1598 static void tcmu_free_device(struct se_device *dev)
1599 {
1600         struct tcmu_dev *udev = TCMU_DEV(dev);
1601
1602         /* release ref from init */
1603         kref_put(&udev->kref, tcmu_dev_kref_release);
1604 }
1605
1606 static void tcmu_destroy_device(struct se_device *dev)
1607 {
1608         struct tcmu_dev *udev = TCMU_DEV(dev);
1609
1610         del_timer_sync(&udev->timeout);
1611
1612         mutex_lock(&root_udev_mutex);
1613         list_del(&udev->node);
1614         mutex_unlock(&root_udev_mutex);
1615
1616         tcmu_netlink_event(udev, TCMU_CMD_REMOVED_DEVICE, 0, NULL);
1617
1618         uio_unregister_device(&udev->uio_info);
1619
1620         /* release ref from configure */
1621         kref_put(&udev->kref, tcmu_dev_kref_release);
1622 }
1623
1624 enum {
1625         Opt_dev_config, Opt_dev_size, Opt_hw_block_size, Opt_hw_max_sectors,
1626         Opt_nl_reply_supported, Opt_err,
1627 };
1628
1629 static match_table_t tokens = {
1630         {Opt_dev_config, "dev_config=%s"},
1631         {Opt_dev_size, "dev_size=%u"},
1632         {Opt_hw_block_size, "hw_block_size=%u"},
1633         {Opt_hw_max_sectors, "hw_max_sectors=%u"},
1634         {Opt_nl_reply_supported, "nl_reply_supported=%d"},
1635         {Opt_err, NULL}
1636 };
1637
1638 static int tcmu_set_dev_attrib(substring_t *arg, u32 *dev_attrib)
1639 {
1640         unsigned long tmp_ul;
1641         char *arg_p;
1642         int ret;
1643
1644         arg_p = match_strdup(arg);
1645         if (!arg_p)
1646                 return -ENOMEM;
1647
1648         ret = kstrtoul(arg_p, 0, &tmp_ul);
1649         kfree(arg_p);
1650         if (ret < 0) {
1651                 pr_err("kstrtoul() failed for dev attrib\n");
1652                 return ret;
1653         }
1654         if (!tmp_ul) {
1655                 pr_err("dev attrib must be nonzero\n");
1656                 return -EINVAL;
1657         }
1658         *dev_attrib = tmp_ul;
1659         return 0;
1660 }
1661
1662 static ssize_t tcmu_set_configfs_dev_params(struct se_device *dev,
1663                 const char *page, ssize_t count)
1664 {
1665         struct tcmu_dev *udev = TCMU_DEV(dev);
1666         char *orig, *ptr, *opts, *arg_p;
1667         substring_t args[MAX_OPT_ARGS];
1668         int ret = 0, token;
1669
1670         opts = kstrdup(page, GFP_KERNEL);
1671         if (!opts)
1672                 return -ENOMEM;
1673
1674         orig = opts;
1675
1676         while ((ptr = strsep(&opts, ",\n")) != NULL) {
1677                 if (!*ptr)
1678                         continue;
1679
1680                 token = match_token(ptr, tokens, args);
1681                 switch (token) {
1682                 case Opt_dev_config:
1683                         if (match_strlcpy(udev->dev_config, &args[0],
1684                                           TCMU_CONFIG_LEN) == 0) {
1685                                 ret = -EINVAL;
1686                                 break;
1687                         }
1688                         pr_debug("TCMU: Referencing Path: %s\n", udev->dev_config);
1689                         break;
1690                 case Opt_dev_size:
1691                         arg_p = match_strdup(&args[0]);
1692                         if (!arg_p) {
1693                                 ret = -ENOMEM;
1694                                 break;
1695                         }
1696                         ret = kstrtoul(arg_p, 0, (unsigned long *) &udev->dev_size);
1697                         kfree(arg_p);
1698                         if (ret < 0)
1699                                 pr_err("kstrtoul() failed for dev_size=\n");
1700                         break;
1701                 case Opt_hw_block_size:
1702                         ret = tcmu_set_dev_attrib(&args[0],
1703                                         &(dev->dev_attrib.hw_block_size));
1704                         break;
1705                 case Opt_hw_max_sectors:
1706                         ret = tcmu_set_dev_attrib(&args[0],
1707                                         &(dev->dev_attrib.hw_max_sectors));
1708                         break;
1709                 case Opt_nl_reply_supported:
1710                         arg_p = match_strdup(&args[0]);
1711                         if (!arg_p) {
1712                                 ret = -ENOMEM;
1713                                 break;
1714                         }
1715                         ret = kstrtoint(arg_p, 0, &udev->nl_reply_supported);
1716                         kfree(arg_p);
1717                         if (ret < 0)
1718                                 pr_err("kstrtoint() failed for nl_reply_supported=\n");
1719                         break;
1720                 default:
1721                         break;
1722                 }
1723
1724                 if (ret)
1725                         break;
1726         }
1727
1728         kfree(orig);
1729         return (!ret) ? count : ret;
1730 }
1731
1732 static ssize_t tcmu_show_configfs_dev_params(struct se_device *dev, char *b)
1733 {
1734         struct tcmu_dev *udev = TCMU_DEV(dev);
1735         ssize_t bl = 0;
1736
1737         bl = sprintf(b + bl, "Config: %s ",
1738                      udev->dev_config[0] ? udev->dev_config : "NULL");
1739         bl += sprintf(b + bl, "Size: %zu\n", udev->dev_size);
1740
1741         return bl;
1742 }
1743
1744 static sector_t tcmu_get_blocks(struct se_device *dev)
1745 {
1746         struct tcmu_dev *udev = TCMU_DEV(dev);
1747
1748         return div_u64(udev->dev_size - dev->dev_attrib.block_size,
1749                        dev->dev_attrib.block_size);
1750 }
1751
1752 static sense_reason_t
1753 tcmu_parse_cdb(struct se_cmd *cmd)
1754 {
1755         return passthrough_parse_cdb(cmd, tcmu_queue_cmd);
1756 }
1757
1758 static ssize_t tcmu_cmd_time_out_show(struct config_item *item, char *page)
1759 {
1760         struct se_dev_attrib *da = container_of(to_config_group(item),
1761                                         struct se_dev_attrib, da_group);
1762         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1763
1764         return snprintf(page, PAGE_SIZE, "%lu\n", udev->cmd_time_out / MSEC_PER_SEC);
1765 }
1766
1767 static ssize_t tcmu_cmd_time_out_store(struct config_item *item, const char *page,
1768                                        size_t count)
1769 {
1770         struct se_dev_attrib *da = container_of(to_config_group(item),
1771                                         struct se_dev_attrib, da_group);
1772         struct tcmu_dev *udev = container_of(da->da_dev,
1773                                         struct tcmu_dev, se_dev);
1774         u32 val;
1775         int ret;
1776
1777         if (da->da_dev->export_count) {
1778                 pr_err("Unable to set tcmu cmd_time_out while exports exist\n");
1779                 return -EINVAL;
1780         }
1781
1782         ret = kstrtou32(page, 0, &val);
1783         if (ret < 0)
1784                 return ret;
1785
1786         udev->cmd_time_out = val * MSEC_PER_SEC;
1787         return count;
1788 }
1789 CONFIGFS_ATTR(tcmu_, cmd_time_out);
1790
1791 static ssize_t tcmu_dev_config_show(struct config_item *item, char *page)
1792 {
1793         struct se_dev_attrib *da = container_of(to_config_group(item),
1794                                                 struct se_dev_attrib, da_group);
1795         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1796
1797         return snprintf(page, PAGE_SIZE, "%s\n", udev->dev_config);
1798 }
1799
1800 static ssize_t tcmu_dev_config_store(struct config_item *item, const char *page,
1801                                      size_t count)
1802 {
1803         struct se_dev_attrib *da = container_of(to_config_group(item),
1804                                                 struct se_dev_attrib, da_group);
1805         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1806         int ret, len;
1807
1808         len = strlen(page);
1809         if (!len || len > TCMU_CONFIG_LEN - 1)
1810                 return -EINVAL;
1811
1812         /* Check if device has been configured before */
1813         if (tcmu_dev_configured(udev)) {
1814                 ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1815                                          TCMU_ATTR_DEV_CFG, page);
1816                 if (ret) {
1817                         pr_err("Unable to reconfigure device\n");
1818                         return ret;
1819                 }
1820                 strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
1821
1822                 ret = tcmu_update_uio_info(udev);
1823                 if (ret)
1824                         return ret;
1825                 return count;
1826         }
1827         strlcpy(udev->dev_config, page, TCMU_CONFIG_LEN);
1828
1829         return count;
1830 }
1831 CONFIGFS_ATTR(tcmu_, dev_config);
1832
1833 static ssize_t tcmu_dev_size_show(struct config_item *item, char *page)
1834 {
1835         struct se_dev_attrib *da = container_of(to_config_group(item),
1836                                                 struct se_dev_attrib, da_group);
1837         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1838
1839         return snprintf(page, PAGE_SIZE, "%zu\n", udev->dev_size);
1840 }
1841
1842 static ssize_t tcmu_dev_size_store(struct config_item *item, const char *page,
1843                                    size_t count)
1844 {
1845         struct se_dev_attrib *da = container_of(to_config_group(item),
1846                                                 struct se_dev_attrib, da_group);
1847         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1848         u64 val;
1849         int ret;
1850
1851         ret = kstrtou64(page, 0, &val);
1852         if (ret < 0)
1853                 return ret;
1854
1855         /* Check if device has been configured before */
1856         if (tcmu_dev_configured(udev)) {
1857                 ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1858                                          TCMU_ATTR_DEV_SIZE, &val);
1859                 if (ret) {
1860                         pr_err("Unable to reconfigure device\n");
1861                         return ret;
1862                 }
1863         }
1864         udev->dev_size = val;
1865         return count;
1866 }
1867 CONFIGFS_ATTR(tcmu_, dev_size);
1868
1869 static ssize_t tcmu_nl_reply_supported_show(struct config_item *item,
1870                 char *page)
1871 {
1872         struct se_dev_attrib *da = container_of(to_config_group(item),
1873                                                 struct se_dev_attrib, da_group);
1874         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1875
1876         return snprintf(page, PAGE_SIZE, "%d\n", udev->nl_reply_supported);
1877 }
1878
1879 static ssize_t tcmu_nl_reply_supported_store(struct config_item *item,
1880                 const char *page, size_t count)
1881 {
1882         struct se_dev_attrib *da = container_of(to_config_group(item),
1883                                                 struct se_dev_attrib, da_group);
1884         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1885         s8 val;
1886         int ret;
1887
1888         ret = kstrtos8(page, 0, &val);
1889         if (ret < 0)
1890                 return ret;
1891
1892         udev->nl_reply_supported = val;
1893         return count;
1894 }
1895 CONFIGFS_ATTR(tcmu_, nl_reply_supported);
1896
1897 static ssize_t tcmu_emulate_write_cache_show(struct config_item *item,
1898                                              char *page)
1899 {
1900         struct se_dev_attrib *da = container_of(to_config_group(item),
1901                                         struct se_dev_attrib, da_group);
1902
1903         return snprintf(page, PAGE_SIZE, "%i\n", da->emulate_write_cache);
1904 }
1905
1906 static ssize_t tcmu_emulate_write_cache_store(struct config_item *item,
1907                                               const char *page, size_t count)
1908 {
1909         struct se_dev_attrib *da = container_of(to_config_group(item),
1910                                         struct se_dev_attrib, da_group);
1911         struct tcmu_dev *udev = TCMU_DEV(da->da_dev);
1912         u8 val;
1913         int ret;
1914
1915         ret = kstrtou8(page, 0, &val);
1916         if (ret < 0)
1917                 return ret;
1918
1919         /* Check if device has been configured before */
1920         if (tcmu_dev_configured(udev)) {
1921                 ret = tcmu_netlink_event(udev, TCMU_CMD_RECONFIG_DEVICE,
1922                                          TCMU_ATTR_WRITECACHE, &val);
1923                 if (ret) {
1924                         pr_err("Unable to reconfigure device\n");
1925                         return ret;
1926                 }
1927         }
1928
1929         da->emulate_write_cache = val;
1930         return count;
1931 }
1932 CONFIGFS_ATTR(tcmu_, emulate_write_cache);
1933
1934 static struct configfs_attribute *tcmu_attrib_attrs[] = {
1935         &tcmu_attr_cmd_time_out,
1936         &tcmu_attr_dev_config,
1937         &tcmu_attr_dev_size,
1938         &tcmu_attr_emulate_write_cache,
1939         &tcmu_attr_nl_reply_supported,
1940         NULL,
1941 };
1942
1943 static struct configfs_attribute **tcmu_attrs;
1944
1945 static struct target_backend_ops tcmu_ops = {
1946         .name                   = "user",
1947         .owner                  = THIS_MODULE,
1948         .transport_flags        = TRANSPORT_FLAG_PASSTHROUGH,
1949         .attach_hba             = tcmu_attach_hba,
1950         .detach_hba             = tcmu_detach_hba,
1951         .alloc_device           = tcmu_alloc_device,
1952         .configure_device       = tcmu_configure_device,
1953         .destroy_device         = tcmu_destroy_device,
1954         .free_device            = tcmu_free_device,
1955         .parse_cdb              = tcmu_parse_cdb,
1956         .set_configfs_dev_params = tcmu_set_configfs_dev_params,
1957         .show_configfs_dev_params = tcmu_show_configfs_dev_params,
1958         .get_device_type        = sbc_get_device_type,
1959         .get_blocks             = tcmu_get_blocks,
1960         .tb_dev_attrib_attrs    = NULL,
1961 };
1962
1963
1964 static void find_free_blocks(void)
1965 {
1966         struct tcmu_dev *udev;
1967         loff_t off;
1968         uint32_t start, end, block;
1969
1970         mutex_lock(&root_udev_mutex);
1971         list_for_each_entry(udev, &root_udev, node) {
1972                 mutex_lock(&udev->cmdr_lock);
1973
1974                 /* Try to complete the finished commands first */
1975                 tcmu_handle_completions(udev);
1976
1977                 /* Skip the udevs waiting the global pool or in idle */
1978                 if (udev->waiting_global || !udev->dbi_thresh) {
1979                         mutex_unlock(&udev->cmdr_lock);
1980                         continue;
1981                 }
1982
1983                 end = udev->dbi_max + 1;
1984                 block = find_last_bit(udev->data_bitmap, end);
1985                 if (block == udev->dbi_max) {
1986                         /*
1987                          * The last bit is dbi_max, so there is
1988                          * no need to shrink any blocks.
1989                          */
1990                         mutex_unlock(&udev->cmdr_lock);
1991                         continue;
1992                 } else if (block == end) {
1993                         /* The current udev will goto idle state */
1994                         udev->dbi_thresh = start = 0;
1995                         udev->dbi_max = 0;
1996                 } else {
1997                         udev->dbi_thresh = start = block + 1;
1998                         udev->dbi_max = block;
1999                 }
2000
2001                 /* Here will truncate the data area from off */
2002                 off = udev->data_off + start * DATA_BLOCK_SIZE;
2003                 unmap_mapping_range(udev->inode->i_mapping, off, 0, 1);
2004
2005                 /* Release the block pages */
2006                 tcmu_blocks_release(&udev->data_blocks, start, end);
2007                 mutex_unlock(&udev->cmdr_lock);
2008         }
2009         mutex_unlock(&root_udev_mutex);
2010 }
2011
2012 static void run_cmdr_queues(void)
2013 {
2014         struct tcmu_dev *udev;
2015
2016         /*
2017          * Try to wake up the udevs who are waiting
2018          * for the global data block pool.
2019          */
2020         mutex_lock(&root_udev_mutex);
2021         list_for_each_entry(udev, &root_udev, node) {
2022                 mutex_lock(&udev->cmdr_lock);
2023                 if (!udev->waiting_global) {
2024                         mutex_unlock(&udev->cmdr_lock);
2025                         break;
2026                 }
2027                 mutex_unlock(&udev->cmdr_lock);
2028
2029                 wake_up(&udev->wait_cmdr);
2030         }
2031         mutex_unlock(&root_udev_mutex);
2032 }
2033
2034 static void check_timedout_devices(void)
2035 {
2036         struct tcmu_dev *udev, *tmp_dev;
2037         LIST_HEAD(devs);
2038
2039         spin_lock_bh(&timed_out_udevs_lock);
2040         list_splice_init(&timed_out_udevs, &devs);
2041
2042         list_for_each_entry_safe(udev, tmp_dev, &devs, timedout_entry) {
2043                 list_del_init(&udev->timedout_entry);
2044                 spin_unlock_bh(&timed_out_udevs_lock);
2045
2046                 mutex_lock(&udev->cmdr_lock);
2047                 idr_for_each(&udev->commands, tcmu_check_expired_cmd, NULL);
2048                 mutex_unlock(&udev->cmdr_lock);
2049
2050                 spin_lock_bh(&timed_out_udevs_lock);
2051         }
2052
2053         spin_unlock_bh(&timed_out_udevs_lock);
2054 }
2055
2056 static void tcmu_unmap_work_fn(struct work_struct *work)
2057 {
2058         check_timedout_devices();
2059         find_free_blocks();
2060         run_cmdr_queues();
2061 }
2062
2063 static int __init tcmu_module_init(void)
2064 {
2065         int ret, i, k, len = 0;
2066
2067         BUILD_BUG_ON((sizeof(struct tcmu_cmd_entry) % TCMU_OP_ALIGN_SIZE) != 0);
2068
2069         INIT_WORK(&tcmu_unmap_work, tcmu_unmap_work_fn);
2070
2071         tcmu_cmd_cache = kmem_cache_create("tcmu_cmd_cache",
2072                                 sizeof(struct tcmu_cmd),
2073                                 __alignof__(struct tcmu_cmd),
2074                                 0, NULL);
2075         if (!tcmu_cmd_cache)
2076                 return -ENOMEM;
2077
2078         tcmu_root_device = root_device_register("tcm_user");
2079         if (IS_ERR(tcmu_root_device)) {
2080                 ret = PTR_ERR(tcmu_root_device);
2081                 goto out_free_cache;
2082         }
2083
2084         ret = genl_register_family(&tcmu_genl_family);
2085         if (ret < 0) {
2086                 goto out_unreg_device;
2087         }
2088
2089         for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2090                 len += sizeof(struct configfs_attribute *);
2091         }
2092         for (i = 0; tcmu_attrib_attrs[i] != NULL; i++) {
2093                 len += sizeof(struct configfs_attribute *);
2094         }
2095         len += sizeof(struct configfs_attribute *);
2096
2097         tcmu_attrs = kzalloc(len, GFP_KERNEL);
2098         if (!tcmu_attrs) {
2099                 ret = -ENOMEM;
2100                 goto out_unreg_genl;
2101         }
2102
2103         for (i = 0; passthrough_attrib_attrs[i] != NULL; i++) {
2104                 tcmu_attrs[i] = passthrough_attrib_attrs[i];
2105         }
2106         for (k = 0; tcmu_attrib_attrs[k] != NULL; k++) {
2107                 tcmu_attrs[i] = tcmu_attrib_attrs[k];
2108                 i++;
2109         }
2110         tcmu_ops.tb_dev_attrib_attrs = tcmu_attrs;
2111
2112         ret = transport_backend_register(&tcmu_ops);
2113         if (ret)
2114                 goto out_attrs;
2115
2116         return 0;
2117
2118 out_attrs:
2119         kfree(tcmu_attrs);
2120 out_unreg_genl:
2121         genl_unregister_family(&tcmu_genl_family);
2122 out_unreg_device:
2123         root_device_unregister(tcmu_root_device);
2124 out_free_cache:
2125         kmem_cache_destroy(tcmu_cmd_cache);
2126
2127         return ret;
2128 }
2129
2130 static void __exit tcmu_module_exit(void)
2131 {
2132         cancel_work_sync(&tcmu_unmap_work);
2133         target_backend_unregister(&tcmu_ops);
2134         kfree(tcmu_attrs);
2135         genl_unregister_family(&tcmu_genl_family);
2136         root_device_unregister(tcmu_root_device);
2137         kmem_cache_destroy(tcmu_cmd_cache);
2138 }
2139
2140 MODULE_DESCRIPTION("TCM USER subsystem plugin");
2141 MODULE_AUTHOR("Shaohua Li <shli@kernel.org>");
2142 MODULE_AUTHOR("Andy Grover <agrover@redhat.com>");
2143 MODULE_LICENSE("GPL");
2144
2145 module_init(tcmu_module_init);
2146 module_exit(tcmu_module_exit);