loop/usb/vhost-scsi/xen-scsiback: Fix use of __transport_register_session
[sfrench/cifs-2.6.git] / drivers / xen / xen-scsiback.c
1 /*
2  * Xen SCSI backend driver
3  *
4  * Copyright (c) 2008, FUJITSU Limited
5  *
6  * Based on the blkback driver code.
7  * Adaption to kernel taget core infrastructure taken from vhost/scsi.c
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License version 2
11  * as published by the Free Software Foundation; or, when distributed
12  * separately from the Linux kernel or incorporated into other
13  * software packages, subject to the following license:
14  *
15  * Permission is hereby granted, free of charge, to any person obtaining a copy
16  * of this source file (the "Software"), to deal in the Software without
17  * restriction, including without limitation the rights to use, copy, modify,
18  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
19  * and to permit persons to whom the Software is furnished to do so, subject to
20  * the following conditions:
21  *
22  * The above copyright notice and this permission notice shall be included in
23  * all copies or substantial portions of the Software.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
31  * IN THE SOFTWARE.
32  */
33
34 #include <stdarg.h>
35
36 #include <linux/module.h>
37 #include <linux/utsname.h>
38 #include <linux/interrupt.h>
39 #include <linux/slab.h>
40 #include <linux/wait.h>
41 #include <linux/sched.h>
42 #include <linux/list.h>
43 #include <linux/gfp.h>
44 #include <linux/delay.h>
45 #include <linux/spinlock.h>
46 #include <linux/configfs.h>
47
48 #include <generated/utsrelease.h>
49
50 #include <scsi/scsi.h>
51 #include <scsi/scsi_dbg.h>
52 #include <scsi/scsi_eh.h>
53 #include <scsi/scsi_tcq.h>
54
55 #include <target/target_core_base.h>
56 #include <target/target_core_fabric.h>
57 #include <target/target_core_configfs.h>
58 #include <target/target_core_fabric_configfs.h>
59
60 #include <asm/hypervisor.h>
61
62 #include <xen/xen.h>
63 #include <xen/balloon.h>
64 #include <xen/events.h>
65 #include <xen/xenbus.h>
66 #include <xen/grant_table.h>
67 #include <xen/page.h>
68
69 #include <xen/interface/grant_table.h>
70 #include <xen/interface/io/vscsiif.h>
71
72 #define DPRINTK(_f, _a...)                      \
73         pr_debug("(file=%s, line=%d) " _f, __FILE__ , __LINE__ , ## _a)
74
75 #define VSCSI_VERSION   "v0.1"
76 #define VSCSI_NAMELEN   32
77
78 struct ids_tuple {
79         unsigned int hst;               /* host    */
80         unsigned int chn;               /* channel */
81         unsigned int tgt;               /* target  */
82         unsigned int lun;               /* LUN     */
83 };
84
85 struct v2p_entry {
86         struct ids_tuple v;             /* translate from */
87         struct scsiback_tpg *tpg;       /* translate to   */
88         unsigned int lun;
89         struct kref kref;
90         struct list_head l;
91 };
92
93 struct vscsibk_info {
94         struct xenbus_device *dev;
95
96         domid_t domid;
97         unsigned int irq;
98
99         struct vscsiif_back_ring ring;
100         int ring_error;
101
102         spinlock_t ring_lock;
103         atomic_t nr_unreplied_reqs;
104
105         spinlock_t v2p_lock;
106         struct list_head v2p_entry_lists;
107
108         wait_queue_head_t waiting_to_free;
109 };
110
111 /* theoretical maximum of grants for one request */
112 #define VSCSI_MAX_GRANTS        (SG_ALL + VSCSIIF_SG_TABLESIZE)
113
114 /*
115  * VSCSI_GRANT_BATCH is the maximum number of grants to be processed in one
116  * call to map/unmap grants. Don't choose it too large, as there are arrays
117  * with VSCSI_GRANT_BATCH elements allocated on the stack.
118  */
119 #define VSCSI_GRANT_BATCH       16
120
121 struct vscsibk_pend {
122         uint16_t rqid;
123
124         uint8_t cmnd[VSCSIIF_MAX_COMMAND_SIZE];
125         uint8_t cmd_len;
126
127         uint8_t sc_data_direction;
128         uint16_t n_sg;          /* real length of SG list */
129         uint16_t n_grants;      /* SG pages and potentially SG list */
130         uint32_t data_len;
131         uint32_t result;
132
133         struct vscsibk_info *info;
134         struct v2p_entry *v2p;
135         struct scatterlist *sgl;
136
137         uint8_t sense_buffer[VSCSIIF_SENSE_BUFFERSIZE];
138
139         grant_handle_t grant_handles[VSCSI_MAX_GRANTS];
140         struct page *pages[VSCSI_MAX_GRANTS];
141
142         struct se_cmd se_cmd;
143 };
144
145 struct scsiback_tmr {
146         atomic_t tmr_complete;
147         wait_queue_head_t tmr_wait;
148 };
149
150 struct scsiback_nexus {
151         /* Pointer to TCM session for I_T Nexus */
152         struct se_session *tvn_se_sess;
153 };
154
155 struct scsiback_tport {
156         /* SCSI protocol the tport is providing */
157         u8 tport_proto_id;
158         /* Binary World Wide unique Port Name for pvscsi Target port */
159         u64 tport_wwpn;
160         /* ASCII formatted WWPN for pvscsi Target port */
161         char tport_name[VSCSI_NAMELEN];
162         /* Returned by scsiback_make_tport() */
163         struct se_wwn tport_wwn;
164 };
165
166 struct scsiback_tpg {
167         /* scsiback port target portal group tag for TCM */
168         u16 tport_tpgt;
169         /* track number of TPG Port/Lun Links wrt explicit I_T Nexus shutdown */
170         int tv_tpg_port_count;
171         /* xen-pvscsi references to tpg_nexus, protected by tv_tpg_mutex */
172         int tv_tpg_fe_count;
173         /* list for scsiback_list */
174         struct list_head tv_tpg_list;
175         /* Used to protect access for tpg_nexus */
176         struct mutex tv_tpg_mutex;
177         /* Pointer to the TCM pvscsi I_T Nexus for this TPG endpoint */
178         struct scsiback_nexus *tpg_nexus;
179         /* Pointer back to scsiback_tport */
180         struct scsiback_tport *tport;
181         /* Returned by scsiback_make_tpg() */
182         struct se_portal_group se_tpg;
183         /* alias used in xenstore */
184         char param_alias[VSCSI_NAMELEN];
185         /* list of info structures related to this target portal group */
186         struct list_head info_list;
187 };
188
189 #define SCSIBACK_INVALID_HANDLE (~0)
190
191 static bool log_print_stat;
192 module_param(log_print_stat, bool, 0644);
193
194 static int scsiback_max_buffer_pages = 1024;
195 module_param_named(max_buffer_pages, scsiback_max_buffer_pages, int, 0644);
196 MODULE_PARM_DESC(max_buffer_pages,
197 "Maximum number of free pages to keep in backend buffer");
198
199 static struct kmem_cache *scsiback_cachep;
200 static DEFINE_SPINLOCK(free_pages_lock);
201 static int free_pages_num;
202 static LIST_HEAD(scsiback_free_pages);
203
204 /* Global spinlock to protect scsiback TPG list */
205 static DEFINE_MUTEX(scsiback_mutex);
206 static LIST_HEAD(scsiback_list);
207
208 /* Local pointer to allocated TCM configfs fabric module */
209 static struct target_fabric_configfs *scsiback_fabric_configfs;
210
211 static void scsiback_get(struct vscsibk_info *info)
212 {
213         atomic_inc(&info->nr_unreplied_reqs);
214 }
215
216 static void scsiback_put(struct vscsibk_info *info)
217 {
218         if (atomic_dec_and_test(&info->nr_unreplied_reqs))
219                 wake_up(&info->waiting_to_free);
220 }
221
222 static void put_free_pages(struct page **page, int num)
223 {
224         unsigned long flags;
225         int i = free_pages_num + num, n = num;
226
227         if (num == 0)
228                 return;
229         if (i > scsiback_max_buffer_pages) {
230                 n = min(num, i - scsiback_max_buffer_pages);
231                 gnttab_free_pages(n, page + num - n);
232                 n = num - n;
233         }
234         spin_lock_irqsave(&free_pages_lock, flags);
235         for (i = 0; i < n; i++)
236                 list_add(&page[i]->lru, &scsiback_free_pages);
237         free_pages_num += n;
238         spin_unlock_irqrestore(&free_pages_lock, flags);
239 }
240
241 static int get_free_page(struct page **page)
242 {
243         unsigned long flags;
244
245         spin_lock_irqsave(&free_pages_lock, flags);
246         if (list_empty(&scsiback_free_pages)) {
247                 spin_unlock_irqrestore(&free_pages_lock, flags);
248                 return gnttab_alloc_pages(1, page);
249         }
250         page[0] = list_first_entry(&scsiback_free_pages, struct page, lru);
251         list_del(&page[0]->lru);
252         free_pages_num--;
253         spin_unlock_irqrestore(&free_pages_lock, flags);
254         return 0;
255 }
256
257 static unsigned long vaddr_page(struct page *page)
258 {
259         unsigned long pfn = page_to_pfn(page);
260
261         return (unsigned long)pfn_to_kaddr(pfn);
262 }
263
264 static unsigned long vaddr(struct vscsibk_pend *req, int seg)
265 {
266         return vaddr_page(req->pages[seg]);
267 }
268
269 static void scsiback_print_status(char *sense_buffer, int errors,
270                                         struct vscsibk_pend *pending_req)
271 {
272         struct scsiback_tpg *tpg = pending_req->v2p->tpg;
273
274         pr_err("xen-pvscsi[%s:%d] cmnd[0]=%02x -> st=%02x msg=%02x host=%02x drv=%02x\n",
275                tpg->tport->tport_name, pending_req->v2p->lun,
276                pending_req->cmnd[0], status_byte(errors), msg_byte(errors),
277                host_byte(errors), driver_byte(errors));
278 }
279
280 static void scsiback_fast_flush_area(struct vscsibk_pend *req)
281 {
282         struct gnttab_unmap_grant_ref unmap[VSCSI_GRANT_BATCH];
283         struct page *pages[VSCSI_GRANT_BATCH];
284         unsigned int i, invcount = 0;
285         grant_handle_t handle;
286         int err;
287
288         kfree(req->sgl);
289         req->sgl = NULL;
290         req->n_sg = 0;
291
292         if (!req->n_grants)
293                 return;
294
295         for (i = 0; i < req->n_grants; i++) {
296                 handle = req->grant_handles[i];
297                 if (handle == SCSIBACK_INVALID_HANDLE)
298                         continue;
299                 gnttab_set_unmap_op(&unmap[invcount], vaddr(req, i),
300                                     GNTMAP_host_map, handle);
301                 req->grant_handles[i] = SCSIBACK_INVALID_HANDLE;
302                 pages[invcount] = req->pages[i];
303                 put_page(pages[invcount]);
304                 invcount++;
305                 if (invcount < VSCSI_GRANT_BATCH)
306                         continue;
307                 err = gnttab_unmap_refs(unmap, NULL, pages, invcount);
308                 BUG_ON(err);
309                 invcount = 0;
310         }
311
312         if (invcount) {
313                 err = gnttab_unmap_refs(unmap, NULL, pages, invcount);
314                 BUG_ON(err);
315         }
316
317         put_free_pages(req->pages, req->n_grants);
318         req->n_grants = 0;
319 }
320
321 static void scsiback_free_translation_entry(struct kref *kref)
322 {
323         struct v2p_entry *entry = container_of(kref, struct v2p_entry, kref);
324         struct scsiback_tpg *tpg = entry->tpg;
325
326         mutex_lock(&tpg->tv_tpg_mutex);
327         tpg->tv_tpg_fe_count--;
328         mutex_unlock(&tpg->tv_tpg_mutex);
329
330         kfree(entry);
331 }
332
333 static void scsiback_do_resp_with_sense(char *sense_buffer, int32_t result,
334                         uint32_t resid, struct vscsibk_pend *pending_req)
335 {
336         struct vscsiif_response *ring_res;
337         struct vscsibk_info *info = pending_req->info;
338         int notify;
339         struct scsi_sense_hdr sshdr;
340         unsigned long flags;
341         unsigned len;
342
343         spin_lock_irqsave(&info->ring_lock, flags);
344
345         ring_res = RING_GET_RESPONSE(&info->ring, info->ring.rsp_prod_pvt);
346         info->ring.rsp_prod_pvt++;
347
348         ring_res->rslt   = result;
349         ring_res->rqid   = pending_req->rqid;
350
351         if (sense_buffer != NULL &&
352             scsi_normalize_sense(sense_buffer, VSCSIIF_SENSE_BUFFERSIZE,
353                                  &sshdr)) {
354                 len = min_t(unsigned, 8 + sense_buffer[7],
355                             VSCSIIF_SENSE_BUFFERSIZE);
356                 memcpy(ring_res->sense_buffer, sense_buffer, len);
357                 ring_res->sense_len = len;
358         } else {
359                 ring_res->sense_len = 0;
360         }
361
362         ring_res->residual_len = resid;
363
364         RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&info->ring, notify);
365         spin_unlock_irqrestore(&info->ring_lock, flags);
366
367         if (notify)
368                 notify_remote_via_irq(info->irq);
369
370         if (pending_req->v2p)
371                 kref_put(&pending_req->v2p->kref,
372                          scsiback_free_translation_entry);
373 }
374
375 static void scsiback_cmd_done(struct vscsibk_pend *pending_req)
376 {
377         struct vscsibk_info *info = pending_req->info;
378         unsigned char *sense_buffer;
379         unsigned int resid;
380         int errors;
381
382         sense_buffer = pending_req->sense_buffer;
383         resid        = pending_req->se_cmd.residual_count;
384         errors       = pending_req->result;
385
386         if (errors && log_print_stat)
387                 scsiback_print_status(sense_buffer, errors, pending_req);
388
389         scsiback_fast_flush_area(pending_req);
390         scsiback_do_resp_with_sense(sense_buffer, errors, resid, pending_req);
391         scsiback_put(info);
392 }
393
394 static void scsiback_cmd_exec(struct vscsibk_pend *pending_req)
395 {
396         struct se_cmd *se_cmd = &pending_req->se_cmd;
397         struct se_session *sess = pending_req->v2p->tpg->tpg_nexus->tvn_se_sess;
398         int rc;
399
400         memset(pending_req->sense_buffer, 0, VSCSIIF_SENSE_BUFFERSIZE);
401
402         memset(se_cmd, 0, sizeof(*se_cmd));
403
404         scsiback_get(pending_req->info);
405         rc = target_submit_cmd_map_sgls(se_cmd, sess, pending_req->cmnd,
406                         pending_req->sense_buffer, pending_req->v2p->lun,
407                         pending_req->data_len, 0,
408                         pending_req->sc_data_direction, 0,
409                         pending_req->sgl, pending_req->n_sg,
410                         NULL, 0, NULL, 0);
411         if (rc < 0) {
412                 transport_send_check_condition_and_sense(se_cmd,
413                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
414                 transport_generic_free_cmd(se_cmd, 0);
415         }
416 }
417
418 static int scsiback_gnttab_data_map_batch(struct gnttab_map_grant_ref *map,
419         struct page **pg, grant_handle_t *grant, int cnt)
420 {
421         int err, i;
422
423         if (!cnt)
424                 return 0;
425
426         err = gnttab_map_refs(map, NULL, pg, cnt);
427         BUG_ON(err);
428         for (i = 0; i < cnt; i++) {
429                 if (unlikely(map[i].status != GNTST_okay)) {
430                         pr_err("xen-pvscsi: invalid buffer -- could not remap it\n");
431                         map[i].handle = SCSIBACK_INVALID_HANDLE;
432                         err = -ENOMEM;
433                 } else {
434                         get_page(pg[i]);
435                 }
436                 grant[i] = map[i].handle;
437         }
438         return err;
439 }
440
441 static int scsiback_gnttab_data_map_list(struct vscsibk_pend *pending_req,
442                         struct scsiif_request_segment *seg, struct page **pg,
443                         grant_handle_t *grant, int cnt, u32 flags)
444 {
445         int mapcount = 0, i, err = 0;
446         struct gnttab_map_grant_ref map[VSCSI_GRANT_BATCH];
447         struct vscsibk_info *info = pending_req->info;
448
449         for (i = 0; i < cnt; i++) {
450                 if (get_free_page(pg + mapcount)) {
451                         put_free_pages(pg, mapcount);
452                         pr_err("xen-pvscsi: no grant page\n");
453                         return -ENOMEM;
454                 }
455                 gnttab_set_map_op(&map[mapcount], vaddr_page(pg[mapcount]),
456                                   flags, seg[i].gref, info->domid);
457                 mapcount++;
458                 if (mapcount < VSCSI_GRANT_BATCH)
459                         continue;
460                 err = scsiback_gnttab_data_map_batch(map, pg, grant, mapcount);
461                 pg += mapcount;
462                 grant += mapcount;
463                 pending_req->n_grants += mapcount;
464                 if (err)
465                         return err;
466                 mapcount = 0;
467         }
468         err = scsiback_gnttab_data_map_batch(map, pg, grant, mapcount);
469         pending_req->n_grants += mapcount;
470         return err;
471 }
472
473 static int scsiback_gnttab_data_map(struct vscsiif_request *ring_req,
474                                         struct vscsibk_pend *pending_req)
475 {
476         u32 flags;
477         int i, err, n_segs, i_seg = 0;
478         struct page **pg;
479         struct scsiif_request_segment *seg;
480         unsigned long end_seg = 0;
481         unsigned int nr_segments = (unsigned int)ring_req->nr_segments;
482         unsigned int nr_sgl = 0;
483         struct scatterlist *sg;
484         grant_handle_t *grant;
485
486         pending_req->n_sg = 0;
487         pending_req->n_grants = 0;
488         pending_req->data_len = 0;
489
490         nr_segments &= ~VSCSIIF_SG_GRANT;
491         if (!nr_segments)
492                 return 0;
493
494         if (nr_segments > VSCSIIF_SG_TABLESIZE) {
495                 DPRINTK("xen-pvscsi: invalid parameter nr_seg = %d\n",
496                         ring_req->nr_segments);
497                 return -EINVAL;
498         }
499
500         if (ring_req->nr_segments & VSCSIIF_SG_GRANT) {
501                 err = scsiback_gnttab_data_map_list(pending_req, ring_req->seg,
502                         pending_req->pages, pending_req->grant_handles,
503                         nr_segments, GNTMAP_host_map | GNTMAP_readonly);
504                 if (err)
505                         return err;
506                 nr_sgl = nr_segments;
507                 nr_segments = 0;
508                 for (i = 0; i < nr_sgl; i++) {
509                         n_segs = ring_req->seg[i].length /
510                                  sizeof(struct scsiif_request_segment);
511                         if ((unsigned)ring_req->seg[i].offset +
512                             (unsigned)ring_req->seg[i].length > PAGE_SIZE ||
513                             n_segs * sizeof(struct scsiif_request_segment) !=
514                             ring_req->seg[i].length)
515                                 return -EINVAL;
516                         nr_segments += n_segs;
517                 }
518                 if (nr_segments > SG_ALL) {
519                         DPRINTK("xen-pvscsi: invalid nr_seg = %d\n",
520                                 nr_segments);
521                         return -EINVAL;
522                 }
523         }
524
525         /* free of (sgl) in fast_flush_area()*/
526         pending_req->sgl = kmalloc_array(nr_segments,
527                                         sizeof(struct scatterlist), GFP_KERNEL);
528         if (!pending_req->sgl)
529                 return -ENOMEM;
530
531         sg_init_table(pending_req->sgl, nr_segments);
532         pending_req->n_sg = nr_segments;
533
534         flags = GNTMAP_host_map;
535         if (pending_req->sc_data_direction == DMA_TO_DEVICE)
536                 flags |= GNTMAP_readonly;
537
538         pg = pending_req->pages + nr_sgl;
539         grant = pending_req->grant_handles + nr_sgl;
540         if (!nr_sgl) {
541                 seg = ring_req->seg;
542                 err = scsiback_gnttab_data_map_list(pending_req, seg,
543                         pg, grant, nr_segments, flags);
544                 if (err)
545                         return err;
546         } else {
547                 for (i = 0; i < nr_sgl; i++) {
548                         seg = (struct scsiif_request_segment *)(
549                               vaddr(pending_req, i) + ring_req->seg[i].offset);
550                         n_segs = ring_req->seg[i].length /
551                                  sizeof(struct scsiif_request_segment);
552                         err = scsiback_gnttab_data_map_list(pending_req, seg,
553                                 pg, grant, n_segs, flags);
554                         if (err)
555                                 return err;
556                         pg += n_segs;
557                         grant += n_segs;
558                 }
559                 end_seg = vaddr(pending_req, 0) + ring_req->seg[0].offset;
560                 seg = (struct scsiif_request_segment *)end_seg;
561                 end_seg += ring_req->seg[0].length;
562                 pg = pending_req->pages + nr_sgl;
563         }
564
565         for_each_sg(pending_req->sgl, sg, nr_segments, i) {
566                 sg_set_page(sg, pg[i], seg->length, seg->offset);
567                 pending_req->data_len += seg->length;
568                 seg++;
569                 if (nr_sgl && (unsigned long)seg >= end_seg) {
570                         i_seg++;
571                         end_seg = vaddr(pending_req, i_seg) +
572                                   ring_req->seg[i_seg].offset;
573                         seg = (struct scsiif_request_segment *)end_seg;
574                         end_seg += ring_req->seg[i_seg].length;
575                 }
576                 if (sg->offset >= PAGE_SIZE ||
577                     sg->length > PAGE_SIZE ||
578                     sg->offset + sg->length > PAGE_SIZE)
579                         return -EINVAL;
580         }
581
582         return 0;
583 }
584
585 static void scsiback_disconnect(struct vscsibk_info *info)
586 {
587         wait_event(info->waiting_to_free,
588                 atomic_read(&info->nr_unreplied_reqs) == 0);
589
590         unbind_from_irqhandler(info->irq, info);
591         info->irq = 0;
592         xenbus_unmap_ring_vfree(info->dev, info->ring.sring);
593 }
594
595 static void scsiback_device_action(struct vscsibk_pend *pending_req,
596         enum tcm_tmreq_table act, int tag)
597 {
598         int rc, err = FAILED;
599         struct scsiback_tpg *tpg = pending_req->v2p->tpg;
600         struct se_cmd *se_cmd = &pending_req->se_cmd;
601         struct scsiback_tmr *tmr;
602
603         tmr = kzalloc(sizeof(struct scsiback_tmr), GFP_KERNEL);
604         if (!tmr)
605                 goto out;
606
607         init_waitqueue_head(&tmr->tmr_wait);
608
609         transport_init_se_cmd(se_cmd, tpg->se_tpg.se_tpg_tfo,
610                 tpg->tpg_nexus->tvn_se_sess, 0, DMA_NONE, TCM_SIMPLE_TAG,
611                 &pending_req->sense_buffer[0]);
612
613         rc = core_tmr_alloc_req(se_cmd, tmr, act, GFP_KERNEL);
614         if (rc < 0)
615                 goto out;
616
617         se_cmd->se_tmr_req->ref_task_tag = tag;
618
619         if (transport_lookup_tmr_lun(se_cmd, pending_req->v2p->lun) < 0)
620                 goto out;
621
622         transport_generic_handle_tmr(se_cmd);
623         wait_event(tmr->tmr_wait, atomic_read(&tmr->tmr_complete));
624
625         err = (se_cmd->se_tmr_req->response == TMR_FUNCTION_COMPLETE) ?
626                 SUCCESS : FAILED;
627
628 out:
629         if (tmr) {
630                 transport_generic_free_cmd(&pending_req->se_cmd, 1);
631                 kfree(tmr);
632         }
633
634         scsiback_do_resp_with_sense(NULL, err, 0, pending_req);
635
636         kmem_cache_free(scsiback_cachep, pending_req);
637 }
638
639 /*
640   Perform virtual to physical translation
641 */
642 static struct v2p_entry *scsiback_do_translation(struct vscsibk_info *info,
643                         struct ids_tuple *v)
644 {
645         struct v2p_entry *entry;
646         struct list_head *head = &(info->v2p_entry_lists);
647         unsigned long flags;
648
649         spin_lock_irqsave(&info->v2p_lock, flags);
650         list_for_each_entry(entry, head, l) {
651                 if ((entry->v.chn == v->chn) &&
652                     (entry->v.tgt == v->tgt) &&
653                     (entry->v.lun == v->lun)) {
654                         kref_get(&entry->kref);
655                         goto out;
656                 }
657         }
658         entry = NULL;
659
660 out:
661         spin_unlock_irqrestore(&info->v2p_lock, flags);
662         return entry;
663 }
664
665 static int prepare_pending_reqs(struct vscsibk_info *info,
666                                 struct vscsiif_request *ring_req,
667                                 struct vscsibk_pend *pending_req)
668 {
669         struct v2p_entry *v2p;
670         struct ids_tuple vir;
671
672         pending_req->rqid       = ring_req->rqid;
673         pending_req->info       = info;
674
675         vir.chn = ring_req->channel;
676         vir.tgt = ring_req->id;
677         vir.lun = ring_req->lun;
678
679         v2p = scsiback_do_translation(info, &vir);
680         if (!v2p) {
681                 pending_req->v2p = NULL;
682                 DPRINTK("xen-pvscsi: doesn't exist.\n");
683                 return -ENODEV;
684         }
685         pending_req->v2p = v2p;
686
687         /* request range check from frontend */
688         pending_req->sc_data_direction = ring_req->sc_data_direction;
689         if ((pending_req->sc_data_direction != DMA_BIDIRECTIONAL) &&
690                 (pending_req->sc_data_direction != DMA_TO_DEVICE) &&
691                 (pending_req->sc_data_direction != DMA_FROM_DEVICE) &&
692                 (pending_req->sc_data_direction != DMA_NONE)) {
693                 DPRINTK("xen-pvscsi: invalid parameter data_dir = %d\n",
694                         pending_req->sc_data_direction);
695                 return -EINVAL;
696         }
697
698         pending_req->cmd_len = ring_req->cmd_len;
699         if (pending_req->cmd_len > VSCSIIF_MAX_COMMAND_SIZE) {
700                 DPRINTK("xen-pvscsi: invalid parameter cmd_len = %d\n",
701                         pending_req->cmd_len);
702                 return -EINVAL;
703         }
704         memcpy(pending_req->cmnd, ring_req->cmnd, pending_req->cmd_len);
705
706         return 0;
707 }
708
709 static int scsiback_do_cmd_fn(struct vscsibk_info *info)
710 {
711         struct vscsiif_back_ring *ring = &info->ring;
712         struct vscsiif_request *ring_req;
713         struct vscsibk_pend *pending_req;
714         RING_IDX rc, rp;
715         int err, more_to_do;
716         uint32_t result;
717         uint8_t act;
718
719         rc = ring->req_cons;
720         rp = ring->sring->req_prod;
721         rmb();  /* guest system is accessing ring, too */
722
723         if (RING_REQUEST_PROD_OVERFLOW(ring, rp)) {
724                 rc = ring->rsp_prod_pvt;
725                 pr_warn("xen-pvscsi: Dom%d provided bogus ring requests (%#x - %#x = %u). Halting ring processing\n",
726                            info->domid, rp, rc, rp - rc);
727                 info->ring_error = 1;
728                 return 0;
729         }
730
731         while ((rc != rp)) {
732                 if (RING_REQUEST_CONS_OVERFLOW(ring, rc))
733                         break;
734                 pending_req = kmem_cache_alloc(scsiback_cachep, GFP_KERNEL);
735                 if (!pending_req)
736                         return 1;
737
738                 ring_req = RING_GET_REQUEST(ring, rc);
739                 ring->req_cons = ++rc;
740
741                 act = ring_req->act;
742                 err = prepare_pending_reqs(info, ring_req, pending_req);
743                 if (err) {
744                         switch (err) {
745                         case -ENODEV:
746                                 result = DID_NO_CONNECT;
747                                 break;
748                         default:
749                                 result = DRIVER_ERROR;
750                                 break;
751                         }
752                         scsiback_do_resp_with_sense(NULL, result << 24, 0,
753                                                     pending_req);
754                         kmem_cache_free(scsiback_cachep, pending_req);
755                         return 1;
756                 }
757
758                 switch (act) {
759                 case VSCSIIF_ACT_SCSI_CDB:
760                         if (scsiback_gnttab_data_map(ring_req, pending_req)) {
761                                 scsiback_fast_flush_area(pending_req);
762                                 scsiback_do_resp_with_sense(NULL,
763                                         DRIVER_ERROR << 24, 0, pending_req);
764                                 kmem_cache_free(scsiback_cachep, pending_req);
765                         } else {
766                                 scsiback_cmd_exec(pending_req);
767                         }
768                         break;
769                 case VSCSIIF_ACT_SCSI_ABORT:
770                         scsiback_device_action(pending_req, TMR_ABORT_TASK,
771                                 ring_req->ref_rqid);
772                         break;
773                 case VSCSIIF_ACT_SCSI_RESET:
774                         scsiback_device_action(pending_req, TMR_LUN_RESET, 0);
775                         break;
776                 default:
777                         pr_err_ratelimited("xen-pvscsi: invalid request\n");
778                         scsiback_do_resp_with_sense(NULL, DRIVER_ERROR << 24,
779                                                     0, pending_req);
780                         kmem_cache_free(scsiback_cachep, pending_req);
781                         break;
782                 }
783
784                 /* Yield point for this unbounded loop. */
785                 cond_resched();
786         }
787
788         RING_FINAL_CHECK_FOR_REQUESTS(&info->ring, more_to_do);
789         return more_to_do;
790 }
791
792 static irqreturn_t scsiback_irq_fn(int irq, void *dev_id)
793 {
794         struct vscsibk_info *info = dev_id;
795
796         if (info->ring_error)
797                 return IRQ_HANDLED;
798
799         while (scsiback_do_cmd_fn(info))
800                 cond_resched();
801
802         return IRQ_HANDLED;
803 }
804
805 static int scsiback_init_sring(struct vscsibk_info *info, grant_ref_t ring_ref,
806                         evtchn_port_t evtchn)
807 {
808         void *area;
809         struct vscsiif_sring *sring;
810         int err;
811
812         if (info->irq)
813                 return -1;
814
815         err = xenbus_map_ring_valloc(info->dev, ring_ref, &area);
816         if (err)
817                 return err;
818
819         sring = (struct vscsiif_sring *)area;
820         BACK_RING_INIT(&info->ring, sring, PAGE_SIZE);
821
822         err = bind_interdomain_evtchn_to_irq(info->domid, evtchn);
823         if (err < 0)
824                 goto unmap_page;
825
826         info->irq = err;
827
828         err = request_threaded_irq(info->irq, NULL, scsiback_irq_fn,
829                                    IRQF_ONESHOT, "vscsiif-backend", info);
830         if (err)
831                 goto free_irq;
832
833         return 0;
834
835 free_irq:
836         unbind_from_irqhandler(info->irq, info);
837         info->irq = 0;
838 unmap_page:
839         xenbus_unmap_ring_vfree(info->dev, area);
840
841         return err;
842 }
843
844 static int scsiback_map(struct vscsibk_info *info)
845 {
846         struct xenbus_device *dev = info->dev;
847         unsigned int ring_ref, evtchn;
848         int err;
849
850         err = xenbus_gather(XBT_NIL, dev->otherend,
851                         "ring-ref", "%u", &ring_ref,
852                         "event-channel", "%u", &evtchn, NULL);
853         if (err) {
854                 xenbus_dev_fatal(dev, err, "reading %s ring", dev->otherend);
855                 return err;
856         }
857
858         return scsiback_init_sring(info, ring_ref, evtchn);
859 }
860
861 /*
862   Add a new translation entry
863 */
864 static int scsiback_add_translation_entry(struct vscsibk_info *info,
865                                           char *phy, struct ids_tuple *v)
866 {
867         int err = 0;
868         struct v2p_entry *entry;
869         struct v2p_entry *new;
870         struct list_head *head = &(info->v2p_entry_lists);
871         unsigned long flags;
872         char *lunp;
873         unsigned int lun;
874         struct scsiback_tpg *tpg_entry, *tpg = NULL;
875         char *error = "doesn't exist";
876
877         lunp = strrchr(phy, ':');
878         if (!lunp) {
879                 pr_err("xen-pvscsi: illegal format of physical device %s\n",
880                         phy);
881                 return -EINVAL;
882         }
883         *lunp = 0;
884         lunp++;
885         if (kstrtouint(lunp, 10, &lun) || lun >= TRANSPORT_MAX_LUNS_PER_TPG) {
886                 pr_err("xen-pvscsi: lun number not valid: %s\n", lunp);
887                 return -EINVAL;
888         }
889
890         mutex_lock(&scsiback_mutex);
891         list_for_each_entry(tpg_entry, &scsiback_list, tv_tpg_list) {
892                 if (!strcmp(phy, tpg_entry->tport->tport_name) ||
893                     !strcmp(phy, tpg_entry->param_alias)) {
894                         spin_lock(&tpg_entry->se_tpg.tpg_lun_lock);
895                         if (tpg_entry->se_tpg.tpg_lun_list[lun]->lun_status ==
896                             TRANSPORT_LUN_STATUS_ACTIVE) {
897                                 if (!tpg_entry->tpg_nexus)
898                                         error = "nexus undefined";
899                                 else
900                                         tpg = tpg_entry;
901                         }
902                         spin_unlock(&tpg_entry->se_tpg.tpg_lun_lock);
903                         break;
904                 }
905         }
906         if (tpg) {
907                 mutex_lock(&tpg->tv_tpg_mutex);
908                 tpg->tv_tpg_fe_count++;
909                 mutex_unlock(&tpg->tv_tpg_mutex);
910         }
911         mutex_unlock(&scsiback_mutex);
912
913         if (!tpg) {
914                 pr_err("xen-pvscsi: %s:%d %s\n", phy, lun, error);
915                 return -ENODEV;
916         }
917
918         new = kmalloc(sizeof(struct v2p_entry), GFP_KERNEL);
919         if (new == NULL) {
920                 err = -ENOMEM;
921                 goto out_free;
922         }
923
924         spin_lock_irqsave(&info->v2p_lock, flags);
925
926         /* Check double assignment to identical virtual ID */
927         list_for_each_entry(entry, head, l) {
928                 if ((entry->v.chn == v->chn) &&
929                     (entry->v.tgt == v->tgt) &&
930                     (entry->v.lun == v->lun)) {
931                         pr_warn("xen-pvscsi: Virtual ID is already used. Assignment was not performed.\n");
932                         err = -EEXIST;
933                         goto out;
934                 }
935
936         }
937
938         /* Create a new translation entry and add to the list */
939         kref_init(&new->kref);
940         new->v = *v;
941         new->tpg = tpg;
942         new->lun = lun;
943         list_add_tail(&new->l, head);
944
945 out:
946         spin_unlock_irqrestore(&info->v2p_lock, flags);
947
948 out_free:
949         mutex_lock(&tpg->tv_tpg_mutex);
950         tpg->tv_tpg_fe_count--;
951         mutex_unlock(&tpg->tv_tpg_mutex);
952
953         if (err)
954                 kfree(new);
955
956         return err;
957 }
958
959 static void __scsiback_del_translation_entry(struct v2p_entry *entry)
960 {
961         list_del(&entry->l);
962         kref_put(&entry->kref, scsiback_free_translation_entry);
963 }
964
965 /*
966   Delete the translation entry specfied
967 */
968 static int scsiback_del_translation_entry(struct vscsibk_info *info,
969                                           struct ids_tuple *v)
970 {
971         struct v2p_entry *entry;
972         struct list_head *head = &(info->v2p_entry_lists);
973         unsigned long flags;
974
975         spin_lock_irqsave(&info->v2p_lock, flags);
976         /* Find out the translation entry specified */
977         list_for_each_entry(entry, head, l) {
978                 if ((entry->v.chn == v->chn) &&
979                     (entry->v.tgt == v->tgt) &&
980                     (entry->v.lun == v->lun)) {
981                         goto found;
982                 }
983         }
984
985         spin_unlock_irqrestore(&info->v2p_lock, flags);
986         return 1;
987
988 found:
989         /* Delete the translation entry specfied */
990         __scsiback_del_translation_entry(entry);
991
992         spin_unlock_irqrestore(&info->v2p_lock, flags);
993         return 0;
994 }
995
996 static void scsiback_do_add_lun(struct vscsibk_info *info, const char *state,
997                                 char *phy, struct ids_tuple *vir)
998 {
999         if (!scsiback_add_translation_entry(info, phy, vir)) {
1000                 if (xenbus_printf(XBT_NIL, info->dev->nodename, state,
1001                                   "%d", XenbusStateInitialised)) {
1002                         pr_err("xen-pvscsi: xenbus_printf error %s\n", state);
1003                         scsiback_del_translation_entry(info, vir);
1004                 }
1005         } else {
1006                 xenbus_printf(XBT_NIL, info->dev->nodename, state,
1007                               "%d", XenbusStateClosed);
1008         }
1009 }
1010
1011 static void scsiback_do_del_lun(struct vscsibk_info *info, const char *state,
1012                                 struct ids_tuple *vir)
1013 {
1014         if (!scsiback_del_translation_entry(info, vir)) {
1015                 if (xenbus_printf(XBT_NIL, info->dev->nodename, state,
1016                                   "%d", XenbusStateClosed))
1017                         pr_err("xen-pvscsi: xenbus_printf error %s\n", state);
1018         }
1019 }
1020
1021 #define VSCSIBACK_OP_ADD_OR_DEL_LUN     1
1022 #define VSCSIBACK_OP_UPDATEDEV_STATE    2
1023
1024 static void scsiback_do_1lun_hotplug(struct vscsibk_info *info, int op,
1025                                      char *ent)
1026 {
1027         int err;
1028         struct ids_tuple vir;
1029         char *val;
1030         int device_state;
1031         char phy[VSCSI_NAMELEN];
1032         char str[64];
1033         char state[64];
1034         struct xenbus_device *dev = info->dev;
1035
1036         /* read status */
1037         snprintf(state, sizeof(state), "vscsi-devs/%s/state", ent);
1038         err = xenbus_scanf(XBT_NIL, dev->nodename, state, "%u", &device_state);
1039         if (XENBUS_EXIST_ERR(err))
1040                 return;
1041
1042         /* physical SCSI device */
1043         snprintf(str, sizeof(str), "vscsi-devs/%s/p-dev", ent);
1044         val = xenbus_read(XBT_NIL, dev->nodename, str, NULL);
1045         if (IS_ERR(val)) {
1046                 xenbus_printf(XBT_NIL, dev->nodename, state,
1047                               "%d", XenbusStateClosed);
1048                 return;
1049         }
1050         strlcpy(phy, val, VSCSI_NAMELEN);
1051         kfree(val);
1052
1053         /* virtual SCSI device */
1054         snprintf(str, sizeof(str), "vscsi-devs/%s/v-dev", ent);
1055         err = xenbus_scanf(XBT_NIL, dev->nodename, str, "%u:%u:%u:%u",
1056                            &vir.hst, &vir.chn, &vir.tgt, &vir.lun);
1057         if (XENBUS_EXIST_ERR(err)) {
1058                 xenbus_printf(XBT_NIL, dev->nodename, state,
1059                               "%d", XenbusStateClosed);
1060                 return;
1061         }
1062
1063         switch (op) {
1064         case VSCSIBACK_OP_ADD_OR_DEL_LUN:
1065                 if (device_state == XenbusStateInitialising)
1066                         scsiback_do_add_lun(info, state, phy, &vir);
1067                 if (device_state == XenbusStateClosing)
1068                         scsiback_do_del_lun(info, state, &vir);
1069                 break;
1070
1071         case VSCSIBACK_OP_UPDATEDEV_STATE:
1072                 if (device_state == XenbusStateInitialised) {
1073                         /* modify vscsi-devs/dev-x/state */
1074                         if (xenbus_printf(XBT_NIL, dev->nodename, state,
1075                                           "%d", XenbusStateConnected)) {
1076                                 pr_err("xen-pvscsi: xenbus_printf error %s\n",
1077                                        str);
1078                                 scsiback_del_translation_entry(info, &vir);
1079                                 xenbus_printf(XBT_NIL, dev->nodename, state,
1080                                               "%d", XenbusStateClosed);
1081                         }
1082                 }
1083                 break;
1084         /*When it is necessary, processing is added here.*/
1085         default:
1086                 break;
1087         }
1088 }
1089
1090 static void scsiback_do_lun_hotplug(struct vscsibk_info *info, int op)
1091 {
1092         int i;
1093         char **dir;
1094         unsigned int ndir = 0;
1095
1096         dir = xenbus_directory(XBT_NIL, info->dev->nodename, "vscsi-devs",
1097                                &ndir);
1098         if (IS_ERR(dir))
1099                 return;
1100
1101         for (i = 0; i < ndir; i++)
1102                 scsiback_do_1lun_hotplug(info, op, dir[i]);
1103
1104         kfree(dir);
1105 }
1106
1107 static void scsiback_frontend_changed(struct xenbus_device *dev,
1108                                         enum xenbus_state frontend_state)
1109 {
1110         struct vscsibk_info *info = dev_get_drvdata(&dev->dev);
1111
1112         switch (frontend_state) {
1113         case XenbusStateInitialising:
1114                 break;
1115
1116         case XenbusStateInitialised:
1117                 if (scsiback_map(info))
1118                         break;
1119
1120                 scsiback_do_lun_hotplug(info, VSCSIBACK_OP_ADD_OR_DEL_LUN);
1121                 xenbus_switch_state(dev, XenbusStateConnected);
1122                 break;
1123
1124         case XenbusStateConnected:
1125                 scsiback_do_lun_hotplug(info, VSCSIBACK_OP_UPDATEDEV_STATE);
1126
1127                 if (dev->state == XenbusStateConnected)
1128                         break;
1129
1130                 xenbus_switch_state(dev, XenbusStateConnected);
1131                 break;
1132
1133         case XenbusStateClosing:
1134                 if (info->irq)
1135                         scsiback_disconnect(info);
1136
1137                 xenbus_switch_state(dev, XenbusStateClosing);
1138                 break;
1139
1140         case XenbusStateClosed:
1141                 xenbus_switch_state(dev, XenbusStateClosed);
1142                 if (xenbus_dev_is_online(dev))
1143                         break;
1144                 /* fall through if not online */
1145         case XenbusStateUnknown:
1146                 device_unregister(&dev->dev);
1147                 break;
1148
1149         case XenbusStateReconfiguring:
1150                 scsiback_do_lun_hotplug(info, VSCSIBACK_OP_ADD_OR_DEL_LUN);
1151                 xenbus_switch_state(dev, XenbusStateReconfigured);
1152
1153                 break;
1154
1155         default:
1156                 xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
1157                                         frontend_state);
1158                 break;
1159         }
1160 }
1161
1162 /*
1163   Release the translation entry specfied
1164 */
1165 static void scsiback_release_translation_entry(struct vscsibk_info *info)
1166 {
1167         struct v2p_entry *entry, *tmp;
1168         struct list_head *head = &(info->v2p_entry_lists);
1169         unsigned long flags;
1170
1171         spin_lock_irqsave(&info->v2p_lock, flags);
1172
1173         list_for_each_entry_safe(entry, tmp, head, l)
1174                 __scsiback_del_translation_entry(entry);
1175
1176         spin_unlock_irqrestore(&info->v2p_lock, flags);
1177 }
1178
1179 static int scsiback_remove(struct xenbus_device *dev)
1180 {
1181         struct vscsibk_info *info = dev_get_drvdata(&dev->dev);
1182
1183         if (info->irq)
1184                 scsiback_disconnect(info);
1185
1186         scsiback_release_translation_entry(info);
1187
1188         dev_set_drvdata(&dev->dev, NULL);
1189
1190         return 0;
1191 }
1192
1193 static int scsiback_probe(struct xenbus_device *dev,
1194                            const struct xenbus_device_id *id)
1195 {
1196         int err;
1197
1198         struct vscsibk_info *info = kzalloc(sizeof(struct vscsibk_info),
1199                                             GFP_KERNEL);
1200
1201         DPRINTK("%p %d\n", dev, dev->otherend_id);
1202
1203         if (!info) {
1204                 xenbus_dev_fatal(dev, -ENOMEM, "allocating backend structure");
1205                 return -ENOMEM;
1206         }
1207         info->dev = dev;
1208         dev_set_drvdata(&dev->dev, info);
1209
1210         info->domid = dev->otherend_id;
1211         spin_lock_init(&info->ring_lock);
1212         info->ring_error = 0;
1213         atomic_set(&info->nr_unreplied_reqs, 0);
1214         init_waitqueue_head(&info->waiting_to_free);
1215         info->dev = dev;
1216         info->irq = 0;
1217         INIT_LIST_HEAD(&info->v2p_entry_lists);
1218         spin_lock_init(&info->v2p_lock);
1219
1220         err = xenbus_printf(XBT_NIL, dev->nodename, "feature-sg-grant", "%u",
1221                             SG_ALL);
1222         if (err)
1223                 xenbus_dev_error(dev, err, "writing feature-sg-grant");
1224
1225         err = xenbus_switch_state(dev, XenbusStateInitWait);
1226         if (err)
1227                 goto fail;
1228
1229         return 0;
1230
1231 fail:
1232         pr_warn("xen-pvscsi: %s failed\n", __func__);
1233         scsiback_remove(dev);
1234
1235         return err;
1236 }
1237
1238 static char *scsiback_dump_proto_id(struct scsiback_tport *tport)
1239 {
1240         switch (tport->tport_proto_id) {
1241         case SCSI_PROTOCOL_SAS:
1242                 return "SAS";
1243         case SCSI_PROTOCOL_FCP:
1244                 return "FCP";
1245         case SCSI_PROTOCOL_ISCSI:
1246                 return "iSCSI";
1247         default:
1248                 break;
1249         }
1250
1251         return "Unknown";
1252 }
1253
1254 static u8 scsiback_get_fabric_proto_ident(struct se_portal_group *se_tpg)
1255 {
1256         struct scsiback_tpg *tpg = container_of(se_tpg,
1257                                 struct scsiback_tpg, se_tpg);
1258         struct scsiback_tport *tport = tpg->tport;
1259
1260         switch (tport->tport_proto_id) {
1261         case SCSI_PROTOCOL_SAS:
1262                 return sas_get_fabric_proto_ident(se_tpg);
1263         case SCSI_PROTOCOL_FCP:
1264                 return fc_get_fabric_proto_ident(se_tpg);
1265         case SCSI_PROTOCOL_ISCSI:
1266                 return iscsi_get_fabric_proto_ident(se_tpg);
1267         default:
1268                 pr_err("Unknown tport_proto_id: 0x%02x, using SAS emulation\n",
1269                         tport->tport_proto_id);
1270                 break;
1271         }
1272
1273         return sas_get_fabric_proto_ident(se_tpg);
1274 }
1275
1276 static char *scsiback_get_fabric_wwn(struct se_portal_group *se_tpg)
1277 {
1278         struct scsiback_tpg *tpg = container_of(se_tpg,
1279                                 struct scsiback_tpg, se_tpg);
1280         struct scsiback_tport *tport = tpg->tport;
1281
1282         return &tport->tport_name[0];
1283 }
1284
1285 static u16 scsiback_get_tag(struct se_portal_group *se_tpg)
1286 {
1287         struct scsiback_tpg *tpg = container_of(se_tpg,
1288                                 struct scsiback_tpg, se_tpg);
1289         return tpg->tport_tpgt;
1290 }
1291
1292 static u32 scsiback_get_default_depth(struct se_portal_group *se_tpg)
1293 {
1294         return 1;
1295 }
1296
1297 static u32
1298 scsiback_get_pr_transport_id(struct se_portal_group *se_tpg,
1299                               struct se_node_acl *se_nacl,
1300                               struct t10_pr_registration *pr_reg,
1301                               int *format_code,
1302                               unsigned char *buf)
1303 {
1304         struct scsiback_tpg *tpg = container_of(se_tpg,
1305                                 struct scsiback_tpg, se_tpg);
1306         struct scsiback_tport *tport = tpg->tport;
1307
1308         switch (tport->tport_proto_id) {
1309         case SCSI_PROTOCOL_SAS:
1310                 return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
1311                                         format_code, buf);
1312         case SCSI_PROTOCOL_FCP:
1313                 return fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
1314                                         format_code, buf);
1315         case SCSI_PROTOCOL_ISCSI:
1316                 return iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
1317                                         format_code, buf);
1318         default:
1319                 pr_err("Unknown tport_proto_id: 0x%02x, using SAS emulation\n",
1320                         tport->tport_proto_id);
1321                 break;
1322         }
1323
1324         return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
1325                         format_code, buf);
1326 }
1327
1328 static u32
1329 scsiback_get_pr_transport_id_len(struct se_portal_group *se_tpg,
1330                                   struct se_node_acl *se_nacl,
1331                                   struct t10_pr_registration *pr_reg,
1332                                   int *format_code)
1333 {
1334         struct scsiback_tpg *tpg = container_of(se_tpg,
1335                                 struct scsiback_tpg, se_tpg);
1336         struct scsiback_tport *tport = tpg->tport;
1337
1338         switch (tport->tport_proto_id) {
1339         case SCSI_PROTOCOL_SAS:
1340                 return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
1341                                         format_code);
1342         case SCSI_PROTOCOL_FCP:
1343                 return fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
1344                                         format_code);
1345         case SCSI_PROTOCOL_ISCSI:
1346                 return iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
1347                                         format_code);
1348         default:
1349                 pr_err("Unknown tport_proto_id: 0x%02x, using SAS emulation\n",
1350                         tport->tport_proto_id);
1351                 break;
1352         }
1353
1354         return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
1355                         format_code);
1356 }
1357
1358 static char *
1359 scsiback_parse_pr_out_transport_id(struct se_portal_group *se_tpg,
1360                                     const char *buf,
1361                                     u32 *out_tid_len,
1362                                     char **port_nexus_ptr)
1363 {
1364         struct scsiback_tpg *tpg = container_of(se_tpg,
1365                                 struct scsiback_tpg, se_tpg);
1366         struct scsiback_tport *tport = tpg->tport;
1367
1368         switch (tport->tport_proto_id) {
1369         case SCSI_PROTOCOL_SAS:
1370                 return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
1371                                         port_nexus_ptr);
1372         case SCSI_PROTOCOL_FCP:
1373                 return fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
1374                                         port_nexus_ptr);
1375         case SCSI_PROTOCOL_ISCSI:
1376                 return iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
1377                                         port_nexus_ptr);
1378         default:
1379                 pr_err("Unknown tport_proto_id: 0x%02x, using SAS emulation\n",
1380                         tport->tport_proto_id);
1381                 break;
1382         }
1383
1384         return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
1385                         port_nexus_ptr);
1386 }
1387
1388 static struct se_wwn *
1389 scsiback_make_tport(struct target_fabric_configfs *tf,
1390                      struct config_group *group,
1391                      const char *name)
1392 {
1393         struct scsiback_tport *tport;
1394         char *ptr;
1395         u64 wwpn = 0;
1396         int off = 0;
1397
1398         tport = kzalloc(sizeof(struct scsiback_tport), GFP_KERNEL);
1399         if (!tport)
1400                 return ERR_PTR(-ENOMEM);
1401
1402         tport->tport_wwpn = wwpn;
1403         /*
1404          * Determine the emulated Protocol Identifier and Target Port Name
1405          * based on the incoming configfs directory name.
1406          */
1407         ptr = strstr(name, "naa.");
1408         if (ptr) {
1409                 tport->tport_proto_id = SCSI_PROTOCOL_SAS;
1410                 goto check_len;
1411         }
1412         ptr = strstr(name, "fc.");
1413         if (ptr) {
1414                 tport->tport_proto_id = SCSI_PROTOCOL_FCP;
1415                 off = 3; /* Skip over "fc." */
1416                 goto check_len;
1417         }
1418         ptr = strstr(name, "iqn.");
1419         if (ptr) {
1420                 tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
1421                 goto check_len;
1422         }
1423
1424         pr_err("Unable to locate prefix for emulated Target Port: %s\n", name);
1425         kfree(tport);
1426         return ERR_PTR(-EINVAL);
1427
1428 check_len:
1429         if (strlen(name) >= VSCSI_NAMELEN) {
1430                 pr_err("Emulated %s Address: %s, exceeds max: %d\n", name,
1431                         scsiback_dump_proto_id(tport), VSCSI_NAMELEN);
1432                 kfree(tport);
1433                 return ERR_PTR(-EINVAL);
1434         }
1435         snprintf(&tport->tport_name[0], VSCSI_NAMELEN, "%s", &name[off]);
1436
1437         pr_debug("xen-pvscsi: Allocated emulated Target %s Address: %s\n",
1438                  scsiback_dump_proto_id(tport), name);
1439
1440         return &tport->tport_wwn;
1441 }
1442
1443 static void scsiback_drop_tport(struct se_wwn *wwn)
1444 {
1445         struct scsiback_tport *tport = container_of(wwn,
1446                                 struct scsiback_tport, tport_wwn);
1447
1448         pr_debug("xen-pvscsi: Deallocating emulated Target %s Address: %s\n",
1449                  scsiback_dump_proto_id(tport), tport->tport_name);
1450
1451         kfree(tport);
1452 }
1453
1454 static struct se_node_acl *
1455 scsiback_alloc_fabric_acl(struct se_portal_group *se_tpg)
1456 {
1457         return kzalloc(sizeof(struct se_node_acl), GFP_KERNEL);
1458 }
1459
1460 static void
1461 scsiback_release_fabric_acl(struct se_portal_group *se_tpg,
1462                              struct se_node_acl *se_nacl)
1463 {
1464         kfree(se_nacl);
1465 }
1466
1467 static u32 scsiback_tpg_get_inst_index(struct se_portal_group *se_tpg)
1468 {
1469         return 1;
1470 }
1471
1472 static int scsiback_check_stop_free(struct se_cmd *se_cmd)
1473 {
1474         /*
1475          * Do not release struct se_cmd's containing a valid TMR
1476          * pointer.  These will be released directly in scsiback_device_action()
1477          * with transport_generic_free_cmd().
1478          */
1479         if (se_cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
1480                 return 0;
1481
1482         transport_generic_free_cmd(se_cmd, 0);
1483         return 1;
1484 }
1485
1486 static void scsiback_release_cmd(struct se_cmd *se_cmd)
1487 {
1488         struct vscsibk_pend *pending_req = container_of(se_cmd,
1489                                 struct vscsibk_pend, se_cmd);
1490
1491         kmem_cache_free(scsiback_cachep, pending_req);
1492 }
1493
1494 static int scsiback_shutdown_session(struct se_session *se_sess)
1495 {
1496         return 0;
1497 }
1498
1499 static void scsiback_close_session(struct se_session *se_sess)
1500 {
1501 }
1502
1503 static u32 scsiback_sess_get_index(struct se_session *se_sess)
1504 {
1505         return 0;
1506 }
1507
1508 static int scsiback_write_pending(struct se_cmd *se_cmd)
1509 {
1510         /* Go ahead and process the write immediately */
1511         target_execute_cmd(se_cmd);
1512
1513         return 0;
1514 }
1515
1516 static int scsiback_write_pending_status(struct se_cmd *se_cmd)
1517 {
1518         return 0;
1519 }
1520
1521 static void scsiback_set_default_node_attrs(struct se_node_acl *nacl)
1522 {
1523 }
1524
1525 static u32 scsiback_get_task_tag(struct se_cmd *se_cmd)
1526 {
1527         struct vscsibk_pend *pending_req = container_of(se_cmd,
1528                                 struct vscsibk_pend, se_cmd);
1529
1530         return pending_req->rqid;
1531 }
1532
1533 static int scsiback_get_cmd_state(struct se_cmd *se_cmd)
1534 {
1535         return 0;
1536 }
1537
1538 static int scsiback_queue_data_in(struct se_cmd *se_cmd)
1539 {
1540         struct vscsibk_pend *pending_req = container_of(se_cmd,
1541                                 struct vscsibk_pend, se_cmd);
1542
1543         pending_req->result = SAM_STAT_GOOD;
1544         scsiback_cmd_done(pending_req);
1545         return 0;
1546 }
1547
1548 static int scsiback_queue_status(struct se_cmd *se_cmd)
1549 {
1550         struct vscsibk_pend *pending_req = container_of(se_cmd,
1551                                 struct vscsibk_pend, se_cmd);
1552
1553         if (se_cmd->sense_buffer &&
1554             ((se_cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ||
1555              (se_cmd->se_cmd_flags & SCF_EMULATED_TASK_SENSE)))
1556                 pending_req->result = (DRIVER_SENSE << 24) |
1557                                       SAM_STAT_CHECK_CONDITION;
1558         else
1559                 pending_req->result = se_cmd->scsi_status;
1560
1561         scsiback_cmd_done(pending_req);
1562         return 0;
1563 }
1564
1565 static void scsiback_queue_tm_rsp(struct se_cmd *se_cmd)
1566 {
1567         struct se_tmr_req *se_tmr = se_cmd->se_tmr_req;
1568         struct scsiback_tmr *tmr = se_tmr->fabric_tmr_ptr;
1569
1570         atomic_set(&tmr->tmr_complete, 1);
1571         wake_up(&tmr->tmr_wait);
1572 }
1573
1574 static void scsiback_aborted_task(struct se_cmd *se_cmd)
1575 {
1576 }
1577
1578 static ssize_t scsiback_tpg_param_show_alias(struct se_portal_group *se_tpg,
1579                                              char *page)
1580 {
1581         struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1582                                                 se_tpg);
1583         ssize_t rb;
1584
1585         mutex_lock(&tpg->tv_tpg_mutex);
1586         rb = snprintf(page, PAGE_SIZE, "%s\n", tpg->param_alias);
1587         mutex_unlock(&tpg->tv_tpg_mutex);
1588
1589         return rb;
1590 }
1591
1592 static ssize_t scsiback_tpg_param_store_alias(struct se_portal_group *se_tpg,
1593                                               const char *page, size_t count)
1594 {
1595         struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1596                                                 se_tpg);
1597         int len;
1598
1599         if (strlen(page) >= VSCSI_NAMELEN) {
1600                 pr_err("param alias: %s, exceeds max: %d\n", page,
1601                         VSCSI_NAMELEN);
1602                 return -EINVAL;
1603         }
1604
1605         mutex_lock(&tpg->tv_tpg_mutex);
1606         len = snprintf(tpg->param_alias, VSCSI_NAMELEN, "%s", page);
1607         if (tpg->param_alias[len - 1] == '\n')
1608                 tpg->param_alias[len - 1] = '\0';
1609         mutex_unlock(&tpg->tv_tpg_mutex);
1610
1611         return count;
1612 }
1613
1614 TF_TPG_PARAM_ATTR(scsiback, alias, S_IRUGO | S_IWUSR);
1615
1616 static struct configfs_attribute *scsiback_param_attrs[] = {
1617         &scsiback_tpg_param_alias.attr,
1618         NULL,
1619 };
1620
1621 static int scsiback_make_nexus(struct scsiback_tpg *tpg,
1622                                 const char *name)
1623 {
1624         struct se_portal_group *se_tpg;
1625         struct se_session *se_sess;
1626         struct scsiback_nexus *tv_nexus;
1627
1628         mutex_lock(&tpg->tv_tpg_mutex);
1629         if (tpg->tpg_nexus) {
1630                 mutex_unlock(&tpg->tv_tpg_mutex);
1631                 pr_debug("tpg->tpg_nexus already exists\n");
1632                 return -EEXIST;
1633         }
1634         se_tpg = &tpg->se_tpg;
1635
1636         tv_nexus = kzalloc(sizeof(struct scsiback_nexus), GFP_KERNEL);
1637         if (!tv_nexus) {
1638                 mutex_unlock(&tpg->tv_tpg_mutex);
1639                 return -ENOMEM;
1640         }
1641         /*
1642          *  Initialize the struct se_session pointer
1643          */
1644         tv_nexus->tvn_se_sess = transport_init_session(TARGET_PROT_NORMAL);
1645         if (IS_ERR(tv_nexus->tvn_se_sess)) {
1646                 mutex_unlock(&tpg->tv_tpg_mutex);
1647                 kfree(tv_nexus);
1648                 return -ENOMEM;
1649         }
1650         se_sess = tv_nexus->tvn_se_sess;
1651         /*
1652          * Since we are running in 'demo mode' this call with generate a
1653          * struct se_node_acl for the scsiback struct se_portal_group with
1654          * the SCSI Initiator port name of the passed configfs group 'name'.
1655          */
1656         tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
1657                                 se_tpg, (unsigned char *)name);
1658         if (!tv_nexus->tvn_se_sess->se_node_acl) {
1659                 mutex_unlock(&tpg->tv_tpg_mutex);
1660                 pr_debug("core_tpg_check_initiator_node_acl() failed for %s\n",
1661                          name);
1662                 goto out;
1663         }
1664         /* Now register the TCM pvscsi virtual I_T Nexus as active. */
1665         transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
1666                         tv_nexus->tvn_se_sess, tv_nexus);
1667         tpg->tpg_nexus = tv_nexus;
1668
1669         mutex_unlock(&tpg->tv_tpg_mutex);
1670         return 0;
1671
1672 out:
1673         transport_free_session(se_sess);
1674         kfree(tv_nexus);
1675         return -ENOMEM;
1676 }
1677
1678 static int scsiback_drop_nexus(struct scsiback_tpg *tpg)
1679 {
1680         struct se_session *se_sess;
1681         struct scsiback_nexus *tv_nexus;
1682
1683         mutex_lock(&tpg->tv_tpg_mutex);
1684         tv_nexus = tpg->tpg_nexus;
1685         if (!tv_nexus) {
1686                 mutex_unlock(&tpg->tv_tpg_mutex);
1687                 return -ENODEV;
1688         }
1689
1690         se_sess = tv_nexus->tvn_se_sess;
1691         if (!se_sess) {
1692                 mutex_unlock(&tpg->tv_tpg_mutex);
1693                 return -ENODEV;
1694         }
1695
1696         if (tpg->tv_tpg_port_count != 0) {
1697                 mutex_unlock(&tpg->tv_tpg_mutex);
1698                 pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG port count: %d\n",
1699                         tpg->tv_tpg_port_count);
1700                 return -EBUSY;
1701         }
1702
1703         if (tpg->tv_tpg_fe_count != 0) {
1704                 mutex_unlock(&tpg->tv_tpg_mutex);
1705                 pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG frontend count: %d\n",
1706                         tpg->tv_tpg_fe_count);
1707                 return -EBUSY;
1708         }
1709
1710         pr_debug("xen-pvscsi: Removing I_T Nexus to emulated %s Initiator Port: %s\n",
1711                 scsiback_dump_proto_id(tpg->tport),
1712                 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1713
1714         /*
1715          * Release the SCSI I_T Nexus to the emulated xen-pvscsi Target Port
1716          */
1717         transport_deregister_session(tv_nexus->tvn_se_sess);
1718         tpg->tpg_nexus = NULL;
1719         mutex_unlock(&tpg->tv_tpg_mutex);
1720
1721         kfree(tv_nexus);
1722         return 0;
1723 }
1724
1725 static ssize_t scsiback_tpg_show_nexus(struct se_portal_group *se_tpg,
1726                                         char *page)
1727 {
1728         struct scsiback_tpg *tpg = container_of(se_tpg,
1729                                 struct scsiback_tpg, se_tpg);
1730         struct scsiback_nexus *tv_nexus;
1731         ssize_t ret;
1732
1733         mutex_lock(&tpg->tv_tpg_mutex);
1734         tv_nexus = tpg->tpg_nexus;
1735         if (!tv_nexus) {
1736                 mutex_unlock(&tpg->tv_tpg_mutex);
1737                 return -ENODEV;
1738         }
1739         ret = snprintf(page, PAGE_SIZE, "%s\n",
1740                         tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1741         mutex_unlock(&tpg->tv_tpg_mutex);
1742
1743         return ret;
1744 }
1745
1746 static ssize_t scsiback_tpg_store_nexus(struct se_portal_group *se_tpg,
1747                                          const char *page,
1748                                          size_t count)
1749 {
1750         struct scsiback_tpg *tpg = container_of(se_tpg,
1751                                 struct scsiback_tpg, se_tpg);
1752         struct scsiback_tport *tport_wwn = tpg->tport;
1753         unsigned char i_port[VSCSI_NAMELEN], *ptr, *port_ptr;
1754         int ret;
1755         /*
1756          * Shutdown the active I_T nexus if 'NULL' is passed..
1757          */
1758         if (!strncmp(page, "NULL", 4)) {
1759                 ret = scsiback_drop_nexus(tpg);
1760                 return (!ret) ? count : ret;
1761         }
1762         /*
1763          * Otherwise make sure the passed virtual Initiator port WWN matches
1764          * the fabric protocol_id set in scsiback_make_tport(), and call
1765          * scsiback_make_nexus().
1766          */
1767         if (strlen(page) >= VSCSI_NAMELEN) {
1768                 pr_err("Emulated NAA Sas Address: %s, exceeds max: %d\n",
1769                         page, VSCSI_NAMELEN);
1770                 return -EINVAL;
1771         }
1772         snprintf(&i_port[0], VSCSI_NAMELEN, "%s", page);
1773
1774         ptr = strstr(i_port, "naa.");
1775         if (ptr) {
1776                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
1777                         pr_err("Passed SAS Initiator Port %s does not match target port protoid: %s\n",
1778                                 i_port, scsiback_dump_proto_id(tport_wwn));
1779                         return -EINVAL;
1780                 }
1781                 port_ptr = &i_port[0];
1782                 goto check_newline;
1783         }
1784         ptr = strstr(i_port, "fc.");
1785         if (ptr) {
1786                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
1787                         pr_err("Passed FCP Initiator Port %s does not match target port protoid: %s\n",
1788                                 i_port, scsiback_dump_proto_id(tport_wwn));
1789                         return -EINVAL;
1790                 }
1791                 port_ptr = &i_port[3]; /* Skip over "fc." */
1792                 goto check_newline;
1793         }
1794         ptr = strstr(i_port, "iqn.");
1795         if (ptr) {
1796                 if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
1797                         pr_err("Passed iSCSI Initiator Port %s does not match target port protoid: %s\n",
1798                                 i_port, scsiback_dump_proto_id(tport_wwn));
1799                         return -EINVAL;
1800                 }
1801                 port_ptr = &i_port[0];
1802                 goto check_newline;
1803         }
1804         pr_err("Unable to locate prefix for emulated Initiator Port: %s\n",
1805                 i_port);
1806         return -EINVAL;
1807         /*
1808          * Clear any trailing newline for the NAA WWN
1809          */
1810 check_newline:
1811         if (i_port[strlen(i_port) - 1] == '\n')
1812                 i_port[strlen(i_port) - 1] = '\0';
1813
1814         ret = scsiback_make_nexus(tpg, port_ptr);
1815         if (ret < 0)
1816                 return ret;
1817
1818         return count;
1819 }
1820
1821 TF_TPG_BASE_ATTR(scsiback, nexus, S_IRUGO | S_IWUSR);
1822
1823 static struct configfs_attribute *scsiback_tpg_attrs[] = {
1824         &scsiback_tpg_nexus.attr,
1825         NULL,
1826 };
1827
1828 static ssize_t
1829 scsiback_wwn_show_attr_version(struct target_fabric_configfs *tf,
1830                                 char *page)
1831 {
1832         return sprintf(page, "xen-pvscsi fabric module %s on %s/%s on "
1833                 UTS_RELEASE"\n",
1834                 VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1835 }
1836
1837 TF_WWN_ATTR_RO(scsiback, version);
1838
1839 static struct configfs_attribute *scsiback_wwn_attrs[] = {
1840         &scsiback_wwn_version.attr,
1841         NULL,
1842 };
1843
1844 static char *scsiback_get_fabric_name(void)
1845 {
1846         return "xen-pvscsi";
1847 }
1848
1849 static int scsiback_port_link(struct se_portal_group *se_tpg,
1850                                struct se_lun *lun)
1851 {
1852         struct scsiback_tpg *tpg = container_of(se_tpg,
1853                                 struct scsiback_tpg, se_tpg);
1854
1855         mutex_lock(&tpg->tv_tpg_mutex);
1856         tpg->tv_tpg_port_count++;
1857         mutex_unlock(&tpg->tv_tpg_mutex);
1858
1859         return 0;
1860 }
1861
1862 static void scsiback_port_unlink(struct se_portal_group *se_tpg,
1863                                   struct se_lun *lun)
1864 {
1865         struct scsiback_tpg *tpg = container_of(se_tpg,
1866                                 struct scsiback_tpg, se_tpg);
1867
1868         mutex_lock(&tpg->tv_tpg_mutex);
1869         tpg->tv_tpg_port_count--;
1870         mutex_unlock(&tpg->tv_tpg_mutex);
1871 }
1872
1873 static struct se_portal_group *
1874 scsiback_make_tpg(struct se_wwn *wwn,
1875                    struct config_group *group,
1876                    const char *name)
1877 {
1878         struct scsiback_tport *tport = container_of(wwn,
1879                         struct scsiback_tport, tport_wwn);
1880
1881         struct scsiback_tpg *tpg;
1882         u16 tpgt;
1883         int ret;
1884
1885         if (strstr(name, "tpgt_") != name)
1886                 return ERR_PTR(-EINVAL);
1887         ret = kstrtou16(name + 5, 10, &tpgt);
1888         if (ret)
1889                 return ERR_PTR(ret);
1890
1891         tpg = kzalloc(sizeof(struct scsiback_tpg), GFP_KERNEL);
1892         if (!tpg)
1893                 return ERR_PTR(-ENOMEM);
1894
1895         mutex_init(&tpg->tv_tpg_mutex);
1896         INIT_LIST_HEAD(&tpg->tv_tpg_list);
1897         INIT_LIST_HEAD(&tpg->info_list);
1898         tpg->tport = tport;
1899         tpg->tport_tpgt = tpgt;
1900
1901         ret = core_tpg_register(&scsiback_fabric_configfs->tf_ops, wwn,
1902                                 &tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
1903         if (ret < 0) {
1904                 kfree(tpg);
1905                 return NULL;
1906         }
1907         mutex_lock(&scsiback_mutex);
1908         list_add_tail(&tpg->tv_tpg_list, &scsiback_list);
1909         mutex_unlock(&scsiback_mutex);
1910
1911         return &tpg->se_tpg;
1912 }
1913
1914 static void scsiback_drop_tpg(struct se_portal_group *se_tpg)
1915 {
1916         struct scsiback_tpg *tpg = container_of(se_tpg,
1917                                 struct scsiback_tpg, se_tpg);
1918
1919         mutex_lock(&scsiback_mutex);
1920         list_del(&tpg->tv_tpg_list);
1921         mutex_unlock(&scsiback_mutex);
1922         /*
1923          * Release the virtual I_T Nexus for this xen-pvscsi TPG
1924          */
1925         scsiback_drop_nexus(tpg);
1926         /*
1927          * Deregister the se_tpg from TCM..
1928          */
1929         core_tpg_deregister(se_tpg);
1930         kfree(tpg);
1931 }
1932
1933 static int scsiback_check_true(struct se_portal_group *se_tpg)
1934 {
1935         return 1;
1936 }
1937
1938 static int scsiback_check_false(struct se_portal_group *se_tpg)
1939 {
1940         return 0;
1941 }
1942
1943 static struct target_core_fabric_ops scsiback_ops = {
1944         .get_fabric_name                = scsiback_get_fabric_name,
1945         .get_fabric_proto_ident         = scsiback_get_fabric_proto_ident,
1946         .tpg_get_wwn                    = scsiback_get_fabric_wwn,
1947         .tpg_get_tag                    = scsiback_get_tag,
1948         .tpg_get_default_depth          = scsiback_get_default_depth,
1949         .tpg_get_pr_transport_id        = scsiback_get_pr_transport_id,
1950         .tpg_get_pr_transport_id_len    = scsiback_get_pr_transport_id_len,
1951         .tpg_parse_pr_out_transport_id  = scsiback_parse_pr_out_transport_id,
1952         .tpg_check_demo_mode            = scsiback_check_true,
1953         .tpg_check_demo_mode_cache      = scsiback_check_true,
1954         .tpg_check_demo_mode_write_protect = scsiback_check_false,
1955         .tpg_check_prod_mode_write_protect = scsiback_check_false,
1956         .tpg_alloc_fabric_acl           = scsiback_alloc_fabric_acl,
1957         .tpg_release_fabric_acl         = scsiback_release_fabric_acl,
1958         .tpg_get_inst_index             = scsiback_tpg_get_inst_index,
1959         .check_stop_free                = scsiback_check_stop_free,
1960         .release_cmd                    = scsiback_release_cmd,
1961         .put_session                    = NULL,
1962         .shutdown_session               = scsiback_shutdown_session,
1963         .close_session                  = scsiback_close_session,
1964         .sess_get_index                 = scsiback_sess_get_index,
1965         .sess_get_initiator_sid         = NULL,
1966         .write_pending                  = scsiback_write_pending,
1967         .write_pending_status           = scsiback_write_pending_status,
1968         .set_default_node_attributes    = scsiback_set_default_node_attrs,
1969         .get_task_tag                   = scsiback_get_task_tag,
1970         .get_cmd_state                  = scsiback_get_cmd_state,
1971         .queue_data_in                  = scsiback_queue_data_in,
1972         .queue_status                   = scsiback_queue_status,
1973         .queue_tm_rsp                   = scsiback_queue_tm_rsp,
1974         .aborted_task                   = scsiback_aborted_task,
1975         /*
1976          * Setup callers for generic logic in target_core_fabric_configfs.c
1977          */
1978         .fabric_make_wwn                = scsiback_make_tport,
1979         .fabric_drop_wwn                = scsiback_drop_tport,
1980         .fabric_make_tpg                = scsiback_make_tpg,
1981         .fabric_drop_tpg                = scsiback_drop_tpg,
1982         .fabric_post_link               = scsiback_port_link,
1983         .fabric_pre_unlink              = scsiback_port_unlink,
1984         .fabric_make_np                 = NULL,
1985         .fabric_drop_np                 = NULL,
1986 #if 0
1987         .fabric_make_nodeacl            = scsiback_make_nodeacl,
1988         .fabric_drop_nodeacl            = scsiback_drop_nodeacl,
1989 #endif
1990 };
1991
1992 static int scsiback_register_configfs(void)
1993 {
1994         struct target_fabric_configfs *fabric;
1995         int ret;
1996
1997         pr_debug("xen-pvscsi: fabric module %s on %s/%s on "UTS_RELEASE"\n",
1998                  VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1999         /*
2000          * Register the top level struct config_item_type with TCM core
2001          */
2002         fabric = target_fabric_configfs_init(THIS_MODULE, "xen-pvscsi");
2003         if (IS_ERR(fabric))
2004                 return PTR_ERR(fabric);
2005
2006         /*
2007          * Setup fabric->tf_ops from our local scsiback_ops
2008          */
2009         fabric->tf_ops = scsiback_ops;
2010         /*
2011          * Setup default attribute lists for various fabric->tf_cit_tmpl
2012          */
2013         fabric->tf_cit_tmpl.tfc_wwn_cit.ct_attrs = scsiback_wwn_attrs;
2014         fabric->tf_cit_tmpl.tfc_tpg_base_cit.ct_attrs = scsiback_tpg_attrs;
2015         fabric->tf_cit_tmpl.tfc_tpg_attrib_cit.ct_attrs = NULL;
2016         fabric->tf_cit_tmpl.tfc_tpg_param_cit.ct_attrs = scsiback_param_attrs;
2017         fabric->tf_cit_tmpl.tfc_tpg_np_base_cit.ct_attrs = NULL;
2018         fabric->tf_cit_tmpl.tfc_tpg_nacl_base_cit.ct_attrs = NULL;
2019         fabric->tf_cit_tmpl.tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
2020         fabric->tf_cit_tmpl.tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
2021         fabric->tf_cit_tmpl.tfc_tpg_nacl_param_cit.ct_attrs = NULL;
2022         /*
2023          * Register the fabric for use within TCM
2024          */
2025         ret = target_fabric_configfs_register(fabric);
2026         if (ret < 0) {
2027                 target_fabric_configfs_free(fabric);
2028                 return ret;
2029         }
2030         /*
2031          * Setup our local pointer to *fabric
2032          */
2033         scsiback_fabric_configfs = fabric;
2034         pr_debug("xen-pvscsi: Set fabric -> scsiback_fabric_configfs\n");
2035         return 0;
2036 };
2037
2038 static void scsiback_deregister_configfs(void)
2039 {
2040         if (!scsiback_fabric_configfs)
2041                 return;
2042
2043         target_fabric_configfs_deregister(scsiback_fabric_configfs);
2044         scsiback_fabric_configfs = NULL;
2045         pr_debug("xen-pvscsi: Cleared scsiback_fabric_configfs\n");
2046 };
2047
2048 static const struct xenbus_device_id scsiback_ids[] = {
2049         { "vscsi" },
2050         { "" }
2051 };
2052
2053 static struct xenbus_driver scsiback_driver = {
2054         .ids                    = scsiback_ids,
2055         .probe                  = scsiback_probe,
2056         .remove                 = scsiback_remove,
2057         .otherend_changed       = scsiback_frontend_changed
2058 };
2059
2060 static void scsiback_init_pend(void *p)
2061 {
2062         struct vscsibk_pend *pend = p;
2063         int i;
2064
2065         memset(pend, 0, sizeof(*pend));
2066         for (i = 0; i < VSCSI_MAX_GRANTS; i++)
2067                 pend->grant_handles[i] = SCSIBACK_INVALID_HANDLE;
2068 }
2069
2070 static int __init scsiback_init(void)
2071 {
2072         int ret;
2073
2074         if (!xen_domain())
2075                 return -ENODEV;
2076
2077         scsiback_cachep = kmem_cache_create("vscsiif_cache",
2078                 sizeof(struct vscsibk_pend), 0, 0, scsiback_init_pend);
2079         if (!scsiback_cachep)
2080                 return -ENOMEM;
2081
2082         ret = xenbus_register_backend(&scsiback_driver);
2083         if (ret)
2084                 goto out_cache_destroy;
2085
2086         ret = scsiback_register_configfs();
2087         if (ret)
2088                 goto out_unregister_xenbus;
2089
2090         return 0;
2091
2092 out_unregister_xenbus:
2093         xenbus_unregister_driver(&scsiback_driver);
2094 out_cache_destroy:
2095         kmem_cache_destroy(scsiback_cachep);
2096         pr_err("xen-pvscsi: %s: error %d\n", __func__, ret);
2097         return ret;
2098 }
2099
2100 static void __exit scsiback_exit(void)
2101 {
2102         struct page *page;
2103
2104         while (free_pages_num) {
2105                 if (get_free_page(&page))
2106                         BUG();
2107                 gnttab_free_pages(1, &page);
2108         }
2109         scsiback_deregister_configfs();
2110         xenbus_unregister_driver(&scsiback_driver);
2111         kmem_cache_destroy(scsiback_cachep);
2112 }
2113
2114 module_init(scsiback_init);
2115 module_exit(scsiback_exit);
2116
2117 MODULE_DESCRIPTION("Xen SCSI backend driver");
2118 MODULE_LICENSE("Dual BSD/GPL");
2119 MODULE_ALIAS("xen-backend:vscsi");
2120 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");