Skip to contentSkip to conversation

OvmfPkg: Add public headers from Xen Project.

PATCH New Anthony PERARD 4 participants 50 messages Sep 4, 2014 – Sep 18, 2014 22 messages not in the archive Page 2 of 2

lore
Share & tools
lore
#52 lore raw

Re: [PATCH v2 11/18] OvmfPkg/XenBusDxe: Add XenStore client implementation

In reply to Konrad Rzeszutek Wilk
Quoted 7 lines · Konrad Rzeszutek Wilk
Quoted 3 lines · Anthony PERARD

XenStore is a key/value database, which is running on another virtual machine. It can be accessed through shared memory. This is a client implementation.

You should really take from patch #1 the io/xs_wire.h and have it as part of this patch.

Ok, will do.

Quoted 641 lines

I have some comments, but overall this looks good. If you want to
fix them up, you can tack on Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>

Quoted 624 lines

Origin: FreeBSD 10.0

Contributed-under: TianoCore Contribution Agreement 1.0

---
Change in V2:
- Change comment style, from freebsd to ovmf
- Fix type of EventChannel
- Fix debug print, no more cast
- Implement XenStoreDeinit.
- Clean up comments
- Fix few codding style issue
- Add FAIL xenstore status value.

---
 OvmfPkg/Include/Protocol/XenBus.h |   29 +
 OvmfPkg/XenBusDxe/XenBusDxe.c     |    5 +
 OvmfPkg/XenBusDxe/XenBusDxe.inf   |    2 +
 OvmfPkg/XenBusDxe/XenStore.c      | 1320 +++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenStore.h      |  292 ++++++++
 5 files changed, 1648 insertions(+)
 create mode 100644 OvmfPkg/XenBusDxe/XenStore.c
 create mode 100644 OvmfPkg/XenBusDxe/XenStore.h
OvmfPkg/Include/Protocol/XenBus.h +29 -0
index bf4a69f..b10c143 100644
@@ -45,6 +45,35 @@
 ///
 typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
 
+typedef enum xenbus_state XenbusState;
+
+typedef struct
+{
+  UINT32 Id;
+} XENSTORE_TRANSACTION;
+
+#define XST_NIL ((XENSTORE_TRANSACTION) { 0 })
+
+typedef enum {
+  XENSTORE_STATUS_SUCCESS = 0,
+  XENSTORE_STATUS_FAIL,
+  XENSTORE_STATUS_EINVAL,
+  XENSTORE_STATUS_EACCES,
+  XENSTORE_STATUS_EEXIST,
+  XENSTORE_STATUS_EISDIR,
+  XENSTORE_STATUS_ENOENT,
+  XENSTORE_STATUS_ENOMEM,
+  XENSTORE_STATUS_ENOSPC,
+  XENSTORE_STATUS_EIO,
+  XENSTORE_STATUS_ENOTEMPTY,
+  XENSTORE_STATUS_ENOSYS,
+  XENSTORE_STATUS_EROFS,
+  XENSTORE_STATUS_EBUSY,
+  XENSTORE_STATUS_EAGAIN,
+  XENSTORE_STATUS_EISCONN,
+  XENSTORE_STATUS_E2BIG
+} XENSTORE_STATUS;
+
 
 #include <IndustryStandard/Xen/grant_table.h>
 
OvmfPkg/XenBusDxe/XenBusDxe.c +5 -0
index 29aadb1..76ea67c 100644
@@ -47,6 +47,7 @@
 
 #include "XenHypercall.h"
 #include "GrantTable.h"
+#include "XenStore.h"
 
 
 ///
