xref: /openbmc/linux/drivers/xen/xen-scsiback.c (revision 9659281c)
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\n",
226 	       tpg->tport->tport_name, pending_req->v2p->lun,
227 	       pending_req->cmnd[0], errors & 0xff, COMMAND_COMPLETE,
228 	       host_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 = DID_ERROR;
723 				break;
724 			}
725 			scsiback_send_response(info, NULL, result << 16, 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 						DID_ERROR << 16, 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, DID_ERROR << 16, 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 = SAM_STAT_CHECK_CONDITION;
1405 	else
1406 		pending_req->result = se_cmd->scsi_status;
1407 
1408 	scsiback_cmd_done(pending_req);
1409 	return 0;
1410 }
1411 
1412 static void scsiback_queue_tm_rsp(struct se_cmd *se_cmd)
1413 {
1414 	struct vscsibk_pend *pending_req = container_of(se_cmd,
1415 				struct vscsibk_pend, se_cmd);
1416 
1417 	complete(&pending_req->tmr_done);
1418 }
1419 
1420 static void scsiback_aborted_task(struct se_cmd *se_cmd)
1421 {
1422 }
1423 
1424 static ssize_t scsiback_tpg_param_alias_show(struct config_item *item,
1425 					     char *page)
1426 {
1427 	struct se_portal_group *se_tpg = param_to_tpg(item);
1428 	struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1429 						se_tpg);
1430 	ssize_t rb;
1431 
1432 	mutex_lock(&tpg->tv_tpg_mutex);
1433 	rb = snprintf(page, PAGE_SIZE, "%s\n", tpg->param_alias);
1434 	mutex_unlock(&tpg->tv_tpg_mutex);
1435 
1436 	return rb;
1437 }
1438 
1439 static ssize_t scsiback_tpg_param_alias_store(struct config_item *item,
1440 					      const char *page, size_t count)
1441 {
1442 	struct se_portal_group *se_tpg = param_to_tpg(item);
1443 	struct scsiback_tpg *tpg = container_of(se_tpg, struct scsiback_tpg,
1444 						se_tpg);
1445 	int len;
1446 
1447 	if (strlen(page) >= VSCSI_NAMELEN) {
1448 		pr_err("param alias: %s, exceeds max: %d\n", page,
1449 			VSCSI_NAMELEN);
1450 		return -EINVAL;
1451 	}
1452 
1453 	mutex_lock(&tpg->tv_tpg_mutex);
1454 	len = snprintf(tpg->param_alias, VSCSI_NAMELEN, "%s", page);
1455 	if (tpg->param_alias[len - 1] == '\n')
1456 		tpg->param_alias[len - 1] = '\0';
1457 	mutex_unlock(&tpg->tv_tpg_mutex);
1458 
1459 	return count;
1460 }
1461 
1462 CONFIGFS_ATTR(scsiback_tpg_param_, alias);
1463 
1464 static struct configfs_attribute *scsiback_param_attrs[] = {
1465 	&scsiback_tpg_param_attr_alias,
1466 	NULL,
1467 };
1468 
1469 static int scsiback_alloc_sess_cb(struct se_portal_group *se_tpg,
1470 				  struct se_session *se_sess, void *p)
1471 {
1472 	struct scsiback_tpg *tpg = container_of(se_tpg,
1473 				struct scsiback_tpg, se_tpg);
1474 
1475 	tpg->tpg_nexus = p;
1476 	return 0;
1477 }
1478 
1479 static int scsiback_make_nexus(struct scsiback_tpg *tpg,
1480 				const char *name)
1481 {
1482 	struct scsiback_nexus *tv_nexus;
1483 	int ret = 0;
1484 
1485 	mutex_lock(&tpg->tv_tpg_mutex);
1486 	if (tpg->tpg_nexus) {
1487 		pr_debug("tpg->tpg_nexus already exists\n");
1488 		ret = -EEXIST;
1489 		goto out_unlock;
1490 	}
1491 
1492 	tv_nexus = kzalloc(sizeof(struct scsiback_nexus), GFP_KERNEL);
1493 	if (!tv_nexus) {
1494 		ret = -ENOMEM;
1495 		goto out_unlock;
1496 	}
1497 
1498 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1499 						     VSCSI_DEFAULT_SESSION_TAGS,
1500 						     sizeof(struct vscsibk_pend),
1501 						     TARGET_PROT_NORMAL, name,
1502 						     tv_nexus, scsiback_alloc_sess_cb);
1503 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1504 		kfree(tv_nexus);
1505 		ret = -ENOMEM;
1506 		goto out_unlock;
1507 	}
1508 
1509 out_unlock:
1510 	mutex_unlock(&tpg->tv_tpg_mutex);
1511 	return ret;
1512 }
1513 
1514 static int scsiback_drop_nexus(struct scsiback_tpg *tpg)
1515 {
1516 	struct se_session *se_sess;
1517 	struct scsiback_nexus *tv_nexus;
1518 
1519 	mutex_lock(&tpg->tv_tpg_mutex);
1520 	tv_nexus = tpg->tpg_nexus;
1521 	if (!tv_nexus) {
1522 		mutex_unlock(&tpg->tv_tpg_mutex);
1523 		return -ENODEV;
1524 	}
1525 
1526 	se_sess = tv_nexus->tvn_se_sess;
1527 	if (!se_sess) {
1528 		mutex_unlock(&tpg->tv_tpg_mutex);
1529 		return -ENODEV;
1530 	}
1531 
1532 	if (tpg->tv_tpg_port_count != 0) {
1533 		mutex_unlock(&tpg->tv_tpg_mutex);
1534 		pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG port count: %d\n",
1535 			tpg->tv_tpg_port_count);
1536 		return -EBUSY;
1537 	}
1538 
1539 	if (tpg->tv_tpg_fe_count != 0) {
1540 		mutex_unlock(&tpg->tv_tpg_mutex);
1541 		pr_err("Unable to remove xen-pvscsi I_T Nexus with active TPG frontend count: %d\n",
1542 			tpg->tv_tpg_fe_count);
1543 		return -EBUSY;
1544 	}
1545 
1546 	pr_debug("Removing I_T Nexus to emulated %s Initiator Port: %s\n",
1547 		scsiback_dump_proto_id(tpg->tport),
1548 		tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1549 
1550 	/*
1551 	 * Release the SCSI I_T Nexus to the emulated xen-pvscsi Target Port
1552 	 */
1553 	target_remove_session(se_sess);
1554 	tpg->tpg_nexus = NULL;
1555 	mutex_unlock(&tpg->tv_tpg_mutex);
1556 
1557 	kfree(tv_nexus);
1558 	return 0;
1559 }
1560 
1561 static ssize_t scsiback_tpg_nexus_show(struct config_item *item, char *page)
1562 {
1563 	struct se_portal_group *se_tpg = to_tpg(item);
1564 	struct scsiback_tpg *tpg = container_of(se_tpg,
1565 				struct scsiback_tpg, se_tpg);
1566 	struct scsiback_nexus *tv_nexus;
1567 	ssize_t ret;
1568 
1569 	mutex_lock(&tpg->tv_tpg_mutex);
1570 	tv_nexus = tpg->tpg_nexus;
1571 	if (!tv_nexus) {
1572 		mutex_unlock(&tpg->tv_tpg_mutex);
1573 		return -ENODEV;
1574 	}
1575 	ret = snprintf(page, PAGE_SIZE, "%s\n",
1576 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1577 	mutex_unlock(&tpg->tv_tpg_mutex);
1578 
1579 	return ret;
1580 }
1581 
1582 static ssize_t scsiback_tpg_nexus_store(struct config_item *item,
1583 		const char *page, size_t count)
1584 {
1585 	struct se_portal_group *se_tpg = to_tpg(item);
1586 	struct scsiback_tpg *tpg = container_of(se_tpg,
1587 				struct scsiback_tpg, se_tpg);
1588 	struct scsiback_tport *tport_wwn = tpg->tport;
1589 	unsigned char i_port[VSCSI_NAMELEN], *ptr, *port_ptr;
1590 	int ret;
1591 	/*
1592 	 * Shutdown the active I_T nexus if 'NULL' is passed.
1593 	 */
1594 	if (!strncmp(page, "NULL", 4)) {
1595 		ret = scsiback_drop_nexus(tpg);
1596 		return (!ret) ? count : ret;
1597 	}
1598 	/*
1599 	 * Otherwise make sure the passed virtual Initiator port WWN matches
1600 	 * the fabric protocol_id set in scsiback_make_tport(), and call
1601 	 * scsiback_make_nexus().
1602 	 */
1603 	if (strlen(page) >= VSCSI_NAMELEN) {
1604 		pr_err("Emulated NAA Sas Address: %s, exceeds max: %d\n",
1605 			page, VSCSI_NAMELEN);
1606 		return -EINVAL;
1607 	}
1608 	snprintf(&i_port[0], VSCSI_NAMELEN, "%s", page);
1609 
1610 	ptr = strstr(i_port, "naa.");
1611 	if (ptr) {
1612 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
1613 			pr_err("Passed SAS Initiator Port %s does not match target port protoid: %s\n",
1614 				i_port, scsiback_dump_proto_id(tport_wwn));
1615 			return -EINVAL;
1616 		}
1617 		port_ptr = &i_port[0];
1618 		goto check_newline;
1619 	}
1620 	ptr = strstr(i_port, "fc.");
1621 	if (ptr) {
1622 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
1623 			pr_err("Passed FCP Initiator Port %s does not match target port protoid: %s\n",
1624 				i_port, scsiback_dump_proto_id(tport_wwn));
1625 			return -EINVAL;
1626 		}
1627 		port_ptr = &i_port[3]; /* Skip over "fc." */
1628 		goto check_newline;
1629 	}
1630 	ptr = strstr(i_port, "iqn.");
1631 	if (ptr) {
1632 		if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
1633 			pr_err("Passed iSCSI Initiator Port %s does not match target port protoid: %s\n",
1634 				i_port, scsiback_dump_proto_id(tport_wwn));
1635 			return -EINVAL;
1636 		}
1637 		port_ptr = &i_port[0];
1638 		goto check_newline;
1639 	}
1640 	pr_err("Unable to locate prefix for emulated Initiator Port: %s\n",
1641 		i_port);
1642 	return -EINVAL;
1643 	/*
1644 	 * Clear any trailing newline for the NAA WWN
1645 	 */
1646 check_newline:
1647 	if (i_port[strlen(i_port) - 1] == '\n')
1648 		i_port[strlen(i_port) - 1] = '\0';
1649 
1650 	ret = scsiback_make_nexus(tpg, port_ptr);
1651 	if (ret < 0)
1652 		return ret;
1653 
1654 	return count;
1655 }
1656 
1657 CONFIGFS_ATTR(scsiback_tpg_, nexus);
1658 
1659 static struct configfs_attribute *scsiback_tpg_attrs[] = {
1660 	&scsiback_tpg_attr_nexus,
1661 	NULL,
1662 };
1663 
1664 static ssize_t
1665 scsiback_wwn_version_show(struct config_item *item, char *page)
1666 {
1667 	return sprintf(page, "xen-pvscsi fabric module %s on %s/%s on "
1668 		UTS_RELEASE"\n",
1669 		VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1670 }
1671 
1672 CONFIGFS_ATTR_RO(scsiback_wwn_, version);
1673 
1674 static struct configfs_attribute *scsiback_wwn_attrs[] = {
1675 	&scsiback_wwn_attr_version,
1676 	NULL,
1677 };
1678 
1679 static int scsiback_port_link(struct se_portal_group *se_tpg,
1680 			       struct se_lun *lun)
1681 {
1682 	struct scsiback_tpg *tpg = container_of(se_tpg,
1683 				struct scsiback_tpg, se_tpg);
1684 
1685 	mutex_lock(&tpg->tv_tpg_mutex);
1686 	tpg->tv_tpg_port_count++;
1687 	mutex_unlock(&tpg->tv_tpg_mutex);
1688 
1689 	return 0;
1690 }
1691 
1692 static void scsiback_port_unlink(struct se_portal_group *se_tpg,
1693 				  struct se_lun *lun)
1694 {
1695 	struct scsiback_tpg *tpg = container_of(se_tpg,
1696 				struct scsiback_tpg, se_tpg);
1697 
1698 	mutex_lock(&tpg->tv_tpg_mutex);
1699 	tpg->tv_tpg_port_count--;
1700 	mutex_unlock(&tpg->tv_tpg_mutex);
1701 }
1702 
1703 static struct se_portal_group *
1704 scsiback_make_tpg(struct se_wwn *wwn, const char *name)
1705 {
1706 	struct scsiback_tport *tport = container_of(wwn,
1707 			struct scsiback_tport, tport_wwn);
1708 
1709 	struct scsiback_tpg *tpg;
1710 	u16 tpgt;
1711 	int ret;
1712 
1713 	if (strstr(name, "tpgt_") != name)
1714 		return ERR_PTR(-EINVAL);
1715 	ret = kstrtou16(name + 5, 10, &tpgt);
1716 	if (ret)
1717 		return ERR_PTR(ret);
1718 
1719 	tpg = kzalloc(sizeof(struct scsiback_tpg), GFP_KERNEL);
1720 	if (!tpg)
1721 		return ERR_PTR(-ENOMEM);
1722 
1723 	mutex_init(&tpg->tv_tpg_mutex);
1724 	INIT_LIST_HEAD(&tpg->tv_tpg_list);
1725 	INIT_LIST_HEAD(&tpg->info_list);
1726 	tpg->tport = tport;
1727 	tpg->tport_tpgt = tpgt;
1728 
1729 	ret = core_tpg_register(wwn, &tpg->se_tpg, tport->tport_proto_id);
1730 	if (ret < 0) {
1731 		kfree(tpg);
1732 		return NULL;
1733 	}
1734 	mutex_lock(&scsiback_mutex);
1735 	list_add_tail(&tpg->tv_tpg_list, &scsiback_list);
1736 	mutex_unlock(&scsiback_mutex);
1737 
1738 	return &tpg->se_tpg;
1739 }
1740 
1741 static void scsiback_drop_tpg(struct se_portal_group *se_tpg)
1742 {
1743 	struct scsiback_tpg *tpg = container_of(se_tpg,
1744 				struct scsiback_tpg, se_tpg);
1745 
1746 	mutex_lock(&scsiback_mutex);
1747 	list_del(&tpg->tv_tpg_list);
1748 	mutex_unlock(&scsiback_mutex);
1749 	/*
1750 	 * Release the virtual I_T Nexus for this xen-pvscsi TPG
1751 	 */
1752 	scsiback_drop_nexus(tpg);
1753 	/*
1754 	 * Deregister the se_tpg from TCM.
1755 	 */
1756 	core_tpg_deregister(se_tpg);
1757 	kfree(tpg);
1758 }
1759 
1760 static int scsiback_check_true(struct se_portal_group *se_tpg)
1761 {
1762 	return 1;
1763 }
1764 
1765 static int scsiback_check_false(struct se_portal_group *se_tpg)
1766 {
1767 	return 0;
1768 }
1769 
1770 static const struct target_core_fabric_ops scsiback_ops = {
1771 	.module				= THIS_MODULE,
1772 	.fabric_name			= "xen-pvscsi",
1773 	.tpg_get_wwn			= scsiback_get_fabric_wwn,
1774 	.tpg_get_tag			= scsiback_get_tag,
1775 	.tpg_check_demo_mode		= scsiback_check_true,
1776 	.tpg_check_demo_mode_cache	= scsiback_check_true,
1777 	.tpg_check_demo_mode_write_protect = scsiback_check_false,
1778 	.tpg_check_prod_mode_write_protect = scsiback_check_false,
1779 	.tpg_get_inst_index		= scsiback_tpg_get_inst_index,
1780 	.check_stop_free		= scsiback_check_stop_free,
1781 	.release_cmd			= scsiback_release_cmd,
1782 	.sess_get_index			= scsiback_sess_get_index,
1783 	.sess_get_initiator_sid		= NULL,
1784 	.write_pending			= scsiback_write_pending,
1785 	.set_default_node_attributes	= scsiback_set_default_node_attrs,
1786 	.get_cmd_state			= scsiback_get_cmd_state,
1787 	.queue_data_in			= scsiback_queue_data_in,
1788 	.queue_status			= scsiback_queue_status,
1789 	.queue_tm_rsp			= scsiback_queue_tm_rsp,
1790 	.aborted_task			= scsiback_aborted_task,
1791 	/*
1792 	 * Setup callers for generic logic in target_core_fabric_configfs.c
1793 	 */
1794 	.fabric_make_wwn		= scsiback_make_tport,
1795 	.fabric_drop_wwn		= scsiback_drop_tport,
1796 	.fabric_make_tpg		= scsiback_make_tpg,
1797 	.fabric_drop_tpg		= scsiback_drop_tpg,
1798 	.fabric_post_link		= scsiback_port_link,
1799 	.fabric_pre_unlink		= scsiback_port_unlink,
1800 
1801 	.tfc_wwn_attrs			= scsiback_wwn_attrs,
1802 	.tfc_tpg_base_attrs		= scsiback_tpg_attrs,
1803 	.tfc_tpg_param_attrs		= scsiback_param_attrs,
1804 };
1805 
1806 static const struct xenbus_device_id scsiback_ids[] = {
1807 	{ "vscsi" },
1808 	{ "" }
1809 };
1810 
1811 static struct xenbus_driver scsiback_driver = {
1812 	.ids			= scsiback_ids,
1813 	.probe			= scsiback_probe,
1814 	.remove			= scsiback_remove,
1815 	.otherend_changed	= scsiback_frontend_changed
1816 };
1817 
1818 static int __init scsiback_init(void)
1819 {
1820 	int ret;
1821 
1822 	if (!xen_domain())
1823 		return -ENODEV;
1824 
1825 	pr_debug("xen-pvscsi: fabric module %s on %s/%s on "UTS_RELEASE"\n",
1826 		 VSCSI_VERSION, utsname()->sysname, utsname()->machine);
1827 
1828 	ret = xenbus_register_backend(&scsiback_driver);
1829 	if (ret)
1830 		goto out;
1831 
1832 	ret = target_register_template(&scsiback_ops);
1833 	if (ret)
1834 		goto out_unregister_xenbus;
1835 
1836 	return 0;
1837 
1838 out_unregister_xenbus:
1839 	xenbus_unregister_driver(&scsiback_driver);
1840 out:
1841 	pr_err("%s: error %d\n", __func__, ret);
1842 	return ret;
1843 }
1844 
1845 static void __exit scsiback_exit(void)
1846 {
1847 	target_unregister_template(&scsiback_ops);
1848 	xenbus_unregister_driver(&scsiback_driver);
1849 }
1850 
1851 module_init(scsiback_init);
1852 module_exit(scsiback_exit);
1853 
1854 MODULE_DESCRIPTION("Xen SCSI backend driver");
1855 MODULE_LICENSE("Dual BSD/GPL");
1856 MODULE_ALIAS("xen-backend:vscsi");
1857 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");
1858