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