xref: /linux/drivers/scsi/xen-scsifront.c (revision 0a94608f0f7de9b1135ffea3546afe68eafef57f)
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_try_end_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 	}
242 
243 	kfree(shadow->sg);
244 }
245 
246 static void scsifront_cdb_cmd_done(struct vscsifrnt_info *info,
247 				   struct vscsiif_response *ring_rsp)
248 {
249 	struct vscsifrnt_shadow *shadow;
250 	struct scsi_cmnd *sc;
251 	uint32_t id;
252 	uint8_t sense_len;
253 	int result;
254 
255 	id = ring_rsp->rqid;
256 	shadow = info->shadow[id];
257 	sc = shadow->sc;
258 
259 	BUG_ON(sc == NULL);
260 
261 	scsifront_gnttab_done(info, shadow);
262 	scsifront_put_rqid(info, id);
263 
264 	result = ring_rsp->rslt;
265 	if (result >> 24)
266 		set_host_byte(sc, DID_ERROR);
267 	else
268 		set_host_byte(sc, host_byte(result));
269 	set_status_byte(sc, result & 0xff);
270 	scsi_set_resid(sc, ring_rsp->residual_len);
271 
272 	sense_len = min_t(uint8_t, VSCSIIF_SENSE_BUFFERSIZE,
273 			  ring_rsp->sense_len);
274 
275 	if (sense_len)
276 		memcpy(sc->sense_buffer, ring_rsp->sense_buffer, sense_len);
277 
278 	scsi_done(sc);
279 }
280 
281 static void scsifront_sync_cmd_done(struct vscsifrnt_info *info,
282 				    struct vscsiif_response *ring_rsp)
283 {
284 	uint16_t id = ring_rsp->rqid;
285 	unsigned long flags;
286 	struct vscsifrnt_shadow *shadow = info->shadow[id];
287 	int kick;
288 
289 	spin_lock_irqsave(&info->shadow_lock, flags);
290 	shadow->wait_reset = 1;
291 	switch (shadow->rslt_reset) {
292 	case RSLT_RESET_WAITING:
293 		shadow->rslt_reset = ring_rsp->rslt;
294 		break;
295 	case RSLT_RESET_ERR:
296 		kick = _scsifront_put_rqid(info, id);
297 		spin_unlock_irqrestore(&info->shadow_lock, flags);
298 		kfree(shadow);
299 		if (kick)
300 			scsifront_wake_up(info);
301 		return;
302 	default:
303 		shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
304 			     "bad reset state %d, possibly leaking %u\n",
305 			     shadow->rslt_reset, id);
306 		break;
307 	}
308 	spin_unlock_irqrestore(&info->shadow_lock, flags);
309 
310 	wake_up(&shadow->wq_reset);
311 }
312 
313 static void scsifront_do_response(struct vscsifrnt_info *info,
314 				  struct vscsiif_response *ring_rsp)
315 {
316 	if (WARN(ring_rsp->rqid >= VSCSIIF_MAX_REQS ||
317 		 test_bit(ring_rsp->rqid, info->shadow_free_bitmap),
318 		 "illegal rqid %u returned by backend!\n", ring_rsp->rqid))
319 		return;
320 
321 	if (info->shadow[ring_rsp->rqid]->act == VSCSIIF_ACT_SCSI_CDB)
322 		scsifront_cdb_cmd_done(info, ring_rsp);
323 	else
324 		scsifront_sync_cmd_done(info, ring_rsp);
325 }
326 
327 static int scsifront_ring_drain(struct vscsifrnt_info *info)
328 {
329 	struct vscsiif_response *ring_rsp;
330 	RING_IDX i, rp;
331 	int more_to_do = 0;
332 
333 	rp = info->ring.sring->rsp_prod;
334 	rmb();	/* ordering required respective to dom0 */
335 	for (i = info->ring.rsp_cons; i != rp; i++) {
336 		ring_rsp = RING_GET_RESPONSE(&info->ring, i);
337 		scsifront_do_response(info, ring_rsp);
338 	}
339 
340 	info->ring.rsp_cons = i;
341 
342 	if (i != info->ring.req_prod_pvt)
343 		RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
344 	else
345 		info->ring.sring->rsp_event = i + 1;
346 
347 	return more_to_do;
348 }
349 
350 static int scsifront_cmd_done(struct vscsifrnt_info *info)
351 {
352 	int more_to_do;
353 	unsigned long flags;
354 
355 	spin_lock_irqsave(info->host->host_lock, flags);
356 
357 	more_to_do = scsifront_ring_drain(info);
358 
359 	info->wait_ring_available = 0;
360 
361 	spin_unlock_irqrestore(info->host->host_lock, flags);
362 
363 	wake_up(&info->wq_sync);
364 
365 	return more_to_do;
366 }
367 
368 static irqreturn_t scsifront_irq_fn(int irq, void *dev_id)
369 {
370 	struct vscsifrnt_info *info = dev_id;
371 
372 	while (scsifront_cmd_done(info))
373 		/* Yield point for this unbounded loop. */
374 		cond_resched();
375 
376 	return IRQ_HANDLED;
377 }
378 
379 static void scsifront_finish_all(struct vscsifrnt_info *info)
380 {
381 	unsigned i;
382 	struct vscsiif_response resp;
383 
384 	scsifront_ring_drain(info);
385 
386 	for (i = 0; i < VSCSIIF_MAX_REQS; i++) {
387 		if (test_bit(i, info->shadow_free_bitmap))
388 			continue;
389 		resp.rqid = i;
390 		resp.sense_len = 0;
391 		resp.rslt = DID_RESET << 16;
392 		resp.residual_len = 0;
393 		scsifront_do_response(info, &resp);
394 	}
395 }
396 
397 static int map_data_for_request(struct vscsifrnt_info *info,
398 				struct scsi_cmnd *sc,
399 				struct vscsifrnt_shadow *shadow)
400 {
401 	grant_ref_t gref_head;
402 	struct page *page;
403 	int err, ref, ref_cnt = 0;
404 	int grant_ro = (sc->sc_data_direction == DMA_TO_DEVICE);
405 	unsigned int i, off, len, bytes;
406 	unsigned int data_len = scsi_bufflen(sc);
407 	unsigned int data_grants = 0, seg_grants = 0;
408 	struct scatterlist *sg;
409 	struct scsiif_request_segment *seg;
410 
411 	if (sc->sc_data_direction == DMA_NONE || !data_len)
412 		return 0;
413 
414 	scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i)
415 		data_grants += PFN_UP(sg->offset + sg->length);
416 
417 	if (data_grants > VSCSIIF_SG_TABLESIZE) {
418 		if (data_grants > info->host->sg_tablesize) {
419 			shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
420 			     "Unable to map request_buffer for command!\n");
421 			return -E2BIG;
422 		}
423 		seg_grants = vscsiif_grants_sg(data_grants);
424 		shadow->sg = kcalloc(data_grants,
425 			sizeof(struct scsiif_request_segment), GFP_ATOMIC);
426 		if (!shadow->sg)
427 			return -ENOMEM;
428 	}
429 	seg = shadow->sg ? : shadow->seg;
430 
431 	err = gnttab_alloc_grant_references(seg_grants + data_grants,
432 					    &gref_head);
433 	if (err) {
434 		kfree(shadow->sg);
435 		shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
436 			     "gnttab_alloc_grant_references() error\n");
437 		return -ENOMEM;
438 	}
439 
440 	if (seg_grants) {
441 		page = virt_to_page(seg);
442 		off = offset_in_page(seg);
443 		len = sizeof(struct scsiif_request_segment) * data_grants;
444 		while (len > 0) {
445 			bytes = min_t(unsigned int, len, PAGE_SIZE - off);
446 
447 			ref = gnttab_claim_grant_reference(&gref_head);
448 			BUG_ON(ref == -ENOSPC);
449 
450 			gnttab_grant_foreign_access_ref(ref,
451 				info->dev->otherend_id,
452 				xen_page_to_gfn(page), 1);
453 			shadow->gref[ref_cnt] = ref;
454 			shadow->seg[ref_cnt].gref   = ref;
455 			shadow->seg[ref_cnt].offset = (uint16_t)off;
456 			shadow->seg[ref_cnt].length = (uint16_t)bytes;
457 
458 			page++;
459 			len -= bytes;
460 			off = 0;
461 			ref_cnt++;
462 		}
463 		BUG_ON(seg_grants < ref_cnt);
464 		seg_grants = ref_cnt;
465 	}
466 
467 	scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i) {
468 		page = sg_page(sg);
469 		off = sg->offset;
470 		len = sg->length;
471 
472 		while (len > 0 && data_len > 0) {
473 			/*
474 			 * sg sends a scatterlist that is larger than
475 			 * the data_len it wants transferred for certain
476 			 * IO sizes.
477 			 */
478 			bytes = min_t(unsigned int, len, PAGE_SIZE - off);
479 			bytes = min(bytes, data_len);
480 
481 			ref = gnttab_claim_grant_reference(&gref_head);
482 			BUG_ON(ref == -ENOSPC);
483 
484 			gnttab_grant_foreign_access_ref(ref,
485 				info->dev->otherend_id,
486 				xen_page_to_gfn(page),
487 				grant_ro);
488 
489 			shadow->gref[ref_cnt] = ref;
490 			seg->gref   = ref;
491 			seg->offset = (uint16_t)off;
492 			seg->length = (uint16_t)bytes;
493 
494 			page++;
495 			seg++;
496 			len -= bytes;
497 			data_len -= bytes;
498 			off = 0;
499 			ref_cnt++;
500 		}
501 	}
502 
503 	if (seg_grants)
504 		shadow->nr_segments = VSCSIIF_SG_GRANT | seg_grants;
505 	else
506 		shadow->nr_segments = (uint8_t)ref_cnt;
507 	shadow->nr_grants = ref_cnt;
508 
509 	return 0;
510 }
511 
512 static int scsifront_enter(struct vscsifrnt_info *info)
513 {
514 	if (info->pause)
515 		return 1;
516 	info->callers++;
517 	return 0;
518 }
519 
520 static void scsifront_return(struct vscsifrnt_info *info)
521 {
522 	info->callers--;
523 	if (info->callers)
524 		return;
525 
526 	if (!info->waiting_pause)
527 		return;
528 
529 	info->waiting_pause = 0;
530 	wake_up(&info->wq_pause);
531 }
532 
533 static int scsifront_queuecommand(struct Scsi_Host *shost,
534 				  struct scsi_cmnd *sc)
535 {
536 	struct vscsifrnt_info *info = shost_priv(shost);
537 	struct vscsifrnt_shadow *shadow = scsi_cmd_priv(sc);
538 	unsigned long flags;
539 	int err;
540 
541 	sc->result = 0;
542 
543 	shadow->sc  = sc;
544 	shadow->act = VSCSIIF_ACT_SCSI_CDB;
545 
546 	spin_lock_irqsave(shost->host_lock, flags);
547 	if (scsifront_enter(info)) {
548 		spin_unlock_irqrestore(shost->host_lock, flags);
549 		return SCSI_MLQUEUE_HOST_BUSY;
550 	}
551 
552 	err = map_data_for_request(info, sc, shadow);
553 	if (err < 0) {
554 		pr_debug("%s: err %d\n", __func__, err);
555 		scsifront_return(info);
556 		spin_unlock_irqrestore(shost->host_lock, flags);
557 		if (err == -ENOMEM)
558 			return SCSI_MLQUEUE_HOST_BUSY;
559 		sc->result = DID_ERROR << 16;
560 		scsi_done(sc);
561 		return 0;
562 	}
563 
564 	if (scsifront_do_request(info, shadow)) {
565 		scsifront_gnttab_done(info, shadow);
566 		goto busy;
567 	}
568 
569 	scsifront_return(info);
570 	spin_unlock_irqrestore(shost->host_lock, flags);
571 
572 	return 0;
573 
574 busy:
575 	scsifront_return(info);
576 	spin_unlock_irqrestore(shost->host_lock, flags);
577 	pr_debug("%s: busy\n", __func__);
578 	return SCSI_MLQUEUE_HOST_BUSY;
579 }
580 
581 /*
582  * Any exception handling (reset or abort) must be forwarded to the backend.
583  * We have to wait until an answer is returned. This answer contains the
584  * result to be returned to the requestor.
585  */
586 static int scsifront_action_handler(struct scsi_cmnd *sc, uint8_t act)
587 {
588 	struct Scsi_Host *host = sc->device->host;
589 	struct vscsifrnt_info *info = shost_priv(host);
590 	struct vscsifrnt_shadow *shadow, *s = scsi_cmd_priv(sc);
591 	int err = 0;
592 
593 	shadow = kzalloc(sizeof(*shadow), GFP_NOIO);
594 	if (!shadow)
595 		return FAILED;
596 
597 	shadow->act = act;
598 	shadow->rslt_reset = RSLT_RESET_WAITING;
599 	shadow->sc = sc;
600 	shadow->ref_rqid = s->rqid;
601 	init_waitqueue_head(&shadow->wq_reset);
602 
603 	spin_lock_irq(host->host_lock);
604 
605 	for (;;) {
606 		if (scsifront_enter(info))
607 			goto fail;
608 
609 		if (!scsifront_do_request(info, shadow))
610 			break;
611 
612 		scsifront_return(info);
613 		if (err)
614 			goto fail;
615 		info->wait_ring_available = 1;
616 		spin_unlock_irq(host->host_lock);
617 		err = wait_event_interruptible(info->wq_sync,
618 					       !info->wait_ring_available);
619 		spin_lock_irq(host->host_lock);
620 	}
621 
622 	spin_unlock_irq(host->host_lock);
623 	err = wait_event_interruptible(shadow->wq_reset, shadow->wait_reset);
624 	spin_lock_irq(host->host_lock);
625 
626 	if (!err) {
627 		err = shadow->rslt_reset;
628 		scsifront_put_rqid(info, shadow->rqid);
629 		kfree(shadow);
630 	} else {
631 		spin_lock(&info->shadow_lock);
632 		shadow->rslt_reset = RSLT_RESET_ERR;
633 		spin_unlock(&info->shadow_lock);
634 		err = FAILED;
635 	}
636 
637 	scsifront_return(info);
638 	spin_unlock_irq(host->host_lock);
639 	return err;
640 
641 fail:
642 	spin_unlock_irq(host->host_lock);
643 	kfree(shadow);
644 	return FAILED;
645 }
646 
647 static int scsifront_eh_abort_handler(struct scsi_cmnd *sc)
648 {
649 	pr_debug("%s\n", __func__);
650 	return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_ABORT);
651 }
652 
653 static int scsifront_dev_reset_handler(struct scsi_cmnd *sc)
654 {
655 	pr_debug("%s\n", __func__);
656 	return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_RESET);
657 }
658 
659 static int scsifront_sdev_configure(struct scsi_device *sdev)
660 {
661 	struct vscsifrnt_info *info = shost_priv(sdev->host);
662 	int err;
663 
664 	if (info && current == info->curr) {
665 		err = xenbus_printf(XBT_NIL, info->dev->nodename,
666 			      info->dev_state_path, "%d", XenbusStateConnected);
667 		if (err) {
668 			xenbus_dev_error(info->dev, err,
669 				"%s: writing dev_state_path", __func__);
670 			return err;
671 		}
672 	}
673 
674 	return 0;
675 }
676 
677 static void scsifront_sdev_destroy(struct scsi_device *sdev)
678 {
679 	struct vscsifrnt_info *info = shost_priv(sdev->host);
680 	int err;
681 
682 	if (info && current == info->curr) {
683 		err = xenbus_printf(XBT_NIL, info->dev->nodename,
684 			      info->dev_state_path, "%d", XenbusStateClosed);
685 		if (err)
686 			xenbus_dev_error(info->dev, err,
687 				"%s: writing dev_state_path", __func__);
688 	}
689 }
690 
691 static struct scsi_host_template scsifront_sht = {
692 	.module			= THIS_MODULE,
693 	.name			= "Xen SCSI frontend driver",
694 	.queuecommand		= scsifront_queuecommand,
695 	.eh_abort_handler	= scsifront_eh_abort_handler,
696 	.eh_device_reset_handler = scsifront_dev_reset_handler,
697 	.slave_configure	= scsifront_sdev_configure,
698 	.slave_destroy		= scsifront_sdev_destroy,
699 	.cmd_per_lun		= VSCSIIF_DEFAULT_CMD_PER_LUN,
700 	.can_queue		= VSCSIIF_MAX_REQS,
701 	.this_id		= -1,
702 	.cmd_size		= sizeof(struct vscsifrnt_shadow),
703 	.sg_tablesize		= VSCSIIF_SG_TABLESIZE,
704 	.proc_name		= "scsifront",
705 };
706 
707 static int scsifront_alloc_ring(struct vscsifrnt_info *info)
708 {
709 	struct xenbus_device *dev = info->dev;
710 	struct vscsiif_sring *sring;
711 	grant_ref_t gref;
712 	int err = -ENOMEM;
713 
714 	/***** Frontend to Backend ring start *****/
715 	sring = (struct vscsiif_sring *)__get_free_page(GFP_KERNEL);
716 	if (!sring) {
717 		xenbus_dev_fatal(dev, err,
718 			"fail to allocate shared ring (Front to Back)");
719 		return err;
720 	}
721 	SHARED_RING_INIT(sring);
722 	FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
723 
724 	err = xenbus_grant_ring(dev, sring, 1, &gref);
725 	if (err < 0) {
726 		free_page((unsigned long)sring);
727 		xenbus_dev_fatal(dev, err,
728 			"fail to grant shared ring (Front to Back)");
729 		return err;
730 	}
731 	info->ring_ref = gref;
732 
733 	err = xenbus_alloc_evtchn(dev, &info->evtchn);
734 	if (err) {
735 		xenbus_dev_fatal(dev, err, "xenbus_alloc_evtchn");
736 		goto free_gnttab;
737 	}
738 
739 	err = bind_evtchn_to_irq(info->evtchn);
740 	if (err <= 0) {
741 		xenbus_dev_fatal(dev, err, "bind_evtchn_to_irq");
742 		goto free_gnttab;
743 	}
744 
745 	info->irq = err;
746 
747 	err = request_threaded_irq(info->irq, NULL, scsifront_irq_fn,
748 				   IRQF_ONESHOT, "scsifront", info);
749 	if (err) {
750 		xenbus_dev_fatal(dev, err, "request_threaded_irq");
751 		goto free_irq;
752 	}
753 
754 	return 0;
755 
756 /* free resource */
757 free_irq:
758 	unbind_from_irqhandler(info->irq, info);
759 free_gnttab:
760 	gnttab_end_foreign_access(info->ring_ref,
761 				  (unsigned long)info->ring.sring);
762 
763 	return err;
764 }
765 
766 static void scsifront_free_ring(struct vscsifrnt_info *info)
767 {
768 	unbind_from_irqhandler(info->irq, info);
769 	gnttab_end_foreign_access(info->ring_ref,
770 				  (unsigned long)info->ring.sring);
771 }
772 
773 static int scsifront_init_ring(struct vscsifrnt_info *info)
774 {
775 	struct xenbus_device *dev = info->dev;
776 	struct xenbus_transaction xbt;
777 	int err;
778 
779 	pr_debug("%s\n", __func__);
780 
781 	err = scsifront_alloc_ring(info);
782 	if (err)
783 		return err;
784 	pr_debug("%s: %u %u\n", __func__, info->ring_ref, info->evtchn);
785 
786 again:
787 	err = xenbus_transaction_start(&xbt);
788 	if (err)
789 		xenbus_dev_fatal(dev, err, "starting transaction");
790 
791 	err = xenbus_printf(xbt, dev->nodename, "ring-ref", "%u",
792 			    info->ring_ref);
793 	if (err) {
794 		xenbus_dev_fatal(dev, err, "%s", "writing ring-ref");
795 		goto fail;
796 	}
797 
798 	err = xenbus_printf(xbt, dev->nodename, "event-channel", "%u",
799 			    info->evtchn);
800 
801 	if (err) {
802 		xenbus_dev_fatal(dev, err, "%s", "writing event-channel");
803 		goto fail;
804 	}
805 
806 	err = xenbus_transaction_end(xbt, 0);
807 	if (err) {
808 		if (err == -EAGAIN)
809 			goto again;
810 		xenbus_dev_fatal(dev, err, "completing transaction");
811 		goto free_sring;
812 	}
813 
814 	return 0;
815 
816 fail:
817 	xenbus_transaction_end(xbt, 1);
818 free_sring:
819 	scsifront_free_ring(info);
820 
821 	return err;
822 }
823 
824 
825 static int scsifront_probe(struct xenbus_device *dev,
826 			   const struct xenbus_device_id *id)
827 {
828 	struct vscsifrnt_info *info;
829 	struct Scsi_Host *host;
830 	int err = -ENOMEM;
831 	char name[TASK_COMM_LEN];
832 
833 	host = scsi_host_alloc(&scsifront_sht, sizeof(*info));
834 	if (!host) {
835 		xenbus_dev_fatal(dev, err, "fail to allocate scsi host");
836 		return err;
837 	}
838 	info = (struct vscsifrnt_info *)host->hostdata;
839 
840 	dev_set_drvdata(&dev->dev, info);
841 	info->dev = dev;
842 
843 	bitmap_fill(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
844 
845 	err = scsifront_init_ring(info);
846 	if (err) {
847 		scsi_host_put(host);
848 		return err;
849 	}
850 
851 	init_waitqueue_head(&info->wq_sync);
852 	init_waitqueue_head(&info->wq_pause);
853 	spin_lock_init(&info->shadow_lock);
854 
855 	snprintf(name, TASK_COMM_LEN, "vscsiif.%d", host->host_no);
856 
857 	host->max_id      = VSCSIIF_MAX_TARGET;
858 	host->max_channel = 0;
859 	host->max_lun     = VSCSIIF_MAX_LUN;
860 	host->max_sectors = (host->sg_tablesize - 1) * PAGE_SIZE / 512;
861 	host->max_cmd_len = VSCSIIF_MAX_COMMAND_SIZE;
862 
863 	err = scsi_add_host(host, &dev->dev);
864 	if (err) {
865 		dev_err(&dev->dev, "fail to add scsi host %d\n", err);
866 		goto free_sring;
867 	}
868 	info->host = host;
869 	info->host_active = 1;
870 
871 	xenbus_switch_state(dev, XenbusStateInitialised);
872 
873 	return 0;
874 
875 free_sring:
876 	scsifront_free_ring(info);
877 	scsi_host_put(host);
878 	return err;
879 }
880 
881 static int scsifront_resume(struct xenbus_device *dev)
882 {
883 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
884 	struct Scsi_Host *host = info->host;
885 	int err;
886 
887 	spin_lock_irq(host->host_lock);
888 
889 	/* Finish all still pending commands. */
890 	scsifront_finish_all(info);
891 
892 	spin_unlock_irq(host->host_lock);
893 
894 	/* Reconnect to dom0. */
895 	scsifront_free_ring(info);
896 	err = scsifront_init_ring(info);
897 	if (err) {
898 		dev_err(&dev->dev, "fail to resume %d\n", err);
899 		scsi_host_put(host);
900 		return err;
901 	}
902 
903 	xenbus_switch_state(dev, XenbusStateInitialised);
904 
905 	return 0;
906 }
907 
908 static int scsifront_suspend(struct xenbus_device *dev)
909 {
910 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
911 	struct Scsi_Host *host = info->host;
912 	int err = 0;
913 
914 	/* No new commands for the backend. */
915 	spin_lock_irq(host->host_lock);
916 	info->pause = 1;
917 	while (info->callers && !err) {
918 		info->waiting_pause = 1;
919 		info->wait_ring_available = 0;
920 		spin_unlock_irq(host->host_lock);
921 		wake_up(&info->wq_sync);
922 		err = wait_event_interruptible(info->wq_pause,
923 					       !info->waiting_pause);
924 		spin_lock_irq(host->host_lock);
925 	}
926 	spin_unlock_irq(host->host_lock);
927 	return err;
928 }
929 
930 static int scsifront_remove(struct xenbus_device *dev)
931 {
932 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
933 
934 	pr_debug("%s: %s removed\n", __func__, dev->nodename);
935 
936 	mutex_lock(&scsifront_mutex);
937 	if (info->host_active) {
938 		/* Scsi_host not yet removed */
939 		scsi_remove_host(info->host);
940 		info->host_active = 0;
941 	}
942 	mutex_unlock(&scsifront_mutex);
943 
944 	scsifront_free_ring(info);
945 	scsi_host_put(info->host);
946 
947 	return 0;
948 }
949 
950 static void scsifront_disconnect(struct vscsifrnt_info *info)
951 {
952 	struct xenbus_device *dev = info->dev;
953 	struct Scsi_Host *host = info->host;
954 
955 	pr_debug("%s: %s disconnect\n", __func__, dev->nodename);
956 
957 	/*
958 	 * When this function is executed, all devices of
959 	 * Frontend have been deleted.
960 	 * Therefore, it need not block I/O before remove_host.
961 	 */
962 
963 	mutex_lock(&scsifront_mutex);
964 	if (info->host_active) {
965 		scsi_remove_host(host);
966 		info->host_active = 0;
967 	}
968 	mutex_unlock(&scsifront_mutex);
969 
970 	xenbus_frontend_closed(dev);
971 }
972 
973 static void scsifront_do_lun_hotplug(struct vscsifrnt_info *info, int op)
974 {
975 	struct xenbus_device *dev = info->dev;
976 	int i, err = 0;
977 	char str[64];
978 	char **dir;
979 	unsigned int dir_n = 0;
980 	unsigned int device_state;
981 	unsigned int hst, chn, tgt, lun;
982 	struct scsi_device *sdev;
983 
984 	dir = xenbus_directory(XBT_NIL, dev->otherend, "vscsi-devs", &dir_n);
985 	if (IS_ERR(dir))
986 		return;
987 
988 	/* mark current task as the one allowed to modify device states */
989 	BUG_ON(info->curr);
990 	info->curr = current;
991 
992 	for (i = 0; i < dir_n; i++) {
993 		/* read status */
994 		snprintf(str, sizeof(str), "vscsi-devs/%s/state", dir[i]);
995 		err = xenbus_scanf(XBT_NIL, dev->otherend, str, "%u",
996 				   &device_state);
997 		if (XENBUS_EXIST_ERR(err))
998 			continue;
999 
1000 		/* virtual SCSI device */
1001 		snprintf(str, sizeof(str), "vscsi-devs/%s/v-dev", dir[i]);
1002 		err = xenbus_scanf(XBT_NIL, dev->otherend, str,
1003 				   "%u:%u:%u:%u", &hst, &chn, &tgt, &lun);
1004 		if (XENBUS_EXIST_ERR(err))
1005 			continue;
1006 
1007 		/*
1008 		 * Front device state path, used in slave_configure called
1009 		 * on successfull scsi_add_device, and in slave_destroy called
1010 		 * on remove of a device.
1011 		 */
1012 		snprintf(info->dev_state_path, sizeof(info->dev_state_path),
1013 			 "vscsi-devs/%s/state", dir[i]);
1014 
1015 		switch (op) {
1016 		case VSCSIFRONT_OP_ADD_LUN:
1017 			if (device_state != XenbusStateInitialised)
1018 				break;
1019 
1020 			if (scsi_add_device(info->host, chn, tgt, lun)) {
1021 				dev_err(&dev->dev, "scsi_add_device\n");
1022 				err = xenbus_printf(XBT_NIL, dev->nodename,
1023 					      info->dev_state_path,
1024 					      "%d", XenbusStateClosed);
1025 				if (err)
1026 					xenbus_dev_error(dev, err,
1027 						"%s: writing dev_state_path", __func__);
1028 			}
1029 			break;
1030 		case VSCSIFRONT_OP_DEL_LUN:
1031 			if (device_state != XenbusStateClosing)
1032 				break;
1033 
1034 			sdev = scsi_device_lookup(info->host, chn, tgt, lun);
1035 			if (sdev) {
1036 				scsi_remove_device(sdev);
1037 				scsi_device_put(sdev);
1038 			}
1039 			break;
1040 		case VSCSIFRONT_OP_READD_LUN:
1041 			if (device_state == XenbusStateConnected) {
1042 				err = xenbus_printf(XBT_NIL, dev->nodename,
1043 					      info->dev_state_path,
1044 					      "%d", XenbusStateConnected);
1045 				if (err)
1046 					xenbus_dev_error(dev, err,
1047 						"%s: writing dev_state_path", __func__);
1048 			}
1049 			break;
1050 		default:
1051 			break;
1052 		}
1053 	}
1054 
1055 	info->curr = NULL;
1056 
1057 	kfree(dir);
1058 }
1059 
1060 static void scsifront_read_backend_params(struct xenbus_device *dev,
1061 					  struct vscsifrnt_info *info)
1062 {
1063 	unsigned int sg_grant, nr_segs;
1064 	struct Scsi_Host *host = info->host;
1065 
1066 	sg_grant = xenbus_read_unsigned(dev->otherend, "feature-sg-grant", 0);
1067 	nr_segs = min_t(unsigned int, sg_grant, SG_ALL);
1068 	nr_segs = max_t(unsigned int, nr_segs, VSCSIIF_SG_TABLESIZE);
1069 	nr_segs = min_t(unsigned int, nr_segs,
1070 			VSCSIIF_SG_TABLESIZE * PAGE_SIZE /
1071 			sizeof(struct scsiif_request_segment));
1072 
1073 	if (!info->pause && sg_grant)
1074 		dev_info(&dev->dev, "using up to %d SG entries\n", nr_segs);
1075 	else if (info->pause && nr_segs < host->sg_tablesize)
1076 		dev_warn(&dev->dev,
1077 			 "SG entries decreased from %d to %u - device may not work properly anymore\n",
1078 			 host->sg_tablesize, nr_segs);
1079 
1080 	host->sg_tablesize = nr_segs;
1081 	host->max_sectors = (nr_segs - 1) * PAGE_SIZE / 512;
1082 }
1083 
1084 static void scsifront_backend_changed(struct xenbus_device *dev,
1085 				      enum xenbus_state backend_state)
1086 {
1087 	struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
1088 
1089 	pr_debug("%s: %p %u %u\n", __func__, dev, dev->state, backend_state);
1090 
1091 	switch (backend_state) {
1092 	case XenbusStateUnknown:
1093 	case XenbusStateInitialising:
1094 	case XenbusStateInitWait:
1095 	case XenbusStateInitialised:
1096 		break;
1097 
1098 	case XenbusStateConnected:
1099 		scsifront_read_backend_params(dev, info);
1100 
1101 		if (info->pause) {
1102 			scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_READD_LUN);
1103 			xenbus_switch_state(dev, XenbusStateConnected);
1104 			info->pause = 0;
1105 			return;
1106 		}
1107 
1108 		if (xenbus_read_driver_state(dev->nodename) ==
1109 		    XenbusStateInitialised)
1110 			scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1111 
1112 		if (dev->state != XenbusStateConnected)
1113 			xenbus_switch_state(dev, XenbusStateConnected);
1114 		break;
1115 
1116 	case XenbusStateClosed:
1117 		if (dev->state == XenbusStateClosed)
1118 			break;
1119 		fallthrough;	/* Missed the backend's Closing state */
1120 	case XenbusStateClosing:
1121 		scsifront_disconnect(info);
1122 		break;
1123 
1124 	case XenbusStateReconfiguring:
1125 		scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_DEL_LUN);
1126 		xenbus_switch_state(dev, XenbusStateReconfiguring);
1127 		break;
1128 
1129 	case XenbusStateReconfigured:
1130 		scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1131 		xenbus_switch_state(dev, XenbusStateConnected);
1132 		break;
1133 	}
1134 }
1135 
1136 static const struct xenbus_device_id scsifront_ids[] = {
1137 	{ "vscsi" },
1138 	{ "" }
1139 };
1140 
1141 static struct xenbus_driver scsifront_driver = {
1142 	.ids			= scsifront_ids,
1143 	.probe			= scsifront_probe,
1144 	.remove			= scsifront_remove,
1145 	.resume			= scsifront_resume,
1146 	.suspend		= scsifront_suspend,
1147 	.otherend_changed	= scsifront_backend_changed,
1148 };
1149 
1150 static int __init scsifront_init(void)
1151 {
1152 	if (!xen_domain())
1153 		return -ENODEV;
1154 
1155 	return xenbus_register_frontend(&scsifront_driver);
1156 }
1157 module_init(scsifront_init);
1158 
1159 static void __exit scsifront_exit(void)
1160 {
1161 	xenbus_unregister_driver(&scsifront_driver);
1162 }
1163 module_exit(scsifront_exit);
1164 
1165 MODULE_DESCRIPTION("Xen SCSI frontend driver");
1166 MODULE_LICENSE("GPL");
1167 MODULE_ALIAS("xen:vscsi");
1168 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");
1169