Skip to contentSkip to conversation

OvmfPkg: Add public headers from Xen Project.

RFC PATCH Superseded Anthony PERARD 3 participants 39 messages Jul 16, 2014 – Jul 18, 2014 11 messages not in the archive

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#1 lore raw

RFC PATCH 1/18 OvmfPkg: Add public headers from Xen Project.

In reply to a message not in the archive

This patch imports publics headers in order to use features from Xen like XenStore, PV Block... There is only the necessary header files and there are only a few modifications in order to facilitate future merge of more recent header (that would be necessary to access new features).

There is little modification compared to the original files:
- Use of ZeroMem() instead of memset()
- Replace types to be more UEFI compliant using a script.

Command to run to change types:
find OvmfPkg/Include/IndustryStandard/Xen -type f -name '*.h' -exec sed
--regexp-extended --file=fix_type_in_xen_includes.sed --in-place {} \;

This line is commented instead of been change as I'm not sure why it does not compile (when s/char/CHAR8/), and it does not seems necessary so far.
/* __DEFINE_XEN_GUEST_HANDLE(uchar, unsigned char); */
in OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen.h

Avoid changing the 'long' that is not a type (with the first line).

$ cat fix_type_in_xen_includes.sed
/as long as/b
s/([^a-zA-Z0-9_]|^)uint8_t([^a-zA-Z0-9_]|$)/\1UINT8\2/g
s/([^a-zA-Z0-9_]|^)uint16_t([^a-zA-Z0-9_]|$)/\1UINT16\2/g
s/([^a-zA-Z0-9_]|^)uint32_t([^a-zA-Z0-9_]|$)/\1UINT32\2/g
s/([^a-zA-Z0-9_]|^)uint64_t([^a-zA-Z0-9_]|$)/\1UINT64\2/g
s/([^a-zA-Z0-9_]|^)int8_t([^a-zA-Z0-9_]|$)/\1INT8\2/g
s/([^a-zA-Z0-9_]|^)int16_t([^a-zA-Z0-9_]|$)/\1INT16\2/g
s/([^a-zA-Z0-9_]|^)int32_t([^a-zA-Z0-9_]|$)/\1INT32\2/g
s/([^a-zA-Z0-9_]|^)int64_t([^a-zA-Z0-9_]|$)/\1INT64\2/g
s/([^a-zA-Z0-9_]|^)void([^a-zA-Z0-9_]|$)/\1VOID\2/g
s/([^a-zA-Z0-9_]|^)unsigned int([^a-zA-Z0-9_]|$)/\1UINT32\2/g
s/([^a-zA-Z0-9_]|^)int([^a-zA-Z0-9_]|$)/\1INT32\2/g
s/([^a-zA-Z0-9_]|^)char([^a-zA-Z0-9_]|$)/\1CHAR8\2/g
s/([^a-zA-Z0-9_]|^)unsigned long([^a-zA-Z0-9_]|$)/\1UINTN\2/g
s/([^a-zA-Z0-9_]|^)long([^a-zA-Z0-9_]|$)/\1INTN\2/g

Contributed-under: TianoCore Contribution Agreement 1.0

---
 .../IndustryStandard/Xen/arch-x86/xen-x86_32.h     | 171 ++++
 .../IndustryStandard/Xen/arch-x86/xen-x86_64.h     | 202 +++++
 .../Include/IndustryStandard/Xen/arch-x86/xen.h    | 273 +++++++
 .../Include/IndustryStandard/Xen/event_channel.h   | 381 +++++++++
 OvmfPkg/Include/IndustryStandard/Xen/grant_table.h | 662 +++++++++++++++
 OvmfPkg/Include/IndustryStandard/Xen/hvm/hvm_op.h  | 275 +++++++
 OvmfPkg/Include/IndustryStandard/Xen/hvm/params.h  | 150 ++++
 OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h    | 608 ++++++++++++++
 .../Include/IndustryStandard/Xen/io/protocols.h    |  40 +
 OvmfPkg/Include/IndustryStandard/Xen/io/ring.h     | 312 +++++++
 OvmfPkg/Include/IndustryStandard/Xen/io/xenbus.h   |  80 ++
 OvmfPkg/Include/IndustryStandard/Xen/io/xs_wire.h  | 138 ++++
 OvmfPkg/Include/IndustryStandard/Xen/memory.h      | 480 +++++++++++
 OvmfPkg/Include/IndustryStandard/Xen/sched.h       | 174 ++++
 OvmfPkg/Include/IndustryStandard/Xen/trace.h       | 310 +++++++
 OvmfPkg/Include/IndustryStandard/Xen/xen-compat.h  |  44 +
 OvmfPkg/Include/IndustryStandard/Xen/xen.h         | 897 +++++++++++++++++++++
 17 files changed, 5197 insertions(+)
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_32.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_64.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/event_channel.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/grant_table.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/hvm/hvm_op.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/hvm/params.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/protocols.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/ring.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/xenbus.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/xs_wire.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/memory.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/sched.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/trace.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/xen-compat.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/xen.h
OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_32.h new file +171 -0
new file mode 100644
index 0000000..98f2f03
@@ -0,0 +1,171 @@
+/******************************************************************************
+ * xen-x86_32.h
+ * 
+ * Guest OS interface to x86 32-bit Xen.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (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.
+ *
+ * Copyright (c) 2004-2007, K A Fraser
+ */
+
+#ifndef __XEN_PUBLIC_ARCH_X86_XEN_X86_32_H__
+#define __XEN_PUBLIC_ARCH_X86_XEN_X86_32_H__
+
+/*
+ * Hypercall interface:
+ *  Input:  %ebx, %ecx, %edx, %esi, %edi, %ebp (arguments 1-6)
+ *  Output: %eax
+ * Access is via hypercall page (set up by guest loader or via a Xen MSR):
+ *  call hypercall_page + hypercall-number * 32
+ * Clobbered: Argument registers (e.g., 2-arg hypercall clobbers %ebx,%ecx)
+ */
+
+/*
+ * These flat segments are in the Xen-private section of every GDT. Since these
+ * are also present in the initial GDT, many OSes will be able to avoid
+ * installing their own GDT.
+ */
+#define FLAT_RING1_CS 0xe019    /* GDT index 259 */
+#define FLAT_RING1_DS 0xe021    /* GDT index 260 */
+#define FLAT_RING1_SS 0xe021    /* GDT index 260 */
+#define FLAT_RING3_CS 0xe02b    /* GDT index 261 */
+#define FLAT_RING3_DS 0xe033    /* GDT index 262 */
+#define FLAT_RING3_SS 0xe033    /* GDT index 262 */
+
+#define FLAT_KERNEL_CS FLAT_RING1_CS
+#define FLAT_KERNEL_DS FLAT_RING1_DS
+#define FLAT_KERNEL_SS FLAT_RING1_SS
+#define FLAT_USER_CS    FLAT_RING3_CS
+#define FLAT_USER_DS    FLAT_RING3_DS
+#define FLAT_USER_SS    FLAT_RING3_SS
+
+#define __HYPERVISOR_VIRT_START_PAE    0xF5800000
+#define __MACH2PHYS_VIRT_START_PAE     0xF5800000
+#define __MACH2PHYS_VIRT_END_PAE       0xF6800000
+#define HYPERVISOR_VIRT_START_PAE      \
+    mk_unsigned_long(__HYPERVISOR_VIRT_START_PAE)
+#define MACH2PHYS_VIRT_START_PAE       \
+    mk_unsigned_long(__MACH2PHYS_VIRT_START_PAE)
+#define MACH2PHYS_VIRT_END_PAE         \
+    mk_unsigned_long(__MACH2PHYS_VIRT_END_PAE)
+
+/* Non-PAE bounds are obsolete. */
+#define __HYPERVISOR_VIRT_START_NONPAE 0xFC000000
+#define __MACH2PHYS_VIRT_START_NONPAE  0xFC000000
+#define __MACH2PHYS_VIRT_END_NONPAE    0xFC400000
+#define HYPERVISOR_VIRT_START_NONPAE   \
+    mk_unsigned_long(__HYPERVISOR_VIRT_START_NONPAE)
+#define MACH2PHYS_VIRT_START_NONPAE    \
+    mk_unsigned_long(__MACH2PHYS_VIRT_START_NONPAE)
+#define MACH2PHYS_VIRT_END_NONPAE      \
+    mk_unsigned_long(__MACH2PHYS_VIRT_END_NONPAE)
+
+#define __HYPERVISOR_VIRT_START __HYPERVISOR_VIRT_START_PAE
+#define __MACH2PHYS_VIRT_START  __MACH2PHYS_VIRT_START_PAE
+#define __MACH2PHYS_VIRT_END    __MACH2PHYS_VIRT_END_PAE
+
+#ifndef HYPERVISOR_VIRT_START
+#define HYPERVISOR_VIRT_START mk_unsigned_long(__HYPERVISOR_VIRT_START)
+#endif
+
+#define MACH2PHYS_VIRT_START  mk_unsigned_long(__MACH2PHYS_VIRT_START)
+#define MACH2PHYS_VIRT_END    mk_unsigned_long(__MACH2PHYS_VIRT_END)
+#define MACH2PHYS_NR_ENTRIES  ((MACH2PHYS_VIRT_END-MACH2PHYS_VIRT_START)>>2)
+#ifndef machine_to_phys_mapping
+#define machine_to_phys_mapping ((UINTN *)MACH2PHYS_VIRT_START)
+#endif
+
+/* 32-/64-bit invariability for control interfaces (domctl/sysctl). */
+#if defined(__XEN__) || defined(__XEN_TOOLS__)
+#undef ___DEFINE_XEN_GUEST_HANDLE
+#define ___DEFINE_XEN_GUEST_HANDLE(name, type)                  \
+    typedef struct { type *p; }                                 \
+        __guest_handle_ ## name;                                \
+    typedef struct { union { type *p; uint64_aligned_t q; }; }  \
+        __guest_handle_64_ ## name
+#undef set_xen_guest_handle_raw
+#define set_xen_guest_handle_raw(hnd, val)                  \
+    do { if ( sizeof(hnd) == 8 ) *(UINT64 *)&(hnd) = 0;   \
+         (hnd).p = val;                                     \
+    } while ( 0 )
+#define uint64_aligned_t UINT64 __attribute__((aligned(8)))
+#define __XEN_GUEST_HANDLE_64(name) __guest_handle_64_ ## name
+#define XEN_GUEST_HANDLE_64(name) __XEN_GUEST_HANDLE_64(name)
+#endif
+
+#ifndef __ASSEMBLY__
+
+struct cpu_user_regs {
+    UINT32 ebx;
+    UINT32 ecx;
+    UINT32 edx;
+    UINT32 esi;
+    UINT32 edi;
+    UINT32 ebp;
+    UINT32 eax;
+    UINT16 error_code;    /* private */
+    UINT16 entry_vector;  /* private */
+    UINT32 eip;
+    UINT16 cs;
+    UINT8  saved_upcall_mask;
+    UINT8  _pad0;
+    UINT32 eflags;        /* eflags.IF == !saved_upcall_mask */
+    UINT32 esp;
+    UINT16 ss, _pad1;
+    UINT16 es, _pad2;
+    UINT16 ds, _pad3;
+    UINT16 fs, _pad4;
+    UINT16 gs, _pad5;
+};
+typedef struct cpu_user_regs cpu_user_regs_t;
+DEFINE_XEN_GUEST_HANDLE(cpu_user_regs_t);
+
+/*
+ * Page-directory addresses above 4GB do not fit into architectural %cr3.
+ * When accessing %cr3, or equivalent field in vcpu_guest_context, guests
+ * must use the following accessor macros to pack/unpack valid MFNs.
+ */
+#define xen_pfn_to_cr3(pfn) (((unsigned)(pfn) << 12) | ((unsigned)(pfn) >> 20))
+#define xen_cr3_to_pfn(cr3) (((unsigned)(cr3) >> 12) | ((unsigned)(cr3) << 20))
+
+struct arch_vcpu_info {
+    UINTN cr2;
+    UINTN pad[5]; /* sizeof(vcpu_info_t) == 64 */
+};
+typedef struct arch_vcpu_info arch_vcpu_info_t;
+
+struct xen_callback {
+    UINTN cs;
+    UINTN eip;
+};
+typedef struct xen_callback xen_callback_t;
+
+#endif /* !__ASSEMBLY__ */
+
+#endif /* __XEN_PUBLIC_ARCH_X86_XEN_X86_32_H__ */
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_64.h new file +202 -0

202 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen.h new file +273 -0

273 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/event_channel.h new file +381 -0

381 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/grant_table.h new file +662 -0

662 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/hvm/hvm_op.h new file +275 -0

275 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/hvm/params.h new file +150 -0

150 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h new file +608 -0

