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