xref: /freebsd/sys/dev/xen/blkfront/blkfront.c (revision c9dbb1cc52b063bbd9ab078a7afc89a8696da659)
1 /*
2  * XenBSD block device driver
3  *
4  * Copyright (c) 2010-2013 Spectra Logic Corporation
5  * Copyright (c) 2009 Scott Long, Yahoo!
6  * Copyright (c) 2009 Frank Suchomel, Citrix
7  * Copyright (c) 2009 Doug F. Rabson, Citrix
8  * Copyright (c) 2005 Kip Macy
9  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
10  * Modifications by Mark A. Williamson are (c) Intel Research Cambridge
11  *
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining a copy
14  * of this software and associated documentation files (the "Software"), to
15  * deal in the Software without restriction, including without limitation the
16  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
17  * sell copies of the Software, and to permit persons to whom the Software is
18  * furnished to do so, subject to the following conditions:
19  *
20  * The above copyright notice and this permission notice shall be included in
21  * all copies or substantial portions of the Software.
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
28  * DEALINGS IN THE SOFTWARE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/kernel.h>
38 #include <vm/vm.h>
39 #include <vm/pmap.h>
40 
41 #include <sys/bio.h>
42 #include <sys/bus.h>
43 #include <sys/conf.h>
44 #include <sys/module.h>
45 #include <sys/sysctl.h>
46 
47 #include <machine/bus.h>
48 #include <sys/rman.h>
49 #include <machine/resource.h>
50 #include <machine/intr_machdep.h>
51 #include <machine/vmparam.h>
52 #include <sys/bus_dma.h>
53 
54 #include <xen/xen-os.h>
55 #include <xen/hypervisor.h>
56 #include <xen/xen_intr.h>
57 #include <xen/gnttab.h>
58 #include <xen/interface/grant_table.h>
59 #include <xen/interface/io/protocols.h>
60 #include <xen/xenbus/xenbusvar.h>
61 
62 #include <machine/_inttypes.h>
63 
64 #include <geom/geom_disk.h>
65 
66 #include <dev/xen/blkfront/block.h>
67 
68 #include "xenbus_if.h"
69 
70 /*--------------------------- Forward Declarations ---------------------------*/
71 static void xbd_closing(device_t);
72 static void xbd_startio(struct xbd_softc *sc);
73 
74 /*---------------------------------- Macros ----------------------------------*/
75 #if 0
76 #define DPRINTK(fmt, args...) printf("[XEN] %s:%d: " fmt ".\n", __func__, __LINE__, ##args)
77 #else
78 #define DPRINTK(fmt, args...)
79 #endif
80 
81 #define XBD_SECTOR_SHFT		9
82 
83 /*---------------------------- Global Static Data ----------------------------*/
84 static MALLOC_DEFINE(M_XENBLOCKFRONT, "xbd", "Xen Block Front driver data");
85 
86 static int xbd_enable_indirect = 1;
87 SYSCTL_NODE(_hw, OID_AUTO, xbd, CTLFLAG_RD, 0, "xbd driver parameters");
88 SYSCTL_INT(_hw_xbd, OID_AUTO, xbd_enable_indirect, CTLFLAG_RDTUN,
89     &xbd_enable_indirect, 0, "Enable xbd indirect segments");
90 
91 /*---------------------------- Command Processing ----------------------------*/
92 static void
93 xbd_freeze(struct xbd_softc *sc, xbd_flag_t xbd_flag)
94 {
95 	if (xbd_flag != XBDF_NONE && (sc->xbd_flags & xbd_flag) != 0)
96 		return;
97 
98 	sc->xbd_flags |= xbd_flag;
99 	sc->xbd_qfrozen_cnt++;
100 }
101 
102 static void
103 xbd_thaw(struct xbd_softc *sc, xbd_flag_t xbd_flag)
104 {
105 	if (xbd_flag != XBDF_NONE && (sc->xbd_flags & xbd_flag) == 0)
106 		return;
107 
108 	if (sc->xbd_qfrozen_cnt == 0)
109 		panic("%s: Thaw with flag 0x%x while not frozen.",
110 		    __func__, xbd_flag);
111 
112 	sc->xbd_flags &= ~xbd_flag;
113 	sc->xbd_qfrozen_cnt--;
114 }
115 
116 static void
117 xbd_cm_freeze(struct xbd_softc *sc, struct xbd_command *cm, xbdc_flag_t cm_flag)
118 {
119 	if ((cm->cm_flags & XBDCF_FROZEN) != 0)
120 		return;
121 
122 	cm->cm_flags |= XBDCF_FROZEN|cm_flag;
123 	xbd_freeze(sc, XBDF_NONE);
124 }
125 
126 static void
127 xbd_cm_thaw(struct xbd_softc *sc, struct xbd_command *cm)
128 {
129 	if ((cm->cm_flags & XBDCF_FROZEN) == 0)
130 		return;
131 
132 	cm->cm_flags &= ~XBDCF_FROZEN;
133 	xbd_thaw(sc, XBDF_NONE);
134 }
135 
136 static inline void
137 xbd_flush_requests(struct xbd_softc *sc)
138 {
139 	int notify;
140 
141 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->xbd_ring, notify);
142 
143 	if (notify)
144 		xen_intr_signal(sc->xen_intr_handle);
145 }
146 
147 static void
148 xbd_free_command(struct xbd_command *cm)
149 {
150 
151 	KASSERT((cm->cm_flags & XBDCF_Q_MASK) == XBD_Q_NONE,
152 	    ("Freeing command that is still on queue %d.",
153 	    cm->cm_flags & XBDCF_Q_MASK));
154 
155 	cm->cm_flags = XBDCF_INITIALIZER;
156 	cm->cm_bp = NULL;
157 	cm->cm_complete = NULL;
158 	xbd_enqueue_cm(cm, XBD_Q_FREE);
159 	xbd_thaw(cm->cm_sc, XBDF_CM_SHORTAGE);
160 }
161 
162 static void
163 xbd_mksegarray(bus_dma_segment_t *segs, int nsegs,
164     grant_ref_t * gref_head, int otherend_id, int readonly,
165     grant_ref_t * sg_ref, blkif_request_segment_t * sg)
166 {
167 	struct blkif_request_segment *last_block_sg = sg + nsegs;
168 	vm_paddr_t buffer_ma;
169 	uint64_t fsect, lsect;
170 	int ref;
171 
172 	while (sg < last_block_sg) {
173 		buffer_ma = segs->ds_addr;
174 		fsect = (buffer_ma & PAGE_MASK) >> XBD_SECTOR_SHFT;
175 		lsect = fsect + (segs->ds_len  >> XBD_SECTOR_SHFT) - 1;
176 
177 		KASSERT(lsect <= 7, ("XEN disk driver data cannot "
178 		    "cross a page boundary"));
179 
180 		/* install a grant reference. */
181 		ref = gnttab_claim_grant_reference(gref_head);
182 
183 		/*
184 		 * GNTTAB_LIST_END == 0xffffffff, but it is private
185 		 * to gnttab.c.
186 		 */
187 		KASSERT(ref != ~0, ("grant_reference failed"));
188 
189 		gnttab_grant_foreign_access_ref(
190 		    ref,
191 		    otherend_id,
192 		    buffer_ma >> PAGE_SHIFT,
193 		    readonly);
194 
195 		*sg_ref = ref;
196 		*sg = (struct blkif_request_segment) {
197 			.gref       = ref,
198 			.first_sect = fsect,
199 			.last_sect  = lsect
200 		};
201 		sg++;
202 		sg_ref++;
203 		segs++;
204 	}
205 }
206 
207 static void
208 xbd_queue_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
209 {
210 	struct xbd_softc *sc;
211 	struct xbd_command *cm;
212 	int op;
213 
214 	cm = arg;
215 	sc = cm->cm_sc;
216 
217 	if (error) {
218 		cm->cm_bp->bio_error = EIO;
219 		biodone(cm->cm_bp);
220 		xbd_free_command(cm);
221 		return;
222 	}
223 
224 	KASSERT(nsegs <= sc->xbd_max_request_segments,
225 	    ("Too many segments in a blkfront I/O"));
226 
227 	if (nsegs <= BLKIF_MAX_SEGMENTS_PER_REQUEST) {
228 		blkif_request_t	*ring_req;
229 
230 		/* Fill out a blkif_request_t structure. */
231 		ring_req = (blkif_request_t *)
232 		    RING_GET_REQUEST(&sc->xbd_ring, sc->xbd_ring.req_prod_pvt);
233 		sc->xbd_ring.req_prod_pvt++;
234 		ring_req->id = cm->cm_id;
235 		ring_req->operation = cm->cm_operation;
236 		ring_req->sector_number = cm->cm_sector_number;
237 		ring_req->handle = (blkif_vdev_t)(uintptr_t)sc->xbd_disk;
238 		ring_req->nr_segments = nsegs;
239 		cm->cm_nseg = nsegs;
240 		xbd_mksegarray(segs, nsegs, &cm->cm_gref_head,
241 		    xenbus_get_otherend_id(sc->xbd_dev),
242 		    cm->cm_operation == BLKIF_OP_WRITE,
243 		    cm->cm_sg_refs, ring_req->seg);
244 	} else {
245 		blkif_request_indirect_t *ring_req;
246 
247 		/* Fill out a blkif_request_indirect_t structure. */
248 		ring_req = (blkif_request_indirect_t *)
249 		    RING_GET_REQUEST(&sc->xbd_ring, sc->xbd_ring.req_prod_pvt);
250 		sc->xbd_ring.req_prod_pvt++;
251 		ring_req->id = cm->cm_id;
252 		ring_req->operation = BLKIF_OP_INDIRECT;
253 		ring_req->indirect_op = cm->cm_operation;
254 		ring_req->sector_number = cm->cm_sector_number;
255 		ring_req->handle = (blkif_vdev_t)(uintptr_t)sc->xbd_disk;
256 		ring_req->nr_segments = nsegs;
257 		cm->cm_nseg = nsegs;
258 		xbd_mksegarray(segs, nsegs, &cm->cm_gref_head,
259 		    xenbus_get_otherend_id(sc->xbd_dev),
260 		    cm->cm_operation == BLKIF_OP_WRITE,
261 		    cm->cm_sg_refs, cm->cm_indirectionpages);
262 		memcpy(ring_req->indirect_grefs, &cm->cm_indirectionrefs,
263 		    sizeof(grant_ref_t) * sc->xbd_max_request_indirectpages);
264 	}
265 
266 	if (cm->cm_operation == BLKIF_OP_READ)
267 		op = BUS_DMASYNC_PREREAD;
268 	else if (cm->cm_operation == BLKIF_OP_WRITE)
269 		op = BUS_DMASYNC_PREWRITE;
270 	else
271 		op = 0;
272 	bus_dmamap_sync(sc->xbd_io_dmat, cm->cm_map, op);
273 
274 	gnttab_free_grant_references(cm->cm_gref_head);
275 
276 	xbd_enqueue_cm(cm, XBD_Q_BUSY);
277 
278 	/*
279 	 * If bus dma had to asynchronously call us back to dispatch
280 	 * this command, we are no longer executing in the context of
281 	 * xbd_startio().  Thus we cannot rely on xbd_startio()'s call to
282 	 * xbd_flush_requests() to publish this command to the backend
283 	 * along with any other commands that it could batch.
284 	 */
285 	if ((cm->cm_flags & XBDCF_ASYNC_MAPPING) != 0)
286 		xbd_flush_requests(sc);
287 
288 	return;
289 }
290 
291 static int
292 xbd_queue_request(struct xbd_softc *sc, struct xbd_command *cm)
293 {
294 	int error;
295 
296 	error = bus_dmamap_load(sc->xbd_io_dmat, cm->cm_map, cm->cm_data,
297 	    cm->cm_datalen, xbd_queue_cb, cm, 0);
298 	if (error == EINPROGRESS) {
299 		/*
300 		 * Maintain queuing order by freezing the queue.  The next
301 		 * command may not require as many resources as the command
302 		 * we just attempted to map, so we can't rely on bus dma
303 		 * blocking for it too.
304 		 */
305 		xbd_cm_freeze(sc, cm, XBDCF_ASYNC_MAPPING);
306 		return (0);
307 	}
308 
309 	return (error);
310 }
311 
312 static void
313 xbd_restart_queue_callback(void *arg)
314 {
315 	struct xbd_softc *sc = arg;
316 
317 	mtx_lock(&sc->xbd_io_lock);
318 
319 	xbd_thaw(sc, XBDF_GNT_SHORTAGE);
320 
321 	xbd_startio(sc);
322 
323 	mtx_unlock(&sc->xbd_io_lock);
324 }
325 
326 static struct xbd_command *
327 xbd_bio_command(struct xbd_softc *sc)
328 {
329 	struct xbd_command *cm;
330 	struct bio *bp;
331 
332 	if (__predict_false(sc->xbd_state != XBD_STATE_CONNECTED))
333 		return (NULL);
334 
335 	bp = xbd_dequeue_bio(sc);
336 	if (bp == NULL)
337 		return (NULL);
338 
339 	if ((cm = xbd_dequeue_cm(sc, XBD_Q_FREE)) == NULL) {
340 		xbd_freeze(sc, XBDF_CM_SHORTAGE);
341 		xbd_requeue_bio(sc, bp);
342 		return (NULL);
343 	}
344 
345 	if (gnttab_alloc_grant_references(sc->xbd_max_request_segments,
346 	    &cm->cm_gref_head) != 0) {
347 		gnttab_request_free_callback(&sc->xbd_callback,
348 		    xbd_restart_queue_callback, sc,
349 		    sc->xbd_max_request_segments);
350 		xbd_freeze(sc, XBDF_GNT_SHORTAGE);
351 		xbd_requeue_bio(sc, bp);
352 		xbd_enqueue_cm(cm, XBD_Q_FREE);
353 		return (NULL);
354 	}
355 
356 	cm->cm_bp = bp;
357 	cm->cm_data = bp->bio_data;
358 	cm->cm_datalen = bp->bio_bcount;
359 	cm->cm_sector_number = (blkif_sector_t)bp->bio_pblkno;
360 
361 	switch (bp->bio_cmd) {
362 	case BIO_READ:
363 		cm->cm_operation = BLKIF_OP_READ;
364 		break;
365 	case BIO_WRITE:
366 		cm->cm_operation = BLKIF_OP_WRITE;
367 		if ((bp->bio_flags & BIO_ORDERED) != 0) {
368 			if ((sc->xbd_flags & XBDF_BARRIER) != 0) {
369 				cm->cm_operation = BLKIF_OP_WRITE_BARRIER;
370 			} else {
371 				/*
372 				 * Single step this command.
373 				 */
374 				cm->cm_flags |= XBDCF_Q_FREEZE;
375 				if (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
376 					/*
377 					 * Wait for in-flight requests to
378 					 * finish.
379 					 */
380 					xbd_freeze(sc, XBDF_WAIT_IDLE);
381 					xbd_requeue_cm(cm, XBD_Q_READY);
382 					return (NULL);
383 				}
384 			}
385 		}
386 		break;
387 	case BIO_FLUSH:
388 		if ((sc->xbd_flags & XBDF_FLUSH) != 0)
389 			cm->cm_operation = BLKIF_OP_FLUSH_DISKCACHE;
390 		else if ((sc->xbd_flags & XBDF_BARRIER) != 0)
391 			cm->cm_operation = BLKIF_OP_WRITE_BARRIER;
392 		else
393 			panic("flush request, but no flush support available");
394 		break;
395 	default:
396 		panic("unknown bio command %d", bp->bio_cmd);
397 	}
398 
399 	return (cm);
400 }
401 
402 /*
403  * Dequeue buffers and place them in the shared communication ring.
404  * Return when no more requests can be accepted or all buffers have
405  * been queued.
406  *
407  * Signal XEN once the ring has been filled out.
408  */
409 static void
410 xbd_startio(struct xbd_softc *sc)
411 {
412 	struct xbd_command *cm;
413 	int error, queued = 0;
414 
415 	mtx_assert(&sc->xbd_io_lock, MA_OWNED);
416 
417 	if (sc->xbd_state != XBD_STATE_CONNECTED)
418 		return;
419 
420 	while (!RING_FULL(&sc->xbd_ring)) {
421 
422 		if (sc->xbd_qfrozen_cnt != 0)
423 			break;
424 
425 		cm = xbd_dequeue_cm(sc, XBD_Q_READY);
426 
427 		if (cm == NULL)
428 		    cm = xbd_bio_command(sc);
429 
430 		if (cm == NULL)
431 			break;
432 
433 		if ((cm->cm_flags & XBDCF_Q_FREEZE) != 0) {
434 			/*
435 			 * Single step command.  Future work is
436 			 * held off until this command completes.
437 			 */
438 			xbd_cm_freeze(sc, cm, XBDCF_Q_FREEZE);
439 		}
440 
441 		if ((error = xbd_queue_request(sc, cm)) != 0) {
442 			printf("xbd_queue_request returned %d\n", error);
443 			break;
444 		}
445 		queued++;
446 	}
447 
448 	if (queued != 0)
449 		xbd_flush_requests(sc);
450 }
451 
452 static void
453 xbd_bio_complete(struct xbd_softc *sc, struct xbd_command *cm)
454 {
455 	struct bio *bp;
456 
457 	bp = cm->cm_bp;
458 
459 	if (__predict_false(cm->cm_status != BLKIF_RSP_OKAY)) {
460 		disk_err(bp, "disk error" , -1, 0);
461 		printf(" status: %x\n", cm->cm_status);
462 		bp->bio_flags |= BIO_ERROR;
463 	}
464 
465 	if (bp->bio_flags & BIO_ERROR)
466 		bp->bio_error = EIO;
467 	else
468 		bp->bio_resid = 0;
469 
470 	xbd_free_command(cm);
471 	biodone(bp);
472 }
473 
474 static void
475 xbd_int(void *xsc)
476 {
477 	struct xbd_softc *sc = xsc;
478 	struct xbd_command *cm;
479 	blkif_response_t *bret;
480 	RING_IDX i, rp;
481 	int op;
482 
483 	mtx_lock(&sc->xbd_io_lock);
484 
485 	if (__predict_false(sc->xbd_state == XBD_STATE_DISCONNECTED)) {
486 		mtx_unlock(&sc->xbd_io_lock);
487 		return;
488 	}
489 
490  again:
491 	rp = sc->xbd_ring.sring->rsp_prod;
492 	rmb(); /* Ensure we see queued responses up to 'rp'. */
493 
494 	for (i = sc->xbd_ring.rsp_cons; i != rp;) {
495 		bret = RING_GET_RESPONSE(&sc->xbd_ring, i);
496 		cm   = &sc->xbd_shadow[bret->id];
497 
498 		xbd_remove_cm(cm, XBD_Q_BUSY);
499 		gnttab_end_foreign_access_references(cm->cm_nseg,
500 		    cm->cm_sg_refs);
501 		i++;
502 
503 		if (cm->cm_operation == BLKIF_OP_READ)
504 			op = BUS_DMASYNC_POSTREAD;
505 		else if (cm->cm_operation == BLKIF_OP_WRITE ||
506 		    cm->cm_operation == BLKIF_OP_WRITE_BARRIER)
507 			op = BUS_DMASYNC_POSTWRITE;
508 		else
509 			op = 0;
510 		bus_dmamap_sync(sc->xbd_io_dmat, cm->cm_map, op);
511 		bus_dmamap_unload(sc->xbd_io_dmat, cm->cm_map);
512 
513 		/*
514 		 * Release any hold this command has on future command
515 		 * dispatch.
516 		 */
517 		xbd_cm_thaw(sc, cm);
518 
519 		/*
520 		 * Directly call the i/o complete routine to save an
521 		 * an indirection in the common case.
522 		 */
523 		cm->cm_status = bret->status;
524 		if (cm->cm_bp)
525 			xbd_bio_complete(sc, cm);
526 		else if (cm->cm_complete != NULL)
527 			cm->cm_complete(cm);
528 		else
529 			xbd_free_command(cm);
530 	}
531 
532 	sc->xbd_ring.rsp_cons = i;
533 
534 	if (i != sc->xbd_ring.req_prod_pvt) {
535 		int more_to_do;
536 		RING_FINAL_CHECK_FOR_RESPONSES(&sc->xbd_ring, more_to_do);
537 		if (more_to_do)
538 			goto again;
539 	} else {
540 		sc->xbd_ring.sring->rsp_event = i + 1;
541 	}
542 
543 	if (xbd_queue_length(sc, XBD_Q_BUSY) == 0)
544 		xbd_thaw(sc, XBDF_WAIT_IDLE);
545 
546 	xbd_startio(sc);
547 
548 	if (__predict_false(sc->xbd_state == XBD_STATE_SUSPENDED))
549 		wakeup(&sc->xbd_cm_q[XBD_Q_BUSY]);
550 
551 	mtx_unlock(&sc->xbd_io_lock);
552 }
553 
554 /*------------------------------- Dump Support -------------------------------*/
555 /**
556  * Quiesce the disk writes for a dump file before allowing the next buffer.
557  */
558 static void
559 xbd_quiesce(struct xbd_softc *sc)
560 {
561 	int mtd;
562 
563 	// While there are outstanding requests
564 	while (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
565 		RING_FINAL_CHECK_FOR_RESPONSES(&sc->xbd_ring, mtd);
566 		if (mtd) {
567 			/* Recieved request completions, update queue. */
568 			xbd_int(sc);
569 		}
570 		if (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
571 			/*
572 			 * Still pending requests, wait for the disk i/o
573 			 * to complete.
574 			 */
575 			HYPERVISOR_yield();
576 		}
577 	}
578 }
579 
580 /* Kernel dump function for a paravirtualized disk device */
581 static void
582 xbd_dump_complete(struct xbd_command *cm)
583 {
584 
585 	xbd_enqueue_cm(cm, XBD_Q_COMPLETE);
586 }
587 
588 static int
589 xbd_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset,
590     size_t length)
591 {
592 	struct disk *dp = arg;
593 	struct xbd_softc *sc = dp->d_drv1;
594 	struct xbd_command *cm;
595 	size_t chunk;
596 	int sbp;
597 	int rc = 0;
598 
599 	if (length <= 0)
600 		return (rc);
601 
602 	xbd_quiesce(sc);	/* All quiet on the western front. */
603 
604 	/*
605 	 * If this lock is held, then this module is failing, and a
606 	 * successful kernel dump is highly unlikely anyway.
607 	 */
608 	mtx_lock(&sc->xbd_io_lock);
609 
610 	/* Split the 64KB block as needed */
611 	for (sbp=0; length > 0; sbp++) {
612 		cm = xbd_dequeue_cm(sc, XBD_Q_FREE);
613 		if (cm == NULL) {
614 			mtx_unlock(&sc->xbd_io_lock);
615 			device_printf(sc->xbd_dev, "dump: no more commands?\n");
616 			return (EBUSY);
617 		}
618 
619 		if (gnttab_alloc_grant_references(sc->xbd_max_request_segments,
620 		    &cm->cm_gref_head) != 0) {
621 			xbd_free_command(cm);
622 			mtx_unlock(&sc->xbd_io_lock);
623 			device_printf(sc->xbd_dev, "no more grant allocs?\n");
624 			return (EBUSY);
625 		}
626 
627 		chunk = length > sc->xbd_max_request_size ?
628 		    sc->xbd_max_request_size : length;
629 		cm->cm_data = virtual;
630 		cm->cm_datalen = chunk;
631 		cm->cm_operation = BLKIF_OP_WRITE;
632 		cm->cm_sector_number = offset / dp->d_sectorsize;
633 		cm->cm_complete = xbd_dump_complete;
634 
635 		xbd_enqueue_cm(cm, XBD_Q_READY);
636 
637 		length -= chunk;
638 		offset += chunk;
639 		virtual = (char *) virtual + chunk;
640 	}
641 
642 	/* Tell DOM0 to do the I/O */
643 	xbd_startio(sc);
644 	mtx_unlock(&sc->xbd_io_lock);
645 
646 	/* Poll for the completion. */
647 	xbd_quiesce(sc);	/* All quite on the eastern front */
648 
649 	/* If there were any errors, bail out... */
650 	while ((cm = xbd_dequeue_cm(sc, XBD_Q_COMPLETE)) != NULL) {
651 		if (cm->cm_status != BLKIF_RSP_OKAY) {
652 			device_printf(sc->xbd_dev,
653 			    "Dump I/O failed at sector %jd\n",
654 			    cm->cm_sector_number);
655 			rc = EIO;
656 		}
657 		xbd_free_command(cm);
658 	}
659 
660 	return (rc);
661 }
662 
663 /*----------------------------- Disk Entrypoints -----------------------------*/
664 static int
665 xbd_open(struct disk *dp)
666 {
667 	struct xbd_softc *sc = dp->d_drv1;
668 
669 	if (sc == NULL) {
670 		printf("xb%d: not found", sc->xbd_unit);
671 		return (ENXIO);
672 	}
673 
674 	sc->xbd_flags |= XBDF_OPEN;
675 	sc->xbd_users++;
676 	return (0);
677 }
678 
679 static int
680 xbd_close(struct disk *dp)
681 {
682 	struct xbd_softc *sc = dp->d_drv1;
683 
684 	if (sc == NULL)
685 		return (ENXIO);
686 	sc->xbd_flags &= ~XBDF_OPEN;
687 	if (--(sc->xbd_users) == 0) {
688 		/*
689 		 * Check whether we have been instructed to close.  We will
690 		 * have ignored this request initially, as the device was
691 		 * still mounted.
692 		 */
693 		if (xenbus_get_otherend_state(sc->xbd_dev) ==
694 		    XenbusStateClosing)
695 			xbd_closing(sc->xbd_dev);
696 	}
697 	return (0);
698 }
699 
700 static int
701 xbd_ioctl(struct disk *dp, u_long cmd, void *addr, int flag, struct thread *td)
702 {
703 	struct xbd_softc *sc = dp->d_drv1;
704 
705 	if (sc == NULL)
706 		return (ENXIO);
707 
708 	return (ENOTTY);
709 }
710 
711 /*
712  * Read/write routine for a buffer.  Finds the proper unit, place it on
713  * the sortq and kick the controller.
714  */
715 static void
716 xbd_strategy(struct bio *bp)
717 {
718 	struct xbd_softc *sc = bp->bio_disk->d_drv1;
719 
720 	/* bogus disk? */
721 	if (sc == NULL) {
722 		bp->bio_error = EINVAL;
723 		bp->bio_flags |= BIO_ERROR;
724 		bp->bio_resid = bp->bio_bcount;
725 		biodone(bp);
726 		return;
727 	}
728 
729 	/*
730 	 * Place it in the queue of disk activities for this disk
731 	 */
732 	mtx_lock(&sc->xbd_io_lock);
733 
734 	xbd_enqueue_bio(sc, bp);
735 	xbd_startio(sc);
736 
737 	mtx_unlock(&sc->xbd_io_lock);
738 	return;
739 }
740 
741 /*------------------------------ Ring Management -----------------------------*/
742 static int
743 xbd_alloc_ring(struct xbd_softc *sc)
744 {
745 	blkif_sring_t *sring;
746 	uintptr_t sring_page_addr;
747 	int error;
748 	int i;
749 
750 	sring = malloc(sc->xbd_ring_pages * PAGE_SIZE, M_XENBLOCKFRONT,
751 	    M_NOWAIT|M_ZERO);
752 	if (sring == NULL) {
753 		xenbus_dev_fatal(sc->xbd_dev, ENOMEM, "allocating shared ring");
754 		return (ENOMEM);
755 	}
756 	SHARED_RING_INIT(sring);
757 	FRONT_RING_INIT(&sc->xbd_ring, sring, sc->xbd_ring_pages * PAGE_SIZE);
758 
759 	for (i = 0, sring_page_addr = (uintptr_t)sring;
760 	     i < sc->xbd_ring_pages;
761 	     i++, sring_page_addr += PAGE_SIZE) {
762 
763 		error = xenbus_grant_ring(sc->xbd_dev,
764 		    (vtophys(sring_page_addr) >> PAGE_SHIFT),
765 		    &sc->xbd_ring_ref[i]);
766 		if (error) {
767 			xenbus_dev_fatal(sc->xbd_dev, error,
768 			    "granting ring_ref(%d)", i);
769 			return (error);
770 		}
771 	}
772 	if (sc->xbd_ring_pages == 1) {
773 		error = xs_printf(XST_NIL, xenbus_get_node(sc->xbd_dev),
774 		    "ring-ref", "%u", sc->xbd_ring_ref[0]);
775 		if (error) {
776 			xenbus_dev_fatal(sc->xbd_dev, error,
777 			    "writing %s/ring-ref",
778 			    xenbus_get_node(sc->xbd_dev));
779 			return (error);
780 		}
781 	} else {
782 		for (i = 0; i < sc->xbd_ring_pages; i++) {
783 			char ring_ref_name[]= "ring_refXX";
784 
785 			snprintf(ring_ref_name, sizeof(ring_ref_name),
786 			    "ring-ref%u", i);
787 			error = xs_printf(XST_NIL, xenbus_get_node(sc->xbd_dev),
788 			     ring_ref_name, "%u", sc->xbd_ring_ref[i]);
789 			if (error) {
790 				xenbus_dev_fatal(sc->xbd_dev, error,
791 				    "writing %s/%s",
792 				    xenbus_get_node(sc->xbd_dev),
793 				    ring_ref_name);
794 				return (error);
795 			}
796 		}
797 	}
798 
799 	error = xen_intr_alloc_and_bind_local_port(sc->xbd_dev,
800 	    xenbus_get_otherend_id(sc->xbd_dev), NULL, xbd_int, sc,
801 	    INTR_TYPE_BIO | INTR_MPSAFE, &sc->xen_intr_handle);
802 	if (error) {
803 		xenbus_dev_fatal(sc->xbd_dev, error,
804 		    "xen_intr_alloc_and_bind_local_port failed");
805 		return (error);
806 	}
807 
808 	return (0);
809 }
810 
811 static void
812 xbd_free_ring(struct xbd_softc *sc)
813 {
814 	int i;
815 
816 	if (sc->xbd_ring.sring == NULL)
817 		return;
818 
819 	for (i = 0; i < sc->xbd_ring_pages; i++) {
820 		if (sc->xbd_ring_ref[i] != GRANT_REF_INVALID) {
821 			gnttab_end_foreign_access_ref(sc->xbd_ring_ref[i]);
822 			sc->xbd_ring_ref[i] = GRANT_REF_INVALID;
823 		}
824 	}
825 	free(sc->xbd_ring.sring, M_XENBLOCKFRONT);
826 	sc->xbd_ring.sring = NULL;
827 }
828 
829 /*-------------------------- Initialization/Teardown -------------------------*/
830 static int
831 xbd_feature_string(struct xbd_softc *sc, char *features, size_t len)
832 {
833 	struct sbuf sb;
834 	int feature_cnt;
835 
836 	sbuf_new(&sb, features, len, SBUF_FIXEDLEN);
837 
838 	feature_cnt = 0;
839 	if ((sc->xbd_flags & XBDF_FLUSH) != 0) {
840 		sbuf_printf(&sb, "flush");
841 		feature_cnt++;
842 	}
843 
844 	if ((sc->xbd_flags & XBDF_BARRIER) != 0) {
845 		if (feature_cnt != 0)
846 			sbuf_printf(&sb, ", ");
847 		sbuf_printf(&sb, "write_barrier");
848 		feature_cnt++;
849 	}
850 
851 	(void) sbuf_finish(&sb);
852 	return (sbuf_len(&sb));
853 }
854 
855 static int
856 xbd_sysctl_features(SYSCTL_HANDLER_ARGS)
857 {
858 	char features[80];
859 	struct xbd_softc *sc = arg1;
860 	int error;
861 	int len;
862 
863 	error = sysctl_wire_old_buffer(req, 0);
864 	if (error != 0)
865 		return (error);
866 
867 	len = xbd_feature_string(sc, features, sizeof(features));
868 
869 	/* len is -1 on error, which will make the SYSCTL_OUT a no-op. */
870 	return (SYSCTL_OUT(req, features, len + 1/*NUL*/));
871 }
872 
873 static void
874 xbd_setup_sysctl(struct xbd_softc *xbd)
875 {
876 	struct sysctl_ctx_list *sysctl_ctx = NULL;
877 	struct sysctl_oid *sysctl_tree = NULL;
878 	struct sysctl_oid_list *children;
879 
880 	sysctl_ctx = device_get_sysctl_ctx(xbd->xbd_dev);
881 	if (sysctl_ctx == NULL)
882 		return;
883 
884 	sysctl_tree = device_get_sysctl_tree(xbd->xbd_dev);
885 	if (sysctl_tree == NULL)
886 		return;
887 
888 	children = SYSCTL_CHILDREN(sysctl_tree);
889 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
890 	    "max_requests", CTLFLAG_RD, &xbd->xbd_max_requests, -1,
891 	    "maximum outstanding requests (negotiated)");
892 
893 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
894 	    "max_request_segments", CTLFLAG_RD,
895 	    &xbd->xbd_max_request_segments, 0,
896 	    "maximum number of pages per requests (negotiated)");
897 
898 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
899 	    "max_request_size", CTLFLAG_RD, &xbd->xbd_max_request_size, 0,
900 	    "maximum size in bytes of a request (negotiated)");
901 
902 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
903 	    "ring_pages", CTLFLAG_RD, &xbd->xbd_ring_pages, 0,
904 	    "communication channel pages (negotiated)");
905 
906 	SYSCTL_ADD_PROC(sysctl_ctx, children, OID_AUTO,
907 	    "features", CTLTYPE_STRING|CTLFLAG_RD, xbd, 0,
908 	    xbd_sysctl_features, "A", "protocol features (negotiated)");
909 }
910 
911 /*
912  * Translate Linux major/minor to an appropriate name and unit
913  * number. For HVM guests, this allows us to use the same drive names
914  * with blkfront as the emulated drives, easing transition slightly.
915  */
916 static void
917 xbd_vdevice_to_unit(uint32_t vdevice, int *unit, const char **name)
918 {
919 	static struct vdev_info {
920 		int major;
921 		int shift;
922 		int base;
923 		const char *name;
924 	} info[] = {
925 		{3,	6,	0,	"ada"},	/* ide0 */
926 		{22,	6,	2,	"ada"},	/* ide1 */
927 		{33,	6,	4,	"ada"},	/* ide2 */
928 		{34,	6,	6,	"ada"},	/* ide3 */
929 		{56,	6,	8,	"ada"},	/* ide4 */
930 		{57,	6,	10,	"ada"},	/* ide5 */
931 		{88,	6,	12,	"ada"},	/* ide6 */
932 		{89,	6,	14,	"ada"},	/* ide7 */
933 		{90,	6,	16,	"ada"},	/* ide8 */
934 		{91,	6,	18,	"ada"},	/* ide9 */
935 
936 		{8,	4,	0,	"da"},	/* scsi disk0 */
937 		{65,	4,	16,	"da"},	/* scsi disk1 */
938 		{66,	4,	32,	"da"},	/* scsi disk2 */
939 		{67,	4,	48,	"da"},	/* scsi disk3 */
940 		{68,	4,	64,	"da"},	/* scsi disk4 */
941 		{69,	4,	80,	"da"},	/* scsi disk5 */
942 		{70,	4,	96,	"da"},	/* scsi disk6 */
943 		{71,	4,	112,	"da"},	/* scsi disk7 */
944 		{128,	4,	128,	"da"},	/* scsi disk8 */
945 		{129,	4,	144,	"da"},	/* scsi disk9 */
946 		{130,	4,	160,	"da"},	/* scsi disk10 */
947 		{131,	4,	176,	"da"},	/* scsi disk11 */
948 		{132,	4,	192,	"da"},	/* scsi disk12 */
949 		{133,	4,	208,	"da"},	/* scsi disk13 */
950 		{134,	4,	224,	"da"},	/* scsi disk14 */
951 		{135,	4,	240,	"da"},	/* scsi disk15 */
952 
953 		{202,	4,	0,	"xbd"},	/* xbd */
954 
955 		{0,	0,	0,	NULL},
956 	};
957 	int major = vdevice >> 8;
958 	int minor = vdevice & 0xff;
959 	int i;
960 
961 	if (vdevice & (1 << 28)) {
962 		*unit = (vdevice & ((1 << 28) - 1)) >> 8;
963 		*name = "xbd";
964 		return;
965 	}
966 
967 	for (i = 0; info[i].major; i++) {
968 		if (info[i].major == major) {
969 			*unit = info[i].base + (minor >> info[i].shift);
970 			*name = info[i].name;
971 			return;
972 		}
973 	}
974 
975 	*unit = minor >> 4;
976 	*name = "xbd";
977 }
978 
979 int
980 xbd_instance_create(struct xbd_softc *sc, blkif_sector_t sectors,
981     int vdevice, uint16_t vdisk_info, unsigned long sector_size)
982 {
983 	char features[80];
984 	int unit, error = 0;
985 	const char *name;
986 
987 	xbd_vdevice_to_unit(vdevice, &unit, &name);
988 
989 	sc->xbd_unit = unit;
990 
991 	if (strcmp(name, "xbd") != 0)
992 		device_printf(sc->xbd_dev, "attaching as %s%d\n", name, unit);
993 
994 	if (xbd_feature_string(sc, features, sizeof(features)) > 0) {
995 		device_printf(sc->xbd_dev, "features: %s\n",
996 		    features);
997 	}
998 
999 	sc->xbd_disk = disk_alloc();
1000 	sc->xbd_disk->d_unit = sc->xbd_unit;
1001 	sc->xbd_disk->d_open = xbd_open;
1002 	sc->xbd_disk->d_close = xbd_close;
1003 	sc->xbd_disk->d_ioctl = xbd_ioctl;
1004 	sc->xbd_disk->d_strategy = xbd_strategy;
1005 	sc->xbd_disk->d_dump = xbd_dump;
1006 	sc->xbd_disk->d_name = name;
1007 	sc->xbd_disk->d_drv1 = sc;
1008 	sc->xbd_disk->d_sectorsize = sector_size;
1009 
1010 	sc->xbd_disk->d_mediasize = sectors * sector_size;
1011 	sc->xbd_disk->d_maxsize = sc->xbd_max_request_size;
1012 	sc->xbd_disk->d_flags = 0;
1013 	if ((sc->xbd_flags & (XBDF_FLUSH|XBDF_BARRIER)) != 0) {
1014 		sc->xbd_disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1015 		device_printf(sc->xbd_dev,
1016 		    "synchronize cache commands enabled.\n");
1017 	}
1018 	disk_create(sc->xbd_disk, DISK_VERSION);
1019 
1020 	return error;
1021 }
1022 
1023 static void
1024 xbd_free(struct xbd_softc *sc)
1025 {
1026 	int i;
1027 
1028 	/* Prevent new requests being issued until we fix things up. */
1029 	mtx_lock(&sc->xbd_io_lock);
1030 	sc->xbd_state = XBD_STATE_DISCONNECTED;
1031 	mtx_unlock(&sc->xbd_io_lock);
1032 
1033 	/* Free resources associated with old device channel. */
1034 	xbd_free_ring(sc);
1035 	if (sc->xbd_shadow) {
1036 
1037 		for (i = 0; i < sc->xbd_max_requests; i++) {
1038 			struct xbd_command *cm;
1039 
1040 			cm = &sc->xbd_shadow[i];
1041 			if (cm->cm_sg_refs != NULL) {
1042 				free(cm->cm_sg_refs, M_XENBLOCKFRONT);
1043 				cm->cm_sg_refs = NULL;
1044 			}
1045 
1046 			if (cm->cm_indirectionpages != NULL) {
1047 				gnttab_end_foreign_access_references(
1048 				    sc->xbd_max_request_indirectpages,
1049 				    &cm->cm_indirectionrefs[0]);
1050 				contigfree(cm->cm_indirectionpages, PAGE_SIZE *
1051 				    sc->xbd_max_request_indirectpages,
1052 				    M_XENBLOCKFRONT);
1053 				cm->cm_indirectionpages = NULL;
1054 			}
1055 
1056 			bus_dmamap_destroy(sc->xbd_io_dmat, cm->cm_map);
1057 		}
1058 		free(sc->xbd_shadow, M_XENBLOCKFRONT);
1059 		sc->xbd_shadow = NULL;
1060 
1061 		bus_dma_tag_destroy(sc->xbd_io_dmat);
1062 
1063 		xbd_initq_cm(sc, XBD_Q_FREE);
1064 		xbd_initq_cm(sc, XBD_Q_READY);
1065 		xbd_initq_cm(sc, XBD_Q_COMPLETE);
1066 	}
1067 
1068 	xen_intr_unbind(&sc->xen_intr_handle);
1069 
1070 }
1071 
1072 /*--------------------------- State Change Handlers --------------------------*/
1073 static void
1074 xbd_initialize(struct xbd_softc *sc)
1075 {
1076 	const char *otherend_path;
1077 	const char *node_path;
1078 	uint32_t max_ring_page_order;
1079 	int error;
1080 
1081 	if (xenbus_get_state(sc->xbd_dev) != XenbusStateInitialising) {
1082 		/* Initialization has already been performed. */
1083 		return;
1084 	}
1085 
1086 	/*
1087 	 * Protocol defaults valid even if negotiation for a
1088 	 * setting fails.
1089 	 */
1090 	max_ring_page_order = 0;
1091 	sc->xbd_ring_pages = 1;
1092 
1093 	/*
1094 	 * Protocol negotiation.
1095 	 *
1096 	 * \note xs_gather() returns on the first encountered error, so
1097 	 *       we must use independant calls in order to guarantee
1098 	 *       we don't miss information in a sparsly populated back-end
1099 	 *       tree.
1100 	 *
1101 	 * \note xs_scanf() does not update variables for unmatched
1102 	 *	 fields.
1103 	 */
1104 	otherend_path = xenbus_get_otherend_path(sc->xbd_dev);
1105 	node_path = xenbus_get_node(sc->xbd_dev);
1106 
1107 	/* Support both backend schemes for relaying ring page limits. */
1108 	(void)xs_scanf(XST_NIL, otherend_path,
1109 	    "max-ring-page-order", NULL, "%" PRIu32,
1110 	    &max_ring_page_order);
1111 	sc->xbd_ring_pages = 1 << max_ring_page_order;
1112 	(void)xs_scanf(XST_NIL, otherend_path,
1113 	    "max-ring-pages", NULL, "%" PRIu32,
1114 	    &sc->xbd_ring_pages);
1115 	if (sc->xbd_ring_pages < 1)
1116 		sc->xbd_ring_pages = 1;
1117 
1118 	if (sc->xbd_ring_pages > XBD_MAX_RING_PAGES) {
1119 		device_printf(sc->xbd_dev,
1120 		    "Back-end specified ring-pages of %u "
1121 		    "limited to front-end limit of %u.\n",
1122 		    sc->xbd_ring_pages, XBD_MAX_RING_PAGES);
1123 		sc->xbd_ring_pages = XBD_MAX_RING_PAGES;
1124 	}
1125 
1126 	if (powerof2(sc->xbd_ring_pages) == 0) {
1127 		uint32_t new_page_limit;
1128 
1129 		new_page_limit = 0x01 << (fls(sc->xbd_ring_pages) - 1);
1130 		device_printf(sc->xbd_dev,
1131 		    "Back-end specified ring-pages of %u "
1132 		    "is not a power of 2. Limited to %u.\n",
1133 		    sc->xbd_ring_pages, new_page_limit);
1134 		sc->xbd_ring_pages = new_page_limit;
1135 	}
1136 
1137 	sc->xbd_max_requests =
1138 	    BLKIF_MAX_RING_REQUESTS(sc->xbd_ring_pages * PAGE_SIZE);
1139 	if (sc->xbd_max_requests > XBD_MAX_REQUESTS) {
1140 		device_printf(sc->xbd_dev,
1141 		    "Back-end specified max_requests of %u "
1142 		    "limited to front-end limit of %zu.\n",
1143 		    sc->xbd_max_requests, XBD_MAX_REQUESTS);
1144 		sc->xbd_max_requests = XBD_MAX_REQUESTS;
1145 	}
1146 
1147 	if (xbd_alloc_ring(sc) != 0)
1148 		return;
1149 
1150 	/* Support both backend schemes for relaying ring page limits. */
1151 	if (sc->xbd_ring_pages > 1) {
1152 		error = xs_printf(XST_NIL, node_path,
1153 		    "num-ring-pages","%u",
1154 		    sc->xbd_ring_pages);
1155 		if (error) {
1156 			xenbus_dev_fatal(sc->xbd_dev, error,
1157 			    "writing %s/num-ring-pages",
1158 			    node_path);
1159 			return;
1160 		}
1161 
1162 		error = xs_printf(XST_NIL, node_path,
1163 		    "ring-page-order", "%u",
1164 		    fls(sc->xbd_ring_pages) - 1);
1165 		if (error) {
1166 			xenbus_dev_fatal(sc->xbd_dev, error,
1167 			    "writing %s/ring-page-order",
1168 			    node_path);
1169 			return;
1170 		}
1171 	}
1172 
1173 	error = xs_printf(XST_NIL, node_path, "event-channel",
1174 	    "%u", xen_intr_port(sc->xen_intr_handle));
1175 	if (error) {
1176 		xenbus_dev_fatal(sc->xbd_dev, error,
1177 		    "writing %s/event-channel",
1178 		    node_path);
1179 		return;
1180 	}
1181 
1182 	error = xs_printf(XST_NIL, node_path, "protocol",
1183 	    "%s", XEN_IO_PROTO_ABI_NATIVE);
1184 	if (error) {
1185 		xenbus_dev_fatal(sc->xbd_dev, error,
1186 		    "writing %s/protocol",
1187 		    node_path);
1188 		return;
1189 	}
1190 
1191 	xenbus_set_state(sc->xbd_dev, XenbusStateInitialised);
1192 }
1193 
1194 /*
1195  * Invoked when the backend is finally 'ready' (and has published
1196  * the details about the physical device - #sectors, size, etc).
1197  */
1198 static void
1199 xbd_connect(struct xbd_softc *sc)
1200 {
1201 	device_t dev = sc->xbd_dev;
1202 	unsigned long sectors, sector_size;
1203 	unsigned int binfo;
1204 	int err, feature_barrier, feature_flush;
1205 	int i, j;
1206 
1207 	if (sc->xbd_state == XBD_STATE_CONNECTED ||
1208 	    sc->xbd_state == XBD_STATE_SUSPENDED)
1209 		return;
1210 
1211 	DPRINTK("blkfront.c:connect:%s.\n", xenbus_get_otherend_path(dev));
1212 
1213 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1214 	    "sectors", "%lu", &sectors,
1215 	    "info", "%u", &binfo,
1216 	    "sector-size", "%lu", &sector_size,
1217 	    NULL);
1218 	if (err) {
1219 		xenbus_dev_fatal(dev, err,
1220 		    "reading backend fields at %s",
1221 		    xenbus_get_otherend_path(dev));
1222 		return;
1223 	}
1224 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1225 	     "feature-barrier", "%lu", &feature_barrier,
1226 	     NULL);
1227 	if (err == 0 && feature_barrier != 0)
1228 		sc->xbd_flags |= XBDF_BARRIER;
1229 
1230 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1231 	     "feature-flush-cache", "%lu", &feature_flush,
1232 	     NULL);
1233 	if (err == 0 && feature_flush != 0)
1234 		sc->xbd_flags |= XBDF_FLUSH;
1235 
1236 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1237 	    "feature-max-indirect-segments", "%" PRIu32,
1238 	    &sc->xbd_max_request_segments, NULL);
1239 	if ((err != 0) || (xbd_enable_indirect == 0))
1240 		sc->xbd_max_request_segments = 0;
1241 	if (sc->xbd_max_request_segments > XBD_MAX_INDIRECT_SEGMENTS)
1242 		sc->xbd_max_request_segments = XBD_MAX_INDIRECT_SEGMENTS;
1243 	if (sc->xbd_max_request_segments > XBD_SIZE_TO_SEGS(MAXPHYS))
1244 		sc->xbd_max_request_segments = XBD_SIZE_TO_SEGS(MAXPHYS);
1245 	sc->xbd_max_request_indirectpages =
1246 	    XBD_INDIRECT_SEGS_TO_PAGES(sc->xbd_max_request_segments);
1247 	if (sc->xbd_max_request_segments < BLKIF_MAX_SEGMENTS_PER_REQUEST)
1248 		sc->xbd_max_request_segments = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1249 	sc->xbd_max_request_size =
1250 	    XBD_SEGS_TO_SIZE(sc->xbd_max_request_segments);
1251 
1252 	/* Allocate datastructures based on negotiated values. */
1253 	err = bus_dma_tag_create(
1254 	    bus_get_dma_tag(sc->xbd_dev),	/* parent */
1255 	    512, PAGE_SIZE,			/* algnmnt, boundary */
1256 	    BUS_SPACE_MAXADDR,			/* lowaddr */
1257 	    BUS_SPACE_MAXADDR,			/* highaddr */
1258 	    NULL, NULL,				/* filter, filterarg */
1259 	    sc->xbd_max_request_size,
1260 	    sc->xbd_max_request_segments,
1261 	    PAGE_SIZE,				/* maxsegsize */
1262 	    BUS_DMA_ALLOCNOW,			/* flags */
1263 	    busdma_lock_mutex,			/* lockfunc */
1264 	    &sc->xbd_io_lock,			/* lockarg */
1265 	    &sc->xbd_io_dmat);
1266 	if (err != 0) {
1267 		xenbus_dev_fatal(sc->xbd_dev, err,
1268 		    "Cannot allocate parent DMA tag\n");
1269 		return;
1270 	}
1271 
1272 	/* Per-transaction data allocation. */
1273 	sc->xbd_shadow = malloc(sizeof(*sc->xbd_shadow) * sc->xbd_max_requests,
1274 	    M_XENBLOCKFRONT, M_NOWAIT|M_ZERO);
1275 	if (sc->xbd_shadow == NULL) {
1276 		bus_dma_tag_destroy(sc->xbd_io_dmat);
1277 		xenbus_dev_fatal(sc->xbd_dev, ENOMEM,
1278 		    "Cannot allocate request structures\n");
1279 		return;
1280 	}
1281 
1282 	for (i = 0; i < sc->xbd_max_requests; i++) {
1283 		struct xbd_command *cm;
1284 		void * indirectpages;
1285 
1286 		cm = &sc->xbd_shadow[i];
1287 		cm->cm_sg_refs = malloc(
1288 		    sizeof(grant_ref_t) * sc->xbd_max_request_segments,
1289 		    M_XENBLOCKFRONT, M_NOWAIT);
1290 		if (cm->cm_sg_refs == NULL)
1291 			break;
1292 		cm->cm_id = i;
1293 		cm->cm_flags = XBDCF_INITIALIZER;
1294 		cm->cm_sc = sc;
1295 		if (bus_dmamap_create(sc->xbd_io_dmat, 0, &cm->cm_map) != 0)
1296 			break;
1297 		if (sc->xbd_max_request_indirectpages > 0) {
1298 			indirectpages = contigmalloc(
1299 			    PAGE_SIZE * sc->xbd_max_request_indirectpages,
1300 			    M_XENBLOCKFRONT, M_ZERO, 0, ~0, PAGE_SIZE, 0);
1301 		} else {
1302 			indirectpages = NULL;
1303 		}
1304 		for (j = 0; j < sc->xbd_max_request_indirectpages; j++) {
1305 			if (gnttab_grant_foreign_access(
1306 			    xenbus_get_otherend_id(sc->xbd_dev),
1307 			    (vtophys(indirectpages) >> PAGE_SHIFT) + j,
1308 			    1 /* grant read-only access */,
1309 			    &cm->cm_indirectionrefs[j]))
1310 				break;
1311 		}
1312 		if (j < sc->xbd_max_request_indirectpages)
1313 			break;
1314 		cm->cm_indirectionpages = indirectpages;
1315 		xbd_free_command(cm);
1316 	}
1317 
1318 	if (sc->xbd_disk == NULL) {
1319 		device_printf(dev, "%juMB <%s> at %s",
1320 		    (uintmax_t) sectors / (1048576 / sector_size),
1321 		    device_get_desc(dev),
1322 		    xenbus_get_node(dev));
1323 		bus_print_child_footer(device_get_parent(dev), dev);
1324 
1325 		xbd_instance_create(sc, sectors, sc->xbd_vdevice, binfo,
1326 		    sector_size);
1327 	}
1328 
1329 	(void)xenbus_set_state(dev, XenbusStateConnected);
1330 
1331 	/* Kick pending requests. */
1332 	mtx_lock(&sc->xbd_io_lock);
1333 	sc->xbd_state = XBD_STATE_CONNECTED;
1334 	xbd_startio(sc);
1335 	sc->xbd_flags |= XBDF_READY;
1336 	mtx_unlock(&sc->xbd_io_lock);
1337 }
1338 
1339 /**
1340  * Handle the change of state of the backend to Closing.  We must delete our
1341  * device-layer structures now, to ensure that writes are flushed through to
1342  * the backend.  Once this is done, we can switch to Closed in
1343  * acknowledgement.
1344  */
1345 static void
1346 xbd_closing(device_t dev)
1347 {
1348 	struct xbd_softc *sc = device_get_softc(dev);
1349 
1350 	xenbus_set_state(dev, XenbusStateClosing);
1351 
1352 	DPRINTK("xbd_closing: %s removed\n", xenbus_get_node(dev));
1353 
1354 	if (sc->xbd_disk != NULL) {
1355 		disk_destroy(sc->xbd_disk);
1356 		sc->xbd_disk = NULL;
1357 	}
1358 
1359 	xenbus_set_state(dev, XenbusStateClosed);
1360 }
1361 
1362 /*---------------------------- NewBus Entrypoints ----------------------------*/
1363 static int
1364 xbd_probe(device_t dev)
1365 {
1366 	if (strcmp(xenbus_get_type(dev), "vbd") != 0)
1367 		return (ENXIO);
1368 
1369 	if (xen_hvm_domain() && xen_disable_pv_disks != 0)
1370 		return (ENXIO);
1371 
1372 	if (xen_hvm_domain()) {
1373 		int error;
1374 		char *type;
1375 
1376 		/*
1377 		 * When running in an HVM domain, IDE disk emulation is
1378 		 * disabled early in boot so that native drivers will
1379 		 * not see emulated hardware.  However, CDROM device
1380 		 * emulation cannot be disabled.
1381 		 *
1382 		 * Through use of FreeBSD's vm_guest and xen_hvm_domain()
1383 		 * APIs, we could modify the native CDROM driver to fail its
1384 		 * probe when running under Xen.  Unfortunatlely, the PV
1385 		 * CDROM support in XenServer (up through at least version
1386 		 * 6.2) isn't functional, so we instead rely on the emulated
1387 		 * CDROM instance, and fail to attach the PV one here in
1388 		 * the blkfront driver.
1389 		 */
1390 		error = xs_read(XST_NIL, xenbus_get_node(dev),
1391 		    "device-type", NULL, (void **) &type);
1392 		if (error)
1393 			return (ENXIO);
1394 
1395 		if (strncmp(type, "cdrom", 5) == 0) {
1396 			free(type, M_XENSTORE);
1397 			return (ENXIO);
1398 		}
1399 		free(type, M_XENSTORE);
1400 	}
1401 
1402 	device_set_desc(dev, "Virtual Block Device");
1403 	device_quiet(dev);
1404 	return (0);
1405 }
1406 
1407 /*
1408  * Setup supplies the backend dir, virtual device.  We place an event
1409  * channel and shared frame entries.  We watch backend to wait if it's
1410  * ok.
1411  */
1412 static int
1413 xbd_attach(device_t dev)
1414 {
1415 	struct xbd_softc *sc;
1416 	const char *name;
1417 	uint32_t vdevice;
1418 	int error;
1419 	int i;
1420 	int unit;
1421 
1422 	/* FIXME: Use dynamic device id if this is not set. */
1423 	error = xs_scanf(XST_NIL, xenbus_get_node(dev),
1424 	    "virtual-device", NULL, "%" PRIu32, &vdevice);
1425 	if (error)
1426 		error = xs_scanf(XST_NIL, xenbus_get_node(dev),
1427 		    "virtual-device-ext", NULL, "%" PRIu32, &vdevice);
1428 	if (error) {
1429 		xenbus_dev_fatal(dev, error, "reading virtual-device");
1430 		device_printf(dev, "Couldn't determine virtual device.\n");
1431 		return (error);
1432 	}
1433 
1434 	xbd_vdevice_to_unit(vdevice, &unit, &name);
1435 	if (!strcmp(name, "xbd"))
1436 		device_set_unit(dev, unit);
1437 
1438 	sc = device_get_softc(dev);
1439 	mtx_init(&sc->xbd_io_lock, "blkfront i/o lock", NULL, MTX_DEF);
1440 	xbd_initqs(sc);
1441 	for (i = 0; i < XBD_MAX_RING_PAGES; i++)
1442 		sc->xbd_ring_ref[i] = GRANT_REF_INVALID;
1443 
1444 	sc->xbd_dev = dev;
1445 	sc->xbd_vdevice = vdevice;
1446 	sc->xbd_state = XBD_STATE_DISCONNECTED;
1447 
1448 	xbd_setup_sysctl(sc);
1449 
1450 	/* Wait for backend device to publish its protocol capabilities. */
1451 	xenbus_set_state(dev, XenbusStateInitialising);
1452 
1453 	return (0);
1454 }
1455 
1456 static int
1457 xbd_detach(device_t dev)
1458 {
1459 	struct xbd_softc *sc = device_get_softc(dev);
1460 
1461 	DPRINTK("%s: %s removed\n", __func__, xenbus_get_node(dev));
1462 
1463 	xbd_free(sc);
1464 	mtx_destroy(&sc->xbd_io_lock);
1465 
1466 	return 0;
1467 }
1468 
1469 static int
1470 xbd_suspend(device_t dev)
1471 {
1472 	struct xbd_softc *sc = device_get_softc(dev);
1473 	int retval;
1474 	int saved_state;
1475 
1476 	/* Prevent new requests being issued until we fix things up. */
1477 	mtx_lock(&sc->xbd_io_lock);
1478 	saved_state = sc->xbd_state;
1479 	sc->xbd_state = XBD_STATE_SUSPENDED;
1480 
1481 	/* Wait for outstanding I/O to drain. */
1482 	retval = 0;
1483 	while (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
1484 		if (msleep(&sc->xbd_cm_q[XBD_Q_BUSY], &sc->xbd_io_lock,
1485 		    PRIBIO, "blkf_susp", 30 * hz) == EWOULDBLOCK) {
1486 			retval = EBUSY;
1487 			break;
1488 		}
1489 	}
1490 	mtx_unlock(&sc->xbd_io_lock);
1491 
1492 	if (retval != 0)
1493 		sc->xbd_state = saved_state;
1494 
1495 	return (retval);
1496 }
1497 
1498 static int
1499 xbd_resume(device_t dev)
1500 {
1501 	struct xbd_softc *sc = device_get_softc(dev);
1502 
1503 	DPRINTK("xbd_resume: %s\n", xenbus_get_node(dev));
1504 
1505 	xbd_free(sc);
1506 	xbd_initialize(sc);
1507 	return (0);
1508 }
1509 
1510 /**
1511  * Callback received when the backend's state changes.
1512  */
1513 static void
1514 xbd_backend_changed(device_t dev, XenbusState backend_state)
1515 {
1516 	struct xbd_softc *sc = device_get_softc(dev);
1517 
1518 	DPRINTK("backend_state=%d\n", backend_state);
1519 
1520 	switch (backend_state) {
1521 	case XenbusStateUnknown:
1522 	case XenbusStateInitialising:
1523 	case XenbusStateReconfigured:
1524 	case XenbusStateReconfiguring:
1525 	case XenbusStateClosed:
1526 		break;
1527 
1528 	case XenbusStateInitWait:
1529 	case XenbusStateInitialised:
1530 		xbd_initialize(sc);
1531 		break;
1532 
1533 	case XenbusStateConnected:
1534 		xbd_initialize(sc);
1535 		xbd_connect(sc);
1536 		break;
1537 
1538 	case XenbusStateClosing:
1539 		if (sc->xbd_users > 0)
1540 			xenbus_dev_error(dev, -EBUSY,
1541 			    "Device in use; refusing to close");
1542 		else
1543 			xbd_closing(dev);
1544 		break;
1545 	}
1546 }
1547 
1548 /*---------------------------- NewBus Registration ---------------------------*/
1549 static device_method_t xbd_methods[] = {
1550 	/* Device interface */
1551 	DEVMETHOD(device_probe,         xbd_probe),
1552 	DEVMETHOD(device_attach,        xbd_attach),
1553 	DEVMETHOD(device_detach,        xbd_detach),
1554 	DEVMETHOD(device_shutdown,      bus_generic_shutdown),
1555 	DEVMETHOD(device_suspend,       xbd_suspend),
1556 	DEVMETHOD(device_resume,        xbd_resume),
1557 
1558 	/* Xenbus interface */
1559 	DEVMETHOD(xenbus_otherend_changed, xbd_backend_changed),
1560 
1561 	{ 0, 0 }
1562 };
1563 
1564 static driver_t xbd_driver = {
1565 	"xbd",
1566 	xbd_methods,
1567 	sizeof(struct xbd_softc),
1568 };
1569 devclass_t xbd_devclass;
1570 
1571 DRIVER_MODULE(xbd, xenbusb_front, xbd_driver, xbd_devclass, 0, 0);
1572