xref: /openbmc/linux/drivers/scsi/xen-scsifront.c (revision 61cb9ac6)
1 /*
2  * Xen SCSI frontend driver
3  *
4  * Copyright (c) 2008, FUJITSU Limited
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation; or, when distributed
9  * separately from the Linux kernel or incorporated into other
10  * software packages, subject to the following license:
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy
13  * of this source file (the "Software"), to deal in the Software without
14  * restriction, including without limitation the rights to use, copy, modify,
15  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
16  * and to permit persons to whom the Software is furnished to do so, subject to
17  * the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be included in
20  * all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28  * IN THE SOFTWARE.
29  */
30 
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/device.h>
34 #include <linux/wait.h>
35 #include <linux/interrupt.h>
36 #include <linux/mutex.h>
37 #include <linux/spinlock.h>
38 #include <linux/sched.h>
39 #include <linux/blkdev.h>
40 #include <linux/pfn.h>
41 #include <linux/slab.h>
42 #include <linux/bitops.h>
43 
44 #include <scsi/scsi_cmnd.h>
45 #include <scsi/scsi_device.h>
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_host.h>
48 
49 #include <xen/xen.h>
50 #include <xen/xenbus.h>
51 #include <xen/grant_table.h>
52 #include <xen/events.h>
53 #include <xen/page.h>
54 
55 #include <xen/interface/grant_table.h>
56 #include <xen/interface/io/vscsiif.h>
57 #include <xen/interface/io/protocols.h>
58 
59 #include <asm/xen/hypervisor.h>
60 
61 
62 #define GRANT_INVALID_REF	0
63 
64 #define VSCSIFRONT_OP_ADD_LUN	1
65 #define VSCSIFRONT_OP_DEL_LUN	2
66 #define VSCSIFRONT_OP_READD_LUN	3
67 
68 /* Tuning point. */
69 #define VSCSIIF_DEFAULT_CMD_PER_LUN 10
70 #define VSCSIIF_MAX_TARGET          64
71 #define VSCSIIF_MAX_LUN             255
72 
73 #define VSCSIIF_RING_SIZE	__CONST_RING_SIZE(vscsiif, PAGE_SIZE)
74 #define VSCSIIF_MAX_REQS	VSCSIIF_RING_SIZE
75 
76 #define vscsiif_grants_sg(_sg)	(PFN_UP((_sg) *		\
77 				sizeof(struct scsiif_request_segment)))
78 
79 struct vscsifrnt_shadow {
80 	/* command between backend and frontend */
81 	unsigned char act;
82 	uint8_t nr_segments;
83 	uint16_t rqid;
84 	uint16_t ref_rqid;
85 
86 	unsigned int nr_grants;		/* number of grants in gref[] */
87 	struct scsiif_request_segment *sg;	/* scatter/gather elements */
88 	struct scsiif_request_segment seg[VSCSIIF_SG_TABLESIZE];
89 
90 	/* Do reset or abort function. */
91 	wait_queue_head_t wq_reset;	/* reset work queue           */
92 	int wait_reset;			/* reset work queue condition */
93 	int32_t rslt_reset;		/* reset response status:     */
94 					/* SUCCESS or FAILED or:      */
95 #define RSLT_RESET_WAITING	0
96 #define RSLT_RESET_ERR		-1
97 
98 	/* Requested struct scsi_cmnd is stored from kernel. */
99 	struct scsi_cmnd *sc;
100 	int gref[vscsiif_grants_sg(SG_ALL) + SG_ALL];
101 };
102 
103 struct vscsifrnt_info {
104 	struct xenbus_device *dev;
105 
106 	struct Scsi_Host *host;
107 	int host_active;
108 
109 	unsigned int evtchn;
110 	unsigned int irq;
111 
112 	grant_ref_t ring_ref;
113 	struct vscsiif_front_ring ring;
114 	struct vscsiif_response	ring_rsp;
115 
116 	spinlock_t shadow_lock;
117 	DECLARE_BITMAP(shadow_free_bitmap, VSCSIIF_MAX_REQS);
118 	struct vscsifrnt_shadow *shadow[VSCSIIF_MAX_REQS];
119 
120 	/* Following items are protected by the host lock. */
121 	wait_queue_head_t wq_sync;
122 	wait_queue_head_t wq_pause;
123 	unsigned int wait_ring_available:1;
124 	unsigned int waiting_pause:1;
125 	unsigned int pause:1;
126 	unsigned callers;
127 
128 	char dev_state_path[64];
129 	struct task_struct *curr;
130 };
131 
132 static DEFINE_MUTEX(scsifront_mutex);
133 
134 static void scsifront_wake_up(struct vscsifrnt_info *info)
135 {
136 	info->wait_ring_available = 0;
137 	wake_up(&info->wq_sync);
138 }
139 
140 static int scsifront_get_rqid(struct vscsifrnt_info *info)
141 {
142 	unsigned long flags;
143 	int free;
144 
145 	spin_lock_irqsave(&info->shadow_lock, flags);
146 
147 	free = find_first_bit(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
148 	__clear_bit(free, info->shadow_free_bitmap);
149 
150 	spin_unlock_irqrestore(&info->shadow_lock, flags);
151 
152 	return free;
153 }
154 
155 static int _scsifront_put_rqid(struct vscsifrnt_info *info, uint32_t id)
156 {
157 	int empty = bitmap_empty(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
158 
159 	__set_bit(id, info->shadow_free_bitmap);
160 	info->shadow[id] = NULL;
161 
162 	return empty || info->wait_ring_available;
163 }
164 
165 static void scsifront_put_rqid(struct vscsifrnt_info *info, uint32_t id)
166 {
167 	unsigned long flags;
168 	int kick;
169 
170 	spin_lock_irqsave(&info->shadow_lock, flags);
171 	kick = _scsifront_put_rqid(info, id);
172 	spin_unlock_irqrestore(&info->shadow_lock, flags);
173 
174 	if (kick)
175 		scsifront_wake_up(info);
176 }
177 
178 static int scsifront_do_request(struct vscsifrnt_info *info,
179 				struct vscsifrnt_shadow *shadow)
180 {
181 	struct vscsiif_front_ring *ring = &(info->ring);
182 	struct vscsiif_request *ring_req;
183 	struct scsi_cmnd *sc = shadow->sc;
184 	uint32_t id;
185 	int i, notify;
186 
187 	if (RING_FULL(&info->ring))
188 		return -EBUSY;
189 
190 	id = scsifront_get_rqid(info);	/* use id in response */
191 	if (id >= VSCSIIF_MAX_REQS)
192 		return -EBUSY;
193 
194 	info->shadow[id] = shadow;
195 	shadow->rqid = id;
196 
197 	ring_req = RING_GET_REQUEST(&(info->ring), ring->req_prod_pvt);
198 	ring->req_prod_pvt++;
199 
200 	ring_req->rqid        = id;
201 	ring_req->act         = shadow->act;
202 	ring_req->ref_rqid    = shadow->ref_rqid;
203 	ring_req->nr_segments = shadow->nr_segments;
204 
205 	ring_req->id      = sc->device->id;
206 	ring_req->lun     = sc->device->lun;
207 	ring_req->channel = sc->device->channel;
208 	ring_req->cmd_len = sc->cmd_len;
209 
210 	BUG_ON(sc->cmd_len > VSCSIIF_MAX_COMMAND_SIZE);
211 
212 	memcpy(ring_req->cmnd, sc->cmnd, sc->cmd_len);
213 
214 	ring_req->sc_data_direction   = (uint8_t)sc->sc_data_direction;
215 	ring_req->timeout_per_command = scsi_cmd_to_rq(sc)->timeout / HZ;
216 
217 	for (i = 0; i < (shadow->nr_segments & ~VSCSIIF_SG_GRANT); i++)
218 		ring_req->seg[i] = shadow->seg[i];
219 
220 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(ring, notify);
221 	if (notify)
222 		notify_remote_via_irq(info->irq);
223 
224 	return 0;
225 }
226 
227 static void scsifront_gnttab_done(struct vscsifrnt_info *info,
228 				  struct vscsifrnt_shadow *shadow)
229 {
230 	int i;
231 
232 	if (shadow->sc->sc_data_direction == DMA_NONE)
233 		return;
234 
235 	for (i = 0; i < shadow->nr_grants; i++) {
236 		if (unlikely(gnttab_query_foreign_access(shadow->gref[i]))) {
237 			shost_printk(KERN_ALERT, info->host, KBUILD_MODNAME
238 				     "grant still in use by backend\n");
239 			BUG();
240 		}
241 		gnttab_end_foreign_access(shadow->gref[i], 0, 0UL);
242 	}
243 
244 	kfree(shadow->sg);
245 }
246 
247 static void scsifront_cdb_cmd_done(struct vscsifrnt_info *info,
248 				   struct vscsiif_response *ring_rsp)
249 {
250 	struct vscsifrnt_shadow *shadow;
251 	struct scsi_cmnd *sc;
252 	uint32_t id;
253 	uint8_t sense_len;
254 	int result;
255 
256 	id = ring_rsp->rqid;
257 	shadow = info->shadow[id];
258 	sc = shadow->sc;
259 
260 	BUG_ON(sc == NULL);
261 
262 	scsifront_gnttab_done(info, shadow);
263 	scsifront_put_rqid(info, id);
264 
265 	result = ring_rsp->rslt;
266 	if (result >> 24)
267 		set_host_byte(sc, DID_ERROR);
268 	else
269 		set_host_byte(sc, host_byte(result));
270 	set_status_byte(sc, result & 0xff);
271 	scsi_set_resid(sc, ring_rsp->residual_len);
272 
273 	sense_len = min_t(uint8_t, VSCSIIF_SENSE_BUFFERSIZE,
274 			  ring_rsp->sense_len);
275 
276 	if (sense_len)
277 		memcpy(sc->sense_buffer, ring_rsp->sense_buffer, sense_len);
278 
279 	sc->scsi_done(sc);
280 }
281 
282 static void scsifront_sync_cmd_done(struct vscsifrnt_info *info,
283 				    struct vscsiif_response *ring_rsp)
284 {
285 	uint16_t id = ring_rsp->rqid;
286 	unsigned long flags;
287 	struct vscsifrnt_shadow *shadow = info->shadow[id];
288 	int kick;
289 
290 	spin_lock_irqsave(&info->shadow_lock, flags);
291 	shadow->wait_reset = 1;
292 	switch (shadow->rslt_reset) {
293 	case RSLT_RESET_WAITING:
294 		shadow->rslt_reset = ring_rsp->rslt;
295 		break;
296 	case RSLT_RESET_ERR:
297 		kick = _scsifront_put_rqid(info, id);
298 		spin_unlock_irqrestore(&info->shadow_lock, flags);
299 		kfree(shadow);
300 		if (kick)
301 			scsifront_wake_up(info);
302 		return;
303 	default:
304 		shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
305 			     "bad reset state %d, possibly leaking %u\n",
306 			     shadow->rslt_reset, id);
307 		break;
308 	}
309 	spin_unlock_irqrestore(&info->shadow_lock, flags);
310 
311 	wake_up(&shadow->wq_reset);
312 }
313 
314 static void scsifront_do_response(struct vscsifrnt_info *info,
315 				  struct vscsiif_response *ring_rsp)
316 {
317 	if (WARN(ring_rsp->rqid >= VSCSIIF_MAX_REQS ||
318 		 test_bit(ring_rsp->rqid, info->shadow_free_bitmap),
319 		 "illegal rqid %u returned by backend!\n", ring_rsp->rqid))
320 		return;
321 
322 	if (info->shadow[ring_rsp->rqid]->act == VSCSIIF_ACT_SCSI_CDB)
323 		scsifront_cdb_cmd_done(info, ring_rsp);
324 	else
325 		scsifront_sync_cmd_done(info, ring_rsp);
326 }
327 
328 static int scsifront_ring_drain(struct vscsifrnt_info *info)
329 {
330 	struct vscsiif_response *ring_rsp;
331 	RING_IDX i, rp;
332 	int more_to_do = 0;
333 
334 	rp = info->ring.sring->rsp_prod;
335 	rmb();	/* ordering required respective to dom0 */
336 	for (i = info->ring.rsp_cons; i != rp; i++) {
337 		ring_rsp = RING_GET_RESPONSE(&info->ring, i);
338 		scsifront_do_response(info, ring_rsp);
339 	}
340 
341 	info->ring.rsp_cons = i;
342 
343 	if (i != info->ring.req_prod_pvt)
344 		RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
345 	else
346 		info->ring.sring->rsp_event = i + 1;
347 
348 	return more_to_do;
349 }
350 
351 static int scsifront_cmd_done(struct vscsifrnt_info *info)
352 {
353 	int more_to_do;
354 	unsigned long flags;
355 
356 	spin_lock_irqsave(info->host->host_lock, flags);
357 
358 	more_to_do = scsifront_ring_drain(info);
359 
360 	info->wait_ring_available = 0;
361 
362 	spin_unlock_irqrestore(info->host->host_lock, flags);
363 
364 	wake_up(&info->wq_sync);
365 
366 	return more_to_do;
367 }
368 
369 static irqreturn_t scsifront_irq_fn(int irq, void *dev_id)
370 {
371 	struct vscsifrnt_info *info = dev_id;
372 
373 	while (scsifront_cmd_done(info))
374 		/* Yield point for this unbounded loop. */
375 		cond_resched();
376 
377 	return IRQ_HANDLED;
378 }
379 
380 static void scsifront_finish_all(struct vscsifrnt_info *info)
381 {
382 	unsigned i;
383 	struct vscsiif_response resp;
384 
385 	scsifront_ring_drain(info);
386 
387 	for (i = 0; i < VSCSIIF_MAX_REQS; i++) {
388 		if (test_bit(i, info->shadow_free_bitmap))
389 			continue;
390 		resp.rqid = i;
391 		resp.sense_len = 0;
392 		resp.rslt = DID_RESET << 16;
393 		resp.residual_len = 0;
394 		scsifront_do_response(info, &resp);
395 	}
396 }
397 
398 static int map_data_for_request(struct vscsifrnt_info *info,
399 				struct scsi_cmnd *sc,
400 				struct vscsifrnt_shadow *shadow)
401 {
402 	grant_ref_t gref_head;
403 	struct page *page;
404 	int err, ref, ref_cnt = 0;
405 	int grant_ro = (sc->sc_data_direction == DMA_TO_DEVICE);
406 	unsigned int i, off, len, bytes;
407 	unsigned int data_len = scsi_bufflen(sc);
408 	unsigned int data_grants = 0, seg_grants = 0;
409 	struct scatterlist *sg;
410 	struct scsiif_request_segment *seg;
411 
412 	if (sc->sc_data_direction == DMA_NONE || !data_len)
413 		return 0;
414 
415 	scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i)
416 		data_grants += PFN_UP(sg->offset + sg->length);
417 
418 	if (data_grants > VSCSIIF_SG_TABLESIZE) {
419 		if (data_grants > info->host->sg_tablesize) {
420 			shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
421 			     "Unable to map request_buffer for command!\n");
422 			return -E2BIG;
423 		}
424 		seg_grants = vscsiif_grants_sg(data_grants);
425 		shadow->sg = kcalloc(data_grants,
426 			sizeof(struct scsiif_request_segment), GFP_ATOMIC);
427 		if (!shadow->sg)
428 			return -ENOMEM;
429 	}
430 	seg = shadow->sg ? : shadow->seg;
431 
432 	err = gnttab_alloc_grant_references(seg_grants + data_grants,
433 					    &gref_head);
434 	if (err) {
435 		kfree(shadow->sg);
436 		shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
437 			     "gnttab_alloc_grant_references() error\n");
438 		return -ENOMEM;
439 	}
440 
441 	if (seg_grants) {
442 		page = virt_to_page(seg);
443 		off = offset_in_page(seg);
444 		len = sizeof(struct scsiif_request_segment) * data_grants;
445 		while (len > 0) {
446 			bytes = min_t(unsigned int, len, PAGE_SIZE - off);
447 
448 			ref = gnttab_claim_grant_reference(&gref_head);
449 			BUG_ON(ref == -ENOSPC);
450 
451 			gnttab_grant_foreign_access_ref(ref,
452 				info->dev->otherend_id,
453 				xen_page_to_gfn(page), 1);
454 			shadow->gref[ref_cnt] = ref;
455 			shadow->seg[ref_cnt].gref   = ref;
456 			shadow->seg[ref_cnt].offset = (uint16_t)off;
457 			shadow->seg[ref_cnt].length = (uint16_t)bytes;
458 
459 			page++;
460 			len -= bytes;
461 			off = 0;
462 			ref_cnt++;
463 		}
464 		BUG_ON(seg_grants < ref_cnt);
465 		seg_grants = ref_cnt;
466 	}
467 
468 	scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i) {
469 		page = sg_page(sg);
470 		off = sg->offset;
471 		len = sg->length;
472 
473 		while (len > 0 && data_len > 0) {
474 			/*
475 			 * sg sends a scatterlist that is larger than
476 			 * the data_len it wants transferred for certain
477 			 * IO sizes.
478 			 */
479 			bytes = min_t(unsigned int, len, PAGE_SIZE - off);
480 			bytes = min(bytes, data_len);
481 
482 			ref = gnttab_claim_grant_reference(&gref_head);
483 			BUG_ON(ref == -ENOSPC);
484 
485 			gnttab_grant_foreign_access_ref(ref,
486 				info->dev->otherend_id,
487 				xen_page_to_gfn(page),
488 				grant_ro);
489 
490 			shadow->gref[ref_cnt] = ref;
491 			seg->gref   = ref;
492 			seg->offset = (uint16_t)off;
493 			seg->length = (uint16_t)bytes;
494 
495 			page++;
496 			seg++;
497 			len -= bytes;
498 			data_len -= bytes;
499 			off = 0;
500 			ref_cnt++;
501 		}
502 	}
503 
504 	if (seg_grants)
505 		shadow->nr_segments = VSCSIIF_SG_GRANT | seg_grants;
506 	else
507 		shadow->nr_segments = (uint8_t)ref_cnt;
508 	shadow->nr_grants = ref_cnt;
509 
510 	return 0;
511 }
512 
513 static int scsifront_enter(struct vscsifrnt_info *info)
514 {
515 	if (info->pause)
516 		return 1;
517 	info->callers++;
518 	return 0;
519 }
520 
521 static void scsifront_return(struct vscsifrnt_info *info)
522 {
523 	info->callers--;
524 	if (info->callers)
525 		return;
526 
527 	if (!info->waiting_pause)
528 		return;
529 
530 	info->waiting_pause = 0;
531 	wake_up(&info->wq_pause);
532 }
533 
534 static int scsifront_queuecommand(struct Scsi_Host *shost,
535 				  struct scsi_cmnd *sc)
536 {
537 	struct vscsifrnt_info *info = shost_priv(shost);
538 	struct vscsifrnt_shadow *shadow = scsi_cmd_priv(sc);
539 	unsigned long flags;
540 	int err;
541 
542 	sc->result = 0;
543 
544 	shadow->sc  = sc;
545 	shadow->act = VSCSIIF_ACT_SCSI_CDB;
546 
547 	spin_lock_irqsave(shost->host_lock, flags);
548 	if (scsifront_enter(info)) {
549 		spin_unlock_irqrestore(shost->host_lock, flags);
550 		return SCSI_MLQUEUE_HOST_BUSY;
551 	}
552 
553 	err = map_data_for_request(info, sc, shadow);
554 	if (err < 0) {
555 		pr_debug("%s: err %d\n", __func__, err);
556 		scsifront_return(info);
557 		spin_unlock_irqrestore(shost->host_lock, flags);
558 		if (err == -ENOMEM)
559 			return SCSI_MLQUEUE_HOST_BUSY;
560 		sc->result = DID_ERROR << 16;
561 		sc->scsi_done(sc);
562 		return 0;
563 	}
564 
565 	if (scsifront_do_request(info, shadow)) {
566 		scsifront_gnttab_done(info, shadow);
567 		goto busy;
568 	}
569 
570 	scsifront_return(info);
571 	spin_unlock_irqrestore(shost->host_lock, flags);
572 
573 	return 0;
574 
575 busy:
576 	scsifront_return(info);
577 	spin_unlock_irqrestore(shost->host_lock, flags);
578 	pr_debug("%s: busy\n", __func__);
579 	return SCSI_MLQUEUE_HOST_BUSY;
580 }
581 
582 /*
583  * Any exception handling (reset or abort) must be forwarded to the backend.
584  * We have to wait until an answer is returned. This answer contains the
585  * result to be returned to the requestor.
586  */
587 static int scsifront_action_handler(struct scsi_cmnd *sc, uint8_t act)
588 {
589 	struct Scsi_Host *host = sc->device->host;
590 	struct vscsifrnt_info *info = shost_priv(host);
591 	struct vscsifrnt_shadow *shadow, *s = scsi_cmd_priv(sc);
592 	int err = 0;
593 
594 	shadow = kzalloc(sizeof(*shadow), GFP_NOIO);
595 	if (!shadow)
596 		return FAILED;
597 
598 	shadow->act = act;
599 	shadow->rslt_reset = RSLT_RESET_WAITING;
600 	shadow->sc = sc;
601 	shadow->ref_rqid = s->rqid;
602 	init_waitqueue_head(&shadow->wq_reset);
603 
604 	spin_lock_irq(host->host_lock);
605 
606 	for (;;) {
607 		if (scsifront_enter(info))
608 			goto fail;
609 
610 		if (!scsifront_do_request(info, shadow))
611 			break;
612 
613 		scsifront_return(info);
614 		if (err)
615 			goto fail;
616 		info->wait_ring_available = 1;
617 		spin_unlock_irq(host->host_lock);
618 		err = wait_event_interruptible(info->wq_sync,
619 					       !info->wait_ring_available);
620 		spin_lock_irq(host->host_lock);
621 	}
622 
623 	spin_unlock_irq(host->host_lock);
624 	err = wait_event_interruptible(shadow->wq_reset, shadow->wait_reset);
625 	spin_lock_irq(host->host_lock);
626 
627 	if (!err) {
628 		err = shadow->rslt_reset;
629 		scsifront_put_rqid(info, shadow->rqid);
630 		kfree(shadow);
631 	} else {
632 		spin_lock(&info->shadow_lock);
633 		shadow->rslt_reset = RSLT_RESET_ERR;
634 		spin_unlock(&info->shadow_lock);
635 		err = FAILED;
636 	}
637 
638 	scsifront_return(info);
639 	spin_unlock_irq(host->host_lock);
640 	return err;
641 
642 fail:
643 	spin_unlock_irq(host->host_lock);
644 	kfree(shadow);
645 	return FAILED;
646 }
647 
648 static int scsifront_eh_abort_handler(struct scsi_cmnd *sc)
649 {
650 	pr_debug("%s\n", __func__);
651 	return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_ABORT);
652 }
653 
654 static int scsifront_dev_reset_handler(struct scsi_cmnd *sc)
655 {
656 	pr_debug("%s\n", __func__);
657 	return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_RESET);
658 }
659 
660 static int scsifront_sdev_configure(struct scsi_device *sdev)
661 {
662 	struct vscsifrnt_info *info = shost_priv(sdev->host);
663 	int err;
664 
665 	if (info && current == info->curr) {
666 		err = xenbus_printf(XBT_NIL, info->dev->nodename,
667 			      info->dev_state_path, "%d", XenbusStateConnected);
668 		if (err) {
669 			xenbus_dev_error(info->dev, err,
670 				"%s: writing dev_state_path", __func__);
671 			return err;
672 		}
673 	}
674 
675 	return 0;
676 }
677 
678 static void scsifront_sdev_destroy(struct scsi_device *sdev)
679 {
680 	struct vscsifrnt_info *info = shost_priv(sdev->host);
681 	int err;
682 
683 	if (info && current == info->curr) {
684 		err = xenbus_printf(XBT_NIL, info->dev->nodename,
685 			      info->dev_state_path, "%d", XenbusStateClosed);
686 		if (err)
687 			xenbus_dev_error(info->dev, err,
688 				"%s: writing dev_state_path", __func__);
689 	}
690 }
691 
692 static struct scsi_host_template scsifront_sht = {
693 	.module			= THIS_MODULE,
694 	.name			= "Xen SCSI frontend driver",
695 	.queuecommand		= scsifront_queuecommand,
696 	.eh_abort_handler	= scsifront_eh_abort_handler,
697 	.eh_device_reset_handler = scsifront_dev_reset_handler,
698 	.slave_configure	= scsifront_sdev_configure,
699 	.slave_destroy		= scsifront_sdev_destroy,
700 	.cmd_per_lun		= VSCSIIF_DEFAULT_CMD_PER_LUN,
701 	.can_queue		= VSCSIIF_MAX_REQS,
702 	.this_id		= -1,
703 	.cmd_size		= sizeof(struct vscsifrnt_shadow),
704 	.sg_tablesize		= VSCSIIF_SG_TABLESIZE,
705 	.proc_name		= "scsifront",
706 };
707 
708 static int scsifront_alloc_ring(struct vscsifrnt_info *info)
709 {
710 	struct xenbus_device *dev = info->dev;
711 	struct vscsiif_sring *sring;
712 	grant_ref_t gref;
713 	int err = -ENOMEM;
714 
715 	/***** Frontend to Backend ring start *****/
716 	sring = (struct vscsiif_sring *)__get_free_page(GFP_KERNEL);
717 	if (!sring) {
718 		xenbus_dev_fatal(dev, err,
719 			"fail to allocate shared ring (Front to Back)");
720 		return err;
721 	}
722 	SHARED_RING_INIT(sring);
723 	FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
724 
725 	err = xenbus_grant_ring(dev, sring, 1, &gref);
726 	if (err < 0) {
727 		free_page((unsigned long)sring);
728 		xenbus_dev_fatal(dev, err,
729 			"fail to grant shared ring (Front to Back)");
730 		return err;
731 	}
732 	info->ring_ref = gref;
733 
734 	err = xenbus_alloc_evtchn(dev, &info->evtchn);
735 	if (err) {
736 		xenbus_dev_fatal(dev, err, "xenbus_alloc_evtchn");
737 		goto free_gnttab;
738 	}
739 
740 	err = bind_evtchn_to_irq(info->evtchn);
741 	if (err <= 0) {
742 		xenbus_dev_fatal(dev, err, "bind_evtchn_to_irq");
743 		goto free_gnttab;
744 	}
745 
746 	info->irq = err;
747 
748 	err = request_threaded_irq(info->irq, NULL, scsifront_irq_fn,
749 				   IRQF_ONESHOT, "scsifront", info);
750 	if (err) {
751 		xenbus_dev_fatal(dev, err, "request_threaded_irq");
752 		goto free_irq;
753 	}
754 
755 	return 0;
756 
757 /* free resource */
758 free_irq:
759 	unbind_from_irqhandler(info->irq, info);
760 free_gnttab:
761 	gnttab_end_foreign_access(info->ring_ref, 0,
762 				  (unsigned long)info->ring.sring);
763 
764 	return err;
765 }
766 
767 static void scsifront_free_ring(struct vscsifrnt_info *info)
768 {
769 	unbind_from_irqhandler(info->irq, info);
770 	gnttab_end_foreign_access(info->ring_ref, 0,
771 				  (unsigned long)info->ring.sring);
772 }
773 
774 static int scsifront_init_ring(struct vscsifrnt_info *info)
775 {
776 	struct xenbus_device *dev = info->dev;
777 	struct xenbus_transaction xbt;
778 	int err;
779 
780 	pr_debug("%s\n", __func__);
781 
782 	err = scsifront_alloc_ring(info);
783 	if (err)
784 		return err;
785 	pr_debug("%s: %u %u\n", __func__, info->ring_ref, info->evtchn);
786 
787 again:
788 	err = xenbus_transaction_start(&xbt);
789 	if (err)
790 		xenbus_dev_fatal(dev, err, "starting transaction");
791 
792 	err = xenbus_printf(xbt, dev->nodename, "ring-ref", "%u",
793 			    info->ring_ref);
794 	if (err) {
795 		xenbus_dev_fatal(dev, err, "%s", "writing ring-ref");
796 		goto fail;
797 	}
798 
799 	err = xenbus_printf(xbt, dev->nodename, "event-channel", "%u",
800 			    info->evtchn);
801 
802 	if (err) {
803 		xenbus_dev_fatal(dev, err, "%s", "writing event-channel");
804 		goto fail;
805 	}
806 
807 	err = xenbus_transaction_end(xbt, 0);
808 	if (err) {
809 		if (err == -EAGAIN)
810 			goto again;
811 		xenbus_dev_fatal(dev, err, "completing transaction");
812 		goto free_sring;
813 	}
814 
815 	return 0;
816 
817 fail:
818 	xenbus_transaction_end(xbt, 1);
819 free_sring:
820 	scsifront_free_ring(info);
821 
822 	return err;
823 }
824 
825 
826 static int scsifront_probe(struct xenbus_device *dev,
827 			   const struct xenbus_device_id *id)
828 {
829 	struct vscsifrnt_info *info;
830 	struct Scsi_Host *host;
831 	int err = -ENOMEM;
832 	char name[TASK_COMM_LEN];
833 
834 	host = scsi_host_alloc(&scsifront_sht, sizeof(*info));
835 	if (!host) {
836 		xenbus_dev_fatal(dev, err, "fail to allocate scsi host");
837 		return err;
838 	}
839 	info = (struct vscsifrnt_info *)host->hostdata;
840 
841 	dev_set_drvdata(&dev->dev, info);
842 	info->dev = dev;
843 
844 	bitmap_fill(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
845 
846 	err = scsifront_init_ring(info);
847 	if (err) {
848 		scsi_host_put(host);
849 		return err;
850 	}
851 
852 	init_waitqueue_head(&info->wq_sync);
853 	init_waitqueue_head(&info->wq_pause);
854 	spin_lock_init(&info->shadow_lock);
855 
856 	snprintf(name, TASK_COMM_LEN, "vscsiif.%d", host->host_no);
857 
858 	host->max_id      = VSCSIIF_MAX_TARGET;
859 	host->max_channel = 0;
860 	host->max_lun     = VSCSIIF_MAX_LUN;
861 	host->max_sectors = (host->sg_tablesize - 1) * PAGE_SIZE / 512;
862 	host->max_cmd_len = VSCSIIF_MAX_COMMAND_SIZE;
863 
864 	err = scsi_add_host(host, &dev->dev);
865 	if (err) {
866 		dev_err(&dev->dev, "fail to add scsi host %d\n", err);
867 		goto free_sring;
868 	}
869 	info->host = host;
870 	info->host_active = 1;
871 
872 	xenbus_switch_state(dev, XenbusStateInitialised);
873 
874 	return 0;
875 
876 free_sring:
877 	scsifront_free_ring(info);
878 	scsi_host_put(host);
879 	return err;
880 }
881 
882 static int scsifront_resume(struct xenbus_device *dev)
883 {
884 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
885 	struct Scsi_Host *host = info->host;
886 	int err;
887 
888 	spin_lock_irq(host->host_lock);
889 
890 	/* Finish all still pending commands. */
891 	scsifront_finish_all(info);
892 
893 	spin_unlock_irq(host->host_lock);
894 
895 	/* Reconnect to dom0. */
896 	scsifront_free_ring(info);
897 	err = scsifront_init_ring(info);
898 	if (err) {
899 		dev_err(&dev->dev, "fail to resume %d\n", err);
900 		scsi_host_put(host);
901 		return err;
902 	}
903 
904 	xenbus_switch_state(dev, XenbusStateInitialised);
905 
906 	return 0;
907 }
908 
909 static int scsifront_suspend(struct xenbus_device *dev)
910 {
911 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
912 	struct Scsi_Host *host = info->host;
913 	int err = 0;
914 
915 	/* No new commands for the backend. */
916 	spin_lock_irq(host->host_lock);
917 	info->pause = 1;
918 	while (info->callers && !err) {
919 		info->waiting_pause = 1;
920 		info->wait_ring_available = 0;
921 		spin_unlock_irq(host->host_lock);
922 		wake_up(&info->wq_sync);
923 		err = wait_event_interruptible(info->wq_pause,
924 					       !info->waiting_pause);
925 		spin_lock_irq(host->host_lock);
926 	}
927 	spin_unlock_irq(host->host_lock);
928 	return err;
929 }
930 
931 static int scsifront_remove(struct xenbus_device *dev)
932 {
933 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
934 
935 	pr_debug("%s: %s removed\n", __func__, dev->nodename);
936 
937 	mutex_lock(&scsifront_mutex);
938 	if (info->host_active) {
939 		/* Scsi_host not yet removed */
940 		scsi_remove_host(info->host);
941 		info->host_active = 0;
942 	}
943 	mutex_unlock(&scsifront_mutex);
944 
945 	scsifront_free_ring(info);
946 	scsi_host_put(info->host);
947 
948 	return 0;
949 }
950 
951 static void scsifront_disconnect(struct vscsifrnt_info *info)
952 {
953 	struct xenbus_device *dev = info->dev;
954 	struct Scsi_Host *host = info->host;
955 
956 	pr_debug("%s: %s disconnect\n", __func__, dev->nodename);
957 
958 	/*
959 	 * When this function is executed, all devices of
960 	 * Frontend have been deleted.
961 	 * Therefore, it need not block I/O before remove_host.
962 	 */
963 
964 	mutex_lock(&scsifront_mutex);
965 	if (info->host_active) {
966 		scsi_remove_host(host);
967 		info->host_active = 0;
968 	}
969 	mutex_unlock(&scsifront_mutex);
970 
971 	xenbus_frontend_closed(dev);
972 }
973 
974 static void scsifront_do_lun_hotplug(struct vscsifrnt_info *info, int op)
975 {
976 	struct xenbus_device *dev = info->dev;
977 	int i, err = 0;
978 	char str[64];
979 	char **dir;
980 	unsigned int dir_n = 0;
981 	unsigned int device_state;
982 	unsigned int hst, chn, tgt, lun;
983 	struct scsi_device *sdev;
984 
985 	dir = xenbus_directory(XBT_NIL, dev->otherend, "vscsi-devs", &dir_n);
986 	if (IS_ERR(dir))
987 		return;
988 
989 	/* mark current task as the one allowed to modify device states */
990 	BUG_ON(info->curr);
991 	info->curr = current;
992 
993 	for (i = 0; i < dir_n; i++) {
994 		/* read status */
995 		snprintf(str, sizeof(str), "vscsi-devs/%s/state", dir[i]);
996 		err = xenbus_scanf(XBT_NIL, dev->otherend, str, "%u",
997 				   &device_state);
998 		if (XENBUS_EXIST_ERR(err))
999 			continue;
1000 
1001 		/* virtual SCSI device */
1002 		snprintf(str, sizeof(str), "vscsi-devs/%s/v-dev", dir[i]);
1003 		err = xenbus_scanf(XBT_NIL, dev->otherend, str,
1004 				   "%u:%u:%u:%u", &hst, &chn, &tgt, &lun);
1005 		if (XENBUS_EXIST_ERR(err))
1006 			continue;
1007 
1008 		/*
1009 		 * Front device state path, used in slave_configure called
1010 		 * on successfull scsi_add_device, and in slave_destroy called
1011 		 * on remove of a device.
1012 		 */
1013 		snprintf(info->dev_state_path, sizeof(info->dev_state_path),
1014 			 "vscsi-devs/%s/state", dir[i]);
1015 
1016 		switch (op) {
1017 		case VSCSIFRONT_OP_ADD_LUN:
1018 			if (device_state != XenbusStateInitialised)
1019 				break;
1020 
1021 			if (scsi_add_device(info->host, chn, tgt, lun)) {
1022 				dev_err(&dev->dev, "scsi_add_device\n");
1023 				err = xenbus_printf(XBT_NIL, dev->nodename,
1024 					      info->dev_state_path,
1025 					      "%d", XenbusStateClosed);
1026 				if (err)
1027 					xenbus_dev_error(dev, err,
1028 						"%s: writing dev_state_path", __func__);
1029 			}
1030 			break;
1031 		case VSCSIFRONT_OP_DEL_LUN:
1032 			if (device_state != XenbusStateClosing)
1033 				break;
1034 
1035 			sdev = scsi_device_lookup(info->host, chn, tgt, lun);
1036 			if (sdev) {
1037 				scsi_remove_device(sdev);
1038 				scsi_device_put(sdev);
1039 			}
1040 			break;
1041 		case VSCSIFRONT_OP_READD_LUN:
1042 			if (device_state == XenbusStateConnected) {
1043 				err = xenbus_printf(XBT_NIL, dev->nodename,
1044 					      info->dev_state_path,
1045 					      "%d", XenbusStateConnected);
1046 				if (err)
1047 					xenbus_dev_error(dev, err,
1048 						"%s: writing dev_state_path", __func__);
1049 			}
1050 			break;
1051 		default:
1052 			break;
1053 		}
1054 	}
1055 
1056 	info->curr = NULL;
1057 
1058 	kfree(dir);
1059 }
1060 
1061 static void scsifront_read_backend_params(struct xenbus_device *dev,
1062 					  struct vscsifrnt_info *info)
1063 {
1064 	unsigned int sg_grant, nr_segs;
1065 	struct Scsi_Host *host = info->host;
1066 
1067 	sg_grant = xenbus_read_unsigned(dev->otherend, "feature-sg-grant", 0);
1068 	nr_segs = min_t(unsigned int, sg_grant, SG_ALL);
1069 	nr_segs = max_t(unsigned int, nr_segs, VSCSIIF_SG_TABLESIZE);
1070 	nr_segs = min_t(unsigned int, nr_segs,
1071 			VSCSIIF_SG_TABLESIZE * PAGE_SIZE /
1072 			sizeof(struct scsiif_request_segment));
1073 
1074 	if (!info->pause && sg_grant)
1075 		dev_info(&dev->dev, "using up to %d SG entries\n", nr_segs);
1076 	else if (info->pause && nr_segs < host->sg_tablesize)
1077 		dev_warn(&dev->dev,
1078 			 "SG entries decreased from %d to %u - device may not work properly anymore\n",
1079 			 host->sg_tablesize, nr_segs);
1080 
1081 	host->sg_tablesize = nr_segs;
1082 	host->max_sectors = (nr_segs - 1) * PAGE_SIZE / 512;
1083 }
1084 
1085 static void scsifront_backend_changed(struct xenbus_device *dev,
1086 				      enum xenbus_state backend_state)
1087 {
1088 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
1089 
1090 	pr_debug("%s: %p %u %u\n", __func__, dev, dev->state, backend_state);
1091 
1092 	switch (backend_state) {
1093 	case XenbusStateUnknown:
1094 	case XenbusStateInitialising:
1095 	case XenbusStateInitWait:
1096 	case XenbusStateInitialised:
1097 		break;
1098 
1099 	case XenbusStateConnected:
1100 		scsifront_read_backend_params(dev, info);
1101 
1102 		if (info->pause) {
1103 			scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_READD_LUN);
1104 			xenbus_switch_state(dev, XenbusStateConnected);
1105 			info->pause = 0;
1106 			return;
1107 		}
1108 
1109 		if (xenbus_read_driver_state(dev->nodename) ==
1110 		    XenbusStateInitialised)
1111 			scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1112 
1113 		if (dev->state != XenbusStateConnected)
1114 			xenbus_switch_state(dev, XenbusStateConnected);
1115 		break;
1116 
1117 	case XenbusStateClosed:
1118 		if (dev->state == XenbusStateClosed)
1119 			break;
1120 		fallthrough;	/* Missed the backend's Closing state */
1121 	case XenbusStateClosing:
1122 		scsifront_disconnect(info);
1123 		break;
1124 
1125 	case XenbusStateReconfiguring:
1126 		scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_DEL_LUN);
1127 		xenbus_switch_state(dev, XenbusStateReconfiguring);
1128 		break;
1129 
1130 	case XenbusStateReconfigured:
1131 		scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1132 		xenbus_switch_state(dev, XenbusStateConnected);
1133 		break;
1134 	}
1135 }
1136 
1137 static const struct xenbus_device_id scsifront_ids[] = {
1138 	{ "vscsi" },
1139 	{ "" }
1140 };
1141 
1142 static struct xenbus_driver scsifront_driver = {
1143 	.ids			= scsifront_ids,
1144 	.probe			= scsifront_probe,
1145 	.remove			= scsifront_remove,
1146 	.resume			= scsifront_resume,
1147 	.suspend		= scsifront_suspend,
1148 	.otherend_changed	= scsifront_backend_changed,
1149 };
1150 
1151 static int __init scsifront_init(void)
1152 {
1153 	if (!xen_domain())
1154 		return -ENODEV;
1155 
1156 	return xenbus_register_frontend(&scsifront_driver);
1157 }
1158 module_init(scsifront_init);
1159 
1160 static void __exit scsifront_exit(void)
1161 {
1162 	xenbus_unregister_driver(&scsifront_driver);
1163 }
1164 module_exit(scsifront_exit);
1165 
1166 MODULE_DESCRIPTION("Xen SCSI frontend driver");
1167 MODULE_LICENSE("GPL");
1168 MODULE_ALIAS("xen:vscsi");
1169 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");
1170