2 * Copyright (c) 2009-2012 Spectra Logic Corporation
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions, and the following disclaimer,
10 * without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 * substantially similar to the "NO WARRANTY" disclaimer below
13 * ("Disclaimer") and any redistribution must be conditioned upon
14 * including a substantially similar Disclaimer requirement for further
15 * binary redistribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGES.
30 * Authors: Justin T. Gibbs (Spectra Logic Corporation)
31 * Ken Merry (Spectra Logic Corporation)
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
39 * \brief Device driver supporting the vending of block storage from
40 * a FreeBSD domain to other domains.
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
51 #include <sys/devicestat.h>
53 #include <sys/fcntl.h>
54 #include <sys/filedesc.h>
56 #include <sys/module.h>
57 #include <sys/namei.h>
60 #include <sys/taskqueue.h>
61 #include <sys/types.h>
62 #include <sys/vnode.h>
63 #include <sys/mount.h>
64 #include <sys/sysctl.h>
65 #include <sys/bitstring.h>
68 #include <geom/geom.h>
70 #include <machine/_inttypes.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_kern.h>
76 #include <xen/xen-os.h>
77 #include <xen/blkif.h>
78 #include <xen/gnttab.h>
79 #include <xen/xen_intr.h>
81 #include <xen/interface/event_channel.h>
82 #include <xen/interface/grant_table.h>
84 #include <xen/xenbus/xenbusvar.h>
86 /*--------------------------- Compile-time Tunables --------------------------*/
88 * The maximum number of shared memory ring pages we will allow in a
89 * negotiated block-front/back communication channel. Allow enough
90 * ring space for all requests to be XBB_MAX_REQUEST_SIZE'd.
92 #define XBB_MAX_RING_PAGES 32
95 * The maximum number of outstanding request blocks (request headers plus
96 * additional segment blocks) we will allow in a negotiated block-front/back
97 * communication channel.
99 #define XBB_MAX_REQUESTS \
100 __CONST_RING_SIZE(blkif, PAGE_SIZE * XBB_MAX_RING_PAGES)
103 * \brief Define to force all I/O to be performed on memory owned by the
104 * backend device, with a copy-in/out to the remote domain's memory.
106 * \note This option is currently required when this driver's domain is
107 * operating in HVM mode on a system using an IOMMU.
109 * This driver uses Xen's grant table API to gain access to the memory of
110 * the remote domains it serves. When our domain is operating in PV mode,
111 * the grant table mechanism directly updates our domain's page table entries
112 * to point to the physical pages of the remote domain. This scheme guarantees
113 * that blkback and the backing devices it uses can safely perform DMA
114 * operations to satisfy requests. In HVM mode, Xen may use a HW IOMMU to
115 * insure that our domain cannot DMA to pages owned by another domain. As
116 * of Xen 4.0, IOMMU mappings for HVM guests are not updated via the grant
117 * table API. For this reason, in HVM mode, we must bounce all requests into
118 * memory that is mapped into our domain at domain startup and thus has
119 * valid IOMMU mappings.
121 #define XBB_USE_BOUNCE_BUFFERS
124 * \brief Define to enable rudimentary request logging to the console.
128 /*---------------------------------- Macros ----------------------------------*/
130 * Custom malloc type for all driver allocations.
132 static MALLOC_DEFINE(M_XENBLOCKBACK, "xbbd", "Xen Block Back Driver Data");
135 #define DPRINTF(fmt, args...) \
136 printf("xbb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
138 #define DPRINTF(fmt, args...) do {} while(0)
142 * The maximum mapped region size per request we will allow in a negotiated
143 * block-front/back communication channel.
145 #define XBB_MAX_REQUEST_SIZE \
146 MIN(MAXPHYS, BLKIF_MAX_SEGMENTS_PER_REQUEST * PAGE_SIZE)
149 * The maximum number of segments (within a request header and accompanying
150 * segment blocks) per request we will allow in a negotiated block-front/back
151 * communication channel.
153 #define XBB_MAX_SEGMENTS_PER_REQUEST \
155 MIN(BLKIF_MAX_SEGMENTS_PER_REQUEST, \
156 (XBB_MAX_REQUEST_SIZE / PAGE_SIZE) + 1)))
159 * The maximum number of ring pages that we can allow per request list.
160 * We limit this to the maximum number of segments per request, because
161 * that is already a reasonable number of segments to aggregate. This
162 * number should never be smaller than XBB_MAX_SEGMENTS_PER_REQUEST,
163 * because that would leave situations where we can't dispatch even one
166 #define XBB_MAX_SEGMENTS_PER_REQLIST XBB_MAX_SEGMENTS_PER_REQUEST
168 /*--------------------------- Forward Declarations ---------------------------*/
172 static void xbb_attach_failed(struct xbb_softc *xbb, int err, const char *fmt,
173 ...) __attribute__((format(printf, 3, 4)));
174 static int xbb_shutdown(struct xbb_softc *xbb);
175 static int xbb_detach(device_t dev);
177 /*------------------------------ Data Structures -----------------------------*/
179 STAILQ_HEAD(xbb_xen_req_list, xbb_xen_req);
182 XBB_REQLIST_NONE = 0x00,
183 XBB_REQLIST_MAPPED = 0x01
186 struct xbb_xen_reqlist {
188 * Back reference to the parent block back instance for this
189 * request. Used during bio_done handling.
191 struct xbb_softc *xbb;
194 * BLKIF_OP code for this request.
199 * Set to BLKIF_RSP_* to indicate request status.
201 * This field allows an error status to be recorded even if the
202 * delivery of this status must be deferred. Deferred reporting
203 * is necessary, for example, when an error is detected during
204 * completion processing of one bio when other bios for this
205 * request are still outstanding.
210 * Number of 512 byte sectors not transferred.
212 int residual_512b_sectors;
215 * Starting sector number of the first request in the list.
217 off_t starting_sector_number;
220 * If we're going to coalesce, the next contiguous sector would be
223 off_t next_contig_sector;
226 * Number of child requests in the list.
231 * Number of I/O requests still pending on the backend.
236 * Total number of segments for requests in the list.
241 * Flags for this particular request list.
243 xbb_reqlist_flags flags;
246 * Kernel virtual address space reserved for this request
247 * list structure and used to map the remote domain's pages for
248 * this I/O, into our domain's address space.
253 * Base, psuedo-physical address, corresponding to the start
254 * of this request's kva region.
259 #ifdef XBB_USE_BOUNCE_BUFFERS
261 * Pre-allocated domain local memory used to proxy remote
262 * domain memory during I/O operations.
268 * Array of grant handles (one per page) used to map this request.
270 grant_handle_t *gnt_handles;
273 * Device statistics request ordering type (ordered or simple).
275 devstat_tag_type ds_tag_type;
278 * Device statistics request type (read, write, no_data).
280 devstat_trans_flags ds_trans_type;
283 * The start time for this request.
285 struct bintime ds_t0;
288 * Linked list of contiguous requests with the same operation type.
290 struct xbb_xen_req_list contig_req_list;
293 * Linked list links used to aggregate idle requests in the
294 * request list free pool (xbb->reqlist_free_stailq) and pending
295 * requests waiting for execution (xbb->reqlist_pending_stailq).
297 STAILQ_ENTRY(xbb_xen_reqlist) links;
300 STAILQ_HEAD(xbb_xen_reqlist_list, xbb_xen_reqlist);
303 * \brief Object tracking an in-flight I/O from a Xen VBD consumer.
307 * Linked list links used to aggregate requests into a reqlist
308 * and to store them in the request free pool.
310 STAILQ_ENTRY(xbb_xen_req) links;
313 * The remote domain's identifier for this I/O request.
318 * The number of pages currently mapped for this request.
323 * The number of 512 byte sectors comprising this requests.
328 * BLKIF_OP code for this request.
333 * Storage used for non-native ring requests.
335 blkif_request_t ring_req_storage;
338 * Pointer to the Xen request in the ring.
340 blkif_request_t *ring_req;
343 * Consumer index for this request.
345 RING_IDX req_ring_idx;
348 * The start time for this request.
350 struct bintime ds_t0;
353 * Pointer back to our parent request list.
355 struct xbb_xen_reqlist *reqlist;
357 SLIST_HEAD(xbb_xen_req_slist, xbb_xen_req);
360 * \brief Configuration data for the shared memory request ring
361 * used to communicate with the front-end client of this
364 struct xbb_ring_config {
365 /** KVA address where ring memory is mapped. */
368 /** The pseudo-physical address where ring memory is mapped.*/
372 * Grant table handles, one per-ring page, returned by the
373 * hyperpervisor upon mapping of the ring and required to
374 * unmap it when a connection is torn down.
376 grant_handle_t handle[XBB_MAX_RING_PAGES];
379 * The device bus address returned by the hypervisor when
380 * mapping the ring and required to unmap it when a connection
383 uint64_t bus_addr[XBB_MAX_RING_PAGES];
385 /** The number of ring pages mapped for the current connection. */
389 * The grant references, one per-ring page, supplied by the
390 * front-end, allowing us to reference the ring pages in the
391 * front-end's domain and to map these pages into our own domain.
393 grant_ref_t ring_ref[XBB_MAX_RING_PAGES];
395 /** The interrupt driven even channel used to signal ring events. */
396 evtchn_port_t evtchn;
400 * Per-instance connection state flags.
405 * The front-end requested a read-only mount of the
406 * back-end device/file.
408 XBBF_READ_ONLY = 0x01,
410 /** Communication with the front-end has been established. */
411 XBBF_RING_CONNECTED = 0x02,
414 * Front-end requests exist in the ring and are waiting for
415 * xbb_xen_req objects to free up.
417 XBBF_RESOURCE_SHORTAGE = 0x04,
419 /** Connection teardown in progress. */
420 XBBF_SHUTDOWN = 0x08,
422 /** A thread is already performing shutdown processing. */
423 XBBF_IN_SHUTDOWN = 0x10
426 /** Backend device type. */
428 /** Backend type unknown. */
429 XBB_TYPE_NONE = 0x00,
432 * Backend type disk (access via cdev switch
435 XBB_TYPE_DISK = 0x01,
437 /** Backend type file (access vnode operations.). */
442 * \brief Structure used to memoize information about a per-request
443 * scatter-gather list.
445 * The chief benefit of using this data structure is it avoids having
446 * to reparse the possibly discontiguous S/G list in the original
447 * request. Due to the way that the mapping of the memory backing an
448 * I/O transaction is handled by Xen, a second pass is unavoidable.
449 * At least this way the second walk is a simple array traversal.
451 * \note A single Scatter/Gather element in the block interface covers
452 * at most 1 machine page. In this context a sector (blkif
453 * nomenclature, not what I'd choose) is a 512b aligned unit
454 * of mapping within the machine page referenced by an S/G
458 /** The number of 512b data chunks mapped in this S/G element. */
462 * The index (0 based) of the first 512b data chunk mapped
463 * in this S/G element.
468 * The index (0 based) of the last 512b data chunk mapped
469 * in this S/G element.
475 * Character device backend specific configuration data.
477 struct xbb_dev_data {
478 /** Cdev used for device backend access. */
481 /** Cdev switch used for device backend access. */
484 /** Used to hold a reference on opened cdev backend devices. */
489 * File backend specific configuration data.
491 struct xbb_file_data {
492 /** Credentials to use for vnode backed (file based) I/O. */
496 * \brief Array of io vectors used to process file based I/O.
498 * Only a single file based request is outstanding per-xbb instance,
499 * so we only need one of these.
501 struct iovec xiovecs[XBB_MAX_SEGMENTS_PER_REQLIST];
502 #ifdef XBB_USE_BOUNCE_BUFFERS
505 * \brief Array of io vectors used to handle bouncing of file reads.
507 * Vnode operations are free to modify uio data during their
508 * exectuion. In the case of a read with bounce buffering active,
509 * we need some of the data from the original uio in order to
510 * bounce-out the read data. This array serves as the temporary
511 * storage for this saved data.
513 struct iovec saved_xiovecs[XBB_MAX_SEGMENTS_PER_REQLIST];
516 * \brief Array of memoized bounce buffer kva offsets used
517 * in the file based backend.
519 * Due to the way that the mapping of the memory backing an
520 * I/O transaction is handled by Xen, a second pass through
521 * the request sg elements is unavoidable. We memoize the computed
522 * bounce address here to reduce the cost of the second walk.
524 void *xiovecs_vaddr[XBB_MAX_SEGMENTS_PER_REQLIST];
525 #endif /* XBB_USE_BOUNCE_BUFFERS */
529 * Collection of backend type specific data.
531 union xbb_backend_data {
532 struct xbb_dev_data dev;
533 struct xbb_file_data file;
537 * Function signature of backend specific I/O handlers.
539 typedef int (*xbb_dispatch_t)(struct xbb_softc *xbb,
540 struct xbb_xen_reqlist *reqlist, int operation,
544 * Per-instance configuration data.
549 * Task-queue used to process I/O requests.
551 struct taskqueue *io_taskqueue;
554 * Single "run the request queue" task enqueued
559 /** Device type for this instance. */
560 xbb_type device_type;
562 /** NewBus device corresponding to this instance. */
565 /** Backend specific dispatch routine for this instance. */
566 xbb_dispatch_t dispatch_io;
568 /** The number of requests outstanding on the backend device/file. */
569 int active_request_count;
571 /** Free pool of request tracking structures. */
572 struct xbb_xen_req_list request_free_stailq;
574 /** Array, sized at connection time, of request tracking structures. */
575 struct xbb_xen_req *requests;
577 /** Free pool of request list structures. */
578 struct xbb_xen_reqlist_list reqlist_free_stailq;
580 /** List of pending request lists awaiting execution. */
581 struct xbb_xen_reqlist_list reqlist_pending_stailq;
583 /** Array, sized at connection time, of request list structures. */
584 struct xbb_xen_reqlist *request_lists;
587 * Global pool of kva used for mapping remote domain ring
588 * and I/O transaction data.
592 /** Psuedo-physical address corresponding to kva. */
593 uint64_t gnt_base_addr;
595 /** The size of the global kva pool. */
598 /** The size of the KVA area used for request lists. */
599 int reqlist_kva_size;
601 /** The number of pages of KVA used for request lists */
602 int reqlist_kva_pages;
604 /** Bitmap of free KVA pages */
608 * \brief Cached value of the front-end's domain id.
610 * This value is used at once for each mapped page in
611 * a transaction. We cache it to avoid incuring the
612 * cost of an ivar access every time this is needed.
617 * \brief The blkif protocol abi in effect.
619 * There are situations where the back and front ends can
620 * have a different, native abi (e.g. intel x86_64 and
621 * 32bit x86 domains on the same machine). The back-end
622 * always accomodates the front-end's native abi. That
623 * value is pulled from the XenStore and recorded here.
628 * \brief The maximum number of requests and request lists allowed
629 * to be in flight at a time.
631 * This value is negotiated via the XenStore.
636 * \brief The maximum number of segments (1 page per segment)
637 * that can be mapped by a request.
639 * This value is negotiated via the XenStore.
641 u_int max_request_segments;
644 * \brief Maximum number of segments per request list.
646 * This value is derived from and will generally be larger than
647 * max_request_segments.
649 u_int max_reqlist_segments;
652 * The maximum size of any request to this back-end
655 * This value is negotiated via the XenStore.
657 u_int max_request_size;
660 * The maximum size of any request list. This is derived directly
661 * from max_reqlist_segments.
663 u_int max_reqlist_size;
665 /** Various configuration and state bit flags. */
668 /** Ring mapping and interrupt configuration data. */
669 struct xbb_ring_config ring_config;
671 /** Runtime, cross-abi safe, structures for ring access. */
672 blkif_back_rings_t rings;
674 /** IRQ mapping for the communication ring event channel. */
675 xen_intr_handle_t xen_intr_handle;
678 * \brief Backend access mode flags (e.g. write, or read-only).
680 * This value is passed to us by the front-end via the XenStore.
685 * \brief Backend device type (e.g. "disk", "cdrom", "floppy").
687 * This value is passed to us by the front-end via the XenStore.
693 * \brief Backend device/file identifier.
695 * This value is passed to us by the front-end via the XenStore.
696 * We expect this to be a POSIX path indicating the file or
702 * Vnode corresponding to the backend device node or file
707 union xbb_backend_data backend;
709 /** The native sector size of the backend. */
712 /** log2 of sector_size. */
713 u_int sector_size_shift;
715 /** Size in bytes of the backend device or file. */
719 * \brief media_size expressed in terms of the backend native
722 * (e.g. xbb->media_size >> xbb->sector_size_shift).
724 uint64_t media_num_sectors;
727 * \brief Array of memoized scatter gather data computed during the
728 * conversion of blkif ring requests to internal xbb_xen_req
731 * Ring processing is serialized so we only need one of these.
733 struct xbb_sg xbb_sgs[XBB_MAX_SEGMENTS_PER_REQLIST];
736 * Temporary grant table map used in xbb_dispatch_io(). When
737 * XBB_MAX_SEGMENTS_PER_REQLIST gets large, keeping this on the
738 * stack could cause a stack overflow.
740 struct gnttab_map_grant_ref maps[XBB_MAX_SEGMENTS_PER_REQLIST];
742 /** Mutex protecting per-instance data. */
746 * Resource representing allocated physical address space
747 * associated with our per-instance kva region.
749 struct resource *pseudo_phys_res;
751 /** Resource id for allocated physical address space. */
752 int pseudo_phys_res_id;
755 * I/O statistics from BlockBack dispatch down. These are
756 * coalesced requests, and we start them right before execution.
758 struct devstat *xbb_stats;
761 * I/O statistics coming into BlockBack. These are the requests as
762 * we get them from BlockFront. They are started as soon as we
763 * receive a request, and completed when the I/O is complete.
765 struct devstat *xbb_stats_in;
767 /** Disable sending flush to the backend */
770 /** Send a real flush for every N flush requests */
773 /** Count of flush requests in the interval */
776 /** Don't coalesce requests if this is set */
777 int no_coalesce_reqs;
779 /** Number of requests we have received */
780 uint64_t reqs_received;
782 /** Number of requests we have completed*/
783 uint64_t reqs_completed;
785 /** Number of requests we queued but not pushed*/
786 uint64_t reqs_queued_for_completion;
788 /** Number of requests we completed with an error status*/
789 uint64_t reqs_completed_with_error;
791 /** How many forced dispatches (i.e. without coalescing) have happend */
792 uint64_t forced_dispatch;
794 /** How many normal dispatches have happend */
795 uint64_t normal_dispatch;
797 /** How many total dispatches have happend */
798 uint64_t total_dispatch;
800 /** How many times we have run out of KVA */
801 uint64_t kva_shortages;
803 /** How many times we have run out of request structures */
804 uint64_t request_shortages;
807 /*---------------------------- Request Processing ----------------------------*/
809 * Allocate an internal transaction tracking structure from the free pool.
811 * \param xbb Per-instance xbb configuration structure.
813 * \return On success, a pointer to the allocated xbb_xen_req structure.
816 static inline struct xbb_xen_req *
817 xbb_get_req(struct xbb_softc *xbb)
819 struct xbb_xen_req *req;
823 mtx_assert(&xbb->lock, MA_OWNED);
825 if ((req = STAILQ_FIRST(&xbb->request_free_stailq)) != NULL) {
826 STAILQ_REMOVE_HEAD(&xbb->request_free_stailq, links);
827 xbb->active_request_count++;
834 * Return an allocated transaction tracking structure to the free pool.
836 * \param xbb Per-instance xbb configuration structure.
837 * \param req The request structure to free.
840 xbb_release_req(struct xbb_softc *xbb, struct xbb_xen_req *req)
842 mtx_assert(&xbb->lock, MA_OWNED);
844 STAILQ_INSERT_HEAD(&xbb->request_free_stailq, req, links);
845 xbb->active_request_count--;
847 KASSERT(xbb->active_request_count >= 0,
848 ("xbb_release_req: negative active count"));
852 * Return an xbb_xen_req_list of allocated xbb_xen_reqs to the free pool.
854 * \param xbb Per-instance xbb configuration structure.
855 * \param req_list The list of requests to free.
856 * \param nreqs The number of items in the list.
859 xbb_release_reqs(struct xbb_softc *xbb, struct xbb_xen_req_list *req_list,
862 mtx_assert(&xbb->lock, MA_OWNED);
864 STAILQ_CONCAT(&xbb->request_free_stailq, req_list);
865 xbb->active_request_count -= nreqs;
867 KASSERT(xbb->active_request_count >= 0,
868 ("xbb_release_reqs: negative active count"));
872 * Given a page index and 512b sector offset within that page,
873 * calculate an offset into a request's kva region.
875 * \param reqlist The request structure whose kva region will be accessed.
876 * \param pagenr The page index used to compute the kva offset.
877 * \param sector The 512b sector index used to compute the page relative
880 * \return The computed global KVA offset.
882 static inline uint8_t *
883 xbb_reqlist_vaddr(struct xbb_xen_reqlist *reqlist, int pagenr, int sector)
885 return (reqlist->kva + (PAGE_SIZE * pagenr) + (sector << 9));
888 #ifdef XBB_USE_BOUNCE_BUFFERS
890 * Given a page index and 512b sector offset within that page,
891 * calculate an offset into a request's local bounce memory region.
893 * \param reqlist The request structure whose bounce region will be accessed.
894 * \param pagenr The page index used to compute the bounce offset.
895 * \param sector The 512b sector index used to compute the page relative
898 * \return The computed global bounce buffer address.
900 static inline uint8_t *
901 xbb_reqlist_bounce_addr(struct xbb_xen_reqlist *reqlist, int pagenr, int sector)
903 return (reqlist->bounce + (PAGE_SIZE * pagenr) + (sector << 9));
908 * Given a page number and 512b sector offset within that page,
909 * calculate an offset into the request's memory region that the
910 * underlying backend device/file should use for I/O.
912 * \param reqlist The request structure whose I/O region will be accessed.
913 * \param pagenr The page index used to compute the I/O offset.
914 * \param sector The 512b sector index used to compute the page relative
917 * \return The computed global I/O address.
919 * Depending on configuration, this will either be a local bounce buffer
920 * or a pointer to the memory mapped in from the front-end domain for
923 static inline uint8_t *
924 xbb_reqlist_ioaddr(struct xbb_xen_reqlist *reqlist, int pagenr, int sector)
926 #ifdef XBB_USE_BOUNCE_BUFFERS
927 return (xbb_reqlist_bounce_addr(reqlist, pagenr, sector));
929 return (xbb_reqlist_vaddr(reqlist, pagenr, sector));
934 * Given a page index and 512b sector offset within that page, calculate
935 * an offset into the local psuedo-physical address space used to map a
936 * front-end's request data into a request.
938 * \param reqlist The request list structure whose pseudo-physical region
940 * \param pagenr The page index used to compute the pseudo-physical offset.
941 * \param sector The 512b sector index used to compute the page relative
942 * pseudo-physical offset.
944 * \return The computed global pseudo-phsyical address.
946 * Depending on configuration, this will either be a local bounce buffer
947 * or a pointer to the memory mapped in from the front-end domain for
950 static inline uintptr_t
951 xbb_get_gntaddr(struct xbb_xen_reqlist *reqlist, int pagenr, int sector)
953 struct xbb_softc *xbb;
957 return ((uintptr_t)(xbb->gnt_base_addr +
958 (uintptr_t)(reqlist->kva - xbb->kva) +
959 (PAGE_SIZE * pagenr) + (sector << 9)));
963 * Get Kernel Virtual Address space for mapping requests.
965 * \param xbb Per-instance xbb configuration structure.
966 * \param nr_pages Number of pages needed.
967 * \param check_only If set, check for free KVA but don't allocate it.
968 * \param have_lock If set, xbb lock is already held.
970 * \return On success, a pointer to the allocated KVA region. Otherwise NULL.
972 * Note: This should be unnecessary once we have either chaining or
973 * scatter/gather support for struct bio. At that point we'll be able to
974 * put multiple addresses and lengths in one bio/bio chain and won't need
975 * to map everything into one virtual segment.
978 xbb_get_kva(struct xbb_softc *xbb, int nr_pages)
980 intptr_t first_clear;
985 KASSERT(nr_pages != 0, ("xbb_get_kva of zero length"));
990 mtx_lock(&xbb->lock);
993 * Look for the first available page. If there are none, we're done.
995 bit_ffc(xbb->kva_free, xbb->reqlist_kva_pages, &first_clear);
997 if (first_clear == -1)
1001 * Starting at the first available page, look for consecutive free
1002 * pages that will satisfy the user's request.
1004 for (i = first_clear, num_clear = 0; i < xbb->reqlist_kva_pages; i++) {
1006 * If this is true, the page is used, so we have to reset
1007 * the number of clear pages and the first clear page
1008 * (since it pointed to a region with an insufficient number
1011 if (bit_test(xbb->kva_free, i)) {
1017 if (first_clear == -1)
1021 * If this is true, we've found a large enough free region
1022 * to satisfy the request.
1024 if (++num_clear == nr_pages) {
1026 bit_nset(xbb->kva_free, first_clear,
1027 first_clear + nr_pages - 1);
1029 free_kva = xbb->kva +
1030 (uint8_t *)(first_clear * PAGE_SIZE);
1032 KASSERT(free_kva >= (uint8_t *)xbb->kva &&
1033 free_kva + (nr_pages * PAGE_SIZE) <=
1034 (uint8_t *)xbb->ring_config.va,
1035 ("Free KVA %p len %d out of range, "
1036 "kva = %#jx, ring VA = %#jx\n", free_kva,
1037 nr_pages * PAGE_SIZE, (uintmax_t)xbb->kva,
1038 (uintmax_t)xbb->ring_config.va));
1045 if (free_kva == NULL) {
1046 xbb->flags |= XBBF_RESOURCE_SHORTAGE;
1047 xbb->kva_shortages++;
1050 mtx_unlock(&xbb->lock);
1056 * Free allocated KVA.
1058 * \param xbb Per-instance xbb configuration structure.
1059 * \param kva_ptr Pointer to allocated KVA region.
1060 * \param nr_pages Number of pages in the KVA region.
1063 xbb_free_kva(struct xbb_softc *xbb, uint8_t *kva_ptr, int nr_pages)
1065 intptr_t start_page;
1067 mtx_assert(&xbb->lock, MA_OWNED);
1069 start_page = (intptr_t)(kva_ptr - xbb->kva) >> PAGE_SHIFT;
1070 bit_nclear(xbb->kva_free, start_page, start_page + nr_pages - 1);
1075 * Unmap the front-end pages associated with this I/O request.
1077 * \param req The request structure to unmap.
1080 xbb_unmap_reqlist(struct xbb_xen_reqlist *reqlist)
1082 struct gnttab_unmap_grant_ref unmap[XBB_MAX_SEGMENTS_PER_REQLIST];
1088 for (i = 0; i < reqlist->nr_segments; i++) {
1090 if (reqlist->gnt_handles[i] == GRANT_REF_INVALID)
1093 unmap[invcount].host_addr = xbb_get_gntaddr(reqlist, i, 0);
1094 unmap[invcount].dev_bus_addr = 0;
1095 unmap[invcount].handle = reqlist->gnt_handles[i];
1096 reqlist->gnt_handles[i] = GRANT_REF_INVALID;
1100 error = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref,
1102 KASSERT(error == 0, ("Grant table operation failed"));
1106 * Allocate an internal transaction tracking structure from the free pool.
1108 * \param xbb Per-instance xbb configuration structure.
1110 * \return On success, a pointer to the allocated xbb_xen_reqlist structure.
1113 static inline struct xbb_xen_reqlist *
1114 xbb_get_reqlist(struct xbb_softc *xbb)
1116 struct xbb_xen_reqlist *reqlist;
1120 mtx_assert(&xbb->lock, MA_OWNED);
1122 if ((reqlist = STAILQ_FIRST(&xbb->reqlist_free_stailq)) != NULL) {
1124 STAILQ_REMOVE_HEAD(&xbb->reqlist_free_stailq, links);
1125 reqlist->flags = XBB_REQLIST_NONE;
1126 reqlist->kva = NULL;
1127 reqlist->status = BLKIF_RSP_OKAY;
1128 reqlist->residual_512b_sectors = 0;
1129 reqlist->num_children = 0;
1130 reqlist->nr_segments = 0;
1131 STAILQ_INIT(&reqlist->contig_req_list);
1138 * Return an allocated transaction tracking structure to the free pool.
1140 * \param xbb Per-instance xbb configuration structure.
1141 * \param req The request list structure to free.
1142 * \param wakeup If set, wakeup the work thread if freeing this reqlist
1143 * during a resource shortage condition.
1146 xbb_release_reqlist(struct xbb_softc *xbb, struct xbb_xen_reqlist *reqlist,
1150 mtx_assert(&xbb->lock, MA_OWNED);
1153 wakeup = xbb->flags & XBBF_RESOURCE_SHORTAGE;
1154 xbb->flags &= ~XBBF_RESOURCE_SHORTAGE;
1157 if (reqlist->kva != NULL)
1158 xbb_free_kva(xbb, reqlist->kva, reqlist->nr_segments);
1160 xbb_release_reqs(xbb, &reqlist->contig_req_list, reqlist->num_children);
1162 STAILQ_INSERT_TAIL(&xbb->reqlist_free_stailq, reqlist, links);
1164 if ((xbb->flags & XBBF_SHUTDOWN) != 0) {
1166 * Shutdown is in progress. See if we can
1167 * progress further now that one more request
1168 * has completed and been returned to the
1175 taskqueue_enqueue(xbb->io_taskqueue, &xbb->io_task);
1179 * Request resources and do basic request setup.
1181 * \param xbb Per-instance xbb configuration structure.
1182 * \param reqlist Pointer to reqlist pointer.
1183 * \param ring_req Pointer to a block ring request.
1184 * \param ring_index The ring index of this request.
1186 * \return 0 for success, non-zero for failure.
1189 xbb_get_resources(struct xbb_softc *xbb, struct xbb_xen_reqlist **reqlist,
1190 blkif_request_t *ring_req, RING_IDX ring_idx)
1192 struct xbb_xen_reqlist *nreqlist;
1193 struct xbb_xen_req *nreq;
1198 mtx_lock(&xbb->lock);
1201 * We don't allow new resources to be allocated if we're in the
1202 * process of shutting down.
1204 if ((xbb->flags & XBBF_SHUTDOWN) != 0) {
1205 mtx_unlock(&xbb->lock);
1210 * Allocate a reqlist if the caller doesn't have one already.
1212 if (*reqlist == NULL) {
1213 nreqlist = xbb_get_reqlist(xbb);
1214 if (nreqlist == NULL)
1218 /* We always allocate a request. */
1219 nreq = xbb_get_req(xbb);
1223 mtx_unlock(&xbb->lock);
1225 if (*reqlist == NULL) {
1226 *reqlist = nreqlist;
1227 nreqlist->operation = ring_req->operation;
1228 nreqlist->starting_sector_number = ring_req->sector_number;
1229 STAILQ_INSERT_TAIL(&xbb->reqlist_pending_stailq, nreqlist,
1233 nreq->reqlist = *reqlist;
1234 nreq->req_ring_idx = ring_idx;
1235 nreq->id = ring_req->id;
1236 nreq->operation = ring_req->operation;
1238 if (xbb->abi != BLKIF_PROTOCOL_NATIVE) {
1239 bcopy(ring_req, &nreq->ring_req_storage, sizeof(*ring_req));
1240 nreq->ring_req = &nreq->ring_req_storage;
1242 nreq->ring_req = ring_req;
1245 binuptime(&nreq->ds_t0);
1246 devstat_start_transaction(xbb->xbb_stats_in, &nreq->ds_t0);
1247 STAILQ_INSERT_TAIL(&(*reqlist)->contig_req_list, nreq, links);
1248 (*reqlist)->num_children++;
1249 (*reqlist)->nr_segments += ring_req->nr_segments;
1256 * We're out of resources, so set the shortage flag. The next time
1257 * a request is released, we'll try waking up the work thread to
1258 * see if we can allocate more resources.
1260 xbb->flags |= XBBF_RESOURCE_SHORTAGE;
1261 xbb->request_shortages++;
1264 xbb_release_req(xbb, nreq);
1266 if (nreqlist != NULL)
1267 xbb_release_reqlist(xbb, nreqlist, /*wakeup*/ 0);
1269 mtx_unlock(&xbb->lock);
1275 * Create and queue a response to a blkif request.
1277 * \param xbb Per-instance xbb configuration structure.
1278 * \param req The request structure to which to respond.
1279 * \param status The status code to report. See BLKIF_RSP_*
1280 * in sys/xen/interface/io/blkif.h.
1283 xbb_queue_response(struct xbb_softc *xbb, struct xbb_xen_req *req, int status)
1285 blkif_response_t *resp;
1288 * The mutex is required here, and should be held across this call
1289 * until after the subsequent call to xbb_push_responses(). This
1290 * is to guarantee that another context won't queue responses and
1291 * push them while we're active.
1293 * That could lead to the other end being notified of responses
1294 * before the resources have been freed on this end. The other end
1295 * would then be able to queue additional I/O, and we may run out
1296 * of resources because we haven't freed them all yet.
1298 mtx_assert(&xbb->lock, MA_OWNED);
1301 * Place on the response ring for the relevant domain.
1302 * For now, only the spacing between entries is different
1303 * in the different ABIs, not the response entry layout.
1306 case BLKIF_PROTOCOL_NATIVE:
1307 resp = RING_GET_RESPONSE(&xbb->rings.native,
1308 xbb->rings.native.rsp_prod_pvt);
1310 case BLKIF_PROTOCOL_X86_32:
1311 resp = (blkif_response_t *)
1312 RING_GET_RESPONSE(&xbb->rings.x86_32,
1313 xbb->rings.x86_32.rsp_prod_pvt);
1315 case BLKIF_PROTOCOL_X86_64:
1316 resp = (blkif_response_t *)
1317 RING_GET_RESPONSE(&xbb->rings.x86_64,
1318 xbb->rings.x86_64.rsp_prod_pvt);
1321 panic("Unexpected blkif protocol ABI.");
1325 resp->operation = req->operation;
1326 resp->status = status;
1328 if (status != BLKIF_RSP_OKAY)
1329 xbb->reqs_completed_with_error++;
1331 xbb->rings.common.rsp_prod_pvt++;
1333 xbb->reqs_queued_for_completion++;
1338 * Send queued responses to blkif requests.
1340 * \param xbb Per-instance xbb configuration structure.
1341 * \param run_taskqueue Flag that is set to 1 if the taskqueue
1342 * should be run, 0 if it does not need to be run.
1343 * \param notify Flag that is set to 1 if the other end should be
1344 * notified via irq, 0 if the other end should not be
1348 xbb_push_responses(struct xbb_softc *xbb, int *run_taskqueue, int *notify)
1353 * The mutex is required here.
1355 mtx_assert(&xbb->lock, MA_OWNED);
1359 RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&xbb->rings.common, *notify);
1361 if (xbb->rings.common.rsp_prod_pvt == xbb->rings.common.req_cons) {
1364 * Tail check for pending requests. Allows frontend to avoid
1365 * notifications if requests are already in flight (lower
1366 * overheads and promotes batching).
1368 RING_FINAL_CHECK_FOR_REQUESTS(&xbb->rings.common, more_to_do);
1369 } else if (RING_HAS_UNCONSUMED_REQUESTS(&xbb->rings.common)) {
1374 xbb->reqs_completed += xbb->reqs_queued_for_completion;
1375 xbb->reqs_queued_for_completion = 0;
1377 *run_taskqueue = more_to_do;
1381 * Complete a request list.
1383 * \param xbb Per-instance xbb configuration structure.
1384 * \param reqlist Allocated internal request list structure.
1387 xbb_complete_reqlist(struct xbb_softc *xbb, struct xbb_xen_reqlist *reqlist)
1389 struct xbb_xen_req *nreq;
1391 int notify, run_taskqueue;
1395 if (reqlist->flags & XBB_REQLIST_MAPPED)
1396 xbb_unmap_reqlist(reqlist);
1398 mtx_lock(&xbb->lock);
1401 * All I/O is done, send the response. A lock is not necessary
1402 * to protect the request list, because all requests have
1403 * completed. Therefore this is the only context accessing this
1404 * reqlist right now. However, in order to make sure that no one
1405 * else queues responses onto the queue or pushes them to the other
1406 * side while we're active, we need to hold the lock across the
1407 * calls to xbb_queue_response() and xbb_push_responses().
1409 STAILQ_FOREACH(nreq, &reqlist->contig_req_list, links) {
1410 off_t cur_sectors_sent;
1412 /* Put this response on the ring, but don't push yet */
1413 xbb_queue_response(xbb, nreq, reqlist->status);
1415 /* We don't report bytes sent if there is an error. */
1416 if (reqlist->status == BLKIF_RSP_OKAY)
1417 cur_sectors_sent = nreq->nr_512b_sectors;
1419 cur_sectors_sent = 0;
1421 sectors_sent += cur_sectors_sent;
1423 devstat_end_transaction(xbb->xbb_stats_in,
1424 /*bytes*/cur_sectors_sent << 9,
1425 reqlist->ds_tag_type,
1426 reqlist->ds_trans_type,
1428 /*then*/&nreq->ds_t0);
1432 * Take out any sectors not sent. If we wind up negative (which
1433 * might happen if an error is reported as well as a residual), just
1434 * report 0 sectors sent.
1436 sectors_sent -= reqlist->residual_512b_sectors;
1437 if (sectors_sent < 0)
1440 devstat_end_transaction(xbb->xbb_stats,
1441 /*bytes*/ sectors_sent << 9,
1442 reqlist->ds_tag_type,
1443 reqlist->ds_trans_type,
1445 /*then*/&reqlist->ds_t0);
1447 xbb_release_reqlist(xbb, reqlist, /*wakeup*/ 1);
1449 xbb_push_responses(xbb, &run_taskqueue, ¬ify);
1451 mtx_unlock(&xbb->lock);
1454 taskqueue_enqueue(xbb->io_taskqueue, &xbb->io_task);
1457 xen_intr_signal(xbb->xen_intr_handle);
1461 * Completion handler for buffer I/O requests issued by the device
1464 * \param bio The buffer I/O request on which to perform completion
1468 xbb_bio_done(struct bio *bio)
1470 struct xbb_softc *xbb;
1471 struct xbb_xen_reqlist *reqlist;
1473 reqlist = bio->bio_caller1;
1476 reqlist->residual_512b_sectors += bio->bio_resid >> 9;
1479 * This is a bit imprecise. With aggregated I/O a single
1480 * request list can contain multiple front-end requests and
1481 * a multiple bios may point to a single request. By carefully
1482 * walking the request list, we could map residuals and errors
1483 * back to the original front-end request, but the interface
1484 * isn't sufficiently rich for us to properly report the error.
1485 * So, we just treat the entire request list as having failed if an
1486 * error occurs on any part. And, if an error occurs, we treat
1487 * the amount of data transferred as 0.
1489 * For residuals, we report it on the overall aggregated device,
1490 * but not on the individual requests, since we don't currently
1491 * do the work to determine which front-end request to which the
1494 if (bio->bio_error) {
1495 DPRINTF("BIO returned error %d for operation on device %s\n",
1496 bio->bio_error, xbb->dev_name);
1497 reqlist->status = BLKIF_RSP_ERROR;
1499 if (bio->bio_error == ENXIO
1500 && xenbus_get_state(xbb->dev) == XenbusStateConnected) {
1503 * Backend device has disappeared. Signal the
1504 * front-end that we (the device proxy) want to
1507 xenbus_set_state(xbb->dev, XenbusStateClosing);
1511 #ifdef XBB_USE_BOUNCE_BUFFERS
1512 if (bio->bio_cmd == BIO_READ) {
1513 vm_offset_t kva_offset;
1515 kva_offset = (vm_offset_t)bio->bio_data
1516 - (vm_offset_t)reqlist->bounce;
1517 memcpy((uint8_t *)reqlist->kva + kva_offset,
1518 bio->bio_data, bio->bio_bcount);
1520 #endif /* XBB_USE_BOUNCE_BUFFERS */
1523 * Decrement the pending count for the request list. When we're
1524 * done with the requests, send status back for all of them.
1526 if (atomic_fetchadd_int(&reqlist->pendcnt, -1) == 1)
1527 xbb_complete_reqlist(xbb, reqlist);
1533 * Parse a blkif request into an internal request structure and send
1534 * it to the backend for processing.
1536 * \param xbb Per-instance xbb configuration structure.
1537 * \param reqlist Allocated internal request list structure.
1539 * \return On success, 0. For resource shortages, non-zero.
1541 * This routine performs the backend common aspects of request parsing
1542 * including compiling an internal request structure, parsing the S/G
1543 * list and any secondary ring requests in which they may reside, and
1544 * the mapping of front-end I/O pages into our domain.
1547 xbb_dispatch_io(struct xbb_softc *xbb, struct xbb_xen_reqlist *reqlist)
1549 struct xbb_sg *xbb_sg;
1550 struct gnttab_map_grant_ref *map;
1551 struct blkif_request_segment *sg;
1552 struct blkif_request_segment *last_block_sg;
1553 struct xbb_xen_req *nreq;
1563 reqlist->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1569 * First determine whether we have enough free KVA to satisfy this
1570 * request list. If not, tell xbb_run_queue() so it can go to
1571 * sleep until we have more KVA.
1573 reqlist->kva = NULL;
1574 if (reqlist->nr_segments != 0) {
1575 reqlist->kva = xbb_get_kva(xbb, reqlist->nr_segments);
1576 if (reqlist->kva == NULL) {
1578 * If we're out of KVA, return ENOMEM.
1584 binuptime(&reqlist->ds_t0);
1585 devstat_start_transaction(xbb->xbb_stats, &reqlist->ds_t0);
1587 switch (reqlist->operation) {
1588 case BLKIF_OP_WRITE_BARRIER:
1589 bio_flags |= BIO_ORDERED;
1590 reqlist->ds_tag_type = DEVSTAT_TAG_ORDERED;
1592 case BLKIF_OP_WRITE:
1593 operation = BIO_WRITE;
1594 reqlist->ds_trans_type = DEVSTAT_WRITE;
1595 if ((xbb->flags & XBBF_READ_ONLY) != 0) {
1596 DPRINTF("Attempt to write to read only device %s\n",
1598 reqlist->status = BLKIF_RSP_ERROR;
1603 operation = BIO_READ;
1604 reqlist->ds_trans_type = DEVSTAT_READ;
1606 case BLKIF_OP_FLUSH_DISKCACHE:
1608 * If this is true, the user has requested that we disable
1609 * flush support. So we just complete the requests
1612 if (xbb->disable_flush != 0) {
1617 * The user has requested that we only send a real flush
1618 * for every N flush requests. So keep count, and either
1619 * complete the request immediately or queue it for the
1622 if (xbb->flush_interval != 0) {
1623 if (++(xbb->flush_count) < xbb->flush_interval) {
1626 xbb->flush_count = 0;
1629 operation = BIO_FLUSH;
1630 reqlist->ds_tag_type = DEVSTAT_TAG_ORDERED;
1631 reqlist->ds_trans_type = DEVSTAT_NO_DATA;
1635 DPRINTF("error: unknown block io operation [%d]\n",
1636 reqlist->operation);
1637 reqlist->status = BLKIF_RSP_ERROR;
1642 xbb_sg = xbb->xbb_sgs;
1646 STAILQ_FOREACH(nreq, &reqlist->contig_req_list, links) {
1647 blkif_request_t *ring_req;
1648 RING_IDX req_ring_idx;
1651 ring_req = nreq->ring_req;
1652 req_ring_idx = nreq->req_ring_idx;
1654 nseg = ring_req->nr_segments;
1655 nreq->nr_pages = nseg;
1656 nreq->nr_512b_sectors = 0;
1660 /* Check that number of segments is sane. */
1661 if (__predict_false(nseg == 0)
1662 || __predict_false(nseg > xbb->max_request_segments)) {
1663 DPRINTF("Bad number of segments in request (%d)\n",
1665 reqlist->status = BLKIF_RSP_ERROR;
1671 last_block_sg = sg + block_segs;
1673 while (sg < last_block_sg) {
1675 XBB_MAX_SEGMENTS_PER_REQLIST,
1676 ("seg_idx %d is too large, max "
1677 "segs %d\n", seg_idx,
1678 XBB_MAX_SEGMENTS_PER_REQLIST));
1680 xbb_sg->first_sect = sg->first_sect;
1681 xbb_sg->last_sect = sg->last_sect;
1683 (int8_t)(sg->last_sect -
1684 sg->first_sect + 1);
1686 if ((sg->last_sect >= (PAGE_SIZE >> 9))
1687 || (xbb_sg->nsect <= 0)) {
1688 reqlist->status = BLKIF_RSP_ERROR;
1692 nr_sects += xbb_sg->nsect;
1693 map->host_addr = xbb_get_gntaddr(reqlist,
1694 seg_idx, /*sector*/0);
1695 KASSERT(map->host_addr + PAGE_SIZE <=
1696 xbb->ring_config.gnt_addr,
1697 ("Host address %#jx len %d overlaps "
1698 "ring address %#jx\n",
1699 (uintmax_t)map->host_addr, PAGE_SIZE,
1700 (uintmax_t)xbb->ring_config.gnt_addr));
1702 map->flags = GNTMAP_host_map;
1703 map->ref = sg->gref;
1704 map->dom = xbb->otherend_id;
1705 if (operation == BIO_WRITE)
1706 map->flags |= GNTMAP_readonly;
1714 /* Convert to the disk's sector size */
1715 nreq->nr_512b_sectors = nr_sects;
1716 nr_sects = (nr_sects << 9) >> xbb->sector_size_shift;
1717 total_sects += nr_sects;
1719 if ((nreq->nr_512b_sectors &
1720 ((xbb->sector_size >> 9) - 1)) != 0) {
1721 device_printf(xbb->dev, "%s: I/O size (%d) is not "
1722 "a multiple of the backing store sector "
1723 "size (%d)\n", __func__,
1724 nreq->nr_512b_sectors << 9,
1726 reqlist->status = BLKIF_RSP_ERROR;
1731 error = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref,
1732 xbb->maps, reqlist->nr_segments);
1734 panic("Grant table operation failed (%d)", error);
1736 reqlist->flags |= XBB_REQLIST_MAPPED;
1738 for (seg_idx = 0, map = xbb->maps; seg_idx < reqlist->nr_segments;
1741 if (__predict_false(map->status != 0)) {
1742 DPRINTF("invalid buffer -- could not remap "
1743 "it (%d)\n", map->status);
1744 DPRINTF("Mapping(%d): Host Addr 0x%lx, flags "
1745 "0x%x ref 0x%x, dom %d\n", seg_idx,
1746 map->host_addr, map->flags, map->ref,
1748 reqlist->status = BLKIF_RSP_ERROR;
1752 reqlist->gnt_handles[seg_idx] = map->handle;
1754 if (reqlist->starting_sector_number + total_sects >
1755 xbb->media_num_sectors) {
1757 DPRINTF("%s of [%" PRIu64 ",%" PRIu64 "] "
1758 "extends past end of device %s\n",
1759 operation == BIO_READ ? "read" : "write",
1760 reqlist->starting_sector_number,
1761 reqlist->starting_sector_number + total_sects,
1763 reqlist->status = BLKIF_RSP_ERROR;
1769 error = xbb->dispatch_io(xbb,
1775 reqlist->status = BLKIF_RSP_ERROR;
1783 xbb_complete_reqlist(xbb, reqlist);
1789 xbb_count_sects(blkif_request_t *ring_req)
1794 for (i = 0; i < ring_req->nr_segments; i++) {
1797 nsect = (int8_t)(ring_req->seg[i].last_sect -
1798 ring_req->seg[i].first_sect + 1);
1809 * Process incoming requests from the shared communication ring in response
1810 * to a signal on the ring's event channel.
1812 * \param context Callback argument registerd during task initialization -
1813 * the xbb_softc for this instance.
1814 * \param pending The number of taskqueue_enqueue events that have
1815 * occurred since this handler was last run.
1818 xbb_run_queue(void *context, int pending)
1820 struct xbb_softc *xbb;
1821 blkif_back_rings_t *rings;
1823 uint64_t cur_sector;
1825 struct xbb_xen_reqlist *reqlist;
1828 xbb = (struct xbb_softc *)context;
1829 rings = &xbb->rings;
1832 * Work gather and dispatch loop. Note that we have a bias here
1833 * towards gathering I/O sent by blockfront. We first gather up
1834 * everything in the ring, as long as we have resources. Then we
1835 * dispatch one request, and then attempt to gather up any
1836 * additional requests that have come in while we were dispatching
1839 * This allows us to get a clearer picture (via devstat) of how
1840 * many requests blockfront is queueing to us at any given time.
1846 * Initialize reqlist to the last element in the pending
1847 * queue, if there is one. This allows us to add more
1848 * requests to that request list, if we have room.
1850 reqlist = STAILQ_LAST(&xbb->reqlist_pending_stailq,
1851 xbb_xen_reqlist, links);
1852 if (reqlist != NULL) {
1853 cur_sector = reqlist->next_contig_sector;
1854 cur_operation = reqlist->operation;
1861 * Cache req_prod to avoid accessing a cache line shared
1862 * with the frontend.
1864 rp = rings->common.sring->req_prod;
1866 /* Ensure we see queued requests up to 'rp'. */
1870 * Run so long as there is work to consume and the generation
1871 * of a response will not overflow the ring.
1873 * @note There's a 1 to 1 relationship between requests and
1874 * responses, so an overflow should never occur. This
1875 * test is to protect our domain from digesting bogus
1876 * data. Shouldn't we log this?
1878 while (rings->common.req_cons != rp
1879 && RING_REQUEST_CONS_OVERFLOW(&rings->common,
1880 rings->common.req_cons) == 0){
1881 blkif_request_t ring_req_storage;
1882 blkif_request_t *ring_req;
1886 case BLKIF_PROTOCOL_NATIVE:
1887 ring_req = RING_GET_REQUEST(&xbb->rings.native,
1888 rings->common.req_cons);
1890 case BLKIF_PROTOCOL_X86_32:
1892 struct blkif_x86_32_request *ring_req32;
1894 ring_req32 = RING_GET_REQUEST(
1895 &xbb->rings.x86_32, rings->common.req_cons);
1896 blkif_get_x86_32_req(&ring_req_storage,
1898 ring_req = &ring_req_storage;
1901 case BLKIF_PROTOCOL_X86_64:
1903 struct blkif_x86_64_request *ring_req64;
1905 ring_req64 =RING_GET_REQUEST(&xbb->rings.x86_64,
1906 rings->common.req_cons);
1907 blkif_get_x86_64_req(&ring_req_storage,
1909 ring_req = &ring_req_storage;
1913 panic("Unexpected blkif protocol ABI.");
1918 * Check for situations that would require closing
1919 * off this I/O for further coalescing:
1920 * - Coalescing is turned off.
1921 * - Current I/O is out of sequence with the previous
1923 * - Coalesced I/O would be too large.
1925 if ((reqlist != NULL)
1926 && ((xbb->no_coalesce_reqs != 0)
1927 || ((xbb->no_coalesce_reqs == 0)
1928 && ((ring_req->sector_number != cur_sector)
1929 || (ring_req->operation != cur_operation)
1930 || ((ring_req->nr_segments + reqlist->nr_segments) >
1931 xbb->max_reqlist_segments))))) {
1936 * Grab and check for all resources in one shot.
1937 * If we can't get all of the resources we need,
1938 * the shortage is noted and the thread will get
1939 * woken up when more resources are available.
1941 retval = xbb_get_resources(xbb, &reqlist, ring_req,
1942 xbb->rings.common.req_cons);
1946 * Resource shortage has been recorded.
1947 * We'll be scheduled to run once a request
1948 * object frees up due to a completion.
1954 * Signify that we can overwrite this request with
1955 * a response by incrementing our consumer index.
1956 * The response won't be generated until after
1957 * we've already consumed all necessary data out
1958 * of the version of the request in the ring buffer
1959 * (for native mode). We must update the consumer
1960 * index before issueing back-end I/O so there is
1961 * no possibility that it will complete and a
1962 * response be generated before we make room in
1963 * the queue for that response.
1965 xbb->rings.common.req_cons++;
1966 xbb->reqs_received++;
1968 cur_size = xbb_count_sects(ring_req);
1969 cur_sector = ring_req->sector_number + cur_size;
1970 reqlist->next_contig_sector = cur_sector;
1971 cur_operation = ring_req->operation;
1974 /* Check for I/O to dispatch */
1975 reqlist = STAILQ_FIRST(&xbb->reqlist_pending_stailq);
1976 if (reqlist == NULL) {
1978 * We're out of work to do, put the task queue to
1985 * Grab the first request off the queue and attempt
1988 STAILQ_REMOVE_HEAD(&xbb->reqlist_pending_stailq, links);
1990 retval = xbb_dispatch_io(xbb, reqlist);
1993 * xbb_dispatch_io() returns non-zero only when
1994 * there is a resource shortage. If that's the
1995 * case, re-queue this request on the head of the
1996 * queue, and go to sleep until we have more
1999 STAILQ_INSERT_HEAD(&xbb->reqlist_pending_stailq,
2004 * If we still have anything on the queue after
2005 * removing the head entry, that is because we
2006 * met one of the criteria to create a new
2007 * request list (outlined above), and we'll call
2008 * that a forced dispatch for statistical purposes.
2010 * Otherwise, if there is only one element on the
2011 * queue, we coalesced everything available on
2012 * the ring and we'll call that a normal dispatch.
2014 reqlist = STAILQ_FIRST(&xbb->reqlist_pending_stailq);
2016 if (reqlist != NULL)
2017 xbb->forced_dispatch++;
2019 xbb->normal_dispatch++;
2021 xbb->total_dispatch++;
2027 * Interrupt handler bound to the shared ring's event channel.
2029 * \param arg Callback argument registerd during event channel
2030 * binding - the xbb_softc for this instance.
2033 xbb_filter(void *arg)
2035 struct xbb_softc *xbb;
2037 /* Defer to taskqueue thread. */
2038 xbb = (struct xbb_softc *)arg;
2039 taskqueue_enqueue(xbb->io_taskqueue, &xbb->io_task);
2041 return (FILTER_HANDLED);
2044 SDT_PROVIDER_DEFINE(xbb);
2045 SDT_PROBE_DEFINE1(xbb, kernel, xbb_dispatch_dev, flush, "int");
2046 SDT_PROBE_DEFINE3(xbb, kernel, xbb_dispatch_dev, read, "int", "uint64_t",
2048 SDT_PROBE_DEFINE3(xbb, kernel, xbb_dispatch_dev, write, "int",
2049 "uint64_t", "uint64_t");
2051 /*----------------------------- Backend Handlers -----------------------------*/
2053 * Backend handler for character device access.
2055 * \param xbb Per-instance xbb configuration structure.
2056 * \param reqlist Allocated internal request list structure.
2057 * \param operation BIO_* I/O operation code.
2058 * \param bio_flags Additional bio_flag data to pass to any generated
2059 * bios (e.g. BIO_ORDERED)..
2061 * \return 0 for success, errno codes for failure.
2064 xbb_dispatch_dev(struct xbb_softc *xbb, struct xbb_xen_reqlist *reqlist,
2065 int operation, int bio_flags)
2067 struct xbb_dev_data *dev_data;
2068 struct bio *bios[XBB_MAX_SEGMENTS_PER_REQLIST];
2071 struct xbb_sg *xbb_sg;
2078 dev_data = &xbb->backend.dev;
2079 bio_offset = (off_t)reqlist->starting_sector_number
2080 << xbb->sector_size_shift;
2085 if (operation == BIO_FLUSH) {
2087 if (__predict_false(bio == NULL)) {
2088 DPRINTF("Unable to allocate bio for BIO_FLUSH\n");
2093 bio->bio_cmd = BIO_FLUSH;
2094 bio->bio_flags |= BIO_ORDERED;
2095 bio->bio_dev = dev_data->cdev;
2096 bio->bio_offset = 0;
2098 bio->bio_done = xbb_bio_done;
2099 bio->bio_caller1 = reqlist;
2100 bio->bio_pblkno = 0;
2102 reqlist->pendcnt = 1;
2104 SDT_PROBE1(xbb, kernel, xbb_dispatch_dev, flush,
2105 device_get_unit(xbb->dev));
2107 (*dev_data->csw->d_strategy)(bio);
2112 xbb_sg = xbb->xbb_sgs;
2114 nseg = reqlist->nr_segments;
2116 for (seg_idx = 0; seg_idx < nseg; seg_idx++, xbb_sg++) {
2119 * KVA will not be contiguous, so any additional
2120 * I/O will need to be represented in a new bio.
2123 && (xbb_sg->first_sect != 0)) {
2124 if ((bio->bio_length & (xbb->sector_size - 1)) != 0) {
2125 printf("%s: Discontiguous I/O request "
2126 "from domain %d ends on "
2127 "non-sector boundary\n",
2128 __func__, xbb->otherend_id);
2130 goto fail_free_bios;
2137 * Make sure that the start of this bio is
2138 * aligned to a device sector.
2140 if ((bio_offset & (xbb->sector_size - 1)) != 0){
2141 printf("%s: Misaligned I/O request "
2142 "from domain %d\n", __func__,
2145 goto fail_free_bios;
2148 bio = bios[nbio++] = g_new_bio();
2149 if (__predict_false(bio == NULL)) {
2151 goto fail_free_bios;
2153 bio->bio_cmd = operation;
2154 bio->bio_flags |= bio_flags;
2155 bio->bio_dev = dev_data->cdev;
2156 bio->bio_offset = bio_offset;
2157 bio->bio_data = xbb_reqlist_ioaddr(reqlist, seg_idx,
2158 xbb_sg->first_sect);
2159 bio->bio_done = xbb_bio_done;
2160 bio->bio_caller1 = reqlist;
2161 bio->bio_pblkno = bio_offset >> xbb->sector_size_shift;
2164 bio->bio_length += xbb_sg->nsect << 9;
2165 bio->bio_bcount = bio->bio_length;
2166 bio_offset += xbb_sg->nsect << 9;
2168 if (xbb_sg->last_sect != (PAGE_SIZE - 512) >> 9) {
2170 if ((bio->bio_length & (xbb->sector_size - 1)) != 0) {
2171 printf("%s: Discontiguous I/O request "
2172 "from domain %d ends on "
2173 "non-sector boundary\n",
2174 __func__, xbb->otherend_id);
2176 goto fail_free_bios;
2179 * KVA will not be contiguous, so any additional
2180 * I/O will need to be represented in a new bio.
2186 reqlist->pendcnt = nbio;
2188 for (bio_idx = 0; bio_idx < nbio; bio_idx++)
2190 #ifdef XBB_USE_BOUNCE_BUFFERS
2191 vm_offset_t kva_offset;
2193 kva_offset = (vm_offset_t)bios[bio_idx]->bio_data
2194 - (vm_offset_t)reqlist->bounce;
2195 if (operation == BIO_WRITE) {
2196 memcpy(bios[bio_idx]->bio_data,
2197 (uint8_t *)reqlist->kva + kva_offset,
2198 bios[bio_idx]->bio_bcount);
2201 if (operation == BIO_READ) {
2202 SDT_PROBE3(xbb, kernel, xbb_dispatch_dev, read,
2203 device_get_unit(xbb->dev),
2204 bios[bio_idx]->bio_offset,
2205 bios[bio_idx]->bio_length);
2206 } else if (operation == BIO_WRITE) {
2207 SDT_PROBE3(xbb, kernel, xbb_dispatch_dev, write,
2208 device_get_unit(xbb->dev),
2209 bios[bio_idx]->bio_offset,
2210 bios[bio_idx]->bio_length);
2212 (*dev_data->csw->d_strategy)(bios[bio_idx]);
2218 for (bio_idx = 0; bio_idx < (nbio-1); bio_idx++)
2219 g_destroy_bio(bios[bio_idx]);
2224 SDT_PROBE_DEFINE1(xbb, kernel, xbb_dispatch_file, flush, "int");
2225 SDT_PROBE_DEFINE3(xbb, kernel, xbb_dispatch_file, read, "int", "uint64_t",
2227 SDT_PROBE_DEFINE3(xbb, kernel, xbb_dispatch_file, write, "int",
2228 "uint64_t", "uint64_t");
2231 * Backend handler for file access.
2233 * \param xbb Per-instance xbb configuration structure.
2234 * \param reqlist Allocated internal request list.
2235 * \param operation BIO_* I/O operation code.
2236 * \param flags Additional bio_flag data to pass to any generated bios
2237 * (e.g. BIO_ORDERED)..
2239 * \return 0 for success, errno codes for failure.
2242 xbb_dispatch_file(struct xbb_softc *xbb, struct xbb_xen_reqlist *reqlist,
2243 int operation, int flags)
2245 struct xbb_file_data *file_data;
2250 struct xbb_sg *xbb_sg;
2251 struct iovec *xiovec;
2252 #ifdef XBB_USE_BOUNCE_BUFFERS
2254 int saved_uio_iovcnt;
2255 #endif /* XBB_USE_BOUNCE_BUFFERS */
2258 file_data = &xbb->backend.file;
2261 bzero(&xuio, sizeof(xuio));
2263 switch (operation) {
2265 xuio.uio_rw = UIO_READ;
2268 xuio.uio_rw = UIO_WRITE;
2271 struct mount *mountpoint;
2273 SDT_PROBE1(xbb, kernel, xbb_dispatch_file, flush,
2274 device_get_unit(xbb->dev));
2276 (void) vn_start_write(xbb->vn, &mountpoint, V_WAIT);
2278 vn_lock(xbb->vn, LK_EXCLUSIVE | LK_RETRY);
2279 error = VOP_FSYNC(xbb->vn, MNT_WAIT, curthread);
2280 VOP_UNLOCK(xbb->vn, 0);
2282 vn_finished_write(mountpoint);
2284 goto bailout_send_response;
2288 panic("invalid operation %d", operation);
2291 xuio.uio_offset = (vm_offset_t)reqlist->starting_sector_number
2292 << xbb->sector_size_shift;
2293 xuio.uio_segflg = UIO_SYSSPACE;
2294 xuio.uio_iov = file_data->xiovecs;
2295 xuio.uio_iovcnt = 0;
2296 xbb_sg = xbb->xbb_sgs;
2297 nseg = reqlist->nr_segments;
2299 for (xiovec = NULL, seg_idx = 0; seg_idx < nseg; seg_idx++, xbb_sg++) {
2302 * If the first sector is not 0, the KVA will
2303 * not be contiguous and we'll need to go on
2304 * to another segment.
2306 if (xbb_sg->first_sect != 0)
2309 if (xiovec == NULL) {
2310 xiovec = &file_data->xiovecs[xuio.uio_iovcnt];
2311 xiovec->iov_base = xbb_reqlist_ioaddr(reqlist,
2312 seg_idx, xbb_sg->first_sect);
2313 #ifdef XBB_USE_BOUNCE_BUFFERS
2315 * Store the address of the incoming
2316 * buffer at this particular offset
2317 * as well, so we can do the copy
2318 * later without having to do more
2319 * work to recalculate this address.
2321 p_vaddr = &file_data->xiovecs_vaddr[xuio.uio_iovcnt];
2322 *p_vaddr = xbb_reqlist_vaddr(reqlist, seg_idx,
2323 xbb_sg->first_sect);
2324 #endif /* XBB_USE_BOUNCE_BUFFERS */
2325 xiovec->iov_len = 0;
2329 xiovec->iov_len += xbb_sg->nsect << 9;
2331 xuio.uio_resid += xbb_sg->nsect << 9;
2334 * If the last sector is not the full page
2335 * size count, the next segment will not be
2336 * contiguous in KVA and we need a new iovec.
2338 if (xbb_sg->last_sect != (PAGE_SIZE - 512) >> 9)
2342 xuio.uio_td = curthread;
2344 #ifdef XBB_USE_BOUNCE_BUFFERS
2345 saved_uio_iovcnt = xuio.uio_iovcnt;
2347 if (operation == BIO_WRITE) {
2348 /* Copy the write data to the local buffer. */
2349 for (seg_idx = 0, p_vaddr = file_data->xiovecs_vaddr,
2350 xiovec = xuio.uio_iov; seg_idx < xuio.uio_iovcnt;
2351 seg_idx++, xiovec++, p_vaddr++) {
2353 memcpy(xiovec->iov_base, *p_vaddr, xiovec->iov_len);
2357 * We only need to save off the iovecs in the case of a
2358 * read, because the copy for the read happens after the
2359 * VOP_READ(). (The uio will get modified in that call
2362 memcpy(file_data->saved_xiovecs, xuio.uio_iov,
2363 xuio.uio_iovcnt * sizeof(xuio.uio_iov[0]));
2365 #endif /* XBB_USE_BOUNCE_BUFFERS */
2367 switch (operation) {
2370 SDT_PROBE3(xbb, kernel, xbb_dispatch_file, read,
2371 device_get_unit(xbb->dev), xuio.uio_offset,
2374 vn_lock(xbb->vn, LK_EXCLUSIVE | LK_RETRY);
2377 * UFS pays attention to IO_DIRECT for reads. If the
2378 * DIRECTIO option is configured into the kernel, it calls
2379 * ffs_rawread(). But that only works for single-segment
2380 * uios with user space addresses. In our case, with a
2381 * kernel uio, it still reads into the buffer cache, but it
2382 * will just try to release the buffer from the cache later
2385 * ZFS does not pay attention to IO_DIRECT for reads.
2387 * UFS does not pay attention to IO_SYNC for reads.
2389 * ZFS pays attention to IO_SYNC (which translates into the
2390 * Solaris define FRSYNC for zfs_read()) for reads. It
2391 * attempts to sync the file before reading.
2393 * So, to attempt to provide some barrier semantics in the
2394 * BIO_ORDERED case, set both IO_DIRECT and IO_SYNC.
2396 error = VOP_READ(xbb->vn, &xuio, (flags & BIO_ORDERED) ?
2397 (IO_DIRECT|IO_SYNC) : 0, file_data->cred);
2399 VOP_UNLOCK(xbb->vn, 0);
2402 struct mount *mountpoint;
2404 SDT_PROBE3(xbb, kernel, xbb_dispatch_file, write,
2405 device_get_unit(xbb->dev), xuio.uio_offset,
2408 (void)vn_start_write(xbb->vn, &mountpoint, V_WAIT);
2410 vn_lock(xbb->vn, LK_EXCLUSIVE | LK_RETRY);
2413 * UFS pays attention to IO_DIRECT for writes. The write
2414 * is done asynchronously. (Normally the write would just
2415 * get put into cache.
2417 * UFS pays attention to IO_SYNC for writes. It will
2418 * attempt to write the buffer out synchronously if that
2421 * ZFS does not pay attention to IO_DIRECT for writes.
2423 * ZFS pays attention to IO_SYNC (a.k.a. FSYNC or FRSYNC)
2424 * for writes. It will flush the transaction from the
2425 * cache before returning.
2427 * So if we've got the BIO_ORDERED flag set, we want
2428 * IO_SYNC in either the UFS or ZFS case.
2430 error = VOP_WRITE(xbb->vn, &xuio, (flags & BIO_ORDERED) ?
2431 IO_SYNC : 0, file_data->cred);
2432 VOP_UNLOCK(xbb->vn, 0);
2434 vn_finished_write(mountpoint);
2439 panic("invalid operation %d", operation);
2443 #ifdef XBB_USE_BOUNCE_BUFFERS
2444 /* We only need to copy here for read operations */
2445 if (operation == BIO_READ) {
2447 for (seg_idx = 0, p_vaddr = file_data->xiovecs_vaddr,
2448 xiovec = file_data->saved_xiovecs;
2449 seg_idx < saved_uio_iovcnt; seg_idx++,
2450 xiovec++, p_vaddr++) {
2453 * Note that we have to use the copy of the
2454 * io vector we made above. uiomove() modifies
2455 * the uio and its referenced vector as uiomove
2456 * performs the copy, so we can't rely on any
2457 * state from the original uio.
2459 memcpy(*p_vaddr, xiovec->iov_base, xiovec->iov_len);
2462 #endif /* XBB_USE_BOUNCE_BUFFERS */
2464 bailout_send_response:
2467 reqlist->status = BLKIF_RSP_ERROR;
2469 xbb_complete_reqlist(xbb, reqlist);
2474 /*--------------------------- Backend Configuration --------------------------*/
2476 * Close and cleanup any backend device/file specific state for this
2477 * block back instance.
2479 * \param xbb Per-instance xbb configuration structure.
2482 xbb_close_backend(struct xbb_softc *xbb)
2485 DPRINTF("closing dev=%s\n", xbb->dev_name);
2489 if ((xbb->flags & XBBF_READ_ONLY) == 0)
2492 switch (xbb->device_type) {
2494 if (xbb->backend.dev.csw) {
2495 dev_relthread(xbb->backend.dev.cdev,
2496 xbb->backend.dev.dev_ref);
2497 xbb->backend.dev.csw = NULL;
2498 xbb->backend.dev.cdev = NULL;
2505 panic("Unexpected backend type.");
2509 (void)vn_close(xbb->vn, flags, NOCRED, curthread);
2512 switch (xbb->device_type) {
2516 if (xbb->backend.file.cred != NULL) {
2517 crfree(xbb->backend.file.cred);
2518 xbb->backend.file.cred = NULL;
2523 panic("Unexpected backend type.");
2531 * Open a character device to be used for backend I/O.
2533 * \param xbb Per-instance xbb configuration structure.
2535 * \return 0 for success, errno codes for failure.
2538 xbb_open_dev(struct xbb_softc *xbb)
2542 struct cdevsw *devsw;
2545 xbb->device_type = XBB_TYPE_DISK;
2546 xbb->dispatch_io = xbb_dispatch_dev;
2547 xbb->backend.dev.cdev = xbb->vn->v_rdev;
2548 xbb->backend.dev.csw = dev_refthread(xbb->backend.dev.cdev,
2549 &xbb->backend.dev.dev_ref);
2550 if (xbb->backend.dev.csw == NULL)
2551 panic("Unable to retrieve device switch");
2553 error = VOP_GETATTR(xbb->vn, &vattr, NOCRED);
2555 xenbus_dev_fatal(xbb->dev, error, "error getting "
2556 "vnode attributes for device %s",
2562 dev = xbb->vn->v_rdev;
2563 devsw = dev->si_devsw;
2564 if (!devsw->d_ioctl) {
2565 xenbus_dev_fatal(xbb->dev, ENODEV, "no d_ioctl for "
2566 "device %s!", xbb->dev_name);
2570 error = devsw->d_ioctl(dev, DIOCGSECTORSIZE,
2571 (caddr_t)&xbb->sector_size, FREAD,
2574 xenbus_dev_fatal(xbb->dev, error,
2575 "error calling ioctl DIOCGSECTORSIZE "
2576 "for device %s", xbb->dev_name);
2580 error = devsw->d_ioctl(dev, DIOCGMEDIASIZE,
2581 (caddr_t)&xbb->media_size, FREAD,
2584 xenbus_dev_fatal(xbb->dev, error,
2585 "error calling ioctl DIOCGMEDIASIZE "
2586 "for device %s", xbb->dev_name);
2594 * Open a file to be used for backend I/O.
2596 * \param xbb Per-instance xbb configuration structure.
2598 * \return 0 for success, errno codes for failure.
2601 xbb_open_file(struct xbb_softc *xbb)
2603 struct xbb_file_data *file_data;
2607 file_data = &xbb->backend.file;
2608 xbb->device_type = XBB_TYPE_FILE;
2609 xbb->dispatch_io = xbb_dispatch_file;
2610 error = VOP_GETATTR(xbb->vn, &vattr, curthread->td_ucred);
2612 xenbus_dev_fatal(xbb->dev, error,
2613 "error calling VOP_GETATTR()"
2614 "for file %s", xbb->dev_name);
2619 * Verify that we have the ability to upgrade to exclusive
2620 * access on this file so we can trap errors at open instead
2621 * of reporting them during first access.
2623 if (VOP_ISLOCKED(xbb->vn) != LK_EXCLUSIVE) {
2624 vn_lock(xbb->vn, LK_UPGRADE | LK_RETRY);
2625 if (xbb->vn->v_iflag & VI_DOOMED) {
2627 xenbus_dev_fatal(xbb->dev, error,
2628 "error locking file %s",
2635 file_data->cred = crhold(curthread->td_ucred);
2636 xbb->media_size = vattr.va_size;
2639 * XXX KDM vattr.va_blocksize may be larger than 512 bytes here.
2640 * With ZFS, it is 131072 bytes. Block sizes that large don't work
2641 * with disklabel and UFS on FreeBSD at least. Large block sizes
2642 * may not work with other OSes as well. So just export a sector
2643 * size of 512 bytes, which should work with any OS or
2644 * application. Since our backing is a file, any block size will
2645 * work fine for the backing store.
2648 xbb->sector_size = vattr.va_blocksize;
2650 xbb->sector_size = 512;
2653 * Sanity check. The media size has to be at least one
2656 if (xbb->media_size < xbb->sector_size) {
2658 xenbus_dev_fatal(xbb->dev, error,
2659 "file %s size %ju < block size %u",
2661 (uintmax_t)xbb->media_size,
2668 * Open the backend provider for this connection.
2670 * \param xbb Per-instance xbb configuration structure.
2672 * \return 0 for success, errno codes for failure.
2675 xbb_open_backend(struct xbb_softc *xbb)
2677 struct nameidata nd;
2684 DPRINTF("opening dev=%s\n", xbb->dev_name);
2686 if (rootvnode == NULL) {
2687 xenbus_dev_fatal(xbb->dev, ENOENT,
2688 "Root file system not mounted");
2692 if ((xbb->flags & XBBF_READ_ONLY) == 0)
2695 if (!curthread->td_proc->p_fd->fd_cdir) {
2696 curthread->td_proc->p_fd->fd_cdir = rootvnode;
2699 if (!curthread->td_proc->p_fd->fd_rdir) {
2700 curthread->td_proc->p_fd->fd_rdir = rootvnode;
2703 if (!curthread->td_proc->p_fd->fd_jdir) {
2704 curthread->td_proc->p_fd->fd_jdir = rootvnode;
2709 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, xbb->dev_name, curthread);
2710 error = vn_open(&nd, &flags, 0, NULL);
2713 * This is the only reasonable guess we can make as far as
2714 * path if the user doesn't give us a fully qualified path.
2715 * If they want to specify a file, they need to specify the
2718 if (xbb->dev_name[0] != '/') {
2719 char *dev_path = "/dev/";
2722 /* Try adding device path at beginning of name */
2723 dev_name = malloc(strlen(xbb->dev_name)
2724 + strlen(dev_path) + 1,
2725 M_XENBLOCKBACK, M_NOWAIT);
2727 sprintf(dev_name, "%s%s", dev_path,
2729 free(xbb->dev_name, M_XENBLOCKBACK);
2730 xbb->dev_name = dev_name;
2734 xenbus_dev_fatal(xbb->dev, error, "error opening device %s",
2739 NDFREE(&nd, NDF_ONLY_PNBUF);
2743 /* We only support disks and files. */
2744 if (vn_isdisk(xbb->vn, &error)) {
2745 error = xbb_open_dev(xbb);
2746 } else if (xbb->vn->v_type == VREG) {
2747 error = xbb_open_file(xbb);
2750 xenbus_dev_fatal(xbb->dev, error, "%s is not a disk "
2751 "or file", xbb->dev_name);
2753 VOP_UNLOCK(xbb->vn, 0);
2756 xbb_close_backend(xbb);
2760 xbb->sector_size_shift = fls(xbb->sector_size) - 1;
2761 xbb->media_num_sectors = xbb->media_size >> xbb->sector_size_shift;
2763 DPRINTF("opened %s=%s sector_size=%u media_size=%" PRId64 "\n",
2764 (xbb->device_type == XBB_TYPE_DISK) ? "dev" : "file",
2765 xbb->dev_name, xbb->sector_size, xbb->media_size);
2770 /*------------------------ Inter-Domain Communication ------------------------*/
2772 * Free dynamically allocated KVA or pseudo-physical address allocations.
2774 * \param xbb Per-instance xbb configuration structure.
2777 xbb_free_communication_mem(struct xbb_softc *xbb)
2779 if (xbb->kva != 0) {
2780 if (xbb->pseudo_phys_res != NULL) {
2781 xenmem_free(xbb->dev, xbb->pseudo_phys_res_id,
2782 xbb->pseudo_phys_res);
2783 xbb->pseudo_phys_res = NULL;
2787 xbb->gnt_base_addr = 0;
2788 if (xbb->kva_free != NULL) {
2789 free(xbb->kva_free, M_XENBLOCKBACK);
2790 xbb->kva_free = NULL;
2795 * Cleanup all inter-domain communication mechanisms.
2797 * \param xbb Per-instance xbb configuration structure.
2800 xbb_disconnect(struct xbb_softc *xbb)
2802 struct gnttab_unmap_grant_ref ops[XBB_MAX_RING_PAGES];
2803 struct gnttab_unmap_grant_ref *op;
2809 if ((xbb->flags & XBBF_RING_CONNECTED) == 0)
2812 xen_intr_unbind(&xbb->xen_intr_handle);
2814 mtx_unlock(&xbb->lock);
2815 taskqueue_drain(xbb->io_taskqueue, &xbb->io_task);
2816 mtx_lock(&xbb->lock);
2819 * No new interrupts can generate work, but we must wait
2820 * for all currently active requests to drain.
2822 if (xbb->active_request_count != 0)
2825 for (ring_idx = 0, op = ops;
2826 ring_idx < xbb->ring_config.ring_pages;
2829 op->host_addr = xbb->ring_config.gnt_addr
2830 + (ring_idx * PAGE_SIZE);
2831 op->dev_bus_addr = xbb->ring_config.bus_addr[ring_idx];
2832 op->handle = xbb->ring_config.handle[ring_idx];
2835 error = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, ops,
2836 xbb->ring_config.ring_pages);
2838 panic("Grant table op failed (%d)", error);
2840 xbb_free_communication_mem(xbb);
2842 if (xbb->requests != NULL) {
2843 free(xbb->requests, M_XENBLOCKBACK);
2844 xbb->requests = NULL;
2847 if (xbb->request_lists != NULL) {
2848 struct xbb_xen_reqlist *reqlist;
2851 /* There is one request list for ever allocated request. */
2852 for (i = 0, reqlist = xbb->request_lists;
2853 i < xbb->max_requests; i++, reqlist++){
2854 #ifdef XBB_USE_BOUNCE_BUFFERS
2855 if (reqlist->bounce != NULL) {
2856 free(reqlist->bounce, M_XENBLOCKBACK);
2857 reqlist->bounce = NULL;
2860 if (reqlist->gnt_handles != NULL) {
2861 free(reqlist->gnt_handles, M_XENBLOCKBACK);
2862 reqlist->gnt_handles = NULL;
2865 free(xbb->request_lists, M_XENBLOCKBACK);
2866 xbb->request_lists = NULL;
2869 xbb->flags &= ~XBBF_RING_CONNECTED;
2874 * Map shared memory ring into domain local address space, initialize
2875 * ring control structures, and bind an interrupt to the event channel
2876 * used to notify us of ring changes.
2878 * \param xbb Per-instance xbb configuration structure.
2881 xbb_connect_ring(struct xbb_softc *xbb)
2883 struct gnttab_map_grant_ref gnts[XBB_MAX_RING_PAGES];
2884 struct gnttab_map_grant_ref *gnt;
2888 if ((xbb->flags & XBBF_RING_CONNECTED) != 0)
2892 * Kva for our ring is at the tail of the region of kva allocated
2893 * by xbb_alloc_communication_mem().
2895 xbb->ring_config.va = xbb->kva
2897 - (xbb->ring_config.ring_pages * PAGE_SIZE));
2898 xbb->ring_config.gnt_addr = xbb->gnt_base_addr
2900 - (xbb->ring_config.ring_pages * PAGE_SIZE));
2902 for (ring_idx = 0, gnt = gnts;
2903 ring_idx < xbb->ring_config.ring_pages;
2904 ring_idx++, gnt++) {
2906 gnt->host_addr = xbb->ring_config.gnt_addr
2907 + (ring_idx * PAGE_SIZE);
2908 gnt->flags = GNTMAP_host_map;
2909 gnt->ref = xbb->ring_config.ring_ref[ring_idx];
2910 gnt->dom = xbb->otherend_id;
2913 error = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, gnts,
2914 xbb->ring_config.ring_pages);
2916 panic("blkback: Ring page grant table op failed (%d)", error);
2918 for (ring_idx = 0, gnt = gnts;
2919 ring_idx < xbb->ring_config.ring_pages;
2920 ring_idx++, gnt++) {
2921 if (gnt->status != 0) {
2922 xbb->ring_config.va = 0;
2923 xenbus_dev_fatal(xbb->dev, EACCES,
2924 "Ring shared page mapping failed. "
2925 "Status %d.", gnt->status);
2928 xbb->ring_config.handle[ring_idx] = gnt->handle;
2929 xbb->ring_config.bus_addr[ring_idx] = gnt->dev_bus_addr;
2932 /* Initialize the ring based on ABI. */
2934 case BLKIF_PROTOCOL_NATIVE:
2936 blkif_sring_t *sring;
2937 sring = (blkif_sring_t *)xbb->ring_config.va;
2938 BACK_RING_INIT(&xbb->rings.native, sring,
2939 xbb->ring_config.ring_pages * PAGE_SIZE);
2942 case BLKIF_PROTOCOL_X86_32:
2944 blkif_x86_32_sring_t *sring_x86_32;
2945 sring_x86_32 = (blkif_x86_32_sring_t *)xbb->ring_config.va;
2946 BACK_RING_INIT(&xbb->rings.x86_32, sring_x86_32,
2947 xbb->ring_config.ring_pages * PAGE_SIZE);
2950 case BLKIF_PROTOCOL_X86_64:
2952 blkif_x86_64_sring_t *sring_x86_64;
2953 sring_x86_64 = (blkif_x86_64_sring_t *)xbb->ring_config.va;
2954 BACK_RING_INIT(&xbb->rings.x86_64, sring_x86_64,
2955 xbb->ring_config.ring_pages * PAGE_SIZE);
2959 panic("Unexpected blkif protocol ABI.");
2962 xbb->flags |= XBBF_RING_CONNECTED;
2964 error = xen_intr_bind_remote_port(xbb->dev,
2966 xbb->ring_config.evtchn,
2968 /*ithread_handler*/NULL,
2970 INTR_TYPE_BIO | INTR_MPSAFE,
2971 &xbb->xen_intr_handle);
2973 (void)xbb_disconnect(xbb);
2974 xenbus_dev_fatal(xbb->dev, error, "binding event channel");
2978 DPRINTF("rings connected!\n");
2983 /* Needed to make bit_alloc() macro work */
2984 #define calloc(count, size) malloc((count)*(size), M_XENBLOCKBACK, \
2988 * Size KVA and pseudo-physical address allocations based on negotiated
2989 * values for the size and number of I/O requests, and the size of our
2990 * communication ring.
2992 * \param xbb Per-instance xbb configuration structure.
2994 * These address spaces are used to dynamically map pages in the
2995 * front-end's domain into our own.
2998 xbb_alloc_communication_mem(struct xbb_softc *xbb)
3000 xbb->reqlist_kva_pages = xbb->max_requests * xbb->max_request_segments;
3001 xbb->reqlist_kva_size = xbb->reqlist_kva_pages * PAGE_SIZE;
3002 xbb->kva_size = xbb->reqlist_kva_size +
3003 (xbb->ring_config.ring_pages * PAGE_SIZE);
3005 xbb->kva_free = bit_alloc(xbb->reqlist_kva_pages);
3006 if (xbb->kva_free == NULL)
3009 DPRINTF("%s: kva_size = %d, reqlist_kva_size = %d\n",
3010 device_get_nameunit(xbb->dev), xbb->kva_size,
3011 xbb->reqlist_kva_size);
3013 * Reserve a range of pseudo physical memory that we can map
3014 * into kva. These pages will only be backed by machine
3015 * pages ("real memory") during the lifetime of front-end requests
3016 * via grant table operations.
3018 xbb->pseudo_phys_res_id = 0;
3019 xbb->pseudo_phys_res = xenmem_alloc(xbb->dev, &xbb->pseudo_phys_res_id,
3021 if (xbb->pseudo_phys_res == NULL) {
3025 xbb->kva = (vm_offset_t)rman_get_virtual(xbb->pseudo_phys_res);
3026 xbb->gnt_base_addr = rman_get_start(xbb->pseudo_phys_res);
3028 DPRINTF("%s: kva: %#jx, gnt_base_addr: %#jx\n",
3029 device_get_nameunit(xbb->dev), (uintmax_t)xbb->kva,
3030 (uintmax_t)xbb->gnt_base_addr);
3035 * Collect front-end information from the XenStore.
3037 * \param xbb Per-instance xbb configuration structure.
3040 xbb_collect_frontend_info(struct xbb_softc *xbb)
3042 char protocol_abi[64];
3043 const char *otherend_path;
3046 u_int ring_page_order;
3049 otherend_path = xenbus_get_otherend_path(xbb->dev);
3052 * Protocol defaults valid even if all negotiation fails.
3054 xbb->ring_config.ring_pages = 1;
3055 xbb->max_request_segments = BLKIF_MAX_SEGMENTS_PER_REQUEST;
3056 xbb->max_request_size = xbb->max_request_segments * PAGE_SIZE;
3059 * Mandatory data (used in all versions of the protocol) first.
3061 error = xs_scanf(XST_NIL, otherend_path,
3062 "event-channel", NULL, "%" PRIu32,
3063 &xbb->ring_config.evtchn);
3065 xenbus_dev_fatal(xbb->dev, error,
3066 "Unable to retrieve event-channel information "
3067 "from frontend %s. Unable to connect.",
3068 xenbus_get_otherend_path(xbb->dev));
3073 * These fields are initialized to legacy protocol defaults
3074 * so we only need to fail if reading the updated value succeeds
3075 * and the new value is outside of its allowed range.
3077 * \note xs_gather() returns on the first encountered error, so
3078 * we must use independant calls in order to guarantee
3079 * we don't miss information in a sparsly populated front-end
3082 * \note xs_scanf() does not update variables for unmatched
3085 ring_page_order = 0;
3086 xbb->max_requests = 32;
3088 (void)xs_scanf(XST_NIL, otherend_path,
3089 "ring-page-order", NULL, "%u",
3091 xbb->ring_config.ring_pages = 1 << ring_page_order;
3092 ring_size = PAGE_SIZE * xbb->ring_config.ring_pages;
3093 xbb->max_requests = BLKIF_MAX_RING_REQUESTS(ring_size);
3095 if (xbb->ring_config.ring_pages > XBB_MAX_RING_PAGES) {
3096 xenbus_dev_fatal(xbb->dev, EINVAL,
3097 "Front-end specified ring-pages of %u "
3098 "exceeds backend limit of %u. "
3099 "Unable to connect.",
3100 xbb->ring_config.ring_pages,
3101 XBB_MAX_RING_PAGES);
3105 if (xbb->ring_config.ring_pages == 1) {
3106 error = xs_gather(XST_NIL, otherend_path,
3107 "ring-ref", "%" PRIu32,
3108 &xbb->ring_config.ring_ref[0],
3111 xenbus_dev_fatal(xbb->dev, error,
3112 "Unable to retrieve ring information "
3113 "from frontend %s. Unable to "
3115 xenbus_get_otherend_path(xbb->dev));
3119 /* Multi-page ring format. */
3120 for (ring_idx = 0; ring_idx < xbb->ring_config.ring_pages;
3122 char ring_ref_name[]= "ring_refXX";
3124 snprintf(ring_ref_name, sizeof(ring_ref_name),
3125 "ring-ref%u", ring_idx);
3126 error = xs_scanf(XST_NIL, otherend_path,
3127 ring_ref_name, NULL, "%" PRIu32,
3128 &xbb->ring_config.ring_ref[ring_idx]);
3130 xenbus_dev_fatal(xbb->dev, error,
3131 "Failed to retriev grant "
3132 "reference for page %u of "
3133 "shared ring. Unable "
3134 "to connect.", ring_idx);
3140 error = xs_gather(XST_NIL, otherend_path,
3141 "protocol", "%63s", protocol_abi,
3144 || !strcmp(protocol_abi, XEN_IO_PROTO_ABI_NATIVE)) {
3146 * Assume native if the frontend has not
3147 * published ABI data or it has published and
3148 * matches our own ABI.
3150 xbb->abi = BLKIF_PROTOCOL_NATIVE;
3151 } else if (!strcmp(protocol_abi, XEN_IO_PROTO_ABI_X86_32)) {
3153 xbb->abi = BLKIF_PROTOCOL_X86_32;
3154 } else if (!strcmp(protocol_abi, XEN_IO_PROTO_ABI_X86_64)) {
3156 xbb->abi = BLKIF_PROTOCOL_X86_64;
3159 xenbus_dev_fatal(xbb->dev, EINVAL,
3160 "Unknown protocol ABI (%s) published by "
3161 "frontend. Unable to connect.", protocol_abi);
3168 * Allocate per-request data structures given request size and number
3169 * information negotiated with the front-end.
3171 * \param xbb Per-instance xbb configuration structure.
3174 xbb_alloc_requests(struct xbb_softc *xbb)
3176 struct xbb_xen_req *req;
3177 struct xbb_xen_req *last_req;
3180 * Allocate request book keeping datastructures.
3182 xbb->requests = malloc(xbb->max_requests * sizeof(*xbb->requests),
3183 M_XENBLOCKBACK, M_NOWAIT|M_ZERO);
3184 if (xbb->requests == NULL) {
3185 xenbus_dev_fatal(xbb->dev, ENOMEM,
3186 "Unable to allocate request structures");
3190 req = xbb->requests;
3191 last_req = &xbb->requests[xbb->max_requests - 1];
3192 STAILQ_INIT(&xbb->request_free_stailq);
3193 while (req <= last_req) {
3194 STAILQ_INSERT_TAIL(&xbb->request_free_stailq, req, links);
3201 xbb_alloc_request_lists(struct xbb_softc *xbb)
3203 struct xbb_xen_reqlist *reqlist;
3207 * If no requests can be merged, we need 1 request list per
3208 * in flight request.
3210 xbb->request_lists = malloc(xbb->max_requests *
3211 sizeof(*xbb->request_lists), M_XENBLOCKBACK, M_NOWAIT|M_ZERO);
3212 if (xbb->request_lists == NULL) {
3213 xenbus_dev_fatal(xbb->dev, ENOMEM,
3214 "Unable to allocate request list structures");
3218 STAILQ_INIT(&xbb->reqlist_free_stailq);
3219 STAILQ_INIT(&xbb->reqlist_pending_stailq);
3220 for (i = 0; i < xbb->max_requests; i++) {
3223 reqlist = &xbb->request_lists[i];
3227 #ifdef XBB_USE_BOUNCE_BUFFERS
3228 reqlist->bounce = malloc(xbb->max_reqlist_size,
3229 M_XENBLOCKBACK, M_NOWAIT);
3230 if (reqlist->bounce == NULL) {
3231 xenbus_dev_fatal(xbb->dev, ENOMEM,
3232 "Unable to allocate request "
3236 #endif /* XBB_USE_BOUNCE_BUFFERS */
3238 reqlist->gnt_handles = malloc(xbb->max_reqlist_segments *
3239 sizeof(*reqlist->gnt_handles),
3240 M_XENBLOCKBACK, M_NOWAIT|M_ZERO);
3241 if (reqlist->gnt_handles == NULL) {
3242 xenbus_dev_fatal(xbb->dev, ENOMEM,
3243 "Unable to allocate request "
3244 "grant references");
3248 for (seg = 0; seg < xbb->max_reqlist_segments; seg++)
3249 reqlist->gnt_handles[seg] = GRANT_REF_INVALID;
3251 STAILQ_INSERT_TAIL(&xbb->reqlist_free_stailq, reqlist, links);
3257 * Supply information about the physical device to the frontend
3260 * \param xbb Per-instance xbb configuration structure.
3263 xbb_publish_backend_info(struct xbb_softc *xbb)
3265 struct xs_transaction xst;
3266 const char *our_path;
3270 our_path = xenbus_get_node(xbb->dev);
3272 error = xs_transaction_start(&xst);
3274 xenbus_dev_fatal(xbb->dev, error,
3275 "Error publishing backend info "
3276 "(start transaction)");
3281 error = xs_printf(xst, our_path, leaf,
3282 "%"PRIu64, xbb->media_num_sectors);
3286 /* XXX Support all VBD attributes here. */
3288 error = xs_printf(xst, our_path, leaf, "%u",
3289 xbb->flags & XBBF_READ_ONLY
3290 ? VDISK_READONLY : 0);
3294 leaf = "sector-size";
3295 error = xs_printf(xst, our_path, leaf, "%u",
3300 error = xs_transaction_end(xst, 0);
3303 } else if (error != EAGAIN) {
3304 xenbus_dev_fatal(xbb->dev, error, "ending transaction");
3309 xenbus_dev_fatal(xbb->dev, error, "writing %s/%s",
3311 xs_transaction_end(xst, 1);
3316 * Connect to our blkfront peer now that it has completed publishing
3317 * its configuration into the XenStore.
3319 * \param xbb Per-instance xbb configuration structure.
3322 xbb_connect(struct xbb_softc *xbb)
3326 if (xenbus_get_state(xbb->dev) == XenbusStateConnected)
3329 if (xbb_collect_frontend_info(xbb) != 0)
3332 xbb->flags &= ~XBBF_SHUTDOWN;
3335 * We limit the maximum number of reqlist segments to the maximum
3336 * number of segments in the ring, or our absolute maximum,
3337 * whichever is smaller.
3339 xbb->max_reqlist_segments = MIN(xbb->max_request_segments *
3340 xbb->max_requests, XBB_MAX_SEGMENTS_PER_REQLIST);
3343 * The maximum size is simply a function of the number of segments
3346 xbb->max_reqlist_size = xbb->max_reqlist_segments * PAGE_SIZE;
3348 /* Allocate resources whose size depends on front-end configuration. */
3349 error = xbb_alloc_communication_mem(xbb);
3351 xenbus_dev_fatal(xbb->dev, error,
3352 "Unable to allocate communication memory");
3356 error = xbb_alloc_requests(xbb);
3358 /* Specific errors are reported by xbb_alloc_requests(). */
3362 error = xbb_alloc_request_lists(xbb);
3364 /* Specific errors are reported by xbb_alloc_request_lists(). */
3369 * Connect communication channel.
3371 error = xbb_connect_ring(xbb);
3373 /* Specific errors are reported by xbb_connect_ring(). */
3377 if (xbb_publish_backend_info(xbb) != 0) {
3379 * If we can't publish our data, we cannot participate
3380 * in this connection, and waiting for a front-end state
3381 * change will not help the situation.
3383 (void)xbb_disconnect(xbb);
3387 /* Ready for I/O. */
3388 xenbus_set_state(xbb->dev, XenbusStateConnected);
3391 /*-------------------------- Device Teardown Support -------------------------*/
3393 * Perform device shutdown functions.
3395 * \param xbb Per-instance xbb configuration structure.
3397 * Mark this instance as shutting down, wait for any active I/O on the
3398 * backend device/file to drain, disconnect from the front-end, and notify
3399 * any waiters (e.g. a thread invoking our detach method) that detach can
3403 xbb_shutdown(struct xbb_softc *xbb)
3405 XenbusState frontState;
3411 * Due to the need to drop our mutex during some
3412 * xenbus operations, it is possible for two threads
3413 * to attempt to close out shutdown processing at
3414 * the same time. Tell the caller that hits this
3415 * race to try back later.
3417 if ((xbb->flags & XBBF_IN_SHUTDOWN) != 0)
3420 xbb->flags |= XBBF_IN_SHUTDOWN;
3421 mtx_unlock(&xbb->lock);
3423 if (xenbus_get_state(xbb->dev) < XenbusStateClosing)
3424 xenbus_set_state(xbb->dev, XenbusStateClosing);
3426 frontState = xenbus_get_otherend_state(xbb->dev);
3427 mtx_lock(&xbb->lock);
3428 xbb->flags &= ~XBBF_IN_SHUTDOWN;
3430 /* The front can submit I/O until entering the closed state. */
3431 if (frontState < XenbusStateClosed)
3436 /* Indicate shutdown is in progress. */
3437 xbb->flags |= XBBF_SHUTDOWN;
3439 /* Disconnect from the front-end. */
3440 error = xbb_disconnect(xbb);
3443 * Requests still outstanding. We'll be called again
3444 * once they complete.
3446 KASSERT(error == EAGAIN,
3447 ("%s: Unexpected xbb_disconnect() failure %d",
3455 /* Indicate to xbb_detach() that is it safe to proceed. */
3462 * Report an attach time error to the console and Xen, and cleanup
3463 * this instance by forcing immediate detach processing.
3465 * \param xbb Per-instance xbb configuration structure.
3466 * \param err Errno describing the error.
3467 * \param fmt Printf style format and arguments
3470 xbb_attach_failed(struct xbb_softc *xbb, int err, const char *fmt, ...)
3476 va_copy(ap_hotplug, ap);
3477 xs_vprintf(XST_NIL, xenbus_get_node(xbb->dev),
3478 "hotplug-error", fmt, ap_hotplug);
3480 xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3481 "hotplug-status", "error");
3483 xenbus_dev_vfatal(xbb->dev, err, fmt, ap);
3486 xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3488 xbb_detach(xbb->dev);
3491 /*---------------------------- NewBus Entrypoints ----------------------------*/
3493 * Inspect a XenBus device and claim it if is of the appropriate type.
3495 * \param dev NewBus device object representing a candidate XenBus device.
3497 * \return 0 for success, errno codes for failure.
3500 xbb_probe(device_t dev)
3503 if (!strcmp(xenbus_get_type(dev), "vbd")) {
3504 device_set_desc(dev, "Backend Virtual Block Device");
3513 * Setup sysctl variables to control various Block Back parameters.
3515 * \param xbb Xen Block Back softc.
3519 xbb_setup_sysctl(struct xbb_softc *xbb)
3521 struct sysctl_ctx_list *sysctl_ctx = NULL;
3522 struct sysctl_oid *sysctl_tree = NULL;
3524 sysctl_ctx = device_get_sysctl_ctx(xbb->dev);
3525 if (sysctl_ctx == NULL)
3528 sysctl_tree = device_get_sysctl_tree(xbb->dev);
3529 if (sysctl_tree == NULL)
3532 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3533 "disable_flush", CTLFLAG_RW, &xbb->disable_flush, 0,
3534 "fake the flush command");
3536 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3537 "flush_interval", CTLFLAG_RW, &xbb->flush_interval, 0,
3538 "send a real flush for N flush requests");
3540 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3541 "no_coalesce_reqs", CTLFLAG_RW, &xbb->no_coalesce_reqs,0,
3542 "Don't coalesce contiguous requests");
3544 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3545 "reqs_received", CTLFLAG_RW, &xbb->reqs_received,
3546 "how many I/O requests we have received");
3548 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3549 "reqs_completed", CTLFLAG_RW, &xbb->reqs_completed,
3550 "how many I/O requests have been completed");
3552 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3553 "reqs_queued_for_completion", CTLFLAG_RW,
3554 &xbb->reqs_queued_for_completion,
3555 "how many I/O requests queued but not yet pushed");
3557 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3558 "reqs_completed_with_error", CTLFLAG_RW,
3559 &xbb->reqs_completed_with_error,
3560 "how many I/O requests completed with error status");
3562 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3563 "forced_dispatch", CTLFLAG_RW, &xbb->forced_dispatch,
3564 "how many I/O dispatches were forced");
3566 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3567 "normal_dispatch", CTLFLAG_RW, &xbb->normal_dispatch,
3568 "how many I/O dispatches were normal");
3570 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3571 "total_dispatch", CTLFLAG_RW, &xbb->total_dispatch,
3572 "total number of I/O dispatches");
3574 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3575 "kva_shortages", CTLFLAG_RW, &xbb->kva_shortages,
3576 "how many times we have run out of KVA");
3578 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3579 "request_shortages", CTLFLAG_RW,
3580 &xbb->request_shortages,
3581 "how many times we have run out of requests");
3583 SYSCTL_ADD_UINT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3584 "max_requests", CTLFLAG_RD, &xbb->max_requests, 0,
3585 "maximum outstanding requests (negotiated)");
3587 SYSCTL_ADD_UINT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3588 "max_request_segments", CTLFLAG_RD,
3589 &xbb->max_request_segments, 0,
3590 "maximum number of pages per requests (negotiated)");
3592 SYSCTL_ADD_UINT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3593 "max_request_size", CTLFLAG_RD,
3594 &xbb->max_request_size, 0,
3595 "maximum size in bytes of a request (negotiated)");
3597 SYSCTL_ADD_UINT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO,
3598 "ring_pages", CTLFLAG_RD,
3599 &xbb->ring_config.ring_pages, 0,
3600 "communication channel pages (negotiated)");
3604 * Attach to a XenBus device that has been claimed by our probe routine.
3606 * \param dev NewBus device object representing this Xen Block Back instance.
3608 * \return 0 for success, errno codes for failure.
3611 xbb_attach(device_t dev)
3613 struct xbb_softc *xbb;
3615 u_int max_ring_page_order;
3617 DPRINTF("Attaching to %s\n", xenbus_get_node(dev));
3620 * Basic initialization.
3621 * After this block it is safe to call xbb_detach()
3622 * to clean up any allocated data for this instance.
3624 xbb = device_get_softc(dev);
3626 xbb->otherend_id = xenbus_get_otherend_id(dev);
3627 TASK_INIT(&xbb->io_task, /*priority*/0, xbb_run_queue, xbb);
3628 mtx_init(&xbb->lock, device_get_nameunit(dev), NULL, MTX_DEF);
3631 * Publish protocol capabilities for consumption by the
3634 error = xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3635 "feature-barrier", "1");
3637 xbb_attach_failed(xbb, error, "writing %s/feature-barrier",
3638 xenbus_get_node(xbb->dev));
3642 error = xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3643 "feature-flush-cache", "1");
3645 xbb_attach_failed(xbb, error, "writing %s/feature-flush-cache",
3646 xenbus_get_node(xbb->dev));
3650 max_ring_page_order = flsl(XBB_MAX_RING_PAGES) - 1;
3651 error = xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3652 "max-ring-page-order", "%u", max_ring_page_order);
3654 xbb_attach_failed(xbb, error, "writing %s/max-ring-page-order",
3655 xenbus_get_node(xbb->dev));
3659 /* Collect physical device information. */
3660 error = xs_gather(XST_NIL, xenbus_get_otherend_path(xbb->dev),
3661 "device-type", NULL, &xbb->dev_type,
3664 xbb->dev_type = NULL;
3666 error = xs_gather(XST_NIL, xenbus_get_node(dev),
3667 "mode", NULL, &xbb->dev_mode,
3668 "params", NULL, &xbb->dev_name,
3671 xbb_attach_failed(xbb, error, "reading backend fields at %s",
3672 xenbus_get_node(dev));
3676 /* Parse fopen style mode flags. */
3677 if (strchr(xbb->dev_mode, 'w') == NULL)
3678 xbb->flags |= XBBF_READ_ONLY;
3681 * Verify the physical device is present and can support
3682 * the desired I/O mode.
3685 error = xbb_open_backend(xbb);
3688 xbb_attach_failed(xbb, error, "Unable to open %s",
3693 /* Use devstat(9) for recording statistics. */
3694 xbb->xbb_stats = devstat_new_entry("xbb", device_get_unit(xbb->dev),
3696 DEVSTAT_ALL_SUPPORTED,
3698 | DEVSTAT_TYPE_IF_OTHER,
3699 DEVSTAT_PRIORITY_OTHER);
3701 xbb->xbb_stats_in = devstat_new_entry("xbbi", device_get_unit(xbb->dev),
3703 DEVSTAT_ALL_SUPPORTED,
3705 | DEVSTAT_TYPE_IF_OTHER,
3706 DEVSTAT_PRIORITY_OTHER);
3708 * Setup sysctl variables.
3710 xbb_setup_sysctl(xbb);
3713 * Create a taskqueue for doing work that must occur from a
3716 xbb->io_taskqueue = taskqueue_create_fast(device_get_nameunit(dev),
3718 taskqueue_thread_enqueue,
3719 /*contxt*/&xbb->io_taskqueue);
3720 if (xbb->io_taskqueue == NULL) {
3721 xbb_attach_failed(xbb, error, "Unable to create taskqueue");
3725 taskqueue_start_threads(&xbb->io_taskqueue,
3729 "%s taskq", device_get_nameunit(dev));
3731 /* Update hot-plug status to satisfy xend. */
3732 error = xs_printf(XST_NIL, xenbus_get_node(xbb->dev),
3733 "hotplug-status", "connected");
3735 xbb_attach_failed(xbb, error, "writing %s/hotplug-status",
3736 xenbus_get_node(xbb->dev));
3740 /* Tell the front end that we are ready to connect. */
3741 xenbus_set_state(dev, XenbusStateInitWait);
3747 * Detach from a block back device instance.
3749 * \param dev NewBus device object representing this Xen Block Back instance.
3751 * \return 0 for success, errno codes for failure.
3753 * \note A block back device may be detached at any time in its life-cycle,
3754 * including part way through the attach process. For this reason,
3755 * initialization order and the intialization state checks in this
3756 * routine must be carefully coupled so that attach time failures
3757 * are gracefully handled.
3760 xbb_detach(device_t dev)
3762 struct xbb_softc *xbb;
3766 xbb = device_get_softc(dev);
3767 mtx_lock(&xbb->lock);
3768 while (xbb_shutdown(xbb) == EAGAIN) {
3769 msleep(xbb, &xbb->lock, /*wakeup prio unchanged*/0,
3772 mtx_unlock(&xbb->lock);
3776 if (xbb->io_taskqueue != NULL)
3777 taskqueue_free(xbb->io_taskqueue);
3779 if (xbb->xbb_stats != NULL)
3780 devstat_remove_entry(xbb->xbb_stats);
3782 if (xbb->xbb_stats_in != NULL)
3783 devstat_remove_entry(xbb->xbb_stats_in);
3785 xbb_close_backend(xbb);
3787 if (xbb->dev_mode != NULL) {
3788 free(xbb->dev_mode, M_XENSTORE);
3789 xbb->dev_mode = NULL;
3792 if (xbb->dev_type != NULL) {
3793 free(xbb->dev_type, M_XENSTORE);
3794 xbb->dev_type = NULL;
3797 if (xbb->dev_name != NULL) {
3798 free(xbb->dev_name, M_XENSTORE);
3799 xbb->dev_name = NULL;
3802 mtx_destroy(&xbb->lock);
3807 * Prepare this block back device for suspension of this VM.
3809 * \param dev NewBus device object representing this Xen Block Back instance.
3811 * \return 0 for success, errno codes for failure.
3814 xbb_suspend(device_t dev)
3817 struct xbb_softc *sc = device_get_softc(dev);
3819 /* Prevent new requests being issued until we fix things up. */
3820 mtx_lock(&sc->xb_io_lock);
3821 sc->connected = BLKIF_STATE_SUSPENDED;
3822 mtx_unlock(&sc->xb_io_lock);
3829 * Perform any processing required to recover from a suspended state.
3831 * \param dev NewBus device object representing this Xen Block Back instance.
3833 * \return 0 for success, errno codes for failure.
3836 xbb_resume(device_t dev)
3842 * Handle state changes expressed via the XenStore by our front-end peer.
3844 * \param dev NewBus device object representing this Xen
3845 * Block Back instance.
3846 * \param frontend_state The new state of the front-end.
3848 * \return 0 for success, errno codes for failure.
3851 xbb_frontend_changed(device_t dev, XenbusState frontend_state)
3853 struct xbb_softc *xbb = device_get_softc(dev);
3855 DPRINTF("frontend_state=%s, xbb_state=%s\n",
3856 xenbus_strstate(frontend_state),
3857 xenbus_strstate(xenbus_get_state(xbb->dev)));
3859 switch (frontend_state) {
3860 case XenbusStateInitialising:
3862 case XenbusStateInitialised:
3863 case XenbusStateConnected:
3866 case XenbusStateClosing:
3867 case XenbusStateClosed:
3868 mtx_lock(&xbb->lock);
3870 mtx_unlock(&xbb->lock);
3871 if (frontend_state == XenbusStateClosed)
3872 xenbus_set_state(xbb->dev, XenbusStateClosed);
3875 xenbus_dev_fatal(xbb->dev, EINVAL, "saw state %d at frontend",
3881 /*---------------------------- NewBus Registration ---------------------------*/
3882 static device_method_t xbb_methods[] = {
3883 /* Device interface */
3884 DEVMETHOD(device_probe, xbb_probe),
3885 DEVMETHOD(device_attach, xbb_attach),
3886 DEVMETHOD(device_detach, xbb_detach),
3887 DEVMETHOD(device_shutdown, bus_generic_shutdown),
3888 DEVMETHOD(device_suspend, xbb_suspend),
3889 DEVMETHOD(device_resume, xbb_resume),
3891 /* Xenbus interface */
3892 DEVMETHOD(xenbus_otherend_changed, xbb_frontend_changed),
3897 static driver_t xbb_driver = {
3900 sizeof(struct xbb_softc),
3902 devclass_t xbb_devclass;
3904 DRIVER_MODULE(xbbd, xenbusb_back, xbb_driver, xbb_devclass, 0, 0);