Merge branch 'urgent'
[firefly-linux-kernel-4.4.55.git] / drivers / vhost / tcm_vhost.c
1 /*******************************************************************************
2  * Vhost kernel TCM fabric driver for virtio SCSI initiators
3  *
4  * (C) Copyright 2010-2012 RisingTide Systems LLC.
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@risingtidesystems.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 <scsi/scsi_tcq.h>
42 #include <target/target_core_base.h>
43 #include <target/target_core_fabric.h>
44 #include <target/target_core_fabric_configfs.h>
45 #include <target/target_core_configfs.h>
46 #include <target/configfs_macros.h>
47 #include <linux/vhost.h>
48 #include <linux/virtio_net.h> /* TODO vhost.h currently depends on this */
49 #include <linux/virtio_scsi.h>
50 #include <linux/llist.h>
51 #include <linux/bitmap.h>
52
53 #include "vhost.c"
54 #include "vhost.h"
55 #include "tcm_vhost.h"
56
57 enum {
58         VHOST_SCSI_VQ_CTL = 0,
59         VHOST_SCSI_VQ_EVT = 1,
60         VHOST_SCSI_VQ_IO = 2,
61 };
62
63 #define VHOST_SCSI_MAX_TARGET   256
64 #define VHOST_SCSI_MAX_VQ       128
65
66 struct vhost_scsi {
67         /* Protected by vhost_scsi->dev.mutex */
68         struct tcm_vhost_tpg *vs_tpg[VHOST_SCSI_MAX_TARGET];
69         char vs_vhost_wwpn[TRANSPORT_IQN_LEN];
70         bool vs_endpoint;
71
72         struct vhost_dev dev;
73         struct vhost_virtqueue vqs[VHOST_SCSI_MAX_VQ];
74
75         struct vhost_work vs_completion_work; /* cmd completion work item */
76         struct llist_head vs_completion_list; /* cmd completion queue */
77 };
78
79 /* Local pointer to allocated TCM configfs fabric module */
80 static struct target_fabric_configfs *tcm_vhost_fabric_configfs;
81
82 static struct workqueue_struct *tcm_vhost_workqueue;
83
84 /* Global spinlock to protect tcm_vhost TPG list for vhost IOCTL access */
85 static DEFINE_MUTEX(tcm_vhost_mutex);
86 static LIST_HEAD(tcm_vhost_list);
87
88 static int iov_num_pages(struct iovec *iov)
89 {
90         return (PAGE_ALIGN((unsigned long)iov->iov_base + iov->iov_len) -
91                ((unsigned long)iov->iov_base & PAGE_MASK)) >> PAGE_SHIFT;
92 }
93
94 static int tcm_vhost_check_true(struct se_portal_group *se_tpg)
95 {
96         return 1;
97 }
98
99 static int tcm_vhost_check_false(struct se_portal_group *se_tpg)
100 {
101         return 0;
102 }
103
104 static char *tcm_vhost_get_fabric_name(void)
105 {
106         return "vhost";
107 }
108
109 static u8 tcm_vhost_get_fabric_proto_ident(struct se_portal_group *se_tpg)
110 {
111         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
112                                 struct tcm_vhost_tpg, se_tpg);
113         struct tcm_vhost_tport *tport = tpg->tport;
114
115         switch (tport->tport_proto_id) {
116         case SCSI_PROTOCOL_SAS:
117                 return sas_get_fabric_proto_ident(se_tpg);
118         case SCSI_PROTOCOL_FCP:
119                 return fc_get_fabric_proto_ident(se_tpg);
120         case SCSI_PROTOCOL_ISCSI:
121                 return iscsi_get_fabric_proto_ident(se_tpg);
122         default:
123                 pr_err("Unknown tport_proto_id: 0x%02x, using"
124                         " SAS emulation\n", tport->tport_proto_id);
125                 break;
126         }
127
128         return sas_get_fabric_proto_ident(se_tpg);
129 }
130
131 static char *tcm_vhost_get_fabric_wwn(struct se_portal_group *se_tpg)
132 {
133         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
134                                 struct tcm_vhost_tpg, se_tpg);
135         struct tcm_vhost_tport *tport = tpg->tport;
136
137         return &tport->tport_name[0];
138 }
139
140 static u16 tcm_vhost_get_tag(struct se_portal_group *se_tpg)
141 {
142         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
143                                 struct tcm_vhost_tpg, se_tpg);
144         return tpg->tport_tpgt;
145 }
146
147 static u32 tcm_vhost_get_default_depth(struct se_portal_group *se_tpg)
148 {
149         return 1;
150 }
151
152 static u32 tcm_vhost_get_pr_transport_id(struct se_portal_group *se_tpg,
153         struct se_node_acl *se_nacl,
154         struct t10_pr_registration *pr_reg,
155         int *format_code,
156         unsigned char *buf)
157 {
158         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
159                                 struct tcm_vhost_tpg, se_tpg);
160         struct tcm_vhost_tport *tport = tpg->tport;
161
162         switch (tport->tport_proto_id) {
163         case SCSI_PROTOCOL_SAS:
164                 return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
165                                         format_code, buf);
166         case SCSI_PROTOCOL_FCP:
167                 return fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
168                                         format_code, buf);
169         case SCSI_PROTOCOL_ISCSI:
170                 return iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
171                                         format_code, buf);
172         default:
173                 pr_err("Unknown tport_proto_id: 0x%02x, using"
174                         " SAS emulation\n", tport->tport_proto_id);
175                 break;
176         }
177
178         return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
179                         format_code, buf);
180 }
181
182 static u32 tcm_vhost_get_pr_transport_id_len(struct se_portal_group *se_tpg,
183         struct se_node_acl *se_nacl,
184         struct t10_pr_registration *pr_reg,
185         int *format_code)
186 {
187         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
188                                 struct tcm_vhost_tpg, se_tpg);
189         struct tcm_vhost_tport *tport = tpg->tport;
190
191         switch (tport->tport_proto_id) {
192         case SCSI_PROTOCOL_SAS:
193                 return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
194                                         format_code);
195         case SCSI_PROTOCOL_FCP:
196                 return fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
197                                         format_code);
198         case SCSI_PROTOCOL_ISCSI:
199                 return iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
200                                         format_code);
201         default:
202                 pr_err("Unknown tport_proto_id: 0x%02x, using"
203                         " SAS emulation\n", tport->tport_proto_id);
204                 break;
205         }
206
207         return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
208                         format_code);
209 }
210
211 static char *tcm_vhost_parse_pr_out_transport_id(struct se_portal_group *se_tpg,
212         const char *buf,
213         u32 *out_tid_len,
214         char **port_nexus_ptr)
215 {
216         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
217                                 struct tcm_vhost_tpg, se_tpg);
218         struct tcm_vhost_tport *tport = tpg->tport;
219
220         switch (tport->tport_proto_id) {
221         case SCSI_PROTOCOL_SAS:
222                 return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
223                                         port_nexus_ptr);
224         case SCSI_PROTOCOL_FCP:
225                 return fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
226                                         port_nexus_ptr);
227         case SCSI_PROTOCOL_ISCSI:
228                 return iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
229                                         port_nexus_ptr);
230         default:
231                 pr_err("Unknown tport_proto_id: 0x%02x, using"
232                         " SAS emulation\n", tport->tport_proto_id);
233                 break;
234         }
235
236         return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
237                         port_nexus_ptr);
238 }
239
240 static struct se_node_acl *tcm_vhost_alloc_fabric_acl(
241         struct se_portal_group *se_tpg)
242 {
243         struct tcm_vhost_nacl *nacl;
244
245         nacl = kzalloc(sizeof(struct tcm_vhost_nacl), GFP_KERNEL);
246         if (!nacl) {
247                 pr_err("Unable to allocate struct tcm_vhost_nacl\n");
248                 return NULL;
249         }
250
251         return &nacl->se_node_acl;
252 }
253
254 static void tcm_vhost_release_fabric_acl(struct se_portal_group *se_tpg,
255         struct se_node_acl *se_nacl)
256 {
257         struct tcm_vhost_nacl *nacl = container_of(se_nacl,
258                         struct tcm_vhost_nacl, se_node_acl);
259         kfree(nacl);
260 }
261
262 static u32 tcm_vhost_tpg_get_inst_index(struct se_portal_group *se_tpg)
263 {
264         return 1;
265 }
266
267 static void tcm_vhost_release_cmd(struct se_cmd *se_cmd)
268 {
269         return;
270 }
271
272 static int tcm_vhost_shutdown_session(struct se_session *se_sess)
273 {
274         return 0;
275 }
276
277 static void tcm_vhost_close_session(struct se_session *se_sess)
278 {
279         return;
280 }
281
282 static u32 tcm_vhost_sess_get_index(struct se_session *se_sess)
283 {
284         return 0;
285 }
286
287 static int tcm_vhost_write_pending(struct se_cmd *se_cmd)
288 {
289         /* Go ahead and process the write immediately */
290         target_execute_cmd(se_cmd);
291         return 0;
292 }
293
294 static int tcm_vhost_write_pending_status(struct se_cmd *se_cmd)
295 {
296         return 0;
297 }
298
299 static void tcm_vhost_set_default_node_attrs(struct se_node_acl *nacl)
300 {
301         return;
302 }
303
304 static u32 tcm_vhost_get_task_tag(struct se_cmd *se_cmd)
305 {
306         return 0;
307 }
308
309 static int tcm_vhost_get_cmd_state(struct se_cmd *se_cmd)
310 {
311         return 0;
312 }
313
314 static void vhost_scsi_complete_cmd(struct tcm_vhost_cmd *tv_cmd)
315 {
316         struct vhost_scsi *vs = tv_cmd->tvc_vhost;
317
318         llist_add(&tv_cmd->tvc_completion_list, &vs->vs_completion_list);
319
320         vhost_work_queue(&vs->dev, &vs->vs_completion_work);
321 }
322
323 static int tcm_vhost_queue_data_in(struct se_cmd *se_cmd)
324 {
325         struct tcm_vhost_cmd *tv_cmd = container_of(se_cmd,
326                                 struct tcm_vhost_cmd, tvc_se_cmd);
327         vhost_scsi_complete_cmd(tv_cmd);
328         return 0;
329 }
330
331 static int tcm_vhost_queue_status(struct se_cmd *se_cmd)
332 {
333         struct tcm_vhost_cmd *tv_cmd = container_of(se_cmd,
334                                 struct tcm_vhost_cmd, tvc_se_cmd);
335         vhost_scsi_complete_cmd(tv_cmd);
336         return 0;
337 }
338
339 static int tcm_vhost_queue_tm_rsp(struct se_cmd *se_cmd)
340 {
341         return 0;
342 }
343
344 static void vhost_scsi_free_cmd(struct tcm_vhost_cmd *tv_cmd)
345 {
346         struct se_cmd *se_cmd = &tv_cmd->tvc_se_cmd;
347
348         /* TODO locking against target/backend threads? */
349         transport_generic_free_cmd(se_cmd, 1);
350
351         if (tv_cmd->tvc_sgl_count) {
352                 u32 i;
353                 for (i = 0; i < tv_cmd->tvc_sgl_count; i++)
354                         put_page(sg_page(&tv_cmd->tvc_sgl[i]));
355
356                 kfree(tv_cmd->tvc_sgl);
357         }
358
359         kfree(tv_cmd);
360 }
361
362 /* Fill in status and signal that we are done processing this command
363  *
364  * This is scheduled in the vhost work queue so we are called with the owner
365  * process mm and can access the vring.
366  */
367 static void vhost_scsi_complete_cmd_work(struct vhost_work *work)
368 {
369         struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
370                                         vs_completion_work);
371         DECLARE_BITMAP(signal, VHOST_SCSI_MAX_VQ);
372         struct virtio_scsi_cmd_resp v_rsp;
373         struct tcm_vhost_cmd *tv_cmd;
374         struct llist_node *llnode;
375         struct se_cmd *se_cmd;
376         int ret, vq;
377
378         bitmap_zero(signal, VHOST_SCSI_MAX_VQ);
379         llnode = llist_del_all(&vs->vs_completion_list);
380         while (llnode) {
381                 tv_cmd = llist_entry(llnode, struct tcm_vhost_cmd,
382                                      tvc_completion_list);
383                 llnode = llist_next(llnode);
384                 se_cmd = &tv_cmd->tvc_se_cmd;
385
386                 pr_debug("%s tv_cmd %p resid %u status %#02x\n", __func__,
387                         tv_cmd, se_cmd->residual_count, se_cmd->scsi_status);
388
389                 memset(&v_rsp, 0, sizeof(v_rsp));
390                 v_rsp.resid = se_cmd->residual_count;
391                 /* TODO is status_qualifier field needed? */
392                 v_rsp.status = se_cmd->scsi_status;
393                 v_rsp.sense_len = se_cmd->scsi_sense_length;
394                 memcpy(v_rsp.sense, tv_cmd->tvc_sense_buf,
395                        v_rsp.sense_len);
396                 ret = copy_to_user(tv_cmd->tvc_resp, &v_rsp, sizeof(v_rsp));
397                 if (likely(ret == 0)) {
398                         vhost_add_used(tv_cmd->tvc_vq, tv_cmd->tvc_vq_desc, 0);
399                         vq = tv_cmd->tvc_vq - vs->vqs;
400                         __set_bit(vq, signal);
401                 } else
402                         pr_err("Faulted on virtio_scsi_cmd_resp\n");
403
404                 vhost_scsi_free_cmd(tv_cmd);
405         }
406
407         vq = -1;
408         while ((vq = find_next_bit(signal, VHOST_SCSI_MAX_VQ, vq + 1))
409                 < VHOST_SCSI_MAX_VQ)
410                 vhost_signal(&vs->dev, &vs->vqs[vq]);
411 }
412
413 static struct tcm_vhost_cmd *vhost_scsi_allocate_cmd(
414         struct tcm_vhost_tpg *tv_tpg,
415         struct virtio_scsi_cmd_req *v_req,
416         u32 exp_data_len,
417         int data_direction)
418 {
419         struct tcm_vhost_cmd *tv_cmd;
420         struct tcm_vhost_nexus *tv_nexus;
421
422         tv_nexus = tv_tpg->tpg_nexus;
423         if (!tv_nexus) {
424                 pr_err("Unable to locate active struct tcm_vhost_nexus\n");
425                 return ERR_PTR(-EIO);
426         }
427
428         tv_cmd = kzalloc(sizeof(struct tcm_vhost_cmd), GFP_ATOMIC);
429         if (!tv_cmd) {
430                 pr_err("Unable to allocate struct tcm_vhost_cmd\n");
431                 return ERR_PTR(-ENOMEM);
432         }
433         tv_cmd->tvc_tag = v_req->tag;
434         tv_cmd->tvc_task_attr = v_req->task_attr;
435         tv_cmd->tvc_exp_data_len = exp_data_len;
436         tv_cmd->tvc_data_direction = data_direction;
437         tv_cmd->tvc_nexus = tv_nexus;
438
439         return tv_cmd;
440 }
441
442 /*
443  * Map a user memory range into a scatterlist
444  *
445  * Returns the number of scatterlist entries used or -errno on error.
446  */
447 static int vhost_scsi_map_to_sgl(struct scatterlist *sgl,
448         unsigned int sgl_count, struct iovec *iov, int write)
449 {
450         unsigned int npages = 0, pages_nr, offset, nbytes;
451         struct scatterlist *sg = sgl;
452         void __user *ptr = iov->iov_base;
453         size_t len = iov->iov_len;
454         struct page **pages;
455         int ret, i;
456
457         pages_nr = iov_num_pages(iov);
458         if (pages_nr > sgl_count)
459                 return -ENOBUFS;
460
461         pages = kmalloc(pages_nr * sizeof(struct page *), GFP_KERNEL);
462         if (!pages)
463                 return -ENOMEM;
464
465         ret = get_user_pages_fast((unsigned long)ptr, pages_nr, write, pages);
466         /* No pages were pinned */
467         if (ret < 0)
468                 goto out;
469         /* Less pages pinned than wanted */
470         if (ret != pages_nr) {
471                 for (i = 0; i < ret; i++)
472                         put_page(pages[i]);
473                 ret = -EFAULT;
474                 goto out;
475         }
476
477         while (len > 0) {
478                 offset = (uintptr_t)ptr & ~PAGE_MASK;
479                 nbytes = min_t(unsigned int, PAGE_SIZE - offset, len);
480                 sg_set_page(sg, pages[npages], nbytes, offset);
481                 ptr += nbytes;
482                 len -= nbytes;
483                 sg++;
484                 npages++;
485         }
486
487 out:
488         kfree(pages);
489         return ret;
490 }
491
492 static int vhost_scsi_map_iov_to_sgl(struct tcm_vhost_cmd *tv_cmd,
493         struct iovec *iov, unsigned int niov, int write)
494 {
495         int ret;
496         unsigned int i;
497         u32 sgl_count;
498         struct scatterlist *sg;
499
500         /*
501          * Find out how long sglist needs to be
502          */
503         sgl_count = 0;
504         for (i = 0; i < niov; i++)
505                 sgl_count += iov_num_pages(&iov[i]);
506
507         /* TODO overflow checking */
508
509         sg = kmalloc(sizeof(tv_cmd->tvc_sgl[0]) * sgl_count, GFP_ATOMIC);
510         if (!sg)
511                 return -ENOMEM;
512         pr_debug("%s sg %p sgl_count %u is_err %d\n", __func__,
513                sg, sgl_count, !sg);
514         sg_init_table(sg, sgl_count);
515
516         tv_cmd->tvc_sgl = sg;
517         tv_cmd->tvc_sgl_count = sgl_count;
518
519         pr_debug("Mapping %u iovecs for %u pages\n", niov, sgl_count);
520         for (i = 0; i < niov; i++) {
521                 ret = vhost_scsi_map_to_sgl(sg, sgl_count, &iov[i], write);
522                 if (ret < 0) {
523                         for (i = 0; i < tv_cmd->tvc_sgl_count; i++)
524                                 put_page(sg_page(&tv_cmd->tvc_sgl[i]));
525                         kfree(tv_cmd->tvc_sgl);
526                         tv_cmd->tvc_sgl = NULL;
527                         tv_cmd->tvc_sgl_count = 0;
528                         return ret;
529                 }
530
531                 sg += ret;
532                 sgl_count -= ret;
533         }
534         return 0;
535 }
536
537 static void tcm_vhost_submission_work(struct work_struct *work)
538 {
539         struct tcm_vhost_cmd *tv_cmd =
540                 container_of(work, struct tcm_vhost_cmd, work);
541         struct tcm_vhost_nexus *tv_nexus;
542         struct se_cmd *se_cmd = &tv_cmd->tvc_se_cmd;
543         struct scatterlist *sg_ptr, *sg_bidi_ptr = NULL;
544         int rc, sg_no_bidi = 0;
545
546         if (tv_cmd->tvc_sgl_count) {
547                 sg_ptr = tv_cmd->tvc_sgl;
548 /* FIXME: Fix BIDI operation in tcm_vhost_submission_work() */
549 #if 0
550                 if (se_cmd->se_cmd_flags & SCF_BIDI) {
551                         sg_bidi_ptr = NULL;
552                         sg_no_bidi = 0;
553                 }
554 #endif
555         } else {
556                 sg_ptr = NULL;
557         }
558         tv_nexus = tv_cmd->tvc_nexus;
559
560         rc = target_submit_cmd_map_sgls(se_cmd, tv_nexus->tvn_se_sess,
561                         tv_cmd->tvc_cdb, &tv_cmd->tvc_sense_buf[0],
562                         tv_cmd->tvc_lun, tv_cmd->tvc_exp_data_len,
563                         tv_cmd->tvc_task_attr, tv_cmd->tvc_data_direction,
564                         0, sg_ptr, tv_cmd->tvc_sgl_count,
565                         sg_bidi_ptr, sg_no_bidi);
566         if (rc < 0) {
567                 transport_send_check_condition_and_sense(se_cmd,
568                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
569                 transport_generic_free_cmd(se_cmd, 0);
570         }
571 }
572
573 static void vhost_scsi_handle_vq(struct vhost_scsi *vs,
574         struct vhost_virtqueue *vq)
575 {
576         struct virtio_scsi_cmd_req v_req;
577         struct tcm_vhost_tpg *tv_tpg;
578         struct tcm_vhost_cmd *tv_cmd;
579         u32 exp_data_len, data_first, data_num, data_direction;
580         unsigned out, in, i;
581         int head, ret;
582         u8 target;
583
584         /* Must use ioctl VHOST_SCSI_SET_ENDPOINT */
585         if (unlikely(!vs->vs_endpoint))
586                 return;
587
588         mutex_lock(&vq->mutex);
589         vhost_disable_notify(&vs->dev, vq);
590
591         for (;;) {
592                 head = vhost_get_vq_desc(&vs->dev, vq, vq->iov,
593                                         ARRAY_SIZE(vq->iov), &out, &in,
594                                         NULL, NULL);
595                 pr_debug("vhost_get_vq_desc: head: %d, out: %u in: %u\n",
596                                         head, out, in);
597                 /* On error, stop handling until the next kick. */
598                 if (unlikely(head < 0))
599                         break;
600                 /* Nothing new?  Wait for eventfd to tell us they refilled. */
601                 if (head == vq->num) {
602                         if (unlikely(vhost_enable_notify(&vs->dev, vq))) {
603                                 vhost_disable_notify(&vs->dev, vq);
604                                 continue;
605                         }
606                         break;
607                 }
608
609 /* FIXME: BIDI operation */
610                 if (out == 1 && in == 1) {
611                         data_direction = DMA_NONE;
612                         data_first = 0;
613                         data_num = 0;
614                 } else if (out == 1 && in > 1) {
615                         data_direction = DMA_FROM_DEVICE;
616                         data_first = out + 1;
617                         data_num = in - 1;
618                 } else if (out > 1 && in == 1) {
619                         data_direction = DMA_TO_DEVICE;
620                         data_first = 1;
621                         data_num = out - 1;
622                 } else {
623                         vq_err(vq, "Invalid buffer layout out: %u in: %u\n",
624                                         out, in);
625                         break;
626                 }
627
628                 /*
629                  * Check for a sane resp buffer so we can report errors to
630                  * the guest.
631                  */
632                 if (unlikely(vq->iov[out].iov_len !=
633                                         sizeof(struct virtio_scsi_cmd_resp))) {
634                         vq_err(vq, "Expecting virtio_scsi_cmd_resp, got %zu"
635                                 " bytes\n", vq->iov[out].iov_len);
636                         break;
637                 }
638
639                 if (unlikely(vq->iov[0].iov_len != sizeof(v_req))) {
640                         vq_err(vq, "Expecting virtio_scsi_cmd_req, got %zu"
641                                 " bytes\n", vq->iov[0].iov_len);
642                         break;
643                 }
644                 pr_debug("Calling __copy_from_user: vq->iov[0].iov_base: %p,"
645                         " len: %zu\n", vq->iov[0].iov_base, sizeof(v_req));
646                 ret = __copy_from_user(&v_req, vq->iov[0].iov_base,
647                                 sizeof(v_req));
648                 if (unlikely(ret)) {
649                         vq_err(vq, "Faulted on virtio_scsi_cmd_req\n");
650                         break;
651                 }
652
653                 /* Extract the tpgt */
654                 target = v_req.lun[1];
655                 tv_tpg = vs->vs_tpg[target];
656
657                 /* Target does not exist, fail the request */
658                 if (unlikely(!tv_tpg)) {
659                         struct virtio_scsi_cmd_resp __user *resp;
660                         struct virtio_scsi_cmd_resp rsp;
661
662                         memset(&rsp, 0, sizeof(rsp));
663                         rsp.response = VIRTIO_SCSI_S_BAD_TARGET;
664                         resp = vq->iov[out].iov_base;
665                         ret = __copy_to_user(resp, &rsp, sizeof(rsp));
666                         if (!ret)
667                                 vhost_add_used_and_signal(&vs->dev,
668                                                           vq, head, 0);
669                         else
670                                 pr_err("Faulted on virtio_scsi_cmd_resp\n");
671
672                         continue;
673                 }
674
675                 exp_data_len = 0;
676                 for (i = 0; i < data_num; i++)
677                         exp_data_len += vq->iov[data_first + i].iov_len;
678
679                 tv_cmd = vhost_scsi_allocate_cmd(tv_tpg, &v_req,
680                                         exp_data_len, data_direction);
681                 if (IS_ERR(tv_cmd)) {
682                         vq_err(vq, "vhost_scsi_allocate_cmd failed %ld\n",
683                                         PTR_ERR(tv_cmd));
684                         break;
685                 }
686                 pr_debug("Allocated tv_cmd: %p exp_data_len: %d, data_direction"
687                         ": %d\n", tv_cmd, exp_data_len, data_direction);
688
689                 tv_cmd->tvc_vhost = vs;
690                 tv_cmd->tvc_vq = vq;
691
692                 if (unlikely(vq->iov[out].iov_len !=
693                                 sizeof(struct virtio_scsi_cmd_resp))) {
694                         vq_err(vq, "Expecting virtio_scsi_cmd_resp, got %zu"
695                                 " bytes, out: %d, in: %d\n",
696                                 vq->iov[out].iov_len, out, in);
697                         break;
698                 }
699
700                 tv_cmd->tvc_resp = vq->iov[out].iov_base;
701
702                 /*
703                  * Copy in the recieved CDB descriptor into tv_cmd->tvc_cdb
704                  * that will be used by tcm_vhost_new_cmd_map() and down into
705                  * target_setup_cmd_from_cdb()
706                  */
707                 memcpy(tv_cmd->tvc_cdb, v_req.cdb, TCM_VHOST_MAX_CDB_SIZE);
708                 /*
709                  * Check that the recieved CDB size does not exceeded our
710                  * hardcoded max for tcm_vhost
711                  */
712                 /* TODO what if cdb was too small for varlen cdb header? */
713                 if (unlikely(scsi_command_size(tv_cmd->tvc_cdb) >
714                                         TCM_VHOST_MAX_CDB_SIZE)) {
715                         vq_err(vq, "Received SCSI CDB with command_size: %d that"
716                                 " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
717                                 scsi_command_size(tv_cmd->tvc_cdb),
718                                 TCM_VHOST_MAX_CDB_SIZE);
719                         break; /* TODO */
720                 }
721                 tv_cmd->tvc_lun = ((v_req.lun[2] << 8) | v_req.lun[3]) & 0x3FFF;
722
723                 pr_debug("vhost_scsi got command opcode: %#02x, lun: %d\n",
724                         tv_cmd->tvc_cdb[0], tv_cmd->tvc_lun);
725
726                 if (data_direction != DMA_NONE) {
727                         ret = vhost_scsi_map_iov_to_sgl(tv_cmd,
728                                         &vq->iov[data_first], data_num,
729                                         data_direction == DMA_TO_DEVICE);
730                         if (unlikely(ret)) {
731                                 vq_err(vq, "Failed to map iov to sgl\n");
732                                 break; /* TODO */
733                         }
734                 }
735
736                 /*
737                  * Save the descriptor from vhost_get_vq_desc() to be used to
738                  * complete the virtio-scsi request in TCM callback context via
739                  * tcm_vhost_queue_data_in() and tcm_vhost_queue_status()
740                  */
741                 tv_cmd->tvc_vq_desc = head;
742                 /*
743                  * Dispatch tv_cmd descriptor for cmwq execution in process
744                  * context provided by tcm_vhost_workqueue.  This also ensures
745                  * tv_cmd is executed on the same kworker CPU as this vhost
746                  * thread to gain positive L2 cache locality effects..
747                  */
748                 INIT_WORK(&tv_cmd->work, tcm_vhost_submission_work);
749                 queue_work(tcm_vhost_workqueue, &tv_cmd->work);
750         }
751
752         mutex_unlock(&vq->mutex);
753 }
754
755 static void vhost_scsi_ctl_handle_kick(struct vhost_work *work)
756 {
757         pr_debug("%s: The handling func for control queue.\n", __func__);
758 }
759
760 static void vhost_scsi_evt_handle_kick(struct vhost_work *work)
761 {
762         pr_debug("%s: The handling func for event queue.\n", __func__);
763 }
764
765 static void vhost_scsi_handle_kick(struct vhost_work *work)
766 {
767         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
768                                                 poll.work);
769         struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
770
771         vhost_scsi_handle_vq(vs, vq);
772 }
773
774 /*
775  * Called from vhost_scsi_ioctl() context to walk the list of available
776  * tcm_vhost_tpg with an active struct tcm_vhost_nexus
777  */
778 static int vhost_scsi_set_endpoint(
779         struct vhost_scsi *vs,
780         struct vhost_scsi_target *t)
781 {
782         struct tcm_vhost_tport *tv_tport;
783         struct tcm_vhost_tpg *tv_tpg;
784         bool match = false;
785         int index, ret;
786
787         mutex_lock(&vs->dev.mutex);
788         /* Verify that ring has been setup correctly. */
789         for (index = 0; index < vs->dev.nvqs; ++index) {
790                 /* Verify that ring has been setup correctly. */
791                 if (!vhost_vq_access_ok(&vs->vqs[index])) {
792                         mutex_unlock(&vs->dev.mutex);
793                         return -EFAULT;
794                 }
795         }
796
797         mutex_lock(&tcm_vhost_mutex);
798         list_for_each_entry(tv_tpg, &tcm_vhost_list, tv_tpg_list) {
799                 mutex_lock(&tv_tpg->tv_tpg_mutex);
800                 if (!tv_tpg->tpg_nexus) {
801                         mutex_unlock(&tv_tpg->tv_tpg_mutex);
802                         continue;
803                 }
804                 if (tv_tpg->tv_tpg_vhost_count != 0) {
805                         mutex_unlock(&tv_tpg->tv_tpg_mutex);
806                         continue;
807                 }
808                 tv_tport = tv_tpg->tport;
809
810                 if (!strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
811                         if (vs->vs_tpg[tv_tpg->tport_tpgt]) {
812                                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
813                                 mutex_unlock(&tcm_vhost_mutex);
814                                 mutex_unlock(&vs->dev.mutex);
815                                 return -EEXIST;
816                         }
817                         tv_tpg->tv_tpg_vhost_count++;
818                         vs->vs_tpg[tv_tpg->tport_tpgt] = tv_tpg;
819                         smp_mb__after_atomic_inc();
820                         match = true;
821                 }
822                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
823         }
824         mutex_unlock(&tcm_vhost_mutex);
825
826         if (match) {
827                 memcpy(vs->vs_vhost_wwpn, t->vhost_wwpn,
828                        sizeof(vs->vs_vhost_wwpn));
829                 vs->vs_endpoint = true;
830                 ret = 0;
831         } else {
832                 ret = -EEXIST;
833         }
834
835         mutex_unlock(&vs->dev.mutex);
836         return ret;
837 }
838
839 static int vhost_scsi_clear_endpoint(
840         struct vhost_scsi *vs,
841         struct vhost_scsi_target *t)
842 {
843         struct tcm_vhost_tport *tv_tport;
844         struct tcm_vhost_tpg *tv_tpg;
845         int index, ret, i;
846         u8 target;
847
848         mutex_lock(&vs->dev.mutex);
849         /* Verify that ring has been setup correctly. */
850         for (index = 0; index < vs->dev.nvqs; ++index) {
851                 if (!vhost_vq_access_ok(&vs->vqs[index])) {
852                         ret = -EFAULT;
853                         goto err_dev;
854                 }
855         }
856         for (i = 0; i < VHOST_SCSI_MAX_TARGET; i++) {
857                 target = i;
858
859                 tv_tpg = vs->vs_tpg[target];
860                 if (!tv_tpg)
861                         continue;
862
863                 mutex_lock(&tv_tpg->tv_tpg_mutex);
864                 tv_tport = tv_tpg->tport;
865                 if (!tv_tport) {
866                         ret = -ENODEV;
867                         goto err_tpg;
868                 }
869
870                 if (strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
871                         pr_warn("tv_tport->tport_name: %s, tv_tpg->tport_tpgt: %hu"
872                                 " does not match t->vhost_wwpn: %s, t->vhost_tpgt: %hu\n",
873                                 tv_tport->tport_name, tv_tpg->tport_tpgt,
874                                 t->vhost_wwpn, t->vhost_tpgt);
875                         ret = -EINVAL;
876                         goto err_tpg;
877                 }
878                 tv_tpg->tv_tpg_vhost_count--;
879                 vs->vs_tpg[target] = NULL;
880                 vs->vs_endpoint = false;
881                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
882         }
883         mutex_unlock(&vs->dev.mutex);
884         return 0;
885
886 err_tpg:
887         mutex_unlock(&tv_tpg->tv_tpg_mutex);
888 err_dev:
889         mutex_unlock(&vs->dev.mutex);
890         return ret;
891 }
892
893 static int vhost_scsi_open(struct inode *inode, struct file *f)
894 {
895         struct vhost_scsi *s;
896         int r, i;
897
898         s = kzalloc(sizeof(*s), GFP_KERNEL);
899         if (!s)
900                 return -ENOMEM;
901
902         vhost_work_init(&s->vs_completion_work, vhost_scsi_complete_cmd_work);
903
904         s->vqs[VHOST_SCSI_VQ_CTL].handle_kick = vhost_scsi_ctl_handle_kick;
905         s->vqs[VHOST_SCSI_VQ_EVT].handle_kick = vhost_scsi_evt_handle_kick;
906         for (i = VHOST_SCSI_VQ_IO; i < VHOST_SCSI_MAX_VQ; i++)
907                 s->vqs[i].handle_kick = vhost_scsi_handle_kick;
908         r = vhost_dev_init(&s->dev, s->vqs, VHOST_SCSI_MAX_VQ);
909         if (r < 0) {
910                 kfree(s);
911                 return r;
912         }
913
914         f->private_data = s;
915         return 0;
916 }
917
918 static int vhost_scsi_release(struct inode *inode, struct file *f)
919 {
920         struct vhost_scsi *s = f->private_data;
921         struct vhost_scsi_target t;
922
923         mutex_lock(&s->dev.mutex);
924         memcpy(t.vhost_wwpn, s->vs_vhost_wwpn, sizeof(t.vhost_wwpn));
925         mutex_unlock(&s->dev.mutex);
926         vhost_scsi_clear_endpoint(s, &t);
927         vhost_dev_stop(&s->dev);
928         vhost_dev_cleanup(&s->dev, false);
929         kfree(s);
930         return 0;
931 }
932
933 static void vhost_scsi_flush_vq(struct vhost_scsi *vs, int index)
934 {
935         vhost_poll_flush(&vs->dev.vqs[index].poll);
936 }
937
938 static void vhost_scsi_flush(struct vhost_scsi *vs)
939 {
940         int i;
941
942         for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
943                 vhost_scsi_flush_vq(vs, i);
944         vhost_work_flush(&vs->dev, &vs->vs_completion_work);
945 }
946
947 static int vhost_scsi_set_features(struct vhost_scsi *vs, u64 features)
948 {
949         if (features & ~VHOST_FEATURES)
950                 return -EOPNOTSUPP;
951
952         mutex_lock(&vs->dev.mutex);
953         if ((features & (1 << VHOST_F_LOG_ALL)) &&
954             !vhost_log_access_ok(&vs->dev)) {
955                 mutex_unlock(&vs->dev.mutex);
956                 return -EFAULT;
957         }
958         vs->dev.acked_features = features;
959         smp_wmb();
960         vhost_scsi_flush(vs);
961         mutex_unlock(&vs->dev.mutex);
962         return 0;
963 }
964
965 static long vhost_scsi_ioctl(struct file *f, unsigned int ioctl,
966                                 unsigned long arg)
967 {
968         struct vhost_scsi *vs = f->private_data;
969         struct vhost_scsi_target backend;
970         void __user *argp = (void __user *)arg;
971         u64 __user *featurep = argp;
972         u64 features;
973         int r, abi_version = VHOST_SCSI_ABI_VERSION;
974
975         switch (ioctl) {
976         case VHOST_SCSI_SET_ENDPOINT:
977                 if (copy_from_user(&backend, argp, sizeof backend))
978                         return -EFAULT;
979                 if (backend.reserved != 0)
980                         return -EOPNOTSUPP;
981
982                 return vhost_scsi_set_endpoint(vs, &backend);
983         case VHOST_SCSI_CLEAR_ENDPOINT:
984                 if (copy_from_user(&backend, argp, sizeof backend))
985                         return -EFAULT;
986                 if (backend.reserved != 0)
987                         return -EOPNOTSUPP;
988
989                 return vhost_scsi_clear_endpoint(vs, &backend);
990         case VHOST_SCSI_GET_ABI_VERSION:
991                 if (copy_to_user(argp, &abi_version, sizeof abi_version))
992                         return -EFAULT;
993                 return 0;
994         case VHOST_GET_FEATURES:
995                 features = VHOST_FEATURES;
996                 if (copy_to_user(featurep, &features, sizeof features))
997                         return -EFAULT;
998                 return 0;
999         case VHOST_SET_FEATURES:
1000                 if (copy_from_user(&features, featurep, sizeof features))
1001                         return -EFAULT;
1002                 return vhost_scsi_set_features(vs, features);
1003         default:
1004                 mutex_lock(&vs->dev.mutex);
1005                 r = vhost_dev_ioctl(&vs->dev, ioctl, argp);
1006                 /* TODO: flush backend after dev ioctl. */
1007                 if (r == -ENOIOCTLCMD)
1008                         r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
1009                 mutex_unlock(&vs->dev.mutex);
1010                 return r;
1011         }
1012 }
1013
1014 #ifdef CONFIG_COMPAT
1015 static long vhost_scsi_compat_ioctl(struct file *f, unsigned int ioctl,
1016                                 unsigned long arg)
1017 {
1018         return vhost_scsi_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1019 }
1020 #endif
1021
1022 static const struct file_operations vhost_scsi_fops = {
1023         .owner          = THIS_MODULE,
1024         .release        = vhost_scsi_release,
1025         .unlocked_ioctl = vhost_scsi_ioctl,
1026 #ifdef CONFIG_COMPAT
1027         .compat_ioctl   = vhost_scsi_compat_ioctl,
1028 #endif
1029         .open           = vhost_scsi_open,
1030         .llseek         = noop_llseek,
1031 };
1032
1033 static struct miscdevice vhost_scsi_misc = {
1034         MISC_DYNAMIC_MINOR,
1035         "vhost-scsi",
1036         &vhost_scsi_fops,
1037 };
1038
1039 static int __init vhost_scsi_register(void)
1040 {
1041         return misc_register(&vhost_scsi_misc);
1042 }
1043
1044 static int vhost_scsi_deregister(void)
1045 {
1046         return misc_deregister(&vhost_scsi_misc);
1047 }
1048
1049 static char *tcm_vhost_dump_proto_id(struct tcm_vhost_tport *tport)
1050 {
1051         switch (tport->tport_proto_id) {
1052         case SCSI_PROTOCOL_SAS:
1053                 return "SAS";
1054         case SCSI_PROTOCOL_FCP:
1055                 return "FCP";
1056         case SCSI_PROTOCOL_ISCSI:
1057                 return "iSCSI";
1058         default:
1059                 break;
1060         }
1061
1062         return "Unknown";
1063 }
1064
1065 static int tcm_vhost_port_link(struct se_portal_group *se_tpg,
1066         struct se_lun *lun)
1067 {
1068         struct tcm_vhost_tpg *tv_tpg = container_of(se_tpg,
1069                                 struct tcm_vhost_tpg, se_tpg);
1070
1071         mutex_lock(&tv_tpg->tv_tpg_mutex);
1072         tv_tpg->tv_tpg_port_count++;
1073         mutex_unlock(&tv_tpg->tv_tpg_mutex);
1074
1075         return 0;
1076 }
1077
1078 static void tcm_vhost_port_unlink(struct se_portal_group *se_tpg,
1079         struct se_lun *se_lun)
1080 {
1081         struct tcm_vhost_tpg *tv_tpg = container_of(se_tpg,
1082                                 struct tcm_vhost_tpg, se_tpg);
1083
1084         mutex_lock(&tv_tpg->tv_tpg_mutex);
1085         tv_tpg->tv_tpg_port_count--;
1086         mutex_unlock(&tv_tpg->tv_tpg_mutex);
1087 }
1088
1089 static struct se_node_acl *tcm_vhost_make_nodeacl(
1090         struct se_portal_group *se_tpg,
1091         struct config_group *group,
1092         const char *name)
1093 {
1094         struct se_node_acl *se_nacl, *se_nacl_new;
1095         struct tcm_vhost_nacl *nacl;
1096         u64 wwpn = 0;
1097         u32 nexus_depth;
1098
1099         /* tcm_vhost_parse_wwn(name, &wwpn, 1) < 0)
1100                 return ERR_PTR(-EINVAL); */
1101         se_nacl_new = tcm_vhost_alloc_fabric_acl(se_tpg);
1102         if (!se_nacl_new)
1103                 return ERR_PTR(-ENOMEM);
1104
1105         nexus_depth = 1;
1106         /*
1107          * se_nacl_new may be released by core_tpg_add_initiator_node_acl()
1108          * when converting a NodeACL from demo mode -> explict
1109          */
1110         se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,
1111                                 name, nexus_depth);
1112         if (IS_ERR(se_nacl)) {
1113                 tcm_vhost_release_fabric_acl(se_tpg, se_nacl_new);
1114                 return se_nacl;
1115         }
1116         /*
1117          * Locate our struct tcm_vhost_nacl and set the FC Nport WWPN
1118          */
1119         nacl = container_of(se_nacl, struct tcm_vhost_nacl, se_node_acl);
1120         nacl->iport_wwpn = wwpn;
1121
1122         return se_nacl;
1123 }
1124
1125 static void tcm_vhost_drop_nodeacl(struct se_node_acl *se_acl)
1126 {
1127         struct tcm_vhost_nacl *nacl = container_of(se_acl,
1128                                 struct tcm_vhost_nacl, se_node_acl);
1129         core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);
1130         kfree(nacl);
1131 }
1132
1133 static int tcm_vhost_make_nexus(struct tcm_vhost_tpg *tv_tpg,
1134         const char *name)
1135 {
1136         struct se_portal_group *se_tpg;
1137         struct tcm_vhost_nexus *tv_nexus;
1138
1139         mutex_lock(&tv_tpg->tv_tpg_mutex);
1140         if (tv_tpg->tpg_nexus) {
1141                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
1142                 pr_debug("tv_tpg->tpg_nexus already exists\n");
1143                 return -EEXIST;
1144         }
1145         se_tpg = &tv_tpg->se_tpg;
1146
1147         tv_nexus = kzalloc(sizeof(struct tcm_vhost_nexus), GFP_KERNEL);
1148         if (!tv_nexus) {
1149                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
1150                 pr_err("Unable to allocate struct tcm_vhost_nexus\n");
1151                 return -ENOMEM;
1152         }
1153         /*
1154          *  Initialize the struct se_session pointer
1155          */
1156         tv_nexus->tvn_se_sess = transport_init_session();
1157         if (IS_ERR(tv_nexus->tvn_se_sess)) {
1158                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
1159                 kfree(tv_nexus);
1160                 return -ENOMEM;
1161         }
1162         /*
1163          * Since we are running in 'demo mode' this call with generate a
1164          * struct se_node_acl for the tcm_vhost struct se_portal_group with
1165          * the SCSI Initiator port name of the passed configfs group 'name'.
1166          */
1167         tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
1168                                 se_tpg, (unsigned char *)name);
1169         if (!tv_nexus->tvn_se_sess->se_node_acl) {
1170                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
1171                 pr_debug("core_tpg_check_initiator_node_acl() failed"
1172                                 " for %s\n", name);
1173                 transport_free_session(tv_nexus->tvn_se_sess);
1174                 kfree(tv_nexus);
1175                 return -ENOMEM;
1176         }
1177         /*
1178          * Now register the TCM vhost virtual I_T Nexus as active with the
1179          * call to __transport_register_session()
1180          */
1181         __transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
1182                         tv_nexus->tvn_se_sess, tv_nexus);
1183         tv_tpg->tpg_nexus = tv_nexus;
1184
1185         mutex_unlock(&tv_tpg->tv_tpg_mutex);
1186         return 0;
1187 }
1188
1189 static int tcm_vhost_drop_nexus(struct tcm_vhost_tpg *tpg)
1190 {
1191         struct se_session *se_sess;
1192         struct tcm_vhost_nexus *tv_nexus;
1193
1194         mutex_lock(&tpg->tv_tpg_mutex);
1195         tv_nexus = tpg->tpg_nexus;
1196         if (!tv_nexus) {
1197                 mutex_unlock(&tpg->tv_tpg_mutex);
1198                 return -ENODEV;
1199         }
1200
1201         se_sess = tv_nexus->tvn_se_sess;
1202         if (!se_sess) {
1203                 mutex_unlock(&tpg->tv_tpg_mutex);
1204                 return -ENODEV;
1205         }
1206
1207         if (tpg->tv_tpg_port_count != 0) {
1208                 mutex_unlock(&tpg->tv_tpg_mutex);
1209                 pr_err("Unable to remove TCM_vhost I_T Nexus with"
1210                         " active TPG port count: %d\n",
1211                         tpg->tv_tpg_port_count);
1212                 return -EBUSY;
1213         }
1214
1215         if (tpg->tv_tpg_vhost_count != 0) {
1216                 mutex_unlock(&tpg->tv_tpg_mutex);
1217                 pr_err("Unable to remove TCM_vhost I_T Nexus with"
1218                         " active TPG vhost count: %d\n",
1219                         tpg->tv_tpg_vhost_count);
1220                 return -EBUSY;
1221         }
1222
1223         pr_debug("TCM_vhost_ConfigFS: Removing I_T Nexus to emulated"
1224                 " %s Initiator Port: %s\n", tcm_vhost_dump_proto_id(tpg->tport),
1225                 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1226         /*
1227          * Release the SCSI I_T Nexus to the emulated vhost Target Port
1228          */
1229         transport_deregister_session(tv_nexus->tvn_se_sess);
1230         tpg->tpg_nexus = NULL;
1231         mutex_unlock(&tpg->tv_tpg_mutex);
1232
1233         kfree(tv_nexus);
1234         return 0;
1235 }
1236
1237 static ssize_t tcm_vhost_tpg_show_nexus(struct se_portal_group *se_tpg,
1238         char *page)
1239 {
1240         struct tcm_vhost_tpg *tv_tpg = container_of(se_tpg,
1241                                 struct tcm_vhost_tpg, se_tpg);
1242         struct tcm_vhost_nexus *tv_nexus;
1243         ssize_t ret;
1244
1245         mutex_lock(&tv_tpg->tv_tpg_mutex);
1246         tv_nexus = tv_tpg->tpg_nexus;
1247         if (!tv_nexus) {
1248                 mutex_unlock(&tv_tpg->tv_tpg_mutex);
1249                 return -ENODEV;
1250         }
1251         ret = snprintf(page, PAGE_SIZE, "%s\n",
1252                         tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1253         mutex_unlock(&tv_tpg->tv_tpg_mutex);
1254
1255         return ret;
1256 }
1257
1258 static ssize_t tcm_vhost_tpg_store_nexus(struct se_portal_group *se_tpg,
1259         const char *page,
1260         size_t count)
1261 {
1262         struct tcm_vhost_tpg *tv_tpg = container_of(se_tpg,
1263                                 struct tcm_vhost_tpg, se_tpg);
1264         struct tcm_vhost_tport *tport_wwn = tv_tpg->tport;
1265         unsigned char i_port[TCM_VHOST_NAMELEN], *ptr, *port_ptr;
1266         int ret;
1267         /*
1268          * Shutdown the active I_T nexus if 'NULL' is passed..
1269          */
1270         if (!strncmp(page, "NULL", 4)) {
1271                 ret = tcm_vhost_drop_nexus(tv_tpg);
1272                 return (!ret) ? count : ret;
1273         }
1274         /*
1275          * Otherwise make sure the passed virtual Initiator port WWN matches
1276          * the fabric protocol_id set in tcm_vhost_make_tport(), and call
1277          * tcm_vhost_make_nexus().
1278          */
1279         if (strlen(page) >= TCM_VHOST_NAMELEN) {
1280                 pr_err("Emulated NAA Sas Address: %s, exceeds"
1281                                 " max: %d\n", page, TCM_VHOST_NAMELEN);
1282                 return -EINVAL;
1283         }
1284         snprintf(&i_port[0], TCM_VHOST_NAMELEN, "%s", page);
1285
1286         ptr = strstr(i_port, "naa.");
1287         if (ptr) {
1288                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
1289                         pr_err("Passed SAS Initiator Port %s does not"
1290                                 " match target port protoid: %s\n", i_port,
1291                                 tcm_vhost_dump_proto_id(tport_wwn));
1292                         return -EINVAL;
1293                 }
1294                 port_ptr = &i_port[0];
1295                 goto check_newline;
1296         }
1297         ptr = strstr(i_port, "fc.");
1298         if (ptr) {
1299                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
1300                         pr_err("Passed FCP Initiator Port %s does not"
1301                                 " match target port protoid: %s\n", i_port,
1302                                 tcm_vhost_dump_proto_id(tport_wwn));
1303                         return -EINVAL;
1304                 }
1305                 port_ptr = &i_port[3]; /* Skip over "fc." */
1306                 goto check_newline;
1307         }
1308         ptr = strstr(i_port, "iqn.");
1309         if (ptr) {
1310                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
1311                         pr_err("Passed iSCSI Initiator Port %s does not"
1312                                 " match target port protoid: %s\n", i_port,
1313                                 tcm_vhost_dump_proto_id(tport_wwn));
1314                         return -EINVAL;
1315                 }
1316                 port_ptr = &i_port[0];
1317                 goto check_newline;
1318         }
1319         pr_err("Unable to locate prefix for emulated Initiator Port:"
1320                         " %s\n", i_port);
1321         return -EINVAL;
1322         /*
1323          * Clear any trailing newline for the NAA WWN
1324          */
1325 check_newline:
1326         if (i_port[strlen(i_port)-1] == '\n')
1327                 i_port[strlen(i_port)-1] = '\0';
1328
1329         ret = tcm_vhost_make_nexus(tv_tpg, port_ptr);
1330         if (ret < 0)
1331                 return ret;
1332
1333         return count;
1334 }
1335
1336 TF_TPG_BASE_ATTR(tcm_vhost, nexus, S_IRUGO | S_IWUSR);
1337
1338 static struct configfs_attribute *tcm_vhost_tpg_attrs[] = {
1339         &tcm_vhost_tpg_nexus.attr,
1340         NULL,
1341 };
1342
1343 static struct se_portal_group *tcm_vhost_make_tpg(struct se_wwn *wwn,
1344         struct config_group *group,
1345         const char *name)
1346 {
1347         struct tcm_vhost_tport *tport = container_of(wwn,
1348                         struct tcm_vhost_tport, tport_wwn);
1349
1350         struct tcm_vhost_tpg *tpg;
1351         unsigned long tpgt;
1352         int ret;
1353
1354         if (strstr(name, "tpgt_") != name)
1355                 return ERR_PTR(-EINVAL);
1356         if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
1357                 return ERR_PTR(-EINVAL);
1358
1359         tpg = kzalloc(sizeof(struct tcm_vhost_tpg), GFP_KERNEL);
1360         if (!tpg) {
1361                 pr_err("Unable to allocate struct tcm_vhost_tpg");
1362                 return ERR_PTR(-ENOMEM);
1363         }
1364         mutex_init(&tpg->tv_tpg_mutex);
1365         INIT_LIST_HEAD(&tpg->tv_tpg_list);
1366         tpg->tport = tport;
1367         tpg->tport_tpgt = tpgt;
1368
1369         ret = core_tpg_register(&tcm_vhost_fabric_configfs->tf_ops, wwn,
1370                                 &tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
1371         if (ret < 0) {
1372                 kfree(tpg);
1373                 return NULL;
1374         }
1375         mutex_lock(&tcm_vhost_mutex);
1376         list_add_tail(&tpg->tv_tpg_list, &tcm_vhost_list);
1377         mutex_unlock(&tcm_vhost_mutex);
1378
1379         return &tpg->se_tpg;
1380 }
1381
1382 static void tcm_vhost_drop_tpg(struct se_portal_group *se_tpg)
1383 {
1384         struct tcm_vhost_tpg *tpg = container_of(se_tpg,
1385                                 struct tcm_vhost_tpg, se_tpg);
1386
1387         mutex_lock(&tcm_vhost_mutex);
1388         list_del(&tpg->tv_tpg_list);
1389         mutex_unlock(&tcm_vhost_mutex);
1390         /*
1391          * Release the virtual I_T Nexus for this vhost TPG
1392          */
1393         tcm_vhost_drop_nexus(tpg);
1394         /*
1395          * Deregister the se_tpg from TCM..
1396          */
1397         core_tpg_deregister(se_tpg);
1398         kfree(tpg);
1399 }
1400
1401 static struct se_wwn *tcm_vhost_make_tport(struct target_fabric_configfs *tf,
1402         struct config_group *group,
1403         const char *name)
1404 {
1405         struct tcm_vhost_tport *tport;
1406         char *ptr;
1407         u64 wwpn = 0;
1408         int off = 0;
1409
1410         /* if (tcm_vhost_parse_wwn(name, &wwpn, 1) < 0)
1411                 return ERR_PTR(-EINVAL); */
1412
1413         tport = kzalloc(sizeof(struct tcm_vhost_tport), GFP_KERNEL);
1414         if (!tport) {
1415                 pr_err("Unable to allocate struct tcm_vhost_tport");
1416                 return ERR_PTR(-ENOMEM);
1417         }
1418         tport->tport_wwpn = wwpn;
1419         /*
1420          * Determine the emulated Protocol Identifier and Target Port Name
1421          * based on the incoming configfs directory name.
1422          */
1423         ptr = strstr(name, "naa.");
1424         if (ptr) {
1425                 tport->tport_proto_id = SCSI_PROTOCOL_SAS;
1426                 goto check_len;
1427         }
1428         ptr = strstr(name, "fc.");
1429         if (ptr) {
1430                 tport->tport_proto_id = SCSI_PROTOCOL_FCP;
1431                 off = 3; /* Skip over "fc." */
1432                 goto check_len;
1433         }
1434         ptr = strstr(name, "iqn.");
1435         if (ptr) {
1436                 tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
1437                 goto check_len;
1438         }
1439
1440         pr_err("Unable to locate prefix for emulated Target Port:"
1441                         " %s\n", name);
1442         kfree(tport);
1443         return ERR_PTR(-EINVAL);
1444
1445 check_len:
1446         if (strlen(name) >= TCM_VHOST_NAMELEN) {
1447                 pr_err("Emulated %s Address: %s, exceeds"
1448                         " max: %d\n", name, tcm_vhost_dump_proto_id(tport),
1449                         TCM_VHOST_NAMELEN);
1450                 kfree(tport);
1451                 return ERR_PTR(-EINVAL);
1452         }
1453         snprintf(&tport->tport_name[0], TCM_VHOST_NAMELEN, "%s", &name[off]);
1454
1455         pr_debug("TCM_VHost_ConfigFS: Allocated emulated Target"
1456                 " %s Address: %s\n", tcm_vhost_dump_proto_id(tport), name);
1457
1458         return &tport->tport_wwn;
1459 }
1460
1461 static void tcm_vhost_drop_tport(struct se_wwn *wwn)
1462 {
1463         struct tcm_vhost_tport *tport = container_of(wwn,
1464                                 struct tcm_vhost_tport, tport_wwn);
1465
1466         pr_debug("TCM_VHost_ConfigFS: Deallocating emulated Target"
1467                 " %s Address: %s\n", tcm_vhost_dump_proto_id(tport),
1468                 tport->tport_name);
1469
1470         kfree(tport);
1471 }
1472
1473 static ssize_t tcm_vhost_wwn_show_attr_version(
1474         struct target_fabric_configfs *tf,
1475         char *page)
1476 {
1477         return sprintf(page, "TCM_VHOST fabric module %s on %s/%s"
1478                 "on "UTS_RELEASE"\n", TCM_VHOST_VERSION, utsname()->sysname,
1479                 utsname()->machine);
1480 }
1481
1482 TF_WWN_ATTR_RO(tcm_vhost, version);
1483
1484 static struct configfs_attribute *tcm_vhost_wwn_attrs[] = {
1485         &tcm_vhost_wwn_version.attr,
1486         NULL,
1487 };
1488
1489 static struct target_core_fabric_ops tcm_vhost_ops = {
1490         .get_fabric_name                = tcm_vhost_get_fabric_name,
1491         .get_fabric_proto_ident         = tcm_vhost_get_fabric_proto_ident,
1492         .tpg_get_wwn                    = tcm_vhost_get_fabric_wwn,
1493         .tpg_get_tag                    = tcm_vhost_get_tag,
1494         .tpg_get_default_depth          = tcm_vhost_get_default_depth,
1495         .tpg_get_pr_transport_id        = tcm_vhost_get_pr_transport_id,
1496         .tpg_get_pr_transport_id_len    = tcm_vhost_get_pr_transport_id_len,
1497         .tpg_parse_pr_out_transport_id  = tcm_vhost_parse_pr_out_transport_id,
1498         .tpg_check_demo_mode            = tcm_vhost_check_true,
1499         .tpg_check_demo_mode_cache      = tcm_vhost_check_true,
1500         .tpg_check_demo_mode_write_protect = tcm_vhost_check_false,
1501         .tpg_check_prod_mode_write_protect = tcm_vhost_check_false,
1502         .tpg_alloc_fabric_acl           = tcm_vhost_alloc_fabric_acl,
1503         .tpg_release_fabric_acl         = tcm_vhost_release_fabric_acl,
1504         .tpg_get_inst_index             = tcm_vhost_tpg_get_inst_index,
1505         .release_cmd                    = tcm_vhost_release_cmd,
1506         .shutdown_session               = tcm_vhost_shutdown_session,
1507         .close_session                  = tcm_vhost_close_session,
1508         .sess_get_index                 = tcm_vhost_sess_get_index,
1509         .sess_get_initiator_sid         = NULL,
1510         .write_pending                  = tcm_vhost_write_pending,
1511         .write_pending_status           = tcm_vhost_write_pending_status,
1512         .set_default_node_attributes    = tcm_vhost_set_default_node_attrs,
1513         .get_task_tag                   = tcm_vhost_get_task_tag,
1514         .get_cmd_state                  = tcm_vhost_get_cmd_state,
1515         .queue_data_in                  = tcm_vhost_queue_data_in,
1516         .queue_status                   = tcm_vhost_queue_status,
1517         .queue_tm_rsp                   = tcm_vhost_queue_tm_rsp,
1518         /*
1519          * Setup callers for generic logic in target_core_fabric_configfs.c
1520          */
1521         .fabric_make_wwn                = tcm_vhost_make_tport,
1522         .fabric_drop_wwn                = tcm_vhost_drop_tport,
1523         .fabric_make_tpg                = tcm_vhost_make_tpg,
1524         .fabric_drop_tpg                = tcm_vhost_drop_tpg,
1525         .fabric_post_link               = tcm_vhost_port_link,
1526         .fabric_pre_unlink              = tcm_vhost_port_unlink,
1527         .fabric_make_np                 = NULL,
1528         .fabric_drop_np                 = NULL,
1529         .fabric_make_nodeacl            = tcm_vhost_make_nodeacl,
1530         .fabric_drop_nodeacl            = tcm_vhost_drop_nodeacl,
1531 };
1532
1533 static int tcm_vhost_register_configfs(void)
1534 {
1535         struct target_fabric_configfs *fabric;
1536         int ret;
1537
1538         pr_debug("TCM_VHOST fabric module %s on %s/%s"
1539                 " on "UTS_RELEASE"\n", TCM_VHOST_VERSION, utsname()->sysname,
1540                 utsname()->machine);
1541         /*
1542          * Register the top level struct config_item_type with TCM core
1543          */
1544         fabric = target_fabric_configfs_init(THIS_MODULE, "vhost");
1545         if (IS_ERR(fabric)) {
1546                 pr_err("target_fabric_configfs_init() failed\n");
1547                 return PTR_ERR(fabric);
1548         }
1549         /*
1550          * Setup fabric->tf_ops from our local tcm_vhost_ops
1551          */
1552         fabric->tf_ops = tcm_vhost_ops;
1553         /*
1554          * Setup default attribute lists for various fabric->tf_cit_tmpl
1555          */
1556         TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = tcm_vhost_wwn_attrs;
1557         TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = tcm_vhost_tpg_attrs;
1558         TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = NULL;
1559         TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;
1560         TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;
1561         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;
1562         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
1563         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
1564         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;
1565         /*
1566          * Register the fabric for use within TCM
1567          */
1568         ret = target_fabric_configfs_register(fabric);
1569         if (ret < 0) {
1570                 pr_err("target_fabric_configfs_register() failed"
1571                                 " for TCM_VHOST\n");
1572                 return ret;
1573         }
1574         /*
1575          * Setup our local pointer to *fabric
1576          */
1577         tcm_vhost_fabric_configfs = fabric;
1578         pr_debug("TCM_VHOST[0] - Set fabric -> tcm_vhost_fabric_configfs\n");
1579         return 0;
1580 };
1581
1582 static void tcm_vhost_deregister_configfs(void)
1583 {
1584         if (!tcm_vhost_fabric_configfs)
1585                 return;
1586
1587         target_fabric_configfs_deregister(tcm_vhost_fabric_configfs);
1588         tcm_vhost_fabric_configfs = NULL;
1589         pr_debug("TCM_VHOST[0] - Cleared tcm_vhost_fabric_configfs\n");
1590 };
1591
1592 static int __init tcm_vhost_init(void)
1593 {
1594         int ret = -ENOMEM;
1595         /*
1596          * Use our own dedicated workqueue for submitting I/O into
1597          * target core to avoid contention within system_wq.
1598          */
1599         tcm_vhost_workqueue = alloc_workqueue("tcm_vhost", 0, 0);
1600         if (!tcm_vhost_workqueue)
1601                 goto out;
1602
1603         ret = vhost_scsi_register();
1604         if (ret < 0)
1605                 goto out_destroy_workqueue;
1606
1607         ret = tcm_vhost_register_configfs();
1608         if (ret < 0)
1609                 goto out_vhost_scsi_deregister;
1610
1611         return 0;
1612
1613 out_vhost_scsi_deregister:
1614         vhost_scsi_deregister();
1615 out_destroy_workqueue:
1616         destroy_workqueue(tcm_vhost_workqueue);
1617 out:
1618         return ret;
1619 };
1620
1621 static void tcm_vhost_exit(void)
1622 {
1623         tcm_vhost_deregister_configfs();
1624         vhost_scsi_deregister();
1625         destroy_workqueue(tcm_vhost_workqueue);
1626 };
1627
1628 MODULE_DESCRIPTION("TCM_VHOST series fabric driver");
1629 MODULE_LICENSE("GPL");
1630 module_init(tcm_vhost_init);
1631 module_exit(tcm_vhost_exit);