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