xref: /openbmc/linux/drivers/xen/xen-scsiback.c (revision 3d37ef41)
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 #define pr_fmt(fmt) "xen-pvscsi: " fmt
35 
36 #include <stdarg.h>
37 
38 #include <linux/module.h>
39 #include <linux/utsname.h>
40 #include <linux/interrupt.h>
41 #include <linux/slab.h>
42 #include <linux/wait.h>
43 #include <linux/sched.h>
44 #include <linux/list.h>
45 #include <linux/gfp.h>
46 #include <linux/delay.h>
47 #include <linux/spinlock.h>
48 #include <linux/configfs.h>
49 
50 #include <generated/utsrelease.h>
51 
52 #include <scsi/scsi_host.h> /* SG_ALL */
53 
54 #include <target/target_core_base.h>
55 #include <target/target_core_fabric.h>
56 
57 #include <asm/hypervisor.h>
58 
59 #include <xen/xen.h>
60 #include <xen/balloon.h>
61 #include <xen/events.h>
62 #include <xen/xenbus.h>
63 #include <xen/grant_table.h>
64 #include <xen/page.h>
65 
66 #include <xen/interface/grant_table.h>
67 #include <xen/interface/io/vscsiif.h>
68 
69 #define VSCSI_VERSION	"v0.1"
70 #define VSCSI_NAMELEN	32
71 
72 struct ids_tuple {
73 	unsigned int hst;		/* host    */
74 	unsigned int chn;		/* channel */
75 	unsigned int tgt;		/* target  */
76 	unsigned int lun;		/* LUN     */
77 };
78 
79 struct v2p_entry {
80 	struct ids_tuple v;		/* translate from */
81 	struct scsiback_tpg *tpg;	/* translate to   */
82 	unsigned int lun;
83 	struct kref kref;
84 	struct list_head l;
85 };
86 
87 struct vscsibk_info {
88 	struct xenbus_device *dev;
89 
90 	domid_t domid;
91 	unsigned int irq;
92 
93 	struct vscsiif_back_ring ring;
94 
95 	spinlock_t ring_lock;
96 	atomic_t nr_unreplied_reqs;
97 
98 	spinlock_t v2p_lock;
99 	struct list_head v2p_entry_lists;
100 
101 	wait_queue_head_t waiting_to_free;
102 
103 	struct gnttab_page_cache free_pages;
104 };
105 
106 /* theoretical maximum of grants for one request */
107 #define VSCSI_MAX_GRANTS	(SG_ALL + VSCSIIF_SG_TABLESIZE)
108 
109 /*
110  * VSCSI_GRANT_BATCH is the maximum number of grants to be processed in one
111  * call to map/unmap grants. Don't choose it too large, as there are arrays
112  * with VSCSI_GRANT_BATCH elements allocated on the stack.
113  */
114 #define VSCSI_GRANT_BATCH	16
115 
116 struct vscsibk_pend {
117 	uint16_t rqid;
118 
119 	uint8_t cmnd[VSCSIIF_MAX_COMMAND_SIZE];
120 	uint8_t cmd_len;
121 
122 	uint8_t sc_data_direction;
123 	uint16_t n_sg;		/* real length of SG list */
124 	uint16_t n_grants;	/* SG pages and potentially SG list */
125 	uint32_t data_len;
126 	uint32_t result;
127 
128 	struct vscsibk_info *info;
129 	struct v2p_entry *v2p;
130 	struct scatterlist *sgl;
131 
132 	uint8_t sense_buffer[VSCSIIF_SENSE_BUFFERSIZE];
133 
134 	grant_handle_t grant_handles[VSCSI_MAX_GRANTS];
135 	struct page *pages[VSCSI_MAX_GRANTS];
136 
137 	struct se_cmd se_cmd;
138 
139 	struct completion tmr_done;
140 };
141 
142 #define VSCSI_DEFAULT_SESSION_TAGS	128
143 
144 struct scsiback_nexus {
145 	/* Pointer to TCM session for I_T Nexus */
146 	struct se_session *tvn_se_sess;
147 };
148 
149 struct scsiback_tport {
150 	/* SCSI protocol the tport is providing */
151 	u8 tport_proto_id;
152 	/* Binary World Wide unique Port Name for pvscsi Target port */
153 	u64 tport_wwpn;
154 	/* ASCII formatted WWPN for pvscsi Target port */
155 	char tport_name[VSCSI_NAMELEN];
156 	/* Returned by scsiback_make_tport() */
157 	struct se_wwn tport_wwn;
158 };
159 
160 struct scsiback_tpg {
161 	/* scsiback port target portal group tag for TCM */
162 	u16 tport_tpgt;
163 	/* track number of TPG Port/Lun Links wrt explicit I_T Nexus shutdown */
164 	int tv_tpg_port_count;
165 	/* xen-pvscsi references to tpg_nexus, protected by tv_tpg_mutex */
166 	int tv_tpg_fe_count;
167 	/* list for scsiback_list */
168 	struct list_head tv_tpg_list;
169 	/* Used to protect access for tpg_nexus */
170 	struct mutex tv_tpg_mutex;
171 	/* Pointer to the TCM pvscsi I_T Nexus for this TPG endpoint */
172 	struct scsiback_nexus *tpg_nexus;
173 	/* Pointer back to scsiback_tport */
174 	struct scsiback_tport *tport;
175 	/* Returned by scsiback_make_tpg() */
176 	struct se_portal_group se_tpg;
177 	/* alias used in xenstore */
178 	char param_alias[VSCSI_NAMELEN];
179 	/* list of info structures related to this target portal group */
180 	struct list_head info_list;
181 };
182 
183 #define SCSIBACK_INVALID_HANDLE (~0)
184 
185 static bool log_print_stat;
186 module_param(log_print_stat, bool, 0644);
187 
188 static int scsiback_max_buffer_pages = 1024;
189 module_param_named(max_buffer_pages, scsiback_max_buffer_pages, int, 0644);
190 MODULE_PARM_DESC(max_buffer_pages,
191 "Maximum number of free pages to keep in backend buffer");
192 
193 /* Global spinlock to protect scsiback TPG list */
194 static DEFINE_MUTEX(scsiback_mutex);
195 static LIST_HEAD(scsiback_list);
196 
197 static void scsiback_get(struct vscsibk_info *info)
198 {
199 	atomic_inc(&info->nr_unreplied_reqs);
200 }
201 
202 static void scsiback_put(struct vscsibk_info *info)
203 {
204 	if (atomic_dec_and_test(&info->nr_unreplied_reqs))
205 		wake_up(&info->waiting_to_free);
206 }
207 
208 static unsigned long vaddr_page(struct page *page)
209 {
210 	unsigned long pfn = page_to_pfn(page);
211 
212 	return (unsigned long)pfn_to_kaddr(pfn);
213 }
214 
215 static unsigned long vaddr(struct vscsibk_pend *req, int seg)
216 {
217 	return vaddr_page(req->pages[seg]);
218 }
219 
220 static void scsiback_print_status(char *sense_buffer, int errors,
221 					struct vscsibk_pend *pending_req)
222 {
223 	struct scsiback_tpg *tpg = pending_req->v2p->tpg;
224 
225 	pr_err("[%s:%d] cmnd[0]=%02x -> st=%02x msg=%02x host=%02x drv=%02x\n",
226 	       tpg->tport->tport_name, pending_req->v2p->lun,
227 	       pending_req->cmnd[0], status_byte(errors), msg_byte(errors),
228 	       host_byte(errors), driver_byte(errors));
229 }
230 
231 static void scsiback_fast_flush_area(struct vscsibk_pend *req)
232 {
233 	struct gnttab_unmap_grant_ref unmap[VSCSI_GRANT_BATCH];
234 	struct page *pages[VSCSI_GRANT_BATCH];
235 	unsigned int i, invcount = 0;
236 	grant_handle_t handle;
237 	int err;
238 
239 	kfree(req->sgl);
240 	req->sgl = NULL;
241 	req->n_sg = 0;
242 
243 	if (!req->n_grants)
244 		return;
245 
246 	for (i = 0; i < req->n_grants; i++) {
247 		handle = req->grant_handles[i];
248 		if (handle == SCSIBACK_INVALID_HANDLE)
249 			continue;
250 		gnttab_set_unmap_op(&unmap[invcount], vaddr(req, i),
251 				    GNTMAP_host_map, handle);
252 		req->grant_handles[i] = SCSIBACK_INVALID_HANDLE;
253 		pages[invcount] = req->pages[i];
254 		put_page(pages[invcount]);
255 		invcount++;
256 		if (invcount < VSCSI_GRANT_BATCH)
257 			continue;
258 		err = gnttab_unmap_refs(unmap, NULL, pages, invcount);
259 		BUG_ON(err);
260 		invcount = 0;
261 	}
262 
263 	if (invcount) {
264 		err = gnttab_unmap_refs(unmap, NULL, pages, invcount);
265 		BUG_ON(err);
266 	}
267 
268 	gnttab_page_cache_put(&req->info->free_pages, req->pages,
269 			      req->n_grants);
270 	req->n_grants = 0;
271 }
272 
273 static void scsiback_free_translation_entry(struct kref *kref)
274 {
275 	struct v2p_entry *entry = container_of(kref, struct v2p_entry, kref);
276 	struct scsiback_tpg *tpg = entry->tpg;
277 
278 	mutex_lock(&tpg->tv_tpg_mutex);
279 	tpg->tv_tpg_fe_count--;
280 	mutex_unlock(&tpg->tv_tpg_mutex);
281 
282 	kfree(entry);
283 }
284 
285 static void scsiback_send_response(struct vscsibk_info *info,
286 			char *sense_buffer, int32_t result, uint32_t resid,
287 			uint16_t rqid)
288 {
289 	struct vscsiif_response *ring_res;
290 	int notify;
291 	struct scsi_sense_hdr sshdr;
292 	unsigned long flags;
293 	unsigned len;
294 
295 	spin_lock_irqsave(&info->ring_lock, flags);
296 
297 	ring_res = RING_GET_RESPONSE(&info->ring, info->ring.rsp_prod_pvt);
298 	info->ring.rsp_prod_pvt++;
299 
300 	ring_res->rslt   = result;
301 	ring_res->rqid   = rqid;
302 
303 	if (sense_buffer != NULL &&
304 	    scsi_normalize_sense(sense_buffer, VSCSIIF_SENSE_BUFFERSIZE,
305 				 &sshdr)) {
306 		len = min_t(unsigned, 8 + sense_buffer[7],
307 			    VSCSIIF_SENSE_BUFFERSIZE);
308 		memcpy(ring_res->sense_buffer, sense_buffer, len);
309 		ring_res->sense_len = len;
310 	} else {
311 		ring_res->sense_len = 0;
312 	}
313 
314 	ring_res->residual_len = resid;
315 
316 	RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&info->ring, notify);
317 	spin_unlock_irqrestore(&info->ring_lock, flags);
318 
319 	if (notify)
320 		notify_remote_via_irq(info->irq);
321 }
322 
323 static void scsiback_do_resp_with_sense(char *sense_buffer, int32_t result,
324 			uint32_t resid, struct vscsibk_pend *pending_req)
325 {
326 	scsiback_send_response(pending_req->info, sense_buffer, result,
327 			       resid, pending_req->rqid);
328 
329 	if (pending_req->v2p)
330 		kref_put(&pending_req->v2p->kref,
331 			 scsiback_free_translation_entry);
332 }
333 
334 static void scsiback_cmd_done(struct vscsibk_pend *pending_req)
335 {
336 	struct vscsibk_info *info = pending_req->info;
337 	unsigned char *sense_buffer;
338 	unsigned int resid;
339 	int errors;
340 
341 	sense_buffer = pending_req->sense_buffer;
342 	resid        = pending_req->se_cmd.residual_count;
343 	errors       = pending_req->result;
344 
345 	if (errors && log_print_stat)
346 		scsiback_print_status(sense_buffer, errors, pending_req);
347 
348 	scsiback_fast_flush_area(pending_req);
349 	scsiback_do_resp_with_sense(sense_buffer, errors, resid, pending_req);
350 	scsiback_put(info);
351 	/*
352 	 * Drop the extra KREF_ACK reference taken by target_submit_cmd_map_sgls()
353 	 * ahead of scsiback_check_stop_free() ->  transport_generic_free_cmd()
354 	 * final se_cmd->cmd_kref put.
355 	 */
356 	target_put_sess_cmd(&pending_req->se_cmd);
357 }
358 
359 static void scsiback_cmd_exec(struct vscsibk_pend *pending_req)
360 {
361 	struct se_cmd *se_cmd = &pending_req->se_cmd;
362 	struct se_session *sess = pending_req->v2p->tpg->tpg_nexus->tvn_se_sess;
363 
364 	scsiback_get(pending_req->info);
365 	se_cmd->tag = pending_req->rqid;
366 	target_init_cmd(se_cmd, sess, pending_req->sense_buffer,
367 			pending_req->v2p->lun, pending_req->data_len, 0,
368 			pending_req->sc_data_direction, TARGET_SCF_ACK_KREF);
369 
370 	if (target_submit_prep(se_cmd, pending_req->cmnd, pending_req->sgl,
371 			       pending_req->n_sg, NULL, 0, NULL, 0, GFP_KERNEL))
372 		return;
373 
374 	target_submit(se_cmd);
375 }
376 
377 static int scsiback_gnttab_data_map_batch(struct gnttab_map_grant_ref *map,
378 	struct page **pg, grant_handle_t *grant, int cnt)
379 {
380 	int err, i;
381 
382 	if (!cnt)
383 		return 0;
384 
385 	err = gnttab_map_refs(map, NULL, pg, cnt);
386 	for (i = 0; i < cnt; i++) {
387 		if (unlikely(map[i].status != GNTST_okay)) {
388 			pr_err("invalid buffer -- could not remap it\n");
389 			map[i].handle = SCSIBACK_INVALID_HANDLE;
390 			if (!err)
391 				err = -ENOMEM;
392 		} else {
393 			get_page(pg[i]);
394 		}
395 		grant[i] = map[i].handle;
396 	}
397 	return err;
398 }
399 
400 static int scsiback_gnttab_data_map_list(struct vscsibk_pend *pending_req,
401 			struct scsiif_request_segment *seg, struct page **pg,
402 			grant_handle_t *grant, int cnt, u32 flags)
403 {
404 	int mapcount = 0, i, err = 0;
405 	struct gnttab_map_grant_ref map[VSCSI_GRANT_BATCH];
406 	struct vscsibk_info *info = pending_req->info;
407 
408 	for (i = 0; i < cnt; i++) {
409 		if (gnttab_page_cache_get(&info->free_pages, pg + mapcount)) {
410 			gnttab_page_cache_put(&info->free_pages, pg, mapcount);
411 			pr_err("no grant page\n");
412 			return -ENOMEM;
413 		}
414 		gnttab_set_map_op(&map[mapcount], vaddr_page(pg[mapcount]),
415 				  flags, seg[i].gref, info->domid);
416 		mapcount++;
417 		if (mapcount < VSCSI_GRANT_BATCH)
418 			continue;
419 		err = scsiback_gnttab_data_map_batch(map, pg, grant, mapcount);
420 		pg += mapcount;
421 		grant += mapcount;
422 		pending_req->n_grants += mapcount;
423 		if (err)
424 			return err;
425 		mapcount = 0;
426 	}
427 	err = scsiback_gnttab_data_map_batch(map, pg, grant, mapcount);
428 	pending_req->n_grants += mapcount;
429 	return err;
430 }
431 
432 static int scsiback_gnttab_data_map(struct vscsiif_request *ring_req,
433 					struct vscsibk_pend *pending_req)
434 {
435 	u32 flags;
436 	int i, err, n_segs, i_seg = 0;
437 	struct page **pg;
438 	struct scsiif_request_segment *seg;
439 	unsigned long end_seg = 0;
440 	unsigned int nr_segments = (unsigned int)ring_req->nr_segments;
441 	unsigned int nr_sgl = 0;
442 	struct scatterlist *sg;
443 	grant_handle_t *grant;
444 
445 	pending_req->n_sg = 0;
446 	pending_req->n_grants = 0;
447 	pending_req->data_len = 0;
448 
449 	nr_segments &= ~VSCSIIF_SG_GRANT;
450 	if (!nr_segments)
451 		return 0;
452 
453 	if (nr_segments > VSCSIIF_SG_TABLESIZE) {
454 		pr_debug("invalid parameter nr_seg = %d\n",
455 			ring_req->nr_segments);
456 		return -EINVAL;
457 	}
458 
459 	if (ring_req->nr_segments & VSCSIIF_SG_GRANT) {
460 		err = scsiback_gnttab_data_map_list(pending_req, ring_req->seg,
461 			pending_req->pages, pending_req->grant_handles,
462 			nr_segments, GNTMAP_host_map | GNTMAP_readonly);
463 		if (err)
464 			return err;
465 		nr_sgl = nr_segments;
466 		nr_segments = 0;
467 		for (i = 0; i < nr_sgl; i++) {
468 			n_segs = ring_req->seg[i].length /
469 				 sizeof(struct scsiif_request_segment);
470 			if ((unsigned)ring_req->seg[i].offset +
471 			    (unsigned)ring_req->seg[i].length > PAGE_SIZE ||
472 			    n_segs * sizeof(struct scsiif_request_segment) !=
473 			    ring_req->seg[i].length)
474 				return -EINVAL;
475 			nr_segments += n_segs;
476 		}
477 		if (nr_segments > SG_ALL) {
478 			pr_debug("invalid nr_seg = %d\n", nr_segments);
479 			return -EINVAL;
480 		}
481 	}
482 
483 	/* free of (sgl) in fast_flush_area() */
484 	pending_req->sgl = kmalloc_array(nr_segments,
485 					sizeof(struct scatterlist), GFP_KERNEL);
486 	if (!pending_req->sgl)
487 		return -ENOMEM;
488 
489 	sg_init_table(pending_req->sgl, nr_segments);
490 	pending_req->n_sg = nr_segments;
491 
492 	flags = GNTMAP_host_map;
493 	if (pending_req->sc_data_direction == DMA_TO_DEVICE)
494 		flags |= GNTMAP_readonly;
495 
496 	pg = pending_req->pages + nr_sgl;
497 	grant = pending_req->grant_handles + nr_sgl;
498 	if (!nr_sgl) {
499 		seg = ring_req->seg;
500 		err = scsiback_gnttab_data_map_list(pending_req, seg,
501 			pg, grant, nr_segments, flags);
502 		if (err)
503 			return err;
504 	} else {
505 		for (i = 0; i < nr_sgl; i++) {
506 			seg = (struct scsiif_request_segment *)(
507 			      vaddr(pending_req, i) + ring_req->seg[i].offset);
508 			n_segs = ring_req->seg[i].length /
509 				 sizeof(struct scsiif_request_segment);
510 			err = scsiback_gnttab_data_map_list(pending_req, seg,
511 				pg, grant, n_segs, flags);
512 			if (err)
513 				return err;
514 			pg += n_segs;
515 			grant += n_segs;
516 		}
517 		end_seg = vaddr(pending_req, 0) + ring_req->seg[0].offset;
518 		seg = (struct scsiif_request_segment *)end_seg;
519 		end_seg += ring_req->seg[0].length;
520 		pg = pending_req->pages + nr_sgl;
521 	}
522 
523 	for_each_sg(pending_req->sgl, sg, nr_segments, i) {
524 		sg_set_page(sg, pg[i], seg->length, seg->offset);
525 		pending_req->data_len += seg->length;
526 		seg++;
527 		if (nr_sgl && (unsigned long)seg >= end_seg) {
528 			i_seg++;
529 			end_seg = vaddr(pending_req, i_seg) +
530 				  ring_req->seg[i_seg].offset;
531 			seg = (struct scsiif_request_segment *)end_seg;
532 			end_seg += ring_req->seg[i_seg].length;
533 		}
534 		if (sg->offset >= PAGE_SIZE ||
535 		    sg->length > PAGE_SIZE ||
536 		    sg->offset + sg->length > PAGE_SIZE)
537 			return -EINVAL;
538 	}
539 
540 	return 0;
541 }
542 
543 static void scsiback_disconnect(struct vscsibk_info *info)
544 {
545 	wait_event(info->waiting_to_free,
546 		atomic_read(&info->nr_unreplied_reqs) == 0);
547 
548 	unbind_from_irqhandler(info->irq, info);
549 	info->irq = 0;
550 	xenbus_unmap_ring_vfree(info->dev, info->ring.sring);
551 }
552 
553 static void scsiback_device_action(struct vscsibk_pend *pending_req,
554 	enum tcm_tmreq_table act, int tag)
555 {
556 	struct scsiback_tpg *tpg = pending_req->v2p->tpg;
557 	struct scsiback_nexus *nexus = tpg->tpg_nexus;
558 	struct se_cmd *se_cmd = &pending_req->se_cmd;
559 	u64 unpacked_lun = pending_req->v2p->lun;
560 	int rc, err = FAILED;
561 
562 	init_completion(&pending_req->tmr_done);
563 
564 	rc = target_submit_tmr(&pending_req->se_cmd, nexus->tvn_se_sess,
565 			       &pending_req->sense_buffer[0],
566 			       unpacked_lun, NULL, act, GFP_KERNEL,
567 			       tag, TARGET_SCF_ACK_KREF);
568 	if (rc)
569 		goto err;
570 
571 	wait_for_completion(&pending_req->tmr_done);
572 
573 	err = (se_cmd->se_tmr_req->response == TMR_FUNCTION_COMPLETE) ?
574 		SUCCESS : FAILED;
575 
576 	scsiback_do_resp_with_sense(NULL, err, 0, pending_req);
577 	transport_generic_free_cmd(&pending_req->se_cmd, 0);
578 	return;
579 
580 err:
581 	scsiback_do_resp_with_sense(NULL, err, 0, pending_req);
582 }
583 
584 /*
585   Perform virtual to physical translation
586 */
587 static struct v2p_entry *scsiback_do_translation(struct vscsibk_info *info,
588 			struct ids_tuple *v)
589 {
590 	struct v2p_entry *entry;
591 	struct list_head *head = &(info->v2p_entry_lists);
592 	unsigned long flags;
593 
594 	spin_lock_irqsave(&info->v2p_lock, flags);
595 	list_for_each_entry(entry, head, l) {
596 		if ((entry->v.chn == v->chn) &&
597 		    (entry->v.tgt == v->tgt) &&
598 		    (entry->v.lun == v->lun)) {
599 			kref_get(&entry->kref);
600 			goto out;
601 		}
602 	}
603 	entry = NULL;
604 
605 out:
606 	spin_unlock_irqrestore(&info->v2p_lock, flags);
607 	return entry;
608 }
609 
610 static struct vscsibk_pend *scsiback_get_pend_req(struct vscsiif_back_ring *ring,
611 				struct v2p_entry *v2p)
612 {
613 	struct scsiback_tpg *tpg = v2p->tpg;
614 	struct scsiback_nexus *nexus = tpg->tpg_nexus;
615 	struct se_session *se_sess = nexus->tvn_se_sess;
616 	struct vscsibk_pend *req;
617 	int tag, cpu, i;
618 
619 	tag = sbitmap_queue_get(&se_sess->sess_tag_pool, &cpu);
620 	if (tag < 0) {
621 		pr_err("Unable to obtain tag for vscsiif_request\n");
622 		return ERR_PTR(-ENOMEM);
623 	}
624 
625 	req = &((struct vscsibk_pend *)se_sess->sess_cmd_map)[tag];
626 	memset(req, 0, sizeof(*req));
627 	req->se_cmd.map_tag = tag;
628 	req->se_cmd.map_cpu = cpu;
629 
630 	for (i = 0; i < VSCSI_MAX_GRANTS; i++)
631 		req->grant_handles[i] = SCSIBACK_INVALID_HANDLE;
632 
633 	return req;
634 }
635 
636 static struct vscsibk_pend *prepare_pending_reqs(struct vscsibk_info *info,
637 				struct vscsiif_back_ring *ring,
638 				struct vscsiif_request *ring_req)
639 {
640 	struct vscsibk_pend *pending_req;
641 	struct v2p_entry *v2p;
642 	struct ids_tuple vir;
643 
644 	/* request range check from frontend */
645 	if ((ring_req->sc_data_direction != DMA_BIDIRECTIONAL) &&
646 		(ring_req->sc_data_direction != DMA_TO_DEVICE) &&
647 		(ring_req->sc_data_direction != DMA_FROM_DEVICE) &&
648 		(ring_req->sc_data_direction != DMA_NONE)) {
649 		pr_debug("invalid parameter data_dir = %d\n",
650 			ring_req->sc_data_direction);
651 		return ERR_PTR(-EINVAL);
652 	}
653 	if (ring_req->cmd_len > VSCSIIF_MAX_COMMAND_SIZE) {
654 		pr_debug("invalid parameter cmd_len = %d\n",
655 			ring_req->cmd_len);
656 		return ERR_PTR(-EINVAL);
657 	}
658 
659 	vir.chn = ring_req->channel;
660 	vir.tgt = ring_req->id;
661 	vir.lun = ring_req->lun;
662 
663 	v2p = scsiback_do_translation(info, &vir);
664 	if (!v2p) {
665 		pr_debug("the v2p of (chn:%d, tgt:%d, lun:%d) doesn't exist.\n",
666 			 vir.chn, vir.tgt, vir.lun);
667 		return ERR_PTR(-ENODEV);
668 	}
669 
670 	pending_req = scsiback_get_pend_req(ring, v2p);
671 	if (IS_ERR(pending_req)) {
672 		kref_put(&v2p->kref, scsiback_free_translation_entry);
673 		return ERR_PTR(-ENOMEM);
674 	}
675 	pending_req->rqid = ring_req->rqid;
676 	pending_req->info = info;
677 	pending_req->v2p = v2p;
678 	pending_req->sc_data_direction = ring_req->sc_data_direction;
679 	pending_req->cmd_len = ring_req->cmd_len;
680 	memcpy(pending_req->cmnd, ring_req->cmnd, pending_req->cmd_len);
681 
682 	return pending_req;
683 }
684 
685 static int scsiback_do_cmd_fn(struct vscsibk_info *info,
686 			      unsigned int *eoi_flags)
687 {
688 	struct vscsiif_back_ring *ring = &info->ring;
689 	struct vscsiif_request ring_req;
690 	struct vscsibk_pend *pending_req;
691 	RING_IDX rc, rp;
692 	int more_to_do;
693 	uint32_t result;
694 
695 	rc = ring->req_cons;
696 	rp = ring->sring->req_prod;
697 	rmb();	/* guest system is accessing ring, too */
698 
699 	if (RING_REQUEST_PROD_OVERFLOW(ring, rp)) {
700 		rc = ring->rsp_prod_pvt;
701 		pr_warn("Dom%d provided bogus ring requests (%#x - %#x = %u). Halting ring processing\n",
702 			   info->domid, rp, rc, rp - rc);
703 		return -EINVAL;
704 	}
705 
706 	while ((rc != rp)) {
707 		*eoi_flags &= ~XEN_EOI_FLAG_SPURIOUS;
708 
709 		if (RING_REQUEST_CONS_OVERFLOW(ring, rc))
710 			break;
711 
712 		RING_COPY_REQUEST(ring, rc, &ring_req);
713 		ring->req_cons = ++rc;
714 
715 		pending_req = prepare_pending_reqs(info, ring, &ring_req);
716 		if (IS_ERR(pending_req)) {
717 			switch (PTR_ERR(pending_req)) {
718 			case -ENODEV:
719 				result = DID_NO_CONNECT;
720 				break;
721 			default:
722 				result = DRIVER_ERROR;
723 				break;
724 			}
725 			scsiback_send_response(info, NULL, result << 24, 0,
726 					       ring_req.rqid);
727 			return 1;
728 		}
729 
730 		switch (ring_req.act) {
731 		case VSCSIIF_ACT_SCSI_CDB:
732 			if (scsiback_gnttab_data_map(&ring_req, pending_req)) {
733 				scsiback_fast_flush_area(pending_req);
734 				scsiback_do_resp_with_sense(NULL,
735 						DRIVER_ERROR << 24, 0, pending_req);
736 				transport_generic_free_cmd(&pending_req->se_cmd, 0);
737 			} else {
738 				scsiback_cmd_exec(pending_req);
739 			}
740 			break;
741 		case VSCSIIF_ACT_SCSI_ABORT:
742 			scsiback_device_action(pending_req, TMR_ABORT_TASK,
743 				ring_req.ref_rqid);
744 			break;
745 		case VSCSIIF_ACT_SCSI_RESET:
746 			scsiback_device_action(pending_req, TMR_LUN_RESET, 0);
747 			break;
748 		default:
749 			pr_err_ratelimited("invalid request\n");
750 			scsiback_do_resp_with_sense(NULL, DRIVER_ERROR << 24, 0,
751 						    pending_req);
752 			transport_generic_free_cmd(&pending_req->se_cmd, 0);
753 			break;
754 		}
755 
756 		/* Yield point for this unbounded loop. */
757 		cond_resched();
758 	}
759 
760 	gnttab_page_cache_shrink(&info->free_pages, scsiback_max_buffer_pages);
761 
762 	RING_FINAL_CHECK_FOR_REQUESTS(&info->ring, more_to_do);
763 	return more_to_do;
764 }
765 
766 static irqreturn_t scsiback_irq_fn(int irq, void *dev_id)
767 {
768 	struct vscsibk_info *info = dev_id;
769 	int rc;
770 	unsigned int eoi_flags = XEN_EOI_FLAG_SPURIOUS;
771 
772 	while ((rc = scsiback_do_cmd_fn(info, &eoi_flags)) > 0)
773 		cond_resched();
774 
775 	/* In case of a ring error we keep the event channel masked. */
776 	if (!rc)
777 		xen_irq_lateeoi(irq, eoi_flags);
778 
779 	return IRQ_HANDLED;
780 }
781 
782 static int scsiback_init_sring(struct vscsibk_info *info, grant_ref_t ring_ref,
783 			evtchn_port_t evtchn)
784 {
785 	void *area;
786 	struct vscsiif_sring *sring;
787 	int err;
788 
789 	if (info->irq)
790 		return -1;
791 
792 	err = xenbus_map_ring_valloc(info->dev, &ring_ref, 1, &area);
793 	if (err)
794 		return err;
795 
796 	sring = (struct vscsiif_sring *)area;
797 	BACK_RING_INIT(&info->ring, sring, PAGE_SIZE);
798 
799 	err = bind_interdomain_evtchn_to_irq_lateeoi(info->dev, evtchn);
800 	if (err < 0)
801 		goto unmap_page;
802 
803 	info->irq = err;
804 
805 	err = request_threaded_irq(info->irq, NULL, scsiback_irq_fn,
806 				   IRQF_ONESHOT, "vscsiif-backend", info);
807 	if (err)
808 		goto free_irq;
809 
810 	return 0;
811 
812 free_irq:
813 	unbind_from_irqhandler(info->irq, info);
814 	info->irq = 0;
815 unmap_page:
816 	xenbus_unmap_ring_vfree(info->dev, area);
817 
818 	return err;
819 }
820 
821 static int scsiback_map(struct vscsibk_info *info)
822 {
823 	struct xenbus_device *dev = info->dev;
824 	unsigned int ring_ref;
825 	evtchn_port_t evtchn;
826 	int err;
827 
828 	err = xenbus_gather(XBT_NIL, dev->otherend,
829 			"ring-ref", "%u", &ring_ref,
830 			"event-channel", "%u", &evtchn, NULL);
831 	if (err) {
832 		xenbus_dev_fatal(dev, err, "reading %s ring", dev->otherend);
833 		return err;
834 	}
835 
836 	return scsiback_init_sring(info, ring_ref, evtchn);
837 }
838 
839 /*
840   Check for a translation entry being present
841 */
842 static struct v2p_entry *scsiback_chk_translation_entry(
843 	struct vscsibk_info *info, struct ids_tuple *v)
844 {
845 	struct list_head *head = &(info->v2p_entry_lists);
846 	struct v2p_entry *entry;
847 
848 	list_for_each_entry(entry, head, l)
849 		if ((entry->v.chn == v->chn) &&
850 		    (entry->v.tgt == v->tgt) &&
851 		    (entry->v.lun == v->lun))
852 			return entry;
853 
854 	return NULL;
855 }
856 
857 /*
858   Add a new translation entry
859 */
860 static int scsiback_add_translation_entry(struct vscsibk_info *info,
861 					  char *phy, struct ids_tuple *v)
862 {
863 	int err = 0;
864 	struct v2p_entry *new;
865 	unsigned long flags;
866 	char *lunp;
867 	unsigned long long unpacked_lun;
868 	struct se_lun *se_lun;
869 	struct scsiback_tpg *tpg_entry, *tpg = NULL;
870 	char *error = "doesn't exist";
871 
872 	lunp = strrchr(phy, ':');
873 	if (!lunp) {
874 		pr_err("illegal format of physical device %s\n", phy);
875 		return -EINVAL;
876 	}
877 	*lunp = 0;
878 	lunp++;
879 	err = kstrtoull(lunp, 10, &unpacked_lun);
880 	if (err < 0) {
881 		pr_err("lun number not valid: %s\n", lunp);
882 		return err;
883 	}
884 
885 	mutex_lock(&scsiback_mutex);
886 	list_for_each_entry(tpg_entry, &scsiback_list, tv_tpg_list) {
887 		if (!strcmp(phy, tpg_entry->tport->tport_name) ||
888 		    !strcmp(phy, tpg_entry->param_alias)) {
889 			mutex_lock(&tpg_entry->se_tpg.tpg_lun_mutex);
890 			hlist_for_each_entry(se_lun, &tpg_entry->se_tpg.tpg_lun_hlist, link) {
891 				if (se_lun->unpacked_lun == unpacked_lun) {
892 					if (!tpg_entry->tpg_nexus)
893 						error = "nexus undefined";
894 					else
895 						tpg = tpg_entry;
896 					break;
897 				}
898 			}
899 			mutex_unlock(&tpg_entry->se_tpg.tpg_lun_mutex);
900 			break;
901 		}
902 	}
903 	if (tpg) {
904 		mutex_lock(&tpg->tv_tpg_mutex);
905 		tpg->tv_tpg_fe_count++;
906 		mutex_unlock(&tpg->tv_tpg_mutex);
907 	}
908 	mutex_unlock(&scsiback_mutex);
909 
910 	if (!tpg) {
911 		pr_err("%s:%llu %s\n", phy, unpacked_lun, error);
912 		return -ENODEV;
913 	}
914 
915 	new = kmalloc(sizeof(struct v2p_entry), GFP_KERNEL);
916 	if (new == NULL) {
917 		err = -ENOMEM;
918 		goto out_free;
919 	}
920 
921 	spin_lock_irqsave(&info->v2p_lock, flags);
922 
923 	/* Check double assignment to identical virtual ID */
924 	if (scsiback_chk_translation_entry(info, v)) {
925 		pr_warn("Virtual ID is already used. Assignment was not performed.\n");
926 		err = -EEXIST;
927 		goto out;
928 	}
929 
930 	/* Create a new translation entry and add to the list */
931 	kref_init(&new->kref);
932 	new->v = *v;
933 	new->tpg = tpg;
934 	new->lun = unpacked_lun;
935 	list_add_tail(&new->l, &info->v2p_entry_lists);
936 
937 out:
938 	spin_unlock_irqrestore(&info->v2p_lock, flags);
939 
940 out_free:
941 	if (err) {
942 		mutex_lock(&tpg->tv_tpg_mutex);
943 		tpg->tv_tpg_fe_count--;
944 		mutex_unlock(&tpg->tv_tpg_mutex);
945 		kfree(new);
946 	}
947 
948 	return err;
949 }
950 
951 static void __scsiback_del_translation_entry(struct v2p_entry *entry)
952 {
953 	list_del(&entry->l);
954 	kref_put(&entry->kref, scsiback_free_translation_entry);
955 }
956 
957 /*
958   Delete the translation entry specified
959 */
960 static int scsiback_del_translation_entry(struct vscsibk_info *info,
961 					  struct ids_tuple *v)
962 {
963 	struct v2p_entry *entry;
964 	unsigned long flags;
965 	int ret = 0;
966 
967 	spin_lock_irqsave(&info->v2p_lock, flags);
968 	/* Find out the translation entry specified */
969 	entry = scsiback_chk_translation_entry(info, v);
970 	if (entry)
971 		__scsiback_del_translation_entry(entry);
972 	else
973 		ret = -ENOENT;
974 
975 	spin_unlock_irqrestore(&info->v2p_lock, flags);
976 	return ret;
977 }
978 
979 static void scsiback_do_add_lun(struct vscsibk_info *info, const char *state,
980 				char *phy, struct ids_tuple *vir, int try)
981 {
982 	struct v2p_entry *entry;
983 	unsigned long flags;
984 	int err;
985 
986 	if (try) {
987 		spin_lock_irqsave(&info->v2p_lock, flags);
988 		entry = scsiback_chk_translation_entry(info, vir);
989 		spin_unlock_irqrestore(&info->v2p_lock, flags);
990 		if (entry)
991 			return;
992 	}
993 	if (!scsiback_add_translation_entry(info, phy, vir)) {
994 		if (xenbus_printf(XBT_NIL, info->dev->nodename, state,
995 				  "%d", XenbusStateInitialised)) {
996 			pr_err("xenbus_printf error %s\n", state);
997 			scsiback_del_translation_entry(info, vir);
998 		}
999 	} else if (!try) {
1000 		err = xenbus_printf(XBT_NIL, info->dev->nodename, state,
1001 			      "%d", XenbusStateClosed);
1002 		if (err)
1003 			xenbus_dev_error(info->dev, err,
1004 				"%s: writing %s", __func__, state);
1005 	}
1006 }
1007 
1008 static void scsiback_do_del_lun(struct vscsibk_info *info, const char *state,
1009 				struct ids_tuple *vir)
1010 {
1011 	if (!scsiback_del_translation_entry(info, vir)) {
1012 		if (xenbus_printf(XBT_NIL, info->dev->nodename, state,
1013 				  "%d", XenbusStateClosed))
1014 			pr_err("xenbus_printf error %s\n", state);
1015 	}
1016 }
1017 
1018 #define VSCSIBACK_OP_ADD_OR_DEL_LUN	1
1019 #define VSCSIBACK_OP_UPDATEDEV_STATE	2
1020 
1021 static void scsiback_do_1lun_hotplug(struct vscsibk_info *info, int op,
1022 				     char *ent)
1023 {
1024 	int err;
1025 	struct ids_tuple vir;
1026 	char *val;
1027 	int device_state;
1028 	char phy[VSCSI_NAMELEN];
1029 	char str[64];
1030 	char state[64];
1031 	struct xenbus_device *dev = info->dev;
1032 
1033 	/* read status */
1034 	snprintf(state, sizeof(state), "vscsi-devs/%s/state", ent);
1035 	err = xenbus_scanf(XBT_NIL, dev->nodename, state, "%u", &device_state);
1036 	if (XENBUS_EXIST_ERR(err))
1037 		return;
1038 
1039 	/* physical SCSI device */
1040 	snprintf(str, sizeof(str), "vscsi-devs/%s/p-dev", ent);
1041 	val = xenbus_read(XBT_NIL, dev->nodename, str, NULL);
1042 	if (IS_ERR(val)) {
1043 		err = xenbus_printf(XBT_NIL, dev->nodename, state,
1044 			      "%d", XenbusStateClosed);
1045 		if (err)
1046 			xenbus_dev_error(info->dev, err,
1047 				"%s: writing %s", __func__, state);
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 		err = xenbus_printf(XBT_NIL, dev->nodename, state,
1059 			      "%d", XenbusStateClosed);
1060 		if (err)
1061 			xenbus_dev_error(info->dev, err,
1062 				"%s: writing %s", __func__, state);
1063 		return;
1064 	}
1065 
1066 	switch (op) {
1067 	case VSCSIBACK_OP_ADD_OR_DEL_LUN:
1068 		switch (device_state) {
1069 		case XenbusStateInitialising:
1070 			scsiback_do_add_lun(info, state, phy, &vir, 0);
1071 			break;
1072 		case XenbusStateConnected:
1073 			scsiback_do_add_lun(info, state, phy, &vir, 1);
1074 			break;
1075 		case XenbusStateClosing:
1076 			scsiback_do_del_lun(info, state, &vir);
1077 			break;
1078 		default:
1079 			break;
1080 		}
1081 		break;
1082 
1083 	case VSCSIBACK_OP_UPDATEDEV_STATE:
1084 		if (device_state == XenbusStateInitialised) {
1085 			/* modify vscsi-devs/dev-x/state */
1086 			if (xenbus_printf(XBT_NIL, dev->nodename, state,
1087 					  "%d", XenbusStateConnected)) {
1088 				pr_err("xenbus_printf error %s\n", str);
1089 				scsiback_del_translation_entry(info, &vir);
1090 				xenbus_printf(XBT_NIL, dev->nodename, state,
1091 					      "%d", XenbusStateClosed);
1092 			}
1093 		}
1094 		break;
1095 	/* When it is necessary, processing is added here. */
1096 	default:
1097 		break;
1098 	}
1099 }
1100 
1101 static void scsiback_do_lun_hotplug(struct vscsibk_info *info, int op)
1102 {
1103 	int i;
1104 	char **dir;
1105 	unsigned int ndir = 0;
1106 
1107 	dir = xenbus_directory(XBT_NIL, info->dev->nodename, "vscsi-devs",
1108 			       &ndir);
1109 	if (IS_ERR(dir))
1110 		return;
1111 
1112 	for (i = 0; i < ndir; i++)
1113 		scsiback_do_1lun_hotplug(info, op, dir[i]);
1114 
1115 	kfree(dir);
1116 }
1117 
1118 static void scsiback_frontend_changed(struct xenbus_device *dev,
1119 					enum xenbus_state frontend_state)
1120 {
1121 	struct vscsibk_info *info = dev_get_drvdata(&dev->dev);
1122 
1123 	switch (frontend_state) {
1124 	case XenbusStateInitialising:
1125 		break;
1126 
1127 	case XenbusStateInitialised:
1128 		if (scsiback_map(info))
1129 			break;
1130 
1131 		scsiback_do_lun_hotplug(info, VSCSIBACK_OP_ADD_OR_DEL_LUN);
1132 		xenbus_switch_state(dev, XenbusStateConnected);
1133 		break;
1134 
1135 	case XenbusStateConnected:
1136 		scsiback_do_lun_hotplug(info, VSCSIBACK_OP_UPDATEDEV_STATE);
1137 
1138 		if (dev->state == XenbusStateConnected)
1139 			break;
1140 
1141 		xenbus_switch_state(dev, XenbusStateConnected);
1142 		break;
1143 
1144 	case XenbusStateClosing:
1145 		if (info->irq)
1146 			scsiback_disconnect(info);
1147 
1148 		xenbus_switch_state(dev, XenbusStateClosing);
1149 		break;
1150 
1151 	case XenbusStateClosed:
1152 		xenbus_switch_state(dev, XenbusStateClosed);
1153 		if (xenbus_dev_is_online(dev))
1154 			break;
1155 		fallthrough;	/* if not online */
1156 	case XenbusStateUnknown:
1157 		device_unregister(&dev->dev);
1158 		break;
1159 
1160 	case XenbusStateReconfiguring:
1161 		scsiback_do_lun_hotplug(info, VSCSIBACK_OP_ADD_OR_DEL_LUN);
1162 		xenbus_switch_state(dev, XenbusStateReconfigured);
1163 
1164 		break;
1165 
1166 	default:
1167 		xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
1168 					frontend_state);
1169 		break;
1170 	}
1171 }
1172 
1173 /*
1174   Release the translation entry specfied
1175 */
1176 static void scsiback_release_translation_entry(struct vscsibk_info *info)
1177 {
1178 	struct v2p_entry *entry, *tmp;
1179 	struct list_head *head = &(info->v2p_entry_lists);
1180 	unsigned long flags;
1181 
1182 	spin_lock_irqsave(&info->v2p_lock, flags);
1183 
1184 	list_for_each_entry_safe(entry, tmp, head, l)
1185 		__scsiback_del_translation_entry(entry);
1186 
1187 	spin_unlock_irqrestore(&info->v2p_lock, flags);
1188 }
1189 
1190 static int scsiback_remove(struct xenbus_device *dev)
1191 {
1192 	struct vscsibk_info *info = dev_get_drvdata(&dev->dev);
1193 
1194 	if (info->irq)
1195 		scsiback_disconnect(info);
1196 
1197 	scsiback_release_translation_entry(info);
1198 
1199 	gnttab_page_cache_shrink(&info->free_pages, 0);
1200 
1201 	dev_set_drvdata(&dev->dev, NULL);
1202 
1203 	return 0;
1204 }
1205 
1206 static int scsiback_probe(struct xenbus_device *dev,
1207 			   const struct xenbus_device_id *id)
1208 {
1209 	int err;
1210 
1211 	struct vscsibk_info *info = kzalloc(sizeof(struct vscsibk_info),
1212 					    GFP_KERNEL);
1213 
1214 	pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
1215 
1216 	if (!info) {
1217 		xenbus_dev_fatal(dev, -ENOMEM, "allocating backend structure");
1218 		return -ENOMEM;
1219 	}
1220 	info->dev = dev;
1221 	dev_set_drvdata(&dev->dev, info);
1222 
1223 	info->domid = dev->otherend_id;
1224 	spin_lock_init(&info->ring_lock);
1225 	atomic_set(&info->nr_unreplied_reqs, 0);
1226 	init_waitqueue_head(&info->waiting_to_free);
1227 	info->dev = dev;
1228 	info->irq = 0;
1229 	INIT_LIST_HEAD(&info->v2p_entry_lists);
1230 	spin_lock_init(&info->v2p_lock);
1231 	gnttab_page_cache_init(&info->free_pages);
1232 
1233 	err = xenbus_printf(XBT_NIL, dev->nodename, "feature-sg-grant", "%u",
1234 			    SG_ALL);
1235 	if (err)
1236 		xenbus_dev_error(dev, err, "writing feature-sg-grant");
1237 
1238 	err = xenbus_switch_state(dev, XenbusStateInitWait);
1239 	if (err)
1240 		goto fail;
1241 
1242 	return 0;
1243 
1244 fail:
1245 	pr_warn("%s failed\n", __func__);
1246 	scsiback_remove(dev);
1247 
1248 	return err;
1249 }
1250 
1251 static char *scsiback_dump_proto_id(struct scsiback_tport *tport)
1252 {
1253 	switch (tport->tport_proto_id) {
1254 	case SCSI_PROTOCOL_SAS:
1255 		return "SAS";
1256 	case SCSI_PROTOCOL_FCP:
1257 		return "FCP";
1258 	case SCSI_PROTOCOL_ISCSI:
1259 		return "iSCSI";
1260 	default:
1261 		break;
1262 	}
1263 
1264 	return "Unknown";
1265 }
1266 
1267 static char *scsiback_get_fabric_wwn(struct se_portal_group *se_tpg)
1268 {
1269 	struct scsiback_tpg *tpg = container_of(se_tpg,
1270 				struct scsiback_tpg, se_tpg);
1271 	struct scsiback_tport *tport = tpg->tport;
1272 
1273 	return &tport->tport_name[0];
1274 }
1275 
1276 static u16 scsiback_get_tag(struct se_portal_group *se_tpg)
1277 {
1278 	struct scsiback_tpg *tpg = container_of(se_tpg,
1279 				struct scsiback_tpg, se_tpg);
1280 	return tpg->tport_tpgt;
1281 }
1282 
1283 static struct se_wwn *
1284 scsiback_make_tport(struct target_fabric_configfs *tf,
1285 		     struct config_group *group,
1286 		     const char *name)
1287 {
1288 	struct scsiback_tport *tport;
1289 	char *ptr;
1290 	u64 wwpn = 0;
1291 	int off = 0;
1292 
1293 	tport = kzalloc(sizeof(struct scsiback_tport), GFP_KERNEL);
1294 	if (!tport)
1295 		return ERR_PTR(-ENOMEM);
1296 
1297 	tport->tport_wwpn = wwpn;
1298 	/*
1299 	 * Determine the emulated Protocol Identifier and Target Port Name
1300 	 * based on the incoming configfs directory name.
1301 	 */
1302 	ptr = strstr(name, "naa.");
1303 	if (ptr) {
1304 		tport->tport_proto_id = SCSI_PROTOCOL_SAS;
1305 		goto check_len;
1306 	}
1307 	ptr = strstr(name, "fc.");
1308 	if (ptr) {
1309 		tport->tport_proto_id = SCSI_PROTOCOL_FCP;
1310 		off = 3; /* Skip over "fc." */
1311 		goto check_len;
1312 	}
1313 	ptr = strstr(name, "iqn.");
1314 	if (ptr) {
1315 		tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
1316 		goto check_len;
1317 	}
1318 
1319 	pr_err("Unable to locate prefix for emulated Target Port: %s\n", name);
1320 	kfree(tport);
1321 	return ERR_PTR(-EINVAL);
1322 
1323 check_len:
1324 	if (strlen(name) >= VSCSI_NAMELEN) {
1325 		pr_err("Emulated %s Address: %s, exceeds max: %d\n", name,
1326 			scsiback_dump_proto_id(tport), VSCSI_NAMELEN);
1327 		kfree(tport);
1328 		return ERR_PTR(-EINVAL);
1329 	}
1330 	snprintf(&tport->tport_name[0], VSCSI_NAMELEN, "%s", &name[off]);
1331 
1332 	pr_debug("Allocated emulated Target %s Address: %s\n",
1333 		 scsiback_dump_proto_id(tport), name);
1334 
1335 	return &tport->tport_wwn;
1336 }
1337 
1338 static void scsiback_drop_tport(struct se_wwn *wwn)
1339 {
1340 	struct scsiback_tport *tport = container_of(wwn,
1341 				struct scsiback_tport, tport_wwn);
1342 
1343 	pr_debug("Deallocating emulated Target %s Address: %s\n",
1344 		 scsiback_dump_proto_id(tport), tport->tport_name);
1345 
1346 	kfree(tport);
1347 }
1348 
1349 static u32 scsiback_tpg_get_inst_index(struct se_portal_group *se_tpg)
1350 {
1351 	return 1;
1352 }
1353 
1354 static int scsiback_check_stop_free(struct se_cmd *se_cmd)
1355 {
1356 	return transport_generic_free_cmd(se_cmd, 0);
1357 }
1358 
1359 static void scsiback_release_cmd(struct se_cmd *se_cmd)
1360 {
1361 	target_free_tag(se_cmd->se_sess, se_cmd);
1362 }
1363 
1364 static u32 scsiback_sess_get_index(struct se_session *se_sess)
1365 {
1366 	return 0;
1367 }
1368 
1369 static int scsiback_write_pending(struct se_cmd *se_cmd)
1370 {
1371 	/* Go ahead and process the write immediately */
1372 	target_execute_cmd(se_cmd);
1373 
1374 	return 0;
1375 }
1376 
1377 static void scsiback_set_default_node_attrs(struct se_node_acl *nacl)
1378 {
1379 }
1380 
1381 static int scsiback_get_cmd_state(struct se_cmd *se_cmd)
1382 {
1383 	return 0;
1384 }
1385 
1386 static int scsiback_queue_data_in(struct se_cmd *se_cmd)
1387 {
1388 	struct vscsibk_pend *pending_req = container_of(se_cmd,
1389 				struct vscsibk_pend, se_cmd);
1390 
1391 	pending_req->result = SAM_STAT_GOOD;
1392 	scsiback_cmd_done(pending_req);
1393 	return 0;
1394 }
1395 
1396 static int scsiback_queue_status(struct se_cmd *se_cmd)
1397 {
1398 	struct vscsibk_pend *pending_req = container_of(se_cmd,
1399 				struct vscsibk_pend, se_cmd);
1400 
1401 	if (se_cmd->sense_buffer &&
1402 	    ((se_cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ||
1403 	     (se_cmd->se_cmd_flags & SCF_EMULATED_TASK_SENSE)))
1404 		pending_req->result = (DRIVER_SENSE << 24) |
1405 				      SAM_STAT_CHECK_CONDITION;
1406 	else
1407 		pending_req->result = se_cmd->scsi_status;
1408 
1409 	scsiback_cmd_done(pending_req);
1410 	return 0;
1411 }
1412 
1413 static void scsiback_queue_tm_rsp(struct se_cmd *se_cmd)
1414 {
1415 	struct vscsibk_pend *pending_req = container_of(se_cmd,
1416 				struct vscsibk_pend, se_cmd);
1417 
1418 	complete(&pending_req->tmr_done);
1419 }
1420 
1421 static void scsiback_aborted_task(struct se_cmd *se_cmd)
1422 {
1423 }
1424 
1425 static ssize_t scsiback_tpg_param_alias_show(struct config_item *item,
1426 					     char *page)
1427 {
1428 	struct se_portal_group *se_tpg = param_to_tpg(item);
1429 	struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1430 						se_tpg);
1431 	ssize_t rb;
1432 
1433 	mutex_lock(&tpg->tv_tpg_mutex);
1434 	rb = snprintf(page, PAGE_SIZE, "%s\n", tpg->param_alias);
1435 	mutex_unlock(&tpg->tv_tpg_mutex);
1436 
1437 	return rb;
1438 }
1439 
1440 static ssize_t scsiback_tpg_param_alias_store(struct config_item *item,
1441 					      const char *page, size_t count)
1442 {
1443 	struct se_portal_group *se_tpg = param_to_tpg(item);
1444 	struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1445 						se_tpg);
1446 	int len;
1447 
1448 	if (strlen(page) >= VSCSI_NAMELEN) {
1449 		pr_err("param alias: %s, exceeds max: %d\n", page,
1450 			VSCSI_NAMELEN);
1451 		return -EINVAL;
1452 	}
1453 
1454 	mutex_lock(&tpg->tv_tpg_mutex);
1455 	len = snprintf(tpg->param_alias, VSCSI_NAMELEN, "%s", page);
1456 	if (tpg->param_alias[len - 1] == '\n')
1457 		tpg->param_alias[len - 1] = '\0';
1458 	mutex_unlock(&tpg->tv_tpg_mutex);
1459 
1460 	return count;
1461 }
1462 
1463 CONFIGFS_ATTR(scsiback_tpg_param_, alias);
1464 
1465 static struct configfs_attribute *scsiback_param_attrs[] = {
1466 	&scsiback_tpg_param_attr_alias,
1467 	NULL,
1468 };
1469 
1470 static int scsiback_alloc_sess_cb(struct se_portal_group *se_tpg,
1471 				  struct se_session *se_sess, void *p)
1472 {
1473 	struct scsiback_tpg *tpg = container_of(se_tpg,
1474 				struct scsiback_tpg, se_tpg);
1475 
1476 	tpg->tpg_nexus = p;
1477 	return 0;
1478 }
1479 
1480 static int scsiback_make_nexus(struct scsiback_tpg *tpg,
1481 				const char *name)
1482 {
1483 	struct scsiback_nexus *tv_nexus;
1484 	int ret = 0;
1485 
1486 	mutex_lock(&tpg->tv_tpg_mutex);
1487 	if (tpg->tpg_nexus) {
1488 		pr_debug("tpg->tpg_nexus already exists\n");
1489 		ret = -EEXIST;
1490 		goto out_unlock;
1491 	}
1492 
1493 	tv_nexus = kzalloc(sizeof(struct scsiback_nexus), GFP_KERNEL);
1494 	if (!tv_nexus) {
1495 		ret = -ENOMEM;
1496 		goto out_unlock;
1497 	}
1498 
1499 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1500 						     VSCSI_DEFAULT_SESSION_TAGS,
1501 						     sizeof(struct vscsibk_pend),
1502 						     TARGET_PROT_NORMAL, name,
1503 						     tv_nexus, scsiback_alloc_sess_cb);
1504 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1505 		kfree(tv_nexus);
1506 		ret = -ENOMEM;
1507 		goto out_unlock;
1508 	}
1509 
1510 out_unlock:
1511 	mutex_unlock(&tpg->tv_tpg_mutex);
1512 	return ret;
1513 }
1514 
1515 static int scsiback_drop_nexus(struct scsiback_tpg *tpg)
1516 {
1517 	struct se_session *se_sess;
1518 	struct scsiback_nexus *tv_nexus;
1519 
1520 	mutex_lock(&tpg->tv_tpg_mutex);
1521 	tv_nexus = tpg->tpg_nexus;
1522 	if (!tv_nexus) {
1523 		mutex_unlock(&tpg->tv_tpg_mutex);
1524 		return -ENODEV;
1525 	}
1526 
1527 	se_sess = tv_nexus->tvn_se_sess;
1528 	if (!se_sess) {
1529 		mutex_unlock(&tpg->tv_tpg_mutex);
1530 		return -ENODEV;
1531 	}
1532 
1533 	if (tpg->tv_tpg_port_count != 0) {
1534 		mutex_unlock(&tpg->tv_tpg_mutex);
1535 		pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG port count: %d\n",
1536 			tpg->tv_tpg_port_count);
1537 		return -EBUSY;
1538 	}
1539 
1540 	if (tpg->tv_tpg_fe_count != 0) {
1541 		mutex_unlock(&tpg->tv_tpg_mutex);
1542 		pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG frontend count: %d\n",
1543 			tpg->tv_tpg_fe_count);
1544 		return -EBUSY;
1545 	}
1546 
1547 	pr_debug("Removing I_T Nexus to emulated %s Initiator Port: %s\n",
1548 		scsiback_dump_proto_id(tpg->tport),
1549 		tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1550 
1551 	/*
1552 	 * Release the SCSI I_T Nexus to the emulated xen-pvscsi Target Port
1553 	 */
1554 	target_remove_session(se_sess);
1555 	tpg->tpg_nexus = NULL;
1556 	mutex_unlock(&tpg->tv_tpg_mutex);
1557 
1558 	kfree(tv_nexus);
1559 	return 0;
1560 }
1561 
1562 static ssize_t scsiback_tpg_nexus_show(struct config_item *item, char *page)
1563 {
1564 	struct se_portal_group *se_tpg = to_tpg(item);
1565 	struct scsiback_tpg *tpg = container_of(se_tpg,
1566 				struct scsiback_tpg, se_tpg);
1567 	struct scsiback_nexus *tv_nexus;
1568 	ssize_t ret;
1569 
1570 	mutex_lock(&tpg->tv_tpg_mutex);
1571 	tv_nexus = tpg->tpg_nexus;
1572 	if (!tv_nexus) {
1573 		mutex_unlock(&tpg->tv_tpg_mutex);
1574 		return -ENODEV;
1575 	}
1576 	ret = snprintf(page, PAGE_SIZE, "%s\n",
1577 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1578 	mutex_unlock(&tpg->tv_tpg_mutex);
1579 
1580 	return ret;
1581 }
1582 
1583 static ssize_t scsiback_tpg_nexus_store(struct config_item *item,
1584 		const char *page, size_t count)
1585 {
1586 	struct se_portal_group *se_tpg = to_tpg(item);
1587 	struct scsiback_tpg *tpg = container_of(se_tpg,
1588 				struct scsiback_tpg, se_tpg);
1589 	struct scsiback_tport *tport_wwn = tpg->tport;
1590 	unsigned char i_port[VSCSI_NAMELEN], *ptr, *port_ptr;
1591 	int ret;
1592 	/*
1593 	 * Shutdown the active I_T nexus if 'NULL' is passed.
1594 	 */
1595 	if (!strncmp(page, "NULL", 4)) {
1596 		ret = scsiback_drop_nexus(tpg);
1597 		return (!ret) ? count : ret;
1598 	}
1599 	/*
1600 	 * Otherwise make sure the passed virtual Initiator port WWN matches
1601 	 * the fabric protocol_id set in scsiback_make_tport(), and call
1602 	 * scsiback_make_nexus().
1603 	 */
1604 	if (strlen(page) >= VSCSI_NAMELEN) {
1605 		pr_err("Emulated NAA Sas Address: %s, exceeds max: %d\n",
1606 			page, VSCSI_NAMELEN);
1607 		return -EINVAL;
1608 	}
1609 	snprintf(&i_port[0], VSCSI_NAMELEN, "%s", page);
1610 
1611 	ptr = strstr(i_port, "naa.");
1612 	if (ptr) {
1613 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
1614 			pr_err("Passed SAS Initiator Port %s does not match target port protoid: %s\n",
1615 				i_port, scsiback_dump_proto_id(tport_wwn));
1616 			return -EINVAL;
1617 		}
1618 		port_ptr = &i_port[0];
1619 		goto check_newline;
1620 	}
1621 	ptr = strstr(i_port, "fc.");
1622 	if (ptr) {
1623 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
1624 			pr_err("Passed FCP Initiator Port %s does not match target port protoid: %s\n",
1625 				i_port, scsiback_dump_proto_id(tport_wwn));
1626 			return -EINVAL;
1627 		}
1628 		port_ptr = &i_port[3]; /* Skip over "fc." */
1629 		goto check_newline;
1630 	}
1631 	ptr = strstr(i_port, "iqn.");
1632 	if (ptr) {
1633 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
1634 			pr_err("Passed iSCSI Initiator Port %s does not match target port protoid: %s\n",
1635 				i_port, scsiback_dump_proto_id(tport_wwn));
1636 			return -EINVAL;
1637 		}
1638 		port_ptr = &i_port[0];
1639 		goto check_newline;
1640 	}
1641 	pr_err("Unable to locate prefix for emulated Initiator Port: %s\n",
1642 		i_port);
1643 	return -EINVAL;
1644 	/*
1645 	 * Clear any trailing newline for the NAA WWN
1646 	 */
1647 check_newline:
1648 	if (i_port[strlen(i_port) - 1] == '\n')
1649 		i_port[strlen(i_port) - 1] = '\0';
1650 
1651 	ret = scsiback_make_nexus(tpg, port_ptr);
1652 	if (ret < 0)
1653 		return ret;
1654 
1655 	return count;
1656 }
1657 
1658 CONFIGFS_ATTR(scsiback_tpg_, nexus);
1659 
1660 static struct configfs_attribute *scsiback_tpg_attrs[] = {
1661 	&scsiback_tpg_attr_nexus,
1662 	NULL,
1663 };
1664 
1665 static ssize_t
1666 scsiback_wwn_version_show(struct config_item *item, char *page)
1667 {
1668 	return sprintf(page, "xen-pvscsi fabric module %s on %s/%s on "
1669 		UTS_RELEASE"\n",
1670 		VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1671 }
1672 
1673 CONFIGFS_ATTR_RO(scsiback_wwn_, version);
1674 
1675 static struct configfs_attribute *scsiback_wwn_attrs[] = {
1676 	&scsiback_wwn_attr_version,
1677 	NULL,
1678 };
1679 
1680 static int scsiback_port_link(struct se_portal_group *se_tpg,
1681 			       struct se_lun *lun)
1682 {
1683 	struct scsiback_tpg *tpg = container_of(se_tpg,
1684 				struct scsiback_tpg, se_tpg);
1685 
1686 	mutex_lock(&tpg->tv_tpg_mutex);
1687 	tpg->tv_tpg_port_count++;
1688 	mutex_unlock(&tpg->tv_tpg_mutex);
1689 
1690 	return 0;
1691 }
1692 
1693 static void scsiback_port_unlink(struct se_portal_group *se_tpg,
1694 				  struct se_lun *lun)
1695 {
1696 	struct scsiback_tpg *tpg = container_of(se_tpg,
1697 				struct scsiback_tpg, se_tpg);
1698 
1699 	mutex_lock(&tpg->tv_tpg_mutex);
1700 	tpg->tv_tpg_port_count--;
1701 	mutex_unlock(&tpg->tv_tpg_mutex);
1702 }
1703 
1704 static struct se_portal_group *
1705 scsiback_make_tpg(struct se_wwn *wwn, const char *name)
1706 {
1707 	struct scsiback_tport *tport = container_of(wwn,
1708 			struct scsiback_tport, tport_wwn);
1709 
1710 	struct scsiback_tpg *tpg;
1711 	u16 tpgt;
1712 	int ret;
1713 
1714 	if (strstr(name, "tpgt_") != name)
1715 		return ERR_PTR(-EINVAL);
1716 	ret = kstrtou16(name + 5, 10, &tpgt);
1717 	if (ret)
1718 		return ERR_PTR(ret);
1719 
1720 	tpg = kzalloc(sizeof(struct scsiback_tpg), GFP_KERNEL);
1721 	if (!tpg)
1722 		return ERR_PTR(-ENOMEM);
1723 
1724 	mutex_init(&tpg->tv_tpg_mutex);
1725 	INIT_LIST_HEAD(&tpg->tv_tpg_list);
1726 	INIT_LIST_HEAD(&tpg->info_list);
1727 	tpg->tport = tport;
1728 	tpg->tport_tpgt = tpgt;
1729 
1730 	ret = core_tpg_register(wwn, &tpg->se_tpg, tport->tport_proto_id);
1731 	if (ret < 0) {
1732 		kfree(tpg);
1733 		return NULL;
1734 	}
1735 	mutex_lock(&scsiback_mutex);
1736 	list_add_tail(&tpg->tv_tpg_list, &scsiback_list);
1737 	mutex_unlock(&scsiback_mutex);
1738 
1739 	return &tpg->se_tpg;
1740 }
1741 
1742 static void scsiback_drop_tpg(struct se_portal_group *se_tpg)
1743 {
1744 	struct scsiback_tpg *tpg = container_of(se_tpg,
1745 				struct scsiback_tpg, se_tpg);
1746 
1747 	mutex_lock(&scsiback_mutex);
1748 	list_del(&tpg->tv_tpg_list);
1749 	mutex_unlock(&scsiback_mutex);
1750 	/*
1751 	 * Release the virtual I_T Nexus for this xen-pvscsi TPG
1752 	 */
1753 	scsiback_drop_nexus(tpg);
1754 	/*
1755 	 * Deregister the se_tpg from TCM.
1756 	 */
1757 	core_tpg_deregister(se_tpg);
1758 	kfree(tpg);
1759 }
1760 
1761 static int scsiback_check_true(struct se_portal_group *se_tpg)
1762 {
1763 	return 1;
1764 }
1765 
1766 static int scsiback_check_false(struct se_portal_group *se_tpg)
1767 {
1768 	return 0;
1769 }
1770 
1771 static const struct target_core_fabric_ops scsiback_ops = {
1772 	.module				= THIS_MODULE,
1773 	.fabric_name			= "xen-pvscsi",
1774 	.tpg_get_wwn			= scsiback_get_fabric_wwn,
1775 	.tpg_get_tag			= scsiback_get_tag,
1776 	.tpg_check_demo_mode		= scsiback_check_true,
1777 	.tpg_check_demo_mode_cache	= scsiback_check_true,
1778 	.tpg_check_demo_mode_write_protect = scsiback_check_false,
1779 	.tpg_check_prod_mode_write_protect = scsiback_check_false,
1780 	.tpg_get_inst_index		= scsiback_tpg_get_inst_index,
1781 	.check_stop_free		= scsiback_check_stop_free,
1782 	.release_cmd			= scsiback_release_cmd,
1783 	.sess_get_index			= scsiback_sess_get_index,
1784 	.sess_get_initiator_sid		= NULL,
1785 	.write_pending			= scsiback_write_pending,
1786 	.set_default_node_attributes	= scsiback_set_default_node_attrs,
1787 	.get_cmd_state			= scsiback_get_cmd_state,
1788 	.queue_data_in			= scsiback_queue_data_in,
1789 	.queue_status			= scsiback_queue_status,
1790 	.queue_tm_rsp			= scsiback_queue_tm_rsp,
1791 	.aborted_task			= scsiback_aborted_task,
1792 	/*
1793 	 * Setup callers for generic logic in target_core_fabric_configfs.c
1794 	 */
1795 	.fabric_make_wwn		= scsiback_make_tport,
1796 	.fabric_drop_wwn		= scsiback_drop_tport,
1797 	.fabric_make_tpg		= scsiback_make_tpg,
1798 	.fabric_drop_tpg		= scsiback_drop_tpg,
1799 	.fabric_post_link		= scsiback_port_link,
1800 	.fabric_pre_unlink		= scsiback_port_unlink,
1801 
1802 	.tfc_wwn_attrs			= scsiback_wwn_attrs,
1803 	.tfc_tpg_base_attrs		= scsiback_tpg_attrs,
1804 	.tfc_tpg_param_attrs		= scsiback_param_attrs,
1805 };
1806 
1807 static const struct xenbus_device_id scsiback_ids[] = {
1808 	{ "vscsi" },
1809 	{ "" }
1810 };
1811 
1812 static struct xenbus_driver scsiback_driver = {
1813 	.ids			= scsiback_ids,
1814 	.probe			= scsiback_probe,
1815 	.remove			= scsiback_remove,
1816 	.otherend_changed	= scsiback_frontend_changed
1817 };
1818 
1819 static int __init scsiback_init(void)
1820 {
1821 	int ret;
1822 
1823 	if (!xen_domain())
1824 		return -ENODEV;
1825 
1826 	pr_debug("xen-pvscsi: fabric module %s on %s/%s on "UTS_RELEASE"\n",
1827 		 VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1828 
1829 	ret = xenbus_register_backend(&scsiback_driver);
1830 	if (ret)
1831 		goto out;
1832 
1833 	ret = target_register_template(&scsiback_ops);
1834 	if (ret)
1835 		goto out_unregister_xenbus;
1836 
1837 	return 0;
1838 
1839 out_unregister_xenbus:
1840 	xenbus_unregister_driver(&scsiback_driver);
1841 out:
1842 	pr_err("%s: error %d\n", __func__, ret);
1843 	return ret;
1844 }
1845 
1846 static void __exit scsiback_exit(void)
1847 {
1848 	target_unregister_template(&scsiback_ops);
1849 	xenbus_unregister_driver(&scsiback_driver);
1850 }
1851 
1852 module_init(scsiback_init);
1853 module_exit(scsiback_exit);
1854 
1855 MODULE_DESCRIPTION("Xen SCSI backend driver");
1856 MODULE_LICENSE("Dual BSD/GPL");
1857 MODULE_ALIAS("xen-backend:vscsi");
1858 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");
1859