608 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/io/protocols.h new file +40 -0
new file mode 100644
index 0000000..80b196b
@@ -0,0 +1,40 @@
+/******************************************************************************
+ * protocols.h
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (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_PROTOCOLS_H__
+#define __XEN_PROTOCOLS_H__
+
+#define XEN_IO_PROTO_ABI_X86_32     "x86_32-abi"
+#define XEN_IO_PROTO_ABI_X86_64     "x86_64-abi"
+#define XEN_IO_PROTO_ABI_ARM        "arm-abi"
+
+#if defined(__i386__)
+# define XEN_IO_PROTO_ABI_NATIVE XEN_IO_PROTO_ABI_X86_32
+#elif defined(__x86_64__)
+# define XEN_IO_PROTO_ABI_NATIVE XEN_IO_PROTO_ABI_X86_64
+#elif defined(__arm__) || defined(__aarch64__)
+# define XEN_IO_PROTO_ABI_NATIVE XEN_IO_PROTO_ABI_ARM
+#else
+# error arch fixup needed here
+#endif
+
+#endif
OvmfPkg/Include/IndustryStandard/Xen/io/ring.h new file +312 -0

238 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/io/xenbus.h new file +80 -0

80 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/io/xs_wire.h new file +138 -0

138 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/memory.h new file +480 -0

480 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/sched.h new file +174 -0

174 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/trace.h new file +310 -0

310 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/xen-compat.h new file +44 -0

44 lines not on this page · raw message

OvmfPkg/Include/IndustryStandard/Xen/xen.h new file +897 -0

897 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 7 lines
Anthony PERARD


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

Part of the diff is not shown here. View the raw message.

#2 lore raw

RFC PATCH 2/18 OvmfPkg: Add basic skeleton for the Xenbus driver.

In reply to a message not in the archive

This includes Component Name and Driver Binding.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/OvmfPkgX64.dsc            |   1 +
 OvmfPkg/OvmfPkgX64.fdf            |   1 +
 OvmfPkg/XenbusDxe/ComponentName.c | 148 ++++++++++++++++++
 OvmfPkg/XenbusDxe/ComponentName.h |  91 +++++++++++
 OvmfPkg/XenbusDxe/DriverBinding.h | 139 +++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c     | 314 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  78 ++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |  56 +++++++
 8 files changed, 828 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/ComponentName.c
 create mode 100644 OvmfPkg/XenbusDxe/ComponentName.h
 create mode 100644 OvmfPkg/XenbusDxe/DriverBinding.h
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.c
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.h
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.inf
OvmfPkg/OvmfPkgX64.dsc +1 -0
index 66459c2..4ea1a83 100644
@@ -430,6 +430,7 @@
   OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
   OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
   OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
+  OvmfPkg/XenbusDxe/XenbusDxe.inf
   OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf {
     <LibraryClasses>
       PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf
OvmfPkg/OvmfPkgX64.fdf +1 -0
index b9e9c59..7f1aab4 100644
@@ -278,6 +278,7 @@ INF  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
 INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
 INF  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf
 INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+INF  OvmfPkg/XenbusDxe/XenbusDxe.inf
 
 !if $(SECURE_BOOT_ENABLE) == TRUE
   INF  SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableRuntimeDxe.inf
OvmfPkg/XenbusDxe/ComponentName.c new file +148 -0

148 lines not on this page · raw message

OvmfPkg/XenbusDxe/ComponentName.h new file +91 -0

91 lines not on this page · raw message

OvmfPkg/XenbusDxe/DriverBinding.h new file +139 -0

139 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.c new file +314 -0

314 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.h new file +78 -0

78 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.inf new file +56 -0

56 lines not on this page · raw message

Signature · 1 line
Anthony PERARD
#3 lore raw

RFC PATCH 3/18 OvmfPkg/XenbusDxe: Add device state struct and create an ExitBoot services event.

In reply to a message not in the archive

The ExitBoot event is used to disconnect from the device before the next operating system start using them.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 39 ++++++++++++++++++++++++++++++++++++---
 OvmfPkg/XenbusDxe/XenbusDxe.h | 10 ++++++++++
 2 files changed, 46 insertions(+), 3 deletions(-)
OvmfPkg/XenbusDxe/XenbusDxe.c +36 -3
index 14113ad..2c3d9b8 100644
@@ -16,7 +16,6 @@
 
 #include "XenbusDxe.h"
 
-
 ///
 /// Driver Binding Protocol instance
 ///
@@ -30,6 +29,8 @@ EFI_DRIVER_BINDING_PROTOCOL gXenbusDxeDriverBinding = {
 };
 
 
+XENBUS_DEVICE *mMyDevice;
+
 /**
   Unloads an image.
 
@@ -229,6 +230,19 @@ XenbusDxeDriverBindingSupported (
   return Status;
 }
 
+VOID
+EFIAPI
+NotifyExitBoot (
+  IN EFI_EVENT Event,
+  IN VOID *Context
+  )
+{
+  XENBUS_DEVICE *Dev = Context;
+
+  gBS->DisconnectController(Dev->ControllerHandle,
+                            Dev->This->DriverBindingHandle, NULL);
+}
+
 /**
   Starts a device controller or a bus controller.
 
@@ -272,7 +286,22 @@ XenbusDxeDriverBindingStart (
   IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  EFI_STATUS Status;
+  XENBUS_DEVICE *Dev;
+
+  Dev = AllocateZeroPool (sizeof (*Dev));
+  Dev->Signature = XENBUS_DEVICE_SIGNATURE;
+  Dev->This = This;
+  Dev->ControllerHandle = ControllerHandle;
+
+  Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
+                             NotifyExitBoot,
+                             (VOID*) Dev,
+                             &Dev->ExitBootEvent);
+  ASSERT_EFI_ERROR (Status);
+
+  mMyDevice = Dev;
+  return EFI_SUCCESS;
 }
 
 /**
@@ -310,5 +339,9 @@ XenbusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  XENBUS_DEVICE *Dev = mMyDevice;
+
+  gBS->CloseEvent (Dev->ExitBootEvent);
+
+  return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +10 -0
index 6f22732..c1ca87a 100644
@@ -75,4 +75,14 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenbusDxeComponentName;
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
 
+typedef struct _XENBUS_DEVICE XENBUS_DEVICE;
+
+#define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')
+struct _XENBUS_DEVICE {
+  UINT32                        Signature;
+  EFI_DRIVER_BINDING_PROTOCOL   *This;
+  EFI_HANDLE                    ControllerHandle;
+  EFI_EVENT                     ExitBootEvent;
+};
+
 #endif
Signature · 1 line
Anthony PERARD
#4 lore raw

RFC PATCH 4/18 OvmfPkg/XenbusDxe: Add support to make Xen Hypercalls.

In reply to a message not in the archive

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/X64/hypercall.S   |  16 ++++++
 OvmfPkg/XenbusDxe/X64/hypercall.asm |  19 +++++++
 OvmfPkg/XenbusDxe/XenHypercall.c    | 101 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenHypercall.h    |  44 ++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c       |   8 +++
 OvmfPkg/XenbusDxe/XenbusDxe.h       |   5 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf     |   6 +++
 7 files changed, 199 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/X64/hypercall.S
 create mode 100644 OvmfPkg/XenbusDxe/X64/hypercall.asm
 create mode 100644 OvmfPkg/XenbusDxe/XenHypercall.c
 create mode 100644 OvmfPkg/XenbusDxe/XenHypercall.h
OvmfPkg/XenbusDxe/X64/hypercall.S new file +16 -0
new file mode 100644
index 0000000..80982e3
@@ -0,0 +1,16 @@
+# Hypercall with 2 arguments
+# INTN
+# EFIAPI
+# XenHypercall2 (
+#   IN     VOID *hypercall_addr,
+#   IN OUT INTN arg1,
+#   IN OUT INTN arg2
+#   );
+# XXX push and pop ?
+ASM_GLOBAL ASM_PFX(XenHypercall2)
+ASM_PFX(XenHypercall2):
+  movq %rcx, %rax
+  movq %rdx, %rdi
+  movq %r8, %rsi
+  call *%rax
+  ret
OvmfPkg/XenbusDxe/X64/hypercall.asm new file +19 -0
new file mode 100644
index 0000000..8bc41a2
@@ -0,0 +1,19 @@
+.code
+
+; Hypercall with 2 arguments
+; INTN
+; EFIAPI
+; XenHypercall2 (
+;   IN     VOID *hypercall_addr,
+;   IN OUT INTN arg1,
+;   IN OUT INTN arg2
+;   );
+XenHypercall2 PROC
+  mov rax, rcx
+  mov rdi, rdx
+  mov rsi, r8
+  call rax
+  ret
+XenHypercall2 ENDP
+
+END
OvmfPkg/XenbusDxe/XenHypercall.c new file +101 -0

101 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenHypercall.h new file +44 -0

44 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.c +8 -0
index 2c3d9b8..63ea31b 100644
@@ -16,6 +16,8 @@
 
 #include "XenbusDxe.h"
 
+#include "XenHypercall.h"
+
 ///
 /// Driver Binding Protocol instance
 ///
@@ -294,6 +296,12 @@ XenbusDxeDriverBindingStart (
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
 
+  Status = XenHyperpageInit (Dev);
+  ASSERT_EFI_ERROR (Status);
+
+  Status = XenGetSharedInfoPage (Dev);
+  ASSERT_EFI_ERROR (Status);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
OvmfPkg/XenbusDxe/XenbusDxe.h +5 -0
index c1ca87a..6140f94 100644
@@ -71,6 +71,8 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenbusDxeComponentName;
 //
 // Other stuff
 //
+#include <IndustryStandard/Xen/xen.h>
+
 #define PCI_VENDOR_ID_XEN                0x5853
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
@@ -83,6 +85,9 @@ struct _XENBUS_DEVICE {
   EFI_DRIVER_BINDING_PROTOCOL   *This;
   EFI_HANDLE                    ControllerHandle;
   EFI_EVENT                     ExitBootEvent;
+
+  VOID                          *Hyperpage;
+  shared_info_t                 *SharedInfo;
 };
 
 #endif
OvmfPkg/XenbusDxe/XenbusDxe.inf +6 -0
index d6685b3..8b69f93 100644
@@ -31,6 +31,12 @@
   DriverBinding.h
   ComponentName.c
   ComponentName.h
+  XenHypercall.c
+  XenHypercall.h
+
+[Sources.X64]
+  X64/hypercall.S
+  X64/hypercall.asm
 
 [LibraryClasses]
   UefiDriverEntryPoint
Signature · 1 line
Anthony PERARD
#5 lore raw

RFC PATCH 5/18 OvmfPkg/XenbusDxe: Open PciIo protocol.

In reply to a message not in the archive

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 16 ++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h |  1 +
 2 files changed, 17 insertions(+)
OvmfPkg/XenbusDxe/XenbusDxe.c +16 -0
index 63ea31b..ba5e8f4 100644
@@ -290,11 +290,25 @@ XenbusDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
+  EFI_PCI_IO_PROTOCOL *PciIo;
+
+  Status = gBS->OpenProtocol (
+                     ControllerHandle,
+                     &gEfiPciIoProtocolGuid,
+                     (VOID **)&PciIo,
+                     This->DriverBindingHandle,
+                     ControllerHandle,
+                     EFI_OPEN_PROTOCOL_BY_DRIVER
+                     );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
 
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
+  Dev->PciIo = PciIo;
 
   Status = XenHyperpageInit (Dev);
   ASSERT_EFI_ERROR (Status);
@@ -351,5 +365,7 @@ XenbusDxeDriverBindingStop (
 
   gBS->CloseEvent (Dev->ExitBootEvent);
 
+  gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +1 -0
index 6140f94..d57e3c8 100644
@@ -84,6 +84,7 @@ struct _XENBUS_DEVICE {
   UINT32                        Signature;
   EFI_DRIVER_BINDING_PROTOCOL   *This;
   EFI_HANDLE                    ControllerHandle;
+  EFI_PCI_IO_PROTOCOL           *PciIo;
   EFI_EVENT                     ExitBootEvent;
 
   VOID                          *Hyperpage;
Signature · 1 line
Anthony PERARD
#6 lore raw

RFC PATCH 6/18 OvmfPkg: Introduce Xenbus Protocol.

In reply to a message not in the archive

This protocol will be used for communication between a PV driver (like a PV block driver) and the Xenbus/Xenstore.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h | 62 +++++++++++++++++++++++++++++++++++++++
 OvmfPkg/OvmfPkg.dec               |  2 ++
 OvmfPkg/XenbusDxe/ComponentName.c | 12 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  3 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |  1 +
 5 files changed, 80 insertions(+)
 create mode 100644 OvmfPkg/Include/Protocol/Xenbus.h
OvmfPkg/Include/Protocol/Xenbus.h new file +62 -0
new file mode 100644
index 0000000..191cee1
@@ -0,0 +1,62 @@
+
+/** @file
+  TODO: Brief Description of Protocol Xenbus
+
+  TODO: Detailed Description of Protocol Xenbus
+
+  TODO: Copyright for Protocol Xenbus
+
+  TODO: License for Protocol Xenbus
+
+**/
+
+#ifndef __PROTOCOL_XENBUS_H__
+#define __PROTOCOL_XENBUS_H__
+
+#define XENBUS_PROTOCOL_GUID \
+  {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}
+
+///
+/// Forward declaration
+///
+typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
+
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+///
+/// Function prototypes
+///
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_ACCESS)(
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame,
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *refp
+  );
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_END_ACCESS)(
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+
+///
+/// Protocol structure
+///
+struct _XENBUS_PROTOCOL {
+  XENBUS_GRANT_ACCESS           GrantAccess;
+  XENBUS_GRANT_END_ACCESS       GrantEndAccess;
+  //
+  // Place protocol data fields here
+  //
+};
+
+extern EFI_GUID gXenbusProtocolGuid;
+
+#endif
OvmfPkg/OvmfPkg.dec +2 -0
index f829247..095d40a 100644
@@ -47,6 +47,8 @@
 [Protocols]
   gVirtioDeviceProtocolGuid       = {0xfa920010, 0x6785, 0x4941, {0xb6, 0xec, 0x49, 0x8c, 0x57, 0x9f, 0x16, 0x0a}}
   gBlockMmioProtocolGuid          = {0x6b558ce3, 0x69e5, 0x4c67, {0xa6, 0x34, 0xf7, 0xfe, 0x72, 0xad, 0xbe, 0x84}}
+  ## Include/Protocol/Xenbus.h
+  gXenbusProtocolGuid = {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}
 
 [PcdsFixedAtBuild]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|0x0|UINT32|0
OvmfPkg/XenbusDxe/ComponentName.c +12 -0
index 2cf11b5..fd46cc8 100644
@@ -140,6 +140,18 @@ XenbusDxeComponentNameGetControllerName (
   }
 
   //
+  // Make sure this driver is currently managing ControllerHandle
+  //
+  Status = EfiTestManagedDevice (
+             ControllerHandle,
+             gXenbusDxeDriverBinding.DriverBindingHandle,
+             &gXenbusProtocolGuid
+             );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
   // Lookup name of controller specified by ControllerHandle
   //
   Status = EFI_UNSUPPORTED;
OvmfPkg/XenbusDxe/XenbusDxe.h +3 -0
index d57e3c8..975fb6b 100644
@@ -42,6 +42,9 @@
 //
 // Produced Protocols
 //
+// Xen interface version used:
+#define  __XEN_INTERFACE_VERSION__ 0x00040400
+#include <Protocol/Xenbus.h>
 
 
 //
OvmfPkg/XenbusDxe/XenbusDxe.inf +1 -0
index 8b69f93..1a6b131 100644
@@ -55,6 +55,7 @@
   gEfiPciIoProtocolGuid
   gEfiComponentName2ProtocolGuid
   gEfiComponentNameProtocolGuid
+  gXenbusProtocolGuid
 
 
 [Guids]
Signature · 1 line
Anthony PERARD
#7 lore raw

RFC PATCH 7/18 OvmfPkg/XenbusDxe: Add InterlockedCompareExchange16.

In reply to a message not in the archive

This is a copy of InterlockedCompareExchange32 from the BaseSynchronizationLib.

The function will be used in the next patch.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/InterlockedCompareExchange16.h   |  7 ++++
 .../XenbusDxe/X64/InterlockedCompareExchange16.c   | 41 ++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.inf                    |  2 ++
 3 files changed, 50 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/InterlockedCompareExchange16.h
 create mode 100644 OvmfPkg/XenbusDxe/X64/InterlockedCompareExchange16.c
OvmfPkg/XenbusDxe/InterlockedCompareExchange16.h new file +7 -0
new file mode 100644
index 0000000..55f61a8
@@ -0,0 +1,7 @@
+UINT16
+EFIAPI
+InterlockedCompareExchange16 (
+  IN OUT volatile  UINT16           *Value,
+  IN      UINT16                    CompareValue,
+  IN      UINT16                    ExchangeValue
+  );
OvmfPkg/XenbusDxe/X64/InterlockedCompareExchange16.c new file +41 -0

41 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.inf +2 -0
index 1a6b131..8f58821 100644
@@ -33,10 +33,12 @@
   ComponentName.h
   XenHypercall.c
   XenHypercall.h
+  InterlockedCompareExchange16.h
 
 [Sources.X64]
   X64/hypercall.S
   X64/hypercall.asm
+  X64/InterlockedCompareExchange16.c | GCC
 
 [LibraryClasses]
   UefiDriverEntryPoint
Signature · 1 line
Anthony PERARD
#8 lore raw

RFC PATCH 8/18 OvmfPkg/XenbusDxe: Add Grant Table functions.

In reply to a message not in the archive

There are used to grant access of pages to other Xen domains.

This code originaly comes from the Xen Project, and more precisely from MiniOS.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/GrantTable.c  | 204 ++++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/GrantTable.h  |  34 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c   |  15 +++
 OvmfPkg/XenbusDxe/XenbusDxe.inf |   2 +
 4 files changed, 255 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.c
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.h
OvmfPkg/XenbusDxe/GrantTable.c new file +204 -0
new file mode 100644
index 0000000..97bd15a
@@ -0,0 +1,204 @@
+/*
+ ****************************************************************************
+ * (C) 2006 - Cambridge University
+ ****************************************************************************
+ *
+ *        File: GrantTable.c
+ *      Author: Steven Smith ([email protected])
+ *     Changes: Grzegorz Milos ([email protected])
+ *
+ *        Date: July 2006
+ *
+ * Environment: Xen Minimal OS
+ * Description: Simple grant tables implementation. About as stupid as it's
+ *  possible to be and still work.
+ *
+ ****************************************************************************
+ */
+#include "XenbusDxe.h"
+
+#include <IndustryStandard/Xen/memory.h>
+
+#include "XenHypercall.h"
+
+#include "GrantTable.h"
+#include "InterlockedCompareExchange16.h"
+
+#define NR_RESERVED_ENTRIES 8
+
+/* NR_GRANT_FRAMES must be less than or equal to that configured in Xen */
+#define NR_GRANT_FRAMES 4
+#define NR_GRANT_ENTRIES (NR_GRANT_FRAMES * EFI_PAGE_SIZE / sizeof(grant_entry_v1_t))
+
+STATIC grant_entry_v1_t *GrantTable = NULL;
+STATIC grant_ref_t GrantList[NR_GRANT_ENTRIES];
+#ifdef GNT_DEBUG
+STATIC BOOLEAN GrantInUseList[NR_GRANT_ENTRIES];
+#endif
+
+STATIC
+VOID
+XenGrantTablePutFreeEntry (
+  grant_ref_t Ref
+  )
+{
+  //local_irq_save(flags);
+  /* MemoryFence (); */
+  // lock ?
+#ifdef GNT_DEBUG
+  ASSERT (GrantInUseList[Ref]);
+  GrantInUseList[Ref] = FALSE;
+#endif
+  GrantList[Ref] = GrantList[0];
+  GrantList[0] = Ref;
+  //local_irq_restore(flags);
+  /* MemoryFence (); */
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGetFreeEntry (
+  VOID
+  )
+{
+  UINTN Ref;
+  /* local_irq_save(flags); */
+  // lock ??
+  Ref = GrantList[0];
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+  GrantList[0] = GrantList[Ref];
+#ifdef GNT_DEBUG
+  ASSERT (!GrantInUseList[Ref]);
+  GrantInUseList[Ref] = TRUE;
+#endif
+  /* local_irq_restore(flags); */
+  return Ref;
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGrantAccess (
+  IN domid_t  DomainId,
+  IN UINTN    Frame,
+  IN BOOLEAN  ReadOnly
+  )
+{
+  grant_ref_t Ref;
+  UINT32 Flags;
+
+  ASSERT (GrantTable != NULL);
+  Ref = XenGrantTableGetFreeEntry ();
+  GrantTable[Ref].frame = Frame;
+  GrantTable[Ref].domid = DomainId;
+  MemoryFence ();
+  Flags = GTF_permit_access;
+  if (ReadOnly) {
+    Flags |= GTF_readonly;
+  }
+  GrantTable[Ref].flags = Flags;
+
+  return Ref;
+}
+
+STATIC
+EFI_STATUS
+XenGrantTableEndAccess (
+  grant_ref_t Ref
+  )
+{
+  UINT16 Flags, OldFlags;
+
+  ASSERT (GrantTable != NULL);
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+
+  OldFlags = GrantTable[Ref].flags;
+  do {
+    if ((Flags = OldFlags) & (GTF_reading | GTF_writing)) {
+      DEBUG ((EFI_D_WARN, "WARNING: g.e. still in use! (%x)\n", Flags));
+      return EFI_NOT_READY;
+    }
+    OldFlags = InterlockedCompareExchange16 (&GrantTable[Ref].flags, Flags, 0);
+  } while (OldFlags != Flags);
+
+  XenGrantTablePutFreeEntry (Ref);
+  return EFI_SUCCESS;
+}
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  )
+{
+  xen_add_to_physmap_t Args;
+  INTN Index;
+  INTN ReturnCode;
+
+#ifdef GNT_DEBUG
+  SetMem(GrantInUseList, sizeof (GrantInUseList), 1);
+#endif
+  for (Index = NR_RESERVED_ENTRIES; Index < NR_GRANT_ENTRIES; Index++) {
+    XenGrantTablePutFreeEntry (Index);
+  }
+
+  GrantTable = (VOID*)(UINTN) MmioAddr;
+  for (Index = 0; Index < NR_GRANT_FRAMES; Index++) {
+    Args.domid = DOMID_SELF;
+    Args.idx = Index;
+    Args.space = XENMAPSPACE_grant_table;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_add_to_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, add_to_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+}
+
+VOID
+XenGrantTableDeinit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  INTN ReturnCode, Index;
+  xen_remove_from_physmap_t Args;
+
+  if (GrantTable == NULL) {
+    return;
+  }
+
+  for (Index = NR_GRANT_FRAMES - 1; Index >= 0; Index--) {
+    Args.domid = DOMID_SELF;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    DEBUG ((EFI_D_INFO, "%a %d, removing %X\n", __func__, __LINE__, Args.gpfn));
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_remove_from_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, remove_from_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+  // XXX remove it from the physmap?
+  GrantTable = NULL;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  )
+{
+  *RefPtr = XenGrantTableGrantAccess (DomainId, Frame, ReadOnly);
+  return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  )
+{
+  return XenGrantTableEndAccess (Ref);
+}
OvmfPkg/XenbusDxe/GrantTable.h new file +34 -0
new file mode 100644
index 0000000..05ab4be
@@ -0,0 +1,34 @@
+#ifndef __GNTTAB_H__
+#define __GNTTAB_H__
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  );
+
+VOID
+XenGrantTableDeinit (
+  IN XENBUS_DEVICE  *Dev
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+#endif /* !__GNTTAB_H__ */
OvmfPkg/XenbusDxe/XenbusDxe.c +15 -0
index ba5e8f4..b19055d 100644
@@ -17,6 +17,7 @@
 #include "XenbusDxe.h"
 
 #include "XenHypercall.h"
+#include "GrantTable.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -291,6 +292,8 @@ XenbusDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
   EFI_PCI_IO_PROTOCOL *PciIo;
+  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
+  UINT64 MmioAddr;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -310,12 +313,23 @@ XenbusDxeDriverBindingStart (
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
 
+  Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);
+  ASSERT_EFI_ERROR (Status);
+  ASSERT (BarDesc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM);
+
+  /* Get a Memory address for mapping the Grant Table. */
+  DEBUG((EFI_D_INFO, "%a, bar at %LX\n", __func__, BarDesc->AddrRangeMin));
+  MmioAddr = BarDesc->AddrRangeMin;
+  FreePool (BarDesc);
+
   Status = XenHyperpageInit (Dev);
   ASSERT_EFI_ERROR (Status);
 
   Status = XenGetSharedInfoPage (Dev);
   ASSERT_EFI_ERROR (Status);
 
+  XenGrantTableInit (Dev, MmioAddr);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -364,6 +378,7 @@ XenbusDxeDriverBindingStop (
   XENBUS_DEVICE *Dev = mMyDevice;
 
   gBS->CloseEvent (Dev->ExitBootEvent);
+  XenGrantTableDeinit (Dev);
 
   gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
OvmfPkg/XenbusDxe/XenbusDxe.inf +2 -0
index 8f58821..093932b 100644
@@ -34,6 +34,8 @@
   XenHypercall.c
   XenHypercall.h
   InterlockedCompareExchange16.h
+  GrantTable.c
+  GrantTable.h
 
 [Sources.X64]
   X64/hypercall.S
Signature · 1 line
Anthony PERARD
#9 lore raw

RFC PATCH 9/18 OvmfPkg/XenbusDxe: Add Event Channel Notify.

In reply to a message not in the archive

This first function is used to notify the other side that there is something to do. The other side is another Xen domain.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/EventChannel.c | 16 ++++++++++++++++
 OvmfPkg/XenbusDxe/EventChannel.h | 14 ++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.inf  |  2 ++
 3 files changed, 32 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/EventChannel.c
 create mode 100644 OvmfPkg/XenbusDxe/EventChannel.h
OvmfPkg/XenbusDxe/EventChannel.c new file +16 -0
new file mode 100644
index 0000000..4ab8a40
@@ -0,0 +1,16 @@
+#include "EventChannel.h"
+#include "XenHypercall.h"
+
+VOID
+XenEventChannelNotify (
+  IN XENBUS_DEVICE *Dev,
+  IN evtchn_port_t Port
+  )
+{
+  INTN ReturnCode;
+  evtchn_send_t send;
+
+  send.port = Port;
+  ReturnCode = XenHypercallEventChannelOp (Dev, EVTCHNOP_send, &send);
+  ASSERT (ReturnCode == 0);
+}
OvmfPkg/XenbusDxe/EventChannel.h new file +14 -0
new file mode 100644
index 0000000..8a3f6d4
@@ -0,0 +1,14 @@
+#ifndef __XENBUS_EVENT_CHANNEL_H
+#define __XENBUS_EVENT_CHANNEL_H
+
+#include "XenbusDxe.h"
+
+#include <IndustryStandard/Xen/event_channel.h>
+
+VOID
+XenEventChannelNotify (
+  IN XENBUS_DEVICE *Dev,
+  IN evtchn_port_t Port
+  );
+
+#endif
OvmfPkg/XenbusDxe/XenbusDxe.inf +2 -0
index 093932b..d4007db 100644
@@ -36,6 +36,8 @@
   InterlockedCompareExchange16.h
   GrantTable.c
   GrantTable.h
+  EventChannel.c
+  EventChannel.h
 
 [Sources.X64]
   X64/hypercall.S
Signature · 1 line
Anthony PERARD
#10 lore raw

RFC PATCH 10/18 OvmfPkg/XenbusDxe: Add TestAndClearBit.

In reply to a message not in the archive

This atomically test and clear a bit.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/X64/TestAndClearBit.S | 10 ++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h           | 11 +++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.inf         |  1 +
 3 files changed, 22 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/X64/TestAndClearBit.S
OvmfPkg/XenbusDxe/X64/TestAndClearBit.S new file +10 -0
new file mode 100644
index 0000000..e266f68
@@ -0,0 +1,10 @@
+# TestAndClearBit (
+#   IN  INT32 Bit,                // rcx
+#   IN  volatile VOID* Address    // rdx
+#   );
+ASM_GLOBAL ASM_PFX(TestAndClearBit)
+ASM_PFX(TestAndClearBit):
+  lock
+  btrl %ecx, (%rdx)
+  sbbl %eax, %eax
+  ret
OvmfPkg/XenbusDxe/XenbusDxe.h +11 -0
index 975fb6b..50d0925 100644
@@ -94,4 +94,15 @@ struct _XENBUS_DEVICE {
   shared_info_t                 *SharedInfo;
 };
 
+/*
+ * Helpers
+ */
+
+INT32
+EFIAPI
+TestAndClearBit (
+  IN INT32 Bit,
+  IN volatile VOID *Address
+  );
+
 #endif
OvmfPkg/XenbusDxe/XenbusDxe.inf +1 -0
index d4007db..dc27c13 100644
@@ -43,6 +43,7 @@
   X64/hypercall.S
   X64/hypercall.asm
   X64/InterlockedCompareExchange16.c | GCC
+  X64/TestAndClearBit.S
 
 [LibraryClasses]
   UefiDriverEntryPoint
Signature · 1 line
Anthony PERARD
#11 lore raw

RFC PATCH 11/18 OvmfPkg/XenbusDxe: Add XenStore client implementation

In reply to a message not in the archive

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.

Origin: FreeBSD 10.0

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h |   28 +
 OvmfPkg/XenbusDxe/XenbusDxe.c     |    5 +
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |    2 +
 OvmfPkg/XenbusDxe/Xenstore.c      | 1313 +++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/Xenstore.h      |  281 ++++++++
 5 files changed, 1629 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/Xenstore.c
 create mode 100644 OvmfPkg/XenbusDxe/Xenstore.h
OvmfPkg/Include/Protocol/Xenbus.h +28 -0
index 191cee1..1e0d01d 100644
@@ -21,6 +21,34 @@
 ///
 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_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 b19055d..2c85d5e 100644
@@ -18,6 +18,7 @@
 
 #include "XenHypercall.h"
 #include "GrantTable.h"
+#include "Xenstore.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -330,6 +331,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,
@@ -378,6 +382,7 @@ XenbusDxeDriverBindingStop (
   XENBUS_DEVICE *Dev = mMyDevice;
 
   gBS->CloseEvent (Dev->ExitBootEvent);
+  // XXX xenstore cleanup
   XenGrantTableDeinit (Dev);
 
   gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
OvmfPkg/XenbusDxe/XenbusDxe.inf +2 -0
index dc27c13..6c8260f 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 +1313 -0

1,313 lines not on this page · raw message

OvmfPkg/XenbusDxe/Xenstore.h new file +281 -0

281 lines not on this page · raw message

Signature · 1 line
Anthony PERARD
#12 lore raw

RFC PATCH 12/18 OvmfPkg/XenbusDxe: Add an helper AsciiStrDup.

In reply to a message not in the archive

Contributed-under: TianoCore Contribution Agreement 1.0

---
 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..4ea63db
@@ -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 50d0925..4d9db72 100644
@@ -105,4 +105,9 @@ TestAndClearBit (
   IN volatile VOID *Address
   );
 
+CHAR8*
+AsciiStrDup (
+  IN CONST CHAR8* Str
+  );
+
 #endif
Signature · 1 line
Anthony PERARD
#13 lore raw

RFC PATCH 13/18 OvmfPkg/XenbusDxe: Add Xenstore function into the Xenbus protocol

In reply to a message not in the archive

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h | 105 +++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/Xenstore.c      | 159 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/Xenstore.h      |  86 +++++++++++++++++++++
 3 files changed, 350 insertions(+)
OvmfPkg/Include/Protocol/Xenbus.h +105 -0
index 1e0d01d..ef4d0c2 100644
@@ -56,6 +56,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)(
@@ -73,16 +129,65 @@ 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;
   //
   // Place protocol data fields here
   //
+  CONST CHAR8                   *Type;
+  // helper, since the value is in Node, avoid calculating twice,
+  // in XenbusDxe and in XenPvBlkDxe
+  UINT16                        DeviceId;
+  CONST CHAR8                   *Node;
+  CONST CHAR8                   *Backend;
 };
 
 extern EFI_GUID gXenbusProtocolGuid;
OvmfPkg/XenbusDxe/Xenstore.c +159 -0

168 lines not on this page · raw message

OvmfPkg/XenbusDxe/Xenstore.h +86 -0

90 lines not on this page · raw message

Signature · 1 line
Anthony PERARD
#14 lore raw

RFC PATCH 14/18 OvmfPkg/XenbusDxe: Indroduce XenBus support itself.

In reply to a message not in the archive

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

---
 OvmfPkg/Include/Protocol/Xenbus.h |   9 +
 OvmfPkg/XenbusDxe/XenBus.c        | 360 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenBus.h        |  76 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c     |  61 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  18 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |   3 +
 6 files changed, 527 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.h
OvmfPkg/Include/Protocol/Xenbus.h +9 -0
index ef4d0c2..25408c1 100644
@@ -113,6 +113,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,
@@ -171,6 +179,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 +360 -0

360 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenBus.h new file +76 -0

76 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.c +61 -0

102 lines not on this page · raw message

OvmfPkg/XenbusDxe/XenbusDxe.h +18 -0
index 4d9db72..3ff08dd 100644
@@ -80,6 +80,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;
 
 #define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')
@@ -89,11 +90,28 @@ 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;
 };
 
+#define XENBUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X', 'B', 'u', 's')
+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 6c8260f..708fae6 100644
@@ -40,6 +40,9 @@
   EventChannel.h
   Xenstore.c
   Xenstore.h
+  XenBus.c
+  XenBus.h
+  Helpers.c
 
 [Sources.X64]
   X64/hypercall.S
Signature · 1 line
Anthony PERARD
#15 lore raw

RFC PATCH 15/18 OvmfPkg/XenbusDxe: Add Event Channel into XenBus protocol.

In reply to a message not in the archive

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h | 27 +++++++++++++++++++
 OvmfPkg/XenbusDxe/EventChannel.c  | 55 +++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/EventChannel.h  | 26 ++++++++++++++++++
 OvmfPkg/XenbusDxe/XenBus.c        |  3 +++
 4 files changed, 111 insertions(+)
OvmfPkg/Include/Protocol/Xenbus.h +27 -0
index 25408c1..aa37369 100644
@@ -51,6 +51,7 @@ typedef enum {
 
 
 #include <IndustryStandard/Xen/grant_table.h>
+#include <IndustryStandard/Xen/event_channel.h>
 
 ///
 /// Function prototypes
@@ -138,6 +139,28 @@ EFI_STATUS
   );
 
 typedef
+int
+(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
+int
+(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,
@@ -184,6 +207,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

58 lines not on this page · raw message

OvmfPkg/XenbusDxe/EventChannel.h +26 -0
index 8a3f6d4..b1e16f0 100644
@@ -11,4 +11,30 @@ XenEventChannelNotify (
   IN evtchn_port_t Port
   );
 
+/*
+ * Xenbus protocol
+ */
+
+int
+EFIAPI
+XenbusEventChannelAllocate (
+  IN XENBUS_PROTOCOL *This,
+  IN domid_t DomainId,
+  OUT evtchn_port_t *Port
+  );
+
+VOID
+EFIAPI
+XenbusEventChannelNotify (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t Port
+  );
+
+int
+EFIAPI
+XenbusEventChannelClose (
+  IN XENBUS_PROTOCOL *This,
+  IN evtchn_port_t Port
+  );
+
 #endif
OvmfPkg/XenbusDxe/XenBus.c +3 -0
index b0cf1ba..f93423f 100644
@@ -347,6 +347,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 · 1 line
Anthony PERARD
#16 lore raw

RFC PATCH 16/18 OvmfPkg/XenPvBlkDxe: Xen PV Block device, initial skeleton

In reply to a message not in the archive

A ParaVirtualize block driver.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/OvmfPkgX64.dsc              |   1 +
 OvmfPkg/OvmfPkgX64.fdf              |   1 +
 OvmfPkg/XenPvBlkDxe/ComponentName.c | 160 ++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/ComponentName.h |  91 ++++++++++
 OvmfPkg/XenPvBlkDxe/DriverBinding.h | 139 ++++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   | 321 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |  82 +++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |  57 +++++++
 8 files changed, 852 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/ComponentName.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/ComponentName.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/DriverBinding.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf
OvmfPkg/OvmfPkgX64.dsc +1 -0
index 4ea1a83..1564c4c 100644
@@ -431,6 +431,7 @@
   OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
   OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
   OvmfPkg/XenbusDxe/XenbusDxe.inf
+  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf
   OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf {
     <LibraryClasses>
       PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf
OvmfPkg/OvmfPkgX64.fdf +1 -0
index 7f1aab4..ef2aee7 100644
@@ -279,6 +279,7 @@ INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
 INF  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf
 INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
 INF  OvmfPkg/XenbusDxe/XenbusDxe.inf
+INF  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf
 
 !if $(SECURE_BOOT_ENABLE) == TRUE
   INF  SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableRuntimeDxe.inf
OvmfPkg/XenPvBlkDxe/ComponentName.c new file +160 -0

160 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/ComponentName.h new file +91 -0

91 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/DriverBinding.h new file +139 -0

139 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c new file +321 -0

321 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h new file +82 -0

82 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf new file +57 -0

57 lines not on this page · raw message

Signature · 1 line
Anthony PERARD
#17 lore raw

RFC PATCH 17/18 OvmfPkg/XenPvBlkDxe: Add BlockFront client.

In reply to a message not in the archive

This is the code that will do the actual communication between OVMF and a PV block backend, where the block device lives.

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

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockFront.c    | 583 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockFront.h    |  88 ++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |   8 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 4 files changed, 681 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.h
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +583 -0
new file mode 100644
index 0000000..ff5641c
@@ -0,0 +1,583 @@
+/* Minimal block driver for Mini-OS.
+ * Copyright (c) 2007-2008 Samuel Thibault.
+ * Based on netfront.c.
+ */
+
+#include <Library/PrintLib.h>
+#include <Library/DebugLib.h>
+
+#include "BlockFront.h"
+
+#include <IndustryStandard/Xen/io/protocols.h>
+#include <IndustryStandard/Xen/io/xenbus.h>
+
+#include "inttypes.h"
+
+STATIC
+XENSTORE_STATUS
+XenbusReadInteger (
+  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);
+  }
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+  // XXX Will assert if p overflow UINT64 ...
+  *ValuePtr = AsciiStrDecimalToUint64 (p);
+  FreePool (p);
+  return Status;
+}
+
+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);
+  }
+  FreePool (Dev);
+}
+
+XENSTORE_STATUS
+XenPvBlkWaitForBackendState (
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN  XenbusState            WaitedState,
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenbusIo = Dev->XenbusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status;
+
+  while (TRUE) {
+    Status = XenbusReadInteger (XenbusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
+    }
+    if (Value > XenbusStateReconfigured) {
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State >= WaitedState) {
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            WaitedState, State));
+    XenbusIo->WaitForWatch (XenbusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+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 = XenbusReadInteger (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));
+  }
+
+  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"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->SetState (XenbusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->XsTransactionEnd (XenbusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
+  }
+
+  XenbusIo->RegisterWatchBackend (XenbusIo, "state", &Dev->StateWatchToken);
+
+  // Waiting backend
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS || State != XenbusStateConnected) {
+    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 = XenbusReadInteger (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 = XenbusReadInteger (XenbusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenbusReadInteger (XenbusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;
+
+  // Default value
+  Value = 0;
+  Status = XenbusReadInteger (XenbusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenbusReadInteger (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 %d 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");
+  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 = XenbusReadInteger (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");
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC
+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)) {
+        break;
+      }
+      /* Really no slot, go to sleep. */
+      // XXX wait for an event on Dev->EventChannel
+      DEBUG ((EFI_D_INFO, "%a %d, waiting\n", __func__, __LINE__));
+    }
+  }
+}
+
+/* Issue an aio */
+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;
+
+  // XXX is this comment still true ?
+  /* qemu's IDE max multsect is 16 (8KB) and SCSI max DMA was set to 32KB,
+   * so max 44KB can't happen */
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);
+
+  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;
+
+  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;
+    if (!IsWrite) {
+      /* Trigger CoW if needed */
+      *(CHAR8 *)(Data + (Request->seg[Index].first_sect << 9)) = 0;
+      MemoryFence ();
+    }
+    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);
+  }
+}
+
+STATIC
+VOID
+XenPvBlockAsyncIoCallback (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     EFI_STATUS         Status
+  )
+{
+  IoData->Data = (VOID *) 1;
+  IoData->Callback = NULL;
+}
+
+VOID
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  ASSERT (IoData->Callback == NULL);
+  // XXX Signal/Event instead ?
+  IoData->Callback = XenPvBlockAsyncIoCallback;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+  IoData->Data = NULL;
+
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+    if (IoData->Data) {
+      break;
+    }
+  }
+}
+
+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);
+  }
+}
+
+VOID
+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;
+      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 %Ld, num bytes %Ld\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;
+      /* Nota: callback frees IoData itself */
+      if (IoData && IoData->Callback) {
+        IoData->Callback (IoData, 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 +88 -0

88 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +8 -0
index 0ce1e86..7ec7d60 100644
@@ -12,6 +12,8 @@
 
 #include "XenPvBlkDxe.h"
 
+#include "BlockFront.h"
+
 
 ///
 /// Driver Binding Protocol instance
@@ -263,6 +265,7 @@ XenPvBlkDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenbusIo;
+  XEN_BLOCK_FRONT_DEVICE *Dev;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -276,6 +279,11 @@ XenPvBlkDxeDriverBindingStart (
     return Status;
   }
 
+  Status = XenPvBlockFrontInitialization (XenbusIo, XenbusIo->Node, &Dev);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
   return EFI_SUCCESS;
 }
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index 4444cda..a43d006 100644
@@ -30,6 +30,8 @@
   XenPvBlkDxe.c
   ComponentName.c
   ComponentName.h
+  BlockFront.c
+  BlockFront.h
 
 
 [LibraryClasses]
Signature · 1 line
Anthony PERARD
#18 lore raw

RFC PATCH 18/18 OvmfPkg/XenPvBlkDxe: Add BlockIo.

In reply to a message not in the archive

Install the BlockIo protocol.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockIo.c       | 256 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h       | 109 +++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |  59 +++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |   1 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 5 files changed, 427 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +256 -0
new file mode 100644
index 0000000..4ac2411
@@ -0,0 +1,256 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Detailed Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Copyright for UEFI Driver XenPvBlkDxe
+
+  TODO: License for UEFI Driver XenPvBlkDxe
+
+**/
+
+#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
+  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
+  (EFI_BLOCK_RESET)XenPvBlkDxeBlockIoReset, // Reset
+  XenPvBlkDxeBlockIoReadBlocks,             // ReadBlocks
+  XenPvBlkDxeBlockIoWriteBlocks,            // WriteBlocks
+  XenPvBlkDxeBlockIoFlushBlocks             // FlushBlocks
+};
+
+
+
+
+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;
+
+  if (Buffer == NULL) {
+    DEBUG ((EFI_D_ERROR, "%a %d, buffer null\n", __func__, __LINE__));
+    return EFI_INVALID_PARAMETER;
+  }
+  if (BufferSize == 0) {
+    return EFI_SUCCESS;
+  }
+
+  Media = This->Media;
+
+  if (BufferSize % Media->BlockSize != 0) {
+    DEBUG ((EFI_D_ERROR, "%a %d, bad buffer size\n", __func__, __LINE__));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  if (Lba > Media->LastBlock ||
+      (BufferSize / Media->BlockSize) - 1 > Media->LastBlock - Lba) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read too large\n", __func__, __LINE__));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (IsWrite && Media->ReadOnly) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read only\n", __func__, __LINE__));
+    return EFI_WRITE_PROTECTED;
+  }
+
+  if ((Media->IoAlign > 1) && (UINTN)Buffer & (Media->IoAlign - 1)) {
+    // This happen often when using grub2
+    VOID *NewBuffer;
+    EFI_STATUS Status;
+
+    /* 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);
+    return Status;
+  }
+
+
+  // XXX Check MediaId
+
+  IoData.Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (This);
+  IoData.Offset = Lba * Media->BlockSize;
+  IoData.Callback = NULL;
+  IoData.Data = NULL;
+  IoData.Size = BufferSize;
+  IoData.Buffer = Buffer;
+
+  NextOffset = Lba * Media->BlockSize;
+  while (BufferSize > 0) {
+    // This should work if every Buffer is page aligned
+    // but block accept sector aligned, so FIXME
+    IoData.Size = MIN(EFI_PAGE_SIZE * 8,//BLKIF_MAX_SEGMENTS_PER_REQUEST,
+                           BufferSize);
+    IoData.Buffer = Buffer;
+    IoData.Offset = NextOffset;
+    BufferSize -= IoData.Size;
+    Buffer = (VOID*) ((UINTN) Buffer + IoData.Size);
+    NextOffset += IoData.Size;
+    XenPvBlockIo (&IoData, IsWrite);
+    if (!IoData.Data) {
+      DEBUG ((EFI_D_ERROR, "%a %d, XenPvBlockIo no data...\n", __func__, __LINE__));
+      return EFI_DEVICE_ERROR;
+    }
+  }
+  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 Indicates that the driver may perform a more
+                                   exhausive verfication operation of the device
+                                   during reset.
+
+  @retval EFI_SUCCESS          The device was reset.
+  @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
+                               not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO2_PROTOCOL  *This,
+  IN BOOLEAN                 ExtendedVerification
+  )
+{
+  // Is there anything to do ?
+  // since initialisation is done in Start (driver binding)
+  DEBUG ((EFI_D_INFO, "%a %d\n", __func__, __LINE__));
+  return EFI_SUCCESS;
+}
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +109 -0

109 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +59 -0

77 lines not on this page · raw message

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h +1 -0
index 186d0ee..3120137 100644
@@ -76,6 +76,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
 //
 #include "DriverBinding.h"
 #include "ComponentName.h"
+#include "BlockIo.h"
 
 
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index a43d006..b379020 100644
@@ -32,6 +32,8 @@
   ComponentName.h
   BlockFront.c
   BlockFront.h
+  BlockIo.c
+  BlockIo.h
 
 
 [LibraryClasses]
Signature · 1 line
Anthony PERARD
#20 lore raw

Re: [PATCH RFC 02/18] OvmfPkg: Add basic skeleton for the Xenbus driver.

In reply to a message not in the archive
Quoted 1 line · Anthony PERARD

This includes Component Name and Driver Binding.

The title says driver, but the cover letter said 'bus driver'. Should it have bus driver in it?

.. snip..

Quoted 14 lines
(quoted diff) +14 -0
+/**
+  Retrieves a Unicode string that is the user readable name of the controller
+  that is being managed by an EFI Driver.
+
+  @param  This             A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
+  @param  ControllerHandle The handle of a controller that the driver specified by
+                           This is managing.  This handle specifies the controller
+                           whose name is to be returned.
+  @param  ChildHandle      The handle of the child controller to retrieve the name
+                           of.  This is an optional parameter that may be NULL.  It
+                           will be NULL for device drivers.  It will also be NULL
+                           for a bus drivers that wish to retrieve the name of the
+                           bus controller.  It will not be NULL for a bus driver
+                           that wishes to retrieve the name of a child controller.

.. snip..

Quoted 4 lines
(quoted diff) +4 -0
+EFI_STATUS
+EFIAPI
+XenbusDxeComponentNameGetControllerName (
+  IN  EFI_COMPONENT_NAME2_PROTOCOL  *This,

Review

Quoted 10 lines
(quoted diff) +10 -0
+  IN  EFI_HANDLE                    ControllerHandle,
+  IN  EFI_HANDLE                    ChildHandle        OPTIONAL,
+  IN  CHAR8                         *Language,
+  OUT CHAR16                        **ControllerName
+  )
+{
+  EFI_STATUS  Status;
+
+  //
+  // ChildHandle must be NULL for a Device Driver

OK, but this is a bus driver in which case ChildHandle can be NULL or not (at least that is what the comment says) ?

Quoted 12 lines
(quoted diff) +12 -0
+  //
+  if (ChildHandle != NULL) {
+    return EFI_UNSUPPORTED;
+  }
+
+  //
+  // Lookup name of controller specified by ControllerHandle
+  //
+  Status = EFI_UNSUPPORTED;
+
+  return Status;
+}

.. snip..

Quoted 51 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +45 -0
new file mode 100644
index 0000000..14113ad
@@ -0,0 +1,314 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenbusDxe
+
+  TODO: Detailed Description of UEFI Driver XenbusDxe
+
+  TODO: Copyright for UEFI Driver XenbusDxe
+
+  TODO: License for UEFI Driver XenbusDxe
+
+**/
+
+#include <IndustryStandard/Pci.h>
+#include <IndustryStandard/Acpi.h>
+#include <Library/DebugLib.h>
+
+#include "XenbusDxe.h"
+
+
+///
+/// Driver Binding Protocol instance
+///
+EFI_DRIVER_BINDING_PROTOCOL gXenbusDxeDriverBinding = {
+  XenbusDxeDriverBindingSupported,
+  XenbusDxeDriverBindingStart,
+  XenbusDxeDriverBindingStop,
+  XENBUS_DXE_VERSION,
+  NULL,
+  NULL
+};
+
+
+/**
+  Unloads an image.
+
+  @param  ImageHandle           Handle that identifies the image to be unloaded.
+
+  @retval EFI_SUCCESS           The image has been unloaded.
+  @retval EFI_INVALID_PARAMETER ImageHandle is not a valid image handle.
+
+**/
+EFI_STATUS
+EFIAPI
+XenbusDxeUnload (
+  IN EFI_HANDLE  ImageHandle

OvmfPkg/XenbusDxe/XenbusDxe.c line 55

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +10 -0
+  )
+{
+  EFI_STATUS  Status;
+
+  EFI_HANDLE  *HandleBuffer;
+  UINTN       HandleCount;
+  UINTN       Index;
+
+
+  Status = EFI_SUCCESS;

Is that neccessary considering the next line you overwrite it?

Quoted 11 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +11 -0
+
+  //
+  // Retrieve array of all handles in the handle database
+  //
+  Status = gBS->LocateHandleBuffer (
+                  AllHandles,
+                  NULL,
+                  NULL,
+                  &HandleCount,
+                  &HandleBuffer
+                  );

OvmfPkg/XenbusDxe/XenbusDxe.c line 76

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +10 -0
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
+  // Disconnect the current driver from handles in the handle database
+  //
+  for (Index = 0; Index < HandleCount; Index++) {
+    Status = gBS->DisconnectController (HandleBuffer[Index], gImageHandle, NULL);
+  }

Should you check the Status?
I guess it doesn't matter at all. In which case why don't you just (void)gBS->DisconnectController ..

Quoted 41 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +41 -0
+
+  //
+  // Free the array of handles
+  //
+  FreePool (HandleBuffer);
+
+
+  //
+  // Uninstall protocols installed in the driver entry point
+  //
+  Status = gBS->UninstallMultipleProtocolInterfaces (
+                  ImageHandle,
+                  &gEfiDriverBindingProtocolGuid, &gXenbusDxeDriverBinding,
+                  &gEfiComponentNameProtocolGuid,  &gXenbusDxeComponentName,
+                  &gEfiComponentName2ProtocolGuid, &gXenbusDxeComponentName2,
+                  NULL
+                  );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+
+  //
+  // Do any additional cleanup that is required for this driver
+  //
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This is the declaration of an EFI image entry point. This entry point is
+  the same for UEFI Applications, UEFI OS Loaders, and UEFI Drivers including
+  both device drivers and bus drivers.
+
+  @param  ImageHandle           The firmware allocated handle for the UEFI image.
+  @param  SystemTable           A pointer to the EFI System Table.
+
+  @retval EFI_SUCCESS           The operation completed successfully.
+  @retval Others                An unexpected error occurred.
+**/
+EFI_STATUS

OvmfPkg/XenbusDxe/XenbusDxe.c line 127

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +10 -0
+EFIAPI
+XenbusDxeDriverEntryPoint (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+
+  Status = EFI_SUCCESS;

Not needed.

Quoted 18 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +18 -0
+
+
+  //
+  // Install UEFI Driver Model protocol(s).
+  //
+  Status = EfiLibInstallDriverBindingComponentName2 (
+             ImageHandle,
+             SystemTable,
+             &gXenbusDxeDriverBinding,
+             ImageHandle,
+             &gXenbusDxeComponentName,
+             &gXenbusDxeComponentName2
+             );
+  ASSERT_EFI_ERROR (Status);
+
+
+  return Status;
+}
#23 lore raw

Re: [PATCH RFC 03/18] OvmfPkg/XenbusDxe: Add device state struct and create an ExitBoot services event.

In reply to a message not in the archive
Quoted 91 lines · Anthony PERARD

The ExitBoot event is used to disconnect from the device before the next operating system start using them.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 39 ++++++++++++++++++++++++++++++++++++---
 OvmfPkg/XenbusDxe/XenbusDxe.h | 10 ++++++++++
 2 files changed, 46 insertions(+), 3 deletions(-)
OvmfPkg/XenbusDxe/XenbusDxe.c +36 -3
index 14113ad..2c3d9b8 100644
@@ -16,7 +16,6 @@
 
 #include "XenbusDxe.h"
 
-
 ///
 /// Driver Binding Protocol instance
 ///
@@ -30,6 +29,8 @@ EFI_DRIVER_BINDING_PROTOCOL gXenbusDxeDriverBinding = {
 };
 
 
+XENBUS_DEVICE *mMyDevice;
+
 /**
   Unloads an image.
 
@@ -229,6 +230,19 @@ XenbusDxeDriverBindingSupported (
   return Status;
 }
 
+VOID
+EFIAPI
+NotifyExitBoot (
+  IN EFI_EVENT Event,
+  IN VOID *Context
+  )
+{
+  XENBUS_DEVICE *Dev = Context;
+
+  gBS->DisconnectController(Dev->ControllerHandle,
+                            Dev->This->DriverBindingHandle, NULL);
+}
+
 /**
   Starts a device controller or a bus controller.
 
@@ -272,7 +286,22 @@ XenbusDxeDriverBindingStart (
   IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  EFI_STATUS Status;
+  XENBUS_DEVICE *Dev;
+
+  Dev = AllocateZeroPool (sizeof (*Dev));
+  Dev->Signature = XENBUS_DEVICE_SIGNATURE;
+  Dev->This = This;
+  Dev->ControllerHandle = ControllerHandle;
+
+  Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
+                             NotifyExitBoot,
+                             (VOID*) Dev,
+                             &Dev->ExitBootEvent);
+  ASSERT_EFI_ERROR (Status);
+
+  mMyDevice = Dev;
+  return EFI_SUCCESS;
 }
 
 /**
@@ -310,5 +339,9 @@ XenbusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  XENBUS_DEVICE *Dev = mMyDevice;
+
+  gBS->CloseEvent (Dev->ExitBootEvent);
+
+  return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +0 -0
index 6f22732..c1ca87a 100644

OvmfPkg/XenbusDxe/XenbusDxe.h extern EFI_COMPONENT_NAME_PROTOCOL gXenbusDxeComponentName; · line 80

Quoted 6 lines
OvmfPkg/XenbusDxe/XenbusDxe.h +3 -0
@@ -75,4 +75,14 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenbusDxeComponentName;
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
 
+typedef struct _XENBUS_DEVICE XENBUS_DEVICE;
+
+#define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')

I get the 'XB', but 'bd' ? Should it be 'XenB' ? Or perhaps 'XBus' ?

Quoted 16 lines
OvmfPkg/XenbusDxe/XenbusDxe.h +7 -0
+struct _XENBUS_DEVICE {
+  UINT32                        Signature;
+  EFI_DRIVER_BINDING_PROTOCOL   *This;
+  EFI_HANDLE                    ControllerHandle;
+  EFI_EVENT                     ExitBootEvent;
+};
+
 #endif
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 04/18] OvmfPkg/XenbusDxe: Add support to make Xen Hypercalls.

In reply to a message not in the archive
Quoted 23 lines
OvmfPkg/XenbusDxe/XenHypercall.c new file +17 -0
new file mode 100644
index 0000000..5e98dd5
@@ -0,0 +1,101 @@
+#include <PiDxe.h>
+#include <Library/HobLib.h>
+#include <Guid/XenInfo.h>
+
+#include "XenbusDxe.h"
+#include "XenHypercall.h"
+
+#include <IndustryStandard/Xen/hvm/params.h>
+#include <IndustryStandard/Xen/memory.h>
+
+EFI_STATUS
+XenHyperpageInit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  EFI_HOB_GUID_TYPE   *GuidHob;
+  EFI_XEN_INFO        *XenInfo;

OvmfPkg/XenbusDxe/XenHypercall.c line 27

Quoted 10 lines
OvmfPkg/XenbusDxe/XenHypercall.c new file +10 -0
+
+  GuidHob = GetFirstGuidHob (&gEfiXenInfoGuid);
+  if (GuidHob == NULL) {
+    DEBUG ((EFI_D_INFO, "XenbusInit: No xeninfo ?\n"));
+    return EFI_NOT_FOUND;
+  }
+  XenInfo = (EFI_XEN_INFO*)GET_GUID_HOB_DATA (GuidHob);
+  Dev->Hyperpage = XenInfo->HyperPages;
+  return EFI_SUCCESS;
+}

Could you describe in the git commit a bit on how/where in hvmloader this EfiXenInfoGuid is set and how the OVMF gets a handle on it?

Thank you.

#29 lore raw

Re: [PATCH RFC 05/18] OvmfPkg/XenbusDxe: Open PciIo protocol.

In reply to a message not in the archive
Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

Could you describe a bit why you need to use it?

I think I know why - that is you need to poke at its IO ports but it would be good to mention that in here.

Quoted 63 lines
---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 16 ++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h |  1 +
 2 files changed, 17 insertions(+)
OvmfPkg/XenbusDxe/XenbusDxe.c +16 -0
index 63ea31b..ba5e8f4 100644
@@ -290,11 +290,25 @@ XenbusDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
+  EFI_PCI_IO_PROTOCOL *PciIo;
+
+  Status = gBS->OpenProtocol (
+                     ControllerHandle,
+                     &gEfiPciIoProtocolGuid,
+                     (VOID **)&PciIo,
+                     This->DriverBindingHandle,
+                     ControllerHandle,
+                     EFI_OPEN_PROTOCOL_BY_DRIVER
+                     );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
 
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
+  Dev->PciIo = PciIo;
 
   Status = XenHyperpageInit (Dev);
   ASSERT_EFI_ERROR (Status);
@@ -351,5 +365,7 @@ XenbusDxeDriverBindingStop (
 
   gBS->CloseEvent (Dev->ExitBootEvent);
 
+  gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +1 -0
index 6140f94..d57e3c8 100644
@@ -84,6 +84,7 @@ struct _XENBUS_DEVICE {
   UINT32                        Signature;
   EFI_DRIVER_BINDING_PROTOCOL   *This;
   EFI_HANDLE                    ControllerHandle;
+  EFI_PCI_IO_PROTOCOL           *PciIo;
   EFI_EVENT                     ExitBootEvent;
 
   VOID                          *Hyperpage;
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 06/18] OvmfPkg: Introduce Xenbus Protocol.

In reply to a message not in the archive
Quoted 27 lines · Anthony PERARD

This protocol will be used for communication between a PV driver (like a PV block driver) and the Xenbus/Xenstore.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h | 62 +++++++++++++++++++++++++++++++++++++++
 OvmfPkg/OvmfPkg.dec               |  2 ++
 OvmfPkg/XenbusDxe/ComponentName.c | 12 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  3 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |  1 +
 5 files changed, 80 insertions(+)
 create mode 100644 OvmfPkg/Include/Protocol/Xenbus.h
OvmfPkg/Include/Protocol/Xenbus.h new file +7 -0
new file mode 100644
index 0000000..191cee1
@@ -0,0 +1,62 @@
+
+/** @file
+  TODO: Brief Description of Protocol Xenbus
+
+  TODO: Detailed Description of Protocol Xenbus
+
+  TODO: Copyright for Protocol Xenbus

OvmfPkg/Include/Protocol/Xenbus.h line 17

Quoted 10 lines
OvmfPkg/Include/Protocol/Xenbus.h new file +10 -0
+
+  TODO: License for Protocol Xenbus
+
+**/
+
+#ifndef __PROTOCOL_XENBUS_H__
+#define __PROTOCOL_XENBUS_H__
+
+#define XENBUS_PROTOCOL_GUID \
+  {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}

For those who are not familiar with these GUIDs and live in the Linux world - how are they constructed? Is there a chance for collision ?

Quoted 50 lines
OvmfPkg/Include/Protocol/Xenbus.h new file +45 -0
+
+///
+/// Forward declaration
+///
+typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
+
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+///
+/// Function prototypes
+///
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_ACCESS)(
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame,
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *refp
+  );
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_END_ACCESS)(
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+
+///
+/// Protocol structure
+///
+struct _XENBUS_PROTOCOL {
+  XENBUS_GRANT_ACCESS           GrantAccess;
+  XENBUS_GRANT_END_ACCESS       GrantEndAccess;
+  //
+  // Place protocol data fields here
+  //
+};
+
+extern EFI_GUID gXenbusProtocolGuid;
+
+#endif
OvmfPkg/OvmfPkg.dec +0 -0
index f829247..095d40a 100644

OvmfPkg/OvmfPkg.dec line 51

Quoted 5 lines
OvmfPkg/OvmfPkg.dec +2 -0
@@ -47,6 +47,8 @@
 [Protocols]
   gVirtioDeviceProtocolGuid       = {0xfa920010, 0x6785, 0x4941, {0xb6, 0xec, 0x49, 0x8c, 0x57, 0x9f, 0x16, 0x0a}}
   gBlockMmioProtocolGuid          = {0x6b558ce3, 0x69e5, 0x4c67, {0xa6, 0x34, 0xf7, 0xfe, 0x72, 0xad, 0xbe, 0x84}}
+  ## Include/Protocol/Xenbus.h
+  gXenbusProtocolGuid = {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}

Formatting? Looks like the others use tabs?

Quoted 60 lines
OvmfPkg/OvmfPkg.dec +0 -0
 [PcdsFixedAtBuild]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|0x0|UINT32|0
OvmfPkg/XenbusDxe/ComponentName.c +12 -0
index 2cf11b5..fd46cc8 100644
@@ -140,6 +140,18 @@ XenbusDxeComponentNameGetControllerName (
   }
 
   //
+  // Make sure this driver is currently managing ControllerHandle
+  //
+  Status = EfiTestManagedDevice (
+             ControllerHandle,
+             gXenbusDxeDriverBinding.DriverBindingHandle,
+             &gXenbusProtocolGuid
+             );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
   // Lookup name of controller specified by ControllerHandle
   //
   Status = EFI_UNSUPPORTED;
OvmfPkg/XenbusDxe/XenbusDxe.h +3 -0
index d57e3c8..975fb6b 100644
@@ -42,6 +42,9 @@
 //
 // Produced Protocols
 //
+// Xen interface version used:
+#define  __XEN_INTERFACE_VERSION__ 0x00040400
+#include <Protocol/Xenbus.h>
 
 
 //
OvmfPkg/XenbusDxe/XenbusDxe.inf +1 -0
index 8b69f93..1a6b131 100644
@@ -55,6 +55,7 @@
   gEfiPciIoProtocolGuid
   gEfiComponentName2ProtocolGuid
   gEfiComponentNameProtocolGuid
+  gXenbusProtocolGuid
 
 
 [Guids]
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 08/18] OvmfPkg/XenbusDxe: Add Grant Table functions.

