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