@@ -344,6 +345,9 @@ XenBusDxeDriverBindingStart (
 
   XenGrantTableInit (Dev, MmioAddr);
 
+  Status = XenStoreInit (Dev);
+  ASSERT_EFI_ERROR (Status);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -398,6 +402,7 @@ XenBusDxeDriverBindingStop (
   XENBUS_DEVICE *Dev = mMyDevice;
 
   gBS->CloseEvent (Dev->ExitBootEvent);
+  XenStoreDeinit (Dev);
   XenGrantTableDeinit (Dev);
 
   gBS->CloseProtocol (ControllerHandle, &gEfiPciIoProtocolGuid,
OvmfPkg/XenBusDxe/XenBusDxe.inf +2 -0
index e8f362a..9052967 100644
@@ -38,6 +38,8 @@
   GrantTable.h
   EventChannel.c
   EventChannel.h
+  XenStore.c
+  XenStore.h
 
 [Sources.X64]
   X64/hypercall.S
OvmfPkg/XenBusDxe/XenStore.c new file +510 -0
new file mode 100644
index 0000000..bcf6e1c
@@ -0,0 +1,1320 @@
+/** @file
+  Low-level kernel interface to the XenStore.
+
+  The XenStore interface is a simple storage system that is a means of
+  communicating state and configuration data between the Xen Domain 0
+  and the various guest domains.  All configuration data other than
+  a small amount of essential information required during the early
+  boot process of launching a Xen aware guest, is managed using the
+  XenStore.
+
+  The XenStore is ASCII string based, and has a structure and semantics
+  similar to a filesystem.  There are files and directories, the directories
+  able to contain files or other directories.  The depth of the hierachy
+  is only limited by the XenStore's maximum path length.
+
+  The communication channel between the XenStore service and other
+  domains is via two, guest specific, ring buffers in a shared memory
+  area.  One ring buffer is used for communicating in each direction.
+  The grant table references for this shared memory are given to the
+  guest either via the xen_start_info structure for a fully para-
+  virtualized guest, or via HVM hypercalls for a hardware virtualized
+  guest.
+
+  The XenStore communication relies on an event channel and thus
+  interrupts.  But under OVMF this XenStore client will pull the
+  state of the event channel.
+
+  Several Xen services depend on the XenStore, most notably the
+  XenBus used to discover and manage Xen devices.
+
+  Copyright (C) 2005 Rusty Russell, IBM Corporation
+  Copyright (C) 2009,2010 Spectra Logic Corporation
+  Copyright (C) 2014, Citrix Ltd.
+
+  This file may be distributed separately from the Linux kernel, or
+  incorporated into other software packages, subject to the following license:
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this source file (the "Software"), to deal in the Software without
+  restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software,
+  and to permit persons to whom the Software is furnished to do so, subject to
+  the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+  IN THE SOFTWARE.
+**/
+
+#include "XenStore.h"
+
+#include <Library/PrintLib.h>
+
+#include <IndustryStandard/Xen/hvm/params.h>
+
+#include "XenHypercall.h"
+#include "EventChannel.h"
+
+//
+// Private Data Structures
+//
+
+typedef struct {
+  CONST VOID  *Data;
+  UINTN       Len;
+} WRITE_REQUEST;
+
+/* Register callback to watch subtree (node) in the XenStore. */
+#define XENSTORE_WATCH_SIGNATURE SIGNATURE_32 ('X','S','w','a')
+struct _XENSTORE_WATCH
+{
+  UINT32      Signature;
+  LIST_ENTRY  Link;
+
+  /* Path being watched. */
+  CHAR8       *Node;
+};
+
+#define XENSTORE_WATCH_FROM_LINK(l) \
+  CR (l, XENSTORE_WATCH, Link, XENSTORE_WATCH_SIGNATURE)
+
+
+/**
+ * Structure capturing messages received from the XenStore service.
+ */
+#define XENSTORE_MESSAGE_SIGNATURE SIGNATURE_32 ('X', 'S', 's', 'm')
+typedef struct {
+  UINT32 Signature;
+  LIST_ENTRY Link;
+
+  struct xsd_sockmsg Header;
+
+  union {
+    /* Queued replies. */
+    struct {
+      CHAR8 *Body;
+    } Reply;
+
+    /* Queued watch events. */
+    struct {
+      XENSTORE_WATCH *Handle;
+      CONST CHAR8 **Vector;
+      UINT32 VectorSize;
+    } Watch;
+  } u;
+} XENSTORE_MESSAGE;
+#define XENSTORE_MESSAGE_FROM_LINK(r) \
+  CR (r, XENSTORE_MESSAGE, Link, XENSTORE_MESSAGE_SIGNATURE)
+
+/**
+ * Container for all XenStore related state.
+ */
+typedef struct {
+  /**
+   * Pointer to shared memory communication structures allowing us
+   * to communicate with the XenStore service.
+   */
+  struct xenstore_domain_interface *XenStore;
+
+  XENBUS_DEVICE *Dev;
+
+  /**
+   * A list of replies to our requests.
+   *
+   * The reply list is filled by xs_rcv_thread().  It
+   * is consumed by the context that issued the request
+   * to which a reply is made.  The requester blocks in
+   * XenStoreReadReply ().
+   *
+   * /note Only one requesting context can be active at a time.
+   */
+  LIST_ENTRY ReplyList;
+
+  /** Lock protecting the reply list. */
+  EFI_LOCK ReplyLock;
+
+  /**
+   * List of registered watches.
+   */
+  LIST_ENTRY RegisteredWatches;
+
+  /** Lock protecting the registered watches list. */
+  EFI_LOCK RegisteredWatchesLock;
+
+  /**
+   * List of pending watch callback events.
+   */
+  LIST_ENTRY WatchEvents;
+
+  /** Lock protecting the watch calback list. */
+  EFI_LOCK WatchEventsLock;
+
+  /**
+   * The event channel for communicating with the
+   * XenStore service.
+   */
+  evtchn_port_t EventChannel;
+
+  /** Handle for XenStore events. */
+  EFI_EVENT EventChannelEvent;
+} XENSTORE_PRIVATE;
+
+//
+// Global Data
+//
+static XENSTORE_PRIVATE xs;
+
+
+//
+// Private Utility Functions
+//
+
+/**
+  Count and optionally record pointers to a number of NUL terminated
+  strings in a buffer.
+
+  @param Strings  A pointer to a contiguous buffer of NUL terminated strings.
+  @param Len      The length of the buffer pointed to by strings.
+  @param Dst      An array to store pointers to each string found in strings.
+
+  @return  A count of the number of strings found.
+**/
+STATIC
+UINT32
+ExtractStrings (
+  IN  CONST CHAR8 *Strings,
+  IN  UINTN       Len,
+  OUT CONST CHAR8 **Dst OPTIONAL
+  )
+{
+  UINT32 Num = 0;
+  CONST CHAR8 *Ptr;
+
+  for (Ptr = Strings; Ptr < Strings + Len; Ptr += AsciiStrSize (Ptr)) {
+    if (Dst != NULL) {
+      *Dst++ = Ptr;
+    }
+    Num++;
+  }
+
+  return Num;
+}
+
+/**
+  Convert a contiguous buffer containing a series of NUL terminated
+  strings into an array of pointers to strings.
+
+  The returned pointer references the array of string pointers which
+  is followed by the storage for the string data.  It is the client's
+  responsibility to free this storage.
+
+  The storage addressed by Strings is free'd prior to Split returning.
+
+  @param Strings  A pointer to a contiguous buffer of NUL terminated strings.
+  @param Len      The length of the buffer pointed to by strings.
+  @param NumPtr   The number of strings found and returned in the strings
+                  array.
+
+  @return  An array of pointers to the strings found in the input buffer.
+**/
+STATIC
+CONST CHAR8 **
+Split (
+  IN  CHAR8   *Strings,
+  IN  UINTN   Len,
+  OUT UINT32  *NumPtr
+  )
+{
+  CONST CHAR8 **Dst;
+
+  ASSERT(NumPtr != NULL);
+  ASSERT(Strings != NULL);
+
+  /* Protect against unterminated buffers. */
+  if (Len > 0) {
+    Strings[Len - 1] = '\0';
+  }
+
+  /* Count the Strings. */
+  *NumPtr = ExtractStrings (Strings, Len, NULL);
+
+  /* Transfer to one big alloc for easy freeing by the caller. */
+  Dst = AllocatePool (*NumPtr * sizeof (CHAR8 *) + Len);
+  CopyMem (&Dst[*NumPtr], Strings, Len);
+  FreePool (Strings);
+
+  /* Extract pointers to newly allocated array. */
+  Strings = (CHAR8 *) &Dst[*NumPtr];
+  ExtractStrings (Strings, Len, Dst);
+
+  return (Dst);
+}
+
+/**
+  Convert from watch token (unique identifier) to the associated
+  internal tracking structure for this watch.
+
+  @param Tocken  The unique identifier for the watch to find.
+
+  @return  A pointer to the found watch structure or NULL.
+**/
+STATIC
+XENSTORE_WATCH *
+XenStoreFindWatch (
+  IN CONST CHAR8 *Token
+  )
+{
+  XENSTORE_WATCH *Watch, *WantedWatch;
+  LIST_ENTRY *Entry;
+
+  WantedWatch = (VOID *) AsciiStrHexToUintn (Token);
+
+  if (IsListEmpty (&xs.RegisteredWatches)) {
+    return NULL;
+  }
+  for (Entry = GetFirstNode (&xs.RegisteredWatches);
+       !IsNull (&xs.RegisteredWatches, Entry);
+       Entry = GetNextNode (&xs.RegisteredWatches, Entry)) {
+    Watch = XENSTORE_WATCH_FROM_LINK (Entry);
+    if (Watch == WantedWatch)
+      return Watch;
+  }
+
+  return NULL;
+}
+
+//
+// Public Utility Functions
+// API comments for these methods can be found in XenStore.h
+//
+
+CHAR8 *
+XenStoreJoin (
+  IN CONST CHAR8 *DirectoryPath,
+  IN CONST CHAR8 *Node
+  )
+{
+  CHAR8 *Buf;
+
+  /* +1 for '/' and +1 for '\0' */
+  Buf = AllocateZeroPool (
+          AsciiStrLen (DirectoryPath) + AsciiStrLen (Node) + 2);
+  AsciiStrCat (Buf, DirectoryPath);
+  if (Node[0] != '\0') {
+    AsciiStrCat (Buf, "/");
+    AsciiStrCat (Buf, Node);
+  }
+
+  return Buf;
+}
+
+//
+// Low Level Communication Management
+//
+
+/**
+  Verify that the indexes for a ring are valid.
+
+  The difference between the producer and consumer cannot
+  exceed the size of the ring.
+
+  @param Cons  The consumer index for the ring to test.
+  @param Prod  The producer index for the ring to test.
+
+  @retval TRUE   If indexes are in range.
+  @retval FALSE  If the indexes are out of range.
+**/
+STATIC
+BOOLEAN
+XenStoreCheckIndexes (
+  XENSTORE_RING_IDX Cons,
+  XENSTORE_RING_IDX Prod
+  )
+{
+  return ((Prod - Cons) <= XENSTORE_RING_SIZE);
+}
+
+/**
+  Return a pointer to, and the length of, the contiguous
+  free region available for output in a ring buffer.
+
+  @param Cons    The consumer index for the ring.
+  @param Prod    The producer index for the ring.
+  @param Buffer  The base address of the ring's storage.
+  @param LenPtr  The amount of contiguous storage available.
+
+  @return  A pointer to the start location of the free region.
+**/
+STATIC
+VOID *
+XenStoreGetOutputChunk (
+  IN  XENSTORE_RING_IDX Cons,
+  IN  XENSTORE_RING_IDX Prod,
+  IN  CHAR8             *Buffer,
+  OUT UINT32            *LenPtr
+  )
+{
+  UINT32 Len;
+  Len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX (Prod);
+  if ((XENSTORE_RING_SIZE - (Prod - Cons)) < Len) {
+    Len = XENSTORE_RING_SIZE - (Prod - Cons);
+  }
+  *LenPtr = Len;
+  return (Buffer + MASK_XENSTORE_IDX (Prod));
+}
+
+/**
+  Return a pointer to, and the length of, the contiguous
+  data available to read from a ring buffer.
+
+  @param Cons    The consumer index for the ring.
+  @param Prod    The producer index for the ring.
+  @param Buffer  The base address of the ring's storage.
+  @param LenPtr  The amount of contiguous data available to read.
+
+  @return  A pointer to the start location of the available data.
+**/
+STATIC
+CONST VOID *
+XenStoreGetInputChunk (
+  IN  XENSTORE_RING_IDX Cons,
+  IN  XENSTORE_RING_IDX Prod,
+  IN  CONST CHAR8       *Buffer,
+  OUT UINT32            *LenPtr
+  )
+{
+  UINT32 Len;
+
+  Len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX (Cons);
+  if ((Prod - Cons) < Len) {
+    Len = Prod - Cons;
+  }
+  *LenPtr = Len;
+  return (Buffer + MASK_XENSTORE_IDX (Cons));
+}
+
+/**
+  Transmit data to the XenStore service.
+
+  The buffer pointed to by DataPtr is at least Len bytes in length.
+
+  @param DataPtr  A pointer to the contiguous data to send.
+  @param Len      The amount of data to send.
+
+  @return  On success 0, otherwise an errno value indicating the
+           cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreWriteStore (
+  IN CONST VOID *DataPtr,
+  IN UINTN      Len
+  )
+{
+  XENSTORE_RING_IDX Cons, Prod;
+  CONST CHAR8 *Data = (CONST CHAR8 *)DataPtr;
+
+  while (Len != 0) {
+    void *Dest;
+    UINT32 Available;
+
+    Cons = xs.XenStore->req_cons;
+    Prod = xs.XenStore->req_prod;
+    if ((Prod - Cons) == XENSTORE_RING_SIZE) {
+      /*
+       * Output ring is full. Wait for a ring event.
+       *
+       * Note that the events from both queues are combined, so being woken
+       * does not guarantee that data exist in the read ring.
+       */
+      UINTN Index;
+      EFI_STATUS Status;
+
+      Status = gBS->WaitForEvent (1, &xs.EventChannelEvent, &Index);
+      ASSERT (Status != EFI_INVALID_PARAMETER);
+
+      /* Try again. */
+      continue;
+    }
+
+    /* Verify queue sanity. */
+    if (!XenStoreCheckIndexes (Cons, Prod)) {
+      xs.XenStore->req_cons = xs.XenStore->req_prod = 0;
+      return XENSTORE_STATUS_EIO;
+    }
+
+    Dest = XenStoreGetOutputChunk (Cons, Prod, xs.XenStore->req, &Available);
+    if (Available > Len) {
+      Available = Len;
+    }
+
+    CopyMem (Dest, Data, Available);
+    Data += Available;
+    Len -= Available;
+
+    /*
+     * The store to the producer index, which indicates
+     * to the other side that new data has arrived, must
+     * be visible only after our copy of the data into the
+     * ring has completed.
+     */
+    MemoryFence ();
+    xs.XenStore->req_prod += Available;
+
+    /*
+     * The other side will see the change to req_prod at the time of the
+     * interrupt.
+     */
+    MemoryFence ();
+    XenEventChannelNotify (xs.Dev, xs.EventChannel);
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+/**
+  Receive data from the XenStore service.
+
+  The buffer pointed to by DataPtr is at least Len bytes in length.
+
+  @param DataPtr  A pointer to the contiguous buffer to receive the data.
+  @param Len      The amount of data to receive.
+
+  @return  On success 0, otherwise an errno value indicating the
+           cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreReadStore (
+  OUT VOID *DataPtr,
+  IN  UINTN Len
+  )
+{
+  XENSTORE_RING_IDX Cons, Prod;
+  CHAR8 *Data = (CHAR8 *) DataPtr;
+
+  while (Len != 0) {
+    UINT32 Available;
+    CONST CHAR8 *Src;
+
+    Cons = xs.XenStore->rsp_cons;
+    Prod = xs.XenStore->rsp_prod;
+    if (Cons == Prod) {

OvmfPkg/XenBusDxe/XenStore.c line 520

Quoted 10 lines
OvmfPkg/XenBusDxe/XenStore.c new file +10 -0
+      /*
+       * Nothing to read. Wait for a ring event.
+       *
+       * Note that the events from both queues are combined, so being woken
+       * does not guarantee that data exist in the read ring.
+       */
+      UINTN Index;
+      EFI_STATUS Status;
+
+      Status = gBS->WaitForEvent (1, &xs.EventChannelEvent, &Index);

Ouch. That if done incorrectly (say the other side does not notify) could stop this whole thing right here.

Quoted 1 line

Perhaps you can add debug printk so at least we know where it might be stuck?

Actually, I could had a timeout here.

So, we could wait 3second, and check the ring again, maybe 2 more time. If the ring is empty, we could just return an error (EIO). That would be around 9second, but after that, the firmware could do something else.

And in case of timeout, have a printk.

Quoted 1 line

Ditto for the other WaitForEvent call site.

ok.

Quoted 185 lines
Quoted 185 lines
OvmfPkg/XenBusDxe/XenStore.c new file +185 -0
+      ASSERT (Status != EFI_INVALID_PARAMETER);
+      continue;
+    }
+
+    /* Verify queue sanity. */
+    if (!XenStoreCheckIndexes (Cons, Prod)) {
+      xs.XenStore->rsp_cons = xs.XenStore->rsp_prod = 0;
+      return XENSTORE_STATUS_EIO;
+    }
+
+    Src = XenStoreGetInputChunk (Cons, Prod, xs.XenStore->rsp, &Available);
+    if (Available > Len) {
+      Available = Len;
+    }
+
+    /*
+     * Insure the data we read is related to the indexes
+     * we read above.
+     */
+    MemoryFence ();
+
+    CopyMem (Data, Src, Available);
+    Data += Available;
+    Len -= Available;
+
+    /*
+     * Insure that the producer of this ring does not see
+     * the ring space as free until after we have copied it
+     * out.
+     */
+    MemoryFence ();
+    xs.XenStore->rsp_cons += Available;
+
+    /*
+     * The producer will see the updated consumer index when the event is
+     * delivered.
+     */
+    MemoryFence ();
+    XenEventChannelNotify (xs.Dev, xs.EventChannel);
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+//
+// Received Message Processing
+//
+
+/**
+  Block reading the next message from the XenStore service and
+  process the result.
+
+  @return  XENSTORE_STATUS_SUCCESS on success.  Otherwise an errno value
+           indicating the type of failure encountered.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreProcessMessage (
+  VOID
+  )
+{
+  XENSTORE_MESSAGE *Message;
+  CHAR8 *Body;
+  XENSTORE_STATUS Status;
+
+  Message = AllocateZeroPool (sizeof (XENSTORE_MESSAGE));
+  Message->Signature = XENSTORE_MESSAGE_SIGNATURE;
+  Status = XenStoreReadStore (&Message->Header, sizeof (Message->Header));
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    FreePool (Message);
+    DEBUG ((EFI_D_ERROR, "XenStore: Error read store (%d)\n", Status));
+    return Status;
+  }
+
+  Body = AllocatePool (Message->Header.len + 1);
+  Status = XenStoreReadStore (Body, Message->Header.len);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    FreePool (Body);
+    FreePool (Message);
+    DEBUG ((EFI_D_ERROR, "XenStore: Error read store (%d)\n", Status));
+    return Status;
+  }
+  Body[Message->Header.len] = '\0';
+
+  if (Message->Header.type == XS_WATCH_EVENT) {
+    Message->u.Watch.Vector = Split(Body, Message->Header.len,
+                                    &Message->u.Watch.VectorSize);
+
+    EfiAcquireLock (&xs.RegisteredWatchesLock);
+    Message->u.Watch.Handle =
+      XenStoreFindWatch (Message->u.Watch.Vector[XS_WATCH_TOKEN]);
+    DEBUG ((EFI_D_INFO, "XenStore: Watch event %a\n",
+            Message->u.Watch.Vector[XS_WATCH_TOKEN]));
+    if (Message->u.Watch.Handle != NULL) {
+      EfiAcquireLock (&xs.WatchEventsLock);
+      InsertHeadList (&xs.WatchEvents, &Message->Link);
+      EfiReleaseLock (&xs.WatchEventsLock);
+    } else {
+      DEBUG ((EFI_D_WARN, "XenStore: Watch handle %a not found\n",
+              Message->u.Watch.Vector[XS_WATCH_TOKEN]));
+      FreePool(Message->u.Watch.Vector);
+      FreePool(Message);
+    }
+    EfiReleaseLock (&xs.RegisteredWatchesLock);
+  } else {
+    Message->u.Reply.Body = Body;
+    EfiAcquireLock (&xs.ReplyLock);
+    InsertTailList (&xs.ReplyList, &Message->Link);
+    EfiReleaseLock (&xs.ReplyLock);
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+//
+// XenStore Message Request/Reply Processing
+//
+
+/**
+  Convert a XenStore error string into an errno number.
+
+  Unknown error strings are converted to EINVAL.
+
+  @param errorstring  The error string to convert.
+
+  @return  The errno best matching the input string.
+
+**/
+typedef struct {
+  XENSTORE_STATUS Status;
+  CONST CHAR8 *ErrorStr;
+} XenStoreErrors;
+
+static XenStoreErrors gXenStoreErrors[] = {
+  { XENSTORE_STATUS_EINVAL, "EINVAL" },
+  { XENSTORE_STATUS_EACCES, "EACCES" },
+  { XENSTORE_STATUS_EEXIST, "EEXIST" },
+  { XENSTORE_STATUS_EISDIR, "EISDIR" },
+  { XENSTORE_STATUS_ENOENT, "ENOENT" },
+  { XENSTORE_STATUS_ENOMEM, "ENOMEM" },
+  { XENSTORE_STATUS_ENOSPC, "ENOSPC" },
+  { XENSTORE_STATUS_EIO, "EIO" },
+  { XENSTORE_STATUS_ENOTEMPTY, "ENOTEMPTY" },
+  { XENSTORE_STATUS_ENOSYS, "ENOSYS" },
+  { XENSTORE_STATUS_EROFS, "EROFS" },
+  { XENSTORE_STATUS_EBUSY, "EBUSY" },
+  { XENSTORE_STATUS_EAGAIN, "EAGAIN" },
+  { XENSTORE_STATUS_EISCONN, "EISCONN" },
+  { XENSTORE_STATUS_E2BIG, "E2BIG" }
+};
+#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
+
+STATIC
+XENSTORE_STATUS
+XenStoreGetError (
+  CONST CHAR8 *ErrorStr
+  )
+{
+  UINT32 Index;
+
+  for (Index = 0; Index < ARRAY_SIZE(gXenStoreErrors); Index++) {
+    if (!AsciiStrCmp (ErrorStr, gXenStoreErrors[Index].ErrorStr)) {
+      return gXenStoreErrors[Index].Status;
+    }
+  }
+  DEBUG ((EFI_D_WARN, "XenStore gave unknown error %a\n", ErrorStr));
+  return XENSTORE_STATUS_EINVAL;
+}
+
+/**
+  Block waiting for a reply to a message request.
+
+  @param TypePtr The returned type of the reply.
+  @param LenPtr  The returned body length of the reply.
+  @param Result  The returned body of the reply.
+**/
+STATIC
+VOID
+XenStoreReadReply (
+  OUT enum xsd_sockmsg_type *TypePtr,
+  OUT UINT32 *LenPtr OPTIONAL,
+  OUT VOID **Result
+  )
+{
+  XENSTORE_MESSAGE *Message;
Quoted 8 lines

OvmfPkg/XenBusDxe/XenStore.c line 710

Quoted 5 lines
OvmfPkg/XenBusDxe/XenStore.c new file +5 -0
+  LIST_ENTRY *Entry;
+  CHAR8 *Body;
+
+  while (IsListEmpty (&xs.ReplyList)) {
+    XenStoreProcessMessage ();

You ignore the return value it gives you. Should there be a check for that and if there is an issue throttle down the spinning?

I can't really throttle down here. But I should check for "hardware" error, and return an error as well, maybe.

Quoted 212 lines
Quoted 212 lines
OvmfPkg/XenBusDxe/XenStore.c new file +212 -0
+  }
+  EfiAcquireLock (&xs.ReplyLock);
+  Entry = GetFirstNode (&xs.ReplyList);
+  Message = XENSTORE_MESSAGE_FROM_LINK (Entry);
+  RemoveEntryList (Entry);
+  EfiReleaseLock (&xs.ReplyLock);
+
+  *TypePtr = Message->Header.type;
+  if (LenPtr != NULL) {
+    *LenPtr = Message->Header.len;
+  }
+  Body = Message->u.Reply.Body;
+
+  FreePool (Message);
+  *Result = Body;
+}
+
+/**
+  Send a message with an optionally muti-part body to the XenStore service.
+
+  @param Transaction    The transaction to use for this request.
+  @param RequestType    The type of message to send.
+  @param WriteRequest   Pointers to the body sections of the request.
+  @param NumRequests    The number of body sections in the request.
+  @param LenPtr         The returned length of the reply.
+  @param ResultPtr      The returned body of the reply.
+
+  @return  XENSTORE_STATUS_SUCCESS on success.  Otherwise an errno indicating
+           the cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreTalkv (
+  IN  XENSTORE_TRANSACTION    Transaction,
+  IN  enum xsd_sockmsg_type   RequestType,
+  IN  CONST WRITE_REQUEST     *WriteRequest,
+  IN  UINT32                  NumRequests,
+  OUT UINT32                  *LenPtr OPTIONAL,
+  OUT VOID                    **ResultPtr OPTIONAL
+  )
+{
+  struct xsd_sockmsg Message;
+  void *Return = NULL;
+  UINT32 Index;
+  XENSTORE_STATUS Status;
+
+  Message.tx_id = Transaction.Id;
+  Message.req_id = 0;
+  Message.type = RequestType;
+  Message.len = 0;
+  for (Index = 0; Index < NumRequests; Index++) {
+    Message.len += WriteRequest[Index].Len;
+  }
+
+  Status = XenStoreWriteStore (&Message, sizeof (Message));
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenStoreTalkv failed %d\n", Status));
+    goto Error;
+  }
+
+  for (Index = 0; Index < NumRequests; Index++) {
+    Status = XenStoreWriteStore (WriteRequest[Index].Data, WriteRequest[Index].Len);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      DEBUG ((EFI_D_ERROR, "XenStoreTalkv failed %d\n", Status));
+      goto Error;
+    }
+  }
+
+  XenStoreReadReply (&Message.type, LenPtr, &Return);
+
+Error:
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+
+  if (Message.type == XS_ERROR) {
+    Status = XenStoreGetError (Return);
+    FreePool (Return);
+    return Status;
+  }
+
+  /* Reply is either error or an echo of our request message type. */
+  ASSERT (Message.type == RequestType);
+
+  if (ResultPtr) {
+    *ResultPtr = Return;
+  } else {
+    FreePool (Return);
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+/**
+  Wrapper for XenStoreTalkv allowing easy transmission of a message with
+  a single, contiguous, message body.
+
+  The returned result is provided in malloced storage and thus must be free'd
+  by the caller.
+
+  @param Transaction    The transaction to use for this request.
+  @param RequestType    The type of message to send.
+  @param Body           The body of the request.
+  @param LenPtr         The returned length of the reply.
+  @param Result         The returned body of the reply.
+
+  @return  0 on success.  Otherwise an errno indicating
+           the cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreSingle (
+  IN  XENSTORE_TRANSACTION    Transaction,
+  IN  enum xsd_sockmsg_type   RequestType,
+  IN  CONST CHAR8             *Body,
+  OUT UINT32                  *LenPtr OPTIONAL,
+  OUT VOID                    **Result OPTIONAL
+  )
+{
+  WRITE_REQUEST WriteRequest;
+
+  WriteRequest.Data = (VOID *) Body;
+  WriteRequest.Len = AsciiStrSize (Body);
+
+  return XenStoreTalkv (Transaction, RequestType, &WriteRequest, 1,
+                        LenPtr, Result);
+}
+
+//
+// XenStore Watch Support
+//
+
+/**
+  Transmit a watch request to the XenStore service.
+
+  @param Path    The path in the XenStore to watch.
+  @param Tocken  A unique identifier for this watch.
+
+  @return  XENSTORE_STATUS_SUCCESS on success.  Otherwise an errno indicating the
+           cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreWatch (
+  CONST CHAR8 *Path,
+  CONST CHAR8 *Token
+  )
+{
+  WRITE_REQUEST WriteRequest[2];
+
+  WriteRequest[0].Data = (VOID *) Path;
+  WriteRequest[0].Len = AsciiStrSize (Path);
+  WriteRequest[1].Data = (VOID *) Token;
+  WriteRequest[1].Len = AsciiStrSize (Token);
+
+  return XenStoreTalkv (XST_NIL, XS_WATCH, WriteRequest, 2, NULL, NULL);
+}
+
+/**
+  Transmit an uwatch request to the XenStore service.
+
+  @param Path    The path in the XenStore to watch.
+  @param Tocken  A unique identifier for this watch.
+
+  @return  XENSTORE_STATUS_SUCCESS on success.  Otherwise an errno indicating
+           the cause of failure.
+**/
+STATIC
+XENSTORE_STATUS
+XenStoreUnwatch (
+  CONST CHAR8 *Path,
+  CONST CHAR8 *Token
+  )
+{
+  WRITE_REQUEST WriteRequest[2];
+
+  WriteRequest[0].Data = (VOID *) Path;
+  WriteRequest[0].Len = AsciiStrSize (Path);
+  WriteRequest[1].Data = (VOID *) Token;
+  WriteRequest[1].Len = AsciiStrSize (Token);
+
+  return XenStoreTalkv (XST_NIL, XS_UNWATCH, WriteRequest, 2, NULL, NULL);
+}
+
+VOID
+EFIAPI
+NotifyEventChannelCheckForEvent (
+  IN EFI_EVENT Event,
+  IN VOID *Context
+  )
+{
+  XENSTORE_PRIVATE *xs;
+  xs = (XENSTORE_PRIVATE *)Context;
+  if (TestAndClearBit (xs->EventChannel, xs->Dev->SharedInfo->evtchn_pending)) {
+    gBS->SignalEvent (Event);
+  }
+}
+
+/**
+  Setup communication channels with the XenStore service.
+
+  @retval EFI_SUCCESS if everything went well.
+**/
+STATIC
+EFI_STATUS
+XenStoreInitComms (
+  XENSTORE_PRIVATE *xs
+  )
+{
+  EFI_STATUS Status;
+  struct xenstore_domain_interface *XenStore = xs->XenStore;
+
Quoted 8 lines

OvmfPkg/XenBusDxe/XenStore.c line 928

Quoted 6 lines
OvmfPkg/XenBusDxe/XenStore.c new file +6 -0
+  if (XenStore->rsp_prod != XenStore->rsp_cons) {
+    DEBUG ((EFI_D_WARN, "XENSTORE response ring is not quiescent "
+            "(%08x:%08x): fixing up\n",
+            XenStore->rsp_cons, XenStore->rsp_prod));
+    XenStore->rsp_cons = XenStore->rsp_prod;
+  }

Perhaps that should be in a while loop in case it takes longer to become quiet?

OK, that can be done.

Quoted 150 lines
Quoted 137 lines
OvmfPkg/XenBusDxe/XenStore.c new file +137 -0
+
+  Status = gBS->CreateEvent (EVT_NOTIFY_WAIT, TPL_NOTIFY,
+                             NotifyEventChannelCheckForEvent, xs,
+                             &xs->EventChannelEvent);
+  ASSERT_EFI_ERROR (Status);
+
+  return Status;
+}
+
+/**
+  Initialize XenStore.
+
+  @param Dev  A XENBUS_DEVICE instance.
+
+  @retval EFI_SUCCESS if everything went well.
+**/
+EFI_STATUS
+XenStoreInit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  EFI_STATUS Status;
+  /**
+   * The HVM guest pseudo-physical frame number.  This is Xen's mapping
+   * of the true machine frame number into our "physical address space".
+   */
+  UINTN XenStoreGpfn;
+
+  xs.Dev = Dev;
+
+  xs.EventChannel = XenHypercallHvmGetParam (Dev, HVM_PARAM_STORE_EVTCHN);
+  XenStoreGpfn = XenHypercallHvmGetParam (Dev, HVM_PARAM_STORE_PFN);
+  xs.XenStore = (VOID *) (XenStoreGpfn << EFI_PAGE_SHIFT);
+  DEBUG ((EFI_D_INFO, "XenBusInit: XenBus rings @%p, event channel %x\n",
+          xs.XenStore, xs.EventChannel));
+
+  InitializeListHead (&xs.ReplyList);
+  InitializeListHead (&xs.WatchEvents);
+  InitializeListHead (&xs.RegisteredWatches);
+
+  EfiInitializeLock (&xs.ReplyLock, TPL_NOTIFY);
+  EfiInitializeLock (&xs.RegisteredWatchesLock, TPL_NOTIFY);
+  EfiInitializeLock (&xs.WatchEventsLock, TPL_NOTIFY);
+
+  /* Initialize the shared memory rings to talk to xenstored */
+  Status = XenStoreInitComms (&xs);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  return Status;
+}
+
+VOID
+XenStoreDeinit (
+  IN XENBUS_DEVICE *Dev
+  )
+{
+  //
+  // Emptying the list RegisteredWatches, but this list should already be
+  // empty. Every driver that is using Watches should unregister them when
+  // it is stopped.
+  //
+  if (!IsListEmpty (&xs.RegisteredWatches)) {
+    XENSTORE_WATCH *Watch;
+    LIST_ENTRY *Entry;
+    DEBUG ((EFI_D_WARN, "XenStore: RegisteredWatches is not empty, cleaning up..."));
+    Entry = GetFirstNode (&xs.RegisteredWatches);
+    while (!IsNull (&xs.RegisteredWatches, Entry)) {
+      Watch = XENSTORE_WATCH_FROM_LINK (Entry);
+      Entry = GetNextNode (&xs.RegisteredWatches, Entry);
+
+      XenStoreUnregisterWatch (Watch);
+    }
+  }
+
+  //
+  // Emptying the list WatchEvents, but this list should already be empty after
+  // having cleanup the list RegisteredWatches.
+  //
+  if (!IsListEmpty (&xs.WatchEvents)) {
+    LIST_ENTRY *Entry;
+    DEBUG ((EFI_D_WARN, "XenStore: WatchEvents is not empty, cleaning up..."));
+    Entry = GetFirstNode (&xs.WatchEvents);
+    while (!IsNull (&xs.WatchEvents, Entry)) {
+      XENSTORE_MESSAGE *Message = XENSTORE_MESSAGE_FROM_LINK (Entry);
+      Entry = GetNextNode (&xs.WatchEvents, Entry);
+      RemoveEntryList (&Message->Link);
+      FreePool (Message->u.Watch.Vector);
+      FreePool (Message);
+    }
+  }
+
+  if (!IsListEmpty (&xs.ReplyList)) {
+    XENSTORE_MESSAGE *Message;
+    LIST_ENTRY *Entry;
+    Entry = GetFirstNode (&xs.ReplyList);
+    while (!IsNull (&xs.ReplyList, Entry)) {
+      Message = XENSTORE_MESSAGE_FROM_LINK (Entry);
+      Entry = GetNextNode (&xs.ReplyList, Entry);
+      RemoveEntryList (&Message->Link);
+      FreePool (Message->u.Reply.Body);
+      FreePool (Message);
+    }
+  }
+
+  gBS->CloseEvent (xs.EventChannelEvent);
+
+  //
+  // We zero out the whole ring -- the backend can handle this, and it's
+  // not going to surprise any frontends since it's equivalent to never
+  // having used the rings.
+  //
+  ZeroMem (xs.XenStore, sizeof (struct xenstore_domain_interface));
+  xs.XenStore = NULL;
+}
+
+//
+// Public API
+// API comments for these methods can be found in XenStore.h
+//
+
+XENSTORE_STATUS
+XenStoreListDirectory (
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *DirectoryPath,
+  IN  CONST CHAR8           *Node,
+  OUT UINT32                *DirectoryCountPtr,
+  OUT CONST CHAR8           ***DirectoryListPtr
+  )
+{
+  CHAR8 *Path;
+  CHAR8 *TempStr;
+  UINT32 Len = 0;
+  XENSTORE_STATUS Status;
+
+  Path = XenStoreJoin (DirectoryPath, Node);

OvmfPkg/XenBusDxe/XenStore.c line 1075

Quoted 10 lines
OvmfPkg/XenBusDxe/XenStore.c new file +10 -0
+  Status = XenStoreSingle (Transaction, XS_DIRECTORY, Path, &Len,
+                           (VOID **) &TempStr);
+  FreePool (Path);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+
+  *DirectoryListPtr = Split (TempStr, Len, DirectoryCountPtr);
+
+  return (0);

Shouldn't that be one of the XENSTORE .. enums?

Quoted 1 line
	return XENSTORE_STATUS_SUCCESS;

Yes, will fix.

Quoted 551 lines
Quoted 551 lines
OvmfPkg/XenBusDxe/XenStore.c new file +245 -0
+}
+
+BOOLEAN
+XenStorePathExists (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8           *Directory,
+  IN CONST CHAR8           *Node
+  )
+{
+  CONST CHAR8 **TempStr;
+  XENSTORE_STATUS Status;
+  UINT32 TempNum;
+
+  Status = XenStoreListDirectory (Transaction, Directory, Node,
+                                  &TempNum, &TempStr);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return FALSE;
+  }
+  FreePool (TempStr);
+  return TRUE;
+}
+
+XENSTORE_STATUS
+XenStoreRead (
+  IN  XENSTORE_TRANSACTION    Transaction,
+  IN  CONST CHAR8             *DirectoryPath,
+  IN  CONST CHAR8             *Node,
+  OUT UINT32                  *LenPtr OPTIONAL,
+  OUT VOID                    **Result
+  )
+{
+  CHAR8 *Path;
+  VOID *Value;
+  XENSTORE_STATUS Status;
+
+  Path = XenStoreJoin (DirectoryPath, Node);
+  Status = XenStoreSingle (Transaction, XS_READ, Path, LenPtr, &Value);
+  FreePool (Path);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+
+  *Result = Value;
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+XENSTORE_STATUS
+XenStoreWrite (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8           *DirectoryPath,
+  IN CONST CHAR8           *Node,
+  IN CONST CHAR8           *Str
+  )
+{
+  CHAR8 *Path;
+  WRITE_REQUEST WriteRequest[2];
+  XENSTORE_STATUS Status;
+
+  Path = XenStoreJoin (DirectoryPath, Node);
+
+  WriteRequest[0].Data = (VOID *) Path;
+  WriteRequest[0].Len = AsciiStrSize (Path);
+  WriteRequest[1].Data = (VOID *) Str;
+  WriteRequest[1].Len = AsciiStrLen (Str);
+
+  Status = XenStoreTalkv (Transaction, XS_WRITE, WriteRequest, 2, NULL, NULL);
+  FreePool (Path);
+
+  return Status;
+}
+
+XENSTORE_STATUS
+XenStoreRemove (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node
+  )
+{
+  CHAR8 *Path;
+  XENSTORE_STATUS Status;
+
+  Path = XenStoreJoin (DirectoryPath, Node);
+  Status = XenStoreSingle (Transaction, XS_RM, Path, NULL, NULL);
+  FreePool (Path);
+
+  return Status;
+}
+
+XENSTORE_STATUS
+XenStoreTransactionStart (
+  OUT XENSTORE_TRANSACTION  *Transaction
+  )
+{
+  CHAR8 *IdStr;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreSingle (XST_NIL, XS_TRANSACTION_START, "", NULL,
+                           (VOID **) &IdStr);
+  if (Status == XENSTORE_STATUS_SUCCESS) {
+    Transaction->Id = AsciiStrDecimalToUintn (IdStr);
+    FreePool (IdStr);
+  }
+
+  return Status;
+}
+
+XENSTORE_STATUS
+XenStoreTransactionEnd (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN BOOLEAN                Abort
+  )
+{
+  CHAR8 AbortStr[2];
+
+  if (Abort) {
+    AsciiStrCpy (AbortStr, "F");
+  } else {
+    AsciiStrCpy (AbortStr, "T");
+  }
+
+  return XenStoreSingle (Transaction, XS_TRANSACTION_END, AbortStr, NULL, NULL);
+}
+
+XENSTORE_STATUS
+XenStoreVSPrint (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8           *DirectoryPath,
+  IN CONST CHAR8           *Node,
+  IN CONST CHAR8           *FormatString,
+  IN VA_LIST               Marker
+  )
+{
+  CHAR8 *Buf;
+  XENSTORE_STATUS Status;
+  UINTN BufSize;
+
+  BufSize = SPrintLengthAsciiFormat (FormatString, Marker) + 1;
+  Buf = AllocateZeroPool (BufSize);
+  AsciiVSPrint (Buf, BufSize, FormatString, Marker);
+  Status = XenStoreWrite (Transaction, DirectoryPath, Node, Buf);
+  FreePool (Buf);
+
+  return Status;
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenStoreSPrint (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node,
+  IN CONST CHAR8            *FormatString,
+  ...
+  )
+{
+  VA_LIST Marker;
+  XENSTORE_STATUS Status;
+
+  VA_START (Marker, FormatString);
+  Status = XenStoreVSPrint (Transaction, DirectoryPath, Node, FormatString, Marker);
+  VA_END (Marker);
+
+  return Status;
+}
+
+XENSTORE_STATUS
+XenStoreRegisterWatch (
+  IN CONST CHAR8      *DirectoryPath,
+  IN CONST CHAR8      *Node,
+  OUT XENSTORE_WATCH  **WatchPtr
+  )
+{
+  /* Pointer in ascii is the token. */
+  CHAR8 Token[sizeof (XENSTORE_WATCH) * 2 + 1];
+  XENSTORE_STATUS Status;
+  XENSTORE_WATCH *Watch;
+
+  Watch = AllocateZeroPool (sizeof (XENSTORE_WATCH));
+  Watch->Signature = XENSTORE_WATCH_SIGNATURE;
+  Watch->Node = XenStoreJoin (DirectoryPath, Node);
+
+  EfiAcquireLock (&xs.RegisteredWatchesLock);
+  InsertTailList (&xs.RegisteredWatches, &Watch->Link);
+  EfiReleaseLock (&xs.RegisteredWatchesLock);
+
+  AsciiSPrint (Token, sizeof (Token), "%p", (VOID*) Watch);
+  Status = XenStoreWatch (Watch->Node, Token);
+
+  /* Ignore errors due to multiple registration. */
+  if (Status == XENSTORE_STATUS_EEXIST) {
+    Status = XENSTORE_STATUS_SUCCESS;
+  }
+
+  if (Status == XENSTORE_STATUS_SUCCESS) {
+    *WatchPtr = Watch;
+  } else {
+    EfiAcquireLock (&xs.RegisteredWatchesLock);
+    RemoveEntryList (&Watch->Link);
+    EfiReleaseLock (&xs.RegisteredWatchesLock);
+    FreePool (Watch->Node);
+    FreePool (Watch);
+  }
+
+  return Status;
+}
+
+VOID
+XenStoreUnregisterWatch (
+  IN XENSTORE_WATCH *Watch
+  )
+{
+  CHAR8 Token[sizeof (Watch) * 2 + 1];
+  XENSTORE_STATUS Status;
+  LIST_ENTRY *Entry;
+
+  ASSERT (Watch->Signature == XENSTORE_WATCH_SIGNATURE);
+
+  AsciiSPrint (Token, sizeof (Token), "%p", (VOID *) Watch);
+  if (XenStoreFindWatch (Token) == NULL) {
+    return;
+  }
+
+  EfiAcquireLock (&xs.RegisteredWatchesLock);
+  RemoveEntryList (&Watch->Link);
+  EfiReleaseLock (&xs.RegisteredWatchesLock);
+
+  Status = XenStoreUnwatch (Watch->Node, Token);
+
+  /* Cancel pending watch events. */
+  EfiAcquireLock (&xs.WatchEventsLock);
+  Entry = GetFirstNode (&xs.WatchEvents);
+  while (!IsNull (&xs.WatchEvents, Entry)) {
+    XENSTORE_MESSAGE *Message = XENSTORE_MESSAGE_FROM_LINK (Entry);
+    Entry = GetNextNode (&xs.WatchEvents, Entry);
+    if (Message->u.Watch.Handle == Watch) {
+      RemoveEntryList (&Message->Link);
+      FreePool (Message->u.Watch.Vector);
+      FreePool (Message);
+    }
+  }
+  EfiReleaseLock (&xs.WatchEventsLock);
+
+  FreePool (Watch->Node);
+  FreePool (Watch);
+}
OvmfPkg/XenBusDxe/XenStore.h new file +292 -0
new file mode 100644
index 0000000..2902e3f
@@ -0,0 +1,292 @@
+/** @file
+  Method declarations and structures for accessing the XenStore
+
+  Copyright (C) 2005 Rusty Russell, IBM Corporation
+  Copyright (C) 2005 XenSource Ltd.
+  Copyright (C) 2009,2010 Spectra Logic Corporation
+  Copyright (C) 2014, Citrix Ltd.
+
+  This file may be distributed separately from the Linux kernel, or
+  incorporated into other software packages, subject to the following license:
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this source file (the "Software"), to deal in the Software without
+  restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software,
+  and to permit persons to whom the Software is furnished to do so, subject to
+  the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+  IN THE SOFTWARE.
+**/
+
+#ifndef _XEN_XENSTORE_XENSTOREVAR_H
+#define _XEN_XENSTORE_XENSTOREVAR_H
+
+#include "XenBusDxe.h"
+
+#include <IndustryStandard/Xen/io/xs_wire.h>
+
+typedef struct _XENSTORE_WATCH XENSTORE_WATCH;
+
+/**
+  Fetch the contents of a directory in the XenStore.
+
+  @param Transaction        The XenStore transaction covering this request.
+  @param DirectoryPath      The dirname of the path to read.
+  @param Node               The basename of the path to read.
+  @param DirectoryCountPtr  The returned number of directory entries.
+  @param DirectoryListPtr   An array of directory entry strings.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+
+  @note The results buffer is alloced and should be free'd by the
+        caller.
+**/
+XENSTORE_STATUS
+XenStoreListDirectory (
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *DirectoryPath,
+  IN  CONST CHAR8           *Node,
+  OUT UINT32                *DirectoryCountPtr,
+  OUT CONST CHAR8           ***DirectoryListPtr
+  );
+
+/**
+  Determine if a path exists in the XenStore.
+
+  @param Transaction  The XenStore transaction covering this request.
+  @param Directory    The dirname of the path to read.
+  @param Node         The basename of the path to read.
+
+  @retval TRUE  The path exists.
+  @retval FALSE The path does not exist or an error occurred attempting
+                to make that determination.
+**/
+BOOLEAN
+XenStorePathExists (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8 *Directory,
+  IN CONST CHAR8 *Node
+  );
+
+/**
+  Get the contents of a single "file".  Returns the contents in
+  *result which should be freed with free(*result, M_XENSTORE) after
+  use.  The length of the value in bytes is returned in *len.
+
+  @param Transaction    The XenStore transaction covering this request.
+  @param DirectoryPath  The dirname of the file to read.
+  @param Node           The basename of the file to read.
+  @param LenPtr         The amount of data read.
+  @param Result         The returned contents from this file.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+
+  @note The results buffer is malloced and should be free'd by the
+        caller.
+**/
+XENSTORE_STATUS
+XenStoreRead (
+  IN  XENSTORE_TRANSACTION    Transaction,
+  IN  CONST CHAR8             *DirectoryPath,
+  IN  CONST CHAR8             *Node,
+  OUT UINT32                  *LenPtr OPTIONAL,
+  OUT VOID                    **Result
+  );
+
+/**
+  Write to a single file.
+
+  @param Transaction    The XenStore transaction covering this request.
+  @param DirectoryPath  The dirname of the file to write.
+  @param Node           The basename of the file to write.
+  @param Str            The NUL terminated string of data to write.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenStoreWrite (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8           *DirectoryPath,
+  IN CONST CHAR8           *Node,
+  IN CONST CHAR8           *Str
+  );
+
+/**
+  Remove a file or directory (directories must be empty).
+
+  @param Transaction    The XenStore transaction covering this request.
+  @param DirectoryPath  The dirname of the directory to remove.
+  @param Node           The basename of the directory to remove.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenStoreRemove (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node
+  );
+
+/**
+  Start a transaction.
+
+  Changes by others will not be seen during the lifetime of this
+  transaction, and changes will not be visible to others until it
+  is committed (xs_transaction_end).
+
+  @param Transaction  The returned transaction.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenStoreTransactionStart (
+  OUT XENSTORE_TRANSACTION  *Transaction
+  );
+
+/**
+  End a transaction.
+
+  @param Transaction  The transaction to end/commit.
+  @param Abort        If TRUE, the transaction is discarded
+                      instead of committed.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenStoreTransactionEnd (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN BOOLEAN                Abort
+  );
+
+/**
+  Printf formatted write to a XenStore file.
+
+  @param Transaction      The XenStore transaction covering this request.
+  @param DirectoryPath    The dirname of the path to read.
+  @param Node             The basename of the path to read.
+  @param FormatString     AsciiSPrint format string followed by a variable number
+                          of arguments.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of write failure.
+**/
+XENSTORE_STATUS
+EFIAPI
+XenStoreSPrint (
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node,
+  IN CONST CHAR8            *FormatString,
+  ...
+  );
+
+/**
+  VA_LIST version of XenStoreSPrint().
+
+  @param Transaction    The XenStore transaction covering this request.
+  @param DirectoryPath  The dirname of the path to read.
+  @param Node           The basename of the path to read.
+  @param FormatString   Printf format string.
+  @param Marker         VA_LIST of printf arguments.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of write failure.
+**/
+XENSTORE_STATUS
+XenStoreVSPrint (
+  IN XENSTORE_TRANSACTION  Transaction,
+  IN CONST CHAR8           *DirectoryPath,
+  IN CONST CHAR8           *Node,
+  IN CONST CHAR8           *FormatString,
+  IN VA_LIST               Marker
+  );
+
+/**
+  Register a XenStore watch.
+
+  XenStore watches allow a client to be notified via a callback (embedded
+  within the watch object) of changes to an object in the XenStore.
+
+  @param DirectoryPath  The dirname of the path to watch.
+  @param Node           The basename of the path to watch.
+  @param WatchPtr       A returned XENSTORE_WATCH pointer.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of write failure.  EEXIST errors from the
+           XenStore are supressed, allowing multiple, physically different,
+           xenbus_watch objects, to watch the same path in the XenStore.
+**/
+XENSTORE_STATUS
+XenStoreRegisterWatch (
+  IN  CONST CHAR8     *DirectoryPath,
+  IN  CONST CHAR8     *Node,
+  OUT XENSTORE_WATCH  **WatchPtr
+  );
+
+/**
+  Unregister a XenStore watch.
+
+  @param Watch  An XENSTORE_WATCH object previously returned by a successful
+                call to XenStoreRegisterWatch ().
+**/
+VOID
+XenStoreUnregisterWatch (
+  IN XENSTORE_WATCH *Watch
+  );
+
+/**
+  Allocate and return the XenStore path string <DirectoryPath>/<Node>.  If name
+  is the NUL string, the returned value contains the path string
+  <DirectoryPath>.
+
+  @param DirectoryPath	The NUL terminated directory prefix for new path.
+  @param Node           The NUL terminated basename for the new path.
+
+  @return  A buffer containing the joined path.
+ */
+CHAR8 *
+XenStoreJoin (
+  IN CONST CHAR8 *DirectoryPath,
+  IN CONST CHAR8 *Node
+  );
+
+
+/**
+  Initialize the XenStore states and rings.
+
+  @param Dev  A pointer to a XENBUS_DEVICE instance.
+
+  @return     EFI_SUCCESS if everything went smoothly.
+**/
+EFI_STATUS
+XenStoreInit (
+  XENBUS_DEVICE *Dev
+  );
+
+/**
+  Deinitialize the XenStore states and rings.
+
+  @param Dev  A pointer to a XENBUS_DEVICE instance.
+**/
+VOID
+XenStoreDeinit (
+  IN XENBUS_DEVICE *Dev
+  );
+
+#endif /* _XEN_XENSTORE_XENSTOREVAR_H */
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Signature · 1 line
Anthony PERARD

A message that is not in the archive (sent off-list or not yet received): [email protected]

#54 lore raw

Re: [PATCH v2 12/18] OvmfPkg/XenBusDxe: Add an helper AsciiStrDup.

Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

.. because we need it in the patch titled: "Indroduce XenBus support itself".

right? Please add that in the commit description, and with that you can add Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>

Quoted 43 lines
---
 OvmfPkg/XenBusDxe/Helpers.c   | 9 +++++++++
 OvmfPkg/XenBusDxe/XenBusDxe.h | 5 +++++
 2 files changed, 14 insertions(+)
 create mode 100644 OvmfPkg/XenBusDxe/Helpers.c
OvmfPkg/XenBusDxe/Helpers.c new file +9 -0
new file mode 100644
index 0000000..3e938b6
@@ -0,0 +1,9 @@
+#include "XenBusDxe.h"
+
+CHAR8*
+AsciiStrDup (
+  IN CONST CHAR8* Str
+  )
+{
+  return AllocateCopyPool (AsciiStrSize (Str), Str);
+}
OvmfPkg/XenBusDxe/XenBusDxe.h +5 -0
index d690914..dc48a46 100644
@@ -132,4 +132,9 @@ TestAndClearBit (
   IN volatile VOID *Address
   );
 
+CHAR8*
+AsciiStrDup (
+  IN CONST CHAR8* Str
+  );
+
 #endif
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

A message that is not in the archive (sent off-list or not yet received): [email protected]

#56 lore raw

Re: [PATCH v2 13/18] OvmfPkg/XenBusDxe: Add XenStore function into the XenBus protocol

Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

Quoted 416 lines
---
 OvmfPkg/Include/Protocol/XenBus.h | 103 ++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenStore.c      | 160 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenStore.h      |  87 +++++++++++++++++++++
 3 files changed, 350 insertions(+)
OvmfPkg/Include/Protocol/XenBus.h +103 -0
index b10c143..99e174b 100644
@@ -81,6 +81,62 @@ typedef enum {
 /// Function prototypes
 ///
 
+/*
+ * Return error from xs_read
+ * Return value of the node ${This->Node}/${node}
+ */
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_READ)(
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Result
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_BACKEND_READ)(
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Result
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_PRINTF) (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *Directory,
+  IN CONST CHAR8            *Node,
+  IN CONST CHAR8            *Format,
+  ...
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_REMOVE) (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *Node
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_TRANSACTION_START)(
+  IN  XENBUS_PROTOCOL       *This,
+  OUT XENSTORE_TRANSACTION  *Transaction
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_XS_TRANSACTION_END) (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN BOOLEAN                Abort
+  );
+
 typedef
 EFI_STATUS
 (EFIAPI *XENBUS_GRANT_ACCESS)(
@@ -98,16 +154,63 @@ EFI_STATUS
   IN grant_ref_t      Ref
   );
 
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_REGISTER_WATCH) (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  // XENSTORE_WATCH ?
+  OUT VOID            **Token
+  );
+
+typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_REGISTER_WATCH_BACKEND) (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  OUT VOID            **Token
+  );
+
+typedef
+VOID
+(EFIAPI *XENBUS_UNREGISTER_WATCH) (
+  IN XENBUS_PROTOCOL  *This,
+  IN VOID             *Token
+  );
+
+typedef
+VOID
+(EFIAPI *XENBUS_WAIT_FOR_WATCH) (
+  IN XENBUS_PROTOCOL  *This,
+  IN VOID             *Token
+  );
+
 
 ///
 /// Protocol structure
 ///
 struct _XENBUS_PROTOCOL {
+  XENBUS_XS_READ                XsRead;
+  XENBUS_XS_BACKEND_READ        XsBackendRead;
+  XENBUS_XS_PRINTF              XsPrintf;
+  XENBUS_XS_REMOVE              XsRemove;
+  XENBUS_XS_TRANSACTION_START   XsTransactionStart;
+  XENBUS_XS_TRANSACTION_END     XsTransactionEnd;
+
   XENBUS_GRANT_ACCESS           GrantAccess;
   XENBUS_GRANT_END_ACCESS       GrantEndAccess;
+
+  XENBUS_REGISTER_WATCH         RegisterWatch;
+  XENBUS_REGISTER_WATCH_BACKEND RegisterWatchBackend;
+  XENBUS_UNREGISTER_WATCH       UnregisterWatch;
+  XENBUS_WAIT_FOR_WATCH         WaitForWatch;
   //
   // Protocol data fields
   //
+  CONST CHAR8                   *Type;
+  UINT16                        DeviceId;
+  CONST CHAR8                   *Node;
+  CONST CHAR8                   *Backend;
 };
 
 extern EFI_GUID gXenBusProtocolGuid;
