]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/vhost/scsi.c
target: target_core_configfs.h is not needed in fabric drivers
[karo-tx-linux.git] / drivers / vhost / scsi.c
1 /*******************************************************************************
2  * Vhost kernel TCM fabric driver for virtio SCSI initiators
3  *
4  * (C) Copyright 2010-2013 Datera, Inc.
5  * (C) Copyright 2010-2012 IBM Corp.
6  *
7  * Licensed to the Linux Foundation under the General Public License (GPL) version 2.
8  *
9  * Authors: Nicholas A. Bellinger <nab@daterainc.com>
10  *          Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  ****************************************************************************/
23
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <generated/utsrelease.h>
27 #include <linux/utsname.h>
28 #include <linux/init.h>
29 #include <linux/slab.h>
30 #include <linux/kthread.h>
31 #include <linux/types.h>
32 #include <linux/string.h>
33 #include <linux/configfs.h>
34 #include <linux/ctype.h>
35 #include <linux/compat.h>
36 #include <linux/eventfd.h>
37 #include <linux/fs.h>
38 #include <linux/miscdevice.h>
39 #include <asm/unaligned.h>
40 #include <scsi/scsi.h>
41 #include <target/target_core_base.h>
42 #include <target/target_core_fabric.h>
43 #include <target/target_core_fabric_configfs.h>
44 #include <target/configfs_macros.h>
45 #include <linux/vhost.h>
46 #include <linux/virtio_scsi.h>
47 #include <linux/llist.h>
48 #include <linux/bitmap.h>
49 #include <linux/percpu_ida.h>
50
51 #include "vhost.h"
52
53 #define VHOST_SCSI_VERSION  "v0.1"
54 #define VHOST_SCSI_NAMELEN 256
55 #define VHOST_SCSI_MAX_CDB_SIZE 32
56 #define VHOST_SCSI_DEFAULT_TAGS 256
57 #define VHOST_SCSI_PREALLOC_SGLS 2048
58 #define VHOST_SCSI_PREALLOC_UPAGES 2048
59 #define VHOST_SCSI_PREALLOC_PROT_SGLS 512
60
61 struct vhost_scsi_inflight {
62         /* Wait for the flush operation to finish */
63         struct completion comp;
64         /* Refcount for the inflight reqs */
65         struct kref kref;
66 };
67
68 struct vhost_scsi_cmd {
69         /* Descriptor from vhost_get_vq_desc() for virt_queue segment */
70         int tvc_vq_desc;
71         /* virtio-scsi initiator task attribute */
72         int tvc_task_attr;
73         /* virtio-scsi response incoming iovecs */
74         int tvc_in_iovs;
75         /* virtio-scsi initiator data direction */
76         enum dma_data_direction tvc_data_direction;
77         /* Expected data transfer length from virtio-scsi header */
78         u32 tvc_exp_data_len;
79         /* The Tag from include/linux/virtio_scsi.h:struct virtio_scsi_cmd_req */
80         u64 tvc_tag;
81         /* The number of scatterlists associated with this cmd */
82         u32 tvc_sgl_count;
83         u32 tvc_prot_sgl_count;
84         /* Saved unpacked SCSI LUN for vhost_scsi_submission_work() */
85         u32 tvc_lun;
86         /* Pointer to the SGL formatted memory from virtio-scsi */
87         struct scatterlist *tvc_sgl;
88         struct scatterlist *tvc_prot_sgl;
89         struct page **tvc_upages;
90         /* Pointer to response header iovec */
91         struct iovec *tvc_resp_iov;
92         /* Pointer to vhost_scsi for our device */
93         struct vhost_scsi *tvc_vhost;
94         /* Pointer to vhost_virtqueue for the cmd */
95         struct vhost_virtqueue *tvc_vq;
96         /* Pointer to vhost nexus memory */
97         struct vhost_scsi_nexus *tvc_nexus;
98         /* The TCM I/O descriptor that is accessed via container_of() */
99         struct se_cmd tvc_se_cmd;
100         /* work item used for cmwq dispatch to vhost_scsi_submission_work() */
101         struct work_struct work;
102         /* Copy of the incoming SCSI command descriptor block (CDB) */
103         unsigned char tvc_cdb[VHOST_SCSI_MAX_CDB_SIZE];
104         /* Sense buffer that will be mapped into outgoing status */
105         unsigned char tvc_sense_buf[TRANSPORT_SENSE_BUFFER];
106         /* Completed commands list, serviced from vhost worker thread */
107         struct llist_node tvc_completion_list;
108         /* Used to track inflight cmd */
109         struct vhost_scsi_inflight *inflight;
110 };
111
112 struct vhost_scsi_nexus {
113         /* Pointer to TCM session for I_T Nexus */
114         struct se_session *tvn_se_sess;
115 };
116
117 struct vhost_scsi_tpg {
118         /* Vhost port target portal group tag for TCM */
119         u16 tport_tpgt;
120         /* Used to track number of TPG Port/Lun Links wrt to explict I_T Nexus shutdown */
121         int tv_tpg_port_count;
122         /* Used for vhost_scsi device reference to tpg_nexus, protected by tv_tpg_mutex */
123         int tv_tpg_vhost_count;
124         /* Used for enabling T10-PI with legacy devices */
125         int tv_fabric_prot_type;
126         /* list for vhost_scsi_list */
127         struct list_head tv_tpg_list;
128         /* Used to protect access for tpg_nexus */
129         struct mutex tv_tpg_mutex;
130         /* Pointer to the TCM VHost I_T Nexus for this TPG endpoint */
131         struct vhost_scsi_nexus *tpg_nexus;
132         /* Pointer back to vhost_scsi_tport */
133         struct vhost_scsi_tport *tport;
134         /* Returned by vhost_scsi_make_tpg() */
135         struct se_portal_group se_tpg;
136         /* Pointer back to vhost_scsi, protected by tv_tpg_mutex */
137         struct vhost_scsi *vhost_scsi;
138 };
139
140 struct vhost_scsi_tport {
141         /* SCSI protocol the tport is providing */
142         u8 tport_proto_id;
143         /* Binary World Wide unique Port Name for Vhost Target port */
144         u64 tport_wwpn;
145         /* ASCII formatted WWPN for Vhost Target port */
146         char tport_name[VHOST_SCSI_NAMELEN];
147         /* Returned by vhost_scsi_make_tport() */
148         struct se_wwn tport_wwn;
149 };
150
151 struct vhost_scsi_evt {
152         /* event to be sent to guest */
153         struct virtio_scsi_event event;
154         /* event list, serviced from vhost worker thread */
155         struct llist_node list;
156 };
157
158 enum {
159         VHOST_SCSI_VQ_CTL = 0,
160         VHOST_SCSI_VQ_EVT = 1,
161         VHOST_SCSI_VQ_IO = 2,
162 };
163
164 /* Note: can't set VIRTIO_F_VERSION_1 yet, since that implies ANY_LAYOUT. */
165 enum {
166         VHOST_SCSI_FEATURES = VHOST_FEATURES | (1ULL << VIRTIO_SCSI_F_HOTPLUG) |
167                                                (1ULL << VIRTIO_SCSI_F_T10_PI) |
168                                                (1ULL << VIRTIO_F_ANY_LAYOUT) |
169                                                (1ULL << VIRTIO_F_VERSION_1)
170 };
171
172 #define VHOST_SCSI_MAX_TARGET   256
173 #define VHOST_SCSI_MAX_VQ       128
174 #define VHOST_SCSI_MAX_EVENT    128
175
176 struct vhost_scsi_virtqueue {
177         struct vhost_virtqueue vq;
178         /*
179          * Reference counting for inflight reqs, used for flush operation. At
180          * each time, one reference tracks new commands submitted, while we
181          * wait for another one to reach 0.
182          */
183         struct vhost_scsi_inflight inflights[2];
184         /*
185          * Indicate current inflight in use, protected by vq->mutex.
186          * Writers must also take dev mutex and flush under it.
187          */
188         int inflight_idx;
189 };
190
191 struct vhost_scsi {
192         /* Protected by vhost_scsi->dev.mutex */
193         struct vhost_scsi_tpg **vs_tpg;
194         char vs_vhost_wwpn[TRANSPORT_IQN_LEN];
195
196         struct vhost_dev dev;
197         struct vhost_scsi_virtqueue vqs[VHOST_SCSI_MAX_VQ];
198
199         struct vhost_work vs_completion_work; /* cmd completion work item */
200         struct llist_head vs_completion_list; /* cmd completion queue */
201
202         struct vhost_work vs_event_work; /* evt injection work item */
203         struct llist_head vs_event_list; /* evt injection queue */
204
205         bool vs_events_missed; /* any missed events, protected by vq->mutex */
206         int vs_events_nr; /* num of pending events, protected by vq->mutex */
207 };
208
209 static struct target_core_fabric_ops vhost_scsi_ops;
210 static struct workqueue_struct *vhost_scsi_workqueue;
211
212 /* Global spinlock to protect vhost_scsi TPG list for vhost IOCTL access */
213 static DEFINE_MUTEX(vhost_scsi_mutex);
214 static LIST_HEAD(vhost_scsi_list);
215
216 static int iov_num_pages(void __user *iov_base, size_t iov_len)
217 {
218         return (PAGE_ALIGN((unsigned long)iov_base + iov_len) -
219                ((unsigned long)iov_base & PAGE_MASK)) >> PAGE_SHIFT;
220 }
221
222 static void vhost_scsi_done_inflight(struct kref *kref)
223 {
224         struct vhost_scsi_inflight *inflight;
225
226         inflight = container_of(kref, struct vhost_scsi_inflight, kref);
227         complete(&inflight->comp);
228 }
229
230 static void vhost_scsi_init_inflight(struct vhost_scsi *vs,
231                                     struct vhost_scsi_inflight *old_inflight[])
232 {
233         struct vhost_scsi_inflight *new_inflight;
234         struct vhost_virtqueue *vq;
235         int idx, i;
236
237         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
238                 vq = &vs->vqs[i].vq;
239
240                 mutex_lock(&vq->mutex);
241
242                 /* store old infight */
243                 idx = vs->vqs[i].inflight_idx;
244                 if (old_inflight)
245                         old_inflight[i] = &vs->vqs[i].inflights[idx];
246
247                 /* setup new infight */
248                 vs->vqs[i].inflight_idx = idx ^ 1;
249                 new_inflight = &vs->vqs[i].inflights[idx ^ 1];
250                 kref_init(&new_inflight->kref);
251                 init_completion(&new_inflight->comp);
252
253                 mutex_unlock(&vq->mutex);
254         }
255 }
256
257 static struct vhost_scsi_inflight *
258 vhost_scsi_get_inflight(struct vhost_virtqueue *vq)
259 {
260         struct vhost_scsi_inflight *inflight;
261         struct vhost_scsi_virtqueue *svq;
262
263         svq = container_of(vq, struct vhost_scsi_virtqueue, vq);
264         inflight = &svq->inflights[svq->inflight_idx];
265         kref_get(&inflight->kref);
266
267         return inflight;
268 }
269
270 static void vhost_scsi_put_inflight(struct vhost_scsi_inflight *inflight)
271 {
272         kref_put(&inflight->kref, vhost_scsi_done_inflight);
273 }
274
275 static int vhost_scsi_check_true(struct se_portal_group *se_tpg)
276 {
277         return 1;
278 }
279
280 static int vhost_scsi_check_false(struct se_portal_group *se_tpg)
281 {
282         return 0;
283 }
284
285 static char *vhost_scsi_get_fabric_name(void)
286 {
287         return "vhost";
288 }
289
290 static char *vhost_scsi_get_fabric_wwn(struct se_portal_group *se_tpg)
291 {
292         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
293                                 struct vhost_scsi_tpg, se_tpg);
294         struct vhost_scsi_tport *tport = tpg->tport;
295
296         return &tport->tport_name[0];
297 }
298
299 static u16 vhost_scsi_get_tpgt(struct se_portal_group *se_tpg)
300 {
301         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
302                                 struct vhost_scsi_tpg, se_tpg);
303         return tpg->tport_tpgt;
304 }
305
306 static int vhost_scsi_check_prot_fabric_only(struct se_portal_group *se_tpg)
307 {
308         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
309                                 struct vhost_scsi_tpg, se_tpg);
310
311         return tpg->tv_fabric_prot_type;
312 }
313
314 static u32 vhost_scsi_tpg_get_inst_index(struct se_portal_group *se_tpg)
315 {
316         return 1;
317 }
318
319 static void vhost_scsi_release_cmd(struct se_cmd *se_cmd)
320 {
321         struct vhost_scsi_cmd *tv_cmd = container_of(se_cmd,
322                                 struct vhost_scsi_cmd, tvc_se_cmd);
323         struct se_session *se_sess = tv_cmd->tvc_nexus->tvn_se_sess;
324         int i;
325
326         if (tv_cmd->tvc_sgl_count) {
327                 for (i = 0; i < tv_cmd->tvc_sgl_count; i++)
328                         put_page(sg_page(&tv_cmd->tvc_sgl[i]));
329         }
330         if (tv_cmd->tvc_prot_sgl_count) {
331                 for (i = 0; i < tv_cmd->tvc_prot_sgl_count; i++)
332                         put_page(sg_page(&tv_cmd->tvc_prot_sgl[i]));
333         }
334
335         vhost_scsi_put_inflight(tv_cmd->inflight);
336         percpu_ida_free(&se_sess->sess_tag_pool, se_cmd->map_tag);
337 }
338
339 static int vhost_scsi_shutdown_session(struct se_session *se_sess)
340 {
341         return 0;
342 }
343
344 static void vhost_scsi_close_session(struct se_session *se_sess)
345 {
346         return;
347 }
348
349 static u32 vhost_scsi_sess_get_index(struct se_session *se_sess)
350 {
351         return 0;
352 }
353
354 static int vhost_scsi_write_pending(struct se_cmd *se_cmd)
355 {
356         /* Go ahead and process the write immediately */
357         target_execute_cmd(se_cmd);
358         return 0;
359 }
360
361 static int vhost_scsi_write_pending_status(struct se_cmd *se_cmd)
362 {
363         return 0;
364 }
365
366 static void vhost_scsi_set_default_node_attrs(struct se_node_acl *nacl)
367 {
368         return;
369 }
370
371 static int vhost_scsi_get_cmd_state(struct se_cmd *se_cmd)
372 {
373         return 0;
374 }
375
376 static void vhost_scsi_complete_cmd(struct vhost_scsi_cmd *cmd)
377 {
378         struct vhost_scsi *vs = cmd->tvc_vhost;
379
380         llist_add(&cmd->tvc_completion_list, &vs->vs_completion_list);
381
382         vhost_work_queue(&vs->dev, &vs->vs_completion_work);
383 }
384
385 static int vhost_scsi_queue_data_in(struct se_cmd *se_cmd)
386 {
387         struct vhost_scsi_cmd *cmd = container_of(se_cmd,
388                                 struct vhost_scsi_cmd, tvc_se_cmd);
389         vhost_scsi_complete_cmd(cmd);
390         return 0;
391 }
392
393 static int vhost_scsi_queue_status(struct se_cmd *se_cmd)
394 {
395         struct vhost_scsi_cmd *cmd = container_of(se_cmd,
396                                 struct vhost_scsi_cmd, tvc_se_cmd);
397         vhost_scsi_complete_cmd(cmd);
398         return 0;
399 }
400
401 static void vhost_scsi_queue_tm_rsp(struct se_cmd *se_cmd)
402 {
403         return;
404 }
405
406 static void vhost_scsi_aborted_task(struct se_cmd *se_cmd)
407 {
408         return;
409 }
410
411 static void vhost_scsi_free_evt(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
412 {
413         vs->vs_events_nr--;
414         kfree(evt);
415 }
416
417 static struct vhost_scsi_evt *
418 vhost_scsi_allocate_evt(struct vhost_scsi *vs,
419                        u32 event, u32 reason)
420 {
421         struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
422         struct vhost_scsi_evt *evt;
423
424         if (vs->vs_events_nr > VHOST_SCSI_MAX_EVENT) {
425                 vs->vs_events_missed = true;
426                 return NULL;
427         }
428
429         evt = kzalloc(sizeof(*evt), GFP_KERNEL);
430         if (!evt) {
431                 vq_err(vq, "Failed to allocate vhost_scsi_evt\n");
432                 vs->vs_events_missed = true;
433                 return NULL;
434         }
435
436         evt->event.event = cpu_to_vhost32(vq, event);
437         evt->event.reason = cpu_to_vhost32(vq, reason);
438         vs->vs_events_nr++;
439
440         return evt;
441 }
442
443 static void vhost_scsi_free_cmd(struct vhost_scsi_cmd *cmd)
444 {
445         struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
446
447         /* TODO locking against target/backend threads? */
448         transport_generic_free_cmd(se_cmd, 0);
449
450 }
451
452 static int vhost_scsi_check_stop_free(struct se_cmd *se_cmd)
453 {
454         return target_put_sess_cmd(se_cmd);
455 }
456
457 static void
458 vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
459 {
460         struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
461         struct virtio_scsi_event *event = &evt->event;
462         struct virtio_scsi_event __user *eventp;
463         unsigned out, in;
464         int head, ret;
465
466         if (!vq->private_data) {
467                 vs->vs_events_missed = true;
468                 return;
469         }
470
471 again:
472         vhost_disable_notify(&vs->dev, vq);
473         head = vhost_get_vq_desc(vq, vq->iov,
474                         ARRAY_SIZE(vq->iov), &out, &in,
475                         NULL, NULL);
476         if (head < 0) {
477                 vs->vs_events_missed = true;
478                 return;
479         }
480         if (head == vq->num) {
481                 if (vhost_enable_notify(&vs->dev, vq))
482                         goto again;
483                 vs->vs_events_missed = true;
484                 return;
485         }
486
487         if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) {
488                 vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n",
489                                 vq->iov[out].iov_len);
490                 vs->vs_events_missed = true;
491                 return;
492         }
493
494         if (vs->vs_events_missed) {
495                 event->event |= cpu_to_vhost32(vq, VIRTIO_SCSI_T_EVENTS_MISSED);
496                 vs->vs_events_missed = false;
497         }
498
499         eventp = vq->iov[out].iov_base;
500         ret = __copy_to_user(eventp, event, sizeof(*event));
501         if (!ret)
502                 vhost_add_used_and_signal(&vs->dev, vq, head, 0);
503         else
504                 vq_err(vq, "Faulted on vhost_scsi_send_event\n");
505 }
506
507 static void vhost_scsi_evt_work(struct vhost_work *work)
508 {
509         struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
510                                         vs_event_work);
511         struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
512         struct vhost_scsi_evt *evt;
513         struct llist_node *llnode;
514
515         mutex_lock(&vq->mutex);
516         llnode = llist_del_all(&vs->vs_event_list);
517         while (llnode) {
518                 evt = llist_entry(llnode, struct vhost_scsi_evt, list);
519                 llnode = llist_next(llnode);
520                 vhost_scsi_do_evt_work(vs, evt);
521                 vhost_scsi_free_evt(vs, evt);
522         }
523         mutex_unlock(&vq->mutex);
524 }
525
526 /* Fill in status and signal that we are done processing this command
527  *
528  * This is scheduled in the vhost work queue so we are called with the owner
529  * process mm and can access the vring.
530  */
531 static void vhost_scsi_complete_cmd_work(struct vhost_work *work)
532 {
533         struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
534                                         vs_completion_work);
535         DECLARE_BITMAP(signal, VHOST_SCSI_MAX_VQ);
536         struct virtio_scsi_cmd_resp v_rsp;
537         struct vhost_scsi_cmd *cmd;
538         struct llist_node *llnode;
539         struct se_cmd *se_cmd;
540         struct iov_iter iov_iter;
541         int ret, vq;
542
543         bitmap_zero(signal, VHOST_SCSI_MAX_VQ);
544         llnode = llist_del_all(&vs->vs_completion_list);
545         while (llnode) {
546                 cmd = llist_entry(llnode, struct vhost_scsi_cmd,
547                                      tvc_completion_list);
548                 llnode = llist_next(llnode);
549                 se_cmd = &cmd->tvc_se_cmd;
550
551                 pr_debug("%s tv_cmd %p resid %u status %#02x\n", __func__,
552                         cmd, se_cmd->residual_count, se_cmd->scsi_status);
553
554                 memset(&v_rsp, 0, sizeof(v_rsp));
555                 v_rsp.resid = cpu_to_vhost32(cmd->tvc_vq, se_cmd->residual_count);
556                 /* TODO is status_qualifier field needed? */
557                 v_rsp.status = se_cmd->scsi_status;
558                 v_rsp.sense_len = cpu_to_vhost32(cmd->tvc_vq,
559                                                  se_cmd->scsi_sense_length);
560                 memcpy(v_rsp.sense, cmd->tvc_sense_buf,
561                        se_cmd->scsi_sense_length);
562
563                 iov_iter_init(&iov_iter, READ, cmd->tvc_resp_iov,
564                               cmd->tvc_in_iovs, sizeof(v_rsp));
565                 ret = copy_to_iter(&v_rsp, sizeof(v_rsp), &iov_iter);
566                 if (likely(ret == sizeof(v_rsp))) {
567                         struct vhost_scsi_virtqueue *q;
568                         vhost_add_used(cmd->tvc_vq, cmd->tvc_vq_desc, 0);
569                         q = container_of(cmd->tvc_vq, struct vhost_scsi_virtqueue, vq);
570                         vq = q - vs->vqs;
571                         __set_bit(vq, signal);
572                 } else
573                         pr_err("Faulted on virtio_scsi_cmd_resp\n");
574
575                 vhost_scsi_free_cmd(cmd);
576         }
577
578         vq = -1;
579         while ((vq = find_next_bit(signal, VHOST_SCSI_MAX_VQ, vq + 1))
580                 < VHOST_SCSI_MAX_VQ)
581                 vhost_signal(&vs->dev, &vs->vqs[vq].vq);
582 }
583
584 static struct vhost_scsi_cmd *
585 vhost_scsi_get_tag(struct vhost_virtqueue *vq, struct vhost_scsi_tpg *tpg,
586                    unsigned char *cdb, u64 scsi_tag, u16 lun, u8 task_attr,
587                    u32 exp_data_len, int data_direction)
588 {
589         struct vhost_scsi_cmd *cmd;
590         struct vhost_scsi_nexus *tv_nexus;
591         struct se_session *se_sess;
592         struct scatterlist *sg, *prot_sg;
593         struct page **pages;
594         int tag;
595
596         tv_nexus = tpg->tpg_nexus;
597         if (!tv_nexus) {
598                 pr_err("Unable to locate active struct vhost_scsi_nexus\n");
599                 return ERR_PTR(-EIO);
600         }
601         se_sess = tv_nexus->tvn_se_sess;
602
603         tag = percpu_ida_alloc(&se_sess->sess_tag_pool, TASK_RUNNING);
604         if (tag < 0) {
605                 pr_err("Unable to obtain tag for vhost_scsi_cmd\n");
606                 return ERR_PTR(-ENOMEM);
607         }
608
609         cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[tag];
610         sg = cmd->tvc_sgl;
611         prot_sg = cmd->tvc_prot_sgl;
612         pages = cmd->tvc_upages;
613         memset(cmd, 0, sizeof(struct vhost_scsi_cmd));
614
615         cmd->tvc_sgl = sg;
616         cmd->tvc_prot_sgl = prot_sg;
617         cmd->tvc_upages = pages;
618         cmd->tvc_se_cmd.map_tag = tag;
619         cmd->tvc_tag = scsi_tag;
620         cmd->tvc_lun = lun;
621         cmd->tvc_task_attr = task_attr;
622         cmd->tvc_exp_data_len = exp_data_len;
623         cmd->tvc_data_direction = data_direction;
624         cmd->tvc_nexus = tv_nexus;
625         cmd->inflight = vhost_scsi_get_inflight(vq);
626
627         memcpy(cmd->tvc_cdb, cdb, VHOST_SCSI_MAX_CDB_SIZE);
628
629         return cmd;
630 }
631
632 /*
633  * Map a user memory range into a scatterlist
634  *
635  * Returns the number of scatterlist entries used or -errno on error.
636  */
637 static int
638 vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd,
639                       void __user *ptr,
640                       size_t len,
641                       struct scatterlist *sgl,
642                       bool write)
643 {
644         unsigned int npages = 0, offset, nbytes;
645         unsigned int pages_nr = iov_num_pages(ptr, len);
646         struct scatterlist *sg = sgl;
647         struct page **pages = cmd->tvc_upages;
648         int ret, i;
649
650         if (pages_nr > VHOST_SCSI_PREALLOC_UPAGES) {
651                 pr_err("vhost_scsi_map_to_sgl() pages_nr: %u greater than"
652                        " preallocated VHOST_SCSI_PREALLOC_UPAGES: %u\n",
653                         pages_nr, VHOST_SCSI_PREALLOC_UPAGES);
654                 return -ENOBUFS;
655         }
656
657         ret = get_user_pages_fast((unsigned long)ptr, pages_nr, write, pages);
658         /* No pages were pinned */
659         if (ret < 0)
660                 goto out;
661         /* Less pages pinned than wanted */
662         if (ret != pages_nr) {
663                 for (i = 0; i < ret; i++)
664                         put_page(pages[i]);
665                 ret = -EFAULT;
666                 goto out;
667         }
668
669         while (len > 0) {
670                 offset = (uintptr_t)ptr & ~PAGE_MASK;
671                 nbytes = min_t(unsigned int, PAGE_SIZE - offset, len);
672                 sg_set_page(sg, pages[npages], nbytes, offset);
673                 ptr += nbytes;
674                 len -= nbytes;
675                 sg++;
676                 npages++;
677         }
678
679 out:
680         return ret;
681 }
682
683 static int
684 vhost_scsi_calc_sgls(struct iov_iter *iter, size_t bytes, int max_sgls)
685 {
686         int sgl_count = 0;
687
688         if (!iter || !iter->iov) {
689                 pr_err("%s: iter->iov is NULL, but expected bytes: %zu"
690                        " present\n", __func__, bytes);
691                 return -EINVAL;
692         }
693
694         sgl_count = iov_iter_npages(iter, 0xffff);
695         if (sgl_count > max_sgls) {
696                 pr_err("%s: requested sgl_count: %d exceeds pre-allocated"
697                        " max_sgls: %d\n", __func__, sgl_count, max_sgls);
698                 return -EINVAL;
699         }
700         return sgl_count;
701 }
702
703 static int
704 vhost_scsi_iov_to_sgl(struct vhost_scsi_cmd *cmd, bool write,
705                       struct iov_iter *iter,
706                       struct scatterlist *sg, int sg_count)
707 {
708         size_t off = iter->iov_offset;
709         int i, ret;
710
711         for (i = 0; i < iter->nr_segs; i++) {
712                 void __user *base = iter->iov[i].iov_base + off;
713                 size_t len = iter->iov[i].iov_len - off;
714
715                 ret = vhost_scsi_map_to_sgl(cmd, base, len, sg, write);
716                 if (ret < 0) {
717                         for (i = 0; i < sg_count; i++) {
718                                 struct page *page = sg_page(&sg[i]);
719                                 if (page)
720                                         put_page(page);
721                         }
722                         return ret;
723                 }
724                 sg += ret;
725                 off = 0;
726         }
727         return 0;
728 }
729
730 static int
731 vhost_scsi_mapal(struct vhost_scsi_cmd *cmd,
732                  size_t prot_bytes, struct iov_iter *prot_iter,
733                  size_t data_bytes, struct iov_iter *data_iter)
734 {
735         int sgl_count, ret;
736         bool write = (cmd->tvc_data_direction == DMA_FROM_DEVICE);
737
738         if (prot_bytes) {
739                 sgl_count = vhost_scsi_calc_sgls(prot_iter, prot_bytes,
740                                                  VHOST_SCSI_PREALLOC_PROT_SGLS);
741                 if (sgl_count < 0)
742                         return sgl_count;
743
744                 sg_init_table(cmd->tvc_prot_sgl, sgl_count);
745                 cmd->tvc_prot_sgl_count = sgl_count;
746                 pr_debug("%s prot_sg %p prot_sgl_count %u\n", __func__,
747                          cmd->tvc_prot_sgl, cmd->tvc_prot_sgl_count);
748
749                 ret = vhost_scsi_iov_to_sgl(cmd, write, prot_iter,
750                                             cmd->tvc_prot_sgl,
751                                             cmd->tvc_prot_sgl_count);
752                 if (ret < 0) {
753                         cmd->tvc_prot_sgl_count = 0;
754                         return ret;
755                 }
756         }
757         sgl_count = vhost_scsi_calc_sgls(data_iter, data_bytes,
758                                          VHOST_SCSI_PREALLOC_SGLS);
759         if (sgl_count < 0)
760                 return sgl_count;
761
762         sg_init_table(cmd->tvc_sgl, sgl_count);
763         cmd->tvc_sgl_count = sgl_count;
764         pr_debug("%s data_sg %p data_sgl_count %u\n", __func__,
765                   cmd->tvc_sgl, cmd->tvc_sgl_count);
766
767         ret = vhost_scsi_iov_to_sgl(cmd, write, data_iter,
768                                     cmd->tvc_sgl, cmd->tvc_sgl_count);
769         if (ret < 0) {
770                 cmd->tvc_sgl_count = 0;
771                 return ret;
772         }
773         return 0;
774 }
775
776 static int vhost_scsi_to_tcm_attr(int attr)
777 {
778         switch (attr) {
779         case VIRTIO_SCSI_S_SIMPLE:
780                 return TCM_SIMPLE_TAG;
781         case VIRTIO_SCSI_S_ORDERED:
782                 return TCM_ORDERED_TAG;
783         case VIRTIO_SCSI_S_HEAD:
784                 return TCM_HEAD_TAG;
785         case VIRTIO_SCSI_S_ACA:
786                 return TCM_ACA_TAG;
787         default:
788                 break;
789         }
790         return TCM_SIMPLE_TAG;
791 }
792
793 static void vhost_scsi_submission_work(struct work_struct *work)
794 {
795         struct vhost_scsi_cmd *cmd =
796                 container_of(work, struct vhost_scsi_cmd, work);
797         struct vhost_scsi_nexus *tv_nexus;
798         struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
799         struct scatterlist *sg_ptr, *sg_prot_ptr = NULL;
800         int rc;
801
802         /* FIXME: BIDI operation */
803         if (cmd->tvc_sgl_count) {
804                 sg_ptr = cmd->tvc_sgl;
805
806                 if (cmd->tvc_prot_sgl_count)
807                         sg_prot_ptr = cmd->tvc_prot_sgl;
808                 else
809                         se_cmd->prot_pto = true;
810         } else {
811                 sg_ptr = NULL;
812         }
813         tv_nexus = cmd->tvc_nexus;
814
815         se_cmd->tag = 0;
816         rc = target_submit_cmd_map_sgls(se_cmd, tv_nexus->tvn_se_sess,
817                         cmd->tvc_cdb, &cmd->tvc_sense_buf[0],
818                         cmd->tvc_lun, cmd->tvc_exp_data_len,
819                         vhost_scsi_to_tcm_attr(cmd->tvc_task_attr),
820                         cmd->tvc_data_direction, TARGET_SCF_ACK_KREF,
821                         sg_ptr, cmd->tvc_sgl_count, NULL, 0, sg_prot_ptr,
822                         cmd->tvc_prot_sgl_count);
823         if (rc < 0) {
824                 transport_send_check_condition_and_sense(se_cmd,
825                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
826                 transport_generic_free_cmd(se_cmd, 0);
827         }
828 }
829
830 static void
831 vhost_scsi_send_bad_target(struct vhost_scsi *vs,
832                            struct vhost_virtqueue *vq,
833                            int head, unsigned out)
834 {
835         struct virtio_scsi_cmd_resp __user *resp;
836         struct virtio_scsi_cmd_resp rsp;
837         int ret;
838
839         memset(&rsp, 0, sizeof(rsp));
840         rsp.response = VIRTIO_SCSI_S_BAD_TARGET;
841         resp = vq->iov[out].iov_base;
842         ret = __copy_to_user(resp, &rsp, sizeof(rsp));
843         if (!ret)
844                 vhost_add_used_and_signal(&vs->dev, vq, head, 0);
845         else
846                 pr_err("Faulted on virtio_scsi_cmd_resp\n");
847 }
848
849 static void
850 vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq)
851 {
852         struct vhost_scsi_tpg **vs_tpg, *tpg;
853         struct virtio_scsi_cmd_req v_req;
854         struct virtio_scsi_cmd_req_pi v_req_pi;
855         struct vhost_scsi_cmd *cmd;
856         struct iov_iter out_iter, in_iter, prot_iter, data_iter;
857         u64 tag;
858         u32 exp_data_len, data_direction;
859         unsigned out, in;
860         int head, ret, prot_bytes;
861         size_t req_size, rsp_size = sizeof(struct virtio_scsi_cmd_resp);
862         size_t out_size, in_size;
863         u16 lun;
864         u8 *target, *lunp, task_attr;
865         bool t10_pi = vhost_has_feature(vq, VIRTIO_SCSI_F_T10_PI);
866         void *req, *cdb;
867
868         mutex_lock(&vq->mutex);
869         /*
870          * We can handle the vq only after the endpoint is setup by calling the
871          * VHOST_SCSI_SET_ENDPOINT ioctl.
872          */
873         vs_tpg = vq->private_data;
874         if (!vs_tpg)
875                 goto out;
876
877         vhost_disable_notify(&vs->dev, vq);
878
879         for (;;) {
880                 head = vhost_get_vq_desc(vq, vq->iov,
881                                          ARRAY_SIZE(vq->iov), &out, &in,
882                                          NULL, NULL);
883                 pr_debug("vhost_get_vq_desc: head: %d, out: %u in: %u\n",
884                          head, out, in);
885                 /* On error, stop handling until the next kick. */
886                 if (unlikely(head < 0))
887                         break;
888                 /* Nothing new?  Wait for eventfd to tell us they refilled. */
889                 if (head == vq->num) {
890                         if (unlikely(vhost_enable_notify(&vs->dev, vq))) {
891                                 vhost_disable_notify(&vs->dev, vq);
892                                 continue;
893                         }
894                         break;
895                 }
896                 /*
897                  * Check for a sane response buffer so we can report early
898                  * errors back to the guest.
899                  */
900                 if (unlikely(vq->iov[out].iov_len < rsp_size)) {
901                         vq_err(vq, "Expecting at least virtio_scsi_cmd_resp"
902                                 " size, got %zu bytes\n", vq->iov[out].iov_len);
903                         break;
904                 }
905                 /*
906                  * Setup pointers and values based upon different virtio-scsi
907                  * request header if T10_PI is enabled in KVM guest.
908                  */
909                 if (t10_pi) {
910                         req = &v_req_pi;
911                         req_size = sizeof(v_req_pi);
912                         lunp = &v_req_pi.lun[0];
913                         target = &v_req_pi.lun[1];
914                 } else {
915                         req = &v_req;
916                         req_size = sizeof(v_req);
917                         lunp = &v_req.lun[0];
918                         target = &v_req.lun[1];
919                 }
920                 /*
921                  * FIXME: Not correct for BIDI operation
922                  */
923                 out_size = iov_length(vq->iov, out);
924                 in_size = iov_length(&vq->iov[out], in);
925
926                 /*
927                  * Copy over the virtio-scsi request header, which for a
928                  * ANY_LAYOUT enabled guest may span multiple iovecs, or a
929                  * single iovec may contain both the header + outgoing
930                  * WRITE payloads.
931                  *
932                  * copy_from_iter() will advance out_iter, so that it will
933                  * point at the start of the outgoing WRITE payload, if
934                  * DMA_TO_DEVICE is set.
935                  */
936                 iov_iter_init(&out_iter, WRITE, vq->iov, out, out_size);
937
938                 ret = copy_from_iter(req, req_size, &out_iter);
939                 if (unlikely(ret != req_size)) {
940                         vq_err(vq, "Faulted on copy_from_iter\n");
941                         vhost_scsi_send_bad_target(vs, vq, head, out);
942                         continue;
943                 }
944                 /* virtio-scsi spec requires byte 0 of the lun to be 1 */
945                 if (unlikely(*lunp != 1)) {
946                         vq_err(vq, "Illegal virtio-scsi lun: %u\n", *lunp);
947                         vhost_scsi_send_bad_target(vs, vq, head, out);
948                         continue;
949                 }
950
951                 tpg = ACCESS_ONCE(vs_tpg[*target]);
952                 if (unlikely(!tpg)) {
953                         /* Target does not exist, fail the request */
954                         vhost_scsi_send_bad_target(vs, vq, head, out);
955                         continue;
956                 }
957                 /*
958                  * Determine data_direction by calculating the total outgoing
959                  * iovec sizes + incoming iovec sizes vs. virtio-scsi request +
960                  * response headers respectively.
961                  *
962                  * For DMA_TO_DEVICE this is out_iter, which is already pointing
963                  * to the right place.
964                  *
965                  * For DMA_FROM_DEVICE, the iovec will be just past the end
966                  * of the virtio-scsi response header in either the same
967                  * or immediately following iovec.
968                  *
969                  * Any associated T10_PI bytes for the outgoing / incoming
970                  * payloads are included in calculation of exp_data_len here.
971                  */
972                 prot_bytes = 0;
973
974                 if (out_size > req_size) {
975                         data_direction = DMA_TO_DEVICE;
976                         exp_data_len = out_size - req_size;
977                         data_iter = out_iter;
978                 } else if (in_size > rsp_size) {
979                         data_direction = DMA_FROM_DEVICE;
980                         exp_data_len = in_size - rsp_size;
981
982                         iov_iter_init(&in_iter, READ, &vq->iov[out], in,
983                                       rsp_size + exp_data_len);
984                         iov_iter_advance(&in_iter, rsp_size);
985                         data_iter = in_iter;
986                 } else {
987                         data_direction = DMA_NONE;
988                         exp_data_len = 0;
989                 }
990                 /*
991                  * If T10_PI header + payload is present, setup prot_iter values
992                  * and recalculate data_iter for vhost_scsi_mapal() mapping to
993                  * host scatterlists via get_user_pages_fast().
994                  */
995                 if (t10_pi) {
996                         if (v_req_pi.pi_bytesout) {
997                                 if (data_direction != DMA_TO_DEVICE) {
998                                         vq_err(vq, "Received non zero pi_bytesout,"
999                                                 " but wrong data_direction\n");
1000                                         vhost_scsi_send_bad_target(vs, vq, head, out);
1001                                         continue;
1002                                 }
1003                                 prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesout);
1004                         } else if (v_req_pi.pi_bytesin) {
1005                                 if (data_direction != DMA_FROM_DEVICE) {
1006                                         vq_err(vq, "Received non zero pi_bytesin,"
1007                                                 " but wrong data_direction\n");
1008                                         vhost_scsi_send_bad_target(vs, vq, head, out);
1009                                         continue;
1010                                 }
1011                                 prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesin);
1012                         }
1013                         /*
1014                          * Set prot_iter to data_iter, and advance past any
1015                          * preceeding prot_bytes that may be present.
1016                          *
1017                          * Also fix up the exp_data_len to reflect only the
1018                          * actual data payload length.
1019                          */
1020                         if (prot_bytes) {
1021                                 exp_data_len -= prot_bytes;
1022                                 prot_iter = data_iter;
1023                                 iov_iter_advance(&data_iter, prot_bytes);
1024                         }
1025                         tag = vhost64_to_cpu(vq, v_req_pi.tag);
1026                         task_attr = v_req_pi.task_attr;
1027                         cdb = &v_req_pi.cdb[0];
1028                         lun = ((v_req_pi.lun[2] << 8) | v_req_pi.lun[3]) & 0x3FFF;
1029                 } else {
1030                         tag = vhost64_to_cpu(vq, v_req.tag);
1031                         task_attr = v_req.task_attr;
1032                         cdb = &v_req.cdb[0];
1033                         lun = ((v_req.lun[2] << 8) | v_req.lun[3]) & 0x3FFF;
1034                 }
1035                 /*
1036                  * Check that the received CDB size does not exceeded our
1037                  * hardcoded max for vhost-scsi, then get a pre-allocated
1038                  * cmd descriptor for the new virtio-scsi tag.
1039                  *
1040                  * TODO what if cdb was too small for varlen cdb header?
1041                  */
1042                 if (unlikely(scsi_command_size(cdb) > VHOST_SCSI_MAX_CDB_SIZE)) {
1043                         vq_err(vq, "Received SCSI CDB with command_size: %d that"
1044                                 " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1045                                 scsi_command_size(cdb), VHOST_SCSI_MAX_CDB_SIZE);
1046                         vhost_scsi_send_bad_target(vs, vq, head, out);
1047                         continue;
1048                 }
1049                 cmd = vhost_scsi_get_tag(vq, tpg, cdb, tag, lun, task_attr,
1050                                          exp_data_len + prot_bytes,
1051                                          data_direction);
1052                 if (IS_ERR(cmd)) {
1053                         vq_err(vq, "vhost_scsi_get_tag failed %ld\n",
1054                                PTR_ERR(cmd));
1055                         vhost_scsi_send_bad_target(vs, vq, head, out);
1056                         continue;
1057                 }
1058                 cmd->tvc_vhost = vs;
1059                 cmd->tvc_vq = vq;
1060                 cmd->tvc_resp_iov = &vq->iov[out];
1061                 cmd->tvc_in_iovs = in;
1062
1063                 pr_debug("vhost_scsi got command opcode: %#02x, lun: %d\n",
1064                          cmd->tvc_cdb[0], cmd->tvc_lun);
1065                 pr_debug("cmd: %p exp_data_len: %d, prot_bytes: %d data_direction:"
1066                          " %d\n", cmd, exp_data_len, prot_bytes, data_direction);
1067
1068                 if (data_direction != DMA_NONE) {
1069                         ret = vhost_scsi_mapal(cmd,
1070                                                prot_bytes, &prot_iter,
1071                                                exp_data_len, &data_iter);
1072                         if (unlikely(ret)) {
1073                                 vq_err(vq, "Failed to map iov to sgl\n");
1074                                 vhost_scsi_release_cmd(&cmd->tvc_se_cmd);
1075                                 vhost_scsi_send_bad_target(vs, vq, head, out);
1076                                 continue;
1077                         }
1078                 }
1079                 /*
1080                  * Save the descriptor from vhost_get_vq_desc() to be used to
1081                  * complete the virtio-scsi request in TCM callback context via
1082                  * vhost_scsi_queue_data_in() and vhost_scsi_queue_status()
1083                  */
1084                 cmd->tvc_vq_desc = head;
1085                 /*
1086                  * Dispatch cmd descriptor for cmwq execution in process
1087                  * context provided by vhost_scsi_workqueue.  This also ensures
1088                  * cmd is executed on the same kworker CPU as this vhost
1089                  * thread to gain positive L2 cache locality effects.
1090                  */
1091                 INIT_WORK(&cmd->work, vhost_scsi_submission_work);
1092                 queue_work(vhost_scsi_workqueue, &cmd->work);
1093         }
1094 out:
1095         mutex_unlock(&vq->mutex);
1096 }
1097
1098 static void vhost_scsi_ctl_handle_kick(struct vhost_work *work)
1099 {
1100         pr_debug("%s: The handling func for control queue.\n", __func__);
1101 }
1102
1103 static void
1104 vhost_scsi_send_evt(struct vhost_scsi *vs,
1105                    struct vhost_scsi_tpg *tpg,
1106                    struct se_lun *lun,
1107                    u32 event,
1108                    u32 reason)
1109 {
1110         struct vhost_scsi_evt *evt;
1111
1112         evt = vhost_scsi_allocate_evt(vs, event, reason);
1113         if (!evt)
1114                 return;
1115
1116         if (tpg && lun) {
1117                 /* TODO: share lun setup code with virtio-scsi.ko */
1118                 /*
1119                  * Note: evt->event is zeroed when we allocate it and
1120                  * lun[4-7] need to be zero according to virtio-scsi spec.
1121                  */
1122                 evt->event.lun[0] = 0x01;
1123                 evt->event.lun[1] = tpg->tport_tpgt;
1124                 if (lun->unpacked_lun >= 256)
1125                         evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
1126                 evt->event.lun[3] = lun->unpacked_lun & 0xFF;
1127         }
1128
1129         llist_add(&evt->list, &vs->vs_event_list);
1130         vhost_work_queue(&vs->dev, &vs->vs_event_work);
1131 }
1132
1133 static void vhost_scsi_evt_handle_kick(struct vhost_work *work)
1134 {
1135         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
1136                                                 poll.work);
1137         struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
1138
1139         mutex_lock(&vq->mutex);
1140         if (!vq->private_data)
1141                 goto out;
1142
1143         if (vs->vs_events_missed)
1144                 vhost_scsi_send_evt(vs, NULL, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
1145 out:
1146         mutex_unlock(&vq->mutex);
1147 }
1148
1149 static void vhost_scsi_handle_kick(struct vhost_work *work)
1150 {
1151         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
1152                                                 poll.work);
1153         struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
1154
1155         vhost_scsi_handle_vq(vs, vq);
1156 }
1157
1158 static void vhost_scsi_flush_vq(struct vhost_scsi *vs, int index)
1159 {
1160         vhost_poll_flush(&vs->vqs[index].vq.poll);
1161 }
1162
1163 /* Callers must hold dev mutex */
1164 static void vhost_scsi_flush(struct vhost_scsi *vs)
1165 {
1166         struct vhost_scsi_inflight *old_inflight[VHOST_SCSI_MAX_VQ];
1167         int i;
1168
1169         /* Init new inflight and remember the old inflight */
1170         vhost_scsi_init_inflight(vs, old_inflight);
1171
1172         /*
1173          * The inflight->kref was initialized to 1. We decrement it here to
1174          * indicate the start of the flush operation so that it will reach 0
1175          * when all the reqs are finished.
1176          */
1177         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
1178                 kref_put(&old_inflight[i]->kref, vhost_scsi_done_inflight);
1179
1180         /* Flush both the vhost poll and vhost work */
1181         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
1182                 vhost_scsi_flush_vq(vs, i);
1183         vhost_work_flush(&vs->dev, &vs->vs_completion_work);
1184         vhost_work_flush(&vs->dev, &vs->vs_event_work);
1185
1186         /* Wait for all reqs issued before the flush to be finished */
1187         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
1188                 wait_for_completion(&old_inflight[i]->comp);
1189 }
1190
1191 /*
1192  * Called from vhost_scsi_ioctl() context to walk the list of available
1193  * vhost_scsi_tpg with an active struct vhost_scsi_nexus
1194  *
1195  *  The lock nesting rule is:
1196  *    vhost_scsi_mutex -> vs->dev.mutex -> tpg->tv_tpg_mutex -> vq->mutex
1197  */
1198 static int
1199 vhost_scsi_set_endpoint(struct vhost_scsi *vs,
1200                         struct vhost_scsi_target *t)
1201 {
1202         struct se_portal_group *se_tpg;
1203         struct vhost_scsi_tport *tv_tport;
1204         struct vhost_scsi_tpg *tpg;
1205         struct vhost_scsi_tpg **vs_tpg;
1206         struct vhost_virtqueue *vq;
1207         int index, ret, i, len;
1208         bool match = false;
1209
1210         mutex_lock(&vhost_scsi_mutex);
1211         mutex_lock(&vs->dev.mutex);
1212
1213         /* Verify that ring has been setup correctly. */
1214         for (index = 0; index < vs->dev.nvqs; ++index) {
1215                 /* Verify that ring has been setup correctly. */
1216                 if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
1217                         ret = -EFAULT;
1218                         goto out;
1219                 }
1220         }
1221
1222         len = sizeof(vs_tpg[0]) * VHOST_SCSI_MAX_TARGET;
1223         vs_tpg = kzalloc(len, GFP_KERNEL);
1224         if (!vs_tpg) {
1225                 ret = -ENOMEM;
1226                 goto out;
1227         }
1228         if (vs->vs_tpg)
1229                 memcpy(vs_tpg, vs->vs_tpg, len);
1230
1231         list_for_each_entry(tpg, &vhost_scsi_list, tv_tpg_list) {
1232                 mutex_lock(&tpg->tv_tpg_mutex);
1233                 if (!tpg->tpg_nexus) {
1234                         mutex_unlock(&tpg->tv_tpg_mutex);
1235                         continue;
1236                 }
1237                 if (tpg->tv_tpg_vhost_count != 0) {
1238                         mutex_unlock(&tpg->tv_tpg_mutex);
1239                         continue;
1240                 }
1241                 tv_tport = tpg->tport;
1242
1243                 if (!strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
1244                         if (vs->vs_tpg && vs->vs_tpg[tpg->tport_tpgt]) {
1245                                 kfree(vs_tpg);
1246                                 mutex_unlock(&tpg->tv_tpg_mutex);
1247                                 ret = -EEXIST;
1248                                 goto out;
1249                         }
1250                         /*
1251                          * In order to ensure individual vhost-scsi configfs
1252                          * groups cannot be removed while in use by vhost ioctl,
1253                          * go ahead and take an explicit se_tpg->tpg_group.cg_item
1254                          * dependency now.
1255                          */
1256                         se_tpg = &tpg->se_tpg;
1257                         ret = target_depend_item(&se_tpg->tpg_group.cg_item);
1258                         if (ret) {
1259                                 pr_warn("configfs_depend_item() failed: %d\n", ret);
1260                                 kfree(vs_tpg);
1261                                 mutex_unlock(&tpg->tv_tpg_mutex);
1262                                 goto out;
1263                         }
1264                         tpg->tv_tpg_vhost_count++;
1265                         tpg->vhost_scsi = vs;
1266                         vs_tpg[tpg->tport_tpgt] = tpg;
1267                         smp_mb__after_atomic();
1268                         match = true;
1269                 }
1270                 mutex_unlock(&tpg->tv_tpg_mutex);
1271         }
1272
1273         if (match) {
1274                 memcpy(vs->vs_vhost_wwpn, t->vhost_wwpn,
1275                        sizeof(vs->vs_vhost_wwpn));
1276                 for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
1277                         vq = &vs->vqs[i].vq;
1278                         mutex_lock(&vq->mutex);
1279                         vq->private_data = vs_tpg;
1280                         vhost_init_used(vq);
1281                         mutex_unlock(&vq->mutex);
1282                 }
1283                 ret = 0;
1284         } else {
1285                 ret = -EEXIST;
1286         }
1287
1288         /*
1289          * Act as synchronize_rcu to make sure access to
1290          * old vs->vs_tpg is finished.
1291          */
1292         vhost_scsi_flush(vs);
1293         kfree(vs->vs_tpg);
1294         vs->vs_tpg = vs_tpg;
1295
1296 out:
1297         mutex_unlock(&vs->dev.mutex);
1298         mutex_unlock(&vhost_scsi_mutex);
1299         return ret;
1300 }
1301
1302 static int
1303 vhost_scsi_clear_endpoint(struct vhost_scsi *vs,
1304                           struct vhost_scsi_target *t)
1305 {
1306         struct se_portal_group *se_tpg;
1307         struct vhost_scsi_tport *tv_tport;
1308         struct vhost_scsi_tpg *tpg;
1309         struct vhost_virtqueue *vq;
1310         bool match = false;
1311         int index, ret, i;
1312         u8 target;
1313
1314         mutex_lock(&vhost_scsi_mutex);
1315         mutex_lock(&vs->dev.mutex);
1316         /* Verify that ring has been setup correctly. */
1317         for (index = 0; index < vs->dev.nvqs; ++index) {
1318                 if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
1319                         ret = -EFAULT;
1320                         goto err_dev;
1321                 }
1322         }
1323
1324         if (!vs->vs_tpg) {
1325                 ret = 0;
1326                 goto err_dev;
1327         }
1328
1329         for (i = 0; i < VHOST_SCSI_MAX_TARGET; i++) {
1330                 target = i;
1331                 tpg = vs->vs_tpg[target];
1332                 if (!tpg)
1333                         continue;
1334
1335                 mutex_lock(&tpg->tv_tpg_mutex);
1336                 tv_tport = tpg->tport;
1337                 if (!tv_tport) {
1338                         ret = -ENODEV;
1339                         goto err_tpg;
1340                 }
1341
1342                 if (strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
1343                         pr_warn("tv_tport->tport_name: %s, tpg->tport_tpgt: %hu"
1344                                 " does not match t->vhost_wwpn: %s, t->vhost_tpgt: %hu\n",
1345                                 tv_tport->tport_name, tpg->tport_tpgt,
1346                                 t->vhost_wwpn, t->vhost_tpgt);
1347                         ret = -EINVAL;
1348                         goto err_tpg;
1349                 }
1350                 tpg->tv_tpg_vhost_count--;
1351                 tpg->vhost_scsi = NULL;
1352                 vs->vs_tpg[target] = NULL;
1353                 match = true;
1354                 mutex_unlock(&tpg->tv_tpg_mutex);
1355                 /*
1356                  * Release se_tpg->tpg_group.cg_item configfs dependency now
1357                  * to allow vhost-scsi WWPN se_tpg->tpg_group shutdown to occur.
1358                  */
1359                 se_tpg = &tpg->se_tpg;
1360                 target_undepend_item(&se_tpg->tpg_group.cg_item);
1361         }
1362         if (match) {
1363                 for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
1364                         vq = &vs->vqs[i].vq;
1365                         mutex_lock(&vq->mutex);
1366                         vq->private_data = NULL;
1367                         mutex_unlock(&vq->mutex);
1368                 }
1369         }
1370         /*
1371          * Act as synchronize_rcu to make sure access to
1372          * old vs->vs_tpg is finished.
1373          */
1374         vhost_scsi_flush(vs);
1375         kfree(vs->vs_tpg);
1376         vs->vs_tpg = NULL;
1377         WARN_ON(vs->vs_events_nr);
1378         mutex_unlock(&vs->dev.mutex);
1379         mutex_unlock(&vhost_scsi_mutex);
1380         return 0;
1381
1382 err_tpg:
1383         mutex_unlock(&tpg->tv_tpg_mutex);
1384 err_dev:
1385         mutex_unlock(&vs->dev.mutex);
1386         mutex_unlock(&vhost_scsi_mutex);
1387         return ret;
1388 }
1389
1390 static int vhost_scsi_set_features(struct vhost_scsi *vs, u64 features)
1391 {
1392         struct vhost_virtqueue *vq;
1393         int i;
1394
1395         if (features & ~VHOST_SCSI_FEATURES)
1396                 return -EOPNOTSUPP;
1397
1398         mutex_lock(&vs->dev.mutex);
1399         if ((features & (1 << VHOST_F_LOG_ALL)) &&
1400             !vhost_log_access_ok(&vs->dev)) {
1401                 mutex_unlock(&vs->dev.mutex);
1402                 return -EFAULT;
1403         }
1404
1405         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
1406                 vq = &vs->vqs[i].vq;
1407                 mutex_lock(&vq->mutex);
1408                 vq->acked_features = features;
1409                 mutex_unlock(&vq->mutex);
1410         }
1411         mutex_unlock(&vs->dev.mutex);
1412         return 0;
1413 }
1414
1415 static int vhost_scsi_open(struct inode *inode, struct file *f)
1416 {
1417         struct vhost_scsi *vs;
1418         struct vhost_virtqueue **vqs;
1419         int r = -ENOMEM, i;
1420
1421         vs = kzalloc(sizeof(*vs), GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
1422         if (!vs) {
1423                 vs = vzalloc(sizeof(*vs));
1424                 if (!vs)
1425                         goto err_vs;
1426         }
1427
1428         vqs = kmalloc(VHOST_SCSI_MAX_VQ * sizeof(*vqs), GFP_KERNEL);
1429         if (!vqs)
1430                 goto err_vqs;
1431
1432         vhost_work_init(&vs->vs_completion_work, vhost_scsi_complete_cmd_work);
1433         vhost_work_init(&vs->vs_event_work, vhost_scsi_evt_work);
1434
1435         vs->vs_events_nr = 0;
1436         vs->vs_events_missed = false;
1437
1438         vqs[VHOST_SCSI_VQ_CTL] = &vs->vqs[VHOST_SCSI_VQ_CTL].vq;
1439         vqs[VHOST_SCSI_VQ_EVT] = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
1440         vs->vqs[VHOST_SCSI_VQ_CTL].vq.handle_kick = vhost_scsi_ctl_handle_kick;
1441         vs->vqs[VHOST_SCSI_VQ_EVT].vq.handle_kick = vhost_scsi_evt_handle_kick;
1442         for (i = VHOST_SCSI_VQ_IO; i < VHOST_SCSI_MAX_VQ; i++) {
1443                 vqs[i] = &vs->vqs[i].vq;
1444                 vs->vqs[i].vq.handle_kick = vhost_scsi_handle_kick;
1445         }
1446         vhost_dev_init(&vs->dev, vqs, VHOST_SCSI_MAX_VQ);
1447
1448         vhost_scsi_init_inflight(vs, NULL);
1449
1450         f->private_data = vs;
1451         return 0;
1452
1453 err_vqs:
1454         kvfree(vs);
1455 err_vs:
1456         return r;
1457 }
1458
1459 static int vhost_scsi_release(struct inode *inode, struct file *f)
1460 {
1461         struct vhost_scsi *vs = f->private_data;
1462         struct vhost_scsi_target t;
1463
1464         mutex_lock(&vs->dev.mutex);
1465         memcpy(t.vhost_wwpn, vs->vs_vhost_wwpn, sizeof(t.vhost_wwpn));
1466         mutex_unlock(&vs->dev.mutex);
1467         vhost_scsi_clear_endpoint(vs, &t);
1468         vhost_dev_stop(&vs->dev);
1469         vhost_dev_cleanup(&vs->dev, false);
1470         /* Jobs can re-queue themselves in evt kick handler. Do extra flush. */
1471         vhost_scsi_flush(vs);
1472         kfree(vs->dev.vqs);
1473         kvfree(vs);
1474         return 0;
1475 }
1476
1477 static long
1478 vhost_scsi_ioctl(struct file *f,
1479                  unsigned int ioctl,
1480                  unsigned long arg)
1481 {
1482         struct vhost_scsi *vs = f->private_data;
1483         struct vhost_scsi_target backend;
1484         void __user *argp = (void __user *)arg;
1485         u64 __user *featurep = argp;
1486         u32 __user *eventsp = argp;
1487         u32 events_missed;
1488         u64 features;
1489         int r, abi_version = VHOST_SCSI_ABI_VERSION;
1490         struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
1491
1492         switch (ioctl) {
1493         case VHOST_SCSI_SET_ENDPOINT:
1494                 if (copy_from_user(&backend, argp, sizeof backend))
1495                         return -EFAULT;
1496                 if (backend.reserved != 0)
1497                         return -EOPNOTSUPP;
1498
1499                 return vhost_scsi_set_endpoint(vs, &backend);
1500         case VHOST_SCSI_CLEAR_ENDPOINT:
1501                 if (copy_from_user(&backend, argp, sizeof backend))
1502                         return -EFAULT;
1503                 if (backend.reserved != 0)
1504                         return -EOPNOTSUPP;
1505
1506                 return vhost_scsi_clear_endpoint(vs, &backend);
1507         case VHOST_SCSI_GET_ABI_VERSION:
1508                 if (copy_to_user(argp, &abi_version, sizeof abi_version))
1509                         return -EFAULT;
1510                 return 0;
1511         case VHOST_SCSI_SET_EVENTS_MISSED:
1512                 if (get_user(events_missed, eventsp))
1513                         return -EFAULT;
1514                 mutex_lock(&vq->mutex);
1515                 vs->vs_events_missed = events_missed;
1516                 mutex_unlock(&vq->mutex);
1517                 return 0;
1518         case VHOST_SCSI_GET_EVENTS_MISSED:
1519                 mutex_lock(&vq->mutex);
1520                 events_missed = vs->vs_events_missed;
1521                 mutex_unlock(&vq->mutex);
1522                 if (put_user(events_missed, eventsp))
1523                         return -EFAULT;
1524                 return 0;
1525         case VHOST_GET_FEATURES:
1526                 features = VHOST_SCSI_FEATURES;
1527                 if (copy_to_user(featurep, &features, sizeof features))
1528                         return -EFAULT;
1529                 return 0;
1530         case VHOST_SET_FEATURES:
1531                 if (copy_from_user(&features, featurep, sizeof features))
1532                         return -EFAULT;
1533                 return vhost_scsi_set_features(vs, features);
1534         default:
1535                 mutex_lock(&vs->dev.mutex);
1536                 r = vhost_dev_ioctl(&vs->dev, ioctl, argp);
1537                 /* TODO: flush backend after dev ioctl. */
1538                 if (r == -ENOIOCTLCMD)
1539                         r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
1540                 mutex_unlock(&vs->dev.mutex);
1541                 return r;
1542         }
1543 }
1544
1545 #ifdef CONFIG_COMPAT
1546 static long vhost_scsi_compat_ioctl(struct file *f, unsigned int ioctl,
1547                                 unsigned long arg)
1548 {
1549         return vhost_scsi_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1550 }
1551 #endif
1552
1553 static const struct file_operations vhost_scsi_fops = {
1554         .owner          = THIS_MODULE,
1555         .release        = vhost_scsi_release,
1556         .unlocked_ioctl = vhost_scsi_ioctl,
1557 #ifdef CONFIG_COMPAT
1558         .compat_ioctl   = vhost_scsi_compat_ioctl,
1559 #endif
1560         .open           = vhost_scsi_open,
1561         .llseek         = noop_llseek,
1562 };
1563
1564 static struct miscdevice vhost_scsi_misc = {
1565         MISC_DYNAMIC_MINOR,
1566         "vhost-scsi",
1567         &vhost_scsi_fops,
1568 };
1569
1570 static int __init vhost_scsi_register(void)
1571 {
1572         return misc_register(&vhost_scsi_misc);
1573 }
1574
1575 static int vhost_scsi_deregister(void)
1576 {
1577         return misc_deregister(&vhost_scsi_misc);
1578 }
1579
1580 static char *vhost_scsi_dump_proto_id(struct vhost_scsi_tport *tport)
1581 {
1582         switch (tport->tport_proto_id) {
1583         case SCSI_PROTOCOL_SAS:
1584                 return "SAS";
1585         case SCSI_PROTOCOL_FCP:
1586                 return "FCP";
1587         case SCSI_PROTOCOL_ISCSI:
1588                 return "iSCSI";
1589         default:
1590                 break;
1591         }
1592
1593         return "Unknown";
1594 }
1595
1596 static void
1597 vhost_scsi_do_plug(struct vhost_scsi_tpg *tpg,
1598                   struct se_lun *lun, bool plug)
1599 {
1600
1601         struct vhost_scsi *vs = tpg->vhost_scsi;
1602         struct vhost_virtqueue *vq;
1603         u32 reason;
1604
1605         if (!vs)
1606                 return;
1607
1608         mutex_lock(&vs->dev.mutex);
1609
1610         if (plug)
1611                 reason = VIRTIO_SCSI_EVT_RESET_RESCAN;
1612         else
1613                 reason = VIRTIO_SCSI_EVT_RESET_REMOVED;
1614
1615         vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
1616         mutex_lock(&vq->mutex);
1617         if (vhost_has_feature(vq, VIRTIO_SCSI_F_HOTPLUG))
1618                 vhost_scsi_send_evt(vs, tpg, lun,
1619                                    VIRTIO_SCSI_T_TRANSPORT_RESET, reason);
1620         mutex_unlock(&vq->mutex);
1621         mutex_unlock(&vs->dev.mutex);
1622 }
1623
1624 static void vhost_scsi_hotplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
1625 {
1626         vhost_scsi_do_plug(tpg, lun, true);
1627 }
1628
1629 static void vhost_scsi_hotunplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
1630 {
1631         vhost_scsi_do_plug(tpg, lun, false);
1632 }
1633
1634 static int vhost_scsi_port_link(struct se_portal_group *se_tpg,
1635                                struct se_lun *lun)
1636 {
1637         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1638                                 struct vhost_scsi_tpg, se_tpg);
1639
1640         mutex_lock(&vhost_scsi_mutex);
1641
1642         mutex_lock(&tpg->tv_tpg_mutex);
1643         tpg->tv_tpg_port_count++;
1644         mutex_unlock(&tpg->tv_tpg_mutex);
1645
1646         vhost_scsi_hotplug(tpg, lun);
1647
1648         mutex_unlock(&vhost_scsi_mutex);
1649
1650         return 0;
1651 }
1652
1653 static void vhost_scsi_port_unlink(struct se_portal_group *se_tpg,
1654                                   struct se_lun *lun)
1655 {
1656         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1657                                 struct vhost_scsi_tpg, se_tpg);
1658
1659         mutex_lock(&vhost_scsi_mutex);
1660
1661         mutex_lock(&tpg->tv_tpg_mutex);
1662         tpg->tv_tpg_port_count--;
1663         mutex_unlock(&tpg->tv_tpg_mutex);
1664
1665         vhost_scsi_hotunplug(tpg, lun);
1666
1667         mutex_unlock(&vhost_scsi_mutex);
1668 }
1669
1670 static void vhost_scsi_free_cmd_map_res(struct vhost_scsi_nexus *nexus,
1671                                        struct se_session *se_sess)
1672 {
1673         struct vhost_scsi_cmd *tv_cmd;
1674         unsigned int i;
1675
1676         if (!se_sess->sess_cmd_map)
1677                 return;
1678
1679         for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
1680                 tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
1681
1682                 kfree(tv_cmd->tvc_sgl);
1683                 kfree(tv_cmd->tvc_prot_sgl);
1684                 kfree(tv_cmd->tvc_upages);
1685         }
1686 }
1687
1688 static ssize_t vhost_scsi_tpg_attrib_store_fabric_prot_type(
1689         struct se_portal_group *se_tpg,
1690         const char *page,
1691         size_t count)
1692 {
1693         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1694                                 struct vhost_scsi_tpg, se_tpg);
1695         unsigned long val;
1696         int ret = kstrtoul(page, 0, &val);
1697
1698         if (ret) {
1699                 pr_err("kstrtoul() returned %d for fabric_prot_type\n", ret);
1700                 return ret;
1701         }
1702         if (val != 0 && val != 1 && val != 3) {
1703                 pr_err("Invalid vhost_scsi fabric_prot_type: %lu\n", val);
1704                 return -EINVAL;
1705         }
1706         tpg->tv_fabric_prot_type = val;
1707
1708         return count;
1709 }
1710
1711 static ssize_t vhost_scsi_tpg_attrib_show_fabric_prot_type(
1712         struct se_portal_group *se_tpg,
1713         char *page)
1714 {
1715         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1716                                 struct vhost_scsi_tpg, se_tpg);
1717
1718         return sprintf(page, "%d\n", tpg->tv_fabric_prot_type);
1719 }
1720 TF_TPG_ATTRIB_ATTR(vhost_scsi, fabric_prot_type, S_IRUGO | S_IWUSR);
1721
1722 static struct configfs_attribute *vhost_scsi_tpg_attrib_attrs[] = {
1723         &vhost_scsi_tpg_attrib_fabric_prot_type.attr,
1724         NULL,
1725 };
1726
1727 static int vhost_scsi_make_nexus(struct vhost_scsi_tpg *tpg,
1728                                 const char *name)
1729 {
1730         struct se_portal_group *se_tpg;
1731         struct se_session *se_sess;
1732         struct vhost_scsi_nexus *tv_nexus;
1733         struct vhost_scsi_cmd *tv_cmd;
1734         unsigned int i;
1735
1736         mutex_lock(&tpg->tv_tpg_mutex);
1737         if (tpg->tpg_nexus) {
1738                 mutex_unlock(&tpg->tv_tpg_mutex);
1739                 pr_debug("tpg->tpg_nexus already exists\n");
1740                 return -EEXIST;
1741         }
1742         se_tpg = &tpg->se_tpg;
1743
1744         tv_nexus = kzalloc(sizeof(struct vhost_scsi_nexus), GFP_KERNEL);
1745         if (!tv_nexus) {
1746                 mutex_unlock(&tpg->tv_tpg_mutex);
1747                 pr_err("Unable to allocate struct vhost_scsi_nexus\n");
1748                 return -ENOMEM;
1749         }
1750         /*
1751          *  Initialize the struct se_session pointer and setup tagpool
1752          *  for struct vhost_scsi_cmd descriptors
1753          */
1754         tv_nexus->tvn_se_sess = transport_init_session_tags(
1755                                         VHOST_SCSI_DEFAULT_TAGS,
1756                                         sizeof(struct vhost_scsi_cmd),
1757                                         TARGET_PROT_DIN_PASS | TARGET_PROT_DOUT_PASS);
1758         if (IS_ERR(tv_nexus->tvn_se_sess)) {
1759                 mutex_unlock(&tpg->tv_tpg_mutex);
1760                 kfree(tv_nexus);
1761                 return -ENOMEM;
1762         }
1763         se_sess = tv_nexus->tvn_se_sess;
1764         for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
1765                 tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
1766
1767                 tv_cmd->tvc_sgl = kzalloc(sizeof(struct scatterlist) *
1768                                         VHOST_SCSI_PREALLOC_SGLS, GFP_KERNEL);
1769                 if (!tv_cmd->tvc_sgl) {
1770                         mutex_unlock(&tpg->tv_tpg_mutex);
1771                         pr_err("Unable to allocate tv_cmd->tvc_sgl\n");
1772                         goto out;
1773                 }
1774
1775                 tv_cmd->tvc_upages = kzalloc(sizeof(struct page *) *
1776                                         VHOST_SCSI_PREALLOC_UPAGES, GFP_KERNEL);
1777                 if (!tv_cmd->tvc_upages) {
1778                         mutex_unlock(&tpg->tv_tpg_mutex);
1779                         pr_err("Unable to allocate tv_cmd->tvc_upages\n");
1780                         goto out;
1781                 }
1782
1783                 tv_cmd->tvc_prot_sgl = kzalloc(sizeof(struct scatterlist) *
1784                                         VHOST_SCSI_PREALLOC_PROT_SGLS, GFP_KERNEL);
1785                 if (!tv_cmd->tvc_prot_sgl) {
1786                         mutex_unlock(&tpg->tv_tpg_mutex);
1787                         pr_err("Unable to allocate tv_cmd->tvc_prot_sgl\n");
1788                         goto out;
1789                 }
1790         }
1791         /*
1792          * Since we are running in 'demo mode' this call with generate a
1793          * struct se_node_acl for the vhost_scsi struct se_portal_group with
1794          * the SCSI Initiator port name of the passed configfs group 'name'.
1795          */
1796         tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
1797                                 se_tpg, (unsigned char *)name);
1798         if (!tv_nexus->tvn_se_sess->se_node_acl) {
1799                 mutex_unlock(&tpg->tv_tpg_mutex);
1800                 pr_debug("core_tpg_check_initiator_node_acl() failed"
1801                                 " for %s\n", name);
1802                 goto out;
1803         }
1804         /*
1805          * Now register the TCM vhost virtual I_T Nexus as active.
1806          */
1807         transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
1808                         tv_nexus->tvn_se_sess, tv_nexus);
1809         tpg->tpg_nexus = tv_nexus;
1810
1811         mutex_unlock(&tpg->tv_tpg_mutex);
1812         return 0;
1813
1814 out:
1815         vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
1816         transport_free_session(se_sess);
1817         kfree(tv_nexus);
1818         return -ENOMEM;
1819 }
1820
1821 static int vhost_scsi_drop_nexus(struct vhost_scsi_tpg *tpg)
1822 {
1823         struct se_session *se_sess;
1824         struct vhost_scsi_nexus *tv_nexus;
1825
1826         mutex_lock(&tpg->tv_tpg_mutex);
1827         tv_nexus = tpg->tpg_nexus;
1828         if (!tv_nexus) {
1829                 mutex_unlock(&tpg->tv_tpg_mutex);
1830                 return -ENODEV;
1831         }
1832
1833         se_sess = tv_nexus->tvn_se_sess;
1834         if (!se_sess) {
1835                 mutex_unlock(&tpg->tv_tpg_mutex);
1836                 return -ENODEV;
1837         }
1838
1839         if (tpg->tv_tpg_port_count != 0) {
1840                 mutex_unlock(&tpg->tv_tpg_mutex);
1841                 pr_err("Unable to remove TCM_vhost I_T Nexus with"
1842                         " active TPG port count: %d\n",
1843                         tpg->tv_tpg_port_count);
1844                 return -EBUSY;
1845         }
1846
1847         if (tpg->tv_tpg_vhost_count != 0) {
1848                 mutex_unlock(&tpg->tv_tpg_mutex);
1849                 pr_err("Unable to remove TCM_vhost I_T Nexus with"
1850                         " active TPG vhost count: %d\n",
1851                         tpg->tv_tpg_vhost_count);
1852                 return -EBUSY;
1853         }
1854
1855         pr_debug("TCM_vhost_ConfigFS: Removing I_T Nexus to emulated"
1856                 " %s Initiator Port: %s\n", vhost_scsi_dump_proto_id(tpg->tport),
1857                 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1858
1859         vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
1860         /*
1861          * Release the SCSI I_T Nexus to the emulated vhost Target Port
1862          */
1863         transport_deregister_session(tv_nexus->tvn_se_sess);
1864         tpg->tpg_nexus = NULL;
1865         mutex_unlock(&tpg->tv_tpg_mutex);
1866
1867         kfree(tv_nexus);
1868         return 0;
1869 }
1870
1871 static ssize_t vhost_scsi_tpg_show_nexus(struct se_portal_group *se_tpg,
1872                                         char *page)
1873 {
1874         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1875                                 struct vhost_scsi_tpg, se_tpg);
1876         struct vhost_scsi_nexus *tv_nexus;
1877         ssize_t ret;
1878
1879         mutex_lock(&tpg->tv_tpg_mutex);
1880         tv_nexus = tpg->tpg_nexus;
1881         if (!tv_nexus) {
1882                 mutex_unlock(&tpg->tv_tpg_mutex);
1883                 return -ENODEV;
1884         }
1885         ret = snprintf(page, PAGE_SIZE, "%s\n",
1886                         tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1887         mutex_unlock(&tpg->tv_tpg_mutex);
1888
1889         return ret;
1890 }
1891
1892 static ssize_t vhost_scsi_tpg_store_nexus(struct se_portal_group *se_tpg,
1893                                          const char *page,
1894                                          size_t count)
1895 {
1896         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
1897                                 struct vhost_scsi_tpg, se_tpg);
1898         struct vhost_scsi_tport *tport_wwn = tpg->tport;
1899         unsigned char i_port[VHOST_SCSI_NAMELEN], *ptr, *port_ptr;
1900         int ret;
1901         /*
1902          * Shutdown the active I_T nexus if 'NULL' is passed..
1903          */
1904         if (!strncmp(page, "NULL", 4)) {
1905                 ret = vhost_scsi_drop_nexus(tpg);
1906                 return (!ret) ? count : ret;
1907         }
1908         /*
1909          * Otherwise make sure the passed virtual Initiator port WWN matches
1910          * the fabric protocol_id set in vhost_scsi_make_tport(), and call
1911          * vhost_scsi_make_nexus().
1912          */
1913         if (strlen(page) >= VHOST_SCSI_NAMELEN) {
1914                 pr_err("Emulated NAA Sas Address: %s, exceeds"
1915                                 " max: %d\n", page, VHOST_SCSI_NAMELEN);
1916                 return -EINVAL;
1917         }
1918         snprintf(&i_port[0], VHOST_SCSI_NAMELEN, "%s", page);
1919
1920         ptr = strstr(i_port, "naa.");
1921         if (ptr) {
1922                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
1923                         pr_err("Passed SAS Initiator Port %s does not"
1924                                 " match target port protoid: %s\n", i_port,
1925                                 vhost_scsi_dump_proto_id(tport_wwn));
1926                         return -EINVAL;
1927                 }
1928                 port_ptr = &i_port[0];
1929                 goto check_newline;
1930         }
1931         ptr = strstr(i_port, "fc.");
1932         if (ptr) {
1933                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
1934                         pr_err("Passed FCP Initiator Port %s does not"
1935                                 " match target port protoid: %s\n", i_port,
1936                                 vhost_scsi_dump_proto_id(tport_wwn));
1937                         return -EINVAL;
1938                 }
1939                 port_ptr = &i_port[3]; /* Skip over "fc." */
1940                 goto check_newline;
1941         }
1942         ptr = strstr(i_port, "iqn.");
1943         if (ptr) {
1944                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
1945                         pr_err("Passed iSCSI Initiator Port %s does not"
1946                                 " match target port protoid: %s\n", i_port,
1947                                 vhost_scsi_dump_proto_id(tport_wwn));
1948                         return -EINVAL;
1949                 }
1950                 port_ptr = &i_port[0];
1951                 goto check_newline;
1952         }
1953         pr_err("Unable to locate prefix for emulated Initiator Port:"
1954                         " %s\n", i_port);
1955         return -EINVAL;
1956         /*
1957          * Clear any trailing newline for the NAA WWN
1958          */
1959 check_newline:
1960         if (i_port[strlen(i_port)-1] == '\n')
1961                 i_port[strlen(i_port)-1] = '\0';
1962
1963         ret = vhost_scsi_make_nexus(tpg, port_ptr);
1964         if (ret < 0)
1965                 return ret;
1966
1967         return count;
1968 }
1969
1970 TF_TPG_BASE_ATTR(vhost_scsi, nexus, S_IRUGO | S_IWUSR);
1971
1972 static struct configfs_attribute *vhost_scsi_tpg_attrs[] = {
1973         &vhost_scsi_tpg_nexus.attr,
1974         NULL,
1975 };
1976
1977 static struct se_portal_group *
1978 vhost_scsi_make_tpg(struct se_wwn *wwn,
1979                    struct config_group *group,
1980                    const char *name)
1981 {
1982         struct vhost_scsi_tport *tport = container_of(wwn,
1983                         struct vhost_scsi_tport, tport_wwn);
1984
1985         struct vhost_scsi_tpg *tpg;
1986         u16 tpgt;
1987         int ret;
1988
1989         if (strstr(name, "tpgt_") != name)
1990                 return ERR_PTR(-EINVAL);
1991         if (kstrtou16(name + 5, 10, &tpgt) || tpgt >= VHOST_SCSI_MAX_TARGET)
1992                 return ERR_PTR(-EINVAL);
1993
1994         tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
1995         if (!tpg) {
1996                 pr_err("Unable to allocate struct vhost_scsi_tpg");
1997                 return ERR_PTR(-ENOMEM);
1998         }
1999         mutex_init(&tpg->tv_tpg_mutex);
2000         INIT_LIST_HEAD(&tpg->tv_tpg_list);
2001         tpg->tport = tport;
2002         tpg->tport_tpgt = tpgt;
2003
2004         ret = core_tpg_register(&vhost_scsi_ops, wwn, &tpg->se_tpg,
2005                                 tport->tport_proto_id);
2006         if (ret < 0) {
2007                 kfree(tpg);
2008                 return NULL;
2009         }
2010         mutex_lock(&vhost_scsi_mutex);
2011         list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
2012         mutex_unlock(&vhost_scsi_mutex);
2013
2014         return &tpg->se_tpg;
2015 }
2016
2017 static void vhost_scsi_drop_tpg(struct se_portal_group *se_tpg)
2018 {
2019         struct vhost_scsi_tpg *tpg = container_of(se_tpg,
2020                                 struct vhost_scsi_tpg, se_tpg);
2021
2022         mutex_lock(&vhost_scsi_mutex);
2023         list_del(&tpg->tv_tpg_list);
2024         mutex_unlock(&vhost_scsi_mutex);
2025         /*
2026          * Release the virtual I_T Nexus for this vhost TPG
2027          */
2028         vhost_scsi_drop_nexus(tpg);
2029         /*
2030          * Deregister the se_tpg from TCM..
2031          */
2032         core_tpg_deregister(se_tpg);
2033         kfree(tpg);
2034 }
2035
2036 static struct se_wwn *
2037 vhost_scsi_make_tport(struct target_fabric_configfs *tf,
2038                      struct config_group *group,
2039                      const char *name)
2040 {
2041         struct vhost_scsi_tport *tport;
2042         char *ptr;
2043         u64 wwpn = 0;
2044         int off = 0;
2045
2046         /* if (vhost_scsi_parse_wwn(name, &wwpn, 1) < 0)
2047                 return ERR_PTR(-EINVAL); */
2048
2049         tport = kzalloc(sizeof(struct vhost_scsi_tport), GFP_KERNEL);
2050         if (!tport) {
2051                 pr_err("Unable to allocate struct vhost_scsi_tport");
2052                 return ERR_PTR(-ENOMEM);
2053         }
2054         tport->tport_wwpn = wwpn;
2055         /*
2056          * Determine the emulated Protocol Identifier and Target Port Name
2057          * based on the incoming configfs directory name.
2058          */
2059         ptr = strstr(name, "naa.");
2060         if (ptr) {
2061                 tport->tport_proto_id = SCSI_PROTOCOL_SAS;
2062                 goto check_len;
2063         }
2064         ptr = strstr(name, "fc.");
2065         if (ptr) {
2066                 tport->tport_proto_id = SCSI_PROTOCOL_FCP;
2067                 off = 3; /* Skip over "fc." */
2068                 goto check_len;
2069         }
2070         ptr = strstr(name, "iqn.");
2071         if (ptr) {
2072                 tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
2073                 goto check_len;
2074         }
2075
2076         pr_err("Unable to locate prefix for emulated Target Port:"
2077                         " %s\n", name);
2078         kfree(tport);
2079         return ERR_PTR(-EINVAL);
2080
2081 check_len:
2082         if (strlen(name) >= VHOST_SCSI_NAMELEN) {
2083                 pr_err("Emulated %s Address: %s, exceeds"
2084                         " max: %d\n", name, vhost_scsi_dump_proto_id(tport),
2085                         VHOST_SCSI_NAMELEN);
2086                 kfree(tport);
2087                 return ERR_PTR(-EINVAL);
2088         }
2089         snprintf(&tport->tport_name[0], VHOST_SCSI_NAMELEN, "%s", &name[off]);
2090
2091         pr_debug("TCM_VHost_ConfigFS: Allocated emulated Target"
2092                 " %s Address: %s\n", vhost_scsi_dump_proto_id(tport), name);
2093
2094         return &tport->tport_wwn;
2095 }
2096
2097 static void vhost_scsi_drop_tport(struct se_wwn *wwn)
2098 {
2099         struct vhost_scsi_tport *tport = container_of(wwn,
2100                                 struct vhost_scsi_tport, tport_wwn);
2101
2102         pr_debug("TCM_VHost_ConfigFS: Deallocating emulated Target"
2103                 " %s Address: %s\n", vhost_scsi_dump_proto_id(tport),
2104                 tport->tport_name);
2105
2106         kfree(tport);
2107 }
2108
2109 static ssize_t
2110 vhost_scsi_wwn_show_attr_version(struct target_fabric_configfs *tf,
2111                                 char *page)
2112 {
2113         return sprintf(page, "TCM_VHOST fabric module %s on %s/%s"
2114                 "on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
2115                 utsname()->machine);
2116 }
2117
2118 TF_WWN_ATTR_RO(vhost_scsi, version);
2119
2120 static struct configfs_attribute *vhost_scsi_wwn_attrs[] = {
2121         &vhost_scsi_wwn_version.attr,
2122         NULL,
2123 };
2124
2125 static struct target_core_fabric_ops vhost_scsi_ops = {
2126         .module                         = THIS_MODULE,
2127         .name                           = "vhost",
2128         .get_fabric_name                = vhost_scsi_get_fabric_name,
2129         .tpg_get_wwn                    = vhost_scsi_get_fabric_wwn,
2130         .tpg_get_tag                    = vhost_scsi_get_tpgt,
2131         .tpg_check_demo_mode            = vhost_scsi_check_true,
2132         .tpg_check_demo_mode_cache      = vhost_scsi_check_true,
2133         .tpg_check_demo_mode_write_protect = vhost_scsi_check_false,
2134         .tpg_check_prod_mode_write_protect = vhost_scsi_check_false,
2135         .tpg_check_prot_fabric_only     = vhost_scsi_check_prot_fabric_only,
2136         .tpg_get_inst_index             = vhost_scsi_tpg_get_inst_index,
2137         .release_cmd                    = vhost_scsi_release_cmd,
2138         .check_stop_free                = vhost_scsi_check_stop_free,
2139         .shutdown_session               = vhost_scsi_shutdown_session,
2140         .close_session                  = vhost_scsi_close_session,
2141         .sess_get_index                 = vhost_scsi_sess_get_index,
2142         .sess_get_initiator_sid         = NULL,
2143         .write_pending                  = vhost_scsi_write_pending,
2144         .write_pending_status           = vhost_scsi_write_pending_status,
2145         .set_default_node_attributes    = vhost_scsi_set_default_node_attrs,
2146         .get_cmd_state                  = vhost_scsi_get_cmd_state,
2147         .queue_data_in                  = vhost_scsi_queue_data_in,
2148         .queue_status                   = vhost_scsi_queue_status,
2149         .queue_tm_rsp                   = vhost_scsi_queue_tm_rsp,
2150         .aborted_task                   = vhost_scsi_aborted_task,
2151         /*
2152          * Setup callers for generic logic in target_core_fabric_configfs.c
2153          */
2154         .fabric_make_wwn                = vhost_scsi_make_tport,
2155         .fabric_drop_wwn                = vhost_scsi_drop_tport,
2156         .fabric_make_tpg                = vhost_scsi_make_tpg,
2157         .fabric_drop_tpg                = vhost_scsi_drop_tpg,
2158         .fabric_post_link               = vhost_scsi_port_link,
2159         .fabric_pre_unlink              = vhost_scsi_port_unlink,
2160
2161         .tfc_wwn_attrs                  = vhost_scsi_wwn_attrs,
2162         .tfc_tpg_base_attrs             = vhost_scsi_tpg_attrs,
2163         .tfc_tpg_attrib_attrs           = vhost_scsi_tpg_attrib_attrs,
2164 };
2165
2166 static int __init vhost_scsi_init(void)
2167 {
2168         int ret = -ENOMEM;
2169
2170         pr_debug("TCM_VHOST fabric module %s on %s/%s"
2171                 " on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
2172                 utsname()->machine);
2173
2174         /*
2175          * Use our own dedicated workqueue for submitting I/O into
2176          * target core to avoid contention within system_wq.
2177          */
2178         vhost_scsi_workqueue = alloc_workqueue("vhost_scsi", 0, 0);
2179         if (!vhost_scsi_workqueue)
2180                 goto out;
2181
2182         ret = vhost_scsi_register();
2183         if (ret < 0)
2184                 goto out_destroy_workqueue;
2185
2186         ret = target_register_template(&vhost_scsi_ops);
2187         if (ret < 0)
2188                 goto out_vhost_scsi_deregister;
2189
2190         return 0;
2191
2192 out_vhost_scsi_deregister:
2193         vhost_scsi_deregister();
2194 out_destroy_workqueue:
2195         destroy_workqueue(vhost_scsi_workqueue);
2196 out:
2197         return ret;
2198 };
2199
2200 static void vhost_scsi_exit(void)
2201 {
2202         target_unregister_template(&vhost_scsi_ops);
2203         vhost_scsi_deregister();
2204         destroy_workqueue(vhost_scsi_workqueue);
2205 };
2206
2207 MODULE_DESCRIPTION("VHOST_SCSI series fabric driver");
2208 MODULE_ALIAS("tcm_vhost");
2209 MODULE_LICENSE("GPL");
2210 module_init(vhost_scsi_init);
2211 module_exit(vhost_scsi_exit);