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