OvmfPkg/XenBusDxe/XenStore.c +160 -0
index bcf6e1c..d828c06 100644
@@ -892,6 +892,42 @@ XenStoreUnwatch (
   return XenStoreTalkv (XST_NIL, XS_UNWATCH, WriteRequest, 2, NULL, NULL);
 }
 
+STATIC
+VOID
+XenStoreWaitWatch (
+  VOID *Token
+  )
+{
+  XENSTORE_MESSAGE *Message;
+  LIST_ENTRY *Entry = NULL;
+  LIST_ENTRY *Last = NULL;
+
+  while (TRUE) {
+    EfiAcquireLock (&xs.WatchEventsLock);
+    if (IsListEmpty (&xs.WatchEvents) ||
+        Last == GetFirstNode (&xs.WatchEvents)) {
+      EfiReleaseLock (&xs.WatchEventsLock);
+      XenStoreProcessMessage ();
+      continue;
+    }
+
+    for (Entry = GetFirstNode (&xs.WatchEvents);
+         Entry != Last && !IsNull (&xs.WatchEvents, Entry);
+         Entry = GetNextNode (&xs.WatchEvents, Entry)) {
+      Message = XENSTORE_MESSAGE_FROM_LINK (Entry);
+      if (Message->u.Watch.Handle == Token) {
+        RemoveEntryList (Entry);
+        EfiReleaseLock (&xs.WatchEventsLock);
+        FreePool(Message->u.Watch.Vector);
+        FreePool(Message);
+        return;
+      }
+    }
+    Last = GetFirstNode (&xs.WatchEvents);
+    EfiReleaseLock (&xs.WatchEventsLock);
+  }
+}
+
 VOID
 EFIAPI
 NotifyEventChannelCheckForEvent (
@@ -1318,3 +1354,127 @@ XenStoreUnregisterWatch (
   FreePool (Watch->Node);
   FreePool (Watch);
 }
+
+
+//
+// XENBUS protocol
+//
+
+VOID
+EFIAPI
+XenBusWaitForWatch (
+  IN XENBUS_PROTOCOL *This,
+  IN VOID *Token
+  )
+{
+  XenStoreWaitWatch (Token);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreRead (
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Value
+  )
+{
+  return XenStoreRead (Transaction, This->Node, Node, NULL, Value);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreBackendRead (
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Value
+  )
+{
+  return XenStoreRead (Transaction, This->Backend, Node, NULL, Value);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreRemove (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN const char             *Node
+  )
+{
+  return XenStoreRemove (Transaction, This->Node, Node);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreTransactionStart (
+  IN  XENBUS_PROTOCOL       *This,
+  OUT XENSTORE_TRANSACTION  *Transaction
+  )
+{
+  return XenStoreTransactionStart (Transaction);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreTransactionEnd (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN BOOLEAN                Abort
+  )
+{
+  return XenStoreTransactionEnd (Transaction, Abort);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreSPrint (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node,
+  IN CONST CHAR8            *FormatString,
+  ...
+  )
+{
+  VA_LIST Marker;
+  XENSTORE_STATUS Status;
+
+  VA_START (Marker, FormatString);
+  Status = XenStoreVSPrint (Transaction, DirectoryPath, Node, FormatString, Marker);
+  VA_END (Marker);
+
+  return Status;
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusRegisterWatch (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  OUT VOID            **Token
+  )
+{
+  return XenStoreRegisterWatch (This->Node, Node, (XENSTORE_WATCH **) Token);
+}
+
+XENSTORE_STATUS
+EFIAPI
+XenBusRegisterWatchBackend (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  OUT VOID            **Token
+  )
+{
+  return XenStoreRegisterWatch (This->Backend, Node, (XENSTORE_WATCH **) Token);
+}
+
+VOID
+EFIAPI
+XenBusUnregisterWatch (
+  IN XENBUS_PROTOCOL  *This,
+  IN VOID             *Token
+  )
+{
+  XenStoreUnregisterWatch ((XENSTORE_WATCH *) Token);
+}
OvmfPkg/XenBusDxe/XenStore.h +87 -0
index 2902e3f..5d1a6b3 100644
@@ -289,4 +289,91 @@ XenStoreDeinit (
   IN XENBUS_DEVICE *Dev
   );
 
+
+//
+// XENBUS protocol
+//
+
+VOID
+EFIAPI
+XenBusWaitForWatch (
+  IN XENBUS_PROTOCOL *This,
+  IN VOID *Token
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreRead (
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Value
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreBackendRead (
+  IN  XENBUS_PROTOCOL       *This,
+  IN  XENSTORE_TRANSACTION  Transaction,
+  IN  CONST CHAR8           *Node,
+  OUT VOID                  **Value
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreRemove (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *Node
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreTransactionStart (
+  IN  XENBUS_PROTOCOL       *This,
+  OUT XENSTORE_TRANSACTION  *Transaction
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreTransactionEnd (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN BOOLEAN                Abort
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusXenStoreSPrint (
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN CONST CHAR8            *DirectoryPath,
+  IN CONST CHAR8            *Node,
+  IN CONST CHAR8            *FormatString,
+  ...
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusRegisterWatch (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  OUT VOID            **Token
+  );
+
+XENSTORE_STATUS
+EFIAPI
+XenBusRegisterWatchBackend (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  OUT VOID            **Token
+  );
+
+VOID
+EFIAPI
+XenBusUnregisterWatch (
+  IN XENBUS_PROTOCOL  *This,
+  IN VOID             *Token
+  );
+
 #endif /* _XEN_XENSTORE_XENSTOREVAR_H */
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

A message that is not in the archive (sent off-list or not yet received): [email protected]

#58 lore raw

Re: [PATCH v2 14/18] OvmfPkg/XenBusDxe: Indroduce XenBus support itself.

Quoted 178 lines · Anthony PERARD

This is a bus-like on top of XenStore. It will look for advertised ParaVirtualized devices and initialize them by producing XenBus protocol.

Origin: FreeBSD 10.0

Contributed-under: TianoCore Contribution Agreement 1.0

---
Change in V2:
- comment, file header
- Fix comment style
- Error handling in the main init function
- coding style
- Fix error path in add device.

---
 OvmfPkg/Include/Protocol/XenBus.h |  11 +-
 OvmfPkg/XenBusDxe/XenBus.c        | 368 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenBus.h        |  67 +++++++
 OvmfPkg/XenBusDxe/XenBusDxe.c     |  71 ++++++++
 OvmfPkg/XenBusDxe/XenBusDxe.h     |  19 ++
 OvmfPkg/XenBusDxe/XenBusDxe.inf   |   3 +
 6 files changed, 538 insertions(+), 1 deletion(-)
 create mode 100644 OvmfPkg/XenBusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenBusDxe/XenBus.h
OvmfPkg/Include/Protocol/XenBus.h +10 -1
index 99e174b..f223be7 100644
@@ -45,7 +45,7 @@
 ///
 typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
 
-typedef enum xenbus_state XenbusState;
+typedef enum xenbus_state XenBusState;
 
 typedef struct
 {
@@ -138,6 +138,14 @@ XENSTORE_STATUS
   );
 
 typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_SET_STATE)(
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN XenBusState            State
+  );
+
+typedef
 EFI_STATUS
 (EFIAPI *XENBUS_GRANT_ACCESS)(
   IN  XENBUS_PROTOCOL *This,
@@ -196,6 +204,7 @@ struct _XENBUS_PROTOCOL {
   XENBUS_XS_REMOVE              XsRemove;
   XENBUS_XS_TRANSACTION_START   XsTransactionStart;
   XENBUS_XS_TRANSACTION_END     XsTransactionEnd;
+  XENBUS_SET_STATE              SetState;
 
   XENBUS_GRANT_ACCESS           GrantAccess;
   XENBUS_GRANT_END_ACCESS       GrantEndAccess;
OvmfPkg/XenBusDxe/XenBus.c new file +109 -0
new file mode 100644
index 0000000..2e1f939
@@ -0,0 +1,368 @@
+/** @file
+  XenBus Bus driver implemtation.
+
+  This file implement the necessary to discover and enumerate Xen PV devices
+  through XenStore.
+
+  Copyright (C) 2010 Spectra Logic Corporation
+  Copyright (C) 2008 Doug Rabson
+  Copyright (C) 2005 Rusty Russell, IBM Corporation
+  Copyright (C) 2005 Mike Wray, Hewlett-Packard
+  Copyright (C) 2005 XenSource Ltd
+  Copyright (C) 2014, Citrix Ltd.
+
+  This file may be distributed separately from the Linux kernel, or
+  incorporated into other software packages, subject to the following license:
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this source file (the "Software"), to deal in the Software without
+  restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software,
+  and to permit persons to whom the Software is furnished to do so, subject to
+  the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+  IN THE SOFTWARE.
+**/
+
+#include <Library/PrintLib.h>
+
+#include "XenBus.h"
+#include "GrantTable.h"
+#include "XenStore.h"
+#include "EventChannel.h"
+
+#include <IndustryStandard/Xen/io/xenbus.h>
+
+STATIC XENBUS_PRIVATE_DATA gXenBusPrivateData;
+
+STATIC XENBUS_DEVICE_PATH gXenBusDevicePathTemplate = {
+  .Vendor.Header.Type = HARDWARE_DEVICE_PATH,
+  .Vendor.Header.SubType = HW_VENDOR_DP,
+  .Vendor.Header.Length[0] = (UINT8) sizeof (XENBUS_DEVICE_PATH),
+  .Vendor.Header.Length[1] = (UINT8) (sizeof (XENBUS_DEVICE_PATH) >> 8),
+  .Vendor.Guid = XENBUS_PROTOCOL_GUID,
+  .Type = 0,
+  .DeviceId = 0
+};
+
+
+/**
+  Search our internal record of configured devices (not the XenStore) to
+  determine if the XenBus device indicated by Node is known to the system.
+
+  @param Dev   The XENBUS_DEVICE instance to search for device children.
+  @param Node  The XenStore node path for the device to find.
+
+  @return  The XENBUS_PRIVATE_DATA of the found device if any, or NULL.
+ */
+STATIC
+XENBUS_PRIVATE_DATA *
+XenBusDeviceInitialized (
+  IN XENBUS_DEVICE *Dev,
+  IN CONST CHAR8 *Node
+  )
+{
+  LIST_ENTRY *Entry;
+  XENBUS_PRIVATE_DATA *Child;
+  XENBUS_PRIVATE_DATA *Result;
+
+  if (IsListEmpty (&Dev->ChildList)) {
+    return NULL;
+  }
+
+  Result = NULL;
+  for (Entry = GetFirstNode (&Dev->ChildList);
+       !IsNodeAtEnd (&Dev->ChildList, Entry);
+       Entry = GetNextNode (&Dev->ChildList, Entry)) {
+    Child = XENBUS_PRIVATE_DATA_FROM_LINK (Entry);
+    if (!AsciiStrCmp (Child->XenBusIo.Node, Node)) {
+      Result = Child;
+      break;
+    }
+  }
+
+  return (Result);
+}
+
+STATIC
+XenbusState
+XenBusReadDriverState (
+  IN CONST CHAR8 *Path
+  )
+{
+  XenbusState State;
+  CHAR8 *Ptr = NULL;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreRead (XST_NIL, Path, "state", NULL, (VOID **)&Ptr);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    State = XenbusStateClosed;
+  } else {

OvmfPkg/XenBusDxe/XenBus.c line 119

Quoted 10 lines
OvmfPkg/XenBusDxe/XenBus.c new file +10 -0
+    State = AsciiStrDecimalToUintn (Ptr);
+  }
+
+  if (Ptr != NULL) {
+    FreePool (Ptr);
+  }
+
+  return State;
+}
+

Could you add a comment here saying that the callers should ensure that they are the only ones calling this function - as this function does not take a lock when adding in the Dev->ChildList

Quoted 60 lines
OvmfPkg/XenBusDxe/XenBus.c new file +60 -0
+STATIC
+EFI_STATUS
+XenBusAddDevice (
+  XENBUS_DEVICE *Dev,
+  CONST CHAR8 *Type,
+  CONST CHAR8 *Id)
+{
+  CHAR8 DevicePath[XENSTORE_ABS_PATH_MAX];
+  XENSTORE_STATUS StatusXenStore;
+  XENBUS_PRIVATE_DATA *Private;
+  EFI_STATUS Status;
+  XENBUS_DEVICE_PATH *TempXenBusPath;
+  VOID *ChildPciIo;
+
+  AsciiSPrint (DevicePath, sizeof (DevicePath),
+               XENBUS_XENSTORE_NODE "/%a/%a", Type, Id);
+
+  if (XenStorePathExists (XST_NIL, DevicePath, "")) {
+    XENBUS_PRIVATE_DATA *Child;
+    enum xenbus_state State;
+    CHAR8 *BackendPath;
+
+    Child = XenBusDeviceInitialized (Dev, DevicePath);
+    if (Child != NULL) {
+      /*
+       * We are already tracking this node
+       */
+      Status = EFI_SUCCESS;
+      goto out;
+    }
+
+    State = XenBusReadDriverState (DevicePath);
+    if (State != XenbusStateInitialising) {
+      /*
+       * Device is not new, so ignore it. This can
+       * happen if a device is going away after
+       * switching to Closed.
+       */
+      DEBUG ((EFI_D_INFO, "XenBus: Device %a ignored. "
+              "State %d\n", DevicePath, State));
+      Status = EFI_SUCCESS;
+      goto out;
+    }
+
+    StatusXenStore = XenStoreRead (XST_NIL, DevicePath, "backend",
+                                   NULL, (VOID **) &BackendPath);
+    if (StatusXenStore != XENSTORE_STATUS_SUCCESS) {
+      DEBUG ((EFI_D_ERROR, "xenbus: %a no backend path.\n", DevicePath));
+      Status = EFI_NOT_FOUND;
+      goto out;
+    }
+
+    Private = AllocateCopyPool (sizeof *Private, &gXenBusPrivateData);
+    InsertTailList (&Dev->ChildList, &Private->Link);
+
+    Private->XenBusIo.Type = AsciiStrDup (Type);
+    Private->XenBusIo.Node = AsciiStrDup (DevicePath);
+    Private->XenBusIo.Backend = BackendPath;
+    Private->XenBusIo.DeviceId = AsciiStrDecimalToUintn (Id);
+    Private->Dev = Dev;

OvmfPkg/XenBusDxe/XenBus.c line 189

Quoted 10 lines
OvmfPkg/XenBusDxe/XenBus.c new file +10 -0
+
+    TempXenBusPath = AllocateCopyPool (sizeof (XENBUS_DEVICE_PATH),
+                                       &gXenBusDevicePathTemplate);
+    if (!AsciiStrCmp (Private->XenBusIo.Type, "vbd")) {
+      TempXenBusPath->Type = XENBUS_DEVICE_PATH_TYPE_VBD;
+    }
+    TempXenBusPath->DeviceId = Private->XenBusIo.DeviceId;
+    Private->DevicePath = (XENBUS_DEVICE_PATH *)AppendDevicePathNode (
+                            Dev->DevicePath,
+                            &TempXenBusPath->Vendor.Header);

Could you move the 'InsertTailList' to be done after the 'Private' has been fully populated? I know that the current caller of this function is only called during initialization - but in the future this could be extended to called multiple times - and if there are two threads - one adding and another reading from Dev->ChildList - the second thread can get incomplete data.

Quoted 44 lines
OvmfPkg/XenBusDxe/XenBus.c new file +44 -0
+    FreePool (TempXenBusPath);
+
+    Status = gBS->InstallMultipleProtocolInterfaces (
+               &Private->Handle,
+               &gEfiDevicePathProtocolGuid, Private->DevicePath,
+               &gXenBusProtocolGuid, &Private->XenBusIo,
+               NULL);
+    if (EFI_ERROR (Status)) {
+      goto ErrorInstallProtocol;
+    }
+
+    Status = gBS->OpenProtocol (Dev->ControllerHandle,
+               &gEfiPciIoProtocolGuid,
+               &ChildPciIo, Dev->This->DriverBindingHandle,
+               Private->Handle,
+               EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "open by child controller fail (%r)\n",
+              Status));
+      goto ErrorOpenProtocolByChild;
+    }
+  } else {
+    DEBUG ((EFI_D_ERROR, "XenBus: does not exist: %a\n", DevicePath));
+    Status = EFI_NOT_FOUND;
+  }
+
+out:
+  return Status;
+ErrorOpenProtocolByChild:
+  gBS->UninstallMultipleProtocolInterfaces (
+    &Private->Handle,
+    &gEfiDevicePathProtocolGuid, Private->DevicePath,
+    &gXenBusProtocolGuid, &Private->XenBusIo,
+    NULL);
+ErrorInstallProtocol:
+  FreePool (Private->DevicePath);
+  FreePool ((VOID *) Private->XenBusIo.Backend);
+  FreePool ((VOID *) Private->XenBusIo.Node);
+  FreePool ((VOID *) Private->XenBusIo.Type);
+  RemoveEntryList (&Private->Link);
+  FreePool (Private);
+  return Status;
+}
+

OvmfPkg/XenBusDxe/XenBus.c line 243

Quoted 10 lines
OvmfPkg/XenBusDxe/XenBus.c new file +10 -0
+/**
+  Enumerate all devices of the given type on this bus.
+
+  @param Dev   A XENBUS_DEVICE instance.
+  @param Type  String indicating the device sub-tree (e.g. "vfb", "vif")
+               to enumerate.
+
+  Devices that are found are been initialize via XenBusAddDevice ().
+  XenBusAddDevice () ignores duplicate detects and ignores duplicate devices,
+  so it can be called unconditionally for any device found in the XenStore.

.. And the caller needs to ensure it is the only one calling it - or it holds a lock.

Quoted 24 lines
OvmfPkg/XenBusDxe/XenBus.c new file +24 -0
+ */
+STATIC
+VOID
+XenBusEnumerateDeviceType (
+  XENBUS_DEVICE *Dev,
+  CONST CHAR8 *Type
+  )
+{
+  CONST CHAR8 **Directory;
+  UINTN Index;
+  UINT32 Count;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreListDirectory (XST_NIL,
+                                  XENBUS_XENSTORE_NODE, Type,
+                                  &Count, &Directory);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return;
+  }
+  for (Index = 0; Index < Count; Index++) {
+    XenBusAddDevice (Dev, Type, Directory[Index]);
+  }
+
+  FreePool (Directory);

OvmfPkg/XenBusDxe/XenBus.c line 277

Quoted 10 lines
OvmfPkg/XenBusDxe/XenBus.c new file +10 -0
+}
+
+
+/**
+  Enumerate the devices on a XenBus bus and install a XenBus Protocol instance.
+
+  @param Dev   A XENBUS_DEVICE instance.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.

Since this is public, I think it should also perculate the need to hold a lock and not call this concurrently. Or that this function ought to not be called at the same as XenBusDeviceInitialized

Quoted 136 lines
OvmfPkg/XenBusDxe/XenBus.c new file +91 -0
+ */
+XENSTORE_STATUS
+XenBusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  )
+{
+  CONST CHAR8 **Types;
+  UINTN Index;
+  UINT32 Count;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreListDirectory (XST_NIL,
+                                  XENBUS_XENSTORE_NODE, "",
+                                  &Count, &Types);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+
+  for (Index = 0; Index < Count; Index++) {
+    XenBusEnumerateDeviceType (Dev, Types[Index]);
+  }
+
+  FreePool (Types);
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+STATIC
+XENSTORE_STATUS
+EFIAPI
+XenBusSetState (
+  IN XENBUS_PROTOCOL      *This,
+  IN XENSTORE_TRANSACTION Transaction,
+  IN enum xenbus_state    NewState
+  )
+{
+  XENBUS_PRIVATE_DATA *Private;
+  enum xenbus_state CurrentState;
+  XENSTORE_STATUS Status;
+  CHAR8 *Temp;
+
+  DEBUG ((EFI_D_INFO, "XenBus: Set state to %d\n", NewState));
+
+  Private = XENBUS_PRIVATE_DATA_FROM_THIS (This);
+
+  Status = XenStoreRead (Transaction, This->Node, "state", NULL, (VOID **)&Temp);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Out;
+  }
+  CurrentState = AsciiStrDecimalToUintn (Temp);
+  FreePool (Temp);
+  if (CurrentState == NewState) {
+    goto Out;
+  }
+
+  do {
+    Status = XenStoreSPrint (Transaction, This->Node, "state", "%d", NewState);
+  } while (Status == XENSTORE_STATUS_EAGAIN);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenBus: failed to write new state\n"));
+    goto Out;
+  }
+  DEBUG ((EFI_D_INFO, "XenBus: Set state to %d, done\n", NewState));
+
+Out:
+  return Status;
+}
+
+STATIC XENBUS_PRIVATE_DATA gXenBusPrivateData = {
+  .Signature = XENBUS_PRIVATE_DATA_SIGNATURE,
+
+  .XenBusIo.XsRead = XenBusXenStoreRead,
+  .XenBusIo.XsBackendRead = XenBusXenStoreBackendRead,
+  .XenBusIo.XsPrintf = XenBusXenStoreSPrint,
+  .XenBusIo.XsRemove = XenBusXenStoreRemove,
+  .XenBusIo.XsTransactionStart = XenBusXenStoreTransactionStart,
+  .XenBusIo.XsTransactionEnd = XenBusXenStoreTransactionEnd,
+  .XenBusIo.SetState = XenBusSetState,
+  .XenBusIo.GrantAccess = XenBusGrantAccess,
+  .XenBusIo.GrantEndAccess = XenBusGrantEndAccess,
+  .XenBusIo.RegisterWatch = XenBusRegisterWatch,
+  .XenBusIo.RegisterWatchBackend = XenBusRegisterWatchBackend,
+  .XenBusIo.UnregisterWatch = XenBusUnregisterWatch,
+  .XenBusIo.WaitForWatch = XenBusWaitForWatch,
+
+  .XenBusIo.Type = NULL,
+  .XenBusIo.Node = NULL,
+  .XenBusIo.Backend = NULL,
+
+  .Dev = NULL
+};
OvmfPkg/XenBusDxe/XenBus.h new file +39 -0
new file mode 100644
index 0000000..48e0389
@@ -0,0 +1,67 @@
+/** @file
+  Core definitions and data structures shareable across OS platforms.
+
+  Copyright (c) 2010 Spectra Logic Corporation
+  Copyright (C) 2008 Doug Rabson
+  All rights reserved.
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+  1. Redistributions of source code must retain the above copyright
+     notice, this list of conditions, and the following disclaimer,
+     without modification.
+  2. Redistributions in binary form must reproduce at minimum a disclaimer
+     substantially similar to the "NO WARRANTY" disclaimer below
+     ("Disclaimer") and any redistribution must be conditioned upon
+     including a substantially similar Disclaimer requirement for further
+     binary redistribution.
+
+  NO WARRANTY
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
+  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+  HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGES.
+
+**/
+#ifndef _XEN_XENBUS_XENBUSB_H
+#define _XEN_XENBUS_XENBUSB_H
+
+#include "XenBusDxe.h"
+

OvmfPkg/XenBusDxe/XenBus.h line 49

Quoted 10 lines
OvmfPkg/XenBusDxe/XenBus.h new file +10 -0
+#define XENBUS_DEVICE_PATH_TYPE_VBD 0x1
+struct _XENBUS_DEVICE_PATH {
+  VENDOR_DEVICE_PATH  Vendor;
+  UINT8               Type;
+  UINT16              DeviceId;
+};
+
+/**
+  The VM relative path to the XenStore subtree this
+  bus attachment manages.

Huh?

OvmfPkg/XenBusDxe/XenBus.h line 55

Quoted 6 lines
OvmfPkg/XenBusDxe/XenBus.h new file +6 -0
+**/
+#define XENBUS_XENSTORE_NODE "device"
+
+
+/**
+  Perform XenBus bus enumeration and install protocol for childs.

childs? children?

Quoted 205 lines
OvmfPkg/XenBusDxe/XenBus.h new file +12 -0
+
+  @param Dev   The NewBus device representing this XenBus bus.
+
+  @return      On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+               indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenBusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  );
+
+#endif /* _XEN_XENBUS_XENBUSB_H */
OvmfPkg/XenBusDxe/XenBusDxe.c +71 -0
index 76ea67c..50090ba 100644
@@ -48,6 +48,7 @@
 #include "XenHypercall.h"
 #include "GrantTable.h"
 #include "XenStore.h"
+#include "XenBus.h"
 
 
 ///
@@ -301,6 +302,7 @@ XenBusDxeDriverBindingStart (
   EFI_PCI_IO_PROTOCOL *PciIo;
   EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
   UINT64 MmioAddr;
+  EFI_DEVICE_PATH_PROTOCOL *DevicePath;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -314,12 +316,32 @@ XenBusDxeDriverBindingStart (
     return Status;
   }
 
+  Status = gBS->OpenProtocol (
+                  ControllerHandle,
+                  &gEfiDevicePathProtocolGuid,
+                  (VOID **) &DevicePath,
+                  This->DriverBindingHandle,
+                  ControllerHandle,
+                  EFI_OPEN_PROTOCOL_BY_DRIVER
+                  );
+
+  if (EFI_ERROR (Status)) {
+    goto ErrorOpenningProtocol;
+  }
+
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
+  Dev->DevicePath = DevicePath;
+  InitializeListHead (&Dev->ChildList);
 
+  //
+  // The BAR1 of this PCI device is used for shared memory and is supposed to
+  // look like MMIO. The address space of the BAR1 will be used to map the
+  // Grant Table.
+  //
   Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);
   ASSERT_EFI_ERROR (Status);
   ASSERT (BarDesc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM);
@@ -348,6 +370,8 @@ XenBusDxeDriverBindingStart (
   Status = XenStoreInit (Dev);
   ASSERT_EFI_ERROR (Status);
 
+  XenBusEnumerateBus (Dev);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -359,6 +383,9 @@ XenBusDxeDriverBindingStart (
 
 ErrorNoHyperpage:
   FreePool (Dev);
+  gBS->CloseProtocol (ControllerHandle, &gEfiDevicePathProtocolGuid,
+                      This->DriverBindingHandle, ControllerHandle);
+ErrorOpenningProtocol:
   gBS->CloseProtocol (ControllerHandle, &gEfiPciIoProtocolGuid,
                       This->DriverBindingHandle, ControllerHandle);
   return Status;
@@ -399,12 +426,56 @@ XenBusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  UINTN Index;
+  XENBUS_PROTOCOL *XenBusIo;
+  XENBUS_PRIVATE_DATA *ChildData;
+  EFI_STATUS Status;
   XENBUS_DEVICE *Dev = mMyDevice;
 
+  for (Index = 0; Index < NumberOfChildren; Index++) {
+    Status = gBS->OpenProtocol (
+               ChildHandleBuffer[Index],
+               &gXenBusProtocolGuid,
+               (VOID **) &XenBusIo,
+               This->DriverBindingHandle,
+               ControllerHandle,
+               EFI_OPEN_PROTOCOL_GET_PROTOCOL);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenBusDxe: get children protocol failed: %r\n", Status));
+      continue;
+    }
+    ChildData = XENBUS_PRIVATE_DATA_FROM_THIS (XenBusIo);
+    Status = gBS->DisconnectController (ChildData->Handle, NULL, NULL);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenBusDxe: error disconnecting child: %r\n",
+              Status));
+      continue;
+    }
+
+    Status = gBS->UninstallMultipleProtocolInterfaces (
+               ChildData->Handle,
+               &gEfiDevicePathProtocolGuid, ChildData->DevicePath,
+               &gXenBusProtocolGuid, &ChildData->XenBusIo,
+               NULL);
+    ASSERT_EFI_ERROR (Status);
+
+    FreePool ((VOID*)ChildData->XenBusIo.Type);
+    FreePool ((VOID*)ChildData->XenBusIo.Node);
+    FreePool ((VOID*)ChildData->XenBusIo.Backend);
+    FreePool (ChildData->DevicePath);
+    RemoveEntryList (&ChildData->Link);
+    FreePool (ChildData);
+  }
+  if (NumberOfChildren > 0) {
+    return EFI_SUCCESS;
+  }
+
   gBS->CloseEvent (Dev->ExitBootEvent);
   XenStoreDeinit (Dev);
   XenGrantTableDeinit (Dev);
 
+  gBS->CloseProtocol (ControllerHandle, &gEfiDevicePathProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   gBS->CloseProtocol (ControllerHandle, &gEfiPciIoProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
OvmfPkg/XenBusDxe/XenBusDxe.h +19 -0
index dc48a46..7213184 100644
@@ -98,6 +98,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenBusDxeComponentName;
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
 
+typedef struct _XENBUS_DEVICE_PATH XENBUS_DEVICE_PATH;
 typedef struct _XENBUS_DEVICE XENBUS_DEVICE;
 
 // Have the state of the driver.
@@ -108,11 +109,29 @@ struct _XENBUS_DEVICE {
   EFI_HANDLE                    ControllerHandle;
   EFI_PCI_IO_PROTOCOL           *PciIo;
   EFI_EVENT                     ExitBootEvent;
+  EFI_DEVICE_PATH_PROTOCOL      *DevicePath;
+  LIST_ENTRY                    ChildList;
 
   VOID                          *Hyperpage;
   shared_info_t                 *SharedInfo;
 };
 
+// There is one of this struct allocated for every child.
+#define XENBUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X', 'B', 'p', 'd')
+typedef struct {
+    UINTN Signature;
+    LIST_ENTRY Link;
+    EFI_HANDLE Handle;
+    XENBUS_PROTOCOL XenBusIo;
+    XENBUS_DEVICE *Dev;
+    XENBUS_DEVICE_PATH *DevicePath;
+} XENBUS_PRIVATE_DATA;
+
+#define XENBUS_PRIVATE_DATA_FROM_THIS(a) \
+  CR (a, XENBUS_PRIVATE_DATA, XenBusIo, XENBUS_PRIVATE_DATA_SIGNATURE)
+#define XENBUS_PRIVATE_DATA_FROM_LINK(a) \
+  CR (a, XENBUS_PRIVATE_DATA, Link, XENBUS_PRIVATE_DATA_SIGNATURE)
+
 /*
  * Helpers
  */
OvmfPkg/XenBusDxe/XenBusDxe.inf +3 -0
index 9052967..c326bcf 100644
@@ -40,6 +40,9 @@
   EventChannel.h
   XenStore.c
   XenStore.h
+  XenBus.c
+  XenBus.h
+  Helpers.c
 
 [Sources.X64]
   X64/hypercall.S
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
#59 lore raw

Re: [PATCH v2 14/18] OvmfPkg/XenBusDxe: Indroduce XenBus support itself.

Quoted 185 lines · Konrad Rzeszutek Wilk
Quoted 184 lines · Anthony PERARD

This is a bus-like on top of XenStore. It will look for advertised ParaVirtualized devices and initialize them by producing XenBus protocol.

Origin: FreeBSD 10.0

Contributed-under: TianoCore Contribution Agreement 1.0

---
Change in V2:
- comment, file header
- Fix comment style
- Error handling in the main init function
- coding style
- Fix error path in add device.

---
 OvmfPkg/Include/Protocol/XenBus.h |  11 +-
 OvmfPkg/XenBusDxe/XenBus.c        | 368 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenBus.h        |  67 +++++++
 OvmfPkg/XenBusDxe/XenBusDxe.c     |  71 ++++++++
 OvmfPkg/XenBusDxe/XenBusDxe.h     |  19 ++
 OvmfPkg/XenBusDxe/XenBusDxe.inf   |   3 +
 6 files changed, 538 insertions(+), 1 deletion(-)
 create mode 100644 OvmfPkg/XenBusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenBusDxe/XenBus.h
OvmfPkg/Include/Protocol/XenBus.h +10 -1
index 99e174b..f223be7 100644
@@ -45,7 +45,7 @@
 ///
 typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
 
-typedef enum xenbus_state XenbusState;
+typedef enum xenbus_state XenBusState;
 
 typedef struct
 {
@@ -138,6 +138,14 @@ XENSTORE_STATUS
   );
 
 typedef
+XENSTORE_STATUS
+(EFIAPI *XENBUS_SET_STATE)(
+  IN XENBUS_PROTOCOL        *This,
+  IN XENSTORE_TRANSACTION   Transaction,
+  IN XenBusState            State
+  );
+
+typedef
 EFI_STATUS
 (EFIAPI *XENBUS_GRANT_ACCESS)(
   IN  XENBUS_PROTOCOL *This,
@@ -196,6 +204,7 @@ struct _XENBUS_PROTOCOL {
   XENBUS_XS_REMOVE              XsRemove;
   XENBUS_XS_TRANSACTION_START   XsTransactionStart;
   XENBUS_XS_TRANSACTION_END     XsTransactionEnd;
+  XENBUS_SET_STATE              SetState;
 
   XENBUS_GRANT_ACCESS           GrantAccess;
   XENBUS_GRANT_END_ACCESS       GrantEndAccess;
OvmfPkg/XenBusDxe/XenBus.c new file +115 -0
new file mode 100644
index 0000000..2e1f939
@@ -0,0 +1,368 @@
+/** @file
+  XenBus Bus driver implemtation.
+
+  This file implement the necessary to discover and enumerate Xen PV devices
+  through XenStore.
+
+  Copyright (C) 2010 Spectra Logic Corporation
+  Copyright (C) 2008 Doug Rabson
+  Copyright (C) 2005 Rusty Russell, IBM Corporation
+  Copyright (C) 2005 Mike Wray, Hewlett-Packard
+  Copyright (C) 2005 XenSource Ltd
+  Copyright (C) 2014, Citrix Ltd.
+
+  This file may be distributed separately from the Linux kernel, or
+  incorporated into other software packages, subject to the following license:
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this source file (the "Software"), to deal in the Software without
+  restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software,
+  and to permit persons to whom the Software is furnished to do so, subject to
+  the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+  IN THE SOFTWARE.
+**/
+
+#include <Library/PrintLib.h>
+
+#include "XenBus.h"
+#include "GrantTable.h"
+#include "XenStore.h"
+#include "EventChannel.h"
+
+#include <IndustryStandard/Xen/io/xenbus.h>
+
+STATIC XENBUS_PRIVATE_DATA gXenBusPrivateData;
+
+STATIC XENBUS_DEVICE_PATH gXenBusDevicePathTemplate = {
+  .Vendor.Header.Type = HARDWARE_DEVICE_PATH,
+  .Vendor.Header.SubType = HW_VENDOR_DP,
+  .Vendor.Header.Length[0] = (UINT8) sizeof (XENBUS_DEVICE_PATH),
+  .Vendor.Header.Length[1] = (UINT8) (sizeof (XENBUS_DEVICE_PATH) >> 8),
+  .Vendor.Guid = XENBUS_PROTOCOL_GUID,
+  .Type = 0,
+  .DeviceId = 0
+};
+
+
+/**
+  Search our internal record of configured devices (not the XenStore) to
+  determine if the XenBus device indicated by Node is known to the system.
+
+  @param Dev   The XENBUS_DEVICE instance to search for device children.
+  @param Node  The XenStore node path for the device to find.
+
+  @return  The XENBUS_PRIVATE_DATA of the found device if any, or NULL.
+ */
+STATIC
+XENBUS_PRIVATE_DATA *
+XenBusDeviceInitialized (
+  IN XENBUS_DEVICE *Dev,
+  IN CONST CHAR8 *Node
+  )
+{
+  LIST_ENTRY *Entry;
+  XENBUS_PRIVATE_DATA *Child;
+  XENBUS_PRIVATE_DATA *Result;
+
+  if (IsListEmpty (&Dev->ChildList)) {
+    return NULL;
+  }
+
+  Result = NULL;
+  for (Entry = GetFirstNode (&Dev->ChildList);
+       !IsNodeAtEnd (&Dev->ChildList, Entry);
+       Entry = GetNextNode (&Dev->ChildList, Entry)) {
+    Child = XENBUS_PRIVATE_DATA_FROM_LINK (Entry);
+    if (!AsciiStrCmp (Child->XenBusIo.Node, Node)) {
+      Result = Child;
+      break;
+    }
+  }
+
+  return (Result);
+}
+
+STATIC
+XenbusState
+XenBusReadDriverState (
+  IN CONST CHAR8 *Path
+  )
+{
+  XenbusState State;
+  CHAR8 *Ptr = NULL;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreRead (XST_NIL, Path, "state", NULL, (VOID **)&Ptr);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    State = XenbusStateClosed;
+  } else {
+    State = AsciiStrDecimalToUintn (Ptr);
+  }
+
+  if (Ptr != NULL) {
+    FreePool (Ptr);
+  }
Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.c line 119

Quoted 4 lines
OvmfPkg/XenBusDxe/XenBus.c new file +4 -0
+
+  return State;
+}
+

Could you add a comment here saying that the callers should ensure that they are the only ones calling this function - as this function does not take a lock when adding in the Dev->ChildList

Ok, will do.

Quoted 69 lines
Quoted 69 lines
OvmfPkg/XenBusDxe/XenBus.c new file +69 -0
+STATIC
+EFI_STATUS
+XenBusAddDevice (
+  XENBUS_DEVICE *Dev,
+  CONST CHAR8 *Type,
+  CONST CHAR8 *Id)
+{
+  CHAR8 DevicePath[XENSTORE_ABS_PATH_MAX];
+  XENSTORE_STATUS StatusXenStore;
+  XENBUS_PRIVATE_DATA *Private;
+  EFI_STATUS Status;
+  XENBUS_DEVICE_PATH *TempXenBusPath;
+  VOID *ChildPciIo;
+
+  AsciiSPrint (DevicePath, sizeof (DevicePath),
+               XENBUS_XENSTORE_NODE "/%a/%a", Type, Id);
+
+  if (XenStorePathExists (XST_NIL, DevicePath, "")) {
+    XENBUS_PRIVATE_DATA *Child;
+    enum xenbus_state State;
+    CHAR8 *BackendPath;
+
+    Child = XenBusDeviceInitialized (Dev, DevicePath);
+    if (Child != NULL) {
+      /*
+       * We are already tracking this node
+       */
+      Status = EFI_SUCCESS;
+      goto out;
+    }
+
+    State = XenBusReadDriverState (DevicePath);
+    if (State != XenbusStateInitialising) {
+      /*
+       * Device is not new, so ignore it. This can
+       * happen if a device is going away after
+       * switching to Closed.
+       */
+      DEBUG ((EFI_D_INFO, "XenBus: Device %a ignored. "
+              "State %d\n", DevicePath, State));
+      Status = EFI_SUCCESS;
+      goto out;
+    }
+
+    StatusXenStore = XenStoreRead (XST_NIL, DevicePath, "backend",
+                                   NULL, (VOID **) &BackendPath);
+    if (StatusXenStore != XENSTORE_STATUS_SUCCESS) {
+      DEBUG ((EFI_D_ERROR, "xenbus: %a no backend path.\n", DevicePath));
+      Status = EFI_NOT_FOUND;
+      goto out;
+    }
+
+    Private = AllocateCopyPool (sizeof *Private, &gXenBusPrivateData);
+    InsertTailList (&Dev->ChildList, &Private->Link);
+
+    Private->XenBusIo.Type = AsciiStrDup (Type);
+    Private->XenBusIo.Node = AsciiStrDup (DevicePath);
+    Private->XenBusIo.Backend = BackendPath;
+    Private->XenBusIo.DeviceId = AsciiStrDecimalToUintn (Id);
+    Private->Dev = Dev;
+
+    TempXenBusPath = AllocateCopyPool (sizeof (XENBUS_DEVICE_PATH),
+                                       &gXenBusDevicePathTemplate);
+    if (!AsciiStrCmp (Private->XenBusIo.Type, "vbd")) {
+      TempXenBusPath->Type = XENBUS_DEVICE_PATH_TYPE_VBD;
+    }
+    TempXenBusPath->DeviceId = Private->XenBusIo.DeviceId;
+    Private->DevicePath = (XENBUS_DEVICE_PATH *)AppendDevicePathNode (
+                            Dev->DevicePath,
Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.c line 189

Quoted 1 line
OvmfPkg/XenBusDxe/XenBus.c new file +1 -0
+                            &TempXenBusPath->Vendor.Header);

Could you move the 'InsertTailList' to be done after the 'Private' has been fully populated? I know that the current caller of this function is only called during initialization - but in the future this could be extended to called multiple times - and if there are two threads - one adding and another reading from Dev->ChildList - the second thread can get incomplete data.

Ok, will do.

Quoted 50 lines
Quoted 50 lines
OvmfPkg/XenBusDxe/XenBus.c new file +50 -0
+    FreePool (TempXenBusPath);
+
+    Status = gBS->InstallMultipleProtocolInterfaces (
+               &Private->Handle,
+               &gEfiDevicePathProtocolGuid, Private->DevicePath,
+               &gXenBusProtocolGuid, &Private->XenBusIo,
+               NULL);
+    if (EFI_ERROR (Status)) {
+      goto ErrorInstallProtocol;
+    }
+
+    Status = gBS->OpenProtocol (Dev->ControllerHandle,
+               &gEfiPciIoProtocolGuid,
+               &ChildPciIo, Dev->This->DriverBindingHandle,
+               Private->Handle,
+               EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "open by child controller fail (%r)\n",
+              Status));
+      goto ErrorOpenProtocolByChild;
+    }
+  } else {
+    DEBUG ((EFI_D_ERROR, "XenBus: does not exist: %a\n", DevicePath));
+    Status = EFI_NOT_FOUND;
+  }
+
+out:
+  return Status;
+ErrorOpenProtocolByChild:
+  gBS->UninstallMultipleProtocolInterfaces (
+    &Private->Handle,
+    &gEfiDevicePathProtocolGuid, Private->DevicePath,
+    &gXenBusProtocolGuid, &Private->XenBusIo,
+    NULL);
+ErrorInstallProtocol:
+  FreePool (Private->DevicePath);
+  FreePool ((VOID *) Private->XenBusIo.Backend);
+  FreePool ((VOID *) Private->XenBusIo.Node);
+  FreePool ((VOID *) Private->XenBusIo.Type);
+  RemoveEntryList (&Private->Link);
+  FreePool (Private);
+  return Status;
+}
+
+/**
+  Enumerate all devices of the given type on this bus.
+
+  @param Dev   A XENBUS_DEVICE instance.
+  @param Type  String indicating the device sub-tree (e.g. "vfb", "vif")
+               to enumerate.
Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.c line 243

Quoted 4 lines
OvmfPkg/XenBusDxe/XenBus.c new file +4 -0
+
+  Devices that are found are been initialize via XenBusAddDevice ().
+  XenBusAddDevice () ignores duplicate detects and ignores duplicate devices,
+  so it can be called unconditionally for any device found in the XenStore.

.. And the caller needs to ensure it is the only one calling it - or it holds a lock.

Ok, will add something.

Quoted 30 lines
Quoted 30 lines
OvmfPkg/XenBusDxe/XenBus.c new file +30 -0
+ */
+STATIC
+VOID
+XenBusEnumerateDeviceType (
+  XENBUS_DEVICE *Dev,
+  CONST CHAR8 *Type
+  )
+{
+  CONST CHAR8 **Directory;
+  UINTN Index;
+  UINT32 Count;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreListDirectory (XST_NIL,
+                                  XENBUS_XENSTORE_NODE, Type,
+                                  &Count, &Directory);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return;
+  }
+  for (Index = 0; Index < Count; Index++) {
+    XenBusAddDevice (Dev, Type, Directory[Index]);
+  }
+
+  FreePool (Directory);
+}
+
+
+/**
+  Enumerate the devices on a XenBus bus and install a XenBus Protocol instance.
+
Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.c line 277

Quoted 4 lines
OvmfPkg/XenBusDxe/XenBus.c new file +4 -0
+  @param Dev   A XENBUS_DEVICE instance.
+
+  @return  On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+           indicating the type of failure.

Since this is public, I think it should also perculate the need to hold a lock and not call this concurrently. Or that this function ought to not be called at the same as XenBusDeviceInitialized

Ok, will do something about it.

Quoted 140 lines
Quoted 140 lines
OvmfPkg/XenBusDxe/XenBus.c new file +91 -0
+ */
+XENSTORE_STATUS
+XenBusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  )
+{
+  CONST CHAR8 **Types;
+  UINTN Index;
+  UINT32 Count;
+  XENSTORE_STATUS Status;
+
+  Status = XenStoreListDirectory (XST_NIL,
+                                  XENBUS_XENSTORE_NODE, "",
+                                  &Count, &Types);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+
+  for (Index = 0; Index < Count; Index++) {
+    XenBusEnumerateDeviceType (Dev, Types[Index]);
+  }
+
+  FreePool (Types);
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+STATIC
+XENSTORE_STATUS
+EFIAPI
+XenBusSetState (
+  IN XENBUS_PROTOCOL      *This,
+  IN XENSTORE_TRANSACTION Transaction,
+  IN enum xenbus_state    NewState
+  )
+{
+  XENBUS_PRIVATE_DATA *Private;
+  enum xenbus_state CurrentState;
+  XENSTORE_STATUS Status;
+  CHAR8 *Temp;
+
+  DEBUG ((EFI_D_INFO, "XenBus: Set state to %d\n", NewState));
+
+  Private = XENBUS_PRIVATE_DATA_FROM_THIS (This);
+
+  Status = XenStoreRead (Transaction, This->Node, "state", NULL, (VOID **)&Temp);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Out;
+  }
+  CurrentState = AsciiStrDecimalToUintn (Temp);
+  FreePool (Temp);
+  if (CurrentState == NewState) {
+    goto Out;
+  }
+
+  do {
+    Status = XenStoreSPrint (Transaction, This->Node, "state", "%d", NewState);
+  } while (Status == XENSTORE_STATUS_EAGAIN);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenBus: failed to write new state\n"));
+    goto Out;
+  }
+  DEBUG ((EFI_D_INFO, "XenBus: Set state to %d, done\n", NewState));
+
+Out:
+  return Status;
+}
+
+STATIC XENBUS_PRIVATE_DATA gXenBusPrivateData = {
+  .Signature = XENBUS_PRIVATE_DATA_SIGNATURE,
+
+  .XenBusIo.XsRead = XenBusXenStoreRead,
+  .XenBusIo.XsBackendRead = XenBusXenStoreBackendRead,
+  .XenBusIo.XsPrintf = XenBusXenStoreSPrint,
+  .XenBusIo.XsRemove = XenBusXenStoreRemove,
+  .XenBusIo.XsTransactionStart = XenBusXenStoreTransactionStart,
+  .XenBusIo.XsTransactionEnd = XenBusXenStoreTransactionEnd,
+  .XenBusIo.SetState = XenBusSetState,
+  .XenBusIo.GrantAccess = XenBusGrantAccess,
+  .XenBusIo.GrantEndAccess = XenBusGrantEndAccess,
+  .XenBusIo.RegisterWatch = XenBusRegisterWatch,
+  .XenBusIo.RegisterWatchBackend = XenBusRegisterWatchBackend,
+  .XenBusIo.UnregisterWatch = XenBusUnregisterWatch,
+  .XenBusIo.WaitForWatch = XenBusWaitForWatch,
+
+  .XenBusIo.Type = NULL,
+  .XenBusIo.Node = NULL,
+  .XenBusIo.Backend = NULL,
+
+  .Dev = NULL
+};
OvmfPkg/XenBusDxe/XenBus.h new file +43 -0
new file mode 100644
index 0000000..48e0389
@@ -0,0 +1,67 @@
+/** @file
+  Core definitions and data structures shareable across OS platforms.
+
+  Copyright (c) 2010 Spectra Logic Corporation
+  Copyright (C) 2008 Doug Rabson
+  All rights reserved.
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+  1. Redistributions of source code must retain the above copyright
+     notice, this list of conditions, and the following disclaimer,
+     without modification.
+  2. Redistributions in binary form must reproduce at minimum a disclaimer
+     substantially similar to the "NO WARRANTY" disclaimer below
+     ("Disclaimer") and any redistribution must be conditioned upon
+     including a substantially similar Disclaimer requirement for further
+     binary redistribution.
+
+  NO WARRANTY
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
+  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+  HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGES.
+
+**/
+#ifndef _XEN_XENBUS_XENBUSB_H
+#define _XEN_XENBUS_XENBUSB_H
+
+#include "XenBusDxe.h"
+
+#define XENBUS_DEVICE_PATH_TYPE_VBD 0x1
+struct _XENBUS_DEVICE_PATH {
+  VENDOR_DEVICE_PATH  Vendor;
+  UINT8               Type;
Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.h line 49

Quoted 6 lines
OvmfPkg/XenBusDxe/XenBus.h new file +6 -0
+  UINT16              DeviceId;
+};
+
+/**
+  The VM relative path to the XenStore subtree this
+  bus attachment manages.

Huh?

That's an original comment, it was originaly a variable for the enumerate bus function.

Maybe I should just replace the macro by "device" directly in the code and avoid the define and it's comment.

Quoted 8 lines

OvmfPkg/XenBusDxe/XenBus.h line 55

Quoted 6 lines
OvmfPkg/XenBusDxe/XenBus.h new file +6 -0
+**/
+#define XENBUS_XENSTORE_NODE "device"
+
+
+/**
+  Perform XenBus bus enumeration and install protocol for childs.

childs? children?

Yes, children...

Quoted 205 lines
Quoted 205 lines
OvmfPkg/XenBusDxe/XenBus.h new file +12 -0
+
+  @param Dev   The NewBus device representing this XenBus bus.
+
+  @return      On success, XENSTORE_STATUS_SUCCESS. Otherwise an errno value
+               indicating the type of failure.
+**/
+XENSTORE_STATUS
+XenBusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  );
+
+#endif /* _XEN_XENBUS_XENBUSB_H */
OvmfPkg/XenBusDxe/XenBusDxe.c +71 -0
index 76ea67c..50090ba 100644
@@ -48,6 +48,7 @@
 #include "XenHypercall.h"
 #include "GrantTable.h"
 #include "XenStore.h"
+#include "XenBus.h"
 
 
 ///
@@ -301,6 +302,7 @@ XenBusDxeDriverBindingStart (
   EFI_PCI_IO_PROTOCOL *PciIo;
   EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
   UINT64 MmioAddr;
+  EFI_DEVICE_PATH_PROTOCOL *DevicePath;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -314,12 +316,32 @@ XenBusDxeDriverBindingStart (
     return Status;
   }
 
+  Status = gBS->OpenProtocol (
+                  ControllerHandle,
+                  &gEfiDevicePathProtocolGuid,
+                  (VOID **) &DevicePath,
+                  This->DriverBindingHandle,
+                  ControllerHandle,
+                  EFI_OPEN_PROTOCOL_BY_DRIVER
+                  );
+
+  if (EFI_ERROR (Status)) {
+    goto ErrorOpenningProtocol;
+  }
+
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
+  Dev->DevicePath = DevicePath;
+  InitializeListHead (&Dev->ChildList);
 
+  //
+  // The BAR1 of this PCI device is used for shared memory and is supposed to
+  // look like MMIO. The address space of the BAR1 will be used to map the
+  // Grant Table.
+  //
   Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);
   ASSERT_EFI_ERROR (Status);
   ASSERT (BarDesc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM);
@@ -348,6 +370,8 @@ XenBusDxeDriverBindingStart (
   Status = XenStoreInit (Dev);
   ASSERT_EFI_ERROR (Status);
 
+  XenBusEnumerateBus (Dev);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -359,6 +383,9 @@ XenBusDxeDriverBindingStart (
 
 ErrorNoHyperpage:
   FreePool (Dev);
+  gBS->CloseProtocol (ControllerHandle, &gEfiDevicePathProtocolGuid,
+                      This->DriverBindingHandle, ControllerHandle);
+ErrorOpenningProtocol:
   gBS->CloseProtocol (ControllerHandle, &gEfiPciIoProtocolGuid,
                       This->DriverBindingHandle, ControllerHandle);
   return Status;
@@ -399,12 +426,56 @@ XenBusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  UINTN Index;
+  XENBUS_PROTOCOL *XenBusIo;
+  XENBUS_PRIVATE_DATA *ChildData;
+  EFI_STATUS Status;
   XENBUS_DEVICE *Dev = mMyDevice;
 
+  for (Index = 0; Index < NumberOfChildren; Index++) {
+    Status = gBS->OpenProtocol (
+               ChildHandleBuffer[Index],
+               &gXenBusProtocolGuid,
+               (VOID **) &XenBusIo,
+               This->DriverBindingHandle,
+               ControllerHandle,
+               EFI_OPEN_PROTOCOL_GET_PROTOCOL);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenBusDxe: get children protocol failed: %r\n", Status));
+      continue;
+    }
+    ChildData = XENBUS_PRIVATE_DATA_FROM_THIS (XenBusIo);
+    Status = gBS->DisconnectController (ChildData->Handle, NULL, NULL);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenBusDxe: error disconnecting child: %r\n",
+              Status));
+      continue;
+    }
+
+    Status = gBS->UninstallMultipleProtocolInterfaces (
+               ChildData->Handle,
+               &gEfiDevicePathProtocolGuid, ChildData->DevicePath,
+               &gXenBusProtocolGuid, &ChildData->XenBusIo,
+               NULL);
+    ASSERT_EFI_ERROR (Status);
+
+    FreePool ((VOID*)ChildData->XenBusIo.Type);
+    FreePool ((VOID*)ChildData->XenBusIo.Node);
+    FreePool ((VOID*)ChildData->XenBusIo.Backend);
+    FreePool (ChildData->DevicePath);
+    RemoveEntryList (&ChildData->Link);
+    FreePool (ChildData);
+  }
+  if (NumberOfChildren > 0) {
+    return EFI_SUCCESS;
+  }
+
   gBS->CloseEvent (Dev->ExitBootEvent);
   XenStoreDeinit (Dev);
   XenGrantTableDeinit (Dev);
 
+  gBS->CloseProtocol (ControllerHandle, &gEfiDevicePathProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   gBS->CloseProtocol (ControllerHandle, &gEfiPciIoProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
OvmfPkg/XenBusDxe/XenBusDxe.h +19 -0
index dc48a46..7213184 100644
@@ -98,6 +98,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenBusDxeComponentName;
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
 
+typedef struct _XENBUS_DEVICE_PATH XENBUS_DEVICE_PATH;
 typedef struct _XENBUS_DEVICE XENBUS_DEVICE;
 
 // Have the state of the driver.
@@ -108,11 +109,29 @@ struct _XENBUS_DEVICE {
   EFI_HANDLE                    ControllerHandle;
   EFI_PCI_IO_PROTOCOL           *PciIo;
   EFI_EVENT                     ExitBootEvent;
+  EFI_DEVICE_PATH_PROTOCOL      *DevicePath;
+  LIST_ENTRY                    ChildList;
 
   VOID                          *Hyperpage;
   shared_info_t                 *SharedInfo;
 };
 
+// There is one of this struct allocated for every child.
+#define XENBUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X', 'B', 'p', 'd')
+typedef struct {
+    UINTN Signature;
+    LIST_ENTRY Link;
+    EFI_HANDLE Handle;
+    XENBUS_PROTOCOL XenBusIo;
+    XENBUS_DEVICE *Dev;
+    XENBUS_DEVICE_PATH *DevicePath;
+} XENBUS_PRIVATE_DATA;
+
+#define XENBUS_PRIVATE_DATA_FROM_THIS(a) \
+  CR (a, XENBUS_PRIVATE_DATA, XenBusIo, XENBUS_PRIVATE_DATA_SIGNATURE)
+#define XENBUS_PRIVATE_DATA_FROM_LINK(a) \
+  CR (a, XENBUS_PRIVATE_DATA, Link, XENBUS_PRIVATE_DATA_SIGNATURE)
+
 /*
  * Helpers
  */
OvmfPkg/XenBusDxe/XenBusDxe.inf +3 -0
index 9052967..c326bcf 100644
@@ -40,6 +40,9 @@
   EventChannel.h
   XenStore.c
   XenStore.h
+  XenBus.c
+  XenBus.h
+  Helpers.c
 
 [Sources.X64]
   X64/hypercall.S
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Signature · 1 line
Anthony PERARD

A message that is not in the archive (sent off-list or not yet received): [email protected]

#61 lore raw

Re: [PATCH v2 15/18] OvmfPkg/XenBusDxe: Add Event Channel into XenBus protocol.

Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

While the code is fine, please expand the description here a bit.

You can even just copy and paste the function comments - and start it with: "Adding three event channel related functions:
a) Allocate (copy-n-paste of the oneline from the function comment).
b) Notify..

and so on.

Thank you.

Quoted 207 lines

---
Change in V2:
- coding style
- adding comment to functions
- Rename Xenbus to XenBus.

---
 OvmfPkg/Include/Protocol/XenBus.h | 27 +++++++++++++++++++
 OvmfPkg/XenBusDxe/EventChannel.c  | 55 +++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/EventChannel.h  | 48 ++++++++++++++++++++++++++++++++++
 OvmfPkg/XenBusDxe/XenBus.c        |  3 +++
 4 files changed, 133 insertions(+)
OvmfPkg/Include/Protocol/XenBus.h +27 -0
index f223be7..f404a81 100644
@@ -76,6 +76,7 @@ typedef enum {
 
 
 #include <IndustryStandard/Xen/grant_table.h>
+#include <IndustryStandard/Xen/event_channel.h>
 
 ///
 /// Function prototypes
@@ -163,6 +164,28 @@ EFI_STATUS
   );
 
 typedef
+UINT32
+(EFIAPI *XENBUS_EVENT_CHANNEL_ALLOCATE) (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  OUT evtchn_port_t   *Port
+  );
+
+typedef
+VOID
+(EFIAPI *XENBUS_EVENT_CHANNEL_NOTIFY) (
+  IN XENBUS_PROTOCOL  *This,
+  IN evtchn_port_t    Port
+  );
+
+typedef
+UINT32
+(EFIAPI *XENBUS_EVENT_CHANNEL_CLOSE) (
+  IN XENBUS_PROTOCOL  *This,
+  IN evtchn_port_t    Port
+  );
+
+typedef
 XENSTORE_STATUS
 (EFIAPI *XENBUS_REGISTER_WATCH) (
   IN  XENBUS_PROTOCOL *This,
@@ -209,6 +232,10 @@ struct _XENBUS_PROTOCOL {
   XENBUS_GRANT_ACCESS           GrantAccess;
   XENBUS_GRANT_END_ACCESS       GrantEndAccess;
 
+  XENBUS_EVENT_CHANNEL_ALLOCATE EventChannelAllocate;
+  XENBUS_EVENT_CHANNEL_NOTIFY   EventChannelNotify;
+  XENBUS_EVENT_CHANNEL_CLOSE    EventChannelClose;
+
   XENBUS_REGISTER_WATCH         RegisterWatch;
   XENBUS_REGISTER_WATCH_BACKEND RegisterWatchBackend;
   XENBUS_UNREGISTER_WATCH       UnregisterWatch;
OvmfPkg/XenBusDxe/EventChannel.c +55 -0
index f34f9b8..82c4f4b 100644
@@ -47,3 +47,58 @@ XenEventChannelNotify (
   ReturnCode = XenHypercallEventChannelOp (Dev, EVTCHNOP_send, &Send);
   ASSERT (ReturnCode == 0);
 }
+
+UINT32
+EFIAPI
+XenBusEventChannelAllocate (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  OUT evtchn_port_t   *Port
+  )
+{
+  XENBUS_PRIVATE_DATA *Private;
+  evtchn_alloc_unbound_t Parameter;
+  UINT32 ReturnCode;
+
+  Private = XENBUS_PRIVATE_DATA_FROM_THIS (This);
+
+  Parameter.dom = DOMID_SELF;
+  Parameter.remote_dom = DomainId;
+  ReturnCode = XenHypercallEventChannelOp (Private->Dev,
+                                   EVTCHNOP_alloc_unbound,
+                                   &Parameter);
+  if (ReturnCode != 0) {
+    DEBUG ((EFI_D_ERROR, "ERROR: alloc_unbound failed with rc=%d", ReturnCode));
+    return ReturnCode;
+  }
+  *Port = Parameter.port;
+  return ReturnCode;
+}
+
+VOID
+EFIAPI
+XenBusEventChannelNotify (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t   Port
+  )
+{
+  XENBUS_PRIVATE_DATA *Private;
+
+  Private = XENBUS_PRIVATE_DATA_FROM_THIS(This);
+  XenEventChannelNotify (Private->Dev, Port);
+}
+
+UINT32
+EFIAPI
+XenBusEventChannelClose (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t   Port
+  )
+{
+  XENBUS_PRIVATE_DATA *Private;
+  evtchn_close_t Close;
+
+  Private = XENBUS_PRIVATE_DATA_FROM_THIS (This);
+  Close.port = Port;
+  return XenHypercallEventChannelOp (Private->Dev, EVTCHNOP_close, &Close);
+}
OvmfPkg/XenBusDxe/EventChannel.h +48 -0
index fb2845b..2cc8266 100644
@@ -47,4 +47,52 @@ XenEventChannelNotify (
   IN evtchn_port_t Port
   );
 
+/*
+ * XenBus protocol
+ */
+
+/**
+  Allocate a port that can be bind from domain DomainId.
+
+  @param This       A pointer to the XENBUS_PROTOCOL.
+  @param DomainId   The domain ID that can bind the newly allocated port.
+  @param Port       A pointer to a evtchn_port_t that will contain the newly
+                    allocated port.
+
+  @retval UINT32    The return value from the hypercall, 0 if success.
+**/
+UINT32
+EFIAPI
+XenBusEventChannelAllocate (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  OUT evtchn_port_t   *Port
+  );
+
+/**
+  Send an event to the remote end of the channel whose local endpoint is Port.
+
+  @param This       A pointer to the XENBUS_PROTOCOL.
+  @param Port       Local port to the the event from.
+**/
+VOID
+EFIAPI
+XenBusEventChannelNotify (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t   Port
+  );
+
+/**
+  Close a local event channel Port.
+
+  @param This       A pointer to the XENBUS_PROTOCOL.
+  @param Port       The event channel to close.
+**/
+UINT32
+EFIAPI
+XenBusEventChannelClose (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t   Port
+  );
+
 #endif
OvmfPkg/XenBusDxe/XenBus.c +3 -0
index 2e1f939..8c68809 100644
@@ -355,6 +355,9 @@ STATIC XENBUS_PRIVATE_DATA gXenBusPrivateData = {
   .XenBusIo.SetState = XenBusSetState,
   .XenBusIo.GrantAccess = XenBusGrantAccess,
   .XenBusIo.GrantEndAccess = XenBusGrantEndAccess,
+  .XenBusIo.EventChannelAllocate = XenBusEventChannelAllocate,
+  .XenBusIo.EventChannelNotify = XenBusEventChannelNotify,
+  .XenBusIo.EventChannelClose = XenBusEventChannelClose,
   .XenBusIo.RegisterWatch = XenBusRegisterWatch,
   .XenBusIo.RegisterWatchBackend = XenBusRegisterWatchBackend,
   .XenBusIo.UnregisterWatch = XenBusUnregisterWatch,
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
#62 lore raw

Re: [PATCH v2 15/18] OvmfPkg/XenBusDxe: Add Event Channel into XenBus protocol.

Quoted 12 lines · Konrad Rzeszutek Wilk
Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

While the code is fine, please expand the description here a bit.

You can even just copy and paste the function comments - and start it with: "Adding three event channel related functions:
a) Allocate (copy-n-paste of the oneline from the function comment).
b) Notify..

Quoted 3 lines

and so on.

Thank you.

Ok, will do.

Signature · 1 line
Anthony PERARD

A message that is not in the archive (sent off-list or not yet received): [email protected]

#64 lore raw

Re: [PATCH v2 16/18] OvmfPkg/XenPvBlkDxe: Xen PV Block device, initial skeleton

Review

Quoted 5 lines
(quoted diff) +5 -0
+
+//
+// Driver Version
+//
+#define XEN_PV_BLK_DXE_VERSION  0x00000000

This is 0, while ..

Quoted 53 lines
(quoted diff) +18 -0
+
+
+//
+// Protocol instances
+//
+extern EFI_DRIVER_BINDING_PROTOCOL  gXenPvBlkDxeDriverBinding;
+extern EFI_COMPONENT_NAME2_PROTOCOL  gXenPvBlkDxeComponentName2;
+extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
+
+
+//
+// Include files with function prototypes
+//
+#include "DriverBinding.h"
+#include "ComponentName.h"
+
+
+#endif
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +29 -0
new file mode 100644
index 0000000..aaa809f
@@ -0,0 +1,76 @@
+
+## @file
+#  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+#
+#  Copyright (C) 2014, Citrix Ltd.
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions
+#  are met:
+#
+#  * Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in
+#    the documentation and/or other materials provided with the
+#    distribution.
+#
+#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+#  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+#  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+#  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+#  POSSIBILITY OF SUCH DAMAGE.

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf line 39

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +10 -0
+#
+##
+
+[Defines]
+  INF_VERSION               = 0x00010005
+  BASE_NAME                 = XenPvBlkDxe
+  FILE_GUID                 = 8c2487ea-9af3-11e3-b966-b8ac6f7d65e6
+  MODULE_TYPE               = UEFI_DRIVER
+
+  VERSION_STRING            = 0.1

This is 0.1?

Should it have the same version number?

Quoted 45 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +37 -0
+  ENTRY_POINT               = XenPvBlkDxeDriverEntryPoint
+  UNLOAD_IMAGE              = XenPvBlkDxeUnload
+
+
+[Packages]
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[Sources]
+  XenPvBlkDxe.h
+  XenPvBlkDxe.c
+  ComponentName.c
+  ComponentName.h
+
+
+[LibraryClasses]
+  UefiDriverEntryPoint
+  UefiBootServicesTableLib
+  MemoryAllocationLib
+  BaseMemoryLib
+  BaseLib
+  UefiLib
+  DevicePathLib
+  DebugLib
+
+
+[Protocols]
+  gEfiDriverBindingProtocolGuid
+  gEfiBlockIoProtocolGuid
+  gEfiComponentName2ProtocolGuid
+  gEfiComponentNameProtocolGuid
+  gXenBusProtocolGuid
+  gEfiDevicePathProtocolGuid                    ## TO_START
+
+
+[Guids]
+
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
#65 lore raw

Re: [PATCH v2 16/18] OvmfPkg/XenPvBlkDxe: Xen PV Block device, initial skeleton

Quoted 73 lines · Konrad Rzeszutek Wilk

Review

Quoted 5 lines
(quoted diff) +5 -0
+
+//
+// Driver Version
+//
+#define XEN_PV_BLK_DXE_VERSION  0x00000000

This is 0, while ..

Quoted 53 lines
(quoted diff) +18 -0
+
+
+//
+// Protocol instances
+//
+extern EFI_DRIVER_BINDING_PROTOCOL  gXenPvBlkDxeDriverBinding;
+extern EFI_COMPONENT_NAME2_PROTOCOL  gXenPvBlkDxeComponentName2;
+extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
+
+
+//
+// Include files with function prototypes
+//
+#include "DriverBinding.h"
+#include "ComponentName.h"
+
+
+#endif
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +29 -0
new file mode 100644
index 0000000..aaa809f
@@ -0,0 +1,76 @@
+
+## @file
+#  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+#
+#  Copyright (C) 2014, Citrix Ltd.
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions
+#  are met:
+#
+#  * Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in
+#    the documentation and/or other materials provided with the
+#    distribution.
+#
+#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+#  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+#  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+#  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+#  POSSIBILITY OF SUCH DAMAGE.

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf line 39

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +10 -0
+#
+##
+
+[Defines]
+  INF_VERSION               = 0x00010005
+  BASE_NAME                 = XenPvBlkDxe
+  FILE_GUID                 = 8c2487ea-9af3-11e3-b966-b8ac6f7d65e6
+  MODULE_TYPE               = UEFI_DRIVER
+
+  VERSION_STRING            = 0.1

This is 0.1?

Quoted 1 line

Should it have the same version number?

I will check what need to be done here. And probably replace 0.1 by a 1. And will do the same thing for the other driver, XenBusDxe.

Quoted 45 lines
Quoted 45 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +37 -0
+  ENTRY_POINT               = XenPvBlkDxeDriverEntryPoint
+  UNLOAD_IMAGE              = XenPvBlkDxeUnload
+
+
+[Packages]
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[Sources]
+  XenPvBlkDxe.h
+  XenPvBlkDxe.c
+  ComponentName.c
+  ComponentName.h
+
+
+[LibraryClasses]
+  UefiDriverEntryPoint
+  UefiBootServicesTableLib
+  MemoryAllocationLib
+  BaseMemoryLib
+  BaseLib
+  UefiLib
+  DevicePathLib
+  DebugLib
+
+
+[Protocols]
+  gEfiDriverBindingProtocolGuid
+  gEfiBlockIoProtocolGuid
+  gEfiComponentName2ProtocolGuid
+  gEfiComponentNameProtocolGuid
+  gXenBusProtocolGuid
+  gEfiDevicePathProtocolGuid                    ## TO_START
+
+
+[Guids]
+
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Signature · 1 line
Anthony PERARD

A message that is not in the archive (sent off-list or not yet received): [email protected]

#67 lore raw

Re: [PATCH v2 17/18] OvmfPkg/XenPvBlkDxe: Add BlockFront client.

Review

Quoted 2 lines
(quoted diff) +2 -0
+/**
+  Helper to read an interger from XenStore.

integer?

Quoted 21 lines
(quoted diff) +21 -0
+
+  @param This         A pointer to a XENBUS_PROTOCOL instance.
+  @param Node         The XenStore node to read from.
+  @param FromBackend  Read frontend or backend value.
+  @param ValuePtr     Where to put the value.
+
+  @retval XENSTORE_STATUS_SUCCESS  If succefull, will update ValuePtr.
+  @return                          Any other return value indicate the error,
+                                   ValuePtr is not updated in this case.
+**/
+STATIC
+XENSTORE_STATUS
+XenBusReadUint64 (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  IN  BOOLEAN         FromBackend,
+  OUT UINT64          *ValuePtr
+  )
+{
+  XENSTORE_STATUS Status;
+  CHAR8 *p;

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+  if (!FromBackend) {
+    Status = This->XsRead (This, XST_NIL, Node, (VOID**)&p);
+  } else {
+    Status = This->XsBackendRead (This, XST_NIL, Node, (VOID**)&p);
+  }
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+  // FIXME Will ASSERT if p overflow UINT64 ...

Do you just want to add the ASSERT in the code then?

Quoted 22 lines
(quoted diff) +22 -0
+  *ValuePtr = AsciiStrDecimalToUint64 (p);
+  FreePool (p);
+  return Status;
+}
+
+/**
+  Free an instance of XEN_BLOCK_FRONT_DEVICE.
+
+  @param Dev  The instance to free.
+**/
+STATIC
+VOID
+XenPvBlockFree (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+
+  if (Dev->RingRef != 0) {
+    XenBusIo->GrantEndAccess (XenBusIo, Dev->RingRef);
+  }
+  if (Dev->Ring.sring != NULL) {

Review

Quoted 10 lines
(quoted diff) +10 -0
+    FreePages (Dev->Ring.sring, 1);
+  }
+  if (Dev->EventChannel != 0) {
+    XenBusIo->EventChannelClose (XenBusIo, Dev->EventChannel);
+  }
+  FreePool (Dev);
+}
+
+/**
+  Wait until until the backend have reach the ExpectedState.

s/have reached/has reached/

Review

Quoted 4 lines
(quoted diff) +4 -0
+
+  @param Dev            A XEN_BLOCK_FRONT_DEVICE instance.
+  @param ExpectedState  The backend state expected.
+  @param LastStatePtr   An optionnal pointer where to right the final state.

s/optionnal/optional/

Quoted 116 lines
(quoted diff) +116 -0
+
+  @return Return XENSTORE_STATUS_SUCCESS if the new backend state is ExpectedState
+          or return an error otherwise.
+**/
+STATIC
+XENSTORE_STATUS
+XenPvBlkWaitForBackendState (
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN  XenbusState            ExpectedState,
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status = XENSTORE_STATUS_SUCCESS;
+
+  while (TRUE) {
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
+    }
+    if (Value > XenbusStateReconfigured) {
+      //
+      // Value is not a State value.
+      //
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State == ExpectedState) {
+      break;
+    } else if (State > ExpectedState) {
+      Status = XENSTORE_STATUS_FAIL;
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            ExpectedState, State));
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return Status;
+}
+
+EFI_STATUS
+XenPvBlockFrontInitialization (
+  IN  XENBUS_PROTOCOL         *XenBusIo,
+  IN  CONST CHAR8             *NodeName,
+  OUT XEN_BLOCK_FRONT_DEVICE  **DevPtr
+  )
+{
+  XENSTORE_TRANSACTION xbt;
+  CHAR8 *DeviceType;
+  blkif_sring_t *SharedRing;
+  XENSTORE_STATUS Status;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
+  XenbusState State;
+  UINT64 Value;
+
+  ASSERT (NodeName != NULL);
+
+  Dev = AllocateZeroPool (sizeof (XEN_BLOCK_FRONT_DEVICE));
+  Dev->Signature = XEN_BLOCK_FRONT_SIGNATURE;
+  Dev->NodeName = NodeName;
+  Dev->XenBusIo = XenBusIo;
+  Dev->DeviceId = XenBusIo->DeviceId;
+
+  XenBusIo->XsRead (XenBusIo, XST_NIL, "device-type", (VOID**)&DeviceType);
+  if (AsciiStrCmp (DeviceType, "cdrom") == 0) {
+    Dev->MediaInfo.CdRom = TRUE;
+  } else {
+    Dev->MediaInfo.CdRom = FALSE;
+  }
+  FreePool (DeviceType);
+
+  Status = XenBusReadUint64 (XenBusIo, "backend-id", FALSE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT16_MAX) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to get backend-id (%d)\n",
+            Status));
+    goto Error;
+  }
+  Dev->DomainId = Value;
+  XenBusIo->EventChannelAllocate (XenBusIo, Dev->DomainId, &Dev->EventChannel);
+
+  SharedRing = (blkif_sring_t*) AllocatePages (1);
+  SHARED_RING_INIT (SharedRing);
+  FRONT_RING_INIT (&Dev->Ring, SharedRing, EFI_PAGE_SIZE);
+  XenBusIo->GrantAccess (XenBusIo,
+                         Dev->DomainId,
+                         (INTN) SharedRing >> EFI_PAGE_SHIFT,
+                         FALSE,
+                         &Dev->RingRef);
+
+Again:
+  Status = XenBusIo->XsTransactionStart (XenBusIo, &xbt);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_WARN, "XenPvBlk: Failed to start transaction, %d\n", Status));
+    goto Error;
+  }
+
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName, "ring-ref", "%d",
+                               Dev->RingRef);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write ring-ref.\n"));
+    goto AbortTransaction;
+  }
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,
+                               "event-channel", "%d", Dev->EventChannel);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write event-channel.\n"));
+    goto AbortTransaction;
+  }

