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