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