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