Review

Quoted 10 lines
(quoted diff) +10 -0
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,
+                               "protocol", "%a", XEN_IO_PROTO_ABI_NATIVE);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write protocol.\n"));
+    goto AbortTransaction;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));

Failed to switch state

Review

Quoted 12 lines
(quoted diff) +12 -0
+    goto AbortTransaction;
+  }
+
+  Status = XenBusIo->XsTransactionEnd (XenBusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
+  }
+
+  XenBusIo->RegisterWatchBackend (XenBusIo, "state", &Dev->StateWatchToken);
+
+  //
+  // Waiting backend

Waiting for backend.

Quoted 146 lines
(quoted diff) +146 -0
+  //
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: backend for %a/%d not available, rc=%d state=%d\n",
+            XenBusIo->Type, XenBusIo->DeviceId, Status, State));
+    goto Error2;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "info", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.VDiskInfo = Value;
+  if (Dev->MediaInfo.VDiskInfo & VDISK_READONLY) {
+    Dev->MediaInfo.ReadWrite = FALSE;
+  } else {
+    Dev->MediaInfo.ReadWrite = TRUE;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;
+
+  // Default value
+  Value = 0;
+  Status = XenBusReadUint64 (XenBusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenBusReadUint64 (XenBusIo, "feature-flush-cache", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureFlushCache = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureFlushCache = FALSE;
+  }
+
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %ld sectors of %d bytes\n",
+          Dev->MediaInfo.Sectors, Dev->MediaInfo.SectorSize));
+
+  *DevPtr = Dev;
+  return EFI_SUCCESS;
+
+Error2:
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");
+  goto Error;
+AbortTransaction:
+  XenBusIo->XsTransactionEnd (XenBusIo, xbt, TRUE);
+Error:
+  XenPvBlockFree (Dev);
+  return EFI_DEVICE_ERROR;
+}
+
+VOID
+XenPvBlockFrontShutdown (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  XENSTORE_STATUS Status;
+  UINT64 Value;
+
+  XenPvBlockSync (Dev);
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosing);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to Closing: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosing, NULL);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while waiting for closing backend state: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosed);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to Closed: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosed, NULL);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while waiting for closed backend state: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateInitialising);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to initialising: %d\n",
+            Status));
+    goto Close;
+  }
+
+  while (TRUE) {
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      DEBUG ((EFI_D_ERROR,
+              "XenPvBlk: error while waiting for new backend state: %d\n",
+              Status));
+      goto Close;
+    }
+    if (Value < XenbusStateInitWait || Value >= XenbusStateClosed) {
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            XenbusStateInitWait, Value));
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);
+  }
+
+Close:
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC

