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