xref: /illumos-gate/usr/src/uts/common/xen/io/xdf.c (revision d1aea6f139360e9e7f1504facb24f8521047b15c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * xdf.c - Xen Virtual Block Device Driver
29  * TODO:
30  *	- support alternate block size (currently only DEV_BSIZE supported)
31  *	- revalidate geometry for removable devices
32  *
33  * This driver export solaris disk device nodes, accepts IO requests from
34  * those nodes, and services those requests by talking to a backend device
35  * in another domain.
36  *
37  * Communication with the backend device is done via a ringbuffer (which is
38  * managed via xvdi interfaces) and dma memory (which is managed via ddi
39  * interfaces).
40  *
41  * Communication with the backend device is dependant upon establishing a
42  * connection to the backend device.  This connection process involves
43  * reading device configuration information from xenbus and publishing
44  * some frontend runtime configuration parameters via the xenbus (for
45  * consumption by the backend).  Once we've published runtime configuration
46  * information via the xenbus, the backend device can enter the connected
47  * state and we'll enter the XD_CONNECTED state.  But before we can allow
48  * random IO to begin, we need to do IO to the backend device to determine
49  * the device label and if flush operations are supported.  Once this is
50  * done we enter the XD_READY state and can process any IO operations.
51  *
52  * We recieve notifications of xenbus state changes for the backend device
53  * (aka, the "other end") via the xdf_oe_change() callback.  This callback
54  * is single threaded, meaning that we can't recieve new notification of
55  * other end state changes while we're processing an outstanding
56  * notification of an other end state change.  There for we can't do any
57  * blocking operations from the xdf_oe_change() callback.  This is why we
58  * have a seperate taskq (xdf_ready_tq) which exists to do the necessary
59  * IO to get us from the XD_CONNECTED to the XD_READY state.  All IO
60  * generated by the xdf_ready_tq thread (xdf_ready_tq_thread) will go
61  * throught xdf_lb_rdwr(), which is a synchronous IO interface.  IOs
62  * generated by the xdf_ready_tq_thread thread have priority over all
63  * other IO requests.
64  *
65  * We also communicate with the backend device via the xenbus "media-req"
66  * (XBP_MEDIA_REQ) property.  For more information on this see the
67  * comments in blkif.h.
68  */
69 
70 #include <io/xdf.h>
71 
72 #include <sys/conf.h>
73 #include <sys/dkio.h>
74 #include <sys/promif.h>
75 #include <sys/sysmacros.h>
76 #include <sys/kstat.h>
77 #include <sys/mach_mmu.h>
78 #ifdef XPV_HVM_DRIVER
79 #include <sys/xpv_support.h>
80 #include <sys/sunndi.h>
81 #else /* !XPV_HVM_DRIVER */
82 #include <sys/evtchn_impl.h>
83 #endif /* !XPV_HVM_DRIVER */
84 #include <public/io/xenbus.h>
85 #include <xen/sys/xenbus_impl.h>
86 #include <sys/scsi/generic/inquiry.h>
87 #include <xen/io/blkif_impl.h>
88 #include <sys/fdio.h>
89 #include <sys/cdio.h>
90 
91 /*
92  * DEBUG_EVAL can be used to include debug only statements without
93  * having to use '#ifdef DEBUG' statements
94  */
95 #ifdef DEBUG
96 #define	DEBUG_EVAL(x)	(x)
97 #else /* !DEBUG */
98 #define	DEBUG_EVAL(x)
99 #endif /* !DEBUG */
100 
101 #define	XDF_DRAIN_MSEC_DELAY		(50*1000)	/* 00.05 sec */
102 #define	XDF_DRAIN_RETRY_COUNT		200		/* 10.00 sec */
103 
104 #define	INVALID_DOMID	((domid_t)-1)
105 #define	FLUSH_DISKCACHE	0x1
106 #define	WRITE_BARRIER	0x2
107 #define	DEFAULT_FLUSH_BLOCK	156 /* block to write to cause a cache flush */
108 #define	USE_WRITE_BARRIER(vdp)						\
109 	((vdp)->xdf_feature_barrier && !(vdp)->xdf_flush_supported)
110 #define	USE_FLUSH_DISKCACHE(vdp)					\
111 	((vdp)->xdf_feature_barrier && (vdp)->xdf_flush_supported)
112 #define	IS_WRITE_BARRIER(vdp, bp)					\
113 	(!IS_READ(bp) && USE_WRITE_BARRIER(vdp) &&			\
114 	((bp)->b_un.b_addr == (vdp)->xdf_cache_flush_block))
115 #define	IS_FLUSH_DISKCACHE(bp)						\
116 	(!IS_READ(bp) && USE_FLUSH_DISKCACHE(vdp) && ((bp)->b_bcount == 0))
117 
118 #define	VREQ_DONE(vreq)							\
119 	VOID2BOOLEAN(((vreq)->v_status == VREQ_DMAWIN_DONE) &&		\
120 	    (((vreq)->v_flush_diskcache == FLUSH_DISKCACHE) ||		\
121 	    (((vreq)->v_dmaw + 1) == (vreq)->v_ndmaws)))
122 
123 #define	BP_VREQ(bp)		((v_req_t *)((bp)->av_back))
124 #define	BP_VREQ_SET(bp, vreq)	(((bp)->av_back = (buf_t *)(vreq)))
125 
126 extern int		do_polled_io;
127 
128 /* run-time tunables that we don't want the compiler to optimize away */
129 volatile int		xdf_debug = 0;
130 volatile boolean_t	xdf_barrier_flush_disable = B_FALSE;
131 
132 /* per module globals */
133 major_t			xdf_major;
134 static void		*xdf_ssp;
135 static kmem_cache_t	*xdf_vreq_cache;
136 static kmem_cache_t	*xdf_gs_cache;
137 static int		xdf_maxphys = XB_MAXPHYS;
138 static diskaddr_t	xdf_flush_block = DEFAULT_FLUSH_BLOCK;
139 static int		xdf_fbrewrites;	/* flush block re-write count */
140 
141 /* misc public functions (used by xdf_shell.c) */
142 int xdf_lb_rdwr(dev_info_t *, uchar_t, void *, diskaddr_t, size_t, void *);
143 int xdf_lb_getinfo(dev_info_t *, int, void *, void *);
144 
145 /*  misc private functions */
146 static void xdf_io_start(xdf_t *);
147 
148 /* callbacks from commmon label */
149 static cmlb_tg_ops_t xdf_lb_ops = {
150 	TG_DK_OPS_VERSION_1,
151 	xdf_lb_rdwr,
152 	xdf_lb_getinfo
153 };
154 
155 /*
156  * I/O buffer DMA attributes
157  * Make sure: one DMA window contains BLKIF_MAX_SEGMENTS_PER_REQUEST at most
158  */
159 static ddi_dma_attr_t xb_dma_attr = {
160 	DMA_ATTR_V0,
161 	(uint64_t)0,			/* lowest address */
162 	(uint64_t)0xffffffffffffffff,	/* highest usable address */
163 	(uint64_t)0xffffff,		/* DMA counter limit max */
164 	(uint64_t)XB_BSIZE,		/* alignment in bytes */
165 	XB_BSIZE - 1,			/* bitmap of burst sizes */
166 	XB_BSIZE,			/* min transfer */
167 	(uint64_t)XB_MAX_XFER, 		/* maximum transfer */
168 	(uint64_t)PAGEOFFSET,		/* 1 page segment length  */
169 	BLKIF_MAX_SEGMENTS_PER_REQUEST,	/* maximum number of segments */
170 	XB_BSIZE,			/* granularity */
171 	0,				/* flags (reserved) */
172 };
173 
174 static ddi_device_acc_attr_t xc_acc_attr = {
175 	DDI_DEVICE_ATTR_V0,
176 	DDI_NEVERSWAP_ACC,
177 	DDI_STRICTORDER_ACC
178 };
179 
180 static void
181 xdf_timeout_handler(void *arg)
182 {
183 	xdf_t *vdp = arg;
184 
185 	mutex_enter(&vdp->xdf_dev_lk);
186 	vdp->xdf_timeout_id = 0;
187 	mutex_exit(&vdp->xdf_dev_lk);
188 
189 	/* new timeout thread could be re-scheduled */
190 	xdf_io_start(vdp);
191 }
192 
193 /*
194  * callback func when DMA/GTE resources is available
195  *
196  * Note: we only register one callback function to grant table subsystem
197  * since we only have one 'struct gnttab_free_callback' in xdf_t.
198  */
199 static int
200 xdf_dmacallback(caddr_t arg)
201 {
202 	xdf_t *vdp = (xdf_t *)arg;
203 	ASSERT(vdp != NULL);
204 
205 	DPRINTF(DMA_DBG, ("xdf@%s: DMA callback started\n",
206 	    vdp->xdf_addr));
207 
208 	ddi_trigger_softintr(vdp->xdf_softintr_id);
209 	return (DDI_DMA_CALLBACK_DONE);
210 }
211 
212 static ge_slot_t *
213 gs_get(xdf_t *vdp, int isread)
214 {
215 	grant_ref_t gh;
216 	ge_slot_t *gs;
217 
218 	/* try to alloc GTEs needed in this slot, first */
219 	if (gnttab_alloc_grant_references(
220 	    BLKIF_MAX_SEGMENTS_PER_REQUEST, &gh) == -1) {
221 		if (vdp->xdf_gnt_callback.next == NULL) {
222 			SETDMACBON(vdp);
223 			gnttab_request_free_callback(
224 			    &vdp->xdf_gnt_callback,
225 			    (void (*)(void *))xdf_dmacallback,
226 			    (void *)vdp,
227 			    BLKIF_MAX_SEGMENTS_PER_REQUEST);
228 		}
229 		return (NULL);
230 	}
231 
232 	gs = kmem_cache_alloc(xdf_gs_cache, KM_NOSLEEP);
233 	if (gs == NULL) {
234 		gnttab_free_grant_references(gh);
235 		if (vdp->xdf_timeout_id == 0)
236 			/* restart I/O after one second */
237 			vdp->xdf_timeout_id =
238 			    timeout(xdf_timeout_handler, vdp, hz);
239 		return (NULL);
240 	}
241 
242 	/* init gs_slot */
243 	gs->gs_oeid = vdp->xdf_peer;
244 	gs->gs_isread = isread;
245 	gs->gs_ghead = gh;
246 	gs->gs_ngrefs = 0;
247 
248 	return (gs);
249 }
250 
251 static void
252 gs_free(ge_slot_t *gs)
253 {
254 	int		i;
255 
256 	/* release all grant table entry resources used in this slot */
257 	for (i = 0; i < gs->gs_ngrefs; i++)
258 		gnttab_end_foreign_access(gs->gs_ge[i], !gs->gs_isread, 0);
259 	gnttab_free_grant_references(gs->gs_ghead);
260 	list_remove(&gs->gs_vreq->v_gs, gs);
261 	kmem_cache_free(xdf_gs_cache, gs);
262 }
263 
264 static grant_ref_t
265 gs_grant(ge_slot_t *gs, mfn_t mfn)
266 {
267 	grant_ref_t gr = gnttab_claim_grant_reference(&gs->gs_ghead);
268 
269 	ASSERT(gr != -1);
270 	ASSERT(gs->gs_ngrefs < BLKIF_MAX_SEGMENTS_PER_REQUEST);
271 	gs->gs_ge[gs->gs_ngrefs++] = gr;
272 	gnttab_grant_foreign_access_ref(gr, gs->gs_oeid, mfn, !gs->gs_isread);
273 
274 	return (gr);
275 }
276 
277 /*
278  * Alloc a vreq for this bp
279  * bp->av_back contains the pointer to the vreq upon return
280  */
281 static v_req_t *
282 vreq_get(xdf_t *vdp, buf_t *bp)
283 {
284 	v_req_t *vreq = NULL;
285 
286 	ASSERT(BP_VREQ(bp) == NULL);
287 
288 	vreq = kmem_cache_alloc(xdf_vreq_cache, KM_NOSLEEP);
289 	if (vreq == NULL) {
290 		if (vdp->xdf_timeout_id == 0)
291 			/* restart I/O after one second */
292 			vdp->xdf_timeout_id =
293 			    timeout(xdf_timeout_handler, vdp, hz);
294 		return (NULL);
295 	}
296 	bzero(vreq, sizeof (v_req_t));
297 	list_create(&vreq->v_gs, sizeof (ge_slot_t),
298 	    offsetof(ge_slot_t, gs_vreq_link));
299 	vreq->v_buf = bp;
300 	vreq->v_status = VREQ_INIT;
301 	vreq->v_runq = B_FALSE;
302 	BP_VREQ_SET(bp, vreq);
303 	/* init of other fields in vreq is up to the caller */
304 
305 	list_insert_head(&vdp->xdf_vreq_act, (void *)vreq);
306 
307 	return (vreq);
308 }
309 
310 static void
311 vreq_free(xdf_t *vdp, v_req_t *vreq)
312 {
313 	buf_t	*bp = vreq->v_buf;
314 
315 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
316 	ASSERT(BP_VREQ(bp) == vreq);
317 
318 	list_remove(&vdp->xdf_vreq_act, vreq);
319 
320 	if (vreq->v_flush_diskcache == FLUSH_DISKCACHE)
321 		goto done;
322 
323 	switch (vreq->v_status) {
324 	case VREQ_DMAWIN_DONE:
325 	case VREQ_GS_ALLOCED:
326 	case VREQ_DMABUF_BOUND:
327 		(void) ddi_dma_unbind_handle(vreq->v_dmahdl);
328 		/*FALLTHRU*/
329 	case VREQ_DMAMEM_ALLOCED:
330 		if (!ALIGNED_XFER(bp)) {
331 			ASSERT(vreq->v_abuf != NULL);
332 			if (!IS_ERROR(bp) && IS_READ(bp))
333 				bcopy(vreq->v_abuf, bp->b_un.b_addr,
334 				    bp->b_bcount);
335 			ddi_dma_mem_free(&vreq->v_align);
336 		}
337 		/*FALLTHRU*/
338 	case VREQ_MEMDMAHDL_ALLOCED:
339 		if (!ALIGNED_XFER(bp))
340 			ddi_dma_free_handle(&vreq->v_memdmahdl);
341 		/*FALLTHRU*/
342 	case VREQ_DMAHDL_ALLOCED:
343 		ddi_dma_free_handle(&vreq->v_dmahdl);
344 		break;
345 	default:
346 		break;
347 	}
348 done:
349 	ASSERT(!vreq->v_runq);
350 	list_destroy(&vreq->v_gs);
351 	kmem_cache_free(xdf_vreq_cache, vreq);
352 }
353 
354 /*
355  * Snarf new data if our flush block was re-written
356  */
357 static void
358 check_fbwrite(xdf_t *vdp, buf_t *bp, daddr_t blkno)
359 {
360 	int nblks;
361 	boolean_t mapin;
362 
363 	if (IS_WRITE_BARRIER(vdp, bp))
364 		return; /* write was a flush write */
365 
366 	mapin = B_FALSE;
367 	nblks = bp->b_bcount >> DEV_BSHIFT;
368 	if (xdf_flush_block >= blkno && xdf_flush_block < (blkno + nblks)) {
369 		xdf_fbrewrites++;
370 		if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
371 			mapin = B_TRUE;
372 			bp_mapin(bp);
373 		}
374 		bcopy(bp->b_un.b_addr +
375 		    ((xdf_flush_block - blkno) << DEV_BSHIFT),
376 		    vdp->xdf_cache_flush_block, DEV_BSIZE);
377 		if (mapin)
378 			bp_mapout(bp);
379 	}
380 }
381 
382 /*
383  * Initalize the DMA and grant table resources for the buf
384  */
385 static int
386 vreq_setup(xdf_t *vdp, v_req_t *vreq)
387 {
388 	int rc;
389 	ddi_dma_attr_t dmaattr;
390 	uint_t ndcs, ndws;
391 	ddi_dma_handle_t dh;
392 	ddi_dma_handle_t mdh;
393 	ddi_dma_cookie_t dc;
394 	ddi_acc_handle_t abh;
395 	caddr_t	aba;
396 	ge_slot_t *gs;
397 	size_t bufsz;
398 	off_t off;
399 	size_t sz;
400 	buf_t *bp = vreq->v_buf;
401 	int dma_flags = (IS_READ(bp) ? DDI_DMA_READ : DDI_DMA_WRITE) |
402 	    DDI_DMA_STREAMING | DDI_DMA_PARTIAL;
403 
404 	switch (vreq->v_status) {
405 	case VREQ_INIT:
406 		if (IS_FLUSH_DISKCACHE(bp)) {
407 			if ((gs = gs_get(vdp, IS_READ(bp))) == NULL) {
408 				DPRINTF(DMA_DBG, ("xdf@%s: "
409 				    "get ge_slotfailed\n", vdp->xdf_addr));
410 				return (DDI_FAILURE);
411 			}
412 			vreq->v_blkno = 0;
413 			vreq->v_nslots = 1;
414 			vreq->v_flush_diskcache = FLUSH_DISKCACHE;
415 			vreq->v_status = VREQ_GS_ALLOCED;
416 			gs->gs_vreq = vreq;
417 			list_insert_head(&vreq->v_gs, gs);
418 			return (DDI_SUCCESS);
419 		}
420 
421 		if (IS_WRITE_BARRIER(vdp, bp))
422 			vreq->v_flush_diskcache = WRITE_BARRIER;
423 		vreq->v_blkno = bp->b_blkno +
424 		    (diskaddr_t)(uintptr_t)bp->b_private;
425 		/* See if we wrote new data to our flush block */
426 		if (!IS_READ(bp) && USE_WRITE_BARRIER(vdp))
427 			check_fbwrite(vdp, bp, vreq->v_blkno);
428 		vreq->v_status = VREQ_INIT_DONE;
429 		/*FALLTHRU*/
430 
431 	case VREQ_INIT_DONE:
432 		/*
433 		 * alloc DMA handle
434 		 */
435 		rc = ddi_dma_alloc_handle(vdp->xdf_dip, &xb_dma_attr,
436 		    xdf_dmacallback, (caddr_t)vdp, &dh);
437 		if (rc != DDI_SUCCESS) {
438 			SETDMACBON(vdp);
439 			DPRINTF(DMA_DBG, ("xdf@%s: DMA handle alloc failed\n",
440 			    vdp->xdf_addr));
441 			return (DDI_FAILURE);
442 		}
443 
444 		vreq->v_dmahdl = dh;
445 		vreq->v_status = VREQ_DMAHDL_ALLOCED;
446 		/*FALLTHRU*/
447 
448 	case VREQ_DMAHDL_ALLOCED:
449 		/*
450 		 * alloc dma handle for 512-byte aligned buf
451 		 */
452 		if (!ALIGNED_XFER(bp)) {
453 			/*
454 			 * XXPV: we need to temporarily enlarge the seg
455 			 * boundary and s/g length to work round CR6381968
456 			 */
457 			dmaattr = xb_dma_attr;
458 			dmaattr.dma_attr_seg = (uint64_t)-1;
459 			dmaattr.dma_attr_sgllen = INT_MAX;
460 			rc = ddi_dma_alloc_handle(vdp->xdf_dip, &dmaattr,
461 			    xdf_dmacallback, (caddr_t)vdp, &mdh);
462 			if (rc != DDI_SUCCESS) {
463 				SETDMACBON(vdp);
464 				DPRINTF(DMA_DBG, ("xdf@%s: "
465 				    "unaligned buf DMAhandle alloc failed\n",
466 				    vdp->xdf_addr));
467 				return (DDI_FAILURE);
468 			}
469 			vreq->v_memdmahdl = mdh;
470 			vreq->v_status = VREQ_MEMDMAHDL_ALLOCED;
471 		}
472 		/*FALLTHRU*/
473 
474 	case VREQ_MEMDMAHDL_ALLOCED:
475 		/*
476 		 * alloc 512-byte aligned buf
477 		 */
478 		if (!ALIGNED_XFER(bp)) {
479 			if (bp->b_flags & (B_PAGEIO | B_PHYS))
480 				bp_mapin(bp);
481 			rc = ddi_dma_mem_alloc(vreq->v_memdmahdl,
482 			    roundup(bp->b_bcount, XB_BSIZE), &xc_acc_attr,
483 			    DDI_DMA_STREAMING, xdf_dmacallback, (caddr_t)vdp,
484 			    &aba, &bufsz, &abh);
485 			if (rc != DDI_SUCCESS) {
486 				SETDMACBON(vdp);
487 				DPRINTF(DMA_DBG, ("xdf@%s: "
488 				    "DMA mem allocation failed\n",
489 				    vdp->xdf_addr));
490 				return (DDI_FAILURE);
491 			}
492 
493 			vreq->v_abuf = aba;
494 			vreq->v_align = abh;
495 			vreq->v_status = VREQ_DMAMEM_ALLOCED;
496 
497 			ASSERT(bufsz >= bp->b_bcount);
498 			if (!IS_READ(bp))
499 				bcopy(bp->b_un.b_addr, vreq->v_abuf,
500 				    bp->b_bcount);
501 		}
502 		/*FALLTHRU*/
503 
504 	case VREQ_DMAMEM_ALLOCED:
505 		/*
506 		 * dma bind
507 		 */
508 		if (ALIGNED_XFER(bp)) {
509 			rc = ddi_dma_buf_bind_handle(vreq->v_dmahdl, bp,
510 			    dma_flags, xdf_dmacallback, (caddr_t)vdp,
511 			    &dc, &ndcs);
512 		} else {
513 			rc = ddi_dma_addr_bind_handle(vreq->v_dmahdl,
514 			    NULL, vreq->v_abuf, bp->b_bcount, dma_flags,
515 			    xdf_dmacallback, (caddr_t)vdp, &dc, &ndcs);
516 		}
517 		if (rc == DDI_DMA_MAPPED || rc == DDI_DMA_PARTIAL_MAP) {
518 			/* get num of dma windows */
519 			if (rc == DDI_DMA_PARTIAL_MAP) {
520 				rc = ddi_dma_numwin(vreq->v_dmahdl, &ndws);
521 				ASSERT(rc == DDI_SUCCESS);
522 			} else {
523 				ndws = 1;
524 			}
525 		} else {
526 			SETDMACBON(vdp);
527 			DPRINTF(DMA_DBG, ("xdf@%s: DMA bind failed\n",
528 			    vdp->xdf_addr));
529 			return (DDI_FAILURE);
530 		}
531 
532 		vreq->v_dmac = dc;
533 		vreq->v_dmaw = 0;
534 		vreq->v_ndmacs = ndcs;
535 		vreq->v_ndmaws = ndws;
536 		vreq->v_nslots = ndws;
537 		vreq->v_status = VREQ_DMABUF_BOUND;
538 		/*FALLTHRU*/
539 
540 	case VREQ_DMABUF_BOUND:
541 		/*
542 		 * get ge_slot, callback is set upon failure from gs_get(),
543 		 * if not set previously
544 		 */
545 		if ((gs = gs_get(vdp, IS_READ(bp))) == NULL) {
546 			DPRINTF(DMA_DBG, ("xdf@%s: get ge_slot failed\n",
547 			    vdp->xdf_addr));
548 			return (DDI_FAILURE);
549 		}
550 
551 		vreq->v_status = VREQ_GS_ALLOCED;
552 		gs->gs_vreq = vreq;
553 		list_insert_head(&vreq->v_gs, gs);
554 		break;
555 
556 	case VREQ_GS_ALLOCED:
557 		/* nothing need to be done */
558 		break;
559 
560 	case VREQ_DMAWIN_DONE:
561 		/*
562 		 * move to the next dma window
563 		 */
564 		ASSERT((vreq->v_dmaw + 1) < vreq->v_ndmaws);
565 
566 		/* get a ge_slot for this DMA window */
567 		if ((gs = gs_get(vdp, IS_READ(bp))) == NULL) {
568 			DPRINTF(DMA_DBG, ("xdf@%s: get ge_slot failed\n",
569 			    vdp->xdf_addr));
570 			return (DDI_FAILURE);
571 		}
572 
573 		vreq->v_dmaw++;
574 		VERIFY(ddi_dma_getwin(vreq->v_dmahdl, vreq->v_dmaw, &off, &sz,
575 		    &vreq->v_dmac, &vreq->v_ndmacs) == DDI_SUCCESS);
576 		vreq->v_status = VREQ_GS_ALLOCED;
577 		gs->gs_vreq = vreq;
578 		list_insert_head(&vreq->v_gs, gs);
579 		break;
580 
581 	default:
582 		return (DDI_FAILURE);
583 	}
584 
585 	return (DDI_SUCCESS);
586 }
587 
588 static int
589 xdf_cmlb_attach(xdf_t *vdp)
590 {
591 	dev_info_t	*dip = vdp->xdf_dip;
592 
593 	return (cmlb_attach(dip, &xdf_lb_ops,
594 	    XD_IS_CD(vdp) ? DTYPE_RODIRECT : DTYPE_DIRECT,
595 	    XD_IS_RM(vdp),
596 	    B_TRUE,
597 	    XD_IS_CD(vdp) ? DDI_NT_CD_XVMD : DDI_NT_BLOCK_XVMD,
598 #if defined(XPV_HVM_DRIVER)
599 	    (XD_IS_CD(vdp) ? 0 : CMLB_CREATE_ALTSLICE_VTOC_16_DTYPE_DIRECT),
600 #else /* !XPV_HVM_DRIVER */
601 	    XD_IS_CD(vdp) ? 0 : CMLB_FAKE_LABEL_ONE_PARTITION,
602 #endif /* !XPV_HVM_DRIVER */
603 	    vdp->xdf_vd_lbl, NULL));
604 }
605 
606 static void
607 xdf_io_err(buf_t *bp, int err, size_t resid)
608 {
609 	bioerror(bp, err);
610 	if (resid == 0)
611 		bp->b_resid = bp->b_bcount;
612 	biodone(bp);
613 }
614 
615 static void
616 xdf_kstat_enter(xdf_t *vdp, buf_t *bp)
617 {
618 	v_req_t *vreq = BP_VREQ(bp);
619 
620 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
621 
622 	if (vdp->xdf_xdev_iostat == NULL)
623 		return;
624 	if ((vreq != NULL) && vreq->v_runq) {
625 		kstat_runq_enter(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
626 	} else {
627 		kstat_waitq_enter(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
628 	}
629 }
630 
631 static void
632 xdf_kstat_exit(xdf_t *vdp, buf_t *bp)
633 {
634 	v_req_t *vreq = BP_VREQ(bp);
635 
636 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
637 
638 	if (vdp->xdf_xdev_iostat == NULL)
639 		return;
640 
641 	if ((vreq != NULL) && vreq->v_runq) {
642 		kstat_runq_exit(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
643 	} else {
644 		kstat_waitq_exit(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
645 	}
646 
647 	if (bp->b_flags & B_READ) {
648 		KSTAT_IO_PTR(vdp->xdf_xdev_iostat)->reads++;
649 		KSTAT_IO_PTR(vdp->xdf_xdev_iostat)->nread += bp->b_bcount;
650 	} else if (bp->b_flags & B_WRITE) {
651 		KSTAT_IO_PTR(vdp->xdf_xdev_iostat)->writes++;
652 		KSTAT_IO_PTR(vdp->xdf_xdev_iostat)->nwritten += bp->b_bcount;
653 	}
654 }
655 
656 static void
657 xdf_kstat_waitq_to_runq(xdf_t *vdp, buf_t *bp)
658 {
659 	v_req_t *vreq = BP_VREQ(bp);
660 
661 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
662 	ASSERT(!vreq->v_runq);
663 
664 	vreq->v_runq = B_TRUE;
665 	if (vdp->xdf_xdev_iostat == NULL)
666 		return;
667 	kstat_waitq_to_runq(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
668 }
669 
670 static void
671 xdf_kstat_runq_to_waitq(xdf_t *vdp, buf_t *bp)
672 {
673 	v_req_t *vreq = BP_VREQ(bp);
674 
675 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
676 	ASSERT(vreq->v_runq);
677 
678 	vreq->v_runq = B_FALSE;
679 	if (vdp->xdf_xdev_iostat == NULL)
680 		return;
681 	kstat_runq_back_to_waitq(KSTAT_IO_PTR(vdp->xdf_xdev_iostat));
682 }
683 
684 int
685 xdf_kstat_create(dev_info_t *dip, char *ks_module, int instance)
686 {
687 	xdf_t		*vdp = (xdf_t *)ddi_get_driver_private(dip);
688 	kstat_t		*kstat;
689 	buf_t		*bp;
690 
691 	if ((kstat = kstat_create(
692 	    ks_module, instance, NULL, "disk",
693 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT)) == NULL)
694 		return (-1);
695 
696 	/* See comment about locking in xdf_kstat_delete(). */
697 	mutex_enter(&vdp->xdf_iostat_lk);
698 	mutex_enter(&vdp->xdf_dev_lk);
699 
700 	/* only one kstat can exist at a time */
701 	if (vdp->xdf_xdev_iostat != NULL) {
702 		mutex_exit(&vdp->xdf_dev_lk);
703 		mutex_exit(&vdp->xdf_iostat_lk);
704 		kstat_delete(kstat);
705 		return (-1);
706 	}
707 
708 	vdp->xdf_xdev_iostat = kstat;
709 	vdp->xdf_xdev_iostat->ks_lock = &vdp->xdf_dev_lk;
710 	kstat_install(vdp->xdf_xdev_iostat);
711 
712 	/*
713 	 * Now that we've created a kstat, we need to update the waitq and
714 	 * runq counts for the kstat to reflect our current state.
715 	 *
716 	 * For a buf_t structure to be on the runq, it must have a ring
717 	 * buffer slot associated with it.  To get a ring buffer slot the
718 	 * buf must first have a v_req_t and a ge_slot_t associated with it.
719 	 * Then when it is granted a ring buffer slot, v_runq will be set to
720 	 * true.
721 	 *
722 	 * For a buf_t structure to be on the waitq, it must not be on the
723 	 * runq.  So to find all the buf_t's that should be on waitq, we
724 	 * walk the active buf list and add any buf_t's which aren't on the
725 	 * runq to the waitq.
726 	 */
727 	bp = vdp->xdf_f_act;
728 	while (bp != NULL) {
729 		xdf_kstat_enter(vdp, bp);
730 		bp = bp->av_forw;
731 	}
732 	if (vdp->xdf_ready_tq_bp != NULL)
733 		xdf_kstat_enter(vdp, vdp->xdf_ready_tq_bp);
734 
735 	mutex_exit(&vdp->xdf_dev_lk);
736 	mutex_exit(&vdp->xdf_iostat_lk);
737 	return (0);
738 }
739 
740 void
741 xdf_kstat_delete(dev_info_t *dip)
742 {
743 	xdf_t		*vdp = (xdf_t *)ddi_get_driver_private(dip);
744 	kstat_t		*kstat;
745 	buf_t		*bp;
746 
747 	/*
748 	 * The locking order here is xdf_iostat_lk and then xdf_dev_lk.
749 	 * xdf_dev_lk is used to protect the xdf_xdev_iostat pointer
750 	 * and the contents of the our kstat.  xdf_iostat_lk is used
751 	 * to protect the allocation and freeing of the actual kstat.
752 	 * xdf_dev_lk can't be used for this purpose because kstat
753 	 * readers use it to access the contents of the kstat and
754 	 * hence it can't be held when calling kstat_delete().
755 	 */
756 	mutex_enter(&vdp->xdf_iostat_lk);
757 	mutex_enter(&vdp->xdf_dev_lk);
758 
759 	if (vdp->xdf_xdev_iostat == NULL) {
760 		mutex_exit(&vdp->xdf_dev_lk);
761 		mutex_exit(&vdp->xdf_iostat_lk);
762 		return;
763 	}
764 
765 	/*
766 	 * We're about to destroy the kstat structures, so it isn't really
767 	 * necessary to update the runq and waitq counts.  But, since this
768 	 * isn't a hot code path we can afford to be a little pedantic and
769 	 * go ahead and decrement the runq and waitq kstat counters to zero
770 	 * before free'ing them.  This helps us ensure that we've gotten all
771 	 * our accounting correct.
772 	 *
773 	 * For an explanation of how we determine which buffers go on the
774 	 * runq vs which go on the waitq, see the comments in
775 	 * xdf_kstat_create().
776 	 */
777 	bp = vdp->xdf_f_act;
778 	while (bp != NULL) {
779 		xdf_kstat_exit(vdp, bp);
780 		bp = bp->av_forw;
781 	}
782 	if (vdp->xdf_ready_tq_bp != NULL)
783 		xdf_kstat_exit(vdp, vdp->xdf_ready_tq_bp);
784 
785 	kstat = vdp->xdf_xdev_iostat;
786 	vdp->xdf_xdev_iostat = NULL;
787 	mutex_exit(&vdp->xdf_dev_lk);
788 	kstat_delete(kstat);
789 	mutex_exit(&vdp->xdf_iostat_lk);
790 }
791 
792 /*
793  * Add an IO requests onto the active queue.
794  *
795  * We have to detect IOs generated by xdf_ready_tq_thread.  These IOs
796  * are used to establish a connection to the backend, so they recieve
797  * priority over all other IOs.  Since xdf_ready_tq_thread only does
798  * synchronous IO, there can only be one xdf_ready_tq_thread request at any
799  * given time and we record the buf associated with that request in
800  * xdf_ready_tq_bp.
801  */
802 static void
803 xdf_bp_push(xdf_t *vdp, buf_t *bp)
804 {
805 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
806 	ASSERT(bp->av_forw == NULL);
807 
808 	xdf_kstat_enter(vdp, bp);
809 
810 	if (curthread == vdp->xdf_ready_tq_thread) {
811 		/* new IO requests from the ready thread */
812 		ASSERT(vdp->xdf_ready_tq_bp == NULL);
813 		vdp->xdf_ready_tq_bp = bp;
814 		return;
815 	}
816 
817 	/* this is normal IO request */
818 	ASSERT(bp != vdp->xdf_ready_tq_bp);
819 
820 	if (vdp->xdf_f_act == NULL) {
821 		/* this is only only IO on the active queue */
822 		ASSERT(vdp->xdf_l_act == NULL);
823 		ASSERT(vdp->xdf_i_act == NULL);
824 		vdp->xdf_f_act = vdp->xdf_l_act = vdp->xdf_i_act = bp;
825 		return;
826 	}
827 
828 	/* add this IO to the tail of the active queue */
829 	vdp->xdf_l_act->av_forw = bp;
830 	vdp->xdf_l_act = bp;
831 	if (vdp->xdf_i_act == NULL)
832 		vdp->xdf_i_act = bp;
833 }
834 
835 static void
836 xdf_bp_pop(xdf_t *vdp, buf_t *bp)
837 {
838 	buf_t	*bp_iter;
839 
840 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
841 	ASSERT(VREQ_DONE(BP_VREQ(bp)));
842 
843 	if (vdp->xdf_ready_tq_bp == bp) {
844 		/* we're done with a ready thread IO request */
845 		ASSERT(bp->av_forw == NULL);
846 		vdp->xdf_ready_tq_bp = NULL;
847 		return;
848 	}
849 
850 	/* we're done with a normal IO request */
851 	ASSERT((bp->av_forw != NULL) || (bp == vdp->xdf_l_act));
852 	ASSERT((bp->av_forw == NULL) || (bp != vdp->xdf_l_act));
853 	ASSERT(VREQ_DONE(BP_VREQ(vdp->xdf_f_act)));
854 	ASSERT(vdp->xdf_f_act != vdp->xdf_i_act);
855 
856 	if (bp == vdp->xdf_f_act) {
857 		/* This IO was at the head of our active queue. */
858 		vdp->xdf_f_act = bp->av_forw;
859 		if (bp == vdp->xdf_l_act)
860 			vdp->xdf_l_act = NULL;
861 	} else {
862 		/* There IO finished before some other pending IOs. */
863 		bp_iter = vdp->xdf_f_act;
864 		while (bp != bp_iter->av_forw) {
865 			bp_iter = bp_iter->av_forw;
866 			ASSERT(VREQ_DONE(BP_VREQ(bp_iter)));
867 			ASSERT(bp_iter != vdp->xdf_i_act);
868 		}
869 		bp_iter->av_forw = bp->av_forw;
870 		if (bp == vdp->xdf_l_act)
871 			vdp->xdf_l_act = bp_iter;
872 	}
873 	bp->av_forw = NULL;
874 }
875 
876 static buf_t *
877 xdf_bp_next(xdf_t *vdp)
878 {
879 	v_req_t	*vreq;
880 	buf_t	*bp;
881 
882 	if (vdp->xdf_state == XD_CONNECTED) {
883 		/*
884 		 * If we're in the XD_CONNECTED state, we only service IOs
885 		 * from the xdf_ready_tq_thread thread.
886 		 */
887 		if ((bp = vdp->xdf_ready_tq_bp) == NULL)
888 			return (NULL);
889 		if (((vreq = BP_VREQ(bp)) == NULL) || (!VREQ_DONE(vreq)))
890 			return (bp);
891 		return (NULL);
892 	}
893 
894 	/* if we're not in the XD_CONNECTED or XD_READY state we can't do IO */
895 	if (vdp->xdf_state != XD_READY)
896 		return (NULL);
897 
898 	ASSERT(vdp->xdf_ready_tq_bp == NULL);
899 	for (;;) {
900 		if ((bp = vdp->xdf_i_act) == NULL)
901 			return (NULL);
902 		if (((vreq = BP_VREQ(bp)) == NULL) || (!VREQ_DONE(vreq)))
903 			return (bp);
904 
905 		/* advance the active buf index pointer */
906 		vdp->xdf_i_act = bp->av_forw;
907 	}
908 }
909 
910 static void
911 xdf_io_fini(xdf_t *vdp, uint64_t id, int bioerr)
912 {
913 	ge_slot_t	*gs = (ge_slot_t *)(uintptr_t)id;
914 	v_req_t		*vreq = gs->gs_vreq;
915 	buf_t		*bp = vreq->v_buf;
916 
917 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
918 	ASSERT(BP_VREQ(bp) == vreq);
919 
920 	gs_free(gs);
921 
922 	if (bioerr != 0)
923 		bioerror(bp, bioerr);
924 	ASSERT(vreq->v_nslots > 0);
925 	if (--vreq->v_nslots > 0)
926 		return;
927 
928 	/* remove this IO from our active queue */
929 	xdf_bp_pop(vdp, bp);
930 
931 	ASSERT(vreq->v_runq);
932 	xdf_kstat_exit(vdp, bp);
933 	vreq->v_runq = B_FALSE;
934 	vreq_free(vdp, vreq);
935 
936 	if (IS_ERROR(bp)) {
937 		xdf_io_err(bp, geterror(bp), 0);
938 	} else if (bp->b_resid != 0) {
939 		/* Partial transfers are an error */
940 		xdf_io_err(bp, EIO, bp->b_resid);
941 	} else {
942 		biodone(bp);
943 	}
944 }
945 
946 /*
947  * xdf interrupt handler
948  */
949 static uint_t
950 xdf_intr_locked(xdf_t *vdp)
951 {
952 	xendev_ring_t *xbr;
953 	blkif_response_t *resp;
954 	int bioerr;
955 	uint64_t id;
956 	uint8_t op;
957 	uint16_t status;
958 	ddi_acc_handle_t acchdl;
959 
960 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
961 
962 	if ((xbr = vdp->xdf_xb_ring) == NULL)
963 		return (DDI_INTR_UNCLAIMED);
964 
965 	acchdl = vdp->xdf_xb_ring_hdl;
966 
967 	/*
968 	 * complete all requests which have a response
969 	 */
970 	while (resp = xvdi_ring_get_response(xbr)) {
971 		id = ddi_get64(acchdl, &resp->id);
972 		op = ddi_get8(acchdl, &resp->operation);
973 		status = ddi_get16(acchdl, (uint16_t *)&resp->status);
974 		DPRINTF(INTR_DBG, ("resp: op %d id %"PRIu64" status %d\n",
975 		    op, id, status));
976 
977 		if (status != BLKIF_RSP_OKAY) {
978 			DPRINTF(IO_DBG, ("xdf@%s: I/O error while %s",
979 			    vdp->xdf_addr,
980 			    (op == BLKIF_OP_READ) ? "reading" : "writing"));
981 			bioerr = EIO;
982 		} else {
983 			bioerr = 0;
984 		}
985 
986 		xdf_io_fini(vdp, id, bioerr);
987 	}
988 	return (DDI_INTR_CLAIMED);
989 }
990 
991 /*
992  * xdf_intr runs at PIL 5, so no one else can grab xdf_dev_lk and
993  * block at a lower pil.
994  */
995 static uint_t
996 xdf_intr(caddr_t arg)
997 {
998 	xdf_t *vdp = (xdf_t *)arg;
999 	int rv;
1000 
1001 	mutex_enter(&vdp->xdf_dev_lk);
1002 	rv = xdf_intr_locked(vdp);
1003 	mutex_exit(&vdp->xdf_dev_lk);
1004 
1005 	if (!do_polled_io)
1006 		xdf_io_start(vdp);
1007 
1008 	return (rv);
1009 }
1010 
1011 static void
1012 xdf_ring_push(xdf_t *vdp)
1013 {
1014 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1015 
1016 	if (vdp->xdf_xb_ring == NULL)
1017 		return;
1018 
1019 	if (xvdi_ring_push_request(vdp->xdf_xb_ring)) {
1020 		DPRINTF(IO_DBG, (
1021 		    "xdf@%s: xdf_ring_push: sent request(s) to backend\n",
1022 		    vdp->xdf_addr));
1023 	}
1024 
1025 	if (xvdi_get_evtchn(vdp->xdf_dip) != INVALID_EVTCHN)
1026 		xvdi_notify_oe(vdp->xdf_dip);
1027 }
1028 
1029 static int
1030 xdf_ring_drain_locked(xdf_t *vdp)
1031 {
1032 	int		pollc, rv = 0;
1033 
1034 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1035 
1036 	if (xdf_debug & SUSRES_DBG)
1037 		xen_printf("xdf_ring_drain: start\n");
1038 
1039 	for (pollc = 0; pollc < XDF_DRAIN_RETRY_COUNT; pollc++) {
1040 		if (vdp->xdf_xb_ring == NULL)
1041 			goto out;
1042 
1043 		if (xvdi_ring_has_unconsumed_responses(vdp->xdf_xb_ring))
1044 			(void) xdf_intr_locked(vdp);
1045 		if (!xvdi_ring_has_incomp_request(vdp->xdf_xb_ring))
1046 			goto out;
1047 		xdf_ring_push(vdp);
1048 
1049 		/* file-backed devices can be slow */
1050 		mutex_exit(&vdp->xdf_dev_lk);
1051 #ifdef XPV_HVM_DRIVER
1052 		(void) HYPERVISOR_yield();
1053 #endif /* XPV_HVM_DRIVER */
1054 		delay(drv_usectohz(XDF_DRAIN_MSEC_DELAY));
1055 		mutex_enter(&vdp->xdf_dev_lk);
1056 	}
1057 	cmn_err(CE_WARN, "xdf@%s: xdf_ring_drain: timeout", vdp->xdf_addr);
1058 
1059 out:
1060 	if (vdp->xdf_xb_ring != NULL) {
1061 		if (xvdi_ring_has_incomp_request(vdp->xdf_xb_ring) ||
1062 		    xvdi_ring_has_unconsumed_responses(vdp->xdf_xb_ring))
1063 			rv = EIO;
1064 	}
1065 	if (xdf_debug & SUSRES_DBG)
1066 		xen_printf("xdf@%s: xdf_ring_drain: end, err=%d\n",
1067 		    vdp->xdf_addr, rv);
1068 	return (rv);
1069 }
1070 
1071 static int
1072 xdf_ring_drain(xdf_t *vdp)
1073 {
1074 	int rv;
1075 	mutex_enter(&vdp->xdf_dev_lk);
1076 	rv = xdf_ring_drain_locked(vdp);
1077 	mutex_exit(&vdp->xdf_dev_lk);
1078 	return (rv);
1079 }
1080 
1081 /*
1082  * Destroy all v_req_t, grant table entries, and our ring buffer.
1083  */
1084 static void
1085 xdf_ring_destroy(xdf_t *vdp)
1086 {
1087 	v_req_t		*vreq;
1088 	buf_t		*bp;
1089 	ge_slot_t	*gs;
1090 
1091 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1092 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1093 
1094 	if ((vdp->xdf_state != XD_INIT) &&
1095 	    (vdp->xdf_state != XD_CONNECTED) &&
1096 	    (vdp->xdf_state != XD_READY)) {
1097 		ASSERT(vdp->xdf_xb_ring == NULL);
1098 		ASSERT(vdp->xdf_xb_ring_hdl == NULL);
1099 		ASSERT(vdp->xdf_peer == INVALID_DOMID);
1100 		ASSERT(vdp->xdf_evtchn == INVALID_EVTCHN);
1101 		ASSERT(list_is_empty(&vdp->xdf_vreq_act));
1102 		return;
1103 	}
1104 
1105 	/*
1106 	 * We don't want to recieve async notifications from the backend
1107 	 * when it finishes processing ring entries.
1108 	 */
1109 #ifdef XPV_HVM_DRIVER
1110 	ec_unbind_evtchn(vdp->xdf_evtchn);
1111 #else /* !XPV_HVM_DRIVER */
1112 	(void) ddi_remove_intr(vdp->xdf_dip, 0, NULL);
1113 #endif /* !XPV_HVM_DRIVER */
1114 
1115 	/*
1116 	 * Drain any requests in the ring.  We need to do this before we
1117 	 * can free grant table entries, because if active ring entries
1118 	 * point to grants, then the backend could be trying to access
1119 	 * those grants.
1120 	 */
1121 	(void) xdf_ring_drain_locked(vdp);
1122 
1123 	/* We're done talking to the backend so free up our event channel */
1124 	xvdi_free_evtchn(vdp->xdf_dip);
1125 	vdp->xdf_evtchn = INVALID_EVTCHN;
1126 
1127 	while ((vreq = list_head(&vdp->xdf_vreq_act)) != NULL) {
1128 		bp = vreq->v_buf;
1129 		ASSERT(BP_VREQ(bp) == vreq);
1130 
1131 		/* Free up any grant table entries associaed with this IO */
1132 		while ((gs = list_head(&vreq->v_gs)) != NULL)
1133 			gs_free(gs);
1134 
1135 		/* If this IO was on the runq, move it back to the waitq. */
1136 		if (vreq->v_runq)
1137 			xdf_kstat_runq_to_waitq(vdp, bp);
1138 
1139 		/*
1140 		 * Reset any buf IO state since we're going to re-issue the
1141 		 * IO when we reconnect.
1142 		 */
1143 		vreq_free(vdp, vreq);
1144 		BP_VREQ_SET(bp, NULL);
1145 		bioerror(bp, 0);
1146 	}
1147 
1148 	/* reset the active queue index pointer */
1149 	vdp->xdf_i_act = vdp->xdf_f_act;
1150 
1151 	/* Destroy the ring */
1152 	xvdi_free_ring(vdp->xdf_xb_ring);
1153 	vdp->xdf_xb_ring = NULL;
1154 	vdp->xdf_xb_ring_hdl = NULL;
1155 	vdp->xdf_peer = INVALID_DOMID;
1156 }
1157 
1158 void
1159 xdfmin(struct buf *bp)
1160 {
1161 	if (bp->b_bcount > xdf_maxphys)
1162 		bp->b_bcount = xdf_maxphys;
1163 }
1164 
1165 /*
1166  * Check if we have a pending "eject" media request.
1167  */
1168 static int
1169 xdf_eject_pending(xdf_t *vdp)
1170 {
1171 	dev_info_t	*dip = vdp->xdf_dip;
1172 	char		*xsname, *str;
1173 
1174 	if (!vdp->xdf_media_req_supported)
1175 		return (B_FALSE);
1176 
1177 	if (((xsname = xvdi_get_xsname(dip)) == NULL) ||
1178 	    (xenbus_read_str(xsname, XBP_MEDIA_REQ, &str) != 0))
1179 		return (B_FALSE);
1180 
1181 	if (strcmp(str, XBV_MEDIA_REQ_EJECT) != 0) {
1182 		strfree(str);
1183 		return (B_FALSE);
1184 	}
1185 	strfree(str);
1186 	return (B_TRUE);
1187 }
1188 
1189 /*
1190  * Generate a media request.
1191  */
1192 static int
1193 xdf_media_req(xdf_t *vdp, char *req, boolean_t media_required)
1194 {
1195 	dev_info_t	*dip = vdp->xdf_dip;
1196 	char		*xsname;
1197 
1198 	/*
1199 	 * we can't be holding xdf_dev_lk because xenbus_printf() can
1200 	 * block while waiting for a PIL 1 interrupt message.  this
1201 	 * would cause a deadlock with xdf_intr() which needs to grab
1202 	 * xdf_dev_lk as well and runs at PIL 5.
1203 	 */
1204 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1205 	ASSERT(MUTEX_NOT_HELD(&vdp->xdf_dev_lk));
1206 
1207 	if ((xsname = xvdi_get_xsname(dip)) == NULL)
1208 		return (ENXIO);
1209 
1210 	/* Check if we support media requests */
1211 	if (!XD_IS_CD(vdp) || !vdp->xdf_media_req_supported)
1212 		return (ENOTTY);
1213 
1214 	/* If an eject is pending then don't allow any new requests */
1215 	if (xdf_eject_pending(vdp))
1216 		return (ENXIO);
1217 
1218 	/* Make sure that there is media present */
1219 	if (media_required && (vdp->xdf_xdev_nblocks == 0))
1220 		return (ENXIO);
1221 
1222 	/* We only allow operations when the device is ready and connected */
1223 	if (vdp->xdf_state != XD_READY)
1224 		return (EIO);
1225 
1226 	if (xenbus_printf(XBT_NULL, xsname, XBP_MEDIA_REQ, "%s", req) != 0)
1227 		return (EIO);
1228 
1229 	return (0);
1230 }
1231 
1232 /*
1233  * populate a single blkif_request_t w/ a buf
1234  */
1235 static void
1236 xdf_process_rreq(xdf_t *vdp, struct buf *bp, blkif_request_t *rreq)
1237 {
1238 	grant_ref_t	gr;
1239 	uint8_t		fsect, lsect;
1240 	size_t		bcnt;
1241 	paddr_t		dma_addr;
1242 	off_t		blk_off;
1243 	dev_info_t	*dip = vdp->xdf_dip;
1244 	blkif_vdev_t	vdev = xvdi_get_vdevnum(dip);
1245 	v_req_t		*vreq = BP_VREQ(bp);
1246 	uint64_t	blkno = vreq->v_blkno;
1247 	uint_t		ndmacs = vreq->v_ndmacs;
1248 	ddi_acc_handle_t acchdl = vdp->xdf_xb_ring_hdl;
1249 	int		seg = 0;
1250 	int		isread = IS_READ(bp);
1251 	ge_slot_t	*gs = list_head(&vreq->v_gs);
1252 
1253 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1254 	ASSERT(vreq->v_status == VREQ_GS_ALLOCED);
1255 
1256 	if (isread)
1257 		ddi_put8(acchdl, &rreq->operation, BLKIF_OP_READ);
1258 	else {
1259 		switch (vreq->v_flush_diskcache) {
1260 		case FLUSH_DISKCACHE:
1261 			ddi_put8(acchdl, &rreq->operation,
1262 			    BLKIF_OP_FLUSH_DISKCACHE);
1263 			ddi_put16(acchdl, &rreq->handle, vdev);
1264 			ddi_put64(acchdl, &rreq->id,
1265 			    (uint64_t)(uintptr_t)(gs));
1266 			ddi_put8(acchdl, &rreq->nr_segments, 0);
1267 			vreq->v_status = VREQ_DMAWIN_DONE;
1268 			return;
1269 		case WRITE_BARRIER:
1270 			ddi_put8(acchdl, &rreq->operation,
1271 			    BLKIF_OP_WRITE_BARRIER);
1272 			break;
1273 		default:
1274 			if (!vdp->xdf_wce)
1275 				ddi_put8(acchdl, &rreq->operation,
1276 				    BLKIF_OP_WRITE_BARRIER);
1277 			else
1278 				ddi_put8(acchdl, &rreq->operation,
1279 				    BLKIF_OP_WRITE);
1280 			break;
1281 		}
1282 	}
1283 
1284 	ddi_put16(acchdl, &rreq->handle, vdev);
1285 	ddi_put64(acchdl, &rreq->sector_number, blkno);
1286 	ddi_put64(acchdl, &rreq->id, (uint64_t)(uintptr_t)(gs));
1287 
1288 	/*
1289 	 * loop until all segments are populated or no more dma cookie in buf
1290 	 */
1291 	for (;;) {
1292 		/*
1293 		 * Each segment of a blkif request can transfer up to
1294 		 * one 4K page of data.
1295 		 */
1296 		bcnt = vreq->v_dmac.dmac_size;
1297 		dma_addr = vreq->v_dmac.dmac_laddress;
1298 		blk_off = (uint_t)((paddr_t)XB_SEGOFFSET & dma_addr);
1299 		fsect = blk_off >> XB_BSHIFT;
1300 		lsect = fsect + (bcnt >> XB_BSHIFT) - 1;
1301 
1302 		ASSERT(bcnt <= PAGESIZE);
1303 		ASSERT((bcnt % XB_BSIZE) == 0);
1304 		ASSERT((blk_off & XB_BMASK) == 0);
1305 		ASSERT(fsect < XB_MAX_SEGLEN / XB_BSIZE &&
1306 		    lsect < XB_MAX_SEGLEN / XB_BSIZE);
1307 
1308 		gr = gs_grant(gs, PATOMA(dma_addr) >> PAGESHIFT);
1309 		ddi_put32(acchdl, &rreq->seg[seg].gref, gr);
1310 		ddi_put8(acchdl, &rreq->seg[seg].first_sect, fsect);
1311 		ddi_put8(acchdl, &rreq->seg[seg].last_sect, lsect);
1312 
1313 		DPRINTF(IO_DBG, (
1314 		    "xdf@%s: seg%d: dmacS %lu blk_off %ld\n",
1315 		    vdp->xdf_addr, seg, vreq->v_dmac.dmac_size, blk_off));
1316 		DPRINTF(IO_DBG, (
1317 		    "xdf@%s: seg%d: fs %d ls %d gr %d dma 0x%"PRIx64"\n",
1318 		    vdp->xdf_addr, seg, fsect, lsect, gr, dma_addr));
1319 
1320 		blkno += (bcnt >> XB_BSHIFT);
1321 		seg++;
1322 		ASSERT(seg <= BLKIF_MAX_SEGMENTS_PER_REQUEST);
1323 		if (--ndmacs) {
1324 			ddi_dma_nextcookie(vreq->v_dmahdl, &vreq->v_dmac);
1325 			continue;
1326 		}
1327 
1328 		vreq->v_status = VREQ_DMAWIN_DONE;
1329 		vreq->v_blkno = blkno;
1330 		break;
1331 	}
1332 	ddi_put8(acchdl,  &rreq->nr_segments, seg);
1333 	DPRINTF(IO_DBG, (
1334 	    "xdf@%s: xdf_process_rreq: request id=%"PRIx64" ready\n",
1335 	    vdp->xdf_addr, rreq->id));
1336 }
1337 
1338 static void
1339 xdf_io_start(xdf_t *vdp)
1340 {
1341 	struct buf	*bp;
1342 	v_req_t		*vreq;
1343 	blkif_request_t	*rreq;
1344 	boolean_t	rreqready = B_FALSE;
1345 
1346 	mutex_enter(&vdp->xdf_dev_lk);
1347 
1348 	/*
1349 	 * Populate the ring request(s).  Loop until there is no buf to
1350 	 * transfer or no free slot available in I/O ring.
1351 	 */
1352 	for (;;) {
1353 		/* don't start any new IO if we're suspending */
1354 		if (vdp->xdf_suspending)
1355 			break;
1356 		if ((bp = xdf_bp_next(vdp)) == NULL)
1357 			break;
1358 
1359 		/* if the buf doesn't already have a vreq, allocate one */
1360 		if (((vreq = BP_VREQ(bp)) == NULL) &&
1361 		    ((vreq = vreq_get(vdp, bp)) == NULL))
1362 			break;
1363 
1364 		/* alloc DMA/GTE resources */
1365 		if (vreq_setup(vdp, vreq) != DDI_SUCCESS)
1366 			break;
1367 
1368 		/* get next blkif_request in the ring */
1369 		if ((rreq = xvdi_ring_get_request(vdp->xdf_xb_ring)) == NULL)
1370 			break;
1371 		bzero(rreq, sizeof (blkif_request_t));
1372 		rreqready = B_TRUE;
1373 
1374 		/* populate blkif_request with this buf */
1375 		xdf_process_rreq(vdp, bp, rreq);
1376 
1377 		/*
1378 		 * This buffer/vreq pair is has been allocated a ring buffer
1379 		 * resources, so if it isn't already in our runq, add it.
1380 		 */
1381 		if (!vreq->v_runq)
1382 			xdf_kstat_waitq_to_runq(vdp, bp);
1383 	}
1384 
1385 	/* Send the request(s) to the backend */
1386 	if (rreqready)
1387 		xdf_ring_push(vdp);
1388 
1389 	mutex_exit(&vdp->xdf_dev_lk);
1390 }
1391 
1392 
1393 /* check if partition is open, -1 - check all partitions on the disk */
1394 static boolean_t
1395 xdf_isopen(xdf_t *vdp, int partition)
1396 {
1397 	int i;
1398 	ulong_t parbit;
1399 	boolean_t rval = B_FALSE;
1400 
1401 	ASSERT((partition == -1) ||
1402 	    ((partition >= 0) || (partition < XDF_PEXT)));
1403 
1404 	if (partition == -1)
1405 		parbit = (ulong_t)-1;
1406 	else
1407 		parbit = 1 << partition;
1408 
1409 	for (i = 0; i < OTYPCNT; i++) {
1410 		if (vdp->xdf_vd_open[i] & parbit)
1411 			rval = B_TRUE;
1412 	}
1413 
1414 	return (rval);
1415 }
1416 
1417 /*
1418  * The connection should never be closed as long as someone is holding
1419  * us open, there is pending IO, or someone is waiting waiting for a
1420  * connection.
1421  */
1422 static boolean_t
1423 xdf_busy(xdf_t *vdp)
1424 {
1425 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1426 
1427 	if ((vdp->xdf_xb_ring != NULL) &&
1428 	    xvdi_ring_has_unconsumed_responses(vdp->xdf_xb_ring)) {
1429 		ASSERT(vdp->xdf_state != XD_CLOSED);
1430 		return (B_TRUE);
1431 	}
1432 
1433 	if (!list_is_empty(&vdp->xdf_vreq_act) || (vdp->xdf_f_act != NULL)) {
1434 		ASSERT(vdp->xdf_state != XD_CLOSED);
1435 		return (B_TRUE);
1436 	}
1437 
1438 	if (xdf_isopen(vdp, -1)) {
1439 		ASSERT(vdp->xdf_state != XD_CLOSED);
1440 		return (B_TRUE);
1441 	}
1442 
1443 	if (vdp->xdf_connect_req > 0) {
1444 		ASSERT(vdp->xdf_state != XD_CLOSED);
1445 		return (B_TRUE);
1446 	}
1447 
1448 	return (B_FALSE);
1449 }
1450 
1451 static void
1452 xdf_set_state(xdf_t *vdp, xdf_state_t new_state)
1453 {
1454 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1455 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1456 	DPRINTF(DDI_DBG, ("xdf@%s: state change %d -> %d\n",
1457 	    vdp->xdf_addr, vdp->xdf_state, new_state));
1458 	vdp->xdf_state = new_state;
1459 	cv_broadcast(&vdp->xdf_dev_cv);
1460 }
1461 
1462 static void
1463 xdf_disconnect(xdf_t *vdp, xdf_state_t new_state, boolean_t quiet)
1464 {
1465 	dev_info_t	*dip = vdp->xdf_dip;
1466 	boolean_t	busy;
1467 
1468 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1469 	ASSERT(MUTEX_NOT_HELD(&vdp->xdf_dev_lk));
1470 	ASSERT((new_state == XD_UNKNOWN) || (new_state == XD_CLOSED));
1471 
1472 	/* Check if we're already there. */
1473 	if (vdp->xdf_state == new_state)
1474 		return;
1475 
1476 	mutex_enter(&vdp->xdf_dev_lk);
1477 	busy = xdf_busy(vdp);
1478 
1479 	/* If we're already closed then there's nothing todo. */
1480 	if (vdp->xdf_state == XD_CLOSED) {
1481 		ASSERT(!busy);
1482 		xdf_set_state(vdp, new_state);
1483 		mutex_exit(&vdp->xdf_dev_lk);
1484 		return;
1485 	}
1486 
1487 #ifdef DEBUG
1488 	/* UhOh.  Warn the user that something bad has happened. */
1489 	if (!quiet && busy && (vdp->xdf_state == XD_READY) &&
1490 	    (vdp->xdf_xdev_nblocks != 0)) {
1491 		cmn_err(CE_WARN, "xdf@%s: disconnected while in use",
1492 		    vdp->xdf_addr);
1493 	}
1494 #endif /* DEBUG */
1495 
1496 	xdf_ring_destroy(vdp);
1497 
1498 	/* If we're busy then we can only go into the unknown state */
1499 	xdf_set_state(vdp, (busy) ? XD_UNKNOWN : new_state);
1500 	mutex_exit(&vdp->xdf_dev_lk);
1501 
1502 	/* if we're closed now, let the other end know */
1503 	if (vdp->xdf_state == XD_CLOSED)
1504 		(void) xvdi_switch_state(dip, XBT_NULL, XenbusStateClosed);
1505 }
1506 
1507 
1508 /*
1509  * Kick-off connect process
1510  * Status should be XD_UNKNOWN or XD_CLOSED
1511  * On success, status will be changed to XD_INIT
1512  * On error, it will be changed to XD_UNKNOWN
1513  */
1514 static int
1515 xdf_setstate_init(xdf_t *vdp)
1516 {
1517 	dev_info_t		*dip = vdp->xdf_dip;
1518 	xenbus_transaction_t	xbt;
1519 	grant_ref_t		gref;
1520 	char			*xsname, *str;
1521 	int 			rv;
1522 
1523 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1524 	ASSERT(MUTEX_NOT_HELD(&vdp->xdf_dev_lk));
1525 	ASSERT((vdp->xdf_state == XD_UNKNOWN) ||
1526 	    (vdp->xdf_state == XD_CLOSED));
1527 
1528 	DPRINTF(DDI_DBG,
1529 	    ("xdf@%s: starting connection process\n", vdp->xdf_addr));
1530 
1531 	/*
1532 	 * If an eject is pending then don't allow a new connection.
1533 	 * (Only the backend can clear media request eject request.)
1534 	 */
1535 	if (xdf_eject_pending(vdp))
1536 		return (DDI_FAILURE);
1537 
1538 	if ((xsname = xvdi_get_xsname(dip)) == NULL)
1539 		goto errout;
1540 
1541 	if ((vdp->xdf_peer = xvdi_get_oeid(dip)) == INVALID_DOMID)
1542 		goto errout;
1543 
1544 	(void) xvdi_switch_state(dip, XBT_NULL, XenbusStateInitialising);
1545 
1546 	/*
1547 	 * Sanity check for the existance of the xenbus device-type property.
1548 	 * This property might not exist if we our xenbus device nodes was
1549 	 * force destroyed while we were still connected to the backend.
1550 	 */
1551 	if (xenbus_read_str(xsname, XBP_DEV_TYPE, &str) != 0)
1552 		goto errout;
1553 	strfree(str);
1554 
1555 	if (xvdi_alloc_evtchn(dip) != DDI_SUCCESS)
1556 		goto errout;
1557 
1558 	vdp->xdf_evtchn = xvdi_get_evtchn(dip);
1559 #ifdef XPV_HVM_DRIVER
1560 	ec_bind_evtchn_to_handler(vdp->xdf_evtchn, IPL_VBD, xdf_intr, vdp);
1561 #else /* !XPV_HVM_DRIVER */
1562 	if (ddi_add_intr(dip, 0, NULL, NULL, xdf_intr, (caddr_t)vdp) !=
1563 	    DDI_SUCCESS) {
1564 		cmn_err(CE_WARN, "xdf@%s: xdf_setstate_init: "
1565 		    "failed to add intr handler", vdp->xdf_addr);
1566 		goto errout1;
1567 	}
1568 #endif /* !XPV_HVM_DRIVER */
1569 
1570 	if (xvdi_alloc_ring(dip, BLKIF_RING_SIZE,
1571 	    sizeof (union blkif_sring_entry), &gref, &vdp->xdf_xb_ring) !=
1572 	    DDI_SUCCESS) {
1573 		cmn_err(CE_WARN, "xdf@%s: failed to alloc comm ring",
1574 		    vdp->xdf_addr);
1575 		goto errout2;
1576 	}
1577 	vdp->xdf_xb_ring_hdl = vdp->xdf_xb_ring->xr_acc_hdl; /* ugly!! */
1578 
1579 	/*
1580 	 * Write into xenstore the info needed by backend
1581 	 */
1582 trans_retry:
1583 	if (xenbus_transaction_start(&xbt)) {
1584 		cmn_err(CE_WARN, "xdf@%s: failed to start transaction",
1585 		    vdp->xdf_addr);
1586 		xvdi_fatal_error(dip, EIO, "connect transaction init");
1587 		goto fail_trans;
1588 	}
1589 
1590 	/*
1591 	 * XBP_PROTOCOL is written by the domain builder in the case of PV
1592 	 * domains. However, it is not written for HVM domains, so let's
1593 	 * write it here.
1594 	 */
1595 	if (((rv = xenbus_printf(xbt, xsname,
1596 	    XBP_MEDIA_REQ, "%s", XBV_MEDIA_REQ_NONE)) != 0) ||
1597 	    ((rv = xenbus_printf(xbt, xsname,
1598 	    XBP_RING_REF, "%u", gref)) != 0) ||
1599 	    ((rv = xenbus_printf(xbt, xsname,
1600 	    XBP_EVENT_CHAN, "%u", vdp->xdf_evtchn)) != 0) ||
1601 	    ((rv = xenbus_printf(xbt, xsname,
1602 	    XBP_PROTOCOL, "%s", XEN_IO_PROTO_ABI_NATIVE)) != 0) ||
1603 	    ((rv = xvdi_switch_state(dip, xbt, XenbusStateInitialised)) > 0)) {
1604 		(void) xenbus_transaction_end(xbt, 1);
1605 		xvdi_fatal_error(dip, rv, "connect transaction setup");
1606 		goto fail_trans;
1607 	}
1608 
1609 	/* kick-off connect process */
1610 	if (rv = xenbus_transaction_end(xbt, 0)) {
1611 		if (rv == EAGAIN)
1612 			goto trans_retry;
1613 		xvdi_fatal_error(dip, rv, "connect transaction commit");
1614 		goto fail_trans;
1615 	}
1616 
1617 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1618 	mutex_enter(&vdp->xdf_dev_lk);
1619 	xdf_set_state(vdp, XD_INIT);
1620 	mutex_exit(&vdp->xdf_dev_lk);
1621 
1622 	return (DDI_SUCCESS);
1623 
1624 fail_trans:
1625 	xvdi_free_ring(vdp->xdf_xb_ring);
1626 errout2:
1627 #ifdef XPV_HVM_DRIVER
1628 	ec_unbind_evtchn(vdp->xdf_evtchn);
1629 #else /* !XPV_HVM_DRIVER */
1630 	(void) ddi_remove_intr(vdp->xdf_dip, 0, NULL);
1631 #endif /* !XPV_HVM_DRIVER */
1632 errout1:
1633 	xvdi_free_evtchn(dip);
1634 	vdp->xdf_evtchn = INVALID_EVTCHN;
1635 errout:
1636 	xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1637 	cmn_err(CE_WARN, "xdf@%s: failed to start connection to backend",
1638 	    vdp->xdf_addr);
1639 	return (DDI_FAILURE);
1640 }
1641 
1642 int
1643 xdf_get_flush_block(xdf_t *vdp)
1644 {
1645 	/*
1646 	 * Get a DEV_BSIZE aligned bufer
1647 	 */
1648 	vdp->xdf_flush_mem = kmem_alloc(vdp->xdf_xdev_secsize * 2, KM_SLEEP);
1649 	vdp->xdf_cache_flush_block =
1650 	    (char *)P2ROUNDUP((uintptr_t)(vdp->xdf_flush_mem),
1651 	    (int)vdp->xdf_xdev_secsize);
1652 
1653 	if (xdf_lb_rdwr(vdp->xdf_dip, TG_READ, vdp->xdf_cache_flush_block,
1654 	    xdf_flush_block, vdp->xdf_xdev_secsize, NULL) != 0)
1655 		return (DDI_FAILURE);
1656 	return (DDI_SUCCESS);
1657 }
1658 
1659 static void
1660 xdf_setstate_ready(void *arg)
1661 {
1662 	xdf_t	*vdp = (xdf_t *)arg;
1663 
1664 	vdp->xdf_ready_tq_thread = curthread;
1665 
1666 	/*
1667 	 * We've created all the minor nodes via cmlb_attach() using default
1668 	 * value in xdf_attach() to make it possible to block in xdf_open(),
1669 	 * in case there's anyone (say, booting thread) ever trying to open
1670 	 * it before connected to backend. We will refresh all those minor
1671 	 * nodes w/ latest info we've got now when we are almost connected.
1672 	 */
1673 	mutex_enter(&vdp->xdf_dev_lk);
1674 	if (vdp->xdf_cmbl_reattach) {
1675 		vdp->xdf_cmbl_reattach = B_FALSE;
1676 
1677 		mutex_exit(&vdp->xdf_dev_lk);
1678 		if (xdf_cmlb_attach(vdp) != 0) {
1679 			xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1680 			return;
1681 		}
1682 		mutex_enter(&vdp->xdf_dev_lk);
1683 	}
1684 
1685 	/* If we're not still trying to get to the ready state, then bail. */
1686 	if (vdp->xdf_state != XD_CONNECTED) {
1687 		mutex_exit(&vdp->xdf_dev_lk);
1688 		return;
1689 	}
1690 	mutex_exit(&vdp->xdf_dev_lk);
1691 
1692 	/*
1693 	 * If backend has feature-barrier, see if it supports disk
1694 	 * cache flush op.
1695 	 */
1696 	vdp->xdf_flush_supported = B_FALSE;
1697 	if (vdp->xdf_feature_barrier) {
1698 		/*
1699 		 * Pretend we already know flush is supported so probe
1700 		 * will attempt the correct op.
1701 		 */
1702 		vdp->xdf_flush_supported = B_TRUE;
1703 		if (xdf_lb_rdwr(vdp->xdf_dip, TG_WRITE, NULL, 0, 0, 0) == 0) {
1704 			vdp->xdf_flush_supported = B_TRUE;
1705 		} else {
1706 			vdp->xdf_flush_supported = B_FALSE;
1707 			/*
1708 			 * If the other end does not support the cache flush op
1709 			 * then we must use a barrier-write to force disk
1710 			 * cache flushing.  Barrier writes require that a data
1711 			 * block actually be written.
1712 			 * Cache a block to barrier-write when we are
1713 			 * asked to perform a flush.
1714 			 * XXX - would it be better to just copy 1 block
1715 			 * (512 bytes) from whatever write we did last
1716 			 * and rewrite that block?
1717 			 */
1718 			if (xdf_get_flush_block(vdp) != DDI_SUCCESS) {
1719 				xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1720 				return;
1721 			}
1722 		}
1723 	}
1724 
1725 	mutex_enter(&vdp->xdf_cb_lk);
1726 	mutex_enter(&vdp->xdf_dev_lk);
1727 	if (vdp->xdf_state == XD_CONNECTED)
1728 		xdf_set_state(vdp, XD_READY);
1729 	mutex_exit(&vdp->xdf_dev_lk);
1730 
1731 	/* Restart any currently queued up io */
1732 	xdf_io_start(vdp);
1733 
1734 	mutex_exit(&vdp->xdf_cb_lk);
1735 }
1736 
1737 /*
1738  * synthetic geometry
1739  */
1740 #define	XDF_NSECTS	256
1741 #define	XDF_NHEADS	16
1742 
1743 static void
1744 xdf_synthetic_pgeom(dev_info_t *dip, cmlb_geom_t *geomp)
1745 {
1746 	xdf_t *vdp;
1747 	uint_t ncyl;
1748 
1749 	vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip));
1750 
1751 	ncyl = vdp->xdf_xdev_nblocks / (XDF_NHEADS * XDF_NSECTS);
1752 
1753 	bzero(geomp, sizeof (*geomp));
1754 	geomp->g_ncyl = ncyl == 0 ? 1 : ncyl;
1755 	geomp->g_acyl = 0;
1756 	geomp->g_nhead = XDF_NHEADS;
1757 	geomp->g_nsect = XDF_NSECTS;
1758 	geomp->g_secsize = vdp->xdf_xdev_secsize;
1759 	geomp->g_capacity = vdp->xdf_xdev_nblocks;
1760 	geomp->g_intrlv = 0;
1761 	geomp->g_rpm = 7200;
1762 }
1763 
1764 /*
1765  * Finish other initialization after we've connected to backend
1766  * Status should be XD_INIT before calling this routine
1767  * On success, status should be changed to XD_CONNECTED.
1768  * On error, status should stay XD_INIT
1769  */
1770 static int
1771 xdf_setstate_connected(xdf_t *vdp)
1772 {
1773 	dev_info_t	*dip = vdp->xdf_dip;
1774 	cmlb_geom_t	pgeom;
1775 	diskaddr_t	nblocks = 0;
1776 	uint_t		secsize = 0;
1777 	char		*oename, *xsname, *str;
1778 	uint_t		dinfo;
1779 
1780 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1781 	ASSERT(MUTEX_NOT_HELD(&vdp->xdf_dev_lk));
1782 	ASSERT(vdp->xdf_state == XD_INIT);
1783 
1784 	if (((xsname = xvdi_get_xsname(dip)) == NULL) ||
1785 	    ((oename = xvdi_get_oename(dip)) == NULL))
1786 		return (DDI_FAILURE);
1787 
1788 	/* Make sure the other end is XenbusStateConnected */
1789 	if (xenbus_read_driver_state(oename) != XenbusStateConnected)
1790 		return (DDI_FAILURE);
1791 
1792 	/* Determine if feature barrier is supported by backend */
1793 	if (!(vdp->xdf_feature_barrier = xenbus_exists(oename, XBP_FB)))
1794 		cmn_err(CE_NOTE, "!xdf@%s: feature-barrier not supported",
1795 		    vdp->xdf_addr);
1796 
1797 	/*
1798 	 * Probe backend.  Read the device size into xdf_xdev_nblocks
1799 	 * and set the VDISK_READONLY, VDISK_CDROM, and VDISK_REMOVABLE
1800 	 * flags in xdf_dinfo.  If the emulated device type is "cdrom",
1801 	 * we always set VDISK_CDROM, regardless of if it's present in
1802 	 * the xenbus info parameter.
1803 	 */
1804 	if (xenbus_gather(XBT_NULL, oename,
1805 	    XBP_SECTORS, "%"SCNu64, &nblocks,
1806 	    XBP_SECTOR_SIZE, "%u", &secsize,
1807 	    XBP_INFO, "%u", &dinfo,
1808 	    NULL) != 0) {
1809 		cmn_err(CE_WARN, "xdf@%s: xdf_setstate_connected: "
1810 		    "cannot read backend info", vdp->xdf_addr);
1811 		return (DDI_FAILURE);
1812 	}
1813 	if (xenbus_read_str(xsname, XBP_DEV_TYPE, &str) != 0) {
1814 		cmn_err(CE_WARN, "xdf@%s: cannot read device-type",
1815 		    vdp->xdf_addr);
1816 		return (DDI_FAILURE);
1817 	}
1818 	if (strcmp(str, XBV_DEV_TYPE_CD) == 0)
1819 		dinfo |= VDISK_CDROM;
1820 	strfree(str);
1821 
1822 	if (secsize == 0 || !(ISP2(secsize / DEV_BSIZE)))
1823 		secsize = DEV_BSIZE;
1824 	vdp->xdf_xdev_nblocks = nblocks;
1825 	vdp->xdf_xdev_secsize = secsize;
1826 #ifdef _ILP32
1827 	if (vdp->xdf_xdev_nblocks > DK_MAX_BLOCKS) {
1828 		cmn_err(CE_WARN, "xdf@%s: xdf_setstate_connected: "
1829 		    "backend disk device too large with %llu blocks for"
1830 		    " 32-bit kernel", vdp->xdf_addr, vdp->xdf_xdev_nblocks);
1831 		xvdi_fatal_error(dip, EFBIG, "reading backend info");
1832 		return (DDI_FAILURE);
1833 	}
1834 #endif
1835 
1836 	/*
1837 	 * If the physical geometry for a fixed disk has been explicity
1838 	 * set then make sure that the specified physical geometry isn't
1839 	 * larger than the device we connected to.
1840 	 */
1841 	if (vdp->xdf_pgeom_fixed &&
1842 	    (vdp->xdf_pgeom.g_capacity > vdp->xdf_xdev_nblocks)) {
1843 		cmn_err(CE_WARN,
1844 		    "xdf@%s: connect failed, fixed geometry too large",
1845 		    vdp->xdf_addr);
1846 		return (DDI_FAILURE);
1847 	}
1848 
1849 	vdp->xdf_media_req_supported = xenbus_exists(oename, XBP_MEDIA_REQ_SUP);
1850 
1851 	/* mark vbd is ready for I/O */
1852 	mutex_enter(&vdp->xdf_dev_lk);
1853 	xdf_set_state(vdp, XD_CONNECTED);
1854 
1855 	/* check if the cmlb label should be updated */
1856 	xdf_synthetic_pgeom(dip, &pgeom);
1857 	if ((vdp->xdf_dinfo != dinfo) ||
1858 	    (!vdp->xdf_pgeom_fixed &&
1859 	    (memcmp(&vdp->xdf_pgeom, &pgeom, sizeof (pgeom)) != 0))) {
1860 		vdp->xdf_cmbl_reattach = B_TRUE;
1861 
1862 		vdp->xdf_dinfo = dinfo;
1863 		if (!vdp->xdf_pgeom_fixed)
1864 			vdp->xdf_pgeom = pgeom;
1865 	}
1866 
1867 	if (XD_IS_CD(vdp) || XD_IS_RM(vdp)) {
1868 		if (vdp->xdf_xdev_nblocks == 0) {
1869 			vdp->xdf_mstate = DKIO_EJECTED;
1870 			cv_broadcast(&vdp->xdf_mstate_cv);
1871 		} else {
1872 			vdp->xdf_mstate = DKIO_INSERTED;
1873 			cv_broadcast(&vdp->xdf_mstate_cv);
1874 		}
1875 	} else {
1876 		if (vdp->xdf_mstate != DKIO_NONE) {
1877 			vdp->xdf_mstate = DKIO_NONE;
1878 			cv_broadcast(&vdp->xdf_mstate_cv);
1879 		}
1880 	}
1881 
1882 	mutex_exit(&vdp->xdf_dev_lk);
1883 
1884 	cmn_err(CE_CONT, "?xdf@%s: %"PRIu64" blocks", vdp->xdf_addr,
1885 	    (uint64_t)vdp->xdf_xdev_nblocks);
1886 
1887 	/* Restart any currently queued up io */
1888 	xdf_io_start(vdp);
1889 
1890 	/*
1891 	 * To get to the ready state we have to do IO to the backend device,
1892 	 * but we can't initiate IO from the other end change callback thread
1893 	 * (which is the current context we're executing in.)  This is because
1894 	 * if the other end disconnects while we're doing IO from the callback
1895 	 * thread, then we can't recieve that disconnect event and we hang
1896 	 * waiting for an IO that can never complete.
1897 	 */
1898 	(void) ddi_taskq_dispatch(vdp->xdf_ready_tq, xdf_setstate_ready, vdp,
1899 	    DDI_SLEEP);
1900 
1901 	(void) xvdi_switch_state(dip, XBT_NULL, XenbusStateConnected);
1902 	return (DDI_SUCCESS);
1903 }
1904 
1905 /*ARGSUSED*/
1906 static void
1907 xdf_oe_change(dev_info_t *dip, ddi_eventcookie_t id, void *arg, void *impl_data)
1908 {
1909 	XenbusState new_state = *(XenbusState *)impl_data;
1910 	xdf_t *vdp = (xdf_t *)ddi_get_driver_private(dip);
1911 
1912 	DPRINTF(DDI_DBG, ("xdf@%s: otherend state change to %d!\n",
1913 	    vdp->xdf_addr, new_state));
1914 
1915 	mutex_enter(&vdp->xdf_cb_lk);
1916 
1917 	/* We assume that this callback is single threaded */
1918 	ASSERT(vdp->xdf_oe_change_thread == NULL);
1919 	DEBUG_EVAL(vdp->xdf_oe_change_thread = curthread);
1920 
1921 	/* ignore any backend state changes if we're suspending/suspended */
1922 	if (vdp->xdf_suspending || (vdp->xdf_state == XD_SUSPEND)) {
1923 		DEBUG_EVAL(vdp->xdf_oe_change_thread = NULL);
1924 		mutex_exit(&vdp->xdf_cb_lk);
1925 		return;
1926 	}
1927 
1928 	switch (new_state) {
1929 	case XenbusStateUnknown:
1930 	case XenbusStateInitialising:
1931 	case XenbusStateInitWait:
1932 	case XenbusStateInitialised:
1933 		if (vdp->xdf_state == XD_INIT)
1934 			break;
1935 
1936 		xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1937 		if (xdf_setstate_init(vdp) != DDI_SUCCESS)
1938 			break;
1939 		ASSERT(vdp->xdf_state == XD_INIT);
1940 		break;
1941 
1942 	case XenbusStateConnected:
1943 		if ((vdp->xdf_state == XD_CONNECTED) ||
1944 		    (vdp->xdf_state == XD_READY))
1945 			break;
1946 
1947 		if (vdp->xdf_state != XD_INIT) {
1948 			xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1949 			if (xdf_setstate_init(vdp) != DDI_SUCCESS)
1950 				break;
1951 			ASSERT(vdp->xdf_state == XD_INIT);
1952 		}
1953 
1954 		if (xdf_setstate_connected(vdp) != DDI_SUCCESS) {
1955 			xdf_disconnect(vdp, XD_UNKNOWN, B_FALSE);
1956 			break;
1957 		}
1958 		ASSERT(vdp->xdf_state == XD_CONNECTED);
1959 		break;
1960 
1961 	case XenbusStateClosing:
1962 		if (xdf_isopen(vdp, -1)) {
1963 			cmn_err(CE_NOTE,
1964 			    "xdf@%s: hot-unplug failed, still in use",
1965 			    vdp->xdf_addr);
1966 			break;
1967 		}
1968 		/*FALLTHROUGH*/
1969 	case XenbusStateClosed:
1970 		xdf_disconnect(vdp, XD_CLOSED, B_FALSE);
1971 		break;
1972 	}
1973 
1974 	/* notify anybody waiting for oe state change */
1975 	cv_broadcast(&vdp->xdf_dev_cv);
1976 	DEBUG_EVAL(vdp->xdf_oe_change_thread = NULL);
1977 	mutex_exit(&vdp->xdf_cb_lk);
1978 }
1979 
1980 static int
1981 xdf_connect_locked(xdf_t *vdp, boolean_t wait)
1982 {
1983 	int	rv, timeouts = 0, reset = 20;
1984 
1985 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
1986 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
1987 
1988 	/* we can't connect once we're in the closed state */
1989 	if (vdp->xdf_state == XD_CLOSED)
1990 		return (XD_CLOSED);
1991 
1992 	vdp->xdf_connect_req++;
1993 	while (vdp->xdf_state != XD_READY) {
1994 		mutex_exit(&vdp->xdf_dev_lk);
1995 
1996 		/* only one thread at a time can be the connection thread */
1997 		if (vdp->xdf_connect_thread == NULL)
1998 			vdp->xdf_connect_thread = curthread;
1999 
2000 		if (vdp->xdf_connect_thread == curthread) {
2001 			if ((timeouts > 0) && ((timeouts % reset) == 0)) {
2002 				/*
2003 				 * If we haven't establised a connection
2004 				 * within the reset time, then disconnect
2005 				 * so we can try again, and double the reset
2006 				 * time.  The reset time starts at 2 sec.
2007 				 */
2008 				(void) xdf_disconnect(vdp, XD_UNKNOWN, B_TRUE);
2009 				reset *= 2;
2010 			}
2011 			if (vdp->xdf_state == XD_UNKNOWN)
2012 				(void) xdf_setstate_init(vdp);
2013 			if (vdp->xdf_state == XD_INIT)
2014 				(void) xdf_setstate_connected(vdp);
2015 		}
2016 
2017 		mutex_enter(&vdp->xdf_dev_lk);
2018 		if (!wait || (vdp->xdf_state == XD_READY))
2019 			goto out;
2020 
2021 		mutex_exit((&vdp->xdf_cb_lk));
2022 		if (vdp->xdf_connect_thread != curthread) {
2023 			rv = cv_wait_sig(&vdp->xdf_dev_cv, &vdp->xdf_dev_lk);
2024 		} else {
2025 			/* delay for 0.1 sec */
2026 			rv = cv_reltimedwait_sig(&vdp->xdf_dev_cv,
2027 			    &vdp->xdf_dev_lk, drv_usectohz(100*1000),
2028 			    TR_CLOCK_TICK);
2029 			if (rv == -1)
2030 				timeouts++;
2031 		}
2032 		mutex_exit((&vdp->xdf_dev_lk));
2033 		mutex_enter((&vdp->xdf_cb_lk));
2034 		mutex_enter((&vdp->xdf_dev_lk));
2035 		if (rv == 0)
2036 			goto out;
2037 	}
2038 
2039 out:
2040 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
2041 	ASSERT(MUTEX_HELD(&vdp->xdf_dev_lk));
2042 
2043 	if (vdp->xdf_connect_thread == curthread) {
2044 		/*
2045 		 * wake up someone else so they can become the connection
2046 		 * thread.
2047 		 */
2048 		cv_signal(&vdp->xdf_dev_cv);
2049 		vdp->xdf_connect_thread = NULL;
2050 	}
2051 
2052 	/* Try to lock the media */
2053 	mutex_exit((&vdp->xdf_dev_lk));
2054 	(void) xdf_media_req(vdp, XBV_MEDIA_REQ_LOCK, B_TRUE);
2055 	mutex_enter((&vdp->xdf_dev_lk));
2056 
2057 	vdp->xdf_connect_req--;
2058 	return (vdp->xdf_state);
2059 }
2060 
2061 static uint_t
2062 xdf_iorestart(caddr_t arg)
2063 {
2064 	xdf_t *vdp = (xdf_t *)arg;
2065 
2066 	ASSERT(vdp != NULL);
2067 
2068 	mutex_enter(&vdp->xdf_dev_lk);
2069 	ASSERT(ISDMACBON(vdp));
2070 	SETDMACBOFF(vdp);
2071 	mutex_exit(&vdp->xdf_dev_lk);
2072 
2073 	xdf_io_start(vdp);
2074 
2075 	return (DDI_INTR_CLAIMED);
2076 }
2077 
2078 #if defined(XPV_HVM_DRIVER)
2079 
2080 typedef struct xdf_hvm_entry {
2081 	list_node_t	xdf_he_list;
2082 	char		*xdf_he_path;
2083 	dev_info_t	*xdf_he_dip;
2084 } xdf_hvm_entry_t;
2085 
2086 static list_t xdf_hvm_list;
2087 static kmutex_t xdf_hvm_list_lock;
2088 
2089 static xdf_hvm_entry_t *
2090 i_xdf_hvm_find(const char *path, dev_info_t *dip)
2091 {
2092 	xdf_hvm_entry_t	*i;
2093 
2094 	ASSERT((path != NULL) || (dip != NULL));
2095 	ASSERT(MUTEX_HELD(&xdf_hvm_list_lock));
2096 
2097 	i = list_head(&xdf_hvm_list);
2098 	while (i != NULL) {
2099 		if ((path != NULL) && strcmp(i->xdf_he_path, path) != 0) {
2100 			i = list_next(&xdf_hvm_list, i);
2101 			continue;
2102 		}
2103 		if ((dip != NULL) && (i->xdf_he_dip != dip)) {
2104 			i = list_next(&xdf_hvm_list, i);
2105 			continue;
2106 		}
2107 		break;
2108 	}
2109 	return (i);
2110 }
2111 
2112 dev_info_t *
2113 xdf_hvm_hold(const char *path)
2114 {
2115 	xdf_hvm_entry_t	*i;
2116 	dev_info_t	*dip;
2117 
2118 	mutex_enter(&xdf_hvm_list_lock);
2119 	i = i_xdf_hvm_find(path, NULL);
2120 	if (i == NULL) {
2121 		mutex_exit(&xdf_hvm_list_lock);
2122 		return (B_FALSE);
2123 	}
2124 	ndi_hold_devi(dip = i->xdf_he_dip);
2125 	mutex_exit(&xdf_hvm_list_lock);
2126 	return (dip);
2127 }
2128 
2129 static void
2130 xdf_hvm_add(dev_info_t *dip)
2131 {
2132 	xdf_hvm_entry_t	*i;
2133 	char		*path;
2134 
2135 	/* figure out the path for the dip */
2136 	path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
2137 	(void) ddi_pathname(dip, path);
2138 
2139 	i = kmem_alloc(sizeof (*i), KM_SLEEP);
2140 	i->xdf_he_dip = dip;
2141 	i->xdf_he_path = i_ddi_strdup(path, KM_SLEEP);
2142 
2143 	mutex_enter(&xdf_hvm_list_lock);
2144 	ASSERT(i_xdf_hvm_find(path, NULL) == NULL);
2145 	ASSERT(i_xdf_hvm_find(NULL, dip) == NULL);
2146 	list_insert_head(&xdf_hvm_list, i);
2147 	mutex_exit(&xdf_hvm_list_lock);
2148 
2149 	kmem_free(path, MAXPATHLEN);
2150 }
2151 
2152 static void
2153 xdf_hvm_rm(dev_info_t *dip)
2154 {
2155 	xdf_hvm_entry_t	*i;
2156 
2157 	mutex_enter(&xdf_hvm_list_lock);
2158 	VERIFY((i = i_xdf_hvm_find(NULL, dip)) != NULL);
2159 	list_remove(&xdf_hvm_list, i);
2160 	mutex_exit(&xdf_hvm_list_lock);
2161 
2162 	kmem_free(i->xdf_he_path, strlen(i->xdf_he_path) + 1);
2163 	kmem_free(i, sizeof (*i));
2164 }
2165 
2166 static void
2167 xdf_hvm_init(void)
2168 {
2169 	list_create(&xdf_hvm_list, sizeof (xdf_hvm_entry_t),
2170 	    offsetof(xdf_hvm_entry_t, xdf_he_list));
2171 	mutex_init(&xdf_hvm_list_lock, NULL, MUTEX_DEFAULT, NULL);
2172 }
2173 
2174 static void
2175 xdf_hvm_fini(void)
2176 {
2177 	ASSERT(list_head(&xdf_hvm_list) == NULL);
2178 	list_destroy(&xdf_hvm_list);
2179 	mutex_destroy(&xdf_hvm_list_lock);
2180 }
2181 
2182 boolean_t
2183 xdf_hvm_connect(dev_info_t *dip)
2184 {
2185 	xdf_t	*vdp = (xdf_t *)ddi_get_driver_private(dip);
2186 	char	*oename, *str;
2187 	int	rv;
2188 
2189 	mutex_enter(&vdp->xdf_cb_lk);
2190 
2191 	/*
2192 	 * Before try to establish a connection we need to wait for the
2193 	 * backend hotplug scripts to have run.  Once they are run the
2194 	 * "<oename>/hotplug-status" property will be set to "connected".
2195 	 */
2196 	for (;;) {
2197 		ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
2198 
2199 		/*
2200 		 * Get the xenbus path to the backend device.  Note that
2201 		 * we can't cache this path (and we look it up on each pass
2202 		 * through this loop) because it could change during
2203 		 * suspend, resume, and migration operations.
2204 		 */
2205 		if ((oename = xvdi_get_oename(dip)) == NULL) {
2206 			mutex_exit(&vdp->xdf_cb_lk);
2207 			return (B_FALSE);
2208 		}
2209 
2210 		str = NULL;
2211 		if ((xenbus_read_str(oename, XBP_HP_STATUS, &str) == 0) &&
2212 		    (strcmp(str, XBV_HP_STATUS_CONN) == 0))
2213 			break;
2214 
2215 		if (str != NULL)
2216 			strfree(str);
2217 
2218 		/* wait for an update to "<oename>/hotplug-status" */
2219 		if (cv_wait_sig(&vdp->xdf_hp_status_cv, &vdp->xdf_cb_lk) == 0) {
2220 			/* we got interrupted by a signal */
2221 			mutex_exit(&vdp->xdf_cb_lk);
2222 			return (B_FALSE);
2223 		}
2224 	}
2225 
2226 	/* Good news.  The backend hotplug scripts have been run. */
2227 	ASSERT(MUTEX_HELD(&vdp->xdf_cb_lk));
2228 	ASSERT(strcmp(str, XBV_HP_STATUS_CONN) == 0);
2229 	strfree(str);
2230 
2231 	/*
2232 	 * If we're emulating a cd device and if the backend doesn't support
2233 	 * media request opreations, then we're not going to bother trying
2234 	 * to establish a connection for a couple reasons.  First off, media
2235 	 * requests support is required to support operations like eject and
2236 	 * media locking.  Second, other backend platforms like Linux don't
2237 	 * support hvm pv cdrom access.  They don't even have a backend pv
2238 	 * driver for cdrom device nodes, so we don't want to block forever
2239 	 * waiting for a connection to a backend driver that doesn't exist.
2240 	 */
2241 	if (XD_IS_CD(vdp) && !xenbus_exists(oename, XBP_MEDIA_REQ_SUP)) {
2242 		mutex_exit(&vdp->xdf_cb_lk);
2243 		return (B_FALSE);
2244 	}
2245 
2246 	mutex_enter(&vdp->xdf_dev_lk);
2247 	rv = xdf_connect_locked(vdp, B_TRUE);
2248 	mutex_exit(&vdp->xdf_dev_lk);
2249 	mutex_exit(&vdp->xdf_cb_lk);
2250 
2251 	return ((rv == XD_READY) ? B_TRUE : B_FALSE);
2252 }
2253 
2254 int
2255 xdf_hvm_setpgeom(dev_info_t *dip, cmlb_geom_t *geomp)
2256 {
2257 	xdf_t	*vdp = (xdf_t *)ddi_get_driver_private(dip);
2258 
2259 	/* sanity check the requested physical geometry */
2260 	mutex_enter(&vdp->xdf_dev_lk);
2261 	if ((geomp->g_secsize != XB_BSIZE) ||
2262 	    (geomp->g_capacity == 0)) {
2263 		mutex_exit(&vdp->xdf_dev_lk);
2264 		return (EINVAL);
2265 	}
2266 
2267 	/*
2268 	 * If we've already connected to the backend device then make sure
2269 	 * we're not defining a physical geometry larger than our backend
2270 	 * device.
2271 	 */
2272 	if ((vdp->xdf_xdev_nblocks != 0) &&
2273 	    (geomp->g_capacity > vdp->xdf_xdev_nblocks)) {
2274 		mutex_exit(&vdp->xdf_dev_lk);
2275 		return (EINVAL);
2276 	}
2277 
2278 	bzero(&vdp->xdf_pgeom, sizeof (vdp->xdf_pgeom));
2279 	vdp->xdf_pgeom.g_ncyl = geomp->g_ncyl;
2280 	vdp->xdf_pgeom.g_acyl = geomp->g_acyl;
2281 	vdp->xdf_pgeom.g_nhead = geomp->g_nhead;
2282 	vdp->xdf_pgeom.g_nsect = geomp->g_nsect;
2283 	vdp->xdf_pgeom.g_secsize = geomp->g_secsize;
2284 	vdp->xdf_pgeom.g_capacity = geomp->g_capacity;
2285 	vdp->xdf_pgeom.g_intrlv = geomp->g_intrlv;
2286 	vdp->xdf_pgeom.g_rpm = geomp->g_rpm;
2287 
2288 	vdp->xdf_pgeom_fixed = B_TRUE;
2289 	mutex_exit(&vdp->xdf_dev_lk);
2290 
2291 	/* force a re-validation */
2292 	cmlb_invalidate(vdp->xdf_vd_lbl, NULL);
2293 
2294 	return (0);
2295 }
2296 
2297 boolean_t
2298 xdf_is_cd(dev_info_t *dip)
2299 {
2300 	xdf_t		*vdp = (xdf_t *)ddi_get_driver_private(dip);
2301 	boolean_t	rv;
2302 
2303 	mutex_enter(&vdp->xdf_cb_lk);
2304 	rv = XD_IS_CD(vdp);
2305 	mutex_exit(&vdp->xdf_cb_lk);
2306 	return (rv);
2307 }
2308 
2309 boolean_t
2310 xdf_is_rm(dev_info_t *dip)
2311 {
2312 	xdf_t		*vdp = (xdf_t *)ddi_get_driver_private(dip);
2313 	boolean_t	rv;
2314 
2315 	mutex_enter(&vdp->xdf_cb_lk);
2316 	rv = XD_IS_RM(vdp);
2317 	mutex_exit(&vdp->xdf_cb_lk);
2318 	return (rv);
2319 }
2320 
2321 boolean_t
2322 xdf_media_req_supported(dev_info_t *dip)
2323 {
2324 	xdf_t		*vdp = (xdf_t *)ddi_get_driver_private(dip);
2325 	boolean_t	rv;
2326 
2327 	mutex_enter(&vdp->xdf_cb_lk);
2328 	rv = vdp->xdf_media_req_supported;
2329 	mutex_exit(&vdp->xdf_cb_lk);
2330 	return (rv);
2331 }
2332 
2333 #endif /* XPV_HVM_DRIVER */
2334 
2335 static int
2336 xdf_lb_getcap(dev_info_t *dip, diskaddr_t *capp)
2337 {
2338 	xdf_t *vdp;
2339 	vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip));
2340 
2341 	if (vdp == NULL)
2342 		return (ENXIO);
2343 
2344 	mutex_enter(&vdp->xdf_dev_lk);
2345 	*capp = vdp->xdf_pgeom.g_capacity;
2346 	DPRINTF(LBL_DBG, ("xdf@%s:capacity %llu\n", vdp->xdf_addr, *capp));
2347 	mutex_exit(&vdp->xdf_dev_lk);
2348 	return (0);
2349 }
2350 
2351 static int
2352 xdf_lb_getpgeom(dev_info_t *dip, cmlb_geom_t *geomp)
2353 {
2354 	xdf_t *vdp;
2355 
2356 	if ((vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip))) == NULL)
2357 		return (ENXIO);
2358 	*geomp = vdp->xdf_pgeom;
2359 	return (0);
2360 }
2361 
2362 /*
2363  * No real HBA, no geometry available from it
2364  */
2365 /*ARGSUSED*/
2366 static int
2367 xdf_lb_getvgeom(dev_info_t *dip, cmlb_geom_t *geomp)
2368 {
2369 	return (EINVAL);
2370 }
2371 
2372 static int
2373 xdf_lb_getattribute(dev_info_t *dip, tg_attribute_t *tgattributep)
2374 {
2375 	xdf_t *vdp;
2376 
2377 	if (!(vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip))))
2378 		return (ENXIO);
2379 
2380 	if (XD_IS_RO(vdp))
2381 		tgattributep->media_is_writable = 0;
2382 	else
2383 		tgattributep->media_is_writable = 1;
2384 	tgattributep->media_is_rotational = 0;
2385 	return (0);
2386 }
2387 
2388 /* ARGSUSED3 */
2389 int
2390 xdf_lb_getinfo(dev_info_t *dip, int cmd, void *arg, void *tg_cookie)
2391 {
2392 	int instance;
2393 	xdf_t   *vdp;
2394 
2395 	instance = ddi_get_instance(dip);
2396 
2397 	if ((vdp = ddi_get_soft_state(xdf_ssp, instance)) == NULL)
2398 		return (ENXIO);
2399 
2400 	switch (cmd) {
2401 	case TG_GETPHYGEOM:
2402 		return (xdf_lb_getpgeom(dip, (cmlb_geom_t *)arg));
2403 	case TG_GETVIRTGEOM:
2404 		return (xdf_lb_getvgeom(dip, (cmlb_geom_t *)arg));
2405 	case TG_GETCAPACITY:
2406 		return (xdf_lb_getcap(dip, (diskaddr_t *)arg));
2407 	case TG_GETBLOCKSIZE:
2408 		mutex_enter(&vdp->xdf_cb_lk);
2409 		*(uint32_t *)arg = vdp->xdf_xdev_secsize;
2410 		mutex_exit(&vdp->xdf_cb_lk);
2411 		return (0);
2412 	case TG_GETATTR:
2413 		return (xdf_lb_getattribute(dip, (tg_attribute_t *)arg));
2414 	default:
2415 		return (ENOTTY);
2416 	}
2417 }
2418 
2419 /* ARGSUSED5 */
2420 int
2421 xdf_lb_rdwr(dev_info_t *dip, uchar_t cmd, void *bufp,
2422     diskaddr_t start, size_t reqlen, void *tg_cookie)
2423 {
2424 	xdf_t *vdp;
2425 	struct buf *bp;
2426 	int err = 0;
2427 
2428 	vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip));
2429 
2430 	/* We don't allow IO from the oe_change callback thread */
2431 	ASSERT(curthread != vdp->xdf_oe_change_thread);
2432 
2433 	if ((start + ((reqlen / (vdp->xdf_xdev_secsize / DEV_BSIZE))
2434 	    >> DEV_BSHIFT)) > vdp->xdf_pgeom.g_capacity)
2435 		return (EINVAL);
2436 
2437 	bp = getrbuf(KM_SLEEP);
2438 	if (cmd == TG_READ)
2439 		bp->b_flags = B_BUSY | B_READ;
2440 	else
2441 		bp->b_flags = B_BUSY | B_WRITE;
2442 
2443 	bp->b_un.b_addr = bufp;
2444 	bp->b_bcount = reqlen;
2445 	bp->b_blkno = start * (vdp->xdf_xdev_secsize / DEV_BSIZE);
2446 	bp->b_edev = DDI_DEV_T_NONE; /* don't have dev_t */
2447 
2448 	mutex_enter(&vdp->xdf_dev_lk);
2449 	xdf_bp_push(vdp, bp);
2450 	mutex_exit(&vdp->xdf_dev_lk);
2451 	xdf_io_start(vdp);
2452 	if (curthread == vdp->xdf_ready_tq_thread)
2453 		(void) xdf_ring_drain(vdp);
2454 	err = biowait(bp);
2455 	ASSERT(bp->b_flags & B_DONE);
2456 	freerbuf(bp);
2457 	return (err);
2458 }
2459 
2460 /*
2461  * Lock the current media.  Set the media state to "lock".
2462  * (Media locks are only respected by the backend driver.)
2463  */
2464 static int
2465 xdf_ioctl_mlock(xdf_t *vdp)
2466 {
2467 	int rv;
2468 	mutex_enter(&vdp->xdf_cb_lk);
2469 	rv = xdf_media_req(vdp, XBV_MEDIA_REQ_LOCK, B_TRUE);
2470 	mutex_exit(&vdp->xdf_cb_lk);
2471 	return (rv);
2472 }
2473 
2474 /*
2475  * Release a media lock.  Set the media state to "none".
2476  */
2477 static int
2478 xdf_ioctl_munlock(xdf_t *vdp)
2479 {
2480 	int rv;
2481 	mutex_enter(&vdp->xdf_cb_lk);
2482 	rv = xdf_media_req(vdp, XBV_MEDIA_REQ_NONE, B_TRUE);
2483 	mutex_exit(&vdp->xdf_cb_lk);
2484 	return (rv);
2485 }
2486 
2487 /*
2488  * Eject the current media.  Ignores any media locks.  (Media locks
2489  * are only for benifit of the the backend.)
2490  */
2491 static int
2492 xdf_ioctl_eject(xdf_t *vdp)
2493 {
2494 	int rv;
2495 
2496 	mutex_enter(&vdp->xdf_cb_lk);
2497 	if ((rv = xdf_media_req(vdp, XBV_MEDIA_REQ_EJECT, B_FALSE)) != 0) {
2498 		mutex_exit(&vdp->xdf_cb_lk);
2499 		return (rv);
2500 	}
2501 
2502 	/*
2503 	 * We've set the media requests xenbus parameter to eject, so now
2504 	 * disconnect from the backend, wait for the backend to clear
2505 	 * the media requets xenbus paramter, and then we can reconnect
2506 	 * to the backend.
2507 	 */
2508 	(void) xdf_disconnect(vdp, XD_UNKNOWN, B_TRUE);
2509 	mutex_enter(&vdp->xdf_dev_lk);
2510 	if (xdf_connect_locked(vdp, B_TRUE) != XD_READY) {
2511 		mutex_exit(&vdp->xdf_dev_lk);
2512 		mutex_exit(&vdp->xdf_cb_lk);
2513 		return (EIO);
2514 	}
2515 	mutex_exit(&vdp->xdf_dev_lk);
2516 	mutex_exit(&vdp->xdf_cb_lk);
2517 	return (0);
2518 }
2519 
2520 /*
2521  * Watch for media state changes.  This can be an insertion of a device
2522  * (triggered by a 'xm block-configure' request in another domain) or
2523  * the ejection of a device (triggered by a local "eject" operation).
2524  * For a full description of the DKIOCSTATE ioctl behavior see dkio(7I).
2525  */
2526 static int
2527 xdf_dkstate(xdf_t *vdp, enum dkio_state mstate)
2528 {
2529 	enum dkio_state		prev_state;
2530 
2531 	mutex_enter(&vdp->xdf_cb_lk);
2532 	prev_state = vdp->xdf_mstate;
2533 
2534 	if (vdp->xdf_mstate == mstate) {
2535 		while (vdp->xdf_mstate == prev_state) {
2536 			if (cv_wait_sig(&vdp->xdf_mstate_cv,
2537 			    &vdp->xdf_cb_lk) == 0) {
2538 				mutex_exit(&vdp->xdf_cb_lk);
2539 				return (EINTR);
2540 			}
2541 		}
2542 	}
2543 
2544 	if ((prev_state != DKIO_INSERTED) &&
2545 	    (vdp->xdf_mstate == DKIO_INSERTED)) {
2546 		(void) xdf_media_req(vdp, XBV_MEDIA_REQ_LOCK, B_TRUE);
2547 		mutex_exit(&vdp->xdf_cb_lk);
2548 		return (0);
2549 	}
2550 
2551 	mutex_exit(&vdp->xdf_cb_lk);
2552 	return (0);
2553 }
2554 
2555 /*ARGSUSED*/
2556 static int
2557 xdf_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
2558     int *rvalp)
2559 {
2560 	minor_t		minor = getminor(dev);
2561 	int		part = XDF_PART(minor);
2562 	xdf_t		*vdp;
2563 	int		rv;
2564 
2565 	if (((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL) ||
2566 	    (!xdf_isopen(vdp, part)))
2567 		return (ENXIO);
2568 
2569 	DPRINTF(IOCTL_DBG, ("xdf@%s:ioctl: cmd %d (0x%x)\n",
2570 	    vdp->xdf_addr, cmd, cmd));
2571 
2572 	switch (cmd) {
2573 	default:
2574 		return (ENOTTY);
2575 	case DKIOCG_PHYGEOM:
2576 	case DKIOCG_VIRTGEOM:
2577 	case DKIOCGGEOM:
2578 	case DKIOCSGEOM:
2579 	case DKIOCGAPART:
2580 	case DKIOCSAPART:
2581 	case DKIOCGVTOC:
2582 	case DKIOCSVTOC:
2583 	case DKIOCPARTINFO:
2584 	case DKIOCGEXTVTOC:
2585 	case DKIOCSEXTVTOC:
2586 	case DKIOCEXTPARTINFO:
2587 	case DKIOCGMBOOT:
2588 	case DKIOCSMBOOT:
2589 	case DKIOCGETEFI:
2590 	case DKIOCSETEFI:
2591 	case DKIOCSETEXTPART:
2592 	case DKIOCPARTITION:
2593 		return (cmlb_ioctl(vdp->xdf_vd_lbl, dev, cmd, arg, mode, credp,
2594 		    rvalp, NULL));
2595 	case FDEJECT:
2596 	case DKIOCEJECT:
2597 	case CDROMEJECT:
2598 		return (xdf_ioctl_eject(vdp));
2599 	case DKIOCLOCK:
2600 		return (xdf_ioctl_mlock(vdp));
2601 	case DKIOCUNLOCK:
2602 		return (xdf_ioctl_munlock(vdp));
2603 	case CDROMREADOFFSET: {
2604 		int offset = 0;
2605 		if (!XD_IS_CD(vdp))
2606 			return (ENOTTY);
2607 		if (ddi_copyout(&offset, (void *)arg, sizeof (int), mode))
2608 			return (EFAULT);
2609 		return (0);
2610 	}
2611 	case DKIOCGMEDIAINFO: {
2612 		struct dk_minfo media_info;
2613 
2614 		media_info.dki_lbsize = vdp->xdf_xdev_secsize;
2615 		media_info.dki_capacity = vdp->xdf_pgeom.g_capacity;
2616 		if (XD_IS_CD(vdp))
2617 			media_info.dki_media_type = DK_CDROM;
2618 		else
2619 			media_info.dki_media_type = DK_FIXED_DISK;
2620 
2621 		if (ddi_copyout(&media_info, (void *)arg,
2622 		    sizeof (struct dk_minfo), mode))
2623 			return (EFAULT);
2624 		return (0);
2625 	}
2626 	case DKIOCINFO: {
2627 		struct dk_cinfo info;
2628 
2629 		/* controller information */
2630 		if (XD_IS_CD(vdp))
2631 			info.dki_ctype = DKC_CDROM;
2632 		else
2633 			info.dki_ctype = DKC_VBD;
2634 
2635 		info.dki_cnum = 0;
2636 		(void) strncpy((char *)(&info.dki_cname), "xdf", 8);
2637 
2638 		/* unit information */
2639 		info.dki_unit = ddi_get_instance(vdp->xdf_dip);
2640 		(void) strncpy((char *)(&info.dki_dname), "xdf", 8);
2641 		info.dki_flags = DKI_FMTVOL;
2642 		info.dki_partition = part;
2643 		info.dki_maxtransfer = maxphys / DEV_BSIZE;
2644 		info.dki_addr = 0;
2645 		info.dki_space = 0;
2646 		info.dki_prio = 0;
2647 		info.dki_vec = 0;
2648 
2649 		if (ddi_copyout(&info, (void *)arg, sizeof (info), mode))
2650 			return (EFAULT);
2651 		return (0);
2652 	}
2653 	case DKIOCSTATE: {
2654 		enum dkio_state mstate;
2655 
2656 		if (ddi_copyin((void *)arg, &mstate,
2657 		    sizeof (mstate), mode) != 0)
2658 			return (EFAULT);
2659 		if ((rv = xdf_dkstate(vdp, mstate)) != 0)
2660 			return (rv);
2661 		mstate = vdp->xdf_mstate;
2662 		if (ddi_copyout(&mstate, (void *)arg,
2663 		    sizeof (mstate), mode) != 0)
2664 			return (EFAULT);
2665 		return (0);
2666 	}
2667 	case DKIOCREMOVABLE: {
2668 		int i = BOOLEAN2VOID(XD_IS_RM(vdp));
2669 		if (ddi_copyout(&i, (caddr_t)arg, sizeof (i), mode))
2670 			return (EFAULT);
2671 		return (0);
2672 	}
2673 	case DKIOCGETWCE: {
2674 		int i = BOOLEAN2VOID(XD_IS_RM(vdp));
2675 		if (ddi_copyout(&i, (void *)arg, sizeof (i), mode))
2676 			return (EFAULT);
2677 		return (0);
2678 	}
2679 	case DKIOCSETWCE: {
2680 		int i;
2681 		if (ddi_copyin((void *)arg, &i, sizeof (i), mode))
2682 			return (EFAULT);
2683 		vdp->xdf_wce = VOID2BOOLEAN(i);
2684 		return (0);
2685 	}
2686 	case DKIOCFLUSHWRITECACHE: {
2687 		struct dk_callback *dkc = (struct dk_callback *)arg;
2688 
2689 		if (vdp->xdf_flush_supported) {
2690 			rv = xdf_lb_rdwr(vdp->xdf_dip, TG_WRITE,
2691 			    NULL, 0, 0, (void *)dev);
2692 		} else if (vdp->xdf_feature_barrier &&
2693 		    !xdf_barrier_flush_disable) {
2694 			rv = xdf_lb_rdwr(vdp->xdf_dip, TG_WRITE,
2695 			    vdp->xdf_cache_flush_block, xdf_flush_block,
2696 			    vdp->xdf_xdev_secsize, (void *)dev);
2697 		} else {
2698 			return (ENOTTY);
2699 		}
2700 		if ((mode & FKIOCTL) && (dkc != NULL) &&
2701 		    (dkc->dkc_callback != NULL)) {
2702 			(*dkc->dkc_callback)(dkc->dkc_cookie, rv);
2703 			/* need to return 0 after calling callback */
2704 			rv = 0;
2705 		}
2706 		return (rv);
2707 	}
2708 	}
2709 	/*NOTREACHED*/
2710 }
2711 
2712 static int
2713 xdf_strategy(struct buf *bp)
2714 {
2715 	xdf_t	*vdp;
2716 	minor_t minor;
2717 	diskaddr_t p_blkct, p_blkst;
2718 	daddr_t blkno;
2719 	ulong_t nblks;
2720 	int part;
2721 
2722 	minor = getminor(bp->b_edev);
2723 	part = XDF_PART(minor);
2724 	vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor));
2725 
2726 	mutex_enter(&vdp->xdf_dev_lk);
2727 	if (!xdf_isopen(vdp, part)) {
2728 		mutex_exit(&vdp->xdf_dev_lk);
2729 		xdf_io_err(bp, ENXIO, 0);
2730 		return (0);
2731 	}
2732 
2733 	/* We don't allow IO from the oe_change callback thread */
2734 	ASSERT(curthread != vdp->xdf_oe_change_thread);
2735 
2736 	/* Check for writes to a read only device */
2737 	if (!IS_READ(bp) && XD_IS_RO(vdp)) {
2738 		mutex_exit(&vdp->xdf_dev_lk);
2739 		xdf_io_err(bp, EROFS, 0);
2740 		return (0);
2741 	}
2742 
2743 	/* Check if this I/O is accessing a partition or the entire disk */
2744 	if ((long)bp->b_private == XB_SLICE_NONE) {
2745 		/* This I/O is using an absolute offset */
2746 		p_blkct = vdp->xdf_xdev_nblocks;
2747 		p_blkst = 0;
2748 	} else {
2749 		/* This I/O is using a partition relative offset */
2750 		mutex_exit(&vdp->xdf_dev_lk);
2751 		if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkct,
2752 		    &p_blkst, NULL, NULL, NULL)) {
2753 			xdf_io_err(bp, ENXIO, 0);
2754 			return (0);
2755 		}
2756 		mutex_enter(&vdp->xdf_dev_lk);
2757 	}
2758 
2759 	/*
2760 	 * Adjust the real blkno and bcount according to the underline
2761 	 * physical sector size.
2762 	 */
2763 	blkno = bp->b_blkno / (vdp->xdf_xdev_secsize / XB_BSIZE);
2764 
2765 	/* check for a starting block beyond the disk or partition limit */
2766 	if (blkno > p_blkct) {
2767 		DPRINTF(IO_DBG, ("xdf@%s: block %lld exceeds VBD size %"PRIu64,
2768 		    vdp->xdf_addr, (longlong_t)blkno, (uint64_t)p_blkct));
2769 		mutex_exit(&vdp->xdf_dev_lk);
2770 		xdf_io_err(bp, EINVAL, 0);
2771 		return (0);
2772 	}
2773 
2774 	/* Legacy: don't set error flag at this case */
2775 	if (blkno == p_blkct) {
2776 		mutex_exit(&vdp->xdf_dev_lk);
2777 		bp->b_resid = bp->b_bcount;
2778 		biodone(bp);
2779 		return (0);
2780 	}
2781 
2782 	/* sanitize the input buf */
2783 	bioerror(bp, 0);
2784 	bp->b_resid = 0;
2785 	bp->av_back = bp->av_forw = NULL;
2786 
2787 	/* Adjust for partial transfer, this will result in an error later */
2788 	if (vdp->xdf_xdev_secsize != 0 &&
2789 	    vdp->xdf_xdev_secsize != XB_BSIZE) {
2790 		nblks = bp->b_bcount / vdp->xdf_xdev_secsize;
2791 	} else {
2792 		nblks = bp->b_bcount >> XB_BSHIFT;
2793 	}
2794 
2795 	if ((blkno + nblks) > p_blkct) {
2796 		if (vdp->xdf_xdev_secsize != 0 &&
2797 		    vdp->xdf_xdev_secsize != XB_BSIZE) {
2798 			bp->b_resid =
2799 			    ((blkno + nblks) - p_blkct) *
2800 			    vdp->xdf_xdev_secsize;
2801 		} else {
2802 			bp->b_resid =
2803 			    ((blkno + nblks) - p_blkct) <<
2804 			    XB_BSHIFT;
2805 		}
2806 		bp->b_bcount -= bp->b_resid;
2807 	}
2808 
2809 	DPRINTF(IO_DBG, ("xdf@%s: strategy blk %lld len %lu\n",
2810 	    vdp->xdf_addr, (longlong_t)blkno, (ulong_t)bp->b_bcount));
2811 
2812 	/* Fix up the buf struct */
2813 	bp->b_flags |= B_BUSY;
2814 	bp->b_private = (void *)(uintptr_t)p_blkst;
2815 
2816 	xdf_bp_push(vdp, bp);
2817 	mutex_exit(&vdp->xdf_dev_lk);
2818 	xdf_io_start(vdp);
2819 	if (do_polled_io)
2820 		(void) xdf_ring_drain(vdp);
2821 	return (0);
2822 }
2823 
2824 /*ARGSUSED*/
2825 static int
2826 xdf_read(dev_t dev, struct uio *uiop, cred_t *credp)
2827 {
2828 	xdf_t	*vdp;
2829 	minor_t minor;
2830 	diskaddr_t p_blkcnt;
2831 	int part;
2832 
2833 	minor = getminor(dev);
2834 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
2835 		return (ENXIO);
2836 
2837 	DPRINTF(IO_DBG, ("xdf@%s: read offset 0x%"PRIx64"\n",
2838 	    vdp->xdf_addr, (int64_t)uiop->uio_offset));
2839 
2840 	part = XDF_PART(minor);
2841 	if (!xdf_isopen(vdp, part))
2842 		return (ENXIO);
2843 
2844 	if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkcnt,
2845 	    NULL, NULL, NULL, NULL))
2846 		return (ENXIO);
2847 
2848 	if (uiop->uio_loffset >= XB_DTOB(p_blkcnt, vdp))
2849 		return (ENOSPC);
2850 
2851 	if (U_INVAL(uiop))
2852 		return (EINVAL);
2853 
2854 	return (physio(xdf_strategy, NULL, dev, B_READ, xdfmin, uiop));
2855 }
2856 
2857 /*ARGSUSED*/
2858 static int
2859 xdf_write(dev_t dev, struct uio *uiop, cred_t *credp)
2860 {
2861 	xdf_t *vdp;
2862 	minor_t minor;
2863 	diskaddr_t p_blkcnt;
2864 	int part;
2865 
2866 	minor = getminor(dev);
2867 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
2868 		return (ENXIO);
2869 
2870 	DPRINTF(IO_DBG, ("xdf@%s: write offset 0x%"PRIx64"\n",
2871 	    vdp->xdf_addr, (int64_t)uiop->uio_offset));
2872 
2873 	part = XDF_PART(minor);
2874 	if (!xdf_isopen(vdp, part))
2875 		return (ENXIO);
2876 
2877 	if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkcnt,
2878 	    NULL, NULL, NULL, NULL))
2879 		return (ENXIO);
2880 
2881 	if (uiop->uio_loffset >= XB_DTOB(p_blkcnt, vdp))
2882 		return (ENOSPC);
2883 
2884 	if (U_INVAL(uiop))
2885 		return (EINVAL);
2886 
2887 	return (physio(xdf_strategy, NULL, dev, B_WRITE, xdfmin, uiop));
2888 }
2889 
2890 /*ARGSUSED*/
2891 static int
2892 xdf_aread(dev_t dev, struct aio_req *aiop, cred_t *credp)
2893 {
2894 	xdf_t	*vdp;
2895 	minor_t minor;
2896 	struct uio *uiop = aiop->aio_uio;
2897 	diskaddr_t p_blkcnt;
2898 	int part;
2899 
2900 	minor = getminor(dev);
2901 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
2902 		return (ENXIO);
2903 
2904 	part = XDF_PART(minor);
2905 	if (!xdf_isopen(vdp, part))
2906 		return (ENXIO);
2907 
2908 	if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkcnt,
2909 	    NULL, NULL, NULL, NULL))
2910 		return (ENXIO);
2911 
2912 	if (uiop->uio_loffset >= XB_DTOB(p_blkcnt, vdp))
2913 		return (ENOSPC);
2914 
2915 	if (U_INVAL(uiop))
2916 		return (EINVAL);
2917 
2918 	return (aphysio(xdf_strategy, anocancel, dev, B_READ, xdfmin, aiop));
2919 }
2920 
2921 /*ARGSUSED*/
2922 static int
2923 xdf_awrite(dev_t dev, struct aio_req *aiop, cred_t *credp)
2924 {
2925 	xdf_t *vdp;
2926 	minor_t minor;
2927 	struct uio *uiop = aiop->aio_uio;
2928 	diskaddr_t p_blkcnt;
2929 	int part;
2930 
2931 	minor = getminor(dev);
2932 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
2933 		return (ENXIO);
2934 
2935 	part = XDF_PART(minor);
2936 	if (!xdf_isopen(vdp, part))
2937 		return (ENXIO);
2938 
2939 	if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkcnt,
2940 	    NULL, NULL, NULL, NULL))
2941 		return (ENXIO);
2942 
2943 	if (uiop->uio_loffset >= XB_DTOB(p_blkcnt, vdp))
2944 		return (ENOSPC);
2945 
2946 	if (U_INVAL(uiop))
2947 		return (EINVAL);
2948 
2949 	return (aphysio(xdf_strategy, anocancel, dev, B_WRITE, xdfmin, aiop));
2950 }
2951 
2952 static int
2953 xdf_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
2954 {
2955 	struct buf dumpbuf, *dbp = &dumpbuf;
2956 	xdf_t	*vdp;
2957 	minor_t minor;
2958 	int err = 0;
2959 	int part;
2960 	diskaddr_t p_blkcnt, p_blkst;
2961 
2962 	minor = getminor(dev);
2963 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
2964 		return (ENXIO);
2965 
2966 	DPRINTF(IO_DBG, ("xdf@%s: dump addr (0x%p) blk (%ld) nblks (%d)\n",
2967 	    vdp->xdf_addr, (void *)addr, blkno, nblk));
2968 
2969 	/* We don't allow IO from the oe_change callback thread */
2970 	ASSERT(curthread != vdp->xdf_oe_change_thread);
2971 
2972 	part = XDF_PART(minor);
2973 	if (!xdf_isopen(vdp, part))
2974 		return (ENXIO);
2975 
2976 	if (cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkcnt, &p_blkst,
2977 	    NULL, NULL, NULL))
2978 		return (ENXIO);
2979 
2980 	if ((blkno + nblk) >
2981 	    (p_blkcnt * (vdp->xdf_xdev_secsize / XB_BSIZE))) {
2982 		cmn_err(CE_WARN, "xdf@%s: block %ld exceeds VBD size %"PRIu64,
2983 		    vdp->xdf_addr, (daddr_t)((blkno + nblk) /
2984 		    (vdp->xdf_xdev_secsize / XB_BSIZE)), (uint64_t)p_blkcnt);
2985 		return (EINVAL);
2986 	}
2987 
2988 	bioinit(dbp);
2989 	dbp->b_flags = B_BUSY;
2990 	dbp->b_un.b_addr = addr;
2991 	dbp->b_bcount = nblk << DEV_BSHIFT;
2992 	dbp->b_blkno = blkno;
2993 	dbp->b_edev = dev;
2994 	dbp->b_private = (void *)(uintptr_t)p_blkst;
2995 
2996 	mutex_enter(&vdp->xdf_dev_lk);
2997 	xdf_bp_push(vdp, dbp);
2998 	mutex_exit(&vdp->xdf_dev_lk);
2999 	xdf_io_start(vdp);
3000 	err = xdf_ring_drain(vdp);
3001 	biofini(dbp);
3002 	return (err);
3003 }
3004 
3005 /*ARGSUSED*/
3006 static int
3007 xdf_close(dev_t dev, int flag, int otyp, struct cred *credp)
3008 {
3009 	minor_t	minor;
3010 	xdf_t	*vdp;
3011 	int part;
3012 	ulong_t parbit;
3013 
3014 	minor = getminor(dev);
3015 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
3016 		return (ENXIO);
3017 
3018 	mutex_enter(&vdp->xdf_dev_lk);
3019 	part = XDF_PART(minor);
3020 	if (!xdf_isopen(vdp, part)) {
3021 		mutex_exit(&vdp->xdf_dev_lk);
3022 		return (ENXIO);
3023 	}
3024 	parbit = 1 << part;
3025 
3026 	ASSERT((vdp->xdf_vd_open[otyp] & parbit) != 0);
3027 	if (otyp == OTYP_LYR) {
3028 		ASSERT(vdp->xdf_vd_lyropen[part] > 0);
3029 		if (--vdp->xdf_vd_lyropen[part] == 0)
3030 			vdp->xdf_vd_open[otyp] &= ~parbit;
3031 	} else {
3032 		vdp->xdf_vd_open[otyp] &= ~parbit;
3033 	}
3034 	vdp->xdf_vd_exclopen &= ~parbit;
3035 
3036 	mutex_exit(&vdp->xdf_dev_lk);
3037 	return (0);
3038 }
3039 
3040 static int
3041 xdf_open(dev_t *devp, int flag, int otyp, cred_t *credp)
3042 {
3043 	minor_t	minor;
3044 	xdf_t	*vdp;
3045 	int part;
3046 	ulong_t parbit;
3047 	diskaddr_t p_blkct = 0;
3048 	boolean_t firstopen;
3049 	boolean_t nodelay;
3050 
3051 	minor = getminor(*devp);
3052 	if ((vdp = ddi_get_soft_state(xdf_ssp, XDF_INST(minor))) == NULL)
3053 		return (ENXIO);
3054 
3055 	nodelay = (flag & (FNDELAY | FNONBLOCK));
3056 
3057 	DPRINTF(DDI_DBG, ("xdf@%s: opening\n", vdp->xdf_addr));
3058 
3059 	/* do cv_wait until connected or failed */
3060 	mutex_enter(&vdp->xdf_cb_lk);
3061 	mutex_enter(&vdp->xdf_dev_lk);
3062 	if (!nodelay && (xdf_connect_locked(vdp, B_TRUE) != XD_READY)) {
3063 		mutex_exit(&vdp->xdf_dev_lk);
3064 		mutex_exit(&vdp->xdf_cb_lk);
3065 		return (ENXIO);
3066 	}
3067 	mutex_exit(&vdp->xdf_cb_lk);
3068 
3069 	if ((flag & FWRITE) && XD_IS_RO(vdp)) {
3070 		mutex_exit(&vdp->xdf_dev_lk);
3071 		return (EROFS);
3072 	}
3073 
3074 	part = XDF_PART(minor);
3075 	parbit = 1 << part;
3076 	if ((vdp->xdf_vd_exclopen & parbit) ||
3077 	    ((flag & FEXCL) && xdf_isopen(vdp, part))) {
3078 		mutex_exit(&vdp->xdf_dev_lk);
3079 		return (EBUSY);
3080 	}
3081 
3082 	/* are we the first one to open this node? */
3083 	firstopen = !xdf_isopen(vdp, -1);
3084 
3085 	if (otyp == OTYP_LYR)
3086 		vdp->xdf_vd_lyropen[part]++;
3087 
3088 	vdp->xdf_vd_open[otyp] |= parbit;
3089 
3090 	if (flag & FEXCL)
3091 		vdp->xdf_vd_exclopen |= parbit;
3092 
3093 	mutex_exit(&vdp->xdf_dev_lk);
3094 
3095 	/* force a re-validation */
3096 	if (firstopen)
3097 		cmlb_invalidate(vdp->xdf_vd_lbl, NULL);
3098 
3099 	/* If this is a non-blocking open then we're done */
3100 	if (nodelay)
3101 		return (0);
3102 
3103 	/*
3104 	 * This is a blocking open, so we require:
3105 	 * - that the disk have a valid label on it
3106 	 * - that the size of the partition that we're opening is non-zero
3107 	 */
3108 	if ((cmlb_partinfo(vdp->xdf_vd_lbl, part, &p_blkct,
3109 	    NULL, NULL, NULL, NULL) != 0) || (p_blkct == 0)) {
3110 		(void) xdf_close(*devp, flag, otyp, credp);
3111 		return (ENXIO);
3112 	}
3113 
3114 	return (0);
3115 }
3116 
3117 /*ARGSUSED*/
3118 static void
3119 xdf_watch_hp_status_cb(dev_info_t *dip, const char *path, void *arg)
3120 {
3121 	xdf_t *vdp = (xdf_t *)ddi_get_driver_private(dip);
3122 	cv_broadcast(&vdp->xdf_hp_status_cv);
3123 }
3124 
3125 static int
3126 xdf_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int flags,
3127     char *name, caddr_t valuep, int *lengthp)
3128 {
3129 	xdf_t	*vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip));
3130 
3131 	/*
3132 	 * Sanity check that if a dev_t or dip were specified that they
3133 	 * correspond to this device driver.  On debug kernels we'll
3134 	 * panic and on non-debug kernels we'll return failure.
3135 	 */
3136 	ASSERT(ddi_driver_major(dip) == xdf_major);
3137 	ASSERT((dev == DDI_DEV_T_ANY) || (getmajor(dev) == xdf_major));
3138 	if ((ddi_driver_major(dip) != xdf_major) ||
3139 	    ((dev != DDI_DEV_T_ANY) && (getmajor(dev) != xdf_major)))
3140 		return (DDI_PROP_NOT_FOUND);
3141 
3142 	if (vdp == NULL)
3143 		return (ddi_prop_op(dev, dip, prop_op, flags,
3144 		    name, valuep, lengthp));
3145 
3146 	return (cmlb_prop_op(vdp->xdf_vd_lbl,
3147 	    dev, dip, prop_op, flags, name, valuep, lengthp,
3148 	    XDF_PART(getminor(dev)), NULL));
3149 }
3150 
3151 /*ARGSUSED*/
3152 static int
3153 xdf_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **rp)
3154 {
3155 	int	instance = XDF_INST(getminor((dev_t)arg));
3156 	xdf_t	*vbdp;
3157 
3158 	switch (cmd) {
3159 	case DDI_INFO_DEVT2DEVINFO:
3160 		if ((vbdp = ddi_get_soft_state(xdf_ssp, instance)) == NULL) {
3161 			*rp = NULL;
3162 			return (DDI_FAILURE);
3163 		}
3164 		*rp = vbdp->xdf_dip;
3165 		return (DDI_SUCCESS);
3166 
3167 	case DDI_INFO_DEVT2INSTANCE:
3168 		*rp = (void *)(uintptr_t)instance;
3169 		return (DDI_SUCCESS);
3170 
3171 	default:
3172 		return (DDI_FAILURE);
3173 	}
3174 }
3175 
3176 /*ARGSUSED*/
3177 static int
3178 xdf_resume(dev_info_t *dip)
3179 {
3180 	xdf_t	*vdp;
3181 	char	*oename;
3182 
3183 	if ((vdp = ddi_get_soft_state(xdf_ssp, ddi_get_instance(dip))) == NULL)
3184 		goto err;
3185 
3186 	if (xdf_debug & SUSRES_DBG)
3187 		xen_printf("xdf@%s: xdf_resume\n", vdp->xdf_addr);
3188 
3189 	mutex_enter(&vdp->xdf_cb_lk);
3190 
3191 	if (xvdi_resume(dip) != DDI_SUCCESS) {
3192 		mutex_exit(&vdp->xdf_cb_lk);
3193 		goto err;
3194 	}
3195 
3196 	if (((oename = xvdi_get_oename(dip)) == NULL) ||
3197 	    (xvdi_add_xb_watch_handler(dip, oename, XBP_HP_STATUS,
3198 	    xdf_watch_hp_status_cb, NULL) != DDI_SUCCESS)) {
3199 		mutex_exit(&vdp->xdf_cb_lk);
3200 		goto err;
3201 	}
3202 
3203 	mutex_enter(&vdp->xdf_dev_lk);
3204 	ASSERT(vdp->xdf_state != XD_READY);
3205 	xdf_set_state(vdp, XD_UNKNOWN);
3206 	mutex_exit(&vdp->xdf_dev_lk);
3207 
3208 	if (xdf_setstate_init(vdp) != DDI_SUCCESS) {
3209 		mutex_exit(&vdp->xdf_cb_lk);
3210 		goto err;
3211 	}
3212 
3213 	mutex_exit(&vdp->xdf_cb_lk);
3214 
3215 	if (xdf_debug & SUSRES_DBG)
3216 		xen_printf("xdf@%s: xdf_resume: done\n", vdp->xdf_addr);
3217 	return (DDI_SUCCESS);
3218 err:
3219 	if (xdf_debug & SUSRES_DBG)
3220 		xen_printf("xdf@%s: xdf_resume: fail\n", vdp->xdf_addr);
3221 	return (DDI_FAILURE);
3222 }
3223 
3224 static int
3225 xdf_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
3226 {
3227 	int			n, instance = ddi_get_instance(dip);
3228 	ddi_iblock_cookie_t	ibc, softibc;
3229 	boolean_t		dev_iscd = B_FALSE;
3230 	xdf_t			*vdp;
3231 	char			*oename, *xsname, *str;
3232 
3233 	if ((n = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_NOTPROM,
3234 	    "xdf_debug", 0)) != 0)
3235 		xdf_debug = n;
3236 
3237 	switch (cmd) {
3238 	case DDI_RESUME:
3239 		return (xdf_resume(dip));
3240 	case DDI_ATTACH:
3241 		break;
3242 	default:
3243 		return (DDI_FAILURE);
3244 	}
3245 	/* DDI_ATTACH */
3246 
3247 	if (((xsname = xvdi_get_xsname(dip)) == NULL) ||
3248 	    ((oename = xvdi_get_oename(dip)) == NULL))
3249 		return (DDI_FAILURE);
3250 
3251 	/*
3252 	 * Disable auto-detach.  This is necessary so that we don't get
3253 	 * detached while we're disconnected from the back end.
3254 	 */
3255 	if ((ddi_prop_update_int(DDI_DEV_T_NONE, dip,
3256 	    DDI_NO_AUTODETACH, 1) != DDI_PROP_SUCCESS))
3257 		return (DDI_FAILURE);
3258 
3259 	/* driver handles kernel-issued IOCTLs */
3260 	if (ddi_prop_create(DDI_DEV_T_NONE, dip,
3261 	    DDI_PROP_CANSLEEP, DDI_KERNEL_IOCTL, NULL, 0) != DDI_PROP_SUCCESS)
3262 		return (DDI_FAILURE);
3263 
3264 	if (ddi_get_iblock_cookie(dip, 0, &ibc) != DDI_SUCCESS)
3265 		return (DDI_FAILURE);
3266 
3267 	if (ddi_get_soft_iblock_cookie(dip,
3268 	    DDI_SOFTINT_LOW, &softibc) != DDI_SUCCESS)
3269 		return (DDI_FAILURE);
3270 
3271 	if (xenbus_read_str(xsname, XBP_DEV_TYPE, &str) != 0) {
3272 		cmn_err(CE_WARN, "xdf@%s: cannot read device-type",
3273 		    ddi_get_name_addr(dip));
3274 		return (DDI_FAILURE);
3275 	}
3276 	if (strcmp(str, XBV_DEV_TYPE_CD) == 0)
3277 		dev_iscd = B_TRUE;
3278 	strfree(str);
3279 
3280 	if (ddi_soft_state_zalloc(xdf_ssp, instance) != DDI_SUCCESS)
3281 		return (DDI_FAILURE);
3282 
3283 	DPRINTF(DDI_DBG, ("xdf@%s: attaching\n", ddi_get_name_addr(dip)));
3284 	vdp = ddi_get_soft_state(xdf_ssp, instance);
3285 	ddi_set_driver_private(dip, vdp);
3286 	vdp->xdf_dip = dip;
3287 	vdp->xdf_addr = ddi_get_name_addr(dip);
3288 	vdp->xdf_suspending = B_FALSE;
3289 	vdp->xdf_media_req_supported = B_FALSE;
3290 	vdp->xdf_peer = INVALID_DOMID;
3291 	vdp->xdf_evtchn = INVALID_EVTCHN;
3292 	list_create(&vdp->xdf_vreq_act, sizeof (v_req_t),
3293 	    offsetof(v_req_t, v_link));
3294 	cv_init(&vdp->xdf_dev_cv, NULL, CV_DEFAULT, NULL);
3295 	cv_init(&vdp->xdf_hp_status_cv, NULL, CV_DEFAULT, NULL);
3296 	cv_init(&vdp->xdf_mstate_cv, NULL, CV_DEFAULT, NULL);
3297 	mutex_init(&vdp->xdf_dev_lk, NULL, MUTEX_DRIVER, (void *)ibc);
3298 	mutex_init(&vdp->xdf_cb_lk, NULL, MUTEX_DRIVER, (void *)ibc);
3299 	mutex_init(&vdp->xdf_iostat_lk, NULL, MUTEX_DRIVER, (void *)ibc);
3300 	vdp->xdf_cmbl_reattach = B_TRUE;
3301 	if (dev_iscd) {
3302 		vdp->xdf_dinfo |= VDISK_CDROM;
3303 		vdp->xdf_mstate = DKIO_EJECTED;
3304 	} else {
3305 		vdp->xdf_mstate = DKIO_NONE;
3306 	}
3307 
3308 	if ((vdp->xdf_ready_tq = ddi_taskq_create(dip, "xdf_ready_tq",
3309 	    1, TASKQ_DEFAULTPRI, 0)) == NULL)
3310 		goto errout0;
3311 
3312 	if (xvdi_add_xb_watch_handler(dip, oename, XBP_HP_STATUS,
3313 	    xdf_watch_hp_status_cb, NULL) != DDI_SUCCESS)
3314 		goto errout0;
3315 
3316 	if (ddi_add_softintr(dip, DDI_SOFTINT_LOW, &vdp->xdf_softintr_id,
3317 	    &softibc, NULL, xdf_iorestart, (caddr_t)vdp) != DDI_SUCCESS) {
3318 		cmn_err(CE_WARN, "xdf@%s: failed to add softintr",
3319 		    ddi_get_name_addr(dip));
3320 		goto errout0;
3321 	}
3322 
3323 	/*
3324 	 * Initialize the physical geometry stucture.  Note that currently
3325 	 * we don't know the size of the backend device so the number
3326 	 * of blocks on the device will be initialized to zero.  Once
3327 	 * we connect to the backend device we'll update the physical
3328 	 * geometry to reflect the real size of the device.
3329 	 */
3330 	xdf_synthetic_pgeom(dip, &vdp->xdf_pgeom);
3331 	vdp->xdf_pgeom_fixed = B_FALSE;
3332 
3333 	/*
3334 	 * create default device minor nodes: non-removable disk
3335 	 * we will adjust minor nodes after we are connected w/ backend
3336 	 */
3337 	cmlb_alloc_handle(&vdp->xdf_vd_lbl);
3338 	if (xdf_cmlb_attach(vdp) != 0) {
3339 		cmn_err(CE_WARN,
3340 		    "xdf@%s: attach failed, cmlb attach failed",
3341 		    ddi_get_name_addr(dip));
3342 		goto errout0;
3343 	}
3344 
3345 	/*
3346 	 * We ship with cache-enabled disks
3347 	 */
3348 	vdp->xdf_wce = B_TRUE;
3349 
3350 	mutex_enter(&vdp->xdf_cb_lk);
3351 	/* Watch backend XenbusState change */
3352 	if (xvdi_add_event_handler(dip,
3353 	    XS_OE_STATE, xdf_oe_change, NULL) != DDI_SUCCESS) {
3354 		mutex_exit(&vdp->xdf_cb_lk);
3355 		goto errout0;
3356 	}
3357 
3358 	if (xdf_setstate_init(vdp) != DDI_SUCCESS) {
3359 		cmn_err(CE_WARN, "xdf@%s: start connection failed",
3360 		    ddi_get_name_addr(dip));
3361 		mutex_exit(&vdp->xdf_cb_lk);
3362 		goto errout1;
3363 	}
3364 	mutex_exit(&vdp->xdf_cb_lk);
3365 
3366 #if defined(XPV_HVM_DRIVER)
3367 
3368 	xdf_hvm_add(dip);
3369 
3370 	/* Report our version to dom0.  */
3371 	if (xenbus_printf(XBT_NULL, "guest/xdf", "version", "%d",
3372 	    HVMPV_XDF_VERS))
3373 		cmn_err(CE_WARN, "xdf: couldn't write version\n");
3374 
3375 #endif /* XPV_HVM_DRIVER */
3376 
3377 	/* create kstat for iostat(1M) */
3378 	if (xdf_kstat_create(dip, "xdf", instance) != 0) {
3379 		cmn_err(CE_WARN, "xdf@%s: failed to create kstat",
3380 		    ddi_get_name_addr(dip));
3381 		goto errout1;
3382 	}
3383 
3384 
3385 	ddi_report_dev(dip);
3386 	DPRINTF(DDI_DBG, ("xdf@%s: attached\n", vdp->xdf_addr));
3387 	return (DDI_SUCCESS);
3388 
3389 errout1:
3390 	(void) xvdi_switch_state(vdp->xdf_dip, XBT_NULL, XenbusStateClosed);
3391 	xvdi_remove_event_handler(dip, XS_OE_STATE);
3392 errout0:
3393 	if (vdp->xdf_vd_lbl != NULL) {
3394 		cmlb_detach(vdp->xdf_vd_lbl, NULL);
3395 		cmlb_free_handle(&vdp->xdf_vd_lbl);
3396 		vdp->xdf_vd_lbl = NULL;
3397 	}
3398 	if (vdp->xdf_softintr_id != NULL)
3399 		ddi_remove_softintr(vdp->xdf_softintr_id);
3400 	xvdi_remove_xb_watch_handlers(dip);
3401 	if (vdp->xdf_ready_tq != NULL)
3402 		ddi_taskq_destroy(vdp->xdf_ready_tq);
3403 	mutex_destroy(&vdp->xdf_cb_lk);
3404 	mutex_destroy(&vdp->xdf_dev_lk);
3405 	cv_destroy(&vdp->xdf_dev_cv);
3406 	cv_destroy(&vdp->xdf_hp_status_cv);
3407 	ddi_soft_state_free(xdf_ssp, instance);
3408 	ddi_set_driver_private(dip, NULL);
3409 	ddi_prop_remove_all(dip);
3410 	cmn_err(CE_WARN, "xdf@%s: attach failed", ddi_get_name_addr(dip));
3411 	return (DDI_FAILURE);
3412 }
3413 
3414 static int
3415 xdf_suspend(dev_info_t *dip)
3416 {
3417 	int		instance = ddi_get_instance(dip);
3418 	xdf_t		*vdp;
3419 
3420 	if ((vdp = ddi_get_soft_state(xdf_ssp, instance)) == NULL)
3421 		return (DDI_FAILURE);
3422 
3423 	if (xdf_debug & SUSRES_DBG)
3424 		xen_printf("xdf@%s: xdf_suspend\n", vdp->xdf_addr);
3425 
3426 	xvdi_suspend(dip);
3427 
3428 	mutex_enter(&vdp->xdf_cb_lk);
3429 	mutex_enter(&vdp->xdf_dev_lk);
3430 
3431 	vdp->xdf_suspending = B_TRUE;
3432 	xdf_ring_destroy(vdp);
3433 	xdf_set_state(vdp, XD_SUSPEND);
3434 	vdp->xdf_suspending = B_FALSE;
3435 
3436 	mutex_exit(&vdp->xdf_dev_lk);
3437 	mutex_exit(&vdp->xdf_cb_lk);
3438 
3439 	if (xdf_debug & SUSRES_DBG)
3440 		xen_printf("xdf@%s: xdf_suspend: done\n", vdp->xdf_addr);
3441 
3442 	return (DDI_SUCCESS);
3443 }
3444 
3445 static int
3446 xdf_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
3447 {
3448 	xdf_t *vdp;
3449 	int instance;
3450 
3451 	switch (cmd) {
3452 
3453 	case DDI_PM_SUSPEND:
3454 		break;
3455 
3456 	case DDI_SUSPEND:
3457 		return (xdf_suspend(dip));
3458 
3459 	case DDI_DETACH:
3460 		break;
3461 
3462 	default:
3463 		return (DDI_FAILURE);
3464 	}
3465 
3466 	instance = ddi_get_instance(dip);
3467 	DPRINTF(DDI_DBG, ("xdf@%s: detaching\n", ddi_get_name_addr(dip)));
3468 	vdp = ddi_get_soft_state(xdf_ssp, instance);
3469 
3470 	if (vdp == NULL)
3471 		return (DDI_FAILURE);
3472 
3473 	mutex_enter(&vdp->xdf_cb_lk);
3474 	xdf_disconnect(vdp, XD_CLOSED, B_FALSE);
3475 	if (vdp->xdf_state != XD_CLOSED) {
3476 		mutex_exit(&vdp->xdf_cb_lk);
3477 		return (DDI_FAILURE);
3478 	}
3479 	mutex_exit(&vdp->xdf_cb_lk);
3480 
3481 	ASSERT(!ISDMACBON(vdp));
3482 
3483 #if defined(XPV_HVM_DRIVER)
3484 	xdf_hvm_rm(dip);
3485 #endif /* XPV_HVM_DRIVER */
3486 
3487 	if (vdp->xdf_timeout_id != 0)
3488 		(void) untimeout(vdp->xdf_timeout_id);
3489 
3490 	xvdi_remove_event_handler(dip, XS_OE_STATE);
3491 	ddi_taskq_destroy(vdp->xdf_ready_tq);
3492 
3493 	cmlb_detach(vdp->xdf_vd_lbl, NULL);
3494 	cmlb_free_handle(&vdp->xdf_vd_lbl);
3495 
3496 	/* we'll support backend running in domU later */
3497 #ifdef	DOMU_BACKEND
3498 	(void) xvdi_post_event(dip, XEN_HP_REMOVE);
3499 #endif
3500 
3501 	list_destroy(&vdp->xdf_vreq_act);
3502 	ddi_prop_remove_all(dip);
3503 	xdf_kstat_delete(dip);
3504 	ddi_remove_softintr(vdp->xdf_softintr_id);
3505 	xvdi_remove_xb_watch_handlers(dip);
3506 	ddi_set_driver_private(dip, NULL);
3507 	cv_destroy(&vdp->xdf_dev_cv);
3508 	mutex_destroy(&vdp->xdf_cb_lk);
3509 	mutex_destroy(&vdp->xdf_dev_lk);
3510 	if (vdp->xdf_cache_flush_block != NULL)
3511 		kmem_free(vdp->xdf_flush_mem, 2 * vdp->xdf_xdev_secsize);
3512 	ddi_soft_state_free(xdf_ssp, instance);
3513 	return (DDI_SUCCESS);
3514 }
3515 
3516 /*
3517  * Driver linkage structures.
3518  */
3519 static struct cb_ops xdf_cbops = {
3520 	xdf_open,
3521 	xdf_close,
3522 	xdf_strategy,
3523 	nodev,
3524 	xdf_dump,
3525 	xdf_read,
3526 	xdf_write,
3527 	xdf_ioctl,
3528 	nodev,
3529 	nodev,
3530 	nodev,
3531 	nochpoll,
3532 	xdf_prop_op,
3533 	NULL,
3534 	D_MP | D_NEW | D_64BIT,
3535 	CB_REV,
3536 	xdf_aread,
3537 	xdf_awrite
3538 };
3539 
3540 struct dev_ops xdf_devops = {
3541 	DEVO_REV,		/* devo_rev */
3542 	0,			/* devo_refcnt */
3543 	xdf_getinfo,		/* devo_getinfo */
3544 	nulldev,		/* devo_identify */
3545 	nulldev,		/* devo_probe */
3546 	xdf_attach,		/* devo_attach */
3547 	xdf_detach,		/* devo_detach */
3548 	nodev,			/* devo_reset */
3549 	&xdf_cbops,		/* devo_cb_ops */
3550 	NULL,			/* devo_bus_ops */
3551 	NULL,			/* devo_power */
3552 	ddi_quiesce_not_supported, /* devo_quiesce */
3553 };
3554 
3555 /*
3556  * Module linkage structures.
3557  */
3558 static struct modldrv modldrv = {
3559 	&mod_driverops,		/* Type of module.  This one is a driver */
3560 	"virtual block driver",	/* short description */
3561 	&xdf_devops		/* driver specific ops */
3562 };
3563 
3564 static struct modlinkage xdf_modlinkage = {
3565 	MODREV_1, (void *)&modldrv, NULL
3566 };
3567 
3568 /*
3569  * standard module entry points
3570  */
3571 int
3572 _init(void)
3573 {
3574 	int rc;
3575 
3576 	xdf_major = ddi_name_to_major("xdf");
3577 	if (xdf_major == (major_t)-1)
3578 		return (EINVAL);
3579 
3580 	if ((rc = ddi_soft_state_init(&xdf_ssp, sizeof (xdf_t), 0)) != 0)
3581 		return (rc);
3582 
3583 	xdf_vreq_cache = kmem_cache_create("xdf_vreq_cache",
3584 	    sizeof (v_req_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3585 	xdf_gs_cache = kmem_cache_create("xdf_gs_cache",
3586 	    sizeof (ge_slot_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3587 
3588 #if defined(XPV_HVM_DRIVER)
3589 	xdf_hvm_init();
3590 #endif /* XPV_HVM_DRIVER */
3591 
3592 	if ((rc = mod_install(&xdf_modlinkage)) != 0) {
3593 #if defined(XPV_HVM_DRIVER)
3594 		xdf_hvm_fini();
3595 #endif /* XPV_HVM_DRIVER */
3596 		kmem_cache_destroy(xdf_vreq_cache);
3597 		kmem_cache_destroy(xdf_gs_cache);
3598 		ddi_soft_state_fini(&xdf_ssp);
3599 		return (rc);
3600 	}
3601 
3602 	return (rc);
3603 }
3604 
3605 int
3606 _fini(void)
3607 {
3608 	int err;
3609 	if ((err = mod_remove(&xdf_modlinkage)) != 0)
3610 		return (err);
3611 
3612 #if defined(XPV_HVM_DRIVER)
3613 	xdf_hvm_fini();
3614 #endif /* XPV_HVM_DRIVER */
3615 
3616 	kmem_cache_destroy(xdf_vreq_cache);
3617 	kmem_cache_destroy(xdf_gs_cache);
3618 	ddi_soft_state_fini(&xdf_ssp);
3619 
3620 	return (0);
3621 }
3622 
3623 int
3624 _info(struct modinfo *modinfop)
3625 {
3626 	return (mod_info(&xdf_modlinkage, modinfop));
3627 }
3628