Review

Quoted 10 lines
(quoted diff) +10 -0
+VOID
+XenPvBlockWaitSlot (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  /* Wait for a slot */
+  if (RING_FULL (&Dev->Ring)) {
+    while (TRUE) {
+      XenPvBlockAsyncIoPoll (Dev);
+      if (!RING_FULL(&Dev->Ring)) {
                       ^
                      Missing space
Quoted 33 lines
(quoted diff) +33 -0
+        break;
+      }
+      /* Really no slot, could wait for an event on Dev->EventChannel. */
+    }
+  }
+}
+
+VOID
+XenPvBlockAsyncIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_DEVICE *Dev = IoData->Dev;
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  blkif_request_t *Request;
+  RING_IDX RingIndex;
+  BOOLEAN Notify;
+  INT32 NumSegments, Index;
+  UINTN Start, End;
+
+  // Can't io at non-sector-aligned location
+  ASSERT(!(IoData->Offset & (Dev->MediaInfo.SectorSize - 1)));
+  // Can't io non-sector-sized amounts
+  ASSERT(!(IoData->Size & (Dev->MediaInfo.SectorSize - 1)));
+  // Can't io non-sector-aligned buffer
+  ASSERT(!((UINTN) IoData->Buffer & (Dev->MediaInfo.SectorSize - 1)));
+
+  Start = (UINTN) IoData->Buffer & ~EFI_PAGE_MASK;
+  End = ((UINTN) IoData->Buffer + IoData->Size + EFI_PAGE_SIZE - 1) & ~EFI_PAGE_MASK;
+  IoData->NumRef = NumSegments = (End - Start) / EFI_PAGE_SIZE;
+
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+  XenPvBlockWaitSlot (Dev);
+  RingIndex = Dev->Ring.req_prod_pvt;
+  Request = RING_GET_REQUEST (&Dev->Ring, RingIndex);
+
+  Request->operation = IsWrite ? BLKIF_OP_WRITE : BLKIF_OP_READ;
+  Request->nr_segments = NumSegments;
+  Request->handle = Dev->DeviceId;
+  Request->id = (UINTN) IoData;
+  Request->sector_number = IoData->Offset / 512;

