]> git.proxmox.com Git - mirror_edk2.git/commitdiff
OvmfPkg/XenPvBlkDxe: Add BlockFront client.
authorSamuel Thibault <samuel.thibault@eu.citrix.com>
Wed, 29 Oct 2014 06:51:58 +0000 (06:51 +0000)
committerjljusten <jljusten@Edk2>
Wed, 29 Oct 2014 06:51:58 +0000 (06:51 +0000)
This is the code that will do the actual communication between OVMF and
a PV block backend, where the block device lives. The protocol used is
describe in the blkif.h header.

This implementation originally comes from Mini-OS, a part of the Xen
Project.

Change in V4:
- add file header to BlockFront.h (license, copyright, brief desc)

Change in V3:
- Improve comment of XenBusReadUint64.
- Moving blkif.h to this patch
  with the necessary #pragma pack(4) applied for Ia32.
- Add a note about the license in the commit message
- Add "The protocol used is describe in the blkif.h header." in the
  commit message
- Have a mandatory sector-size multiple of 512 or fail to initialize.
- use Sector instead of Offset for IO request.
  with Sector been 512-byte unit.
- print something if EventChannelNotify return an error.

Change in V2:
- trigger CoW is probably not needed on OVMF (as opposed to Mini-OS),
  removed the test.
- comments
- renamed XenbusReadInteger to XenBusReadUint64
- remove callback from IoData, use simple status instead
- return a status from the synchronus io
- Close protocol if blockfront init fail.
- fix few debug print
- Rename XenbusIo to XenBusIo
- XenPvBlkWaitForBackendState will return an error if the new backend
  states is not the expected state.
- Add the license

License: This patch adds some files which are under the MIT license.
Signed-off-by: Samuel Thibault <samuel.thibault@eu.citrix.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Anthony PERARD <anthony.perard@citrix.com>
Acked-by: Jordan Justen <jordan.l.justen@intel.com>
git-svn-id: https://svn.code.sf.net/p/edk2/code/trunk/edk2@16273 6f19259b-4bc3-4df7-8a09-765794883524

OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h [new file with mode: 0644]
OvmfPkg/XenPvBlkDxe/BlockFront.c [new file with mode: 0644]
OvmfPkg/XenPvBlkDxe/BlockFront.h [new file with mode: 0644]
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf

