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