Offset? Why not just call it 'LBA' instead of Offset?

Quoted 66 lines
(quoted diff) +66 -0
+
+  for (Index = 0; Index < NumSegments; Index++) {
+    Request->seg[Index].first_sect = 0;
+    Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;
+  }
+  Request->seg[0].first_sect = ((UINTN) IoData->Buffer & EFI_PAGE_MASK) / 512;
+  Request->seg[NumSegments - 1].last_sect =
+      (((UINTN) IoData->Buffer + IoData->Size - 1) & EFI_PAGE_MASK) / 512;
+  for (Index = 0; Index < NumSegments; Index++) {
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;
+    XenBusIo->GrantAccess (XenBusIo, Dev->DomainId,
+                           Data >> EFI_PAGE_SHIFT, IsWrite,
+                           &Request->seg[Index].gref);
+    IoData->GrantRef[Index] = Request->seg[Index].gref;
+  }
+
+  Dev->Ring.req_prod_pvt = RingIndex + 1;
+
+  MemoryFence ();
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);
+
+  if (Notify) {
+    XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);
+  }
+}
+
+EFI_STATUS
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  //
+  // Status value that correspond to an IO in progress.
+  //
+  IoData->Status = EFI_ALREADY_STARTED;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+
+  while (IoData->Status == EFI_ALREADY_STARTED) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+  }
+
+  return IoData->Status;
+}
+
+STATIC
+VOID
+XenPvBlockPushOperation (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN UINT8                  Operation,
+  IN UINT64                 Id
+  )
+{
+  INT32 Index;
+  blkif_request_t *Request;
+  BOOLEAN Notify;
+
+  XenPvBlockWaitSlot (Dev);
+  Index = Dev->Ring.req_prod_pvt;
+  Request = RING_GET_REQUEST(&Dev->Ring, Index);
+  Request->operation = Operation;
+  Request->nr_segments = 0;
+  Request->handle = Dev->DeviceId;
+  Request->id = Id;
+  /* Not needed anyway, but the backend will check it */
+  Request->sector_number = 0;

Review

Quoted 10 lines
(quoted diff) +10 -0
+  Dev->Ring.req_prod_pvt = Index + 1;
+  MemoryFence ();
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);
+  if (Notify) {
+    XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+    XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);
+  }
+}
+
+VOID

Should you have a comment mentioning that a lock might be needed by the caller ? So that it won't try to make this call and also send (or read) data at the same time?

Quoted 254 lines
(quoted diff) +101 -0
+XenPvBlockSync (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  if (Dev->MediaInfo.ReadWrite) {
+    if (Dev->MediaInfo.FeatureBarrier) {
+      XenPvBlockPushOperation (Dev, BLKIF_OP_WRITE_BARRIER, 0);
+    }
+
+    if (Dev->MediaInfo.FeatureFlushCache) {
+      XenPvBlockPushOperation (Dev, BLKIF_OP_FLUSH_DISKCACHE, 0);
+    }
+  }
+
+  /* Note: This won't finish if another thread enqueues requests.  */
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (Dev);
+    if (RING_FREE_REQUESTS (&Dev->Ring) == RING_SIZE (&Dev->Ring)) {
+      break;
+    }
+  }
+}
+
+VOID
+XenPvBlockAsyncIoPoll (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  RING_IDX ProducerIndex, ConsumerIndex;
+  blkif_response_t *Response;
+  INT32 More;
+
+  do {
+    ProducerIndex = Dev->Ring.sring->rsp_prod;
+    /* Ensure we see queued responses up to 'ProducerIndex'. */
+    MemoryFence ();
+    ConsumerIndex = Dev->Ring.rsp_cons;
+
+    while (ConsumerIndex != ProducerIndex) {
+      XEN_BLOCK_FRONT_IO *IoData = NULL;
+      INT16 Status;
+
+      Response = RING_GET_RESPONSE (&Dev->Ring, ConsumerIndex);
+
+      IoData = (VOID *) (UINTN) Response->id;
+      Status = Response->status;
+
+      switch (Response->operation) {
+      case BLKIF_OP_READ:
+      case BLKIF_OP_WRITE:
+        {
+          INT32 Index;
+
+          if (Status != BLKIF_RSP_OKAY) {
+            DEBUG ((EFI_D_ERROR,
+                    "XenPvBlk: "
+                    "%a error %d on %a at offset %p, num bytes %p\n",
+                    Response->operation == BLKIF_OP_READ ? "read" : "write",
+                    Status, IoData->Dev->NodeName,
+                    IoData->Offset,
+                    IoData->Size));
+          }
+
+          for (Index = 0; Index < IoData->NumRef; Index++) {
+            Dev->XenBusIo->GrantEndAccess (Dev->XenBusIo, IoData->GrantRef[Index]);
+          }
+
+          break;
+        }
+
+      case BLKIF_OP_WRITE_BARRIER:
+        if (Status != BLKIF_RSP_OKAY) {
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: write barrier error %d\n", Status));
+        }
+        break;
+      case BLKIF_OP_FLUSH_DISKCACHE:
+        if (Status != BLKIF_RSP_OKAY) {
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: flush error %d\n", Status));
+        }
+        break;
+
+      default:
+        DEBUG ((EFI_D_ERROR,
+                "XenPvBlk: unrecognized block operation %d response (status %d)\n",
+                Response->operation, Status));
+        break;
+      }
+
+      Dev->Ring.rsp_cons = ++ConsumerIndex;
+      if (IoData != NULL) {
+        IoData->Status = Status ? EFI_DEVICE_ERROR : EFI_SUCCESS;
+      }
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {
+        /* We reentered, we must not continue here */
+        break;
+      }
+    }
+
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);
+  } while (More != 0);
+}
OvmfPkg/XenPvBlkDxe/BlockFront.h new file +87 -0
new file mode 100644
index 0000000..fb60dbd
@@ -0,0 +1,87 @@
+#include "XenPvBlkDxe.h"
+
+#include <IndustryStandard/Xen/event_channel.h>
+#include <IndustryStandard/Xen/io/blkif.h>
+
+typedef struct _XEN_BLOCK_FRONT_DEVICE XEN_BLOCK_FRONT_DEVICE;
+typedef struct _XEN_BLOCK_FRONT_IO XEN_BLOCK_FRONT_IO;
+
+struct _XEN_BLOCK_FRONT_IO
+{
+  XEN_BLOCK_FRONT_DEVICE  *Dev;
+  UINT8                   *Buffer;
+  UINTN                   Size;
+  UINTN                   Offset;
+
+  grant_ref_t             GrantRef[BLKIF_MAX_SEGMENTS_PER_REQUEST];
+  INT32                   NumRef;
+
+  EFI_STATUS              Status;
+};
+
+typedef struct
+{
+  UINT64    Sectors;
+  UINT32    SectorSize;
+  UINT32    VDiskInfo;
+  BOOLEAN   ReadWrite;
+  BOOLEAN   CdRom;
+  BOOLEAN   FeatureBarrier;
+  BOOLEAN   FeatureFlushCache;
+} XEN_BLOCK_FRONT_MEDIA_INFO;
+
+#define XEN_BLOCK_FRONT_SIGNATURE SIGNATURE_32 ('X', 'p', 'v', 'B')
+struct _XEN_BLOCK_FRONT_DEVICE {
+  UINT32                      Signature;
+  EFI_BLOCK_IO_PROTOCOL       BlockIo;
+  domid_t                     DomainId;
+
+  blkif_front_ring_t          Ring;
+  grant_ref_t                 RingRef;
+  evtchn_port_t               EventChannel;
+  blkif_vdev_t                DeviceId;
+
+  CONST CHAR8                 *NodeName;
+  XEN_BLOCK_FRONT_MEDIA_INFO  MediaInfo;
+
+  VOID                        *StateWatchToken;
+
+  XENBUS_PROTOCOL             *XenBusIo;
+};
+
+#define XEN_BLOCK_FRONT_FROM_BLOCK_IO(b) \
+  CR (b, XEN_BLOCK_FRONT_DEVICE, BlockIo, XEN_BLOCK_FRONT_SIGNATURE)
+
+EFI_STATUS
+XenPvBlockFrontInitialization (
+  IN  XENBUS_PROTOCOL  *XenBusIo,
+  IN  CONST CHAR8      *NodeName,
+  OUT XEN_BLOCK_FRONT_DEVICE **DevPtr
+  );
+
+VOID
+XenPvBlockFrontShutdown (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
+
+VOID
+XenPvBlockAsyncIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  );
+
+EFI_STATUS
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  );
+
+VOID
+XenPvBlockAsyncIoPoll (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
+
+VOID
+XenPvBlockSync (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +13 -0
index 00a8a2c..930333f 100644
@@ -36,6 +36,8 @@
 
 #include "XenPvBlkDxe.h"
 
+#include "BlockFront.h"
+
 
 ///
 /// Driver Binding Protocol instance
@@ -278,6 +280,7 @@ XenPvBlkDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenBusIo;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -291,7 +294,17 @@ XenPvBlkDxeDriverBindingStart (
     return Status;
   }
 
+  Status = XenPvBlockFrontInitialization (XenBusIo, XenBusIo->Node, &Dev);
+  if (EFI_ERROR (Status)) {
+    goto CloseProtocol;
+  }
+
   return EFI_SUCCESS;
+
+CloseProtocol:
+  gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
+                      This->DriverBindingHandle, ControllerHandle);
+  return Status;
 }
 
 /**
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index aaa809f..619ed8f 100644
@@ -50,6 +50,8 @@
   XenPvBlkDxe.c
   ComponentName.c
   ComponentName.h
+  BlockFront.c
+  BlockFront.h
 
 
 [LibraryClasses]
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
#68 lore raw

Re: [PATCH v2 17/18] OvmfPkg/XenPvBlkDxe: Add BlockFront client.

Quoted 4 lines · Konrad Rzeszutek Wilk

Review

Quoted 2 lines
(quoted diff) +2 -0
+/**
+  Helper to read an interger from XenStore.

integer?

Yes.

Quoted 26 lines
Quoted 26 lines
(quoted diff) +26 -0
+
+  @param This         A pointer to a XENBUS_PROTOCOL instance.
+  @param Node         The XenStore node to read from.
+  @param FromBackend  Read frontend or backend value.
+  @param ValuePtr     Where to put the value.
+
+  @retval XENSTORE_STATUS_SUCCESS  If succefull, will update ValuePtr.
+  @return                          Any other return value indicate the error,
+                                   ValuePtr is not updated in this case.
+**/
+STATIC
+XENSTORE_STATUS
+XenBusReadUint64 (
+  IN  XENBUS_PROTOCOL *This,
+  IN  CONST CHAR8     *Node,
+  IN  BOOLEAN         FromBackend,
+  OUT UINT64          *ValuePtr
+  )
+{
+  XENSTORE_STATUS Status;
+  CHAR8 *p;
+
+  if (!FromBackend) {
+    Status = This->XsRead (This, XST_NIL, Node, (VOID**)&p);
+  } else {
+    Status = This->XsBackendRead (This, XST_NIL, Node, (VOID**)&p);
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+  }
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+  // FIXME Will ASSERT if p overflow UINT64 ...

Do you just want to add the ASSERT in the code then?

The problem is not in this function, but in AsciiStrDecimalToUint64. If the value pass to AsciiStrDecimalToUint64 is bigger than uint64, then AsciiStrDecimalToUint64 will ASSERT.

I will look for an alternative, or just have a better comment here.

Quoted 26 lines
Quoted 26 lines
(quoted diff) +26 -0
+  *ValuePtr = AsciiStrDecimalToUint64 (p);
+  FreePool (p);
+  return Status;
+}
+
+/**
+  Free an instance of XEN_BLOCK_FRONT_DEVICE.
+
+  @param Dev  The instance to free.
+**/
+STATIC
+VOID
+XenPvBlockFree (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+
+  if (Dev->RingRef != 0) {
+    XenBusIo->GrantEndAccess (XenBusIo, Dev->RingRef);
+  }
+  if (Dev->Ring.sring != NULL) {
+    FreePages (Dev->Ring.sring, 1);
+  }
+  if (Dev->EventChannel != 0) {
+    XenBusIo->EventChannelClose (XenBusIo, Dev->EventChannel);
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+  }
+  FreePool (Dev);
+}
+
+/**
+  Wait until until the backend have reach the ExpectedState.

s/have reached/has reached/

ok

Quoted 6 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+
+  @param Dev            A XEN_BLOCK_FRONT_DEVICE instance.
+  @param ExpectedState  The backend state expected.
+  @param LastStatePtr   An optionnal pointer where to right the final state.

s/optionnal/optional/

ok

Quoted 120 lines
Quoted 120 lines
(quoted diff) +120 -0
+
+  @return Return XENSTORE_STATUS_SUCCESS if the new backend state is ExpectedState
+          or return an error otherwise.
+**/
+STATIC
+XENSTORE_STATUS
+XenPvBlkWaitForBackendState (
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN  XenbusState            ExpectedState,
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status = XENSTORE_STATUS_SUCCESS;
+
+  while (TRUE) {
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
+    }
+    if (Value > XenbusStateReconfigured) {
+      //
+      // Value is not a State value.
+      //
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State == ExpectedState) {
+      break;
+    } else if (State > ExpectedState) {
+      Status = XENSTORE_STATUS_FAIL;
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            ExpectedState, State));
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return Status;
+}
+
+EFI_STATUS
+XenPvBlockFrontInitialization (
+  IN  XENBUS_PROTOCOL         *XenBusIo,
+  IN  CONST CHAR8             *NodeName,
+  OUT XEN_BLOCK_FRONT_DEVICE  **DevPtr
+  )
+{
+  XENSTORE_TRANSACTION xbt;
+  CHAR8 *DeviceType;
+  blkif_sring_t *SharedRing;
+  XENSTORE_STATUS Status;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
+  XenbusState State;
+  UINT64 Value;
+
+  ASSERT (NodeName != NULL);
+
+  Dev = AllocateZeroPool (sizeof (XEN_BLOCK_FRONT_DEVICE));
+  Dev->Signature = XEN_BLOCK_FRONT_SIGNATURE;
+  Dev->NodeName = NodeName;
+  Dev->XenBusIo = XenBusIo;
+  Dev->DeviceId = XenBusIo->DeviceId;
+
+  XenBusIo->XsRead (XenBusIo, XST_NIL, "device-type", (VOID**)&DeviceType);
+  if (AsciiStrCmp (DeviceType, "cdrom") == 0) {
+    Dev->MediaInfo.CdRom = TRUE;
+  } else {
+    Dev->MediaInfo.CdRom = FALSE;
+  }
+  FreePool (DeviceType);
+
+  Status = XenBusReadUint64 (XenBusIo, "backend-id", FALSE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT16_MAX) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to get backend-id (%d)\n",
+            Status));
+    goto Error;
+  }
+  Dev->DomainId = Value;
+  XenBusIo->EventChannelAllocate (XenBusIo, Dev->DomainId, &Dev->EventChannel);
+
+  SharedRing = (blkif_sring_t*) AllocatePages (1);
+  SHARED_RING_INIT (SharedRing);
+  FRONT_RING_INIT (&Dev->Ring, SharedRing, EFI_PAGE_SIZE);
+  XenBusIo->GrantAccess (XenBusIo,
+                         Dev->DomainId,
+                         (INTN) SharedRing >> EFI_PAGE_SHIFT,
+                         FALSE,
+                         &Dev->RingRef);
+
+Again:
+  Status = XenBusIo->XsTransactionStart (XenBusIo, &xbt);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_WARN, "XenPvBlk: Failed to start transaction, %d\n", Status));
+    goto Error;
+  }
+
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName, "ring-ref", "%d",
+                               Dev->RingRef);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write ring-ref.\n"));
+    goto AbortTransaction;
+  }
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,
+                               "event-channel", "%d", Dev->EventChannel);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write event-channel.\n"));
+    goto AbortTransaction;
+  }
+  Status = XenBusIo->XsPrintf (XenBusIo, xbt, NodeName,
+                               "protocol", "%a", XEN_IO_PROTO_ABI_NATIVE);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed to write protocol.\n"));
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+    goto AbortTransaction;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));