diff --git a/OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h b/OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h
new file mode 100644 (file)
index 0000000..5130e3a
--- /dev/null
@@ -0,0 +1,619 @@
+/******************************************************************************\r
+ * blkif.h\r
+ *\r
+ * Unified block-device I/O interface for Xen guest OSes.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a copy\r
+ * of this software and associated documentation files (the "Software"), to\r
+ * deal in the Software without restriction, including without limitation the\r
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\r
+ * sell copies of the Software, and to permit persons to whom the Software is\r
+ * furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in\r
+ * all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+ * DEALINGS IN THE SOFTWARE.\r
+ *\r
+ * Copyright (c) 2003-2004, Keir Fraser\r
+ * Copyright (c) 2012, Spectra Logic Corporation\r
+ */\r
+\r
+#ifndef __XEN_PUBLIC_IO_BLKIF_H__\r
+#define __XEN_PUBLIC_IO_BLKIF_H__\r
+\r
+#include "ring.h"\r
+#include "../grant_table.h"\r
+\r
+/*\r
+ * Front->back notifications: When enqueuing a new request, sending a\r
+ * notification can be made conditional on req_event (i.e., the generic\r
+ * hold-off mechanism provided by the ring macros). Backends must set\r
+ * req_event appropriately (e.g., using RING_FINAL_CHECK_FOR_REQUESTS()).\r
+ *\r
+ * Back->front notifications: When enqueuing a new response, sending a\r
+ * notification can be made conditional on rsp_event (i.e., the generic\r
+ * hold-off mechanism provided by the ring macros). Frontends must set\r
+ * rsp_event appropriately (e.g., using RING_FINAL_CHECK_FOR_RESPONSES()).\r
+ */\r
+\r
+#ifndef blkif_vdev_t\r
+#define blkif_vdev_t   UINT16\r
+#endif\r
+#define blkif_sector_t UINT64\r
+\r
+/*\r
+ * Feature and Parameter Negotiation\r
+ * =================================\r
+ * The two halves of a Xen block driver utilize nodes within the XenStore to\r
+ * communicate capabilities and to negotiate operating parameters.  This\r
+ * section enumerates these nodes which reside in the respective front and\r
+ * backend portions of the XenStore, following the XenBus convention.\r
+ *\r
+ * All data in the XenStore is stored as strings.  Nodes specifying numeric\r
+ * values are encoded in decimal.  Integer value ranges listed below are\r
+ * expressed as fixed sized integer types capable of storing the conversion\r
+ * of a properly formated node string, without loss of information.\r
+ *\r
+ * Any specified default value is in effect if the corresponding XenBus node\r
+ * is not present in the XenStore.\r
+ *\r
+ * XenStore nodes in sections marked "PRIVATE" are solely for use by the\r
+ * driver side whose XenBus tree contains them.\r
+ *\r
+ * XenStore nodes marked "DEPRECATED" in their notes section should only be\r
+ * used to provide interoperability with legacy implementations.\r
+ *\r
+ * See the XenBus state transition diagram below for details on when XenBus\r
+ * nodes must be published and when they can be queried.\r
+ *\r
+ *****************************************************************************\r
+ *                            Backend XenBus Nodes\r
+ *****************************************************************************\r
+ *\r
+ *------------------ Backend Device Identification (PRIVATE) ------------------\r
+ *\r
+ * mode\r
+ *      Values:         "r" (read only), "w" (writable)\r
+ *\r
+ *      The read or write access permissions to the backing store to be\r
+ *      granted to the frontend.\r
+ *\r
+ * params\r
+ *      Values:         string\r
+ *\r
+ *      A free formatted string providing sufficient information for the\r
+ *      backend driver to open the backing device.  (e.g. the path to the\r
+ *      file or block device representing the backing store.)\r
+ *\r
+ * type\r
+ *      Values:         "file", "phy", "tap"\r
+ *\r
+ *      The type of the backing device/object.\r
+ *\r
+ *--------------------------------- Features ---------------------------------\r
+ *\r
+ * feature-barrier\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *\r
+ *      A value of "1" indicates that the backend can process requests\r
+ *      containing the BLKIF_OP_WRITE_BARRIER request opcode.  Requests\r
+ *      of this type may still be returned at any time with the\r
+ *      BLKIF_RSP_EOPNOTSUPP result code.\r
+ *\r
+ * feature-flush-cache\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *\r
+ *      A value of "1" indicates that the backend can process requests\r
+ *      containing the BLKIF_OP_FLUSH_DISKCACHE request opcode.  Requests\r
+ *      of this type may still be returned at any time with the\r
+ *      BLKIF_RSP_EOPNOTSUPP result code.\r
+ *\r
+ * feature-discard\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *\r
+ *      A value of "1" indicates that the backend can process requests\r
+ *      containing the BLKIF_OP_DISCARD request opcode.  Requests\r
+ *      of this type may still be returned at any time with the\r
+ *      BLKIF_RSP_EOPNOTSUPP result code.\r
+ *\r
+ * feature-persistent\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *      Notes: 7\r
+ *\r
+ *      A value of "1" indicates that the backend can keep the grants used\r
+ *      by the frontend driver mapped, so the same set of grants should be\r
+ *      used in all transactions. The maximum number of grants the backend\r
+ *      can map persistently depends on the implementation, but ideally it\r
+ *      should be RING_SIZE * BLKIF_MAX_SEGMENTS_PER_REQUEST. Using this\r
+ *      feature the backend doesn't need to unmap each grant, preventing\r
+ *      costly TLB flushes. The backend driver should only map grants\r
+ *      persistently if the frontend supports it. If a backend driver chooses\r
+ *      to use the persistent protocol when the frontend doesn't support it,\r
+ *      it will probably hit the maximum number of persistently mapped grants\r
+ *      (due to the fact that the frontend won't be reusing the same grants),\r
+ *      and fall back to non-persistent mode. Backend implementations may\r
+ *      shrink or expand the number of persistently mapped grants without\r
+ *      notifying the frontend depending on memory constraints (this might\r
+ *      cause a performance degradation).\r
+ *\r
+ *      If a backend driver wants to limit the maximum number of persistently\r
+ *      mapped grants to a value less than RING_SIZE *\r
+ *      BLKIF_MAX_SEGMENTS_PER_REQUEST a LRU strategy should be used to\r
+ *      discard the grants that are less commonly used. Using a LRU in the\r
+ *      backend driver paired with a LIFO queue in the frontend will\r
+ *      allow us to have better performance in this scenario.\r
+ *\r
+ *----------------------- Request Transport Parameters ------------------------\r
+ *\r
+ * max-ring-page-order\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  0\r
+ *      Notes:          1, 3\r
+ *\r
+ *      The maximum supported size of the request ring buffer in units of\r
+ *      lb(machine pages). (e.g. 0 == 1 page,  1 = 2 pages, 2 == 4 pages,\r
+ *      etc.).\r
+ *\r
+ * max-ring-pages\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  1\r
+ *      Notes:          DEPRECATED, 2, 3\r
+ *\r
+ *      The maximum supported size of the request ring buffer in units of\r
+ *      machine pages.  The value must be a power of 2.\r
+ *\r
+ *------------------------- Backend Device Properties -------------------------\r
+ *\r
+ * discard-alignment\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  0\r
+ *      Notes:          4, 5\r
+ *\r
+ *      The offset, in bytes from the beginning of the virtual block device,\r
+ *      to the first, addressable, discard extent on the underlying device.\r
+ *\r
+ * discard-granularity\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  <"sector-size">\r
+ *      Notes:          4\r
+ *\r
+ *      The size, in bytes, of the individually addressable discard extents\r
+ *      of the underlying device.\r
+ *\r
+ * discard-secure\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *      Notes:          10\r
+ *\r
+ *      A value of "1" indicates that the backend can process BLKIF_OP_DISCARD\r
+ *      requests with the BLKIF_DISCARD_SECURE flag set.\r
+ *\r
+ * info\r
+ *      Values:         <UINT32> (bitmap)\r
+ *\r
+ *      A collection of bit flags describing attributes of the backing\r
+ *      device.  The VDISK_* macros define the meaning of each bit\r
+ *      location.\r
+ *\r
+ * sector-size\r
+ *      Values:         <UINT32>\r
+ *\r
+ *      The logical sector size, in bytes, of the backend device.\r
+ *\r
+ * physical-sector-size\r
+ *      Values:         <UINT32>\r
+ *\r
+ *      The physical sector size, in bytes, of the backend device.\r
+ *\r
+ * sectors\r
+ *      Values:         <UINT64>\r
+ *\r
+ *      The size of the backend device, expressed in units of its logical\r
+ *      sector size ("sector-size").\r
+ *\r
+ *****************************************************************************\r
+ *                            Frontend XenBus Nodes\r
+ *****************************************************************************\r
+ *\r
+ *----------------------- Request Transport Parameters -----------------------\r
+ *\r
+ * event-channel\r
+ *      Values:         <UINT32>\r
+ *\r
+ *      The identifier of the Xen event channel used to signal activity\r
+ *      in the ring buffer.\r
+ *\r
+ * ring-ref\r
+ *      Values:         <UINT32>\r
+ *      Notes:          6\r
+ *\r
+ *      The Xen grant reference granting permission for the backend to map\r
+ *      the sole page in a single page sized ring buffer.\r
+ *\r
+ * ring-ref%u\r
+ *      Values:         <UINT32>\r
+ *      Notes:          6\r
+ *\r
+ *      For a frontend providing a multi-page ring, a "number of ring pages"\r
+ *      sized list of nodes, each containing a Xen grant reference granting\r
+ *      permission for the backend to map the page of the ring located\r
+ *      at page index "%u".  Page indexes are zero based.\r
+ *\r
+ * protocol\r
+ *      Values:         string (XEN_IO_PROTO_ABI_*)\r
+ *      Default Value:  XEN_IO_PROTO_ABI_NATIVE\r
+ *\r
+ *      The machine ABI rules governing the format of all ring request and\r
+ *      response structures.\r
+ *\r
+ * ring-page-order\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  0\r
+ *      Maximum Value:  MAX(ffs(max-ring-pages) - 1, max-ring-page-order)\r
+ *      Notes:          1, 3\r
+ *\r
+ *      The size of the frontend allocated request ring buffer in units\r
+ *      of lb(machine pages). (e.g. 0 == 1 page, 1 = 2 pages, 2 == 4 pages,\r
+ *      etc.).\r
+ *\r
+ * num-ring-pages\r
+ *      Values:         <UINT32>\r
+ *      Default Value:  1\r
+ *      Maximum Value:  MAX(max-ring-pages,(0x1 << max-ring-page-order))\r
+ *      Notes:          DEPRECATED, 2, 3\r
+ *\r
+ *      The size of the frontend allocated request ring buffer in units of\r
+ *      machine pages.  The value must be a power of 2.\r
+ *\r
+ * feature-persistent\r
+ *      Values:         0/1 (boolean)\r
+ *      Default Value:  0\r
+ *      Notes: 7, 8, 9\r
+ *\r
+ *      A value of "1" indicates that the frontend will reuse the same grants\r
+ *      for all transactions, allowing the backend to map them with write\r
+ *      access (even when it should be read-only). If the frontend hits the\r
+ *      maximum number of allowed persistently mapped grants, it can fallback\r
+ *      to non persistent mode. This will cause a performance degradation,\r
+ *      since the the backend driver will still try to map those grants\r
+ *      persistently. Since the persistent grants protocol is compatible with\r
+ *      the previous protocol, a frontend driver can choose to work in\r
+ *      persistent mode even when the backend doesn't support it.\r
+ *\r
+ *      It is recommended that the frontend driver stores the persistently\r
+ *      mapped grants in a LIFO queue, so a subset of all persistently mapped\r
+ *      grants gets used commonly. This is done in case the backend driver\r
+ *      decides to limit the maximum number of persistently mapped grants\r
+ *      to a value less than RING_SIZE * BLKIF_MAX_SEGMENTS_PER_REQUEST.\r
+ *\r
+ *------------------------- Virtual Device Properties -------------------------\r
+ *\r
+ * device-type\r
+ *      Values:         "disk", "cdrom", "floppy", etc.\r
+ *\r
+ * virtual-device\r
+ *      Values:         <UINT32>\r
+ *\r
+ *      A value indicating the physical device to virtualize within the\r
+ *      frontend's domain.  (e.g. "The first ATA disk", "The third SCSI\r
+ *      disk", etc.)\r
+ *\r
+ *      See docs/misc/vbd-interface.txt for details on the format of this\r
+ *      value.\r
+ *\r
+ * Notes\r
+ * -----\r
+ * (1) Multi-page ring buffer scheme first developed in the Citrix XenServer\r
+ *     PV drivers.\r
+ * (2) Multi-page ring buffer scheme first used in some RedHat distributions\r
+ *     including a distribution deployed on certain nodes of the Amazon\r
+ *     EC2 cluster.\r
+ * (3) Support for multi-page ring buffers was implemented independently,\r
+ *     in slightly different forms, by both Citrix and RedHat/Amazon.\r
+ *     For full interoperability, block front and backends should publish\r
+ *     identical ring parameters, adjusted for unit differences, to the\r
+ *     XenStore nodes used in both schemes.\r
+ * (4) Devices that support discard functionality may internally allocate space\r
+ *     (discardable extents) in units that are larger than the exported logical\r
+ *     block size. If the backing device has such discardable extents the\r
+ *     backend should provide both discard-granularity and discard-alignment.\r
+ *     Providing just one of the two may be considered an error by the frontend.\r
+ *     Backends supporting discard should include discard-granularity and\r
+ *     discard-alignment even if it supports discarding individual sectors.\r
+ *     Frontends should assume discard-alignment == 0 and discard-granularity\r
+ *     == sector size if these keys are missing.\r
+ * (5) The discard-alignment parameter allows a physical device to be\r
+ *     partitioned into virtual devices that do not necessarily begin or\r
+ *     end on a discardable extent boundary.\r
+ * (6) When there is only a single page allocated to the request ring,\r
+ *     'ring-ref' is used to communicate the grant reference for this\r
+ *     page to the backend.  When using a multi-page ring, the 'ring-ref'\r
+ *     node is not created.  Instead 'ring-ref0' - 'ring-refN' are used.\r
+ * (7) When using persistent grants data has to be copied from/to the page\r
+ *     where the grant is currently mapped. The overhead of doing this copy\r
+ *     however doesn't suppress the speed improvement of not having to unmap\r
+ *     the grants.\r
+ * (8) The frontend driver has to allow the backend driver to map all grants\r
+ *     with write access, even when they should be mapped read-only, since\r
+ *     further requests may reuse these grants and require write permissions.\r
+ * (9) Linux implementation doesn't have a limit on the maximum number of\r
+ *     grants that can be persistently mapped in the frontend driver, but\r
+ *     due to the frontent driver implementation it should never be bigger\r
+ *     than RING_SIZE * BLKIF_MAX_SEGMENTS_PER_REQUEST.\r
+ *(10) The discard-secure property may be present and will be set to 1 if the\r
+ *     backing device supports secure discard.\r
+ */\r
+\r
+/*\r
+ * STATE DIAGRAMS\r
+ *\r
+ *****************************************************************************\r
+ *                                   Startup                                 *\r
+ *****************************************************************************\r
+ *\r
+ * Tool stack creates front and back nodes with state XenbusStateInitialising.\r
+ *\r
+ * Front                                Back\r
+ * =================================    =====================================\r
+ * XenbusStateInitialising              XenbusStateInitialising\r
+ *  o Query virtual device               o Query backend device identification\r
+ *    properties.                          data.\r
+ *  o Setup OS device instance.          o Open and validate backend device.\r
+ *                                       o Publish backend features and\r
+ *                                         transport parameters.\r
+ *                                                      |\r
+ *                                                      |\r
+ *                                                      V\r
+ *                                      XenbusStateInitWait\r
+ *\r
+ * o Query backend features and\r
+ *   transport parameters.\r
+ * o Allocate and initialize the\r
+ *   request ring.\r
+ * o Publish transport parameters\r
+ *   that will be in effect during\r
+ *   this connection.\r
+ *              |\r
+ *              |\r
+ *              V\r
+ * XenbusStateInitialised\r
+ *\r
+ *                                       o Query frontend transport parameters.\r
+ *                                       o Connect to the request ring and\r
+ *                                         event channel.\r
+ *                                       o Publish backend device properties.\r
+ *                                                      |\r
+ *                                                      |\r
+ *                                                      V\r
+ *                                      XenbusStateConnected\r
+ *\r
+ *  o Query backend device properties.\r
+ *  o Finalize OS virtual device\r
+ *    instance.\r
+ *              |\r
+ *              |\r
+ *              V\r
+ * XenbusStateConnected\r
+ *\r
+ * Note: Drivers that do not support any optional features, or the negotiation\r
+ *       of transport parameters, can skip certain states in the state machine:\r
+ *\r
+ *       o A frontend may transition to XenbusStateInitialised without\r
+ *         waiting for the backend to enter XenbusStateInitWait.  In this\r
+ *         case, default transport parameters are in effect and any\r
+ *         transport parameters published by the frontend must contain\r
+ *         their default values.\r
+ *\r
+ *       o A backend may transition to XenbusStateInitialised, bypassing\r
+ *         XenbusStateInitWait, without waiting for the frontend to first\r
+ *         enter the XenbusStateInitialised state.  In this case, default\r
+ *         transport parameters are in effect and any transport parameters\r
+ *         published by the backend must contain their default values.\r
+ *\r
+ *       Drivers that support optional features and/or transport parameter\r
+ *       negotiation must tolerate these additional state transition paths.\r
+ *       In general this means performing the work of any skipped state\r
+ *       transition, if it has not already been performed, in addition to the\r
+ *       work associated with entry into the current state.\r
+ */\r
+\r
+/*\r
+ * REQUEST CODES.\r
+ */\r
+#define BLKIF_OP_READ              0\r
+#define BLKIF_OP_WRITE             1\r
+/*\r
+ * All writes issued prior to a request with the BLKIF_OP_WRITE_BARRIER\r
+ * operation code ("barrier request") must be completed prior to the\r
+ * execution of the barrier request.  All writes issued after the barrier\r
+ * request must not execute until after the completion of the barrier request.\r
+ *\r
+ * Optional.  See "feature-barrier" XenBus node documentation above.\r
+ */\r
+#define BLKIF_OP_WRITE_BARRIER     2\r
+/*\r
+ * Commit any uncommitted contents of the backing device's volatile cache\r
+ * to stable storage.\r
+ *\r
+ * Optional.  See "feature-flush-cache" XenBus node documentation above.\r
+ */\r
+#define BLKIF_OP_FLUSH_DISKCACHE   3\r
+/*\r
+ * Used in SLES sources for device specific command packet\r
+ * contained within the request. Reserved for that purpose.\r
+ */\r
+#define BLKIF_OP_RESERVED_1        4\r
+/*\r
+ * Indicate to the backend device that a region of storage is no longer in\r
+ * use, and may be discarded at any time without impact to the client.  If\r
+ * the BLKIF_DISCARD_SECURE flag is set on the request, all copies of the\r
+ * discarded region on the device must be rendered unrecoverable before the\r
+ * command returns.\r
+ *\r
+ * This operation is analogous to performing a trim (ATA) or unamp (SCSI),\r
+ * command on a native device.\r
+ *\r
+ * More information about trim/unmap operations can be found at:\r
+ * http://t13.org/Documents/UploadedDocuments/docs2008/\r
+ *     e07154r6-Data_Set_Management_Proposal_for_ATA-ACS2.doc\r
+ * http://www.seagate.com/staticfiles/support/disc/manuals/\r
+ *     Interface%20manuals/100293068c.pdf\r
+ *\r
+ * Optional.  See "feature-discard", "discard-alignment",\r
+ * "discard-granularity", and "discard-secure" in the XenBus node\r
+ * documentation above.\r
+ */\r
+#define BLKIF_OP_DISCARD           5\r
+\r
+/*\r
+ * Recognized if "feature-max-indirect-segments" in present in the backend\r
+ * xenbus info. The "feature-max-indirect-segments" node contains the maximum\r
+ * number of segments allowed by the backend per request. If the node is\r
+ * present, the frontend might use blkif_request_indirect structs in order to\r
+ * issue requests with more than BLKIF_MAX_SEGMENTS_PER_REQUEST (11). The\r
+ * maximum number of indirect segments is fixed by the backend, but the\r
+ * frontend can issue requests with any number of indirect segments as long as\r
+ * it's less than the number provided by the backend. The indirect_grefs field\r
+ * in blkif_request_indirect should be filled by the frontend with the\r
+ * grant references of the pages that are holding the indirect segments.\r
+ * These pages are filled with an array of blkif_request_segment that hold the\r
+ * information about the segments. The number of indirect pages to use is\r
+ * determined by the number of segments an indirect request contains. Every\r
+ * indirect page can contain a maximum of\r
+ * (PAGE_SIZE / sizeof(struct blkif_request_segment)) segments, so to\r
+ * calculate the number of indirect pages to use we have to do\r
+ * ceil(indirect_segments / (PAGE_SIZE / sizeof(struct blkif_request_segment))).\r
+ *\r
+ * If a backend does not recognize BLKIF_OP_INDIRECT, it should *not*\r
+ * create the "feature-max-indirect-segments" node!\r
+ */\r
+#define BLKIF_OP_INDIRECT          6\r
+\r
+/*\r
+ * Maximum scatter/gather segments per request.\r
+ * This is carefully chosen so that sizeof(blkif_ring_t) <= PAGE_SIZE.\r
+ * NB. This could be 12 if the ring indexes weren't stored in the same page.\r
+ */\r
+#define BLKIF_MAX_SEGMENTS_PER_REQUEST 11\r
+\r
+/*\r
+ * Maximum number of indirect pages to use per request.\r
+ */\r
+#define BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST 8\r
+\r
+/*\r
+ * NB. first_sect and last_sect in blkif_request_segment, as well as\r
+ * sector_number in blkif_request, are always expressed in 512-byte units.\r
+ * However they must be properly aligned to the real sector size of the\r
+ * physical disk, which is reported in the "physical-sector-size" node in\r
+ * the backend xenbus info. Also the xenbus "sectors" node is expressed in\r
+ * 512-byte units.\r
+ */\r
+struct blkif_request_segment {\r
+    grant_ref_t gref;        /* reference to I/O buffer frame        */\r
+    /* @first_sect: first sector in frame to transfer (inclusive).   */\r
+    /* @last_sect: last sector in frame to transfer (inclusive).     */\r
+    UINT8     first_sect, last_sect;\r
+};\r
+\r
+/*\r
+ * Starting ring element for any I/O request.\r
+ */\r
+#if defined(__i386__)\r
+//\r
+// pack(4) is necessary when these structs are compiled for Ia32.\r
+// Without it, the struct will have a different alignment than the one\r
+// a backend expect for a 32bit guest.\r
+//\r
+#pragma pack(4)\r
+#endif\r
+struct blkif_request {\r
+    UINT8        operation;    /* BLKIF_OP_???                         */\r
+    UINT8        nr_segments;  /* number of segments                   */\r
+    blkif_vdev_t   handle;       /* only for read/write requests         */\r
+    UINT64       id;           /* private guest value, echoed in resp  */\r
+    blkif_sector_t sector_number;/* start sector idx on disk (r/w only)  */\r
+    struct blkif_request_segment seg[BLKIF_MAX_SEGMENTS_PER_REQUEST];\r
+};\r
+typedef struct blkif_request blkif_request_t;\r
+\r
+/*\r
+ * Cast to this structure when blkif_request.operation == BLKIF_OP_DISCARD\r
+ * sizeof(struct blkif_request_discard) <= sizeof(struct blkif_request)\r
+ */\r
+struct blkif_request_discard {\r
+    UINT8        operation;    /* BLKIF_OP_DISCARD                     */\r
+    UINT8        flag;         /* BLKIF_DISCARD_SECURE or zero         */\r
+#define BLKIF_DISCARD_SECURE (1<<0)  /* ignored if discard-secure=0      */\r
+    blkif_vdev_t   handle;       /* same as for read/write requests      */\r
+    UINT64       id;           /* private guest value, echoed in resp  */\r
+    blkif_sector_t sector_number;/* start sector idx on disk             */\r
+    UINT64       nr_sectors;   /* number of contiguous sectors to discard*/\r
+};\r
+typedef struct blkif_request_discard blkif_request_discard_t;\r
+\r
+struct blkif_request_indirect {\r
+    UINT8        operation;    /* BLKIF_OP_INDIRECT                    */\r
+    UINT8        indirect_op;  /* BLKIF_OP_{READ/WRITE}                */\r
+    UINT16       nr_segments;  /* number of segments                   */\r
+    UINT64       id;           /* private guest value, echoed in resp  */\r
+    blkif_sector_t sector_number;/* start sector idx on disk (r/w only)  */\r
+    blkif_vdev_t   handle;       /* same as for read/write requests      */\r
+    grant_ref_t    indirect_grefs[BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST];\r
+#ifdef __i386__\r
+    UINT64       pad;          /* Make it 64 byte aligned on i386      */\r
+#endif\r
+};\r
+typedef struct blkif_request_indirect blkif_request_indirect_t;\r
+\r
+struct blkif_response {\r
+    UINT64        id;              /* copied from request */\r
+    UINT8         operation;       /* copied from request */\r
+    INT16         status;          /* BLKIF_RSP_???       */\r
+};\r
+typedef struct blkif_response blkif_response_t;\r
+#if defined(__i386__)\r
+#pragma pack()\r
+#endif\r
+\r
+/*\r
+ * STATUS RETURN CODES.\r
+ */\r
+ /* Operation not supported (only happens on barrier writes). */\r
+#define BLKIF_RSP_EOPNOTSUPP  -2\r
+ /* Operation failed for some unspecified reason (-EIO). */\r
+#define BLKIF_RSP_ERROR       -1\r
+ /* Operation completed successfully. */\r
+#define BLKIF_RSP_OKAY         0\r
+\r
+/*\r
+ * Generate blkif ring structures and types.\r
+ */\r
+DEFINE_RING_TYPES(blkif, struct blkif_request, struct blkif_response);\r
+\r
+#define VDISK_CDROM        0x1\r
+#define VDISK_REMOVABLE    0x2\r
+#define VDISK_READONLY     0x4\r
+\r
+#endif /* __XEN_PUBLIC_IO_BLKIF_H__ */\r
+\r
+/*\r
+ * Local variables:\r
+ * mode: C\r
+ * c-file-style: "BSD"\r
+ * c-basic-offset: 4\r
+ * tab-width: 4\r
+ * indent-tabs-mode: nil\r
+ * End:\r
+ */\r
diff --git a/OvmfPkg/XenPvBlkDxe/BlockFront.c b/OvmfPkg/XenPvBlkDxe/BlockFront.c
new file mode 100644 (file)
index 0000000..3c039e7
--- /dev/null
@@ -0,0 +1,647 @@
+/** @file\r
+  Minimal block driver for Mini-OS.\r
+\r
+  Copyright (c) 2007-2008 Samuel Thibault.\r
+  Copyright (C) 2014, Citrix Ltd.\r
+\r
+  Redistribution and use in source and binary forms, with or without\r
+  modification, are permitted provided that the following conditions\r
+  are met:\r
+  1. Redistributions of source code must retain the above copyright\r
+     notice, this list of conditions and the following disclaimer.\r
+  2. Redistributions in binary form must reproduce the above copyright\r
+     notice, this list of conditions and the following disclaimer in the\r
+     documentation and/or other materials provided with the distribution.\r
+\r
+  THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND\r
+  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+  ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE\r
+  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
+  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\r
+  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\r
+  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r
+  SUCH DAMAGE.\r
+**/\r
+\r
+#include <Library/PrintLib.h>\r
+#include <Library/DebugLib.h>\r
+\r
+#include "BlockFront.h"\r
+\r
+#include <IndustryStandard/Xen/io/protocols.h>\r
+#include <IndustryStandard/Xen/io/xenbus.h>\r
+\r
+//\r
+// Header used for UINT32_MAX and UINT16_MAX\r
+//\r
+#include "inttypes.h"\r
+\r
+/**\r
+  Helper to read an integer from XenStore.\r
+\r
+  If the number overflows according to the range defined by UINT64,\r
+  then ASSERT().\r
+\r
+  @param This         A pointer to a XENBUS_PROTOCOL instance.\r
+  @param Node         The XenStore node to read from.\r
+  @param FromBackend  Read frontend or backend value.\r
+  @param ValuePtr     Where to put the value.\r
+\r
+  @retval XENSTORE_STATUS_SUCCESS  If succefull, will update ValuePtr.\r
+  @return                          Any other return value indicate the error,\r
+                                   ValuePtr is not updated in this case.\r
+**/\r
+STATIC\r
+XENSTORE_STATUS\r
+XenBusReadUint64 (\r
+  IN  XENBUS_PROTOCOL *This,\r
+  IN  CONST CHAR8     *Node,\r
+  IN  BOOLEAN         FromBackend,\r
+  OUT UINT64          *ValuePtr\r
+  )\r
+{\r
+  XENSTORE_STATUS Status;\r
+  CHAR8 *Ptr;\r
+\r
+  if (!FromBackend) {\r
+    Status = This->XsRead (This, XST_NIL, Node, (VOID**)&Ptr);\r
+  } else {\r
+    Status = This->XsBackendRead (This, XST_NIL, Node, (VOID**)&Ptr);\r
+  }\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    return Status;\r
+  }\r
+  // AsciiStrDecimalToUint64 will ASSERT if Ptr overflow UINT64.\r
+  *ValuePtr = AsciiStrDecimalToUint64 (Ptr);\r
+  FreePool (Ptr);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Free an instance of XEN_BLOCK_FRONT_DEVICE.\r
+\r
+  @param Dev  The instance to free.\r
+**/\r
+STATIC\r
+VOID\r
+XenPvBlockFree (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  )\r
+{\r
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;\r
+\r
+  if (Dev->RingRef != 0) {\r
+    XenBusIo->GrantEndAccess (XenBusIo, Dev->RingRef);\r
+  }\r
+  if (Dev->Ring.sring != NULL) {\r
+    FreePages (Dev->Ring.sring, 1);\r
+  }\r
+  if (Dev->EventChannel != 0) {\r
+    XenBusIo->EventChannelClose (XenBusIo, Dev->EventChannel);\r
+  }\r
+  FreePool (Dev);\r
+}\r
+\r
+/**\r
+  Wait until until the backend has reached the ExpectedState.\r
+\r
+  @param Dev            A XEN_BLOCK_FRONT_DEVICE instance.\r
+  @param ExpectedState  The backend state expected.\r
+  @param LastStatePtr   An optional pointer where to right the final state.\r
+\r
+  @return Return XENSTORE_STATUS_SUCCESS if the new backend state is ExpectedState\r
+          or return an error otherwise.\r
+**/\r
+STATIC\r
+XENSTORE_STATUS\r
+XenPvBlkWaitForBackendState (\r
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,\r
+  IN  XenbusState            ExpectedState,\r
+  OUT XenbusState            *LastStatePtr OPTIONAL\r
+  )\r
+{\r
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;\r
+  XenbusState State;\r
+  UINT64 Value;\r
+  XENSTORE_STATUS Status = XENSTORE_STATUS_SUCCESS;\r
+\r
+  while (TRUE) {\r
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);\r
+    if (Status != XENSTORE_STATUS_SUCCESS) {\r
+      return Status;\r
+    }\r
+    if (Value > XenbusStateReconfigured) {\r
+      //\r
+      // Value is not a State value.\r
+      //\r
+      return XENSTORE_STATUS_EIO;\r
+    }\r
+    State = Value;\r
+    if (State == ExpectedState) {\r
+      break;\r
+    } else if (State > ExpectedState) {\r
+      Status = XENSTORE_STATUS_FAIL;\r
+      break;\r
+    }\r
+    DEBUG ((EFI_D_INFO,\r
+            "XenPvBlk: waiting backend state %d, current: %d\n",\r
+            ExpectedState, State));\r
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);\r
+  }\r
+\r
+  if (LastStatePtr != NULL) {\r
+    *LastStatePtr = State;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+XenPvBlockFrontInitialization (\r
+  IN  XENBUS_PROTOCOL         *XenBusIo,\r
+  IN  CONST CHAR8             *NodeName,\r
+  OUT XEN_BLOCK_FRONT_DEVICE  **DevPtr\r
+  )\r
+{\r
+  XENSTORE_TRANSACTION xbt;\r
+  CHAR8 *DeviceType;\r
+  blkif_sring_t *SharedRing;\r
+  XENSTORE_STATUS Status;\r
+  XEN_BLOCK_FRONT_DEVICE *Dev;\r
+  XenbusState State;\r
+  UINT64 Value;\r
+\r
+  ASSERT (NodeName != NULL);\r
+\r
+  Dev = AllocateZeroPool (sizeof (XEN_BLOCK_FRONT_DEVICE));\r
+  Dev->Signature = XEN_BLOCK_FRONT_SIGNATURE;\r
+  Dev->NodeName = NodeName;\r
+  Dev->XenBusIo = XenBusIo;\r
+  Dev->DeviceId = XenBusIo->DeviceId;\r
+\r
+  XenBusIo->XsRead (XenBusIo, XST_NIL, "device-type", (VOID**)&DeviceType);\r
+  if (AsciiStrCmp (DeviceType, "cdrom") == 0) {\r
+    Dev->MediaInfo.CdRom = TRUE;\r
+  } else {\r
+    Dev->MediaInfo.CdRom = FALSE;\r
+  }\r
+  FreePool (DeviceType);\r
+\r
+  Status = XenBusReadUint64 (XenBusIo, "backend-id", FALSE, &Value);\r
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT16_MAX) {\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to get backend-id (%d)\n",\r
+            Status));\r
+    goto Error;\r
+  }\r
+  Dev->DomainId = Value;\r
+  XenBusIo->EventChannelAllocate (XenBusIo, Dev->DomainId, &Dev->EventChannel);\r
+\r
+  SharedRing = (blkif_sring_t*) AllocatePages (1);\r
+  SHARED_RING_INIT (SharedRing);\r
+  FRONT_RING_INIT (&Dev->Ring, SharedRing, EFI_PAGE_SIZE);\r
+  XenBusIo->GrantAccess (XenBusIo,\r
+                         Dev->DomainId,\r
+                         (INTN) SharedRing >> EFI_PAGE_SHIFT,\r
+                         FALSE,\r
+                         &Dev->RingRef);\r
+\r
+Again:\r
+  Status = XenBusIo->XsTransactionStart (XenBusIo, &xbt);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_WARN, "XenPvBlk: Failed to start transaction, %d\n", Status));\r
+    goto Error;\r
+  }\r
+\r
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName, "ring-ref", "%d",\r
+                               Dev->RingRef);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write ring-ref.\n"));\r
+    goto AbortTransaction;\r
+  }\r
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,\r
+                               "event-channel", "%d", Dev->EventChannel);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write event-channel.\n"));\r
+    goto AbortTransaction;\r
+  }\r
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,\r
+                               "protocol", "%a", XEN_IO_PROTO_ABI_NATIVE);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write protocol.\n"));\r
+    goto AbortTransaction;\r
+  }\r
+\r
+  Status = XenBusIo->SetState (XenBusIo, xbt, XenbusStateConnected);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to switch state.\n"));\r
+    goto AbortTransaction;\r
+  }\r
+\r
+  Status = XenBusIo->XsTransactionEnd (XenBusIo, xbt, FALSE);\r
+  if (Status == XENSTORE_STATUS_EAGAIN) {\r
+    goto Again;\r
+  }\r
+\r
+  XenBusIo->RegisterWatchBackend (XenBusIo, "state", &Dev->StateWatchToken);\r
+\r
+  //\r
+  // Waiting for backend\r
+  //\r
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: backend for %a/%d not available, rc=%d state=%d\n",\r
+            XenBusIo->Type, XenBusIo->DeviceId, Status, State));\r
+    goto Error2;\r
+  }\r
+\r
+  Status = XenBusReadUint64 (XenBusIo, "info", TRUE, &Value);\r
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {\r
+    goto Error2;\r
+  }\r
+  Dev->MediaInfo.VDiskInfo = Value;\r
+  if (Dev->MediaInfo.VDiskInfo & VDISK_READONLY) {\r
+    Dev->MediaInfo.ReadWrite = FALSE;\r
+  } else {\r
+    Dev->MediaInfo.ReadWrite = TRUE;\r
+  }\r
+\r
+  Status = XenBusReadUint64 (XenBusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    goto Error2;\r
+  }\r
+\r
+  Status = XenBusReadUint64 (XenBusIo, "sector-size", TRUE, &Value);\r
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {\r
+    goto Error2;\r
+  }\r
+  if (Value % 512 != 0) {\r
+    //\r
+    // This is not supported by the driver.\r
+    //\r
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Unsupported sector-size value %d, "\r
+            "it must be a multiple of 512\n", Value));\r
+    goto Error2;\r
+  }\r
+  Dev->MediaInfo.SectorSize = Value;\r
+\r
+  // Default value\r
+  Value = 0;\r
+  XenBusReadUint64 (XenBusIo, "feature-barrier", TRUE, &Value);\r
+  if (Value == 1) {\r
+    Dev->MediaInfo.FeatureBarrier = TRUE;\r
+  } else {\r
+    Dev->MediaInfo.FeatureBarrier = FALSE;\r
+  }\r
+\r
+  // Default value\r
+  Value = 0;\r
+  XenBusReadUint64 (XenBusIo, "feature-flush-cache", TRUE, &Value);\r
+  if (Value == 1) {\r
+    Dev->MediaInfo.FeatureFlushCache = TRUE;\r
+  } else {\r
+    Dev->MediaInfo.FeatureFlushCache = FALSE;\r
+  }\r
+\r
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %ld sectors of %d bytes\n",\r
+          Dev->MediaInfo.Sectors, Dev->MediaInfo.SectorSize));\r
+\r
+  *DevPtr = Dev;\r
+  return EFI_SUCCESS;\r
+\r
+Error2:\r
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");\r
+  goto Error;\r
+AbortTransaction:\r
+  XenBusIo->XsTransactionEnd (XenBusIo, xbt, TRUE);\r
+Error:\r
+  XenPvBlockFree (Dev);\r
+  return EFI_DEVICE_ERROR;\r
+}\r
+\r
+VOID\r
+XenPvBlockFrontShutdown (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  )\r
+{\r
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;\r
+  XENSTORE_STATUS Status;\r
+  UINT64 Value;\r
+\r
+  XenPvBlockSync (Dev);\r
+\r
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosing);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: error while changing state to Closing: %d\n",\r
+            Status));\r
+    goto Close;\r
+  }\r
+\r
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosing, NULL);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: error while waiting for closing backend state: %d\n",\r
+            Status));\r
+    goto Close;\r
+  }\r
+\r
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosed);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: error while changing state to Closed: %d\n",\r
+            Status));\r
+    goto Close;\r
+  }\r
+\r
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosed, NULL);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: error while waiting for closed backend state: %d\n",\r
+            Status));\r
+    goto Close;\r
+  }\r
+\r
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateInitialising);\r
+  if (Status != XENSTORE_STATUS_SUCCESS) {\r
+    DEBUG ((EFI_D_ERROR,\r
+            "XenPvBlk: error while changing state to initialising: %d\n",\r
+            Status));\r
+    goto Close;\r
+  }\r
+\r
+  while (TRUE) {\r
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);\r
+    if (Status != XENSTORE_STATUS_SUCCESS) {\r
+      DEBUG ((EFI_D_ERROR,\r
+              "XenPvBlk: error while waiting for new backend state: %d\n",\r
+              Status));\r
+      goto Close;\r
+    }\r
+    if (Value <= XenbusStateInitWait || Value >= XenbusStateClosed) {\r
+      break;\r
+    }\r
+    DEBUG ((EFI_D_INFO,\r
+            "XenPvBlk: waiting backend state %d, current: %d\n",\r
+            XenbusStateInitWait, Value));\r
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);\r
+  }\r
+\r
+Close:\r
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");\r
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");\r
+\r
+  XenPvBlockFree (Dev);\r
+}\r
+\r
+STATIC\r
+VOID\r
+XenPvBlockWaitSlot (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  )\r
+{\r
+  /* Wait for a slot */\r
+  if (RING_FULL (&Dev->Ring)) {\r
+    while (TRUE) {\r
+      XenPvBlockAsyncIoPoll (Dev);\r
+      if (!RING_FULL (&Dev->Ring)) {\r
+        break;\r
+      }\r
+      /* Really no slot, could wait for an event on Dev->EventChannel. */\r
+    }\r
+  }\r
+}\r
+\r
+VOID\r
+XenPvBlockAsyncIo (\r
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,\r
+  IN     BOOLEAN            IsWrite\r
+  )\r
+{\r
+  XEN_BLOCK_FRONT_DEVICE *Dev = IoData->Dev;\r
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;\r
+  blkif_request_t *Request;\r
+  RING_IDX RingIndex;\r
+  BOOLEAN Notify;\r
+  INT32 NumSegments, Index;\r
+  UINTN Start, End;\r
+\r
+  // Can't io at non-sector-aligned location\r
+  ASSERT(!(IoData->Sector & ((Dev->MediaInfo.SectorSize / 512) - 1)));\r
+  // Can't io non-sector-sized amounts\r
+  ASSERT(!(IoData->Size & (Dev->MediaInfo.SectorSize - 1)));\r
+  // Can't io non-sector-aligned buffer\r
+  ASSERT(!((UINTN) IoData->Buffer & (Dev->MediaInfo.SectorSize - 1)));\r
+\r
+  Start = (UINTN) IoData->Buffer & ~EFI_PAGE_MASK;\r
+  End = ((UINTN) IoData->Buffer + IoData->Size + EFI_PAGE_SIZE - 1) & ~EFI_PAGE_MASK;\r
+  IoData->NumRef = NumSegments = (End - Start) / EFI_PAGE_SIZE;\r
+\r
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);\r
+\r
+  XenPvBlockWaitSlot (Dev);\r
+  RingIndex = Dev->Ring.req_prod_pvt;\r
+  Request = RING_GET_REQUEST (&Dev->Ring, RingIndex);\r
+\r
+  Request->operation = IsWrite ? BLKIF_OP_WRITE : BLKIF_OP_READ;\r
+  Request->nr_segments = NumSegments;\r
+  Request->handle = Dev->DeviceId;\r
+  Request->id = (UINTN) IoData;\r
+  Request->sector_number = IoData->Sector;\r
+\r
+  for (Index = 0; Index < NumSegments; Index++) {\r
+    Request->seg[Index].first_sect = 0;\r
+    Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;\r
+  }\r
+  Request->seg[0].first_sect = ((UINTN) IoData->Buffer & EFI_PAGE_MASK) / 512;\r
+  Request->seg[NumSegments - 1].last_sect =\r
+      (((UINTN) IoData->Buffer + IoData->Size - 1) & EFI_PAGE_MASK) / 512;\r
+  for (Index = 0; Index < NumSegments; Index++) {\r
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;\r
+    XenBusIo->GrantAccess (XenBusIo, Dev->DomainId,\r
+                           Data >> EFI_PAGE_SHIFT, IsWrite,\r
+                           &Request->seg[Index].gref);\r
+    IoData->GrantRef[Index] = Request->seg[Index].gref;\r
+  }\r
+\r
+  Dev->Ring.req_prod_pvt = RingIndex + 1;\r
+\r
+  MemoryFence ();\r
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);\r
+\r
+  if (Notify) {\r
+    UINT32 ReturnCode;\r
+    ReturnCode = XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);\r
+    if (ReturnCode != 0) {\r
+      DEBUG ((EFI_D_ERROR,\r
+              "XenPvBlk: Unexpected return value from EventChannelNotify: %d\n",\r
+              ReturnCode));\r
+    }\r
+  }\r
+}\r
+\r
+EFI_STATUS\r
+XenPvBlockIo (\r
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,\r
+  IN     BOOLEAN            IsWrite\r
+  )\r
+{\r
+  //\r
+  // Status value that correspond to an IO in progress.\r
+  //\r
+  IoData->Status = EFI_ALREADY_STARTED;\r
+  XenPvBlockAsyncIo (IoData, IsWrite);\r
+\r
+  while (IoData->Status == EFI_ALREADY_STARTED) {\r
+    XenPvBlockAsyncIoPoll (IoData->Dev);\r
+  }\r
+\r
+  return IoData->Status;\r
+}\r
+\r
+STATIC\r
+VOID\r
+XenPvBlockPushOperation (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,\r
+  IN UINT8                  Operation,\r
+  IN UINT64                 Id\r
+  )\r
+{\r
+  INT32 Index;\r
+  blkif_request_t *Request;\r
+  BOOLEAN Notify;\r
+\r
+  XenPvBlockWaitSlot (Dev);\r
+  Index = Dev->Ring.req_prod_pvt;\r
+  Request = RING_GET_REQUEST(&Dev->Ring, Index);\r
+  Request->operation = Operation;\r
+  Request->nr_segments = 0;\r
+  Request->handle = Dev->DeviceId;\r
+  Request->id = Id;\r
+  /* Not needed anyway, but the backend will check it */\r
+  Request->sector_number = 0;\r
+  Dev->Ring.req_prod_pvt = Index + 1;\r
+  MemoryFence ();\r
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);\r
+  if (Notify) {\r
+    XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;\r
+    UINT32 ReturnCode;\r
+    ReturnCode = XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);\r
+    if (ReturnCode != 0) {\r
+      DEBUG ((EFI_D_ERROR,\r
+              "XenPvBlk: Unexpected return value from EventChannelNotify: %d\n",\r
+              ReturnCode));\r
+    }\r
+  }\r
+}\r
+\r
+VOID\r
+XenPvBlockSync (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  )\r
+{\r
+  if (Dev->MediaInfo.ReadWrite) {\r
+    if (Dev->MediaInfo.FeatureBarrier) {\r
+      XenPvBlockPushOperation (Dev, BLKIF_OP_WRITE_BARRIER, 0);\r
+    }\r
+\r
+    if (Dev->MediaInfo.FeatureFlushCache) {\r
+      XenPvBlockPushOperation (Dev, BLKIF_OP_FLUSH_DISKCACHE, 0);\r
+    }\r
+  }\r
+\r
+  /* Note: This won't finish if another thread enqueues requests.  */\r
+  while (TRUE) {\r
+    XenPvBlockAsyncIoPoll (Dev);\r
+    if (RING_FREE_REQUESTS (&Dev->Ring) == RING_SIZE (&Dev->Ring)) {\r
+      break;\r
+    }\r
+  }\r
+}\r
+\r
+VOID\r
+XenPvBlockAsyncIoPoll (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  )\r
+{\r
+  RING_IDX ProducerIndex, ConsumerIndex;\r
+  blkif_response_t *Response;\r
+  INT32 More;\r
+\r
+  do {\r
+    ProducerIndex = Dev->Ring.sring->rsp_prod;\r
+    /* Ensure we see queued responses up to 'ProducerIndex'. */\r
+    MemoryFence ();\r
+    ConsumerIndex = Dev->Ring.rsp_cons;\r
+\r
+    while (ConsumerIndex != ProducerIndex) {\r
+      XEN_BLOCK_FRONT_IO *IoData = NULL;\r
+      INT16 Status;\r
+\r
+      Response = RING_GET_RESPONSE (&Dev->Ring, ConsumerIndex);\r
+\r
+      IoData = (VOID *) (UINTN) Response->id;\r
+      Status = Response->status;\r
+\r
+      switch (Response->operation) {\r
+      case BLKIF_OP_READ:\r
+      case BLKIF_OP_WRITE:\r
+        {\r
+          INT32 Index;\r
+\r
+          if (Status != BLKIF_RSP_OKAY) {\r
+            DEBUG ((EFI_D_ERROR,\r
+                    "XenPvBlk: "\r
+                    "%a error %d on %a at sector %p, num bytes %p\n",\r
+                    Response->operation == BLKIF_OP_READ ? "read" : "write",\r
+                    Status, IoData->Dev->NodeName,\r
+                    IoData->Sector,\r
+                    IoData->Size));\r
+          }\r
+\r
+          for (Index = 0; Index < IoData->NumRef; Index++) {\r
+            Dev->XenBusIo->GrantEndAccess (Dev->XenBusIo, IoData->GrantRef[Index]);\r
+          }\r
+\r
+          break;\r
+        }\r
+\r
+      case BLKIF_OP_WRITE_BARRIER:\r
+        if (Status != BLKIF_RSP_OKAY) {\r
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: write barrier error %d\n", Status));\r
+        }\r
+        break;\r
+      case BLKIF_OP_FLUSH_DISKCACHE:\r
+        if (Status != BLKIF_RSP_OKAY) {\r
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: flush error %d\n", Status));\r
+        }\r
+        break;\r
+\r
+      default:\r
+        DEBUG ((EFI_D_ERROR,\r
+                "XenPvBlk: unrecognized block operation %d response (status %d)\n",\r
+                Response->operation, Status));\r
+        break;\r
+      }\r
+\r
+      Dev->Ring.rsp_cons = ++ConsumerIndex;\r
+      if (IoData != NULL) {\r
+        IoData->Status = Status ? EFI_DEVICE_ERROR : EFI_SUCCESS;\r
+      }\r
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {\r
+        /* We reentered, we must not continue here */\r
+        break;\r
+      }\r
+    }\r
+\r
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);\r
+  } while (More != 0);\r
+}\r
diff --git a/OvmfPkg/XenPvBlkDxe/BlockFront.h b/OvmfPkg/XenPvBlkDxe/BlockFront.h
new file mode 100644 (file)
index 0000000..867b39f
--- /dev/null
@@ -0,0 +1,101 @@
+/** @file\r
+  BlockFront functions and types declarations.\r
+\r
+  Copyright (C) 2014, Citrix Ltd.\r
+\r
+  This program and the accompanying materials\r
+  are licensed and made available under the terms and conditions of the BSD License\r
+  which accompanies this distribution.  The full text of the license may be found at\r
+  http://opensource.org/licenses/bsd-license.php\r
+\r
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+#include "XenPvBlkDxe.h"\r
+\r
+#include <IndustryStandard/Xen/event_channel.h>\r
+#include <IndustryStandard/Xen/io/blkif.h>\r
+\r
+typedef struct _XEN_BLOCK_FRONT_DEVICE XEN_BLOCK_FRONT_DEVICE;\r
+typedef struct _XEN_BLOCK_FRONT_IO XEN_BLOCK_FRONT_IO;\r
+\r
+struct _XEN_BLOCK_FRONT_IO\r
+{\r
+  XEN_BLOCK_FRONT_DEVICE  *Dev;\r
+  UINT8                   *Buffer;\r
+  UINTN                   Size;\r
+  UINTN                   Sector; ///< 512 bytes sector.\r
+\r
+  grant_ref_t             GrantRef[BLKIF_MAX_SEGMENTS_PER_REQUEST];\r
+  INT32                   NumRef;\r
+\r
+  EFI_STATUS              Status;\r
+};\r
+\r
+typedef struct\r
+{\r
+  UINT64    Sectors;\r
+  UINT32    SectorSize;\r
+  UINT32    VDiskInfo;\r
+  BOOLEAN   ReadWrite;\r
+  BOOLEAN   CdRom;\r
+  BOOLEAN   FeatureBarrier;\r
+  BOOLEAN   FeatureFlushCache;\r
+} XEN_BLOCK_FRONT_MEDIA_INFO;\r
+\r
+#define XEN_BLOCK_FRONT_SIGNATURE SIGNATURE_32 ('X', 'p', 'v', 'B')\r
+struct _XEN_BLOCK_FRONT_DEVICE {\r
+  UINT32                      Signature;\r
+  EFI_BLOCK_IO_PROTOCOL       BlockIo;\r
+  domid_t                     DomainId;\r
+\r
+  blkif_front_ring_t          Ring;\r
+  grant_ref_t                 RingRef;\r
+  evtchn_port_t               EventChannel;\r
+  blkif_vdev_t                DeviceId;\r
+\r
+  CONST CHAR8                 *NodeName;\r
+  XEN_BLOCK_FRONT_MEDIA_INFO  MediaInfo;\r
+\r
+  VOID                        *StateWatchToken;\r
+\r
+  XENBUS_PROTOCOL             *XenBusIo;\r
+};\r
+\r
+#define XEN_BLOCK_FRONT_FROM_BLOCK_IO(b) \\r
+  CR (b, XEN_BLOCK_FRONT_DEVICE, BlockIo, XEN_BLOCK_FRONT_SIGNATURE)\r
+\r
+EFI_STATUS\r
+XenPvBlockFrontInitialization (\r
+  IN  XENBUS_PROTOCOL  *XenBusIo,\r
+  IN  CONST CHAR8      *NodeName,\r
+  OUT XEN_BLOCK_FRONT_DEVICE **DevPtr\r
+  );\r
+\r
+VOID\r
+XenPvBlockFrontShutdown (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  );\r
+\r
+VOID\r
+XenPvBlockAsyncIo (\r
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,\r
+  IN     BOOLEAN            IsWrite\r
+  );\r
+\r
+EFI_STATUS\r
+XenPvBlockIo (\r
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,\r
+  IN     BOOLEAN            IsWrite\r
+  );\r
+\r
+VOID\r
+XenPvBlockAsyncIoPoll (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  );\r
+\r
+VOID\r
+XenPvBlockSync (\r
+  IN XEN_BLOCK_FRONT_DEVICE *Dev\r
+  );\r
index a5a69537ee137bcb219431037abdb3539c3d8ac3..e755a43dd687d9d1c023544de76b5c95cd02eca4 100644 (file)
@@ -20,6 +20,8 @@
 \r
 #include "XenPvBlkDxe.h"\r
 \r
+#include "BlockFront.h"\r
+\r
 \r
 ///\r
 /// Driver Binding Protocol instance\r
@@ -258,6 +260,7 @@ XenPvBlkDxeDriverBindingStart (
 {\r
   EFI_STATUS Status;\r
   XENBUS_PROTOCOL *XenBusIo;\r
+  XEN_BLOCK_FRONT_DEVICE *Dev;\r
 \r
   Status = gBS->OpenProtocol (\r
                 ControllerHandle,\r
@@ -271,7 +274,17 @@ XenPvBlkDxeDriverBindingStart (
     return Status;\r
   }\r
 \r
+  Status = XenPvBlockFrontInitialization (XenBusIo, XenBusIo->Node, &Dev);\r
+  if (EFI_ERROR (Status)) {\r
+    goto CloseProtocol;\r
+  }\r
+\r
   return EFI_SUCCESS;\r
+\r
+CloseProtocol:\r
+  gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,\r
+                      This->DriverBindingHandle, ControllerHandle);\r
+  return Status;\r
 }\r
 \r
 /**\r
index 32ae952bb5b646198c406868dc46e60f516f3ab7..af0ed2ed4b88a3dea25460475386c5be25609d5a 100644 (file)
@@ -33,6 +33,8 @@
   XenPvBlkDxe.c\r
   ComponentName.c\r
   ComponentName.h\r
+  BlockFront.c\r
+  BlockFront.h\r
 \r
 \r
 [LibraryClasses]\r