In reply to a message not in the archive
Quoted 4 lines · Anthony PERARD

There are used to grant access of pages to other Xen domains.

This code originaly comes from the Xen Project, and more precisely from MiniOS.

Should you mention something about its license?

Quoted 57 lines

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/GrantTable.c  | 204 ++++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/GrantTable.h  |  34 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c   |  15 +++
 OvmfPkg/XenbusDxe/XenbusDxe.inf |   2 +
 4 files changed, 255 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.c
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.h
OvmfPkg/XenbusDxe/GrantTable.c new file +37 -0
new file mode 100644
index 0000000..97bd15a
@@ -0,0 +1,204 @@
+/*
+ ****************************************************************************
+ * (C) 2006 - Cambridge University
+ ****************************************************************************
+ *
+ *        File: GrantTable.c
+ *      Author: Steven Smith ([email protected])
+ *     Changes: Grzegorz Milos ([email protected])
+ *
+ *        Date: July 2006
+ *
+ * Environment: Xen Minimal OS
+ * Description: Simple grant tables implementation. About as stupid as it's
+ *  possible to be and still work.
+ *
+ ****************************************************************************
+ */
+#include "XenbusDxe.h"
+
+#include <IndustryStandard/Xen/memory.h>
+
+#include "XenHypercall.h"
+
+#include "GrantTable.h"
+#include "InterlockedCompareExchange16.h"
+
+#define NR_RESERVED_ENTRIES 8
+
+/* NR_GRANT_FRAMES must be less than or equal to that configured in Xen */
+#define NR_GRANT_FRAMES 4
+#define NR_GRANT_ENTRIES (NR_GRANT_FRAMES * EFI_PAGE_SIZE / sizeof(grant_entry_v1_t))
+
+STATIC grant_entry_v1_t *GrantTable = NULL;
+STATIC grant_ref_t GrantList[NR_GRANT_ENTRIES];
+#ifdef GNT_DEBUG
+STATIC BOOLEAN GrantInUseList[NR_GRANT_ENTRIES];
+#endif