Failed to switch state

ok

Quoted 6 lines
Quoted 6 lines
(quoted diff) +6 -0
+    goto AbortTransaction;
+  }
+
+  Status = XenBusIo->XsTransactionEnd (XenBusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+  }
+
+  XenBusIo->RegisterWatchBackend (XenBusIo, "state", &Dev->StateWatchToken);
+
+  //
+  // Waiting backend

Waiting for backend.

ok

Quoted 150 lines
Quoted 150 lines
(quoted diff) +150 -0
+  //
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: backend for %a/%d not available, rc=%d state=%d\n",
+            XenBusIo->Type, XenBusIo->DeviceId, Status, State));
+    goto Error2;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "info", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.VDiskInfo = Value;
+  if (Dev->MediaInfo.VDiskInfo & VDISK_READONLY) {
+    Dev->MediaInfo.ReadWrite = FALSE;
+  } else {
+    Dev->MediaInfo.ReadWrite = TRUE;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenBusReadUint64 (XenBusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;
+
+  // Default value
+  Value = 0;
+  Status = XenBusReadUint64 (XenBusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenBusReadUint64 (XenBusIo, "feature-flush-cache", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureFlushCache = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureFlushCache = FALSE;
+  }
+
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %ld sectors of %d bytes\n",
+          Dev->MediaInfo.Sectors, Dev->MediaInfo.SectorSize));
+
+  *DevPtr = Dev;
+  return EFI_SUCCESS;
+
+Error2:
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");
+  goto Error;
+AbortTransaction:
+  XenBusIo->XsTransactionEnd (XenBusIo, xbt, TRUE);
+Error:
+  XenPvBlockFree (Dev);
+  return EFI_DEVICE_ERROR;
+}
+
+VOID
+XenPvBlockFrontShutdown (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  XENSTORE_STATUS Status;
+  UINT64 Value;
+
+  XenPvBlockSync (Dev);
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosing);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to Closing: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosing, NULL);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while waiting for closing backend state: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateClosed);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to Closed: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateClosed, NULL);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while waiting for closed backend state: %d\n",
+            Status));
+    goto Close;
+  }
+
+  Status = XenBusIo->SetState (XenBusIo, XST_NIL, XenbusStateInitialising);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR,
+            "XenPvBlk: error while changing state to initialising: %d\n",
+            Status));
+    goto Close;
+  }
+
+  while (TRUE) {
+    Status = XenBusReadUint64 (XenBusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      DEBUG ((EFI_D_ERROR,
+              "XenPvBlk: error while waiting for new backend state: %d\n",
+              Status));
+      goto Close;
+    }
+    if (Value < XenbusStateInitWait || Value >= XenbusStateClosed) {
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            XenbusStateInitWait, Value));
+    XenBusIo->WaitForWatch (XenBusIo, Dev->StateWatchToken);
+  }
+
+Close:
+  XenBusIo->UnregisterWatch (XenBusIo, Dev->StateWatchToken);
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "ring-ref");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "event-channel");
+  XenBusIo->XsRemove (XenBusIo, XST_NIL, "protocol");
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC
+VOID
+XenPvBlockWaitSlot (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+{
+  /* Wait for a slot */
+  if (RING_FULL (&Dev->Ring)) {
+    while (TRUE) {
+      XenPvBlockAsyncIoPoll (Dev);
+      if (!RING_FULL(&Dev->Ring)) {
                       ^
                      Missing space

Indeed, will fix it.

Quoted 37 lines
Quoted 37 lines
(quoted diff) +37 -0
+        break;
+      }
+      /* Really no slot, could wait for an event on Dev->EventChannel. */
+    }
+  }
+}
+
+VOID
+XenPvBlockAsyncIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_DEVICE *Dev = IoData->Dev;
+  XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+  blkif_request_t *Request;
+  RING_IDX RingIndex;
+  BOOLEAN Notify;
+  INT32 NumSegments, Index;
+  UINTN Start, End;
+
+  // Can't io at non-sector-aligned location
+  ASSERT(!(IoData->Offset & (Dev->MediaInfo.SectorSize - 1)));
+  // Can't io non-sector-sized amounts
+  ASSERT(!(IoData->Size & (Dev->MediaInfo.SectorSize - 1)));
+  // Can't io non-sector-aligned buffer
+  ASSERT(!((UINTN) IoData->Buffer & (Dev->MediaInfo.SectorSize - 1)));
+
+  Start = (UINTN) IoData->Buffer & ~EFI_PAGE_MASK;
+  End = ((UINTN) IoData->Buffer + IoData->Size + EFI_PAGE_SIZE - 1) & ~EFI_PAGE_MASK;
+  IoData->NumRef = NumSegments = (End - Start) / EFI_PAGE_SIZE;
+
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);
+
+  XenPvBlockWaitSlot (Dev);
+  RingIndex = Dev->Ring.req_prod_pvt;
+  Request = RING_GET_REQUEST (&Dev->Ring, RingIndex);
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+
+  Request->operation = IsWrite ? BLKIF_OP_WRITE : BLKIF_OP_READ;
+  Request->nr_segments = NumSegments;
+  Request->handle = Dev->DeviceId;
+  Request->id = (UINTN) IoData;
+  Request->sector_number = IoData->Offset / 512;

Offset? Why not just call it 'LBA' instead of Offset?

Because LBA are in Media.BlockSize bytes and Offset are in 1 byte.

Quoted 72 lines
Quoted 72 lines
(quoted diff) +72 -0
+
+  for (Index = 0; Index < NumSegments; Index++) {
+    Request->seg[Index].first_sect = 0;
+    Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;
+  }
+  Request->seg[0].first_sect = ((UINTN) IoData->Buffer & EFI_PAGE_MASK) / 512;
+  Request->seg[NumSegments - 1].last_sect =
+      (((UINTN) IoData->Buffer + IoData->Size - 1) & EFI_PAGE_MASK) / 512;
+  for (Index = 0; Index < NumSegments; Index++) {
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;
+    XenBusIo->GrantAccess (XenBusIo, Dev->DomainId,
+                           Data >> EFI_PAGE_SHIFT, IsWrite,
+                           &Request->seg[Index].gref);
+    IoData->GrantRef[Index] = Request->seg[Index].gref;
+  }
+
+  Dev->Ring.req_prod_pvt = RingIndex + 1;
+
+  MemoryFence ();
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);
+
+  if (Notify) {
+    XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);
+  }
+}
+
+EFI_STATUS
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  //
+  // Status value that correspond to an IO in progress.
+  //
+  IoData->Status = EFI_ALREADY_STARTED;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+
+  while (IoData->Status == EFI_ALREADY_STARTED) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+  }
+
+  return IoData->Status;
+}
+
+STATIC
+VOID
+XenPvBlockPushOperation (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN UINT8                  Operation,
+  IN UINT64                 Id
+  )
+{
+  INT32 Index;
+  blkif_request_t *Request;
+  BOOLEAN Notify;
+
+  XenPvBlockWaitSlot (Dev);
+  Index = Dev->Ring.req_prod_pvt;
+  Request = RING_GET_REQUEST(&Dev->Ring, Index);
+  Request->operation = Operation;
+  Request->nr_segments = 0;
+  Request->handle = Dev->DeviceId;
+  Request->id = Id;
+  /* Not needed anyway, but the backend will check it */
+  Request->sector_number = 0;
+  Dev->Ring.req_prod_pvt = Index + 1;
+  MemoryFence ();
+  RING_PUSH_REQUESTS_AND_CHECK_NOTIFY (&Dev->Ring, Notify);
+  if (Notify) {
+    XENBUS_PROTOCOL *XenBusIo = Dev->XenBusIo;
+    XenBusIo->EventChannelNotify (XenBusIo, Dev->EventChannel);
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+  }
+}
+
+VOID

Should you have a comment mentioning that a lock might be needed by the caller ? So that it won't try to make this call and also send (or read) data at the same time?

I think that fine without it. At the moment, only one request can be done at a time, due to the firmware limitation and the protocol (EfiBlockIo) implemented.

Something might be needed to be done if we try to implement BlockIo2. (There is an extra argument, an efi_event or callback.) But I prefare to not think about it right now.

Quoted 254 lines
Quoted 254 lines
(quoted diff) +101 -0
+XenPvBlockSync (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  if (Dev->MediaInfo.ReadWrite) {
+    if (Dev->MediaInfo.FeatureBarrier) {
+      XenPvBlockPushOperation (Dev, BLKIF_OP_WRITE_BARRIER, 0);
+    }
+
+    if (Dev->MediaInfo.FeatureFlushCache) {
+      XenPvBlockPushOperation (Dev, BLKIF_OP_FLUSH_DISKCACHE, 0);
+    }
+  }
+
+  /* Note: This won't finish if another thread enqueues requests.  */
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (Dev);
+    if (RING_FREE_REQUESTS (&Dev->Ring) == RING_SIZE (&Dev->Ring)) {
+      break;
+    }
+  }
+}
+
+VOID
+XenPvBlockAsyncIoPoll (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  )
+{
+  RING_IDX ProducerIndex, ConsumerIndex;
+  blkif_response_t *Response;
+  INT32 More;
+
+  do {
+    ProducerIndex = Dev->Ring.sring->rsp_prod;
+    /* Ensure we see queued responses up to 'ProducerIndex'. */
+    MemoryFence ();
+    ConsumerIndex = Dev->Ring.rsp_cons;
+
+    while (ConsumerIndex != ProducerIndex) {
+      XEN_BLOCK_FRONT_IO *IoData = NULL;
+      INT16 Status;
+
+      Response = RING_GET_RESPONSE (&Dev->Ring, ConsumerIndex);
+
+      IoData = (VOID *) (UINTN) Response->id;
+      Status = Response->status;
+
+      switch (Response->operation) {
+      case BLKIF_OP_READ:
+      case BLKIF_OP_WRITE:
+        {
+          INT32 Index;
+
+          if (Status != BLKIF_RSP_OKAY) {
+            DEBUG ((EFI_D_ERROR,
+                    "XenPvBlk: "
+                    "%a error %d on %a at offset %p, num bytes %p\n",
+                    Response->operation == BLKIF_OP_READ ? "read" : "write",
+                    Status, IoData->Dev->NodeName,
+                    IoData->Offset,
+                    IoData->Size));
+          }
+
+          for (Index = 0; Index < IoData->NumRef; Index++) {
+            Dev->XenBusIo->GrantEndAccess (Dev->XenBusIo, IoData->GrantRef[Index]);
+          }
+
+          break;
+        }
+
+      case BLKIF_OP_WRITE_BARRIER:
+        if (Status != BLKIF_RSP_OKAY) {
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: write barrier error %d\n", Status));
+        }
+        break;
+      case BLKIF_OP_FLUSH_DISKCACHE:
+        if (Status != BLKIF_RSP_OKAY) {
+          DEBUG ((EFI_D_ERROR, "XenPvBlk: flush error %d\n", Status));
+        }
+        break;
+
+      default:
+        DEBUG ((EFI_D_ERROR,
+                "XenPvBlk: unrecognized block operation %d response (status %d)\n",
+                Response->operation, Status));
+        break;
+      }
+
+      Dev->Ring.rsp_cons = ++ConsumerIndex;
+      if (IoData != NULL) {
+        IoData->Status = Status ? EFI_DEVICE_ERROR : EFI_SUCCESS;
+      }
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {
+        /* We reentered, we must not continue here */
+        break;
+      }
+    }
+
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);
+  } while (More != 0);
+}
OvmfPkg/XenPvBlkDxe/BlockFront.h new file +87 -0
new file mode 100644
index 0000000..fb60dbd
@@ -0,0 +1,87 @@
+#include "XenPvBlkDxe.h"
+
+#include <IndustryStandard/Xen/event_channel.h>
+#include <IndustryStandard/Xen/io/blkif.h>
+
+typedef struct _XEN_BLOCK_FRONT_DEVICE XEN_BLOCK_FRONT_DEVICE;
+typedef struct _XEN_BLOCK_FRONT_IO XEN_BLOCK_FRONT_IO;
+
+struct _XEN_BLOCK_FRONT_IO
+{
+  XEN_BLOCK_FRONT_DEVICE  *Dev;
+  UINT8                   *Buffer;
+  UINTN                   Size;
+  UINTN                   Offset;
+
+  grant_ref_t             GrantRef[BLKIF_MAX_SEGMENTS_PER_REQUEST];
+  INT32                   NumRef;
+
+  EFI_STATUS              Status;
+};
+
+typedef struct
+{
+  UINT64    Sectors;
+  UINT32    SectorSize;
+  UINT32    VDiskInfo;
+  BOOLEAN   ReadWrite;
+  BOOLEAN   CdRom;
+  BOOLEAN   FeatureBarrier;
+  BOOLEAN   FeatureFlushCache;
+} XEN_BLOCK_FRONT_MEDIA_INFO;
+
+#define XEN_BLOCK_FRONT_SIGNATURE SIGNATURE_32 ('X', 'p', 'v', 'B')
+struct _XEN_BLOCK_FRONT_DEVICE {
+  UINT32                      Signature;
+  EFI_BLOCK_IO_PROTOCOL       BlockIo;
+  domid_t                     DomainId;
+
+  blkif_front_ring_t          Ring;
+  grant_ref_t                 RingRef;
+  evtchn_port_t               EventChannel;
+  blkif_vdev_t                DeviceId;
+
+  CONST CHAR8                 *NodeName;
+  XEN_BLOCK_FRONT_MEDIA_INFO  MediaInfo;
+
+  VOID                        *StateWatchToken;
+
+  XENBUS_PROTOCOL             *XenBusIo;
+};
+
+#define XEN_BLOCK_FRONT_FROM_BLOCK_IO(b) \
+  CR (b, XEN_BLOCK_FRONT_DEVICE, BlockIo, XEN_BLOCK_FRONT_SIGNATURE)
+
+EFI_STATUS
+XenPvBlockFrontInitialization (
+  IN  XENBUS_PROTOCOL  *XenBusIo,
+  IN  CONST CHAR8      *NodeName,
+  OUT XEN_BLOCK_FRONT_DEVICE **DevPtr
+  );
+
+VOID
+XenPvBlockFrontShutdown (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
+
+VOID
+XenPvBlockAsyncIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  );
+
+EFI_STATUS
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  );
+
+VOID
+XenPvBlockAsyncIoPoll (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
+
+VOID
+XenPvBlockSync (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev
+  );
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +13 -0
index 00a8a2c..930333f 100644
@@ -36,6 +36,8 @@
 
 #include "XenPvBlkDxe.h"
 
+#include "BlockFront.h"
+
 
 ///
 /// Driver Binding Protocol instance
@@ -278,6 +280,7 @@ XenPvBlkDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenBusIo;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -291,7 +294,17 @@ XenPvBlkDxeDriverBindingStart (
     return Status;
   }
 
+  Status = XenPvBlockFrontInitialization (XenBusIo, XenBusIo->Node, &Dev);
+  if (EFI_ERROR (Status)) {
+    goto CloseProtocol;
+  }
+
   return EFI_SUCCESS;
+
+CloseProtocol:
+  gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
+                      This->DriverBindingHandle, ControllerHandle);
+  return Status;
 }
 
 /**
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index aaa809f..619ed8f 100644
@@ -50,6 +50,8 @@
   XenPvBlkDxe.c
   ComponentName.c
   ComponentName.h
+  BlockFront.c
+  BlockFront.h
 
 
 [LibraryClasses]
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Signature · 1 line
Anthony PERARD

A message that is not in the archive (sent off-list or not yet received): [email protected]

#70 lore raw

Re: [PATCH v2 18/18] OvmfPkg/XenPvBlkDxe: Add BlockIo.

Quoted 1 line · Anthony PERARD

Install the BlockIo protocol.

Implement. Perhaps point out that the blkif.h is a good literature to understand it?

Quoted 180 lines

Contributed-under: TianoCore Contribution Agreement 1.0

---
Change in V2:
- Remove blockIo2 headers.
- Fix few comment.
- file header, copyright
- Rewrite few comment and error messages
- No more callback
- Improving block read/write, increase to the max size in one request (instead of only 8pages)
- Fix lastblock when it's a cdrom
- Do uninitialisation when fail to install fail
- few comment
- Licenses

---
 OvmfPkg/XenPvBlkDxe/BlockIo.c       | 292 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h       | 124 +++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |  64 ++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |   1 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 5 files changed, 483 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +147 -0
new file mode 100644
index 0000000..f08339b
@@ -0,0 +1,292 @@
+/** @file
+  BlockIo implementation for Xen PV Block driver.
+
+  This file is implementing the interface between the actual driver in
+  BlockFront.c to the BlockIo protocol.
+
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGE.
+
+**/
+
+#include "XenPvBlkDxe.h"
+
+#include "BlockFront.h"
+
+///
+/// Block I/O Media structure
+///
+GLOBAL_REMOVE_IF_UNREFERENCED
+EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia = {
+  0,      // MediaId
+  FALSE,  // RemovableMedia
+  FALSE,  // MediaPresent
+  FALSE,  // LogicalPartition
+  TRUE,   // ReadOnly
+  FALSE,  // WriteCaching
+  512,    // BlockSize
+  512,    // IoAlign, BlockFront does not support less than 512 bits-aligned.
+  0,      // LastBlock
+  0,      // LowestAlignedLba
+  0,      // LogicalBlocksPerPhysicalBlock
+  0       // OptimalTransferLengthGranularity
+};
+
+///
+/// Block I/O Protocol instance
+///
+GLOBAL_REMOVE_IF_UNREFERENCED
+EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo = {
+  EFI_BLOCK_IO_PROTOCOL_REVISION3,          // Revision
+  &gXenPvBlkDxeBlockIoMedia,                // Media
+  XenPvBlkDxeBlockIoReset,                  // Reset
+  XenPvBlkDxeBlockIoReadBlocks,             // ReadBlocks
+  XenPvBlkDxeBlockIoWriteBlocks,            // WriteBlocks
+  XenPvBlkDxeBlockIoFlushBlocks             // FlushBlocks
+};
+
+
+
+
+/**
+  Read/Write BufferSize bytes from Lba into Buffer.
+
+  This function is commun to XenPvBlkDxeBlockIoReadBlocks and
+  XenPvBlkDxeBlockIoWriteBlocks.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from/write to.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination/source buffer for the data.
+  @param  IsWrite    Indicate if the operation is write or read.
+
+  @return See description of XenPvBlkDxeBlockIoReadBlocks and
+          XenPvBlkDxeBlockIoWriteBlocks.
+**/
+STATIC
+EFI_STATUS
+XenPvBlkDxeBlockIoReadWriteBlocks (
+  IN     EFI_BLOCK_IO_PROTOCOL  *This,
+  IN     UINT32                 MediaId,
+  IN     EFI_LBA                Lba,
+  IN     UINTN                  BufferSize,
+  IN OUT VOID                   *Buffer,
+  IN     BOOLEAN                IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_IO IoData;
+  EFI_BLOCK_IO_MEDIA *Media;
+  UINTN NextOffset;
+  EFI_STATUS Status;
+
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+  if (BufferSize == 0) {
+    return EFI_SUCCESS;
+  }
+
+  Media = This->Media;
+
+  if (BufferSize % Media->BlockSize != 0) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: Bad buffer size: 0x%X\n", BufferSize));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  if (Lba > Media->LastBlock ||
+      (BufferSize / Media->BlockSize) - 1 > Media->LastBlock - Lba) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: %a with invalid LBA: 0x%LX, size: 0x%x\n",
+            IsWrite ? "Write" : "Read", Lba, BufferSize));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (IsWrite && Media->ReadOnly) {
+    return EFI_WRITE_PROTECTED;
+  }
+
+  if ((Media->IoAlign > 1) && (UINTN)Buffer & (Media->IoAlign - 1)) {
+    //
+    // Grub2 does not appear to respect IoAlign of 512, so reallocate the
+    // buffer here.
+    //
+    VOID *NewBuffer;
+
+    //
+    // Try again with a properly aligned buffer.
+    //
+    NewBuffer = AllocateAlignedPages((BufferSize + EFI_PAGE_SIZE) / EFI_PAGE_SIZE,
+                                     Media->IoAlign);
+    if (!IsWrite) {
+      Status = XenPvBlkDxeBlockIoReadBlocks (This, MediaId,
+                                             Lba, BufferSize, NewBuffer);
+      CopyMem (Buffer, NewBuffer, BufferSize);
+    } else {

OvmfPkg/XenPvBlkDxe/BlockIo.c line 157

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +10 -0
+      CopyMem (NewBuffer, Buffer, BufferSize);
+      Status = XenPvBlkDxeBlockIoWriteBlocks (This, MediaId,
+                                              Lba, BufferSize, NewBuffer);
+    }
+    FreeAlignedPages (NewBuffer, (BufferSize + EFI_PAGE_SIZE) / EFI_PAGE_SIZE);
+    return Status;
+  }
+
+  IoData.Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (This);
+  NextOffset = Lba * Media->BlockSize;

Perhaps instead of calling it 'Offset' could it be Sector? SAy 'NextSector' ? [edit: Just ditch this]

OvmfPkg/XenPvBlkDxe/BlockIo.c line 169

