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