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