Quoted 12 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +12 -0
+
+  while (BufferSize > 0) {
+    if (((UINTN)Buffer & EFI_PAGE_MASK) == 0) {
+      IoData.Size = MIN (BLKIF_MAX_SEGMENTS_PER_REQUEST * EFI_PAGE_SIZE,
+                         BufferSize);
+    } else {
+      IoData.Size = MIN ((BLKIF_MAX_SEGMENTS_PER_REQUEST - 1) * EFI_PAGE_SIZE,
+                         BufferSize);
+    }
+
+    IoData.Buffer = Buffer;
+    IoData.Offset = NextOffset;

And this would be 'IoData.Lba = NextSector' or perhaps to make obvious:
IoData.Lba = Lba * Media->BlockSize;

Thought why even bother with the multiplication of BlockSize when you are going to divide it in the XenPvBlockIo again? Perhaps just do

IoData.Lba = Lba;
[edit: Use that]

And modify the 'Lba' value ?

OvmfPkg/XenPvBlkDxe/BlockIo.c line 172

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+    BufferSize -= IoData.Size;
+    Buffer = (VOID*) ((UINTN) Buffer + IoData.Size);
+    NextOffset += IoData.Size;

So this would be 'Lba += IoData.Size'

That would make this easier - and you can ditch the NextOffset altogther? [edit: And Dev.Lba would have the LBA value instead of the odd 'Offset' thing]

Quoted 149 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +120 -0
+    Status = XenPvBlockIo (&IoData, IsWrite);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: Error durring %a operation.\n",
+              IsWrite ? "write" : "read"));
+      return Status;
+    }
+  }
+  return EFI_SUCCESS;
+}
+
+
+/**
+  Read BufferSize bytes from Lba into Buffer.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination buffer for the data. The caller is
+                     responsible for either having implicit or explicit ownership of the buffer.
+
+  @retval EFI_SUCCESS           The data was read correctly from the device.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReadBlocks (
+  IN  EFI_BLOCK_IO_PROTOCOL         *This,
+  IN  UINT32                        MediaId,
+  IN  EFI_LBA                       Lba,
+  IN  UINTN                         BufferSize,
+  OUT VOID                          *Buffer
+  )
+{
+  return XenPvBlkDxeBlockIoReadWriteBlocks (This,
+      MediaId, Lba, BufferSize, Buffer, FALSE);
+}
+
+/**
+  Write BufferSize bytes from Lba into Buffer.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    The media ID that the write request is for.
+  @param  Lba        The starting logical block address to be written. The caller is
+                     responsible for writing to only legitimate locations.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the source buffer for the data.
+
+  @retval EFI_SUCCESS           The data was written correctly to the device.
+  @retval EFI_WRITE_PROTECTED   The device can not be written to.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoWriteBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  IN VOID                           *Buffer
+  )
+{
+  return XenPvBlkDxeBlockIoReadWriteBlocks (This,
+      MediaId, Lba, BufferSize, Buffer, TRUE);
+}
+
+/**
+  Flush the Block Device.
+
+  @param  This              Indicates a pointer to the calling context.
+
+  @retval EFI_SUCCESS       All outstanding data was written to the device
+  @retval EFI_DEVICE_ERROR  The device reported an error while writting back the data
+  @retval EFI_NO_MEDIA      There is no media in the device.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoFlushBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL  *This
+  )
+{
+  XenPvBlockSync (XEN_BLOCK_FRONT_FROM_BLOCK_IO (This));
+  return EFI_SUCCESS;
+}
+
+/**
+  Reset the block device hardware.
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Not used.
+
+  @retval EFI_SUCCESS          The device was reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO_PROTOCOL   *This,
+  IN BOOLEAN                 ExtendedVerification
+  )
+{
+  //
+  // Since the initialization of the devices is done, then the device is
+  // working correctly.
+  //
+  return EFI_SUCCESS;
+}
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +23 -0
new file mode 100644
index 0000000..22b6de2
@@ -0,0 +1,124 @@
+/** @file
+  BlockIo function declaration for Xen PV block driver.
+
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;

OvmfPkg/XenPvBlkDxe/BlockIo.h line 33

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGE.
+
+**/
+
+/**
+  Read BufferSize bytes from Lba into Buffer.

The caller has to ensure that the XenPvBlkDxeBlockIoFlushBlocks or Reset are not called when this is executing.

Quoted 19 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +19 -0
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination buffer for the data. The caller is
+                     responsible for either having implicit or explicit ownership of the buffer.
+
+  @retval EFI_SUCCESS           The data was read correctly from the device.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI

OvmfPkg/XenPvBlkDxe/BlockIo.h line 62

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+XenPvBlkDxeBlockIoReadBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  OUT VOID                          *Buffer
+  );
+
+/**
+  Write BufferSize bytes from Lba into Buffer.

The caller has to ensure that the XenPvBlkDxeBlockIoFlushBlocks or Reset are not called when this is executing.

Quoted 20 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +20 -0
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    The media ID that the write request is for.
+  @param  Lba        The starting logical block address to be written. The caller is
+                     responsible for writing to only legitimate locations.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the source buffer for the data.
+
+  @retval EFI_SUCCESS           The data was written correctly to the device.
+  @retval EFI_WRITE_PROTECTED   The device can not be written to.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI

OvmfPkg/XenPvBlkDxe/BlockIo.h line 92

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+XenPvBlkDxeBlockIoWriteBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  IN VOID                           *Buffer
+  );
+
+/**
+  Flush the Block Device.

The caller has to ensure that there are no other calls to read/write to the device when this is executued.

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +6 -0
+
+  @param  This              Indicates a pointer to the calling context.
+
+  @retval EFI_SUCCESS       All outstanding data was written to the device
+  @retval EFI_DEVICE_ERROR  The device reported an error while writting back the data
+  @retval EFI_NO_MEDIA      There is no media in the device.

OvmfPkg/XenPvBlkDxe/BlockIo.h line 108

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoFlushBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL  *This
+  );
+
+/**
+  Reset the block device hardware.

Ditto.

Quoted 140 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +16 -0
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Not used.
+
+  @retval EFI_SUCCESS          The device was reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO_PROTOCOL   *This,
+  IN BOOLEAN                 ExtendedVerification
+  );
+
+extern EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia;
+extern EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo;
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +64 -0
index 930333f..d530600 100644
@@ -281,6 +281,7 @@ XenPvBlkDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenBusIo;
   XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -299,8 +300,44 @@ XenPvBlkDxeDriverBindingStart (
     goto CloseProtocol;
   }
 
+  CopyMem (&Dev->BlockIo, &gXenPvBlkDxeBlockIo, sizeof (EFI_BLOCK_IO_PROTOCOL));
+  Media = AllocateCopyPool (sizeof (EFI_BLOCK_IO_MEDIA),
+                            &gXenPvBlkDxeBlockIoMedia);
+  if (Dev->MediaInfo.VDiskInfo & VDISK_REMOVABLE) {
+    Media->RemovableMedia = TRUE;
+  }
+  Media->MediaPresent = TRUE;
+  Media->ReadOnly = !Dev->MediaInfo.ReadWrite;
+  if (Dev->MediaInfo.CdRom) {
+    //
+    // If it's a cdrom, the blocksize value need to be 2048 for OVMF to
+    // recognize it as a cdrom:
+    //    MdeModulePkg/Universal/Disk/PartitionDxe/ElTorito.c
+    //
+    Media->BlockSize = 2048;
+    Media->LastBlock = DivU64x32 (Dev->MediaInfo.Sectors,
+                                  Media->BlockSize / Dev->MediaInfo.SectorSize) - 1;
+  } else {
+    Media->BlockSize = Dev->MediaInfo.SectorSize;
+    Media->LastBlock = Dev->MediaInfo.Sectors - 1;
+  }
+  Dev->BlockIo.Media = Media;
+
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                    &ControllerHandle,
+                    &gEfiBlockIoProtocolGuid, &Dev->BlockIo,
+                    NULL
+                    );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: install protocol fail: %r\n", Status));
+    goto UninitBlockFront;
+  }
+
   return EFI_SUCCESS;
 
+UninitBlockFront:
+  FreePool (Media);
+  XenPvBlockFrontShutdown (Dev);
 CloseProtocol:
   gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
                       This->DriverBindingHandle, ControllerHandle);
@@ -342,6 +379,33 @@ XenPvBlkDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  EFI_BLOCK_IO_PROTOCOL *BlockIo;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
+  EFI_STATUS Status;
+
+  Status = gBS->OpenProtocol (
+                  ControllerHandle, &gEfiBlockIoProtocolGuid,
+                  (VOID **)&BlockIo,
+                  This->DriverBindingHandle, ControllerHandle,
+                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
+                  );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Status = gBS->UninstallProtocolInterface (ControllerHandle,
+                  &gEfiBlockIoProtocolGuid, BlockIo);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Media = BlockIo->Media;
+  Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (BlockIo);
+  XenPvBlockFrontShutdown (Dev);
+
+  FreePool (Media);
+
   gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h +1 -0
index 14c65b2..420e751 100644
@@ -93,6 +93,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
 //
 #include "DriverBinding.h"
 #include "ComponentName.h"
+#include "BlockIo.h"
 
 
 #endif
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index 619ed8f..b7c4a1f 100644
@@ -52,6 +52,8 @@
   ComponentName.h
   BlockFront.c
   BlockFront.h
+  BlockIo.c
+  BlockIo.h
 
 
 [LibraryClasses]
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
#71 lore raw

Re: [PATCH v2 18/18] OvmfPkg/XenPvBlkDxe: Add BlockIo.

Quoted 5 lines · Konrad Rzeszutek Wilk
Quoted 1 line · Anthony PERARD

Install the BlockIo protocol.

Implement. Perhaps point out that the blkif.h is a good literature to understand it?

Maybe not in this patch, but in the previous one. This patch is just an interface between the block front implementation and the EFI IO insterface.

Quoted 185 lines
Quoted 185 lines

Contributed-under: TianoCore Contribution Agreement 1.0

---
Change in V2:
- Remove blockIo2 headers.
- Fix few comment.
- file header, copyright
- Rewrite few comment and error messages
- No more callback
- Improving block read/write, increase to the max size in one request (instead of only 8pages)
- Fix lastblock when it's a cdrom
- Do uninitialisation when fail to install fail
- few comment
- Licenses

---
 OvmfPkg/XenPvBlkDxe/BlockIo.c       | 292 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h       | 124 +++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |  64 ++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |   1 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 5 files changed, 483 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +152 -0
new file mode 100644
index 0000000..f08339b
@@ -0,0 +1,292 @@
+/** @file
+  BlockIo implementation for Xen PV Block driver.
+
+  This file is implementing the interface between the actual driver in
+  BlockFront.c to the BlockIo protocol.
+
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGE.
+
+**/
+
+#include "XenPvBlkDxe.h"
+
+#include "BlockFront.h"
+
+///
+/// Block I/O Media structure
+///
+GLOBAL_REMOVE_IF_UNREFERENCED
+EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia = {
+  0,      // MediaId
+  FALSE,  // RemovableMedia
+  FALSE,  // MediaPresent
+  FALSE,  // LogicalPartition
+  TRUE,   // ReadOnly
+  FALSE,  // WriteCaching
+  512,    // BlockSize
+  512,    // IoAlign, BlockFront does not support less than 512 bits-aligned.
+  0,      // LastBlock
+  0,      // LowestAlignedLba
+  0,      // LogicalBlocksPerPhysicalBlock
+  0       // OptimalTransferLengthGranularity
+};
+
+///
+/// Block I/O Protocol instance
+///
+GLOBAL_REMOVE_IF_UNREFERENCED
+EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo = {
+  EFI_BLOCK_IO_PROTOCOL_REVISION3,          // Revision
+  &gXenPvBlkDxeBlockIoMedia,                // Media
+  XenPvBlkDxeBlockIoReset,                  // Reset
+  XenPvBlkDxeBlockIoReadBlocks,             // ReadBlocks
+  XenPvBlkDxeBlockIoWriteBlocks,            // WriteBlocks
+  XenPvBlkDxeBlockIoFlushBlocks             // FlushBlocks
+};
+
+
+
+
+/**
+  Read/Write BufferSize bytes from Lba into Buffer.
+
+  This function is commun to XenPvBlkDxeBlockIoReadBlocks and
+  XenPvBlkDxeBlockIoWriteBlocks.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from/write to.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination/source buffer for the data.
+  @param  IsWrite    Indicate if the operation is write or read.
+
+  @return See description of XenPvBlkDxeBlockIoReadBlocks and
+          XenPvBlkDxeBlockIoWriteBlocks.
+**/
+STATIC
+EFI_STATUS
+XenPvBlkDxeBlockIoReadWriteBlocks (
+  IN     EFI_BLOCK_IO_PROTOCOL  *This,
+  IN     UINT32                 MediaId,
+  IN     EFI_LBA                Lba,
+  IN     UINTN                  BufferSize,
+  IN OUT VOID                   *Buffer,
+  IN     BOOLEAN                IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_IO IoData;
+  EFI_BLOCK_IO_MEDIA *Media;
+  UINTN NextOffset;
+  EFI_STATUS Status;
+
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+  if (BufferSize == 0) {
+    return EFI_SUCCESS;
+  }
+
+  Media = This->Media;
+
+  if (BufferSize % Media->BlockSize != 0) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: Bad buffer size: 0x%X\n", BufferSize));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  if (Lba > Media->LastBlock ||
+      (BufferSize / Media->BlockSize) - 1 > Media->LastBlock - Lba) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: %a with invalid LBA: 0x%LX, size: 0x%x\n",
+            IsWrite ? "Write" : "Read", Lba, BufferSize));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (IsWrite && Media->ReadOnly) {
+    return EFI_WRITE_PROTECTED;
+  }
+
+  if ((Media->IoAlign > 1) && (UINTN)Buffer & (Media->IoAlign - 1)) {
+    //
+    // Grub2 does not appear to respect IoAlign of 512, so reallocate the
+    // buffer here.
+    //
+    VOID *NewBuffer;
+
+    //
+    // Try again with a properly aligned buffer.
+    //
+    NewBuffer = AllocateAlignedPages((BufferSize + EFI_PAGE_SIZE) / EFI_PAGE_SIZE,
+                                     Media->IoAlign);
+    if (!IsWrite) {
+      Status = XenPvBlkDxeBlockIoReadBlocks (This, MediaId,
+                                             Lba, BufferSize, NewBuffer);
+      CopyMem (Buffer, NewBuffer, BufferSize);
+    } else {
+      CopyMem (NewBuffer, Buffer, BufferSize);
+      Status = XenPvBlkDxeBlockIoWriteBlocks (This, MediaId,
+                                              Lba, BufferSize, NewBuffer);
+    }
+    FreeAlignedPages (NewBuffer, (BufferSize + EFI_PAGE_SIZE) / EFI_PAGE_SIZE);
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 157

Quoted 5 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +5 -0
+    return Status;
+  }
+
+  IoData.Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (This);
+  NextOffset = Lba * Media->BlockSize;

Perhaps instead of calling it 'Offset' could it be Sector? SAy 'NextSector' ? [edit: Just ditch this]

ok

Quoted 24 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 169

Quoted 12 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +12 -0
+
+  while (BufferSize > 0) {
+    if (((UINTN)Buffer & EFI_PAGE_MASK) == 0) {
+      IoData.Size = MIN (BLKIF_MAX_SEGMENTS_PER_REQUEST * EFI_PAGE_SIZE,
+                         BufferSize);
+    } else {
+      IoData.Size = MIN ((BLKIF_MAX_SEGMENTS_PER_REQUEST - 1) * EFI_PAGE_SIZE,
+                         BufferSize);
+    }
+
+    IoData.Buffer = Buffer;
+    IoData.Offset = NextOffset;

And this would be 'IoData.Lba = NextSector' or perhaps to make obvious:
IoData.Lba = Lba * Media->BlockSize;

Thought why even bother with the multiplication of BlockSize when you are going to divide it in the XenPvBlockIo again? Perhaps just do

IoData.Lba = Lba;
[edit: Use that]

And modify the 'Lba' value ?

Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 172

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+    BufferSize -= IoData.Size;
+    Buffer = (VOID*) ((UINTN) Buffer + IoData.Size);
+    NextOffset += IoData.Size;

So this would be 'Lba += IoData.Size'

That would make this easier - and you can ditch the NextOffset altogther? [edit: And Dev.Lba would have the LBA value instead of the odd 'Offset' thing]

Ok, I will see what can be done.
I will probably change IoData.Offset to IoData.Sector. Media->BlockSize (which is what the rest of the firmware will see) might be diferent than the sector_size that block_front advertise. This is the case when blockfront advertize a cdrom, blocksize needs to be 2048 otherwise ovmf will not try to find a ElTorito header, that's cdrom specific.

Quoted 154 lines
Quoted 154 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +120 -0
+    Status = XenPvBlockIo (&IoData, IsWrite);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((EFI_D_ERROR, "XenPvBlkDxe: Error durring %a operation.\n",
+              IsWrite ? "write" : "read"));
+      return Status;
+    }
+  }
+  return EFI_SUCCESS;
+}
+
+
+/**
+  Read BufferSize bytes from Lba into Buffer.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination buffer for the data. The caller is
+                     responsible for either having implicit or explicit ownership of the buffer.
+
+  @retval EFI_SUCCESS           The data was read correctly from the device.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReadBlocks (
+  IN  EFI_BLOCK_IO_PROTOCOL         *This,
+  IN  UINT32                        MediaId,
+  IN  EFI_LBA                       Lba,
+  IN  UINTN                         BufferSize,
+  OUT VOID                          *Buffer
+  )
+{
+  return XenPvBlkDxeBlockIoReadWriteBlocks (This,
+      MediaId, Lba, BufferSize, Buffer, FALSE);
+}
+
+/**
+  Write BufferSize bytes from Lba into Buffer.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    The media ID that the write request is for.
+  @param  Lba        The starting logical block address to be written. The caller is
+                     responsible for writing to only legitimate locations.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the source buffer for the data.
+
+  @retval EFI_SUCCESS           The data was written correctly to the device.
+  @retval EFI_WRITE_PROTECTED   The device can not be written to.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoWriteBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  IN VOID                           *Buffer
+  )
+{
+  return XenPvBlkDxeBlockIoReadWriteBlocks (This,
+      MediaId, Lba, BufferSize, Buffer, TRUE);
+}
+
+/**
+  Flush the Block Device.
+
+  @param  This              Indicates a pointer to the calling context.
+
+  @retval EFI_SUCCESS       All outstanding data was written to the device
+  @retval EFI_DEVICE_ERROR  The device reported an error while writting back the data
+  @retval EFI_NO_MEDIA      There is no media in the device.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoFlushBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL  *This
+  )
+{
+  XenPvBlockSync (XEN_BLOCK_FRONT_FROM_BLOCK_IO (This));
+  return EFI_SUCCESS;
+}
+
+/**
+  Reset the block device hardware.
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Not used.
+
+  @retval EFI_SUCCESS          The device was reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO_PROTOCOL   *This,
+  IN BOOLEAN                 ExtendedVerification
+  )
+{
+  //
+  // Since the initialization of the devices is done, then the device is
+  // working correctly.
+  //
+  return EFI_SUCCESS;
+}
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +28 -0
new file mode 100644
index 0000000..22b6de2
@@ -0,0 +1,124 @@
+/** @file
+  BlockIo function declaration for Xen PV block driver.
+
+  Copyright (C) 2014, Citrix Ltd.
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  POSSIBILITY OF SUCH DAMAGE.
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockIo.h line 33

Quoted 5 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +5 -0
+
+**/
+
+/**
+  Read BufferSize bytes from Lba into Buffer.

The caller has to ensure that the XenPvBlkDxeBlockIoFlushBlocks or Reset are not called when this is executing.

I think those functions are suppose to be blocking. So I suppose only one of them will be called at a time.

Quoted 225 lines
Quoted 19 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +19 -0
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    Id of the media, changes every time the media is replaced.
+  @param  Lba        The starting Logical Block Address to read from
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the destination buffer for the data. The caller is
+                     responsible for either having implicit or explicit ownership of the buffer.
+
+  @retval EFI_SUCCESS           The data was read correctly from the device.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI

OvmfPkg/XenPvBlkDxe/BlockIo.h line 62

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+XenPvBlkDxeBlockIoReadBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  OUT VOID                          *Buffer
+  );
+
+/**
+  Write BufferSize bytes from Lba into Buffer.

The caller has to ensure that the XenPvBlkDxeBlockIoFlushBlocks or Reset are not called when this is executing.

Quoted 20 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +20 -0
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    The media ID that the write request is for.
+  @param  Lba        The starting logical block address to be written. The caller is
+                     responsible for writing to only legitimate locations.
+  @param  BufferSize Size of Buffer, must be a multiple of device block size.
+  @param  Buffer     A pointer to the source buffer for the data.
+
+  @retval EFI_SUCCESS           The data was written correctly to the device.
+  @retval EFI_WRITE_PROTECTED   The device can not be written to.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
+  @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
+  @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
+                                or the buffer is not on proper alignment.
+
+**/
+EFI_STATUS
+EFIAPI

OvmfPkg/XenPvBlkDxe/BlockIo.h line 92

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+XenPvBlkDxeBlockIoWriteBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL          *This,
+  IN UINT32                         MediaId,
+  IN EFI_LBA                        Lba,
+  IN UINTN                          BufferSize,
+  IN VOID                           *Buffer
+  );
+
+/**
+  Flush the Block Device.

The caller has to ensure that there are no other calls to read/write to the device when this is executued.

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +6 -0
+
+  @param  This              Indicates a pointer to the calling context.
+
+  @retval EFI_SUCCESS       All outstanding data was written to the device
+  @retval EFI_DEVICE_ERROR  The device reported an error while writting back the data
+  @retval EFI_NO_MEDIA      There is no media in the device.

OvmfPkg/XenPvBlkDxe/BlockIo.h line 108

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +10 -0
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoFlushBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL  *This
+  );
+
+/**
+  Reset the block device hardware.

Ditto.

Quoted 140 lines
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +16 -0
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Not used.
+
+  @retval EFI_SUCCESS          The device was reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO_PROTOCOL   *This,
+  IN BOOLEAN                 ExtendedVerification
+  );
+
+extern EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia;
+extern EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo;
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +64 -0
index 930333f..d530600 100644
@@ -281,6 +281,7 @@ XenPvBlkDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenBusIo;
   XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -299,8 +300,44 @@ XenPvBlkDxeDriverBindingStart (
     goto CloseProtocol;
   }
 
+  CopyMem (&Dev->BlockIo, &gXenPvBlkDxeBlockIo, sizeof (EFI_BLOCK_IO_PROTOCOL));
+  Media = AllocateCopyPool (sizeof (EFI_BLOCK_IO_MEDIA),
+                            &gXenPvBlkDxeBlockIoMedia);
+  if (Dev->MediaInfo.VDiskInfo & VDISK_REMOVABLE) {
+    Media->RemovableMedia = TRUE;
+  }
+  Media->MediaPresent = TRUE;
+  Media->ReadOnly = !Dev->MediaInfo.ReadWrite;
+  if (Dev->MediaInfo.CdRom) {
+    //
+    // If it's a cdrom, the blocksize value need to be 2048 for OVMF to
+    // recognize it as a cdrom:
+    //    MdeModulePkg/Universal/Disk/PartitionDxe/ElTorito.c
+    //
+    Media->BlockSize = 2048;
+    Media->LastBlock = DivU64x32 (Dev->MediaInfo.Sectors,
+                                  Media->BlockSize / Dev->MediaInfo.SectorSize) - 1;
+  } else {
+    Media->BlockSize = Dev->MediaInfo.SectorSize;
+    Media->LastBlock = Dev->MediaInfo.Sectors - 1;
+  }
+  Dev->BlockIo.Media = Media;
+
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                    &ControllerHandle,
+                    &gEfiBlockIoProtocolGuid, &Dev->BlockIo,
+                    NULL
+                    );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: install protocol fail: %r\n", Status));
+    goto UninitBlockFront;
+  }
+
   return EFI_SUCCESS;
 
+UninitBlockFront:
+  FreePool (Media);
+  XenPvBlockFrontShutdown (Dev);
 CloseProtocol:
   gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
                       This->DriverBindingHandle, ControllerHandle);
@@ -342,6 +379,33 @@ XenPvBlkDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  EFI_BLOCK_IO_PROTOCOL *BlockIo;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
+  EFI_STATUS Status;
+
+  Status = gBS->OpenProtocol (
+                  ControllerHandle, &gEfiBlockIoProtocolGuid,
+                  (VOID **)&BlockIo,
+                  This->DriverBindingHandle, ControllerHandle,
+                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
+                  );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Status = gBS->UninstallProtocolInterface (ControllerHandle,
+                  &gEfiBlockIoProtocolGuid, BlockIo);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Media = BlockIo->Media;
+  Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (BlockIo);
+  XenPvBlockFrontShutdown (Dev);
+
+  FreePool (Media);
+
   gBS->CloseProtocol (ControllerHandle, &gXenBusProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h +1 -0
index 14c65b2..420e751 100644
@@ -93,6 +93,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
 //
 #include "DriverBinding.h"
 #include "ComponentName.h"
+#include "BlockIo.h"
 
 
 #endif
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index 619ed8f..b7c4a1f 100644
@@ -52,6 +52,8 @@
   ComponentName.h
   BlockFront.c
   BlockFront.h
+  BlockIo.c
+  BlockIo.h
 
 
 [LibraryClasses]
Signature · 7 lines
Anthony PERARD


_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Signature · 1 line
Anthony PERARD