OvmfPkg/XenbusDxe/GrantTable.c line 47

Quoted 10 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +10 -0
+
+STATIC
+VOID
+XenGrantTablePutFreeEntry (
+  grant_ref_t Ref
+  )
+{
+  //local_irq_save(flags);
+  /* MemoryFence (); */
+  // lock ?

You just need some form of locking. If EFI has some simple Mutex() you can use that.

Quoted 121 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +121 -0
+#ifdef GNT_DEBUG
+  ASSERT (GrantInUseList[Ref]);
+  GrantInUseList[Ref] = FALSE;
+#endif
+  GrantList[Ref] = GrantList[0];
+  GrantList[0] = Ref;
+  //local_irq_restore(flags);
+  /* MemoryFence (); */
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGetFreeEntry (
+  VOID
+  )
+{
+  UINTN Ref;
+  /* local_irq_save(flags); */
+  // lock ??
+  Ref = GrantList[0];
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+  GrantList[0] = GrantList[Ref];
+#ifdef GNT_DEBUG
+  ASSERT (!GrantInUseList[Ref]);
+  GrantInUseList[Ref] = TRUE;
+#endif
+  /* local_irq_restore(flags); */
+  return Ref;
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGrantAccess (
+  IN domid_t  DomainId,
+  IN UINTN    Frame,
+  IN BOOLEAN  ReadOnly
+  )
+{
+  grant_ref_t Ref;
+  UINT32 Flags;
+
+  ASSERT (GrantTable != NULL);
+  Ref = XenGrantTableGetFreeEntry ();
+  GrantTable[Ref].frame = Frame;
+  GrantTable[Ref].domid = DomainId;
+  MemoryFence ();
+  Flags = GTF_permit_access;
+  if (ReadOnly) {
+    Flags |= GTF_readonly;
+  }
+  GrantTable[Ref].flags = Flags;
+
+  return Ref;
+}
+
+STATIC
+EFI_STATUS
+XenGrantTableEndAccess (
+  grant_ref_t Ref
+  )
+{
+  UINT16 Flags, OldFlags;
+
+  ASSERT (GrantTable != NULL);
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+
+  OldFlags = GrantTable[Ref].flags;
+  do {
+    if ((Flags = OldFlags) & (GTF_reading | GTF_writing)) {
+      DEBUG ((EFI_D_WARN, "WARNING: g.e. still in use! (%x)\n", Flags));
+      return EFI_NOT_READY;
+    }
+    OldFlags = InterlockedCompareExchange16 (&GrantTable[Ref].flags, Flags, 0);
+  } while (OldFlags != Flags);
+
+  XenGrantTablePutFreeEntry (Ref);
+  return EFI_SUCCESS;
+}
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  )
+{
+  xen_add_to_physmap_t Args;
+  INTN Index;
+  INTN ReturnCode;
+
+#ifdef GNT_DEBUG
+  SetMem(GrantInUseList, sizeof (GrantInUseList), 1);
+#endif
+  for (Index = NR_RESERVED_ENTRIES; Index < NR_GRANT_ENTRIES; Index++) {
+    XenGrantTablePutFreeEntry (Index);
+  }
+
+  GrantTable = (VOID*)(UINTN) MmioAddr;
+  for (Index = 0; Index < NR_GRANT_FRAMES; Index++) {
+    Args.domid = DOMID_SELF;
+    Args.idx = Index;
+    Args.space = XENMAPSPACE_grant_table;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_add_to_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, add_to_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+}
+
+VOID
+XenGrantTableDeinit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  INTN ReturnCode, Index;
+  xen_remove_from_physmap_t Args;
+
+  if (GrantTable == NULL) {
+    return;
+  }
+

OvmfPkg/XenbusDxe/GrantTable.c line 178

Quoted 10 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +10 -0
+  for (Index = NR_GRANT_FRAMES - 1; Index >= 0; Index--) {
+    Args.domid = DOMID_SELF;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    DEBUG ((EFI_D_INFO, "%a %d, removing %X\n", __func__, __LINE__, Args.gpfn));
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_remove_from_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, remove_from_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+  // XXX remove it from the physmap?

Didn't you just do that?

Quoted 88 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +26 -0
+  GrantTable = NULL;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  )
+{
+  *RefPtr = XenGrantTableGrantAccess (DomainId, Frame, ReadOnly);
+  return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  )
+{
+  return XenGrantTableEndAccess (Ref);
+}
OvmfPkg/XenbusDxe/GrantTable.h new file +34 -0
new file mode 100644
index 0000000..05ab4be
@@ -0,0 +1,34 @@
+#ifndef __GNTTAB_H__
+#define __GNTTAB_H__
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  );
+
+VOID
+XenGrantTableDeinit (
+  IN XENBUS_DEVICE  *Dev
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+#endif /* !__GNTTAB_H__ */
OvmfPkg/XenbusDxe/XenbusDxe.c +3 -0
index ba5e8f4..b19055d 100644
@@ -17,6 +17,7 @@
 #include "XenbusDxe.h"
 
 #include "XenHypercall.h"
+#include "GrantTable.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -291,6 +292,8 @@ XenbusDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
   EFI_PCI_IO_PROTOCOL *PciIo;
+  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
+  UINT64 MmioAddr;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStart ( · line 316

Quoted 4 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +1 -0
@@ -310,12 +313,23 @@ XenbusDxeDriverBindingStart (
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
 
+  Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);

I think we have a spec somewhere for this device. Do you think it might make sense to reference it here?

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStart ( · line 318

Quoted 2 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +2 -0
+  ASSERT_EFI_ERROR (Status);
+  ASSERT (BarDesc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM);

I sooo hope the spec mandates that it is always this type of BAR.

#38 lore raw

Re: [PATCH RFC 14/18] OvmfPkg/XenbusDxe: Indroduce XenBus support itself.

In reply to a message not in the archive
Quoted 154 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

---
 OvmfPkg/Include/Protocol/Xenbus.h |   9 +
 OvmfPkg/XenbusDxe/XenBus.c        | 360 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenBus.h        |  76 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c     |  61 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  18 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |   3 +
 6 files changed, 527 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.h
OvmfPkg/Include/Protocol/Xenbus.h +9 -0
index ef4d0c2..25408c1 100644
@@ -113,6 +113,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,
@@ -171,6 +179,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 +102 -0
new file mode 100644
index 0000000..b0cf1ba
@@ -0,0 +1,360 @@
+/******************************************************************************
+ * 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
+ *
+ * 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 "XenbusDxe.h"
+
+#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 \a node is known to
+ * the system.
+ *
+ * \param Dev   The XenBus bus instance to search for device children.
+ * \param node  The XenStore node path for the device to find.
+ *
+ * \return  The device_t of the found device if any, or NULL.
+ *
+ * \note device_t is a pointer type, so it can be compared against
+ *       NULL for validity.
+ */
+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;

OvmfPkg/XenbusDxe/XenBus.c line 112

Quoted 10 lines
OvmfPkg/XenbusDxe/XenBus.c new file +10 -0
+  CHAR8 *Ptr;
+  XENSTORE_STATUS Status;
+
+  Status = XenstoreRead (XST_NIL, Path, "state", NULL, (VOID **)&Ptr);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    State = XenbusStateClosed;
+  } else {
+    State = AsciiStrDecimalToUintn (Ptr);
+    FreePool (Ptr);
+  }

I think the FreePool(Ptr) should be here. You want to it irregardless of what the error might be (thought the implemenation in XenstoreRead et.all is pretty clear that we won't initialize *Ptr to anything if !Status. But just in case this changes in the future..

Quoted 66 lines
OvmfPkg/XenbusDxe/XenBus.c new file +66 -0
+
+  return State;
+}
+
+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);
+
+  Status = EFI_NOT_STARTED; //ENXIO; // Device not configured
+
+  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 188

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 provide a comment explaining why you do that please?

OvmfPkg/XenbusDxe/XenBus.c line 196

Quoted 8 lines
OvmfPkg/XenbusDxe/XenBus.c new file +8 -0
+    FreePool (TempXenbusPath);
+
+    Status = gBS->InstallMultipleProtocolInterfaces (
+               &Private->Handle,
+               &gEfiDevicePathProtocolGuid, Private->DevicePath,
+               &gXenbusProtocolGuid, &Private->XenbusIo,
+               NULL);
+    if (EFI_ERROR (Status)) {

Shouldn't you free 'Private' and 'BackendPath' ? And also de-link yourself from 'Dev->ChildList' ?

Quoted 123 lines
OvmfPkg/XenbusDxe/XenBus.c new file +123 -0
+      return Status;
+    }
+
+    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));
+    }
+  } else {
+    DEBUG ((EFI_D_INFO, "Xenbus: does not exist: %a\n", DevicePath));
+  }
+
+out:
+  return Status;
+}
+
+/**
+ * \brief Enumerate all devices of the given type on this bus.
+ *
+ * \param Dev   NewBus device_t for this XenBus front bus instance.
+ * \param type  String indicating the device sub-tree (e.g. "vfb", "vif")
+ *              to enumerate.
+ *
+ * Devices that are found are entered into the NewBus hierarchy via
+ * xenbusb_add_device().  xenbusb_add_device() ignores duplicate detects
+ * and ignores duplicate devices, so it can be called unconditionally
+ * for any device found in the XenStore.
+ */
+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);
+}
+
+
+/**
+ * \brief Enumerate the devices on a XenBus bus and register them with
+ *        the NewBus device tree.
+ *
+ * xenbusb_enumerate_bus() will create entries (in state DS_NOTPRESENT)
+ * for nodes that appear in the XenStore, but will not invoke probe/attach
+ * operations on drivers.  Probe/Attach processing must be separately
+ * performed via an invocation of xenbusb_probe_children().  This is usually
+ * done via the xbs_probe_children task.
+ *
+ * \param Dev  XenBus Bus device softc of the owner of the bus to enumerate.
+ *
+ * \return  On success, 0. Otherwise an errno value indicating the
+ *          type of failure.
+ */
+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 Error;
+  }
+  CurrentState = AsciiStrDecimalToUintn (Temp);
+  FreePool (Temp);

OvmfPkg/XenbusDxe/XenBus.c line 329

Quoted 10 lines
OvmfPkg/XenbusDxe/XenBus.c new file +10 -0
+  if (CurrentState == NewState) {
+    DEBUG ((EFI_D_INFO, "%a %d, same state\n", __func__, __LINE__));
+    goto Error;
+  }
+
+  do {
+    Status = XenstoreSPrint (Transaction, This->Node, "state", "%d", NewState);
+  } while (Status == XENSTORE_STATUS_EAGAIN);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "Xenbus: fail to writing new state\n"));

failed to write new state

OvmfPkg/XenbusDxe/XenBus.c line 334

Quoted 5 lines
OvmfPkg/XenbusDxe/XenBus.c new file +5 -0
+    goto Error;
+  }
+  DEBUG ((EFI_D_INFO, "Xenbus: Set state to %d, done\n", NewState));
+
+Error:

s/Error/Out/

as it is OK for to set to the same state twice.

Quoted 174 lines
OvmfPkg/XenbusDxe/XenBus.c new file +26 -0
+  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 +76 -0
new file mode 100644
index 0000000..63d0815
@@ -0,0 +1,76 @@
+/*-
+ * Core definitions and data structures shareable across OS platforms.
+ *
+ * Copyright (c) 2010 Spectra Logic Corporation
+ * Copyright (C) 2008 Doug Rabson
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * $FreeBSD: release/10.0.0/sys/xen/xenbus/xenbusb.h 222975 2011-06-11 04:59:01Z gibbs $
+ */
+#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;
+  UINT16              DeviceId;
+};
+
+/**
+ * The VM relative path to the XenStore subtree this
+ * bus attachment manages.
+ *
+ * OR
+ *
+ * The XenStore path to the XenStore subtree for this XenBus bus.
+ */
+#define XENBUS_XENSTORE_NODE "device"
+
+
+/**
+ * \brief Perform common XenBus bus attach processing.
+ *
+ * \param Dev            The NewBus device representing this XenBus bus.
+ *
+ * \return  On success, 0. Otherwise an errno value indicating the
+ *          type of failure.
+ *
+ * Intiailizes the softc for this bus, installs an interrupt driven
+ * configuration hook to block boot processing until XenBus devices fully
+ * configure, performs an initial probe/attach of the bus, and registers
+ * a XenStore watch so we are notified when the bus topology changes.
+ */
+XENSTORE_STATUS
+XenbusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  );
+
+#endif /* _XEN_XENBUS_XENBUSB_H */
OvmfPkg/XenbusDxe/XenbusDxe.c +23 -0
index 2c85d5e..56225c4 100644
@@ -19,6 +19,7 @@
 #include "XenHypercall.h"
 #include "GrantTable.h"
 #include "Xenstore.h"
+#include "XenBus.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -295,6 +296,7 @@ XenbusDxeDriverBindingStart (
   EFI_PCI_IO_PROTOCOL *PciIo;
   EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
   UINT64 MmioAddr;
+  EFI_DEVICE_PATH_PROTOCOL *DevicePath;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -308,11 +310,26 @@ XenbusDxeDriverBindingStart (
     return Status;
   }
 
+  Status = gBS->OpenProtocol (
+                  ControllerHandle,
+                  &gEfiDevicePathProtocolGuid,
+                  (VOID **) &DevicePath,
+                  This->DriverBindingHandle,
+                  ControllerHandle,
+                  EFI_OPEN_PROTOCOL_BY_DRIVER
+                  );
+
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
+  Dev->DevicePath = DevicePath;
+  InitializeListHead (&Dev->ChildList);
 
   Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);
   ASSERT_EFI_ERROR (Status);
@@ -334,6 +351,8 @@ XenbusDxeDriverBindingStart (
   Status = XenstoreInit (Dev);
   ASSERT_EFI_ERROR (Status);
 
+  XenbusEnumerateBus (Dev);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -379,12 +398,54 @@ XenbusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  UINTN Index;
+  XENBUS_PROTOCOL *XenbusIo;
+  XENBUS_PRIVATE_DATA *ChildData;
+  EFI_STATUS Status;
   XENBUS_DEVICE *Dev = mMyDevice;
 

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStop ( · line 416

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +10 -0
+  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 childre proto: %r\n", Status));

get children protocol failed: %r

Quoted 98 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +28 -0
+      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);
+  }
+
   gBS->CloseEvent (Dev->ExitBootEvent);
+  // XXX xenbus cleanup
   // XXX xenstore cleanup
   XenGrantTableDeinit (Dev);
 
+  gBS->CloseProtocol(ControllerHandle, &gEfiDevicePathProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
OvmfPkg/XenbusDxe/XenbusDxe.h +18 -0
index 4d9db72..3ff08dd 100644
@@ -80,6 +80,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;
 
 #define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')
@@ -89,11 +90,28 @@ 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;
 };
 
+#define XENBUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X', 'B', 'u', 's')
+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 6c8260f..708fae6 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
#41 lore raw

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

In reply to a message not in the archive
Quoted 79 lines · Anthony PERARD

This is the code that will do the actual communication between OVMF and a PV block backend, where the block device lives.

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

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockFront.c    | 583 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockFront.h    |  88 ++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |   8 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 4 files changed, 681 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.h
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +55 -0
new file mode 100644
index 0000000..ff5641c
@@ -0,0 +1,583 @@
+/* Minimal block driver for Mini-OS.
+ * Copyright (c) 2007-2008 Samuel Thibault.
+ * Based on netfront.c.
+ */
+
+#include <Library/PrintLib.h>
+#include <Library/DebugLib.h>
+
+#include "BlockFront.h"
+
+#include <IndustryStandard/Xen/io/protocols.h>
+#include <IndustryStandard/Xen/io/xenbus.h>
+
+#include "inttypes.h"
+
+STATIC
+XENSTORE_STATUS
+XenbusReadInteger (
+  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);
+  }
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+  // XXX Will assert if p overflow UINT64 ...
+  *ValuePtr = AsciiStrDecimalToUint64 (p);
+  FreePool (p);
+  return Status;
+}
+
+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);
+  }

OvmfPkg/XenPvBlkDxe/BlockFront.c line 65

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  if (Dev->EventChannel != 0) {
+    XenbusIo->EventChannelClose (XenbusIo, Dev->EventChannel);
+  }
+  FreePool (Dev);
+}
+
+XENSTORE_STATUS
+XenPvBlkWaitForBackendState (
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN  XenbusState            WaitedState,

ExpectedState

?

Quoted 8 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +8 -0
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenbusIo = Dev->XenbusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status;
+

OvmfPkg/XenPvBlkDxe/BlockFront.c line 83

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  while (TRUE) {
+    Status = XenbusReadInteger (XenbusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
+    }
+    if (Value > XenbusStateReconfigured) {
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State >= WaitedState) {

Not State != WaitedState ?

Quoted 58 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +58 -0
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            WaitedState, State));
+    XenbusIo->WaitForWatch (XenbusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+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 = XenbusReadInteger (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);

OvmfPkg/XenPvBlkDxe/BlockFront.c line 151

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  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));

.. and do you want to error out?

Quoted 54 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +54 -0
+  }
+
+  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"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->SetState (XenbusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->XsTransactionEnd (XenbusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
+  }
+
+  XenbusIo->RegisterWatchBackend (XenbusIo, "state", &Dev->StateWatchToken);
+
+  // Waiting backend
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS || State != XenbusStateConnected) {
+    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 = XenbusReadInteger (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;
+  }
+

OvmfPkg/XenPvBlkDxe/BlockFront.c line 215

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  Status = XenbusReadInteger (XenbusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenbusReadInteger (XenbusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;

Why not &Dev->MediaInfo.SectorSize in XenbusReadInteger?

Is it because of types? If so, please add a comment stating that.

Quoted 19 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +19 -0
+
+  // Default value
+  Value = 0;
+  Status = XenbusReadInteger (XenbusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenbusReadInteger (XenbusIo, "feature-flush-cache", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureFlushCache = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureFlushCache = FALSE;
+  }
+

OvmfPkg/XenPvBlkDxe/BlockFront.c line 244

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %d 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");

?

Quoted 70 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +70 -0
+  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 = XenbusReadInteger (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;
+    }

OvmfPkg/XenPvBlkDxe/BlockFront.c line 324

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+    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");

"protocol"

Quoted 41 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +41 -0
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC
+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)) {
+        break;
+      }
+      /* Really no slot, go to sleep. */
+      // XXX wait for an event on Dev->EventChannel
+      DEBUG ((EFI_D_INFO, "%a %d, waiting\n", __func__, __LINE__));
+    }
+  }
+}
+
+/* Issue an aio */
+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)));

OvmfPkg/XenPvBlkDxe/BlockFront.c line 375

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  // 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;
+
+  // XXX is this comment still true ?

I think it is outdated, as Linux would do max DMA up to the segment size that is advertised. Ditto for the SCSI stack.

OvmfPkg/XenPvBlkDxe/BlockFront.c line 378

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +3 -0
+  /* qemu's IDE max multsect is 16 (8KB) and SCSI max DMA was set to 32KB,
+   * so max 44KB can't happen */
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);

But this check is OK as we can't truly fit more on the ring.

OvmfPkg/XenPvBlkDxe/BlockFront.c line 380

Quoted 2 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +2 -0
+
+  XenPvBlockWaitSlot (Dev);

What happens if there are multiple threads calling this function? Don't we need a mutex to only allow one thread to grab an RingIndex?

OvmfPkg/XenPvBlkDxe/BlockFront.c line 391

Quoted 11 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +11 -0
+  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;
+
+  for (Index = 0; Index < NumSegments; Index++) {
+    Request->seg[Index].first_sect = 0;

Uh?

OvmfPkg/XenPvBlkDxe/BlockFront.c line 392

Quoted 1 line
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +1 -0
+    Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;

Uh? I thought you wanted to use the real sector values?

OvmfPkg/XenPvBlkDxe/BlockFront.c line 396

Quoted 4 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +4 -0
+  }
+  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;

What about in between 0 and NumSegments? You should also fill out those values with valid entries.

OvmfPkg/XenPvBlkDxe/BlockFront.c line 400

Quoted 4 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +4 -0
+  for (Index = 0; Index < NumSegments; Index++) {
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;
+    if (!IsWrite) {
+      /* Trigger CoW if needed */

Not sure I understand that reference?

Quoted 28 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +28 -0
+      *(CHAR8 *)(Data + (Request->seg[Index].first_sect << 9)) = 0;
+      MemoryFence ();
+    }
+    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);
+  }
+}
+
+STATIC
+VOID
+XenPvBlockAsyncIoCallback (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     EFI_STATUS         Status
+  )
+{
+  IoData->Data = (VOID *) 1;
+  IoData->Callback = NULL;

OvmfPkg/XenPvBlkDxe/BlockFront.c line 438

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+}
+
+VOID
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  ASSERT (IoData->Callback == NULL);
+  // XXX Signal/Event instead ?

Maybe for later versions. I think this is OK for right now, thought it will mean we can only do one I/O .. and have then to wait until it is completed.

That limititation should be mentioned in the commit description.

Quoted 15 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +15 -0
+  IoData->Callback = XenPvBlockAsyncIoCallback;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+  IoData->Data = NULL;
+
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+    if (IoData->Data) {
+      break;
+    }
+  }
+}
+
+STATIC
+VOID
+XenPvBlockPushOperation (

OvmfPkg/XenPvBlkDxe/BlockFront.c line 463

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN UINT8                  Operation,
+  IN UINT64                 Id
+  )
+{
+  INT32 Index;
+  blkif_request_t *Request;
+  BOOLEAN Notify;
+
+  XenPvBlockWaitSlot (Dev);

How do we make sure that there aren't multiple threads calling this?

Quoted 103 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +103 -0
+  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);
+  }
+}
+
+VOID
+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;
+      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 %Ld, num bytes %Ld\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));

OvmfPkg/XenPvBlkDxe/BlockFront.c line 576

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+        break;
+      }
+
+      Dev->Ring.rsp_cons = ++ConsumerIndex;
+      /* Nota: callback frees IoData itself */
+      if (IoData && IoData->Callback) {
+        IoData->Callback (IoData, Status ? EFI_DEVICE_ERROR : EFI_SUCCESS);
+      }
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {
+        /* We reentered, we must not continue here */

Uh, how does that happen?

Quoted 7 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +7 -0
+        break;
+      }
+    }
+
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);
+  } while (More != 0);
+}
#46 lore raw

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

In reply to a message not in the archive
Quoted 78 lines · Anthony PERARD

Install the BlockIo protocol.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockIo.c       | 256 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h       | 109 +++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |  59 +++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |   1 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 5 files changed, 427 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +58 -0
new file mode 100644
index 0000000..4ac2411
@@ -0,0 +1,256 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Detailed Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Copyright for UEFI Driver XenPvBlkDxe
+
+  TODO: License for UEFI Driver XenPvBlkDxe
+
+**/
+
+#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
+  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
+  (EFI_BLOCK_RESET)XenPvBlkDxeBlockIoReset, // Reset
+  XenPvBlkDxeBlockIoReadBlocks,             // ReadBlocks
+  XenPvBlkDxeBlockIoWriteBlocks,            // WriteBlocks
+  XenPvBlkDxeBlockIoFlushBlocks             // FlushBlocks
+};
+
+
+
+
+STATIC
+EFI_STATUS
+XenPvBlkDxeBlockIoReadWriteBlocks (
+  IN     EFI_BLOCK_IO_PROTOCOL  *This,
+  IN     UINT32                 MediaId,
+  IN     EFI_LBA                Lba,
+  IN     UINTN                  BufferSize,

OvmfPkg/XenPvBlkDxe/BlockIo.c line 68

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +10 -0
+  IN OUT VOID                   *Buffer,
+  IN     BOOLEAN                IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_IO IoData;
+  EFI_BLOCK_IO_MEDIA *Media;
+  UINTN NextOffset;
+
+  if (Buffer == NULL) {
+    DEBUG ((EFI_D_ERROR, "%a %d, buffer null\n", __func__, __LINE__));

Heheh.

Quoted 46 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +46 -0
+    return EFI_INVALID_PARAMETER;
+  }
+  if (BufferSize == 0) {
+    return EFI_SUCCESS;
+  }
+
+  Media = This->Media;
+
+  if (BufferSize % Media->BlockSize != 0) {
+    DEBUG ((EFI_D_ERROR, "%a %d, bad buffer size\n", __func__, __LINE__));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  if (Lba > Media->LastBlock ||
+      (BufferSize / Media->BlockSize) - 1 > Media->LastBlock - Lba) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read too large\n", __func__, __LINE__));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (IsWrite && Media->ReadOnly) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read only\n", __func__, __LINE__));
+    return EFI_WRITE_PROTECTED;
+  }
+
+  if ((Media->IoAlign > 1) && (UINTN)Buffer & (Media->IoAlign - 1)) {
+    // This happen often when using grub2
+    VOID *NewBuffer;
+    EFI_STATUS Status;
+
+    /* 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);
+    return Status;
+  }
+
+

OvmfPkg/XenPvBlkDxe/BlockIo.c line 124

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +10 -0
+  // XXX Check MediaId
+
+  IoData.Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (This);
+  IoData.Offset = Lba * Media->BlockSize;
+  IoData.Callback = NULL;
+  IoData.Data = NULL;
+  IoData.Size = BufferSize;
+  IoData.Buffer = Buffer;
+
+  NextOffset = Lba * Media->BlockSize;

Or just = IoData.Offset ?

OvmfPkg/XenPvBlkDxe/BlockIo.c line 127

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+  while (BufferSize > 0) {
+    // This should work if every Buffer is page aligned
+    // but block accept sector aligned, so FIXME

Isn't the work-around for GRUB2 above doing this?

OvmfPkg/XenPvBlkDxe/BlockIo.c line 129

Quoted 2 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +2 -0
+    IoData.Size = MIN(EFI_PAGE_SIZE * 8,//BLKIF_MAX_SEGMENTS_PER_REQUEST,
+                           BufferSize);

Why 8 ?

OvmfPkg/XenPvBlkDxe/BlockIo.c line 136

Quoted 7 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +7 -0
+    IoData.Buffer = Buffer;
+    IoData.Offset = NextOffset;
+    BufferSize -= IoData.Size;
+    Buffer = (VOID*) ((UINTN) Buffer + IoData.Size);
+    NextOffset += IoData.Size;
+    XenPvBlockIo (&IoData, IsWrite);
+    if (!IoData.Data) {

Well that wouldn't be possible as the XenPvBlockIo loops forever until that is done.

However, you should probably have a comment here:

/* XXX If we move to a different mechanism for CallBack this might
go away */

Quoted 107 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +107 -0
+      DEBUG ((EFI_D_ERROR, "%a %d, XenPvBlockIo no data...\n", __func__, __LINE__));
+      return EFI_DEVICE_ERROR;
+    }
+  }
+  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 Indicates that the driver may perform a more
+                                   exhausive verfication operation of the device
+                                   during reset.
+
+  @retval EFI_SUCCESS          The device was reset.
+  @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
+                               not be reset.
+

OvmfPkg/XenPvBlkDxe/BlockIo.c line 253

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +10 -0
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO2_PROTOCOL  *This,
+  IN BOOLEAN                 ExtendedVerification
+  )
+{
+  // Is there anything to do ?
+  // since initialisation is done in Start (driver binding)

Won't we leak memory? Or will it after an Reset do Stop, then Start?

Quoted 142 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+  DEBUG ((EFI_D_INFO, "%a %d\n", __func__, __LINE__));
+  return EFI_SUCCESS;
+}
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +109 -0
new file mode 100644
index 0000000..ec0fe2b
@@ -0,0 +1,109 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Detailed Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Copyright for UEFI Driver XenPvBlkDxe
+
+  TODO: License for UEFI Driver XenPvBlkDxe
+
+**/
+
+/**
+  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
+  );
+
+/**
+  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
+  );
+
+/**
+  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
+  );
+
+/**
+  Reset the block device hardware.
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Indicates that the driver may perform a more
+                                   exhausive verfication operation of the device
+                                   during reset.
+
+  @retval EFI_SUCCESS          The device was reset.
+  @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
+                               not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO2_PROTOCOL  *This,
+  IN BOOLEAN                 ExtendedVerification
+  );
+
+extern EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia;
+extern EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo;
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +9 -0
index 7ec7d60..3991e83 100644
@@ -266,6 +266,7 @@ XenPvBlkDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenbusIo;
   XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -284,6 +285,37 @@ XenPvBlkDxeDriverBindingStart (
     return Status;
   }
 
+  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;

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c XenPvBlkDxeDriverBindingStart ( · line 305

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +10 -0
+  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;
+  } else {
+    Media->BlockSize = Dev->MediaInfo.SectorSize;
+  }
+  Media->LastBlock = Dev->MediaInfo.Sectors - 1;
+  // XXX What about LowestAlignedLba, LogicalBlocksPerPhysicalBlock and OptimalTransferLengthGranularity?

I think you can skip LogicalBlocksPerPhysicalBlock and OptimalTransferLengthGranularity as they are used for discard operations.

The LowestAlignedLba .. no idea.

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c XenPvBlkDxeDriverBindingStart ( · line 314

Quoted 9 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +9 -0
+  Dev->BlockIo.Media = Media;
+
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                    &ControllerHandle,
+                    &gEfiBlockIoProtocolGuid, &Dev->BlockIo,
+                    NULL
+                    );
+  if (EFI_ERROR (Status)) {
+    // XXX: uninit everythings

XenPvBlockFrontShutdown (Dev); ?
FreePool(Media) ?

Quoted 74 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +31 -0
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: install protocol fail: %r\n", Status));
+    return Status;
+  }
+
   return EFI_SUCCESS;
 }
 
@@ -322,6 +354,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 186d0ee..3120137 100644
@@ -76,6 +76,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
 //
 #include "DriverBinding.h"
 #include "ComponentName.h"
+#include "BlockIo.h"
 
 
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index a43d006..b379020 100644
@@ -32,6 +32,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
#48 lore raw

Re: [PATCH RFC 00/18] Introducing Xen PV block driver to OVMF

In reply to a message not in the archive
Quoted 11 lines · Anthony PERARD

Hi all,

This patch series is implementing the necessary in order to access a PV block device. For that, one need a XenStore client, a XenBus client, and the PV block driver.

There are two new drivers, XenbusDxe and XenPvBlkDxe. The first one implement a bus drivers, and the second is a block drivers.

There are still a bit of work to be done on this series, especially the comment in the code, but I'd like your comment on this patch series.

Went through it - I had some questions and spotted some issues that are pretty easy to fix.

Otherwise I think you just need to flesh it out with more comments, links to the specs or just copy the relevant parts.

And little puzzled by the usage of 8 pages instead of doing it via 11. But that is probably not a big deal since you are doing each I/O request synchronously anyhow.

Thank you for posting this and developing it!

Quoted 135 lines

Anthony PERARD (18):
OvmfPkg: Add public headers from Xen Project.
OvmfPkg: Add basic skeleton for the Xenbus driver. OvmfPkg/XenbusDxe: Add device state struct and create an ExitBoot
services event.
OvmfPkg/XenbusDxe: Add support to make Xen Hypercalls. OvmfPkg/XenbusDxe: Open PciIo protocol.
OvmfPkg: Introduce Xenbus Protocol.
OvmfPkg/XenbusDxe: Add InterlockedCompareExchange16. OvmfPkg/XenbusDxe: Add Grant Table functions. OvmfPkg/XenbusDxe: Add Event Channel Notify. OvmfPkg/XenbusDxe: Add TestAndClearBit. OvmfPkg/XenbusDxe: Add XenStore client implementation OvmfPkg/XenbusDxe: Add an helper AsciiStrDup. OvmfPkg/XenbusDxe: Add Xenstore function into the Xenbus protocol OvmfPkg/XenbusDxe: Indroduce XenBus support itself. OvmfPkg/XenbusDxe: Add Event Channel into XenBus protocol. OvmfPkg/XenPvBlkDxe: Xen PV Block device, initial skeleton OvmfPkg/XenPvBlkDxe: Add BlockFront client. OvmfPkg/XenPvBlkDxe: Add BlockIo.

 .../IndustryStandard/Xen/arch-x86/xen-x86_32.h     |  171 +++
 .../IndustryStandard/Xen/arch-x86/xen-x86_64.h     |  202 +++
 .../Include/IndustryStandard/Xen/arch-x86/xen.h    |  273 ++++
 .../Include/IndustryStandard/Xen/event_channel.h   |  381 +++++
 OvmfPkg/Include/IndustryStandard/Xen/grant_table.h |  662 +++++++++
 OvmfPkg/Include/IndustryStandard/Xen/hvm/hvm_op.h  |  275 ++++
 OvmfPkg/Include/IndustryStandard/Xen/hvm/params.h  |  150 ++
 OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h    |  608 ++++++++
 .../Include/IndustryStandard/Xen/io/protocols.h    |   40 +
 OvmfPkg/Include/IndustryStandard/Xen/io/ring.h     |  312 +++++
 OvmfPkg/Include/IndustryStandard/Xen/io/xenbus.h   |   80 ++
 OvmfPkg/Include/IndustryStandard/Xen/io/xs_wire.h  |  138 ++
 OvmfPkg/Include/IndustryStandard/Xen/memory.h      |  480 +++++++
 OvmfPkg/Include/IndustryStandard/Xen/sched.h       |  174 +++
 OvmfPkg/Include/IndustryStandard/Xen/trace.h       |  310 +++++
 OvmfPkg/Include/IndustryStandard/Xen/xen-compat.h  |   44 +
 OvmfPkg/Include/IndustryStandard/Xen/xen.h         |  897 ++++++++++++
 OvmfPkg/Include/Protocol/Xenbus.h                  |  231 +++
 OvmfPkg/OvmfPkg.dec                                |    2 +
 OvmfPkg/OvmfPkgX64.dsc                             |    2 +
 OvmfPkg/OvmfPkgX64.fdf                             |    2 +
 OvmfPkg/XenPvBlkDxe/BlockFront.c                   |  583 ++++++++
 OvmfPkg/XenPvBlkDxe/BlockFront.h                   |   88 ++
 OvmfPkg/XenPvBlkDxe/BlockIo.c                      |  256 ++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h                      |  109 ++
 OvmfPkg/XenPvBlkDxe/ComponentName.c                |  160 +++
 OvmfPkg/XenPvBlkDxe/ComponentName.h                |   91 ++
 OvmfPkg/XenPvBlkDxe/DriverBinding.h                |  139 ++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c                  |  388 ++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h                  |   83 ++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf                |   61 +
 OvmfPkg/XenbusDxe/ComponentName.c                  |  160 +++
 OvmfPkg/XenbusDxe/ComponentName.h                  |   91 ++
 OvmfPkg/XenbusDxe/DriverBinding.h                  |  139 ++
 OvmfPkg/XenbusDxe/EventChannel.c                   |   71 +
 OvmfPkg/XenbusDxe/EventChannel.h                   |   40 +
 OvmfPkg/XenbusDxe/GrantTable.c                     |  204 +++
 OvmfPkg/XenbusDxe/GrantTable.h                     |   34 +
 OvmfPkg/XenbusDxe/Helpers.c                        |    9 +
 OvmfPkg/XenbusDxe/InterlockedCompareExchange16.h   |    7 +
 .../XenbusDxe/X64/InterlockedCompareExchange16.c   |   41 +
 OvmfPkg/XenbusDxe/X64/TestAndClearBit.S            |   10 +
 OvmfPkg/XenbusDxe/X64/hypercall.S                  |   16 +
 OvmfPkg/XenbusDxe/X64/hypercall.asm                |   19 +
 OvmfPkg/XenbusDxe/XenBus.c                         |  363 +++++
 OvmfPkg/XenbusDxe/XenBus.h                         |   76 +
 OvmfPkg/XenbusDxe/XenHypercall.c                   |  101 ++
 OvmfPkg/XenbusDxe/XenHypercall.h                   |   44 +
 OvmfPkg/XenbusDxe/XenbusDxe.c                      |  452 ++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h                      |  131 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf                    |   75 +
 OvmfPkg/XenbusDxe/Xenstore.c                       | 1472 ++++++++++++++++++++
 OvmfPkg/XenbusDxe/Xenstore.h                       |  367 +++++
 53 files changed, 11314 insertions(+)
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_32.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen-x86_64.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/arch-x86/xen.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/event_channel.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/grant_table.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/hvm/hvm_op.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/hvm/params.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/blkif.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/protocols.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/ring.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/xenbus.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/io/xs_wire.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/memory.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/sched.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/trace.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/xen-compat.h
 create mode 100644 OvmfPkg/Include/IndustryStandard/Xen/xen.h
 create mode 100644 OvmfPkg/Include/Protocol/Xenbus.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/ComponentName.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/ComponentName.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/DriverBinding.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h
 create mode 100644 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf
 create mode 100644 OvmfPkg/XenbusDxe/ComponentName.c
 create mode 100644 OvmfPkg/XenbusDxe/ComponentName.h
 create mode 100644 OvmfPkg/XenbusDxe/DriverBinding.h
 create mode 100644 OvmfPkg/XenbusDxe/EventChannel.c
 create mode 100644 OvmfPkg/XenbusDxe/EventChannel.h
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.c
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.h
 create mode 100644 OvmfPkg/XenbusDxe/Helpers.c
 create mode 100644 OvmfPkg/XenbusDxe/InterlockedCompareExchange16.h
 create mode 100644 OvmfPkg/XenbusDxe/X64/InterlockedCompareExchange16.c
 create mode 100644 OvmfPkg/XenbusDxe/X64/TestAndClearBit.S
 create mode 100644 OvmfPkg/XenbusDxe/X64/hypercall.S
 create mode 100644 OvmfPkg/XenbusDxe/X64/hypercall.asm
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.h
 create mode 100644 OvmfPkg/XenbusDxe/XenHypercall.c
 create mode 100644 OvmfPkg/XenbusDxe/XenHypercall.h
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.c
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.h
 create mode 100644 OvmfPkg/XenbusDxe/XenbusDxe.inf
 create mode 100644 OvmfPkg/XenbusDxe/Xenstore.c
 create mode 100644 OvmfPkg/XenbusDxe/Xenstore.h
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 04/18] OvmfPkg/XenbusDxe: Add support to make Xen Hypercalls.

In reply to Konrad Rzeszutek Wilk

On Wed, Jul 16, 2014 at 01:37:05PM -0400, Konrad Rzeszutek Wilk wrote:
[...]

Quoted 13 lines
Quoted 13 lines
(quoted diff) +13 -0
+
+EFI_STATUS
+XenHyperpageInit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  EFI_HOB_GUID_TYPE   *GuidHob;
+  EFI_XEN_INFO        *XenInfo;
+
+  GuidHob = GetFirstGuidHob (&gEfiXenInfoGuid);
+  if (GuidHob == NULL) {
+    DEBUG ((EFI_D_INFO, "XenbusInit: No xeninfo ?\n"));
+    return EFI_NOT_FOUND;
Quoted 9 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+  }
+  XenInfo = (EFI_XEN_INFO*)GET_GUID_HOB_DATA (GuidHob);
+  Dev->Hyperpage = XenInfo->HyperPages;
+  return EFI_SUCCESS;
+}

Could you describe in the git commit a bit on how/where in hvmloader this EfiXenInfoGuid is set and how the OVMF gets a handle on it?

I don't think hvmloader creates this info. OVMF creates this by itself. See OvmfPkg/PlatformPei/Xen.c:XenConnect.

Wei.

Quoted 6 lines

Thank you.

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

#21 lore raw

Re: [PATCH RFC 02/18] OvmfPkg: Add basic skeleton for the Xenbus driver.

In reply to Konrad Rzeszutek Wilk
Quoted 5 lines · Konrad Rzeszutek Wilk
Quoted 1 line · Anthony PERARD

This includes Component Name and Driver Binding.

The title says driver, but the cover letter said 'bus driver'. Should it have bus driver in it?

Do you mean having "Xenbus bus driver" in the title? It feels a bit redondant, but might be better.

Quoted 25 lines

.. snip..

Quoted 14 lines
(quoted diff) +14 -0
+/**
+  Retrieves a Unicode string that is the user readable name of the controller
+  that is being managed by an EFI Driver.
+
+  @param  This             A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
+  @param  ControllerHandle The handle of a controller that the driver specified by
+                           This is managing.  This handle specifies the controller
+                           whose name is to be returned.
+  @param  ChildHandle      The handle of the child controller to retrieve the name
+                           of.  This is an optional parameter that may be NULL.  It
+                           will be NULL for device drivers.  It will also be NULL
+                           for a bus drivers that wish to retrieve the name of the
+                           bus controller.  It will not be NULL for a bus driver
+                           that wishes to retrieve the name of a child controller.

.. snip..

Quoted 9 lines
(quoted diff) +9 -0
+EFI_STATUS
+EFIAPI
+XenbusDxeComponentNameGetControllerName (
+  IN  EFI_COMPONENT_NAME2_PROTOCOL  *This,
+  IN  EFI_HANDLE                    ControllerHandle,
+  IN  EFI_HANDLE                    ChildHandle        OPTIONAL,
+  IN  CHAR8                         *Language,
+  OUT CHAR16                        **ControllerName
+  )
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+{
+  EFI_STATUS  Status;
+
+  //
+  // ChildHandle must be NULL for a Device Driver

OK, but this is a bus driver in which case ChildHandle can be NULL or not (at least that is what the comment says) ?

Yes. Most (all?) of the code in this files (and this patch) comes from a template. I haven't been through the comment yet. But yes this bus driver can have childs.

Quoted 69 lines
Quoted 12 lines
(quoted diff) +12 -0
+  //
+  if (ChildHandle != NULL) {
+    return EFI_UNSUPPORTED;
+  }
+
+  //
+  // Lookup name of controller specified by ControllerHandle
+  //
+  Status = EFI_UNSUPPORTED;
+
+  return Status;
+}

.. snip..

Quoted 55 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +49 -0
new file mode 100644
index 0000000..14113ad
@@ -0,0 +1,314 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenbusDxe
+
+  TODO: Detailed Description of UEFI Driver XenbusDxe
+
+  TODO: Copyright for UEFI Driver XenbusDxe
+
+  TODO: License for UEFI Driver XenbusDxe
+
+**/
+
+#include <IndustryStandard/Pci.h>
+#include <IndustryStandard/Acpi.h>
+#include <Library/DebugLib.h>
+
+#include "XenbusDxe.h"
+
+
+///
+/// Driver Binding Protocol instance
+///
+EFI_DRIVER_BINDING_PROTOCOL gXenbusDxeDriverBinding = {
+  XenbusDxeDriverBindingSupported,
+  XenbusDxeDriverBindingStart,
+  XenbusDxeDriverBindingStop,
+  XENBUS_DXE_VERSION,
+  NULL,
+  NULL
+};
+
+
+/**
+  Unloads an image.
+
+  @param  ImageHandle           Handle that identifies the image to be unloaded.
+
+  @retval EFI_SUCCESS           The image has been unloaded.
+  @retval EFI_INVALID_PARAMETER ImageHandle is not a valid image handle.
+
+**/
+EFI_STATUS
+EFIAPI
+XenbusDxeUnload (
+  IN EFI_HANDLE  ImageHandle
+  )
+{
+  EFI_STATUS  Status;
+
Quoted 8 lines

OvmfPkg/XenbusDxe/XenbusDxe.c line 55

Quoted 6 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +6 -0
+  EFI_HANDLE  *HandleBuffer;
+  UINTN       HandleCount;
+  UINTN       Index;
+
+
+  Status = EFI_SUCCESS;

Is that neccessary considering the next line you overwrite it?

No, it is not.

Quoted 17 lines
Quoted 17 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +17 -0
+
+  //
+  // Retrieve array of all handles in the handle database
+  //
+  Status = gBS->LocateHandleBuffer (
+                  AllHandles,
+                  NULL,
+                  NULL,
+                  &HandleCount,
+                  &HandleBuffer
+                  );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
+  // Disconnect the current driver from handles in the handle database
Quoted 8 lines

OvmfPkg/XenbusDxe/XenbusDxe.c line 76

Quoted 4 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +4 -0
+  //
+  for (Index = 0; Index < HandleCount; Index++) {
+    Status = gBS->DisconnectController (HandleBuffer[Index], gImageHandle, NULL);
+  }

Should you check the Status?
I guess it doesn't matter at all. In which case why don't you just (void)gBS->DisconnectController ..

Will do.

Quoted 72 lines
Quoted 41 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +41 -0
+
+  //
+  // Free the array of handles
+  //
+  FreePool (HandleBuffer);
+
+
+  //
+  // Uninstall protocols installed in the driver entry point
+  //
+  Status = gBS->UninstallMultipleProtocolInterfaces (
+                  ImageHandle,
+                  &gEfiDriverBindingProtocolGuid, &gXenbusDxeDriverBinding,
+                  &gEfiComponentNameProtocolGuid,  &gXenbusDxeComponentName,
+                  &gEfiComponentName2ProtocolGuid, &gXenbusDxeComponentName2,
+                  NULL
+                  );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+
+  //
+  // Do any additional cleanup that is required for this driver
+  //
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This is the declaration of an EFI image entry point. This entry point is
+  the same for UEFI Applications, UEFI OS Loaders, and UEFI Drivers including
+  both device drivers and bus drivers.
+
+  @param  ImageHandle           The firmware allocated handle for the UEFI image.
+  @param  SystemTable           A pointer to the EFI System Table.
+
+  @retval EFI_SUCCESS           The operation completed successfully.
+  @retval Others                An unexpected error occurred.
+**/
+EFI_STATUS

OvmfPkg/XenbusDxe/XenbusDxe.c line 127

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +10 -0
+EFIAPI
+XenbusDxeDriverEntryPoint (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+
+  Status = EFI_SUCCESS;

Not needed.

Quoted 18 lines
OvmfPkg/XenbusDxe/XenbusDxe.c new file +18 -0
+
+
+  //
+  // Install UEFI Driver Model protocol(s).
+  //
+  Status = EfiLibInstallDriverBindingComponentName2 (
+             ImageHandle,
+             SystemTable,
+             &gXenbusDxeDriverBinding,
+             ImageHandle,
+             &gXenbusDxeComponentName,
+             &gXenbusDxeComponentName2
+             );
+  ASSERT_EFI_ERROR (Status);
+
+
+  return Status;
+}
Signature · 1 line
Anthony PERARD
#24 lore raw

Re: [PATCH RFC 03/18] OvmfPkg/XenbusDxe: Add device state struct and create an ExitBoot services event.

In reply to Konrad Rzeszutek Wilk
Quoted 95 lines · Konrad Rzeszutek Wilk
Quoted 94 lines · Anthony PERARD

The ExitBoot event is used to disconnect from the device before the next operating system start using them.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 39 ++++++++++++++++++++++++++++++++++++---
 OvmfPkg/XenbusDxe/XenbusDxe.h | 10 ++++++++++
 2 files changed, 46 insertions(+), 3 deletions(-)
OvmfPkg/XenbusDxe/XenbusDxe.c +36 -3
index 14113ad..2c3d9b8 100644
@@ -16,7 +16,6 @@
 
 #include "XenbusDxe.h"
 
-
 ///
 /// Driver Binding Protocol instance
 ///
@@ -30,6 +29,8 @@ EFI_DRIVER_BINDING_PROTOCOL gXenbusDxeDriverBinding = {
 };
 
 
+XENBUS_DEVICE *mMyDevice;
+
 /**
   Unloads an image.
 
@@ -229,6 +230,19 @@ XenbusDxeDriverBindingSupported (
   return Status;
 }
 
+VOID
+EFIAPI
+NotifyExitBoot (
+  IN EFI_EVENT Event,
+  IN VOID *Context
+  )
+{
+  XENBUS_DEVICE *Dev = Context;
+
+  gBS->DisconnectController(Dev->ControllerHandle,
+                            Dev->This->DriverBindingHandle, NULL);
+}
+
 /**
   Starts a device controller or a bus controller.
 
@@ -272,7 +286,22 @@ XenbusDxeDriverBindingStart (
   IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  EFI_STATUS Status;
+  XENBUS_DEVICE *Dev;
+
+  Dev = AllocateZeroPool (sizeof (*Dev));
+  Dev->Signature = XENBUS_DEVICE_SIGNATURE;
+  Dev->This = This;
+  Dev->ControllerHandle = ControllerHandle;
+
+  Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
+                             NotifyExitBoot,
+                             (VOID*) Dev,
+                             &Dev->ExitBootEvent);
+  ASSERT_EFI_ERROR (Status);
+
+  mMyDevice = Dev;
+  return EFI_SUCCESS;
 }
 
 /**
@@ -310,5 +339,9 @@ XenbusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
-  return EFI_UNSUPPORTED;
+  XENBUS_DEVICE *Dev = mMyDevice;
+
+  gBS->CloseEvent (Dev->ExitBootEvent);
+
+  return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +0 -0
index 6f22732..c1ca87a 100644
@@ -75,4 +75,14 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenbusDxeComponentName;
 #define PCI_DEVICE_ID_XEN_PLATFORM       0x0001
 
 
Quoted 6 lines

OvmfPkg/XenbusDxe/XenbusDxe.h extern EFI_COMPONENT_NAME_PROTOCOL gXenbusDxeComponentName; · line 80

Quoted 3 lines
OvmfPkg/XenbusDxe/XenbusDxe.h +3 -0
+typedef struct _XENBUS_DEVICE XENBUS_DEVICE;
+
+#define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')

I get the 'XB', but 'bd' ? Should it be 'XenB' ? Or perhaps 'XBus' ?

I don't remember about 'bd', maybus "bus driver". I think I'll go with 'XBus'.

Quoted 16 lines
Quoted 16 lines
OvmfPkg/XenbusDxe/XenbusDxe.h +7 -0
+struct _XENBUS_DEVICE {
+  UINT32                        Signature;
+  EFI_DRIVER_BINDING_PROTOCOL   *This;
+  EFI_HANDLE                    ControllerHandle;
+  EFI_EVENT                     ExitBootEvent;
+};
+
 #endif
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 05/18] OvmfPkg/XenbusDxe: Open PciIo protocol.

In reply to Konrad Rzeszutek Wilk
Quoted 8 lines · Konrad Rzeszutek Wilk
Quoted 2 lines · Anthony PERARD

Contributed-under: TianoCore Contribution Agreement 1.0

Could you describe a bit why you need to use it?

I think I know why - that is you need to poke at its IO ports but it would be good to mention that in here.

I thinks it's need to be open so that, OVMF will not be able to start the drivers a second time (OpenProtocol would return ALREADY_STARTED or something equivalent).

So far I did not do anything with the IO ports, I probably should. But I don't think it will be needed to explain that before it's actually done.

Quoted 63 lines
Quoted 63 lines
---
 OvmfPkg/XenbusDxe/XenbusDxe.c | 16 ++++++++++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h |  1 +
 2 files changed, 17 insertions(+)
OvmfPkg/XenbusDxe/XenbusDxe.c +16 -0
index 63ea31b..ba5e8f4 100644
@@ -290,11 +290,25 @@ XenbusDxeDriverBindingStart (
 {
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
+  EFI_PCI_IO_PROTOCOL *PciIo;
+
+  Status = gBS->OpenProtocol (
+                     ControllerHandle,
+                     &gEfiPciIoProtocolGuid,
+                     (VOID **)&PciIo,
+                     This->DriverBindingHandle,
+                     ControllerHandle,
+                     EFI_OPEN_PROTOCOL_BY_DRIVER
+                     );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
 
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
+  Dev->PciIo = PciIo;
 
   Status = XenHyperpageInit (Dev);
   ASSERT_EFI_ERROR (Status);
@@ -351,5 +365,7 @@ XenbusDxeDriverBindingStop (
 
   gBS->CloseEvent (Dev->ExitBootEvent);
 
+  gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
 }
OvmfPkg/XenbusDxe/XenbusDxe.h +1 -0
index 6140f94..d57e3c8 100644
@@ -84,6 +84,7 @@ struct _XENBUS_DEVICE {
   UINT32                        Signature;
   EFI_DRIVER_BINDING_PROTOCOL   *This;
   EFI_HANDLE                    ControllerHandle;
+  EFI_PCI_IO_PROTOCOL           *PciIo;
   EFI_EVENT                     ExitBootEvent;
 
   VOID                          *Hyperpage;
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 06/18] OvmfPkg: Introduce Xenbus Protocol.

In reply to Konrad Rzeszutek Wilk
Quoted 33 lines · Konrad Rzeszutek Wilk
Quoted 32 lines · Anthony PERARD

This protocol will be used for communication between a PV driver (like a PV block driver) and the Xenbus/Xenstore.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/Include/Protocol/Xenbus.h | 62 +++++++++++++++++++++++++++++++++++++++
 OvmfPkg/OvmfPkg.dec               |  2 ++
 OvmfPkg/XenbusDxe/ComponentName.c | 12 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  3 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |  1 +
 5 files changed, 80 insertions(+)
 create mode 100644 OvmfPkg/Include/Protocol/Xenbus.h
OvmfPkg/Include/Protocol/Xenbus.h new file +12 -0
new file mode 100644
index 0000000..191cee1
@@ -0,0 +1,62 @@
+
+/** @file
+  TODO: Brief Description of Protocol Xenbus
+
+  TODO: Detailed Description of Protocol Xenbus
+
+  TODO: Copyright for Protocol Xenbus
+
+  TODO: License for Protocol Xenbus
+
+**/
+
Quoted 8 lines

OvmfPkg/Include/Protocol/Xenbus.h line 17

Quoted 5 lines
OvmfPkg/Include/Protocol/Xenbus.h new file +5 -0
+#ifndef __PROTOCOL_XENBUS_H__
+#define __PROTOCOL_XENBUS_H__
+
+#define XENBUS_PROTOCOL_GUID \
+  {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}

For those who are not familiar with these GUIDs and live in the Linux world - how are they constructed? Is there a chance for collision ?

Well, I actually don't know. To get the GUID, I've used UefiDriverWizard which gave me this GUID and a bunch of files to actually code in. That's way there is so many comment written TODO or that may no make sense.

Quoted 49 lines
Quoted 49 lines
OvmfPkg/Include/Protocol/Xenbus.h new file +45 -0
+
+///
+/// Forward declaration
+///
+typedef struct _XENBUS_PROTOCOL XENBUS_PROTOCOL;
+
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+///
+/// Function prototypes
+///
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_ACCESS)(
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame,
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *refp
+  );
+
+typedef
+EFI_STATUS
+(EFIAPI *XENBUS_GRANT_END_ACCESS)(
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+
+///
+/// Protocol structure
+///
+struct _XENBUS_PROTOCOL {
+  XENBUS_GRANT_ACCESS           GrantAccess;
+  XENBUS_GRANT_END_ACCESS       GrantEndAccess;
+  //
+  // Place protocol data fields here
+  //
+};
+
+extern EFI_GUID gXenbusProtocolGuid;
+
+#endif
OvmfPkg/OvmfPkg.dec +0 -0
index f829247..095d40a 100644
Quoted 8 lines

OvmfPkg/OvmfPkg.dec line 51

Quoted 6 lines
OvmfPkg/OvmfPkg.dec +2 -0
@@ -47,6 +47,8 @@
 [Protocols]
   gVirtioDeviceProtocolGuid       = {0xfa920010, 0x6785, 0x4941, {0xb6, 0xec, 0x49, 0x8c, 0x57, 0x9f, 0x16, 0x0a}}
   gBlockMmioProtocolGuid          = {0x6b558ce3, 0x69e5, 0x4c67, {0xa6, 0x34, 0xf7, 0xfe, 0x72, 0xad, 0xbe, 0x84}}
+  ## Include/Protocol/Xenbus.h
+  gXenbusProtocolGuid = {0x3d3ca290, 0xb9a5, 0x11e3, {0xb7, 0x5d, 0xb8, 0xac, 0x6f, 0x7d, 0x65, 0xe6}}

Formatting? Looks like the others use tabs?

Probably, yes, I'll change that.

Quoted 60 lines
Quoted 60 lines
OvmfPkg/OvmfPkg.dec +0 -0
 [PcdsFixedAtBuild]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|0x0|UINT32|0
OvmfPkg/XenbusDxe/ComponentName.c +12 -0
index 2cf11b5..fd46cc8 100644
@@ -140,6 +140,18 @@ XenbusDxeComponentNameGetControllerName (
   }
 
   //
+  // Make sure this driver is currently managing ControllerHandle
+  //
+  Status = EfiTestManagedDevice (
+             ControllerHandle,
+             gXenbusDxeDriverBinding.DriverBindingHandle,
+             &gXenbusProtocolGuid
+             );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
   // Lookup name of controller specified by ControllerHandle
   //
   Status = EFI_UNSUPPORTED;
OvmfPkg/XenbusDxe/XenbusDxe.h +3 -0
index d57e3c8..975fb6b 100644
@@ -42,6 +42,9 @@
 //
 // Produced Protocols
 //
+// Xen interface version used:
+#define  __XEN_INTERFACE_VERSION__ 0x00040400
+#include <Protocol/Xenbus.h>
 
 
 //
OvmfPkg/XenbusDxe/XenbusDxe.inf +1 -0
index 8b69f93..1a6b131 100644
@@ -55,6 +55,7 @@
   gEfiPciIoProtocolGuid
   gEfiComponentName2ProtocolGuid
   gEfiComponentNameProtocolGuid
+  gXenbusProtocolGuid
 
 
 [Guids]
Signature · 7 lines
Anthony PERARD


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

Re: [PATCH RFC 08/18] OvmfPkg/XenbusDxe: Add Grant Table functions.

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

There are used to grant access of pages to other Xen domains.

This code originaly comes from the Xen Project, and more precisely from MiniOS.

Should you mention something about its license?

Just in case, maybe. But both mini-os and ovmf are mostly BSD, so it's probably not a big issue either way. I'll make sure to better describe the original licenses in the commit messages.

Quoted 62 lines
Quoted 62 lines

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenbusDxe/GrantTable.c  | 204 ++++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/GrantTable.h  |  34 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c   |  15 +++
 OvmfPkg/XenbusDxe/XenbusDxe.inf |   2 +
 4 files changed, 255 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.c
 create mode 100644 OvmfPkg/XenbusDxe/GrantTable.h
OvmfPkg/XenbusDxe/GrantTable.c new file +42 -0
new file mode 100644
index 0000000..97bd15a
@@ -0,0 +1,204 @@
+/*
+ ****************************************************************************
+ * (C) 2006 - Cambridge University
+ ****************************************************************************
+ *
+ *        File: GrantTable.c
+ *      Author: Steven Smith ([email protected])
+ *     Changes: Grzegorz Milos ([email protected])
+ *
+ *        Date: July 2006
+ *
+ * Environment: Xen Minimal OS
+ * Description: Simple grant tables implementation. About as stupid as it's
+ *  possible to be and still work.
+ *
+ ****************************************************************************
+ */
+#include "XenbusDxe.h"
+
+#include <IndustryStandard/Xen/memory.h>
+
+#include "XenHypercall.h"
+
+#include "GrantTable.h"
+#include "InterlockedCompareExchange16.h"
+
+#define NR_RESERVED_ENTRIES 8
+
+/* NR_GRANT_FRAMES must be less than or equal to that configured in Xen */
+#define NR_GRANT_FRAMES 4
+#define NR_GRANT_ENTRIES (NR_GRANT_FRAMES * EFI_PAGE_SIZE / sizeof(grant_entry_v1_t))
+
+STATIC grant_entry_v1_t *GrantTable = NULL;
+STATIC grant_ref_t GrantList[NR_GRANT_ENTRIES];
+#ifdef GNT_DEBUG
+STATIC BOOLEAN GrantInUseList[NR_GRANT_ENTRIES];
+#endif
+
+STATIC
+VOID
+XenGrantTablePutFreeEntry (
+  grant_ref_t Ref
Quoted 8 lines

OvmfPkg/XenbusDxe/GrantTable.c line 47

Quoted 5 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +5 -0
+  )
+{
+  //local_irq_save(flags);
+  /* MemoryFence (); */
+  // lock ?

You just need some form of locking. If EFI has some simple Mutex() you can use that.

No, no mutex available, but there are some form of lock. It increase the priority of the current task, so nothing else can run.

Quoted 125 lines
Quoted 125 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +125 -0
+#ifdef GNT_DEBUG
+  ASSERT (GrantInUseList[Ref]);
+  GrantInUseList[Ref] = FALSE;
+#endif
+  GrantList[Ref] = GrantList[0];
+  GrantList[0] = Ref;
+  //local_irq_restore(flags);
+  /* MemoryFence (); */
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGetFreeEntry (
+  VOID
+  )
+{
+  UINTN Ref;
+  /* local_irq_save(flags); */
+  // lock ??
+  Ref = GrantList[0];
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+  GrantList[0] = GrantList[Ref];
+#ifdef GNT_DEBUG
+  ASSERT (!GrantInUseList[Ref]);
+  GrantInUseList[Ref] = TRUE;
+#endif
+  /* local_irq_restore(flags); */
+  return Ref;
+}
+
+STATIC
+grant_ref_t
+XenGrantTableGrantAccess (
+  IN domid_t  DomainId,
+  IN UINTN    Frame,
+  IN BOOLEAN  ReadOnly
+  )
+{
+  grant_ref_t Ref;
+  UINT32 Flags;
+
+  ASSERT (GrantTable != NULL);
+  Ref = XenGrantTableGetFreeEntry ();
+  GrantTable[Ref].frame = Frame;
+  GrantTable[Ref].domid = DomainId;
+  MemoryFence ();
+  Flags = GTF_permit_access;
+  if (ReadOnly) {
+    Flags |= GTF_readonly;
+  }
+  GrantTable[Ref].flags = Flags;
+
+  return Ref;
+}
+
+STATIC
+EFI_STATUS
+XenGrantTableEndAccess (
+  grant_ref_t Ref
+  )
+{
+  UINT16 Flags, OldFlags;
+
+  ASSERT (GrantTable != NULL);
+  ASSERT (Ref >= NR_RESERVED_ENTRIES && Ref < NR_GRANT_ENTRIES);
+
+  OldFlags = GrantTable[Ref].flags;
+  do {
+    if ((Flags = OldFlags) & (GTF_reading | GTF_writing)) {
+      DEBUG ((EFI_D_WARN, "WARNING: g.e. still in use! (%x)\n", Flags));
+      return EFI_NOT_READY;
+    }
+    OldFlags = InterlockedCompareExchange16 (&GrantTable[Ref].flags, Flags, 0);
+  } while (OldFlags != Flags);
+
+  XenGrantTablePutFreeEntry (Ref);
+  return EFI_SUCCESS;
+}
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  )
+{
+  xen_add_to_physmap_t Args;
+  INTN Index;
+  INTN ReturnCode;
+
+#ifdef GNT_DEBUG
+  SetMem(GrantInUseList, sizeof (GrantInUseList), 1);
+#endif
+  for (Index = NR_RESERVED_ENTRIES; Index < NR_GRANT_ENTRIES; Index++) {
+    XenGrantTablePutFreeEntry (Index);
+  }
+
+  GrantTable = (VOID*)(UINTN) MmioAddr;
+  for (Index = 0; Index < NR_GRANT_FRAMES; Index++) {
+    Args.domid = DOMID_SELF;
+    Args.idx = Index;
+    Args.space = XENMAPSPACE_grant_table;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_add_to_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, add_to_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+}
+
+VOID
+XenGrantTableDeinit (
+  XENBUS_DEVICE *Dev
+  )
+{
+  INTN ReturnCode, Index;
+  xen_remove_from_physmap_t Args;
+
+  if (GrantTable == NULL) {
+    return;
+  }
+
+  for (Index = NR_GRANT_FRAMES - 1; Index >= 0; Index--) {
+    Args.domid = DOMID_SELF;
+    Args.gpfn = (((xen_pfn_t) GrantTable) >> EFI_PAGE_SHIFT) + Index;
+    DEBUG ((EFI_D_INFO, "%a %d, removing %X\n", __func__, __LINE__, Args.gpfn));
Quoted 8 lines

OvmfPkg/XenbusDxe/GrantTable.c line 178

Quoted 6 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +6 -0
+    ReturnCode = XenHypercallMemoryOp (Dev, XENMEM_remove_from_physmap, &Args);
+    if (ReturnCode != 0) {
+      DEBUG ((EFI_D_ERROR, "Xen GrantTable, remove_from_physmap hypercall error: %d\n", ReturnCode));
+    }
+  }
+  // XXX remove it from the physmap?

Didn't you just do that?

Yes, a comment to remove...

Quoted 91 lines
Quoted 91 lines
OvmfPkg/XenbusDxe/GrantTable.c new file +26 -0
+  GrantTable = NULL;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  )
+{
+  *RefPtr = XenGrantTableGrantAccess (DomainId, Frame, ReadOnly);
+  return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  )
+{
+  return XenGrantTableEndAccess (Ref);
+}
OvmfPkg/XenbusDxe/GrantTable.h new file +34 -0
new file mode 100644
index 0000000..05ab4be
@@ -0,0 +1,34 @@
+#ifndef __GNTTAB_H__
+#define __GNTTAB_H__
+
+#include <IndustryStandard/Xen/grant_table.h>
+
+VOID
+XenGrantTableInit (
+  IN XENBUS_DEVICE  *Dev,
+  IN UINT64         MmioAddr
+  );
+
+VOID
+XenGrantTableDeinit (
+  IN XENBUS_DEVICE  *Dev
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantAccess (
+  IN  XENBUS_PROTOCOL *This,
+  IN  domid_t         DomainId,
+  IN  UINTN           Frame, // MFN
+  IN  BOOLEAN         ReadOnly,
+  OUT grant_ref_t     *RefPtr
+  );
+
+EFI_STATUS
+EFIAPI
+XenbusGrantEndAccess (
+  IN XENBUS_PROTOCOL  *This,
+  IN grant_ref_t      Ref
+  );
+
+#endif /* !__GNTTAB_H__ */
OvmfPkg/XenbusDxe/XenbusDxe.c +3 -0
index ba5e8f4..b19055d 100644
@@ -17,6 +17,7 @@
 #include "XenbusDxe.h"
 
 #include "XenHypercall.h"
+#include "GrantTable.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -291,6 +292,8 @@ XenbusDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_DEVICE *Dev;
   EFI_PCI_IO_PROTOCOL *PciIo;
+  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
+  UINT64 MmioAddr;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -310,12 +313,23 @@ XenbusDxeDriverBindingStart (
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
 
Quoted 4 lines

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStart ( · line 316

Quoted 1 line
OvmfPkg/XenbusDxe/XenbusDxe.c +1 -0
+  Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);

I think we have a spec somewhere for this device. Do you think it might make sense to reference it here?

Probably, yes. But I'm not sure yet if it's the right things to do here. I'm just use the BAR address to map the grant table in.

Quoted 4 lines

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStart ( · line 318

Quoted 2 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +2 -0
+  ASSERT_EFI_ERROR (Status);
+  ASSERT (BarDesc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM);

I sooo hope the spec mandates that it is always this type of BAR.

Signature · 1 line
Anthony PERARD
#39 lore raw

Re: [PATCH RFC 14/18] OvmfPkg/XenbusDxe: Indroduce XenBus support itself.

In reply to Konrad Rzeszutek Wilk
Quoted 163 lines · Konrad Rzeszutek Wilk
Quoted 162 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

---
 OvmfPkg/Include/Protocol/Xenbus.h |   9 +
 OvmfPkg/XenbusDxe/XenBus.c        | 360 ++++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenbusDxe/XenBus.h        |  76 ++++++++
 OvmfPkg/XenbusDxe/XenbusDxe.c     |  61 +++++++
 OvmfPkg/XenbusDxe/XenbusDxe.h     |  18 ++
 OvmfPkg/XenbusDxe/XenbusDxe.inf   |   3 +
 6 files changed, 527 insertions(+)
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.c
 create mode 100644 OvmfPkg/XenbusDxe/XenBus.h
OvmfPkg/Include/Protocol/Xenbus.h +9 -0
index ef4d0c2..25408c1 100644
@@ -113,6 +113,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,
@@ -171,6 +179,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 +110 -0
new file mode 100644
index 0000000..b0cf1ba
@@ -0,0 +1,360 @@
+/******************************************************************************
+ * 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
+ *
+ * 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 "XenbusDxe.h"
+
+#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 \a node is known to
+ * the system.
+ *
+ * \param Dev   The XenBus bus instance to search for device children.
+ * \param node  The XenStore node path for the device to find.
+ *
+ * \return  The device_t of the found device if any, or NULL.
+ *
+ * \note device_t is a pointer type, so it can be compared against
+ *       NULL for validity.
+ */
+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;
+  XENSTORE_STATUS Status;
+
+  Status = XenstoreRead (XST_NIL, Path, "state", NULL, (VOID **)&Ptr);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    State = XenbusStateClosed;
+  } else {
+    State = AsciiStrDecimalToUintn (Ptr);
Quoted 8 lines

OvmfPkg/XenbusDxe/XenBus.c line 112

Quoted 2 lines
OvmfPkg/XenbusDxe/XenBus.c new file +2 -0
+    FreePool (Ptr);
+  }

I think the FreePool(Ptr) should be here. You want to it irregardless of what the error might be (thought the implemenation in XenstoreRead et.all is pretty clear that we won't initialize *Ptr to anything if !Status. But just in case this changes in the future..

OK, will do. But I might have to check for NULL.

Quoted 70 lines
Quoted 70 lines
OvmfPkg/XenbusDxe/XenBus.c new file +70 -0
+
+  return State;
+}
+
+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);
+
+  Status = EFI_NOT_STARTED; //ENXIO; // Device not configured
+
+  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")) {
Quoted 8 lines

OvmfPkg/XenbusDxe/XenBus.c line 188

Quoted 6 lines
OvmfPkg/XenbusDxe/XenBus.c new file +6 -0
+      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 provide a comment explaining why you do that please?

Will do.

I think bus drivers need to do that. It is used to specify wich device to boot on. Without it done here, it would be hard to differentiate two PV block drivers from each other.

Quoted 10 lines

OvmfPkg/XenbusDxe/XenBus.c line 195

Quoted 7 lines
OvmfPkg/XenbusDxe/XenBus.c new file +7 -0
+
+    Status = gBS->InstallMultipleProtocolInterfaces (
+               &Private->Handle,
+               &gEfiDevicePathProtocolGuid, Private->DevicePath,
+               &gXenbusProtocolGuid, &Private->XenbusIo,
+               NULL);
+    if (EFI_ERROR (Status)) {

Shouldn't you free 'Private' and 'BackendPath' ? And also de-link yourself from 'Dev->ChildList' ?

Yes, I need to fix the error handling.

Quoted 127 lines
Quoted 127 lines
OvmfPkg/XenbusDxe/XenBus.c new file +127 -0
+      return Status;
+    }
+
+    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));
+    }
+  } else {
+    DEBUG ((EFI_D_INFO, "Xenbus: does not exist: %a\n", DevicePath));
+  }
+
+out:
+  return Status;
+}
+
+/**
+ * \brief Enumerate all devices of the given type on this bus.
+ *
+ * \param Dev   NewBus device_t for this XenBus front bus instance.
+ * \param type  String indicating the device sub-tree (e.g. "vfb", "vif")
+ *              to enumerate.
+ *
+ * Devices that are found are entered into the NewBus hierarchy via
+ * xenbusb_add_device().  xenbusb_add_device() ignores duplicate detects
+ * and ignores duplicate devices, so it can be called unconditionally
+ * for any device found in the XenStore.
+ */
+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);
+}
+
+
+/**
+ * \brief Enumerate the devices on a XenBus bus and register them with
+ *        the NewBus device tree.
+ *
+ * xenbusb_enumerate_bus() will create entries (in state DS_NOTPRESENT)
+ * for nodes that appear in the XenStore, but will not invoke probe/attach
+ * operations on drivers.  Probe/Attach processing must be separately
+ * performed via an invocation of xenbusb_probe_children().  This is usually
+ * done via the xbs_probe_children task.
+ *
+ * \param Dev  XenBus Bus device softc of the owner of the bus to enumerate.
+ *
+ * \return  On success, 0. Otherwise an errno value indicating the
+ *          type of failure.
+ */
+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 Error;
+  }
+  CurrentState = AsciiStrDecimalToUintn (Temp);
+  FreePool (Temp);
+  if (CurrentState == NewState) {
+    DEBUG ((EFI_D_INFO, "%a %d, same state\n", __func__, __LINE__));
+    goto Error;
+  }
Quoted 8 lines

OvmfPkg/XenbusDxe/XenBus.c line 328

Quoted 6 lines
OvmfPkg/XenbusDxe/XenBus.c new file +6 -0
+
+  do {
+    Status = XenstoreSPrint (Transaction, This->Node, "state", "%d", NewState);
+  } while (Status == XENSTORE_STATUS_EAGAIN);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "Xenbus: fail to writing new state\n"));

failed to write new state

OK.

Quoted 9 lines

OvmfPkg/XenbusDxe/XenBus.c line 333

Quoted 5 lines
OvmfPkg/XenbusDxe/XenBus.c new file +5 -0
+    goto Error;
+  }
+  DEBUG ((EFI_D_INFO, "Xenbus: Set state to %d, done\n", NewState));
+
+Error:

s/Error/Out/

as it is OK for to set to the same state twice.

OK.

Quoted 174 lines
Quoted 174 lines
OvmfPkg/XenbusDxe/XenBus.c new file +26 -0
+  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 +76 -0
new file mode 100644
index 0000000..63d0815
@@ -0,0 +1,76 @@
+/*-
+ * Core definitions and data structures shareable across OS platforms.
+ *
+ * Copyright (c) 2010 Spectra Logic Corporation
+ * Copyright (C) 2008 Doug Rabson
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * $FreeBSD: release/10.0.0/sys/xen/xenbus/xenbusb.h 222975 2011-06-11 04:59:01Z gibbs $
+ */
+#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;
+  UINT16              DeviceId;
+};
+
+/**
+ * The VM relative path to the XenStore subtree this
+ * bus attachment manages.
+ *
+ * OR
+ *
+ * The XenStore path to the XenStore subtree for this XenBus bus.
+ */
+#define XENBUS_XENSTORE_NODE "device"
+
+
+/**
+ * \brief Perform common XenBus bus attach processing.
+ *
+ * \param Dev            The NewBus device representing this XenBus bus.
+ *
+ * \return  On success, 0. Otherwise an errno value indicating the
+ *          type of failure.
+ *
+ * Intiailizes the softc for this bus, installs an interrupt driven
+ * configuration hook to block boot processing until XenBus devices fully
+ * configure, performs an initial probe/attach of the bus, and registers
+ * a XenStore watch so we are notified when the bus topology changes.
+ */
+XENSTORE_STATUS
+XenbusEnumerateBus (
+  XENBUS_DEVICE *Dev
+  );
+
+#endif /* _XEN_XENBUS_XENBUSB_H */
OvmfPkg/XenbusDxe/XenbusDxe.c +23 -0
index 2c85d5e..56225c4 100644
@@ -19,6 +19,7 @@
 #include "XenHypercall.h"
 #include "GrantTable.h"
 #include "Xenstore.h"
+#include "XenBus.h"
 
 ///
 /// Driver Binding Protocol instance
@@ -295,6 +296,7 @@ XenbusDxeDriverBindingStart (
   EFI_PCI_IO_PROTOCOL *PciIo;
   EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc;
   UINT64 MmioAddr;
+  EFI_DEVICE_PATH_PROTOCOL *DevicePath;
 
   Status = gBS->OpenProtocol (
                      ControllerHandle,
@@ -308,11 +310,26 @@ XenbusDxeDriverBindingStart (
     return Status;
   }
 
+  Status = gBS->OpenProtocol (
+                  ControllerHandle,
+                  &gEfiDevicePathProtocolGuid,
+                  (VOID **) &DevicePath,
+                  This->DriverBindingHandle,
+                  ControllerHandle,
+                  EFI_OPEN_PROTOCOL_BY_DRIVER
+                  );
+
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
   Dev = AllocateZeroPool (sizeof (*Dev));
   Dev->Signature = XENBUS_DEVICE_SIGNATURE;
   Dev->This = This;
   Dev->ControllerHandle = ControllerHandle;
   Dev->PciIo = PciIo;
+  Dev->DevicePath = DevicePath;
+  InitializeListHead (&Dev->ChildList);
 
   Status = PciIo->GetBarAttributes (PciIo, PCI_BAR_IDX1, NULL, (VOID**) &BarDesc);
   ASSERT_EFI_ERROR (Status);
@@ -334,6 +351,8 @@ XenbusDxeDriverBindingStart (
   Status = XenstoreInit (Dev);
   ASSERT_EFI_ERROR (Status);
 
+  XenbusEnumerateBus (Dev);
+
   Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
                              NotifyExitBoot,
                              (VOID*) Dev,
@@ -379,12 +398,54 @@ XenbusDxeDriverBindingStop (
   IN EFI_HANDLE                   *ChildHandleBuffer OPTIONAL
   )
 {
+  UINTN Index;
+  XENBUS_PROTOCOL *XenbusIo;
+  XENBUS_PRIVATE_DATA *ChildData;
+  EFI_STATUS Status;
   XENBUS_DEVICE *Dev = mMyDevice;
 
Quoted 12 lines

OvmfPkg/XenbusDxe/XenbusDxe.c XenbusDxeDriverBindingStop ( · line 416

Quoted 10 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +10 -0
+  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 childre proto: %r\n", Status));

get children protocol failed: %r

Will fix.

Quoted 98 lines
Quoted 98 lines
OvmfPkg/XenbusDxe/XenbusDxe.c +28 -0
+      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);
+  }
+
   gBS->CloseEvent (Dev->ExitBootEvent);
+  // XXX xenbus cleanup
   // XXX xenstore cleanup
   XenGrantTableDeinit (Dev);
 
+  gBS->CloseProtocol(ControllerHandle, &gEfiDevicePathProtocolGuid,
+         This->DriverBindingHandle, ControllerHandle);
   gBS->CloseProtocol(ControllerHandle, &gEfiPciIoProtocolGuid,
          This->DriverBindingHandle, ControllerHandle);
   return EFI_SUCCESS;
OvmfPkg/XenbusDxe/XenbusDxe.h +18 -0
index 4d9db72..3ff08dd 100644
@@ -80,6 +80,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;
 
 #define XENBUS_DEVICE_SIGNATURE SIGNATURE_32 ('X','B','b','d')
@@ -89,11 +90,28 @@ 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;
 };
 
+#define XENBUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X', 'B', 'u', 's')
+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 6c8260f..708fae6 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
#42 lore raw

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

In reply to Konrad Rzeszutek Wilk
Quoted 93 lines · Konrad Rzeszutek Wilk
Quoted 79 lines · Anthony PERARD

This is the code that will do the actual communication between OVMF and a PV block backend, where the block device lives.

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

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockFront.c    | 583 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockFront.h    |  88 ++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |   8 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 4 files changed, 681 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockFront.h
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +55 -0
new file mode 100644
index 0000000..ff5641c
@@ -0,0 +1,583 @@
+/* Minimal block driver for Mini-OS.
+ * Copyright (c) 2007-2008 Samuel Thibault.
+ * Based on netfront.c.
+ */
+
+#include <Library/PrintLib.h>
+#include <Library/DebugLib.h>
+
+#include "BlockFront.h"
+
+#include <IndustryStandard/Xen/io/protocols.h>
+#include <IndustryStandard/Xen/io/xenbus.h>
+
+#include "inttypes.h"
+
+STATIC
+XENSTORE_STATUS
+XenbusReadInteger (
+  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);
+  }
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    return Status;
+  }
+  // XXX Will assert if p overflow UINT64 ...
+  *ValuePtr = AsciiStrDecimalToUint64 (p);
+  FreePool (p);
+  return Status;
+}
+
+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);
+  }

OvmfPkg/XenPvBlkDxe/BlockFront.c line 65

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  if (Dev->EventChannel != 0) {
+    XenbusIo->EventChannelClose (XenbusIo, Dev->EventChannel);
+  }
+  FreePool (Dev);
+}
+
+XENSTORE_STATUS
+XenPvBlkWaitForBackendState (
+  IN  XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN  XenbusState            WaitedState,

ExpectedState

Quoted 1 line

?

Yes, will change.

Quoted 12 lines
Quoted 12 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +12 -0
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenbusIo = Dev->XenbusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status;
+
+  while (TRUE) {
+    Status = XenbusReadInteger (XenbusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 83

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +6 -0
+    }
+    if (Value > XenbusStateReconfigured) {
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State >= WaitedState) {

Not State != WaitedState ?

I don't think so, the function is actually waiting for the State to be equal to WaitedState. At least, that how I wrote it. There might be a better algorithm.

Quoted 62 lines
Quoted 62 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +62 -0
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            WaitedState, State));
+    XenbusIo->WaitForWatch (XenbusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+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 = XenbusReadInteger (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,
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 151

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +6 -0
+                         &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));

.. and do you want to error out?

The original code (mini-os) is continuing in thes case, so I thought it was possible to do the initialisation without transaction. But maybe I'm wrong and this should be an error.

Quoted 67 lines
Quoted 54 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +54 -0
+  }
+
+  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"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->SetState (XenbusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->XsTransactionEnd (XenbusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
+  }
+
+  XenbusIo->RegisterWatchBackend (XenbusIo, "state", &Dev->StateWatchToken);
+
+  // Waiting backend
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS || State != XenbusStateConnected) {
+    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 = XenbusReadInteger (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;
+  }
+

OvmfPkg/XenPvBlkDxe/BlockFront.c line 215

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  Status = XenbusReadInteger (XenbusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenbusReadInteger (XenbusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;

Why not &Dev->MediaInfo.SectorSize in XenbusReadInteger?

Quoted 1 line

Is it because of types? If so, please add a comment stating that.

Yes, because of the type, uint64 vs uint32.

Maybe I could rename the XenbusReadInteger to XenbusReadUint64, and it would be more obvious that the function require a specific type.

Quoted 32 lines
Quoted 19 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +19 -0
+
+  // Default value
+  Value = 0;
+  Status = XenbusReadInteger (XenbusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenbusReadInteger (XenbusIo, "feature-flush-cache", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureFlushCache = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureFlushCache = FALSE;
+  }
+

OvmfPkg/XenPvBlkDxe/BlockFront.c line 244

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %d 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");

Quoted 1 line

?

I don't know, but I can do that.

Quoted 128 lines
Quoted 70 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +70 -0
+  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 = XenbusReadInteger (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;
+    }

OvmfPkg/XenPvBlkDxe/BlockFront.c line 324

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+    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");

"protocol"

Quoted 46 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +46 -0
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC
+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)) {
+        break;
+      }
+      /* Really no slot, go to sleep. */
+      // XXX wait for an event on Dev->EventChannel
+      DEBUG ((EFI_D_INFO, "%a %d, waiting\n", __func__, __LINE__));
+    }
+  }
+}
+
+/* Issue an aio */
+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)));
+
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 375

Quoted 5 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +5 -0
+  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;
+
+  // XXX is this comment still true ?

I think it is outdated, as Linux would do max DMA up to the segment size that is advertised. Ditto for the SCSI stack.

OK, thanks.

Quoted 5 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 378

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +3 -0
+  /* qemu's IDE max multsect is 16 (8KB) and SCSI max DMA was set to 32KB,
+   * so max 44KB can't happen */
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);

But this check is OK as we can't truly fit more on the ring.

OK.

Quoted 6 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 380

Quoted 2 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +2 -0
+
+  XenPvBlockWaitSlot (Dev);

What happens if there are multiple threads calling this function? Don't we need a mutex to only allow one thread to grab an RingIndex?

So, OVMF does not have threads but the are "events", called by a timer. This code does not support it, yet, so I don't need any form of locking, yet.

Quoted 15 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 391

Quoted 11 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +11 -0
+  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;
+
+  for (Index = 0; Index < NumSegments; Index++) {
+    Request->seg[Index].first_sect = 0;

Uh?

OvmfPkg/XenPvBlkDxe/BlockFront.c line 392

Quoted 1 line
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +1 -0
+    Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;
Quoted 8 lines

Uh? I thought you wanted to use the real sector values?

OvmfPkg/XenPvBlkDxe/BlockFront.c line 396

Quoted 4 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +4 -0
+  }
+  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;

What about in between 0 and NumSegments? You should also fill out those values with valid entries.

It's done by the previous for loop. Maybe this part is hard to understand without the interface explain.
include io/blkif.h says:
@first_sect: first sector in frame to transfer (inclusive). @last_sect: last sector in frame to transfer (inclusive).

but does not explain what a frame is, beyond this comment on:
grant_ref_t gref; /* reference to I/O buffer frame */
(all this from the struct blkif_request_segment)
Or maybe frame == page.

Anyway, the way the segments are initialized feel weirds now, but I don't think it's incorrect, otherwise, I would not be able to boot any guest.

Quoted 6 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 400

Quoted 4 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +4 -0
+  for (Index = 0; Index < NumSegments; Index++) {
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;
+    if (!IsWrite) {
+      /* Trigger CoW if needed */

Not sure I understand that reference?

Maybe a reference to the original commit will help to understand:
minios: Fix bug when blkfront reading into zero-mapped buffer by just poking the page. No need to use virtual_to_mfn() for the ring since that is a real page. 7b1257946080b63421a8dc59c7b3dfd67997c643 (xen.git)

But I still don't undertand this.

Quoted 43 lines
Quoted 28 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +28 -0
+      *(CHAR8 *)(Data + (Request->seg[Index].first_sect << 9)) = 0;
+      MemoryFence ();
+    }
+    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);
+  }
+}
+
+STATIC
+VOID
+XenPvBlockAsyncIoCallback (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     EFI_STATUS         Status
+  )
+{
+  IoData->Data = (VOID *) 1;
+  IoData->Callback = NULL;

OvmfPkg/XenPvBlkDxe/BlockFront.c line 438

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +10 -0
+}
+
+VOID
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  ASSERT (IoData->Callback == NULL);
+  // XXX Signal/Event instead ?

Maybe for later versions. I think this is OK for right now, thought it will mean we can only do one I/O .. and have then to wait until it is completed.

Quoted 1 line

That limititation should be mentioned in the commit description.

That right, right now, it's only one IO at a time. I think my comment is more to tell me that Callback is not really one, and it could be replace by something more Uefi, an event.

Quoted 20 lines
Quoted 20 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +20 -0
+  IoData->Callback = XenPvBlockAsyncIoCallback;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+  IoData->Data = NULL;
+
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+    if (IoData->Data) {
+      break;
+    }
+  }
+}
+
+STATIC
+VOID
+XenPvBlockPushOperation (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN UINT8                  Operation,
+  IN UINT64                 Id
+  )
+{
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 463

Quoted 5 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +5 -0
+  INT32 Index;
+  blkif_request_t *Request;
+  BOOLEAN Notify;
+
+  XenPvBlockWaitSlot (Dev);

How do we make sure that there aren't multiple threads calling this?

Not possible yet.

Quoted 107 lines
Quoted 107 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +107 -0
+  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);
+  }
+}
+
+VOID
+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;
+      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 %Ld, num bytes %Ld\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;
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockFront.c line 576

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +6 -0
+      /* Nota: callback frees IoData itself */
+      if (IoData && IoData->Callback) {
+        IoData->Callback (IoData, Status ? EFI_DEVICE_ERROR : EFI_SUCCESS);
+      }
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {
+        /* We reentered, we must not continue here */

Uh, how does that happen?

That an original comment, I don't think it's possible yet in ovmf.

Quoted 7 lines
Quoted 7 lines
OvmfPkg/XenPvBlkDxe/BlockFront.c new file +7 -0
+        break;
+      }
+    }
+
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);
+  } while (More != 0);
+}
Signature · 1 line
Anthony PERARD
#47 lore raw

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

In reply to Konrad Rzeszutek Wilk
Quoted 142 lines · Konrad Rzeszutek Wilk
Quoted 78 lines · Anthony PERARD

Install the BlockIo protocol.

Contributed-under: TianoCore Contribution Agreement 1.0

---
 OvmfPkg/XenPvBlkDxe/BlockIo.c       | 256 ++++++++++++++++++++++++++++++++++++
 OvmfPkg/XenPvBlkDxe/BlockIo.h       | 109 +++++++++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c   |  59 +++++++++
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.h   |   1 +
 OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf |   2 +
 5 files changed, 427 insertions(+)
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.c
 create mode 100644 OvmfPkg/XenPvBlkDxe/BlockIo.h
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +58 -0
new file mode 100644
index 0000000..4ac2411
@@ -0,0 +1,256 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Detailed Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Copyright for UEFI Driver XenPvBlkDxe
+
+  TODO: License for UEFI Driver XenPvBlkDxe
+
+**/
+
+#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
+  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
+  (EFI_BLOCK_RESET)XenPvBlkDxeBlockIoReset, // Reset
+  XenPvBlkDxeBlockIoReadBlocks,             // ReadBlocks
+  XenPvBlkDxeBlockIoWriteBlocks,            // WriteBlocks
+  XenPvBlkDxeBlockIoFlushBlocks             // FlushBlocks
+};
+
+
+
+
+STATIC
+EFI_STATUS
+XenPvBlkDxeBlockIoReadWriteBlocks (
+  IN     EFI_BLOCK_IO_PROTOCOL  *This,
+  IN     UINT32                 MediaId,
+  IN     EFI_LBA                Lba,
+  IN     UINTN                  BufferSize,

OvmfPkg/XenPvBlkDxe/BlockIo.c line 68

Quoted 10 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +10 -0
+  IN OUT VOID                   *Buffer,
+  IN     BOOLEAN                IsWrite
+  )
+{
+  XEN_BLOCK_FRONT_IO IoData;
+  EFI_BLOCK_IO_MEDIA *Media;
+  UINTN NextOffset;
+
+  if (Buffer == NULL) {
+    DEBUG ((EFI_D_ERROR, "%a %d, buffer null\n", __func__, __LINE__));

Heheh.

Quoted 50 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +50 -0
+    return EFI_INVALID_PARAMETER;
+  }
+  if (BufferSize == 0) {
+    return EFI_SUCCESS;
+  }
+
+  Media = This->Media;
+
+  if (BufferSize % Media->BlockSize != 0) {
+    DEBUG ((EFI_D_ERROR, "%a %d, bad buffer size\n", __func__, __LINE__));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  if (Lba > Media->LastBlock ||
+      (BufferSize / Media->BlockSize) - 1 > Media->LastBlock - Lba) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read too large\n", __func__, __LINE__));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (IsWrite && Media->ReadOnly) {
+    DEBUG ((EFI_D_ERROR, "%a %d, read only\n", __func__, __LINE__));
+    return EFI_WRITE_PROTECTED;
+  }
+
+  if ((Media->IoAlign > 1) && (UINTN)Buffer & (Media->IoAlign - 1)) {
+    // This happen often when using grub2
+    VOID *NewBuffer;
+    EFI_STATUS Status;
+
+    /* 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);
+    return Status;
+  }
+
+
+  // XXX Check MediaId
+
+  IoData.Dev = XEN_BLOCK_FRONT_FROM_BLOCK_IO (This);
+  IoData.Offset = Lba * Media->BlockSize;
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 124

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +6 -0
+  IoData.Callback = NULL;
+  IoData.Data = NULL;
+  IoData.Size = BufferSize;
+  IoData.Buffer = Buffer;
+
+  NextOffset = Lba * Media->BlockSize;

Or just = IoData.Offset ?

Yes.

Quoted 5 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 127

Quoted 3 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+  while (BufferSize > 0) {
+    // This should work if every Buffer is page aligned
+    // but block accept sector aligned, so FIXME

Isn't the work-around for GRUB2 above doing this?

No, GRUB2 is worth, it's not even sector aligned... I think my comment is about why a Size of EFI_PAGE_SIZE * BLKIF_MAX_SEGMENTS_PER_REQUEST did not work and that I should find a better value than page_size * 8.

Quoted 4 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 129

Quoted 2 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +2 -0
+    IoData.Size = MIN(EFI_PAGE_SIZE * 8,//BLKIF_MAX_SEGMENTS_PER_REQUEST,
+                           BufferSize);

Why 8 ?

I don't remember, but maybe the first value that works, or just a random value that I've seen somewhere else ... anyway, that need to be change.

Quoted 8 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 136

Quoted 7 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +7 -0
+    IoData.Buffer = Buffer;
+    IoData.Offset = NextOffset;
+    BufferSize -= IoData.Size;
+    Buffer = (VOID*) ((UINTN) Buffer + IoData.Size);
+    NextOffset += IoData.Size;
+    XenPvBlockIo (&IoData, IsWrite);
+    if (!IoData.Data) {
Quoted 7 lines

Well that wouldn't be possible as the XenPvBlockIo loops forever until that is done.

However, you should probably have a comment here:

/* XXX If we move to a different mechanism for CallBack this might
go away */

That right.

Quoted 111 lines
Quoted 111 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +111 -0
+      DEBUG ((EFI_D_ERROR, "%a %d, XenPvBlockIo no data...\n", __func__, __LINE__));
+      return EFI_DEVICE_ERROR;
+    }
+  }
+  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 Indicates that the driver may perform a more
+                                   exhausive verfication operation of the device
+                                   during reset.
+
+  @retval EFI_SUCCESS          The device was reset.
+  @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
+                               not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
Quoted 9 lines

OvmfPkg/XenPvBlkDxe/BlockIo.c line 253

Quoted 6 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +6 -0
+  IN EFI_BLOCK_IO2_PROTOCOL  *This,
+  IN BOOLEAN                 ExtendedVerification
+  )
+{
+  // Is there anything to do ?
+  // since initialisation is done in Start (driver binding)

Won't we leak memory? Or will it after an Reset do Stop, then Start?

No, I don't think so. Reset is probably to reset the hardware. That a function that I need to take a closer look at.

Quoted 147 lines
Quoted 147 lines
OvmfPkg/XenPvBlkDxe/BlockIo.c new file +3 -0
+  DEBUG ((EFI_D_INFO, "%a %d\n", __func__, __LINE__));
+  return EFI_SUCCESS;
+}
OvmfPkg/XenPvBlkDxe/BlockIo.h new file +109 -0
new file mode 100644
index 0000000..ec0fe2b
@@ -0,0 +1,109 @@
+
+/** @file
+  TODO: Brief Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Detailed Description of UEFI Driver XenPvBlkDxe
+
+  TODO: Copyright for UEFI Driver XenPvBlkDxe
+
+  TODO: License for UEFI Driver XenPvBlkDxe
+
+**/
+
+/**
+  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
+  );
+
+/**
+  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
+  );
+
+/**
+  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
+  );
+
+/**
+  Reset the block device hardware.
+
+  @param[in]  This                 Indicates a pointer to the calling context.
+  @param[in]  ExtendedVerification Indicates that the driver may perform a more
+                                   exhausive verfication operation of the device
+                                   during reset.
+
+  @retval EFI_SUCCESS          The device was reset.
+  @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
+                               not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+XenPvBlkDxeBlockIoReset (
+  IN EFI_BLOCK_IO2_PROTOCOL  *This,
+  IN BOOLEAN                 ExtendedVerification
+  );
+
+extern EFI_BLOCK_IO_MEDIA  gXenPvBlkDxeBlockIoMedia;
+extern EFI_BLOCK_IO_PROTOCOL  gXenPvBlkDxeBlockIo;
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +14 -0
index 7ec7d60..3991e83 100644
@@ -266,6 +266,7 @@ XenPvBlkDxeDriverBindingStart (
   EFI_STATUS Status;
   XENBUS_PROTOCOL *XenbusIo;
   XEN_BLOCK_FRONT_DEVICE *Dev;
+  EFI_BLOCK_IO_MEDIA *Media;
 
   Status = gBS->OpenProtocol (
                 ControllerHandle,
@@ -284,6 +285,37 @@ XenPvBlkDxeDriverBindingStart (
     return Status;
   }
 
+  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;
Quoted 8 lines

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c XenPvBlkDxeDriverBindingStart ( · line 305

Quoted 5 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +5 -0
+  } else {
+    Media->BlockSize = Dev->MediaInfo.SectorSize;
+  }
+  Media->LastBlock = Dev->MediaInfo.Sectors - 1;
+  // XXX What about LowestAlignedLba, LogicalBlocksPerPhysicalBlock and OptimalTransferLengthGranularity?

I think you can skip LogicalBlocksPerPhysicalBlock and OptimalTransferLengthGranularity as they are used for discard operations.

Ok.

Quoted 1 line

The LowestAlignedLba .. no idea.

I think in pv block case, LowestAlignedLba will always be 0.

Quoted 10 lines

OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c XenPvBlkDxeDriverBindingStart ( · line 314

Quoted 9 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +9 -0
+  Dev->BlockIo.Media = Media;
+
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                    &ControllerHandle,
+                    &gEfiBlockIoProtocolGuid, &Dev->BlockIo,
+                    NULL
+                    );
+  if (EFI_ERROR (Status)) {
+    // XXX: uninit everythings
Quoted 2 lines

XenPvBlockFrontShutdown (Dev); ?
FreePool(Media) ?

Yes.

Quoted 74 lines
Quoted 74 lines
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.c +31 -0
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: install protocol fail: %r\n", Status));
+    return Status;
+  }
+
   return EFI_SUCCESS;
 }
 
@@ -322,6 +354,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 186d0ee..3120137 100644
@@ -76,6 +76,7 @@ extern EFI_COMPONENT_NAME_PROTOCOL  gXenPvBlkDxeComponentName;
 //
 #include "DriverBinding.h"
 #include "ComponentName.h"
+#include "BlockIo.h"
 
 
 
OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf +2 -0
index a43d006..b379020 100644
@@ -32,6 +32,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
#49 lore raw

Re: [PATCH RFC 00/18] Introducing Xen PV block driver to OVMF

In reply to Konrad Rzeszutek Wilk
Quoted 16 lines · Konrad Rzeszutek Wilk
Quoted 11 lines · Anthony PERARD

Hi all,

This patch series is implementing the necessary in order to access a PV block device. For that, one need a XenStore client, a XenBus client, and the PV block driver.

There are two new drivers, XenbusDxe and XenPvBlkDxe. The first one implement a bus drivers, and the second is a block drivers.

There are still a bit of work to be done on this series, especially the comment in the code, but I'd like your comment on this patch series.

Went through it - I had some questions and spotted some issues that are pretty easy to fix.

Quoted 8 lines

Otherwise I think you just need to flesh it out with more comments, links to the specs or just copy the relevant parts.

And little puzzled by the usage of 8 pages instead of doing it via 11. But that is probably not a big deal since you are doing each I/O request synchronously anyhow.

Thank you for posting this and developing it!

Thanks for your review.

Signature · 1 line
Anthony PERARD
#44 lore raw

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

In reply to a message not in the archive
Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
(quoted diff) +12 -0
+  OUT XenbusState            *LastStatePtr OPTIONAL
+  )
+{
+  XENBUS_PROTOCOL *XenbusIo = Dev->XenbusIo;
+  XenbusState State;
+  UINT64 Value;
+  XENSTORE_STATUS Status;
+
+  while (TRUE) {
+    Status = XenbusReadInteger (XenbusIo, "state", TRUE, &Value);
+    if (Status != XENSTORE_STATUS_SUCCESS) {
+      return Status;
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+    }
+    if (Value > XenbusStateReconfigured) {
+      return XENSTORE_STATUS_EIO;
+    }
+    State = Value;
+    if (State >= WaitedState) {

Not State != WaitedState ?

Quoted 3 lines

I don't think so, the function is actually waiting for the State to be equal to WaitedState. At least, that how I wrote it. There might be a better algorithm.

Then State == WaitedState

seems the proper way?

Quoted 72 lines
Quoted 63 lines
Quoted 63 lines
(quoted diff) +62 -0
+      break;
+    }
+    DEBUG ((EFI_D_INFO,
+            "XenPvBlk: waiting backend state %d, current: %d\n",
+            WaitedState, State));
+    XenbusIo->WaitForWatch (XenbusIo, Dev->StateWatchToken);
+  }
+
+  if (LastStatePtr != NULL) {
+    *LastStatePtr = State;
+  }
+
+  return XENSTORE_STATUS_SUCCESS;
+}
+
+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 = XenbusReadInteger (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,
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+                         &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));

.. and do you want to error out?

Quoted 3 lines

The original code (mini-os) is continuing in thes case, so I thought it was possible to do the initialisation without transaction. But maybe I'm wrong and this should be an error.

No explanation in the commit for that?

Quoted 68 lines
Quoted 68 lines
Quoted 55 lines
(quoted diff) +54 -0
+  }
+
+  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"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->SetState (XenbusIo, xbt, XenbusStateConnected);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    DEBUG ((EFI_D_ERROR, "XenPvBlk: Failed switch state.\n"));
+    goto AbortTransaction;
+  }
+
+  Status = XenbusIo->XsTransactionEnd (XenbusIo, xbt, FALSE);
+  if (Status == XENSTORE_STATUS_EAGAIN) {
+    goto Again;
+  }
+
+  XenbusIo->RegisterWatchBackend (XenbusIo, "state", &Dev->StateWatchToken);
+
+  // Waiting backend
+  Status = XenPvBlkWaitForBackendState (Dev, XenbusStateConnected, &State);
+  if (Status != XENSTORE_STATUS_SUCCESS || State != XenbusStateConnected) {
+    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 = XenbusReadInteger (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;
+  }
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+  Status = XenbusReadInteger (XenbusIo, "sectors", TRUE, &Dev->MediaInfo.Sectors);
+  if (Status != XENSTORE_STATUS_SUCCESS) {
+    goto Error2;
+  }
+
+  Status = XenbusReadInteger (XenbusIo, "sector-size", TRUE, &Value);
+  if (Status != XENSTORE_STATUS_SUCCESS || Value > UINT32_MAX) {
+    goto Error2;
+  }
+  Dev->MediaInfo.SectorSize = Value;

Why not &Dev->MediaInfo.SectorSize in XenbusReadInteger?

Quoted 6 lines
Quoted 1 line

Is it because of types? If so, please add a comment stating that.

Yes, because of the type, uint64 vs uint32.

Maybe I could rename the XenbusReadInteger to XenbusReadUint64, and it would be more obvious that the function require a specific type.

That would be much better. Thank you

Quoted 33 lines
Quoted 33 lines
Quoted 20 lines
(quoted diff) +19 -0
+
+  // Default value
+  Value = 0;
+  Status = XenbusReadInteger (XenbusIo, "feature-barrier", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureBarrier = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureBarrier = FALSE;
+  }
+
+  // Default value
+  Value = 0;
+  XenbusReadInteger (XenbusIo, "feature-flush-cache", TRUE, &Value);
+  if (Value == 1) {
+    Dev->MediaInfo.FeatureFlushCache = TRUE;
+  } else {
+    Dev->MediaInfo.FeatureFlushCache = FALSE;
+  }
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+  DEBUG ((EFI_D_INFO, "XenPvBlk: New disk with %d 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");

Quoted 86 lines
Quoted 1 line

?

I don't know, but I can do that.

Quoted 82 lines
Quoted 70 lines
(quoted diff) +70 -0
+  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 = XenbusReadInteger (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;
+    }

Review

Quoted 10 lines
(quoted diff) +10 -0
+    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");

"protocol"

As in, also do the XenbusIo->XsRemove(...)

Quoted 68 lines
Quoted 46 lines
Quoted 46 lines
(quoted diff) +46 -0
+
+  XenPvBlockFree (Dev);
+}
+
+STATIC
+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)) {
+        break;
+      }
+      /* Really no slot, go to sleep. */
+      // XXX wait for an event on Dev->EventChannel
+      DEBUG ((EFI_D_INFO, "%a %d, waiting\n", __func__, __LINE__));
+    }
+  }
+}
+
+/* Issue an aio */
+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)));
+
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+  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;
+
+  // XXX is this comment still true ?

I think it is outdated, as Linux would do max DMA up to the segment size that is advertised. Ditto for the SCSI stack.

OK, thanks.

Quoted 5 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+  /* qemu's IDE max multsect is 16 (8KB) and SCSI max DMA was set to 32KB,
+   * so max 44KB can't happen */
+  ASSERT (NumSegments <= BLKIF_MAX_SEGMENTS_PER_REQUEST);

But this check is OK as we can't truly fit more on the ring.

OK.

Quoted 3 lines
Quoted 2 lines
(quoted diff) +2 -0
+
+  XenPvBlockWaitSlot (Dev);
Quoted 7 lines
Quoted 3 lines

What happens if there are multiple threads calling this function? Don't we need a mutex to only allow one thread to grab an RingIndex?

So, OVMF does not have threads but the are "events", called by a timer. This code does not support it, yet, so I don't need any form of locking, yet.

Ok, why don't you mention that in the commit description.

Quoted 31 lines
Quoted 16 lines

Review

Quoted 12 lines
(quoted diff) +11 -0
+  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;
+
+  for (Index = 0; Index < NumSegments; Index++) {
+    Request->seg[Index].first_sect = 0;

Uh?

Quoted 1 line

+ Request->seg[Index].last_sect = EFI_PAGE_SIZE / 512 - 1;

Quoted 8 lines

Uh? I thought you wanted to use the real sector values?

Review

Quoted 4 lines
(quoted diff) +4 -0
+  }
+  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;

What about in between 0 and NumSegments? You should also fill out those values with valid entries.

It's done by the previous for loop. Maybe this part is hard to understand without the interface explain.
include io/blkif.h says:
@first_sect: first sector in frame to transfer (inclusive). @last_sect: last sector in frame to transfer (inclusive).

Quoted 4 lines

but does not explain what a frame is, beyond this comment on:
grant_ref_t gref; /* reference to I/O buffer frame */
(all this from the struct blkif_request_segment)
Or maybe frame == page.

That is what it means. If you have a page, with 4 sectors of data (so half-page) and they are discontingious you have to enumerate the sector values. For example:

First sector = lba + 0 -> lba + 1; #2 sector = lba + 5-> lba + 6; #3 sector = lba + 55 -> lba + 56; #4 sector = lba + 32768 -> lba + 32769

Quoted 4 lines

Anyway, the way the segments are initialized feel weirds now, but I don't think it's incorrect, otherwise, I would not be able to boot any guest.

Well, you could because you might be reading only one sector per I/O request. And then the first_sect and last_sect get filled with proper values.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
(quoted diff) +4 -0
+  for (Index = 0; Index < NumSegments; Index++) {
+    UINTN Data = Start + Index * EFI_PAGE_SIZE;
+    if (!IsWrite) {
+      /* Trigger CoW if needed */
Quoted 8 lines
Quoted 1 line

Not sure I understand that reference?

Maybe a reference to the original commit will help to understand:
minios: Fix bug when blkfront reading into zero-mapped buffer by just poking the page. No need to use virtual_to_mfn() for the ring since that is a real page. 7b1257946080b63421a8dc59c7b3dfd67997c643 (xen.git)

But I still don't undertand this.

I think that means the MiniOS would hit a page fault and allocate a page. I don't know if EFI drivers have this concept?

Quoted 3 lines
Quoted 3 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+      *(CHAR8 *)(Data + (Request->seg[Index].first_sect << 9)) = 0;
+      MemoryFence ();

If the EFI 'things' that use the BlockIO drivers allocate an page for read, then there is no need for this.

Quoted 206 lines
Quoted 41 lines
Quoted 26 lines
(quoted diff) +26 -0
+    }
+    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);
+  }
+}
+
+STATIC
+VOID
+XenPvBlockAsyncIoCallback (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     EFI_STATUS         Status
+  )
+{
+  IoData->Data = (VOID *) 1;
+  IoData->Callback = NULL;

Review

Quoted 10 lines
(quoted diff) +10 -0
+}
+
+VOID
+XenPvBlockIo (
+  IN OUT XEN_BLOCK_FRONT_IO *IoData,
+  IN     BOOLEAN            IsWrite
+  )
+{
+  ASSERT (IoData->Callback == NULL);
+  // XXX Signal/Event instead ?

Maybe for later versions. I think this is OK for right now, thought it will mean we can only do one I/O .. and have then to wait until it is completed.

Quoted 1 line

That limititation should be mentioned in the commit description.

That right, right now, it's only one IO at a time. I think my comment is more to tell me that Callback is not really one, and it could be replace by something more Uefi, an event.

Quoted 20 lines
Quoted 20 lines
(quoted diff) +20 -0
+  IoData->Callback = XenPvBlockAsyncIoCallback;
+  XenPvBlockAsyncIo (IoData, IsWrite);
+  IoData->Data = NULL;
+
+  while (TRUE) {
+    XenPvBlockAsyncIoPoll (IoData->Dev);
+    if (IoData->Data) {
+      break;
+    }
+  }
+}
+
+STATIC
+VOID
+XenPvBlockPushOperation (
+  IN XEN_BLOCK_FRONT_DEVICE *Dev,
+  IN UINT8                  Operation,
+  IN UINT64                 Id
+  )
+{
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+  INT32 Index;
+  blkif_request_t *Request;
+  BOOLEAN Notify;
+
+  XenPvBlockWaitSlot (Dev);

How do we make sure that there aren't multiple threads calling this?

Not possible yet.

Quoted 107 lines
Quoted 107 lines
(quoted diff) +107 -0
+  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);
+  }
+}
+
+VOID
+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;
+      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 %Ld, num bytes %Ld\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;
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+      /* Nota: callback frees IoData itself */
+      if (IoData && IoData->Callback) {
+        IoData->Callback (IoData, Status ? EFI_DEVICE_ERROR : EFI_SUCCESS);
+      }
+      if (Dev->Ring.rsp_cons != ConsumerIndex) {
+        /* We reentered, we must not continue here */

Uh, how does that happen?

That an original comment, I don't think it's possible yet in ovmf.

Quoted 7 lines
Quoted 7 lines
(quoted diff) +7 -0
+        break;
+      }
+    }
+
+    RING_FINAL_CHECK_FOR_RESPONSES (&Dev->Ring, More);
+  } while (More != 0);
+}
Signature · 1 line
Anthony PERARD