Blame SOURCES/ovmf-whitepaper-c770f8c.txt

cc9195
Open Virtual Machine Firmware (OVMF) Status Report
cc9195
July 2014 (with updates in August 2014 - January 2015)
cc9195
cc9195
Author: Laszlo Ersek <lersek@redhat.com>
cc9195
Copyright (C) 2014-2015, Red Hat, Inc.
cc9195
CC BY-SA 4.0 <http://creativecommons.org/licenses/by-sa/4.0/>
cc9195
cc9195
Abstract
cc9195
--------
cc9195
cc9195
The Unified Extensible Firmware Interface (UEFI) is a specification that
cc9195
defines a software interface between an operating system and platform firmware.
cc9195
UEFI is designed to replace the Basic Input/Output System (BIOS) firmware
cc9195
interface.
cc9195
cc9195
Hardware platform vendors have been increasingly adopting the UEFI
cc9195
Specification to govern their boot firmware developments. OVMF (Open Virtual
cc9195
Machine Firmware), a sub-project of Intel's EFI Development Kit II (edk2),
cc9195
enables UEFI support for Ia32 and X64 Virtual Machines.
cc9195
cc9195
This paper reports on the status of the OVMF project, treats features and
cc9195
limitations, gives end-user hints, and examines some areas in-depth.
cc9195
cc9195
Keywords: ACPI, boot options, CSM, edk2, firmware, flash, fw_cfg, KVM, memory
cc9195
map, non-volatile variables, OVMF, PCD, QEMU, reset vector, S3, Secure Boot,
cc9195
Smbios, SMM, TianoCore, UEFI, VBE shim, Virtio
cc9195
cc9195
Table of Contents
cc9195
-----------------
cc9195
cc9195
- Motivation
cc9195
- Scope
cc9195
- Example qemu invocation
cc9195
- Installation of OVMF guests with virt-manager and virt-install
cc9195
- Supported guest operating systems
cc9195
- Compatibility Support Module (CSM)
cc9195
- Phases of the boot process
cc9195
- Project structure
cc9195
- Platform Configuration Database (PCD)
cc9195
- Firmware image structure
cc9195
- S3 (suspend to RAM and resume)
cc9195
- A comprehensive memory map of OVMF
cc9195
- Known Secure Boot limitations
cc9195
- Variable store and LockBox in SMRAM
cc9195
- Select features
cc9195
  - X64-specific reset vector for OVMF
cc9195
  - Client library for QEMU's firmware configuration interface
cc9195
  - Guest ACPI tables
cc9195
  - Guest SMBIOS tables
cc9195
  - Platform-specific boot policy
cc9195
  - Virtio drivers
cc9195
  - Platform Driver
cc9195
  - Video driver
cc9195
- Afterword
cc9195
cc9195
Motivation
cc9195
----------
cc9195
cc9195
OVMF extends the usual benefits of virtualization to UEFI. Reasons to use OVMF
cc9195
include:
cc9195
cc9195
- Legacy-free guests. A UEFI-based environment eliminates dependencies on
cc9195
  legacy address spaces and devices. This is especially beneficial when used
cc9195
  with physically assigned devices where the legacy operating mode is
cc9195
  troublesome to support, ex. assigned graphics cards operating in legacy-free,
cc9195
  non-VGA mode in the guest.
cc9195
cc9195
- Future proof guests. The x86 market is steadily moving towards a legacy-free
cc9195
  platform and guest operating systems may eventually require a UEFI
cc9195
  environment. OVMF provides that next generation firmware support for such
cc9195
  applications.
cc9195
cc9195
- GUID partition tables (GPTs). MBR partition tables represent partition
cc9195
  offsets and sizes with 32-bit integers, in units of 512 byte sectors. This
cc9195
  limits the addressable portion of the disk to 2 TB. GPT represents logical
cc9195
  block addresses with 64 bits.
cc9195
cc9195
- Liberating boot loader binaries from residing in contested and poorly defined
cc9195
  space between the partition table and the partitions.
cc9195
cc9195
- Support for booting off disks (eg. pass-through physical SCSI devices) with a
cc9195
  4kB physical and logical sector size, i.e. which don't have 512-byte block
cc9195
  emulation.
cc9195
cc9195
- Development and testing of Secure Boot-related features in guest operating
cc9195
  systems. Although OVMF's Secure Boot implementation is currently not secure
cc9195
  against malicious UEFI drivers, UEFI applications, and guest kernels,
cc9195
  trusted guest code that only uses standard UEFI interfaces will find a valid
cc9195
  Secure Boot environment under OVMF, with working key enrollment and signature
cc9195
  validation. This enables development and testing of portable, Secure
cc9195
  Boot-related guest code.
cc9195
cc9195
- Presence of non-volatile UEFI variables. This furthers development and
cc9195
  testing of OS installers, UEFI boot loaders, and unique, dependent guest OS
cc9195
  features. For example, an efivars-backed pstore (persistent storage)
cc9195
  file system works under Linux.
cc9195
cc9195
- Altogether, a near production-level UEFI environment for virtual machines
cc9195
  when Secure Boot is not required.
cc9195
cc9195
Scope
cc9195
-----
cc9195
cc9195
UEFI and especially Secure Boot have been topics fraught with controversy and
cc9195
political activism. This paper sidesteps these aspects and strives to focus on
cc9195
use cases, hands-on information for end users, and technical details.
cc9195
cc9195
Unless stated otherwise, the expression "X supports Y" means "X is technically
cc9195
compatible with interfaces provided or required by Y". It does not imply
cc9195
support as an activity performed by natural persons or companies.
cc9195
cc9195
We discuss the status of OVMF at a state no earlier than edk2 SVN revision
cc9195
16158. The paper concentrates on upstream projects and communities, but
cc9195
occasionally it pans out about OVMF as it is planned to be shipped (as
cc9195
Technical Preview) in Red Hat Enterprise Linux 7.1. Such digressions are marked
cc9195
with the [RHEL] margin notation.
cc9195
cc9195
Although other VMMs and accelerators are known to support (or plan to support)
cc9195
OVMF to various degrees -- for example, VirtualBox, Xen, BHyVe --, we'll
cc9195
emphasize OVMF on qemu/KVM, because QEMU and KVM have always been Red Hat's
cc9195
focus wrt. OVMF.
cc9195
cc9195
The recommended upstream QEMU version is 2.1+. The recommended host Linux
cc9195
kernel (KVM) version is 3.10+. The recommended QEMU machine type is
cc9195
"qemu-system-x86_64 -M pc-i440fx-2.1" or later.
cc9195
cc9195
The term "TianoCore" is used interchangeably with "edk2" in this paper.
cc9195
cc9195
Example qemu invocation
cc9195
-----------------------
cc9195
cc9195
The following commands give a quick foretaste of installing a UEFI operating
cc9195
system on OVMF, relying only on upstream edk2 and qemu.
cc9195
cc9195
- Clone and build OVMF:
cc9195
cc9195
  git clone https://github.com/tianocore/edk2.git
cc9195
  cd edk2
cc9195
  nice OvmfPkg/build.sh -a X64 -n $(getconf _NPROCESSORS_ONLN)
cc9195
cc9195
  (Note that this ad-hoc build will not include the Secure Boot feature.)
cc9195
cc9195
- The build output file, "OVMF.fd", includes not only the executable firmware
cc9195
  code, but the non-volatile variable store as well. For this reason, make a
cc9195
  VM-specific copy of the build output (the variable store should be private to
cc9195
  the virtual machine):
cc9195
cc9195
  cp Build/OvmfX64/DEBUG_GCC4?/FV/OVMF.fd fedora.flash
cc9195
cc9195
  (The variable store and the firmware executable are also available in the
cc9195
  build output as separate files: "OVMF_VARS.fd" and "OVMF_CODE.fd". This
cc9195
  enables central management and updates of the firmware executable, while each
cc9195
  virtual machine can retain its own variable store.)
cc9195
cc9195
- Download a Fedora LiveCD:
cc9195
cc9195
  wget https://dl.fedoraproject.org/pub/fedora/linux/releases/20/Live/x86_64/Fedora-Live-Xfce-x86_64-20-1.iso
cc9195
cc9195
- Create a virtual disk (qcow2 format, 20 GB in size):
cc9195
cc9195
  qemu-img create -f qcow2 fedora.img 20G
cc9195
cc9195
- Create the following qemu wrapper script under the name "fedora.sh":
cc9195
cc9195
  # Basic virtual machine properties: a recent i440fx machine type, KVM
cc9195
  # acceleration, 2048 MB RAM, two VCPUs.
cc9195
  OPTS="-M pc-i440fx-2.1 -enable-kvm -m 2048 -smp 2"
cc9195
cc9195
  # The OVMF binary, including the non-volatile variable store, appears as a
cc9195
  # "normal" qemu drive on the host side, and it is exposed to the guest as a
cc9195
  # persistent flash device.
cc9195
  OPTS="$OPTS -drive if=pflash,format=raw,file=fedora.flash"
cc9195
cc9195
  # The hard disk is exposed to the guest as a virtio-block device. OVMF has a
cc9195
  # driver stack that supports such a disk. We specify this disk as first boot
cc9195
  # option. OVMF recognizes the boot order specification.
cc9195
  OPTS="$OPTS -drive id=disk0,if=none,format=qcow2,file=fedora.img"
cc9195
  OPTS="$OPTS -device virtio-blk-pci,drive=disk0,bootindex=0"
cc9195
cc9195
  # The Fedora installer disk appears as an IDE CD-ROM in the guest. This is
cc9195
  # the 2nd boot option.
cc9195
  OPTS="$OPTS -drive id=cd0,if=none,format=raw,readonly"
cc9195
  OPTS="$OPTS,file=Fedora-Live-Xfce-x86_64-20-1.iso"
cc9195
  OPTS="$OPTS -device ide-cd,bus=ide.1,drive=cd0,bootindex=1"
cc9195
cc9195
  # The following setting enables S3 (suspend to RAM). OVMF supports S3
cc9195
  # suspend/resume.
cc9195
  OPTS="$OPTS -global PIIX4_PM.disable_s3=0"
cc9195
cc9195
  # OVMF emits a number of info / debug messages to the QEMU debug console, at
cc9195
  # ioport 0x402. We configure qemu so that the debug console is indeed
cc9195
  # available at that ioport. We redirect the host side of the debug console to
cc9195
  # a file.
cc9195
  OPTS="$OPTS -global isa-debugcon.iobase=0x402 -debugcon file:fedora.ovmf.log"
cc9195
cc9195
  # QEMU accepts various commands and queries from the user on the monitor
cc9195
  # interface. Connect the monitor with the qemu process's standard input and
cc9195
  # output.
cc9195
  OPTS="$OPTS -monitor stdio"
cc9195
cc9195
  # A USB tablet device in the guest allows for accurate pointer tracking
cc9195
  # between the host and the guest.
cc9195
  OPTS="$OPTS -device piix3-usb-uhci -device usb-tablet"
cc9195
cc9195
  # Provide the guest with a virtual network card (virtio-net).
cc9195
  #
cc9195
  # Normally, qemu provides the guest with a UEFI-conformant network driver
cc9195
  # from the iPXE project, in the form of a PCI expansion ROM. For this test,
cc9195
  # we disable the expansion ROM and allow OVMF's built-in virtio-net driver to
cc9195
  # take effect.
cc9195
  #
cc9195
  # On the host side, we use the SLIRP ("user") network backend, which has
cc9195
  # relatively low performance, but it doesn't require extra privileges from
cc9195
  # the user executing qemu.
cc9195
  OPTS="$OPTS -netdev id=net0,type=user"
cc9195
  OPTS="$OPTS -device virtio-net-pci,netdev=net0,romfile="
cc9195
cc9195
  # A Spice QXL GPU is recommended as the primary VGA-compatible display
cc9195
  # device. It is a full-featured virtual video card, with great operating
cc9195
  # system driver support. OVMF supports it too.
cc9195
  OPTS="$OPTS -device qxl-vga"
cc9195
cc9195
  qemu-system-x86_64 $OPTS
cc9195
cc9195
- Start the Fedora guest:
cc9195
cc9195
  sh fedora.sh
cc9195
cc9195
- The above command can be used for both installation and later boots of the
cc9195
  Fedora guest.
cc9195
cc9195
- In order to verify basic OVMF network connectivity:
cc9195
cc9195
  - Assuming that the non-privileged user running qemu belongs to group G
cc9195
    (where G is a numeric identifier), ensure as root on the host that the
cc9195
    group range in file "/proc/sys/net/ipv4/ping_group_range" includes G.
cc9195
cc9195
  - As the non-privileged user, boot the guest as usual.
cc9195
cc9195
  - On the TianoCore splash screen, press ESC.
cc9195
cc9195
  - Navigate to Boot Manager | EFI Internal Shell
cc9195
cc9195
  - In the UEFI Shell, issue the following commands:
cc9195
cc9195
    ifconfig -s eth0 dhcp
cc9195
    ping A.B.C.D
cc9195
cc9195
    where A.B.C.D is a public IPv4 address in dotted decimal notation that your
cc9195
    host can reach.
cc9195
cc9195
  - Type "quit" at the (qemu) monitor prompt.
cc9195
cc9195
Installation of OVMF guests with virt-manager and virt-install
cc9195
--------------------------------------------------------------
cc9195
cc9195
(1) Assuming OVMF has been installed on the host with the following files:
cc9195
    - /usr/share/OVMF/OVMF_CODE.fd
cc9195
    - /usr/share/OVMF/OVMF_VARS.fd
cc9195
cc9195
    locate the "nvram" stanza in "/etc/libvirt/qemu.conf", and edit it as
cc9195
    follows:
cc9195
cc9195
    nvram = [ "/usr/share/OVMF/OVMF_CODE.fd:/usr/share/OVMF/OVMF_VARS.fd" ]
cc9195
cc9195
(2) Restart libvirtd with your Linux distribution's service management tool;
cc9195
    for example,
cc9195
cc9195
    systemctl restart libvirtd
cc9195
cc9195
(3) In virt-manager, proceed with the guest installation as usual:
cc9195
    - select File | New Virtual Machine,
cc9195
    - advance to Step 5 of 5,
cc9195
    - in Step 5, check "Customize configuration before install",
cc9195
    - click Finish;
cc9195
    - in the customization dialog, select Overview | Firmware, and choose UEFI,
cc9195
    - click Apply and Begin Installation.
cc9195
cc9195
(4) With virt-install:
cc9195
cc9195
    LDR="loader=/usr/share/OVMF/OVMF_CODE.fd,loader_ro=yes,loader_type=pflash"
cc9195
    virt-install \
cc9195
      --name fedora20 \
cc9195
      --memory 2048 \
cc9195
      --vcpus 2 \
cc9195
      --os-variant fedora20 \
cc9195
      --boot hd,cdrom,$LDR \
cc9195
      --disk size=20 \
cc9195
      --disk path=Fedora-Live-Xfce-x86_64-20-1.iso,device=cdrom,bus=scsi
cc9195
cc9195
(5) A popular, distribution-independent, bleeding-edge OVMF package is
cc9195
    available under <https://www.kraxel.org/repos/>, courtesy of Gerd Hoffmann.
cc9195
cc9195
    The "edk2.git-ovmf-x64" package provides the following files, among others:
cc9195
    - /usr/share/edk2.git/ovmf-x64/OVMF_CODE-pure-efi.fd
cc9195
    - /usr/share/edk2.git/ovmf-x64/OVMF_VARS-pure-efi.fd
cc9195
cc9195
    When using this package, adapt steps (1) and (4) accordingly.
cc9195
cc9195
(6) Additionally, the "edk2.git-ovmf-x64" package seeks to simplify the
cc9195
    enablement of Secure Boot in a virtual machine (strictly for development
cc9195
    and testing purposes).
cc9195
cc9195
    - Boot the virtual machine off the CD-ROM image called
cc9195
      "/usr/share/edk2.git/ovmf-x64/UefiShell.iso"; before or after installing
cc9195
      the main guest operating system.
cc9195
cc9195
    - When the UEFI shell appears, issue the following commands:
cc9195
cc9195
      EnrollDefaultKeys.efi
cc9195
      reset -s
cc9195
cc9195
    - The EnrollDefaultKeys.efi utility enrolls the following keys:
cc9195
cc9195
      - A static example X.509 certificate (CN=TestCommonName) as Platform Key
cc9195
        and first Key Exchange Key.
cc9195
cc9195
        The private key matching this certificate has been destroyed (but you
cc9195
        shouldn't trust this statement).
cc9195
cc9195
      - "Microsoft Corporation KEK CA 2011" as second Key Exchange Key
cc9195
        (SHA1: 31:59:0b:fd:89:c9:d7:4e:d0:87:df:ac:66:33:4b:39:31:25:4b:30).
cc9195
cc9195
      - "Microsoft Windows Production PCA 2011" as first DB entry
cc9195
        (SHA1: 58:0a:6f:4c:c4:e4:b6:69:b9:eb:dc:1b:2b:3e:08:7b:80:d0:67:8d).
cc9195
cc9195
      - "Microsoft Corporation UEFI CA 2011" as second DB entry
cc9195
        (SHA1: 46:de:f6:3b:5c:e6:1c:f8:ba:0d:e2:e6:63:9c:10:19:d0:ed:14:f3).
cc9195
cc9195
      These keys suffice to boot released versions of popular Linux
cc9195
      distributions (through the shim.efi utility), and Windows 8 and Windows
cc9195
      Server 2012 R2, in Secure Boot mode.
cc9195
cc9195
Supported guest operating systems
cc9195
---------------------------------
cc9195
cc9195
Upstream OVMF does not favor some guest operating systems over others for
cc9195
political or ideological reasons. However, some operating systems are harder to
cc9195
obtain and/or technically more difficult to support. The general expectation is
cc9195
that recent UEFI OSes should just work. Please consult the "OvmfPkg/README"
cc9195
file.
cc9195
cc9195
The following guest OSes were tested with OVMF:
cc9195
- Red Hat Enterprise Linux 6
cc9195
- Red Hat Enterprise Linux 7
cc9195
- Fedora 18
cc9195
- Fedora 19
cc9195
- Fedora 20
cc9195
- Windows Server 2008 R2 SP1
cc9195
- Windows Server 2012
cc9195
- Windows 8
cc9195
cc9195
Notes about Windows Server 2008 R2 (paraphrasing the "OvmfPkg/README" file):
cc9195
cc9195
- QEMU should be started with one of the "-device qxl-vga" and "-device VGA"
cc9195
  options.
cc9195
cc9195
- Only one video mode, 1024x768x32, is supported at OS runtime.
cc9195
cc9195
  Please refer to the section about QemuVideoDxe (OVMF's built-in video driver)
cc9195
  for more details on this limitation.
cc9195
cc9195
- The qxl-vga video card is recommended ("-device qxl-vga"). After booting the
cc9195
  installed guest OS, select the video card in Device Manager, and upgrade the
cc9195
  video driver to the QXL XDDM one.
cc9195
cc9195
  The QXL XDDM driver can be downloaded from
cc9195
  <http://www.spice-space.org/download.html>, under Guest | Windows binaries.
cc9195
cc9195
  This driver enables additional graphics resolutions at OS runtime, and
cc9195
  provides S3 (suspend/resume) capability.
cc9195
cc9195
Notes about Windows Server 2012 and Windows 8:
cc9195
cc9195
- QEMU should be started with the "-device qxl-vga,revision=4" option (or a
cc9195
  later revision, if available).
cc9195
cc9195
- The guest OS's builtin video driver inherits the video mode / frame buffer
cc9195
  from OVMF. There's no way to change the resolution at OS runtime.
cc9195
cc9195
  For this reason, a platform driver has been developed for OVMF, which allows
cc9195
  users to change the preferred video mode in the firmware. Please refer to the
cc9195
  section about PlatformDxe for details.
cc9195
cc9195
- It is recommended to upgrade the guest OS's video driver to the QXL WDDM one,
cc9195
  via Device Manager.
cc9195
cc9195
  Binaries for the QXL WDDM driver can be found at
cc9195
  <http://people.redhat.com/~vrozenfe/qxlwddm> (pick a version greater than or
cc9195
  equal to 0.6), while the source code resides at
cc9195
  <https://github.com/vrozenfe/qxl-dod>.
cc9195
cc9195
  This driver enables additional graphics resolutions at OS runtime, and
cc9195
  provides S3 (suspend/resume) capability.
cc9195
cc9195
Compatibility Support Module (CSM)
cc9195
----------------------------------
cc9195
cc9195
Collaboration between SeaBIOS and OVMF developers has enabled SeaBIOS to be
cc9195
built as a Compatibility Support Module, and OVMF to embed and use it.
cc9195
cc9195
Benefits of a SeaBIOS CSM include:
cc9195
cc9195
- The ability to boot legacy (non-UEFI) operating systems, such as legacy Linux
cc9195
  systems, Windows 7, OpenBSD 5.2, FreeBSD 8/9, NetBSD, DragonflyBSD, Solaris
cc9195
  10/11.
cc9195
cc9195
- Legacy (non-UEFI-compliant) PCI expansion ROMs, such as a VGA BIOS, mapped by
cc9195
  QEMU in emulated devices' ROM BARs, are loaded and executed by OVMF.
cc9195
cc9195
  For example, this grants the Windows Server 2008 R2 SP1 guest's native,
cc9195
  legacy video driver access to all modes of all QEMU video cards.
cc9195
cc9195
Building the CSM target of the SeaBIOS source tree is out of scope for this
cc9195
report. Additionally, upstream OVMF does not enable the CSM by default.
cc9195
cc9195
Interested users and developers should look for OVMF's "-D CSM_ENABLE"
cc9195
build-time option, and check out the <https://www.kraxel.org/repos/> continuous
cc9195
integration repository, which provides CSM-enabled OVMF builds.
cc9195
cc9195
[RHEL] The "OVMF_CODE.fd" firmware image made available on the Red Hat
cc9195
       Enterprise Linux 7.1 host does not include a Compatibility Support
cc9195
       Module, for the following reasons:
cc9195
cc9195
       - Virtual machines running officially supported, legacy guest operating
cc9195
         systems should just use the standalone SeaBIOS firmware. Firmware
cc9195
         selection is flexible in virtualization, see eg. "Installation of OVMF
cc9195
         guests with virt-manager and virt-install" above.
cc9195
cc9195
       - The 16-bit thunking interface between OVMF and SeaBIOS is very complex
cc9195
         and presents a large debugging and support burden, based on past
cc9195
         experience.
cc9195
cc9195
       - Secure Boot is incompatible with CSM.
cc9195
cc9195
       - Inter-project dependencies should be minimized whenever possible.
cc9195
cc9195
       - Using the default QXL video card, the Windows 2008 R2 SP1 guest can be
cc9195
         installed with its built-in, legacy video driver. Said driver will
cc9195
         select the only available video mode, 1024x768x32. After installation,
cc9195
         the video driver can be upgraded to the full-featured QXL XDDM driver.
cc9195
cc9195
Phases of the boot process
cc9195
--------------------------
cc9195
cc9195
The PI and UEFI specifications, and Intel's UEFI and EDK II Learning and
cc9195
Development materials provide ample information on PI and UEFI concepts. The
cc9195
following is an absolutely minimal, rough glossary that is included only to
cc9195
help readers new to PI and UEFI understand references in later, OVMF-specific
cc9195
sections. We defer heavily to the official specifications and the training
cc9195
materials, and frequently quote them below.
cc9195
cc9195
A central concept to mention early is the GUID -- globally unique identifier. A
cc9195
GUID is a 128-bit number, written as XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,
cc9195
where each X stands for a hexadecimal nibble. GUIDs are used to name everything
cc9195
in PI and in UEFI. Programmers introduce new GUIDs with the "uuidgen" utility,
cc9195
and standards bodies standardize well-known services by positing their GUIDs.
cc9195
cc9195
The boot process is roughly divided in the following phases:
cc9195
cc9195
- Reset vector code.
cc9195
cc9195
- SEC: Security phase. This phase is the root of firmware integrity.
cc9195
cc9195
- PEI: Pre-EFI Initialization. This phase performs "minimal processor, chipset
cc9195
  and platform configuration for the purpose of discovering memory". Modules in
cc9195
  PEI collectively save their findings about the platform in a list of HOBs
cc9195
  (hand-off blocks).
cc9195
cc9195
  When developing PEI code, the Platform Initialization (PI) specification
cc9195
  should be consulted.
cc9195
cc9195
- DXE: Driver eXecution Environment, pronounced as "Dixie". This "is the phase
cc9195
  where the bulk of the booting occurs: devices are enumerated and initialized,
cc9195
  UEFI services are supported, and protocols and drivers are implemented. Also,
cc9195
  the tables that create the UEFI interface are produced".
cc9195
cc9195
  On the PEI/DXE boundary, the HOBs produced by PEI are consumed. For example,
cc9195
  this is how the memory space map is configured initially.
cc9195
cc9195
- BDS: Boot Device Selection. It is "responsible for determining how and where
cc9195
  you want to boot the operating system".
cc9195
cc9195
  When developing DXE and BDS code, it is mainly the UEFI specification that
cc9195
  should be consulted. When speaking about DXE, BDS is frequently considered to
cc9195
  be a part of it.
cc9195
cc9195
The following concepts are tied to specific boot process phases:
cc9195
cc9195
- PEIM: a PEI Module (pronounced "PIM"). A binary module running in the PEI
cc9195
  phase, consuming some PPIs and producing other PPIs, and producing HOBs.
cc9195
cc9195
- PPI: PEIM-to-PEIM interface. A structure of function pointers and related
cc9195
  data members that establishes a PEI service, or an instance of a PEI service.
cc9195
  PPIs are identified by GUID.
cc9195
cc9195
  An example is EFI_PEI_S3_RESUME2_PPI (6D582DBC-DB85-4514-8FCC-5ADF6227B147).
cc9195
cc9195
- DXE driver: a binary module running in the DXE and BDS phases, consuming some
cc9195
  protocols and producing other protocols.
cc9195
cc9195
- Protocol: A structure of function pointers and related data members that
cc9195
  establishes a DXE service, or an instance of a DXE service. Protocols are
cc9195
  identified by GUID.
cc9195
cc9195
  An example is EFI_BLOCK_IO_PROTOCOL (964E5B21-6459-11D2-8E39-00A0C969723B).
cc9195
cc9195
- Architectural protocols: a set of standard protocols that are foundational to
cc9195
  the working of a UEFI system. Each architectural protocol has at most one
cc9195
  instance. Architectural protocols are implemented by a subset of DXE drivers.
cc9195
  DXE drivers explicitly list the set of protocols (including architectural
cc9195
  protocols) that they need to work. UEFI drivers can only be loaded once all
cc9195
  architectural protocols have become available during the DXE phase.
cc9195
cc9195
  An example is EFI_VARIABLE_WRITE_ARCH_PROTOCOL
cc9195
  (6441F818-6362-4E44-B570-7DBA31DD2453).
cc9195
cc9195
Project structure
cc9195
-----------------
cc9195
cc9195
The term "OVMF" usually denotes the project (community and development effort)
cc9195
that provide and maintain the subject matter UEFI firmware for virtual
cc9195
machines. However the term is also frequently applied to the firmware binary
cc9195
proper that a virtual machine executes.
cc9195
cc9195
OVMF emerges as a compilation of several modules from the edk2 source
cc9195
repository. "edk2" stands for EFI Development Kit II; it is a "modern,
cc9195
feature-rich, cross-platform firmware development environment for the UEFI and
cc9195
PI specifications".
cc9195
cc9195
The composition of OVMF is dictated by the following build control files:
cc9195
cc9195
  OvmfPkg/OvmfPkgIa32.dsc
cc9195
  OvmfPkg/OvmfPkgIa32.fdf
cc9195
cc9195
  OvmfPkg/OvmfPkgIa32X64.dsc
cc9195
  OvmfPkg/OvmfPkgIa32X64.fdf
cc9195
cc9195
  OvmfPkg/OvmfPkgX64.dsc
cc9195
  OvmfPkg/OvmfPkgX64.fdf
cc9195
cc9195
The format of these files is described in the edk2 DSC and FDF specifications.
cc9195
Roughly, the DSC file determines:
cc9195
- library instance resolutions for library class requirements presented by the
cc9195
  modules to be compiled,
cc9195
- the set of modules to compile.
cc9195
cc9195
The FDF file roughly determines:
cc9195
- what binary modules (compilation output files, precompiled binaries, graphics
cc9195
  image files, verbatim binary sections) to include in the firmware image,
cc9195
- how to lay out the firmware image.
cc9195
cc9195
The Ia32 flavor of these files builds a firmware where both PEI and DXE phases
cc9195
are 32-bit. The Ia32X64 flavor builds a firmware where the PEI phase consists
cc9195
of 32-bit modules, and the DXE phase is 64-bit. The X64 flavor builds a purely
cc9195
64-bit firmware.
cc9195
cc9195
The word size of the DXE phase must match the word size of the runtime OS -- a
cc9195
32-bit DXE can't cooperate with a 64-bit OS, and a 64-bit DXE can't work a
cc9195
32-bit OS.
cc9195
cc9195
OVMF pulls together modules from across the edk2 tree. For example:
cc9195
cc9195
- common drivers and libraries that are platform independent are usually
cc9195
  located under MdeModulePkg and MdePkg,
cc9195
cc9195
- common but hardware-specific drivers and libraries that match QEMU's
cc9195
  pc-i440fx-* machine type are pulled in from IntelFrameworkModulePkg,
cc9195
  PcAtChipsetPkg and UefiCpuPkg,
cc9195
cc9195
- the platform independent UEFI Shell is built from ShellPkg,
cc9195
cc9195
- OvmfPkg includes drivers and libraries that are useful for virtual machines
cc9195
  and may or may not be specific to QEMU's pc-i440fx-* machine type.
cc9195
cc9195
Platform Configuration Database (PCD)
cc9195
-------------------------------------
cc9195
cc9195
Like the "Phases of the boot process" section, this one introduces a concept in
cc9195
very raw form. We defer to the PCD related edk2 specifications, and we won't
cc9195
discuss implementation details here. Our purpose is only to offer the reader a
cc9195
usable (albeit possibly inaccurate) definition, so that we can refer to PCDs
cc9195
later on.
cc9195
cc9195
Colloquially, when we say "PCD", we actually mean "PCD entry"; that is, an
cc9195
entry stored in the Platform Configuration Database.
cc9195
cc9195
The Platform Configuration Database is
cc9195
- a firmware-wide
cc9195
- name-value store
cc9195
- of scalars and buffers
cc9195
- where each entry may be
cc9195
  - build-time constant, or
cc9195
  - run-time dynamic, or
cc9195
  - theoretically, a middle option: patchable in the firmware file itself,
cc9195
    using a dedicated tool. (OVMF does not utilize externally patchable
cc9195
    entries.)
cc9195
cc9195
A PCD entry is declared in the DEC file of the edk2 top-level Package directory
cc9195
whose modules (drivers and libraries) are the primary consumers of the PCD
cc9195
entry. (See for example OvmfPkg/OvmfPkg.dec). Basically, a PCD in a DEC file
cc9195
exposes a simple customization point.
cc9195
cc9195
Interest in a PCD entry is communicated to the build system by naming the PCD
cc9195
entry in the INF file of the interested module (application, driver or
cc9195
library). The module may read and -- dependent on the PCD entry's category --
cc9195
write the PCD entry.
cc9195
cc9195
Let's investigate the characteristics of the Database and the PCD entries.
cc9195
cc9195
- Firmware-wide: technically, all modules may access all entries they are
cc9195
  interested in, assuming they advertise their interest in their INF files.
cc9195
  With careful design, PCDs enable inter-driver propagation of (simple) system
cc9195
  configuration. PCDs are available in both PEI and DXE.
cc9195
cc9195
  (UEFI drivers meant to be portable (ie. from third party vendors) are not
cc9195
  supposed to use PCDs, since PCDs qualify internal to the specific edk2
cc9195
  firmware in question.)
cc9195
cc9195
- Name-value store of scalars and buffers: each PCD has a symbolic name, and a
cc9195
  fixed scalar type (UINT16, UINT32 etc), or VOID* for buffers. Each PCD entry
cc9195
  belongs to a namespace, where a namespace is (obviously) a GUID, defined in
cc9195
  the DEC file.
cc9195
cc9195
- A DEC file can permit several categories for a PCD:
cc9195
  - build-time constant ("FixedAtBuild"),
cc9195
  - patchable in the firmware image ("PatchableInModule", unused in OVMF),
cc9195
  - runtime modifiable ("Dynamic").
cc9195
cc9195
The platform description file (DSC) of a top-level Package directory may choose
cc9195
the exact category for a given PCD entry that its modules wish to use, and
cc9195
assign a default (or constant) initial value to it.
cc9195
cc9195
In addition, the edk2 build system too can initialize PCD entries to values
cc9195
that it calculates while laying out the flash device image. Such PCD
cc9195
assignments are described in the FDF control file.
cc9195
cc9195
Firmware image structure
cc9195
------------------------
cc9195
cc9195
(We assume the common X64 choice for both PEI and DXE, and the default DEBUG
cc9195
build target.)
cc9195
cc9195
The OvmfPkg/OvmfPkgX64.fdf file defines the following layout for the flash
cc9195
device image "OVMF.fd":
cc9195
cc9195
  Description                     Compression type        Size
cc9195
  ------------------------------  ----------------------  -------
cc9195
  Non-volatile data storage       open-coded binary data   128 KB
cc9195
    Variable store                                          56 KB
cc9195
    Event log                                                4 KB
cc9195
    Working block                                            4 KB
cc9195
    Spare area                                              64 KB
cc9195
cc9195
  FVMAIN_COMPACT                  uncompressed            1712 KB
cc9195
    FV Firmware File System file  LZMA compressed
cc9195
      PEIFV                       uncompressed             896 KB
cc9195
        individual PEI modules    uncompressed
cc9195
      DXEFV                       uncompressed            8192 KB
cc9195
        individual DXE modules    uncompressed
cc9195
cc9195
  SECFV                           uncompressed             208 KB
cc9195
    SEC driver
cc9195
    reset vector code
cc9195
cc9195
The top-level image consists of three regions (three firmware volumes):
cc9195
- non-volatile data store (128 KB),
cc9195
- main firmware volume (FVMAIN_COMPACT, 1712 KB),
cc9195
- firmware volume containing the reset vector code and the SEC phase code (208
cc9195
  KB).
cc9195
cc9195
In total, the OVMF.fd file has size 128 KB + 1712 KB + 208 KB == 2 MB.
cc9195
cc9195
(1) The firmware volume with non-volatile data store (128 KB) has the following
cc9195
    internal structure, in blocks of 4 KB:
cc9195
cc9195
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  L: event log
cc9195
       LIVE | varstore                  |L|W|  W: working block
cc9195
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cc9195
cc9195
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cc9195
      SPARE |                               |
cc9195
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cc9195
cc9195
    The first half of this firmware volume is "live", while the second half is
cc9195
    "spare". The spare half is important when the variable driver reclaims
cc9195
    unused storage and reorganizes the variable store.
cc9195
cc9195
    The live half dedicates 14 blocks (56 KB) to the variable store itself. On
cc9195
    top of those, one block is set aside for an event log, and one block is
cc9195
    used as the working block of the fault tolerant write protocol. Fault
cc9195
    tolerant writes are used to recover from an occasional (virtual) power loss
cc9195
    during variable updates.
cc9195
cc9195
    The blocks in this firmware volume are accessed, in stacking order from
cc9195
    least abstract to most abstract, by:
cc9195
cc9195
    - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL (provided by
cc9195
      OvmfPkg/QemuFlashFvbServicesRuntimeDxe),
cc9195
cc9195
    - EFI_FAULT_TOLERANT_WRITE_PROTOCOL (provided by
cc9195
      MdeModulePkg/Universal/FaultTolerantWriteDxe),
cc9195
cc9195
    - architectural protocols instrumental to the runtime UEFI variable
cc9195
      services:
cc9195
      - EFI_VARIABLE_ARCH_PROTOCOL,
cc9195
      - EFI_VARIABLE_WRITE_ARCH_PROTOCOL.
cc9195
cc9195
      In a non-secure boot build, the DXE driver providing these architectural
cc9195
      protocols is MdeModulePkg/Universal/Variable/RuntimeDxe. In a secure boot
cc9195
      build, where authenticated variables are available, the DXE driver
cc9195
      offering these protocols is SecurityPkg/VariableAuthenticated/RuntimeDxe.
cc9195
cc9195
(2) The main firmware volume (FVMAIN_COMPACT, 1712 KB) embeds further firmware
cc9195
    volumes. The outermost layer is a Firmware File System (FFS), carrying a
cc9195
    single file. This file holds an LZMA-compressed section, which embeds two
cc9195
    firmware volumes: PEIFV (896 KB) with PEIMs, and DXEFV (8192 KB) with DXE
cc9195
    and UEFI drivers.
cc9195
cc9195
    This scheme enables us to build 896 KB worth of PEI drivers and 8192 KB
cc9195
    worth of DXE and UEFI drivers, compress them all with LZMA in one go, and
cc9195
    store the compressed result in 1712 KB, saving room in the flash device.
cc9195
cc9195
(3) The SECFV firmware volume (208 KB) is not compressed. It carries the
cc9195
    "volume top file" with the reset vector code, to end at 4 GB in
cc9195
    guest-physical address space, and the SEC phase driver (OvmfPkg/Sec).
cc9195
cc9195
    The last 16 bytes of the volume top file (mapped directly under 4 GB)
cc9195
    contain a NOP slide and a jump instruction. This is where QEMU starts
cc9195
    executing the firmware, at address 0xFFFF_FFF0. The reset vector and the
cc9195
    SEC driver run from flash directly.
cc9195
cc9195
    The SEC driver locates FVMAIN_COMPACT in the flash, and decompresses the
cc9195
    main firmware image to RAM. The rest of OVMF (PEI, DXE, BDS phases) run
cc9195
    from RAM.
cc9195
cc9195
As already mentioned, the OVMF.fd file is mapped by qemu's
cc9195
"hw/block/pflash_cfi01.c" device just under 4 GB in guest-physical address
cc9195
space, according to the command line option
cc9195
cc9195
  -drive if=pflash,format=raw,file=fedora.flash
cc9195
cc9195
(refer to the Example qemu invocation). This is a "ROMD device", which can
cc9195
switch out of "ROMD mode" and back into it.
cc9195
cc9195
Namely, in the default ROMD mode, the guest-physical address range backed by
cc9195
the flash device reads and executes as ROM (it does not trap from KVM to QEMU).
cc9195
The first write access in this mode traps to QEMU, and flips the device out of
cc9195
ROMD mode.
cc9195
cc9195
In non-ROMD mode, the flash chip is programmed by storing CFI (Common Flash
cc9195
Interface) command values at the flash-covered addresses; both reads and writes
cc9195
trap to QEMU, and the flash contents are modified and synchronized to the
cc9195
host-side file. A special CFI command flips the flash device back to ROMD mode.
cc9195
cc9195
Qemu implements the above based on the KVM_CAP_READONLY_MEM / KVM_MEM_READONLY
cc9195
KVM features, and OVMF puts it to use in its EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
cc9195
implementation, under "OvmfPkg/QemuFlashFvbServicesRuntimeDxe".
cc9195
cc9195
IMPORTANT: Never pass OVMF.fd to qemu with the -bios option. That option maps
cc9195
the firmware image as ROM into the guest's address space, and forces OVMF to
cc9195
emulate non-volatile variables with a fallback driver that is bound to have
cc9195
insufficient and confusing semantics.
cc9195
cc9195
The 128 KB firmware volume with the variable store, discussed under (1), is
cc9195
also built as a separate host-side file, named "OVMF_VARS.fd". The "rest" is
cc9195
built into a third file, "OVMF_CODE.fd", which is only 1920 KB in size. The
cc9195
variable store is mapped into its usual location, at 4 GB - 2 MB = 0xFFE0_0000,
cc9195
through the following qemu options:
cc9195
cc9195
  -drive if=pflash,format=raw,readonly,file=OVMF_CODE.fd   \
cc9195
  -drive if=pflash,format=raw,file=fedora.varstore.fd
cc9195
cc9195
This way qemu configures two flash chips consecutively, with start addresses
cc9195
growing downwards, which is transparent to OVMF.
cc9195
cc9195
[RHEL] Red Hat Enterprise Linux 7.1 ships a Secure Boot-enabled, X64, DEBUG
cc9195
       firmware only. Furthermore, only the split files ("OVMF_VARS.fd" and
cc9195
       "OVMF_CODE.fd") are available.
cc9195
cc9195
S3 (suspend to RAM and resume)
cc9195
------------------------------
cc9195
cc9195
As noted in Example qemu invocation, the
cc9195
cc9195
  -global PIIX4_PM.disable_s3=0
cc9195
cc9195
command line option tells qemu and OVMF if the user would like to enable S3
cc9195
support. (This is corresponds to the /domain/pm/suspend-to-mem/@enabled libvirt
cc9195
domain XML attribute.)
cc9195
cc9195
Implementing / orchestrating S3 was a considerable community effort in OVMF. A
cc9195
detailed description exceeds the scope of this report; we only make a few
cc9195
statements.
cc9195
cc9195
(1) S3-related PPIs and protocols are well documented in the PI specification.
cc9195
cc9195
(2) Edk2 contains most modules that are needed to implement S3 on a given
cc9195
    platform. One abstraction that is central to the porting / extending of the
cc9195
    S3-related modules to a new platform is the LockBox library interface,
cc9195
    which a specific platform can fill in by implementing its own LockBox
cc9195
    library instance.
cc9195
cc9195
    The LockBox library provides a privileged name-value store (to be addressed
cc9195
    by GUIDs). The privilege separation stretches between the firmware and the
cc9195
    operating system. That is, the S3-related machinery of the firmware saves
cc9195
    some items in the LockBox securely, under well-known GUIDs, before booting
cc9195
    the operating system. During resume (which is a form of warm reset), the
cc9195
    firmware is activated again, and retrieves items from the LockBox. Before
cc9195
    jumping to the OS's resume vector, the LockBox is secured again.
cc9195
cc9195
    We'll return to this later when we separately discuss SMRAM and SMM.
cc9195
cc9195
(3) During resume, the DXE and later phases are never reached; only the reset
cc9195
    vector, and the SEC and PEI phases of the firmware run. The platform is
cc9195
    supposed to detect a resume in progress during PEI, and to store that fact
cc9195
    in the BootMode field of the Phase Handoff Information Table (PHIT) HOB.
cc9195
    OVMF keys this off the CMOS, see OvmfPkg/PlatformPei.
cc9195
cc9195
    At the end of PEI, the DXE IPL PEIM (Initial Program Load PEI Module, see
cc9195
    MdeModulePkg/Core/DxeIplPeim) examines the Boot Mode, and if it says "S3
cc9195
    resume in progress", then the IPL branches to the PEIM that exports
cc9195
    EFI_PEI_S3_RESUME2_PPI (provided by UefiCpuPkg/Universal/Acpi/S3Resume2Pei)
cc9195
    rather than loading the DXE core.
cc9195
cc9195
    S3Resume2Pei executes the technical steps of the resumption, relying on the
cc9195
    contents of the LockBox.
cc9195
cc9195
(4) During first boot (or after a normal platform reset), when DXE does run,
cc9195
    hardware drivers in the DXE phase are encouraged to "stash" their hardware
cc9195
    configuration steps (eg. accesses to PCI config space, I/O ports, memory
cc9195
    mapped addresses, and so on) in a centrally maintained, so called "S3 boot
cc9195
    script". Hardware accesses are represented with opcodes of a special binary
cc9195
    script language.
cc9195
cc9195
    This boot script is to be replayed during resume, by S3Resume2Pei. The
cc9195
    general goal is to bring back hardware devices -- which have been powered
cc9195
    off during suspend -- to their original after-first-boot state, and in
cc9195
    particular, to do so quickly.
cc9195
cc9195
    At the moment, OVMF saves only one opcode in the S3 resume boot script: an
cc9195
    INFORMATION opcode, with contents 0xDEADBEEF (in network byte order). The
cc9195
    consensus between Linux developers seems to be that boot firmware is only
cc9195
    responsible for restoring basic chipset state, which OVMF does during PEI
cc9195
    anyway, independently of S3 vs. normal reset. (One example is the power
cc9195
    management registers of the i440fx chipset.) Device and peripheral state is
cc9195
    the responsibility of the runtime operating system.
cc9195
cc9195
    Although an experimental OVMF S3 boot script was at one point captured for
cc9195
    the virtual Cirrus VGA card, such a boot script cannot follow eg. video
cc9195
    mode changes effected by the OS. Hence the operating system can never avoid
cc9195
    restoring device state, and most Linux display drivers (eg. stdvga, QXL)
cc9195
    already cover S3 resume fully.
cc9195
cc9195
    The XDDM and WDDM driver models used under Windows OSes seem to recognize
cc9195
    this notion of runtime OS responsibility as well. (See the list of OSes
cc9195
    supported by OVMF in a separate section.)
cc9195
cc9195
(5) The S3 suspend/resume data flow in OVMF is included here tersely, for
cc9195
    interested developers.
cc9195
cc9195
    (a) BdsLibBootViaBootOption()
cc9195
          EFI_ACPI_S3_SAVE_PROTOCOL [AcpiS3SaveDxe]
cc9195
          - saves ACPI S3 Context to LockBox  ---------------------+
cc9195
            (including FACS address -- FACS ACPI table             |
cc9195
            contains OS waking vector)                             |
cc9195
                                                                   |
cc9195
          - prepares boot script:                                  |
cc9195
            EFI_S3_SAVE_STATE_PROTOCOL.Write() [S3SaveStateDxe]    |
cc9195
              S3BootScriptLib [PiDxeS3BootScriptLib]               |
cc9195
              - opcodes & arguments are saved in NVS.  --+         |
cc9195
                                                         |         |
cc9195
          - issues a notification by installing          |         |
cc9195
            EFI_DXE_SMM_READY_TO_LOCK_PROTOCOL           |         |
cc9195
                                                         |         |
cc9195
    (b) EFI_S3_SAVE_STATE_PROTOCOL [S3SaveStateDxe]      |         |
cc9195
          S3BootScriptLib [PiDxeS3BootScriptLib]         |         |
cc9195
          - closes script with special opcode  <---------+         |
cc9195
          - script is available in non-volatile memory             |
cc9195
            via PcdS3BootScriptTablePrivateDataPtr  --+            |
cc9195
                                                      |            |
cc9195
        BootScriptExecutorDxe                         |            |
cc9195
          S3BootScriptLib [PiDxeS3BootScriptLib]      |            |
cc9195
          - Knows about boot script location by  <----+            |
cc9195
            synchronizing with the other library                   |
cc9195
            instance via                                           |
cc9195
            PcdS3BootScriptTablePrivateDataPtr.                    |
cc9195
          - Copies relocated image of itself to                    |
cc9195
            reserved memory. --------------------------------+     |
cc9195
          - Saved image contains pointer to boot script.  ---|--+  |
cc9195
                                                             |  |  |
cc9195
    Runtime:                                                 |  |  |
cc9195
                                                             |  |  |
cc9195
    (c) OS is booted, writes OS waking vector to FACS,       |  |  |
cc9195
        suspends machine                                     |  |  |
cc9195
                                                             |  |  |
cc9195
    S3 Resume (PEI):                                         |  |  |
cc9195
                                                             |  |  |
cc9195
    (d) PlatformPei sets S3 Boot Mode based on CMOS          |  |  |
cc9195
                                                             |  |  |
cc9195
    (e) DXE core is skipped and EFI_PEI_S3_RESUME2 is        |  |  |
cc9195
        called as last step of PEI                           |  |  |
cc9195
                                                             |  |  |
cc9195
    (f) S3Resume2Pei retrieves from LockBox:                 |  |  |
cc9195
        - ACPI S3 Context (path to FACS)  <------------------|--|--+
cc9195
                                          |                  |  |
cc9195
                                          +------------------|--|--+
cc9195
        - Boot Script Executor Image  <----------------------+  |  |
cc9195
                                                                |  |
cc9195
    (g) BootScriptExecutorDxe                                   |  |
cc9195
          S3BootScriptLib [PiDxeS3BootScriptLib]                |  |
cc9195
          - executes boot script  <-----------------------------+  |
cc9195
                                                                   |
cc9195
    (h) OS waking vector available from ACPI S3 Context / FACS  <--+
cc9195
        is called
cc9195
cc9195
A comprehensive memory map of OVMF
cc9195
----------------------------------
cc9195
cc9195
The following section gives a detailed analysis of memory ranges below 4 GB
cc9195
that OVMF statically uses.
cc9195
cc9195
In the rightmost column, the PCD entry is identified by which the source refers
cc9195
to the address or size in question.
cc9195
cc9195
The flash-covered range has been discussed previously in "Firmware image
cc9195
structure", therefore we include it only for completeness. Due to the fact that
cc9195
this range is always backed by a memory mapped device (and never RAM), it is
cc9195
unaffected by S3 (suspend to RAM and resume).
cc9195
cc9195
+--------------------------+ 4194304 KB
cc9195
|                          |
cc9195
|          SECFV           | size: 208 KB
cc9195
|                          |
cc9195
+--------------------------+ 4194096 KB
cc9195
|                          |
cc9195
|      FVMAIN_COMPACT      | size: 1712 KB
cc9195
|                          |
cc9195
+--------------------------+ 4192384 KB
cc9195
|                          |
cc9195
|      variable store      | size: 64 KB   PcdFlashNvStorageFtwSpareSize
cc9195
|        spare area        |
cc9195
|                          |
cc9195
+--------------------------+ 4192320 KB    PcdOvmfFlashNvStorageFtwSpareBase
cc9195
|                          |
cc9195
|    FTW working block     | size: 4 KB    PcdFlashNvStorageFtwWorkingSize
cc9195
|                          |
cc9195
+--------------------------+ 4192316 KB    PcdOvmfFlashNvStorageFtwWorkingBase
cc9195
|                          |
cc9195
|       Event log of       | size: 4 KB    PcdOvmfFlashNvStorageEventLogSize
cc9195
|   non-volatile storage   |
cc9195
|                          |
cc9195
+--------------------------+ 4192312 KB    PcdOvmfFlashNvStorageEventLogBase
cc9195
|                          |
cc9195
|      variable store      | size: 56 KB   PcdFlashNvStorageVariableSize
cc9195
|                          |
cc9195
+--------------------------+ 4192256 KB    PcdOvmfFlashNvStorageVariableBase
cc9195
cc9195
The flash-mapped image of OVMF.fd covers the entire structure above (2048 KB).
cc9195
cc9195
When using the split files, the address 4192384 KB
cc9195
(PcdOvmfFlashNvStorageFtwSpareBase + PcdFlashNvStorageFtwSpareSize) is the
cc9195
boundary between the mapped images of OVMF_VARS.fd (56 KB + 4 KB + 4 KB + 64 KB
cc9195
= 128 KB) and OVMF_CODE.fd (1712 KB + 208 KB = 1920 KB).
cc9195
cc9195
With regard to RAM that is statically used by OVMF, S3 (suspend to RAM and
cc9195
resume) complicates matters. Many ranges have been introduced only to support
cc9195
S3, hence for all ranges below, the following questions will be audited:
cc9195
cc9195
(a) when and how a given range is initialized after first boot of the VM,
cc9195
(b) how it is protected from memory allocations during DXE,
cc9195
(c) how it is protected from the OS,
cc9195
(d) how it is accessed on the S3 resume path,
cc9195
(e) how it is accessed on the warm reset path.
cc9195
cc9195
Importantly, the term "protected" is meant as protection against inadvertent
cc9195
reallocations and overwrites by co-operating DXE and OS modules. It does not
cc9195
imply security against malicious code.
cc9195
cc9195
+--------------------------+ 17408 KB
cc9195
|                          |
cc9195
|DXEFV from FVMAIN_COMPACT | size: 8192 KB PcdOvmfDxeMemFvSize
cc9195
|  decompressed firmware   |
cc9195
| volume with DXE modules  |
cc9195
|                          |
cc9195
+--------------------------+ 9216 KB       PcdOvmfDxeMemFvBase
cc9195
|                          |
cc9195
|PEIFV from FVMAIN_COMPACT | size: 896 KB  PcdOvmfPeiMemFvSize
cc9195
|  decompressed firmware   |
cc9195
| volume with PEI modules  |
cc9195
|                          |
cc9195
+--------------------------+ 8320 KB       PcdOvmfPeiMemFvBase
cc9195
|                          |
cc9195
| permanent PEI memory for | size: 32 KB   PcdS3AcpiReservedMemorySize
cc9195
|   the S3 resume path     |
cc9195
|                          |
cc9195
+--------------------------+ 8288 KB       PcdS3AcpiReservedMemoryBase
cc9195
|                          |
cc9195
|  temporary SEC/PEI heap  | size: 32 KB   PcdOvmfSecPeiTempRamSize
cc9195
|         and stack        |
cc9195
|                          |
cc9195
+--------------------------+ 8256 KB       PcdOvmfSecPeiTempRamBase
cc9195
|                          |
cc9195
|          unused          | size: 32 KB
cc9195
|                          |
cc9195
+--------------------------+ 8224 KB
cc9195
|                          |
cc9195
|      SEC's table of      | size: 4 KB    PcdGuidedExtractHandlerTableSize
cc9195
| GUIDed section handlers  |
cc9195
|                          |
cc9195
+--------------------------+ 8220 KB       PcdGuidedExtractHandlerTableAddress
cc9195
|                          |
cc9195
|     LockBox storage      | size: 4 KB    PcdOvmfLockBoxStorageSize
cc9195
|                          |
cc9195
+--------------------------+ 8216 KB       PcdOvmfLockBoxStorageBase
cc9195
|                          |
cc9195
| early page tables on X64 | size: 24 KB   PcdOvmfSecPageTablesSize
cc9195
|                          |
cc9195
+--------------------------+ 8192 KB       PcdOvmfSecPageTablesBase
cc9195
cc9195
(1) Early page tables on X64:
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    The range is filled in during the SEC phase
cc9195
    [OvmfPkg/ResetVector/Ia32/PageTables64.asm]. The CR3 register is verified
cc9195
    against the base address in SecCoreStartupWithStack()
cc9195
    [OvmfPkg/Sec/SecMain.c].
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    If S3 was enabled on the QEMU command line (see "-global
cc9195
    PIIX4_PM.disable_s3=0" earlier), then InitializeRamRegions()
cc9195
    [OvmfPkg/PlatformPei/MemDetect.c] protects the range with an AcpiNVS memory
cc9195
    allocation HOB, in PEI.
cc9195
cc9195
    If S3 was disabled, then this range is not protected. DXE's own page tables
cc9195
    are first built while still in PEI (see HandOffToDxeCore()
cc9195
    [MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c]). Those tables are located
cc9195
    in permanent PEI memory. After CR3 is switched over to them (which occurs
cc9195
    before jumping to the DXE core entry point), we don't have to preserve the
cc9195
    initial tables.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    If S3 is enabled, then (1b) reserves it from the OS too.
cc9195
cc9195
    If S3 is disabled, then the range needs no protection.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    It is rewritten same as in (1a), which is fine because (1c) reserved it.
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    It is rewritten same as in (1a).
cc9195
cc9195
(2) LockBox storage:
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    InitializeRamRegions() [OvmfPkg/PlatformPei/MemDetect.c] zeroes out the
cc9195
    area during PEI. This is correct but not strictly necessary, since on first
cc9195
    boot the area is zero-filled anyway.
cc9195
cc9195
    The LockBox signature of the area is filled in by the PEI module or DXE
cc9195
    driver that has been linked against OVMF's LockBoxLib and is run first. The
cc9195
    signature is written in LockBoxLibInitialize()
cc9195
    [OvmfPkg/Library/LockBoxLib/LockBoxLib.c].
cc9195
cc9195
    Any module calling SaveLockBox() [OvmfPkg/Library/LockBoxLib/LockBoxLib.c]
cc9195
    will co-populate this area.
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    If S3 is enabled, then InitializeRamRegions()
cc9195
    [OvmfPkg/PlatformPei/MemDetect.c] protects the range as AcpiNVS.
cc9195
cc9195
    Otherwise, the range is covered with a BootServicesData memory allocation
cc9195
    HOB.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    If S3 is enabled, then (2b) protects it sufficiently.
cc9195
cc9195
    Otherwise the range requires no runtime protection, and the
cc9195
    BootServicesData allocation type from (2b) ensures that the range will be
cc9195
    released to the OS.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    The S3 Resume PEIM restores data from the LockBox, which has been correctly
cc9195
    protected in (2c).
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    InitializeRamRegions() [OvmfPkg/PlatformPei/MemDetect.c] zeroes out the
cc9195
    range during PEI, effectively emptying the LockBox. Modules will
cc9195
    re-populate the LockBox as described in (2a).
cc9195
cc9195
(3) SEC's table of GUIDed section handlers
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    The following two library instances are linked into SecMain:
cc9195
    - IntelFrameworkModulePkg/Library/LzmaCustomDecompressLib,
cc9195
    - MdePkg/Library/BaseExtractGuidedSectionLib.
cc9195
cc9195
    The first library registers its LZMA decompressor plugin (which is a called
cc9195
    a "section handler") by calling the second library:
cc9195
cc9195
    LzmaDecompressLibConstructor() [GuidedSectionExtraction.c]
cc9195
      ExtractGuidedSectionRegisterHandlers() [BaseExtractGuidedSectionLib.c]
cc9195
cc9195
    The second library maintains its table of registered "section handlers", to
cc9195
    be indexed by GUID, in this fixed memory area, independently of S3
cc9195
    enablement.
cc9195
cc9195
    (The decompression of FVMAIN_COMPACT's FFS file section that contains the
cc9195
    PEIFV and DXEFV firmware volumes occurs with the LZMA decompressor
cc9195
    registered above. See (6) and (7) below.)
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    There is no need to protect this area from DXE: because nothing else in
cc9195
    OVMF links against BaseExtractGuidedSectionLib, the area loses its
cc9195
    significance as soon as OVMF progresses from SEC to PEI, therefore DXE is
cc9195
    allowed to overwrite the region.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    When S3 is enabled, we cover the range with an AcpiNVS memory allocation
cc9195
    HOB in InitializeRamRegions().
cc9195
cc9195
    When S3 is disabled, the range is not protected.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    The table of registered section handlers is again managed by
cc9195
    BaseExtractGuidedSectionLib linked into SecMain exclusively. Section
cc9195
    handler registrations update the table in-place (based on GUID matches).
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    If S3 is enabled, then the OS won't damage the table (due to (3c)), thus
cc9195
    see (3d).
cc9195
cc9195
    If S3 is disabled, then the OS has most probably overwritten the range with
cc9195
    its own data, hence (3a) -- complete reinitialization -- will come into
cc9195
    effect, based on the table signature check in BaseExtractGuidedSectionLib.
cc9195
cc9195
(4) temporary SEC/PEI heap and stack
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    The range is configured in [OvmfPkg/Sec/X64/SecEntry.S] and
cc9195
    SecCoreStartupWithStack() [OvmfPkg/Sec/SecMain.c]. The stack half is read &
cc9195
    written by the CPU transparently. The heap half is used for memory
cc9195
    allocations during PEI.
cc9195
cc9195
    Data is migrated out (to permanent PEI stack & memory) in (or soon after)
cc9195
    PublishPeiMemory() [OvmfPkg/PlatformPei/MemDetect.c].
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    It is not necessary to protect this range during DXE because its use ends
cc9195
    still in PEI.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    If S3 is enabled, then InitializeRamRegions()
cc9195
    [OvmfPkg/PlatformPei/MemDetect.c] reserves it as AcpiNVS.
cc9195
cc9195
    If S3 is disabled, then the range doesn't require protection.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    Same as in (4a), except the target area of the migration triggered by
cc9195
    PublishPeiMemory() [OvmfPkg/PlatformPei/MemDetect.c] is different -- see
cc9195
    (5).
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    Same as in (4a). The stack and heap halves both may contain garbage, but it
cc9195
    doesn't matter.
cc9195
cc9195
(5) permanent PEI memory for the S3 resume path
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    No particular initialization or use.
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    We don't need to protect this area during DXE.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    When S3 is enabled, InitializeRamRegions()
cc9195
    [OvmfPkg/PlatformPei/MemDetect.c] makes sure the OS stays away by covering
cc9195
    the range with an AcpiNVS memory allocation HOB.
cc9195
cc9195
    When S3 is disabled, the range needs no protection.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    PublishPeiMemory() installs the range as permanent RAM for PEI. The range
cc9195
    will serve as stack and will satisfy allocation requests during the rest of
cc9195
    PEI. OS data won't overlap due to (5c).
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    Same as (5a).
cc9195
cc9195
(6) PEIFV -- decompressed firmware volume with PEI modules
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    DecompressMemFvs() [OvmfPkg/Sec/SecMain.c] populates the area, by
cc9195
    decompressing the flash-mapped FVMAIN_COMPACT volume's contents. (Refer to
cc9195
    "Firmware image structure".)
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    When S3 is disabled, PeiFvInitialization() [OvmfPkg/PlatformPei/Fv.c]
cc9195
    covers the range with a BootServicesData memory allocation HOB.
cc9195
cc9195
    When S3 is enabled, the same is coverage is ensured, just with the stronger
cc9195
    AcpiNVS memory allocation type.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    When S3 is disabled, it is not necessary to keep the range from the OS.
cc9195
cc9195
    Otherwise the AcpiNVS type allocation from (6b) provides coverage.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    Rather than decompressing it again from FVMAIN_COMPACT, GetS3ResumePeiFv()
cc9195
    [OvmfPkg/Sec/SecMain.c] reuses the protected area for parsing / execution
cc9195
    from (6c).
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    Same as (6a).
cc9195
cc9195
(7) DXEFV -- decompressed firmware volume with DXE modules
cc9195
cc9195
  (a) when and how it is initialized after first boot of the VM
cc9195
cc9195
    Same as (6a).
cc9195
cc9195
  (b) how it is protected from memory allocations during DXE
cc9195
cc9195
    PeiFvInitialization() [OvmfPkg/PlatformPei/Fv.c] covers the range with a
cc9195
    BootServicesData memory allocation HOB.
cc9195
cc9195
  (c) how it is protected from the OS
cc9195
cc9195
    The OS is allowed to release and reuse this range.
cc9195
cc9195
  (d) how it is accessed on the S3 resume path
cc9195
cc9195
    It's not; DXE never runs during S3 resume.
cc9195
cc9195
  (e) how it is accessed on the warm reset path
cc9195
cc9195
    Same as in (7a).
cc9195
cc9195
Known Secure Boot limitations
cc9195
-----------------------------
cc9195
cc9195
Under "Motivation" we've mentioned that OVMF's Secure Boot implementation is
cc9195
not suitable for production use yet -- it's only good for development and
cc9195
testing of standards-conformant, non-malicious guest code (UEFI and operating
cc9195
system alike).
cc9195
cc9195
Now that we've examined the persistent flash device, the workings of S3, and
cc9195
the memory map, we can discuss two currently known shortcomings of OVMF's
cc9195
Secure Boot that in fact make it insecure. (Clearly problems other than these
cc9195
two might exist; the set of issues considered here is not meant to be
cc9195
exhaustive.)
cc9195
cc9195
One trait of Secure Boot is tamper-evidence. Secure Boot may not prevent
cc9195
malicious modification of software components (for example, operating system
cc9195
drivers), but by being the root of integrity on a platform, it can catch (or
cc9195
indirectly contribute to catching) unauthorized changes, by way of signature
cc9195
and certificate checks at the earliest phases of boot.
cc9195
cc9195
If an attacker can tamper with key material stored in authenticated and/or
cc9195
boot-time only persistent variables (for example, PK, KEK, db, dbt, dbx), then
cc9195
the intended security of this scheme is compromised. The UEFI 2.4A
cc9195
specification says
cc9195
cc9195
- in section 28.3.4:
cc9195
cc9195
  Platform Keys:
cc9195
cc9195
    The public key must be stored in non-volatile storage which is tamper and
cc9195
    delete resistant.
cc9195
cc9195
  Key Exchange Keys:
cc9195
cc9195
    The public key must be stored in non-volatile storage which is tamper
cc9195
    resistant.
cc9195
cc9195
- in section 28.6.1:
cc9195
cc9195
  The signature database variables db, dbt, and dbx must be stored in
cc9195
  tamper-resistant non-volatile storage.
cc9195
cc9195
(1) The combination of QEMU, KVM, and OVMF does not provide this kind of
cc9195
    resistance. The variable store in the emulated flash chip is directly
cc9195
    accessible to, and reprogrammable by, UEFI drivers, applications, and
cc9195
    operating systems.
cc9195
cc9195
(2) Under "S3 (suspend to RAM and resume)" we pointed out that the LockBox
cc9195
    storage must be similarly secure and tamper-resistant.
cc9195
cc9195
    On the S3 resume path, the PEIM providing EFI_PEI_S3_RESUME2_PPI
cc9195
    (UefiCpuPkg/Universal/Acpi/S3Resume2Pei) restores and interprets data from
cc9195
    the LockBox that has been saved there during boot. This PEIM, being part of
cc9195
    the firmware, has full access to the platform. If an operating system can
cc9195
    tamper with the contents of the LockBox, then at the next resume the
cc9195
    platform's integrity might be subverted.
cc9195
cc9195
    OVMF stores the LockBox in normal guest RAM (refer to the memory map
cc9195
    section above). Operating systems and third party UEFI drivers and UEFI
cc9195
    applications that respect the UEFI memory map will not inadvertently
cc9195
    overwrite the LockBox storage, but there's nothing to prevent eg. a
cc9195
    malicious kernel from modifying the LockBox.
cc9195
cc9195
One means to address these issues is SMM and SMRAM (System Management Mode and
cc9195
System Management RAM).
cc9195
cc9195
During boot and resume, the firmware can enter and leave SMM and access SMRAM.
cc9195
Before the DXE phase is left, and control is transferred to the BDS phase (when
cc9195
third party UEFI drivers and applications can be loaded, and an operating
cc9195
system can be loaded), SMRAM is locked in hardware, and subsequent modules
cc9195
cannot access it directly. (See EFI_DXE_SMM_READY_TO_LOCK_PROTOCOL.)
cc9195
cc9195
Once SMRAM has been locked, UEFI drivers and the operating system can enter SMM
cc9195
by raising a System Management Interrupt (SMI), at which point trusted code
cc9195
(part of the platform firmware) takes control. SMRAM is also unlocked by
cc9195
platform reset, at which point the boot firmware takes control again.
cc9195
cc9195
Variable store and LockBox in SMRAM
cc9195
-----------------------------------
cc9195
cc9195
Edk2 provides almost all components to implement the variable store and the
cc9195
LockBox in SMRAM. In this section we summarize ideas for utilizing those
cc9195
facilities.
cc9195
cc9195
The SMRAM and SMM infrastructure in edk2 is built up as follows:
cc9195
cc9195
(1) The platform hardware provides SMM / SMI / SMRAM.
cc9195
cc9195
    Qemu/KVM doesn't support these features currently and should implement them
cc9195
    in the longer term.
cc9195
cc9195
(2) The platform vendor (in this case, OVMF developers) implement device
cc9195
    drivers for the platform's System Management Mode:
cc9195
cc9195
    - EFI_SMM_CONTROL2_PROTOCOL: for raising a synchronous (and/or) periodic
cc9195
      SMI(s); that is, for entering SMM.
cc9195
cc9195
    - EFI_SMM_ACCESS2_PROTOCOL: for describing and accessing SMRAM.
cc9195
cc9195
    These protocols are documented in the PI Specification, Volume 4.
cc9195
cc9195
(3) The platform DSC file is to include the following platform-independent
cc9195
    modules:
cc9195
cc9195
    - MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf: SMM Initial Program Load
cc9195
    - MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf: SMM Core
cc9195
cc9195
(4) At this point, modules of type DXE_SMM_DRIVER can be loaded.
cc9195
cc9195
    Such drivers are privileged. They run in SMM, have access to SMRAM, and are
cc9195
    separated and switched from other drivers through SMIs. Secure
cc9195
    communication between unprivileged (non-SMM) and privileged (SMM) drivers
cc9195
    happens through EFI_SMM_COMMUNICATION_PROTOCOL (implemented by the SMM
cc9195
    Core, see (3)).
cc9195
cc9195
    DXE_SMM_DRIVER modules must sanitize their input (coming from unprivileged
cc9195
    drivers) carefully.
cc9195
cc9195
(5) The authenticated runtime variable services driver (for Secure Boot builds)
cc9195
    is located under "SecurityPkg/VariableAuthenticated/RuntimeDxe". OVMF
cc9195
    currently builds the driver (a DXE_RUNTIME_DRIVER module) with the
cc9195
    "VariableRuntimeDxe.inf" control file (refer to "OvmfPkg/OvmfPkgX64.dsc"),
cc9195
    which does not use SMM.
cc9195
cc9195
    The directory includes two more INF files:
cc9195
cc9195
    - VariableSmm.inf -- module type: DXE_SMM_DRIVER. A privileged driver that
cc9195
      runs in SMM and has access to SMRAM.
cc9195
cc9195
    - VariableSmmRuntimeDxe.inf -- module type: DXE_RUNTIME_DRIVER. A
cc9195
      non-privileged driver that implements the variable runtime services
cc9195
      (replacing the current "VariableRuntimeDxe.inf" file) by communicating
cc9195
      with the above privileged SMM half via EFI_SMM_COMMUNICATION_PROTOCOL.
cc9195
cc9195
(6) An SMRAM-based LockBox implementation needs to be discussed in two parts,
cc9195
    because the LockBox is accessed in both PEI and DXE.
cc9195
cc9195
    (a) During DXE, drivers save data in the LockBox. A save operation is
cc9195
        layered as follows:
cc9195
cc9195
        - The unprivileged driver wishing to store data in the LockBox links
cc9195
          against the "MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf"
cc9195
          library instance.
cc9195
cc9195
          The library allows the unprivileged driver to format requests for the
cc9195
          privileged SMM LockBox driver (see below), and to parse responses.
cc9195
cc9195
        - The privileged SMM LockBox driver is built from
cc9195
          "MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf". This
cc9195
          driver has module type DXE_SMM_DRIVER and can access SMRAM.
cc9195
cc9195
          The driver delegates command parsing and response formatting to
cc9195
          "MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf".
cc9195
cc9195
        - The above two halves (unprivileged and privileged) mirror what we've
cc9195
          seen in case of the variable service drivers, under (5).
cc9195
cc9195
    (b) In PEI, the S3 Resume PEIM (UefiCpuPkg/Universal/Acpi/S3Resume2Pei)
cc9195
        retrieves data from the LockBox.
cc9195
cc9195
        Presumably, S3Resume2Pei should be considered an "unprivileged PEIM",
cc9195
        and the SMRAM access should be layered as seen in DXE. Unfortunately,
cc9195
        edk2 does not implement all of the layers in PEI -- the code either
cc9195
        doesn't exist, or it is not open source:
cc9195
cc9195
  role         | DXE: protocol/module           | PEI: PPI/module
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  unprivileged | any                            | S3Resume2Pei.inf
cc9195
  driver       |                                |
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  command      | LIBRARY_CLASS = LockBoxLib     | LIBRARY_CLASS = LockBoxLib
cc9195
  formatting   |                                |
cc9195
  and response | SmmLockBoxDxeLib.inf           | SmmLockBoxPeiLib.inf
cc9195
  parsing      |                                |
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  privilege    | EFI_SMM_COMMUNICATION_PROTOCOL | EFI_PEI_SMM_COMMUNICATION_PPI
cc9195
  separation   |                                |
cc9195
               | PiSmmCore.inf                  | missing!
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  platform SMM | EFI_SMM_CONTROL2_PROTOCOL      | PEI_SMM_CONTROL_PPI
cc9195
  and SMRAM    | EFI_SMM_ACCESS2_PROTOCOL       | PEI_SMM_ACCESS_PPI
cc9195
  access       |                                |
cc9195
               | to be done in OVMF             | to be done in OVMF
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  command      | LIBRARY_CLASS = LockBoxLib     | LIBRARY_CLASS = LockBoxLib
cc9195
  parsing and  |                                |
cc9195
  response     | SmmLockBoxSmmLib.inf           | missing!
cc9195
  formatting   |                                |
cc9195
  -------------+--------------------------------+------------------------------
cc9195
  privileged   | SmmLockBox.inf                 | missing!
cc9195
  LockBox      |                                |
cc9195
  driver       |                                |
cc9195
cc9195
        Alternatively, in the future OVMF might be able to provide a LockBoxLib
cc9195
        instance (an SmmLockBoxPeiLib substitute) for S3Resume2Pei that
cc9195
        accesses SMRAM directly, eliminating the need for deeper layers in the
cc9195
        stack (that is, EFI_PEI_SMM_COMMUNICATION_PPI and deeper).
cc9195
cc9195
        In fact, a "thin" EFI_PEI_SMM_COMMUNICATION_PPI implementation whose
cc9195
        sole Communicate() member invariably returns EFI_NOT_STARTED would
cc9195
        cause the current SmmLockBoxPeiLib library instance to directly perform
cc9195
        full-depth SMRAM access and LockBox search, obviating the "missing"
cc9195
        cells. (With reference to A Tour Beyond BIOS: Implementing S3 Resume
cc9195
        with EDK2, by Jiewen Yao and Vincent Zimmer, October 2014.)
cc9195
cc9195
Select features
cc9195
---------------
cc9195
cc9195
In this section we'll browse the top-level "OvmfPkg" package directory, and
cc9195
discuss the more interesting drivers and libraries that have not been mentioned
cc9195
thus far.
cc9195
cc9195
X64-specific reset vector for OVMF
cc9195
..................................
cc9195
cc9195
The "OvmfPkg/ResetVector" directory customizes the reset vector (found in
cc9195
"UefiCpuPkg/ResetVector/Vtf0") for "OvmfPkgX64.fdf", that is, when the SEC/PEI
cc9195
phases run in 64-bit (ie. long) mode.
cc9195
cc9195
The reset vector's control flow looks roughly like:
cc9195
cc9195
  resetVector                               [Ia16/ResetVectorVtf0.asm]
cc9195
  EarlyBspInitReal16                        [Ia16/Init16.asm]
cc9195
  Main16                                    [Main.asm]
cc9195
    EarlyInit16                             [Ia16/Init16.asm]
cc9195
cc9195
    ; Transition the processor from
cc9195
    ; 16-bit real mode to 32-bit flat mode
cc9195
    TransitionFromReal16To32BitFlat         [Ia16/Real16ToFlat32.asm]
cc9195
cc9195
    ; Search for the
cc9195
    ; Boot Firmware Volume (BFV)
cc9195
    Flat32SearchForBfvBase                  [Ia32/SearchForBfvBase.asm]
cc9195
cc9195
    ; Search for the SEC entry point
cc9195
    Flat32SearchForSecEntryPoint            [Ia32/SearchForSecEntry.asm]
cc9195
cc9195
    %ifdef ARCH_IA32
cc9195
      ; Jump to the 32-bit SEC entry point
cc9195
    %else
cc9195
      ; Transition the processor
cc9195
      ; from 32-bit flat mode
cc9195
      ; to 64-bit flat mode
cc9195
      Transition32FlatTo64Flat              [Ia32/Flat32ToFlat64.asm]
cc9195
cc9195
        SetCr3ForPageTables64               [Ia32/PageTables64.asm]
cc9195
          ; set CR3 to page tables
cc9195
          ; built into the ROM image
cc9195
cc9195
        ; enable PAE
cc9195
        ; set LME
cc9195
        ; enable paging
cc9195
cc9195
      ; Jump to the 64-bit SEC entry point
cc9195
    %endif
cc9195
cc9195
On physical platforms, the initial page tables referenced by
cc9195
SetCr3ForPageTables64 are built statically into the flash device image, and are
cc9195
present in ROM at runtime. This is fine on physical platforms because the
cc9195
pre-built page table entries have the Accessed and Dirty bits set from the
cc9195
start.
cc9195
cc9195
Accordingly, for OVMF running in long mode on qemu/KVM, the initial page tables
cc9195
were mapped as a KVM_MEM_READONLY slot, as part of QEMU's pflash device (refer
cc9195
to "Firmware image structure" above).
cc9195
cc9195
In spite of the Accessed and Dirty bits being pre-set in the read-only,
cc9195
in-flash PTEs, in a virtual machine attempts are made to update said PTE bits,
cc9195
differently from physical hardware. The component attempting to update the
cc9195
read-only PTEs can be one of the following:
cc9195
cc9195
- The processor itself, if it supports nested paging, and the user enables that
cc9195
  processor feature,
cc9195
cc9195
- KVM code implementing shadow paging, otherwise.
cc9195
cc9195
The first case presents no user-visible symptoms, but the second case (KVM,
cc9195
shadow paging) used to cause a triple fault, prior to Linux commit ba6a354
cc9195
("KVM: mmu: allow page tables to be in read-only slots").
cc9195
cc9195
For compatibility with earlier KVM versions, the OvmfPkg/ResetVector directory
cc9195
adapts the generic reset vector code as follows:
cc9195
cc9195
      Transition32FlatTo64Flat         [UefiCpuPkg/.../Ia32/Flat32ToFlat64.asm]
cc9195
cc9195
        SetCr3ForPageTables64       [OvmfPkg/ResetVector/Ia32/PageTables64.asm]
cc9195
cc9195
          ; dynamically build the initial page tables in RAM, at address
cc9195
          ; PcdOvmfSecPageTablesBase (refer to the memory map above),
cc9195
          ; identity-mapping the first 4 GB of address space
cc9195
cc9195
          ; set CR3 to PcdOvmfSecPageTablesBase
cc9195
cc9195
        ; enable PAE
cc9195
        ; set LME
cc9195
        ; enable paging
cc9195
cc9195
This way the PTEs that earlier KVM versions try to update (during shadow
cc9195
paging) are located in a read-write memory slot, and the write attempts
cc9195
succeed.
cc9195
cc9195
Client library for QEMU's firmware configuration interface
cc9195
..........................................................
cc9195
cc9195
QEMU provides a write-only, 16-bit wide control port, and a read-write, 8-bit
cc9195
wide data port for exchanging configuration elements with the firmware.
cc9195
cc9195
The firmware writes a selector (a key) to the control port (0x510), and then
cc9195
reads the corresponding configuration data (produced by QEMU) from the data
cc9195
port (0x511).
cc9195
cc9195
If the selected entry is writable, the firmware may overwrite it. If QEMU has
cc9195
associated a callback with the entry, then when the entry is completely
cc9195
rewritten, QEMU runs the callback. (OVMF does not rewrite any entries at the
cc9195
moment.)
cc9195
cc9195
A number of selector values (keys) are predefined. In particular, key 0x19
cc9195
selects (returns) a directory of { name, selector, size } triplets, roughly
cc9195
speaking.
cc9195
cc9195
The firmware can request configuration elements by well-known name as well, by
cc9195
looking up the selector value first in the directory, by name, and then writing
cc9195
the selector to the control port. The number of bytes to read subsequently from
cc9195
the data port is known from the directory entry's "size" field.
cc9195
cc9195
By convention, directory entries (well-known symbolic names of configuration
cc9195
elements) are formatted as POSIX pathnames. For example, the array selected by
cc9195
the "etc/system-states" name indicates (among other things) whether the user
cc9195
enabled S3 support in QEMU.
cc9195
cc9195
The above interface is called "fw_cfg".
cc9195
cc9195
The binary data associated with a symbolic name is called an "fw_cfg file".
cc9195
cc9195
OVMF's fw_cfg client library is found in "OvmfPkg/Library/QemuFwCfgLib". OVMF
cc9195
discovers many aspects of the virtual system with it; we refer to a few
cc9195
examples below.
cc9195
cc9195
Guest ACPI tables
cc9195
.................
cc9195
cc9195
An operating system discovers a good amount of its hardware by parsing ACPI
cc9195
tables, and by interpreting ACPI objects and methods. On physical hardware, the
cc9195
platform vendor's firmware installs ACPI tables in memory that match both the
cc9195
hardware present in the system and the user's firmware configuration ("BIOS
cc9195
setup").
cc9195
cc9195
Under qemu/KVM, the owner of the (virtual) hardware configuration is QEMU.
cc9195
Hardware can easily be reconfigured on the command line. Furthermore, features
cc9195
like CPU hotplug, PCI hotplug, memory hotplug are continuously developed for
cc9195
QEMU, and operating systems need direct ACPI support to exploit these features.
cc9195
cc9195
For this reason, QEMU builds its own ACPI tables dynamically, in a
cc9195
self-descriptive manner, and exports them to the firmware through a complex,
cc9195
multi-file fw_cfg interface. It is rooted in the "etc/table-loader" fw_cfg
cc9195
file. (Further details of this interface are out of scope for this report.)
cc9195
cc9195
OVMF's AcpiPlatformDxe driver fetches the ACPI tables, and installs them for
cc9195
the guest OS with the EFI_ACPI_TABLE_PROTOCOL (which is in turn provided by the
cc9195
generic "MdeModulePkg/Universal/Acpi/AcpiTableDxe" driver).
cc9195
cc9195
For earlier QEMU versions and machine types (which we generally don't recommend
cc9195
for OVMF; see "Scope"), the "OvmfPkg/AcpiTables" directory contains a few
cc9195
static ACPI table templates. When the "etc/table-loader" fw_cfg file is
cc9195
unavailable, AcpiPlatformDxe installs these default tables (with a little bit
cc9195
of dynamic patching).
cc9195
cc9195
When OVMF runs in a Xen domU, AcpiTableDxe also installs ACPI tables that
cc9195
originate from the hypervisor's environment.
cc9195
cc9195
Guest SMBIOS tables
cc9195
...................
cc9195
cc9195
Quoting the SMBIOS Reference Specification,
cc9195
cc9195
  [...] the System Management BIOS Reference Specification addresses how
cc9195
  motherboard and system vendors present management information about their
cc9195
  products in a standard format [...]
cc9195
cc9195
In practice SMBIOS tables are just another set of tables that the platform
cc9195
vendor's firmware installs in RAM for the operating system, and, importantly,
cc9195
for management applications running on the OS. Without rehashing the "Guest
cc9195
ACPI tables" section in full, let's map the OVMF roles seen there from ACPI to
cc9195
SMBIOS:
cc9195
cc9195
  role                     | ACPI                    | SMBIOS
cc9195
  -------------------------+-------------------------+-------------------------
cc9195
  fw_cfg file              | etc/table-loader        | etc/smbios/smbios-tables
cc9195
  -------------------------+-------------------------+-------------------------
cc9195
  OVMF driver              | AcpiPlatformDxe         | SmbiosPlatformDxe
cc9195
  under "OvmfPkg"          |                         |
cc9195
  -------------------------+-------------------------+-------------------------
cc9195
  Underlying protocol,     | EFI_ACPI_TABLE_PROTOCOL | EFI_SMBIOS_PROTOCOL
cc9195
  implemented by generic   |                         |
cc9195
  driver under             | Acpi/AcpiTableDxe       | SmbiosDxe
cc9195
  "MdeModulePkg/Universal" |                         |
cc9195
  -------------------------+-------------------------+-------------------------
cc9195
  default tables available | yes                     | [RHEL] yes, Type0 and
cc9195
  for earlier QEMU machine |                         |        Type1 tables
cc9195
  types, with hot-patching |                         |
cc9195
  -------------------------+-------------------------+-------------------------
cc9195
  tables fetched in Xen    | yes                     | yes
cc9195
  domUs                    |                         |
cc9195
cc9195
Platform-specific boot policy
cc9195
.............................
cc9195
cc9195
OVMF's BDS (Boot Device Selection) phase is implemented by
cc9195
IntelFrameworkModulePkg/Universal/BdsDxe. Roughly speaking, this large driver:
cc9195
cc9195
- provides the EFI BDS architectural protocol (which DXE transfers control to
cc9195
  after dispatching all DXE drivers),
cc9195
cc9195
- connects drivers to devices,
cc9195
cc9195
- enumerates boot devices,
cc9195
cc9195
- auto-generates boot options,
cc9195
cc9195
- provides "BIOS setup" screens, such as:
cc9195
cc9195
  - Boot Manager, for booting an option,
cc9195
cc9195
  - Boot Maintenance Manager, for adding, deleting, and reordering boot
cc9195
    options, changing console properties etc,
cc9195
cc9195
  - Device Manager, where devices can register configuration forms, including
cc9195
cc9195
    - Secure Boot configuration forms,
cc9195
cc9195
    - OVMF's Platform Driver form (see under PlatformDxe).
cc9195
cc9195
Firmware that includes the "IntelFrameworkModulePkg/Universal/BdsDxe" driver
cc9195
can customize its behavior by providing an instance of the PlatformBdsLib
cc9195
library class. The driver links against this platform library, and the
cc9195
platform library can call Intel's BDS utility functions from
cc9195
"IntelFrameworkModulePkg/Library/GenericBdsLib".
cc9195
cc9195
OVMF's PlatformBdsLib instance can be found in
cc9195
"OvmfPkg/Library/PlatformBdsLib". The main function where the BdsDxe driver
cc9195
enters the library is PlatformBdsPolicyBehavior(). We mention two OVMF
cc9195
particulars here.
cc9195
cc9195
(1) OVMF is capable of loading kernel images directly from fw_cfg, matching
cc9195
    QEMU's -kernel, -initrd, and -append command line options. This feature is
cc9195
    useful for rapid, repeated Linux kernel testing, and is implemented in the
cc9195
    following call tree:
cc9195
cc9195
    PlatformBdsPolicyBehavior() [OvmfPkg/Library/PlatformBdsLib/BdsPlatform.c]
cc9195
      TryRunningQemuKernel() [OvmfPkg/Library/PlatformBdsLib/QemuKernel.c]
cc9195
        LoadLinux*() [OvmfPkg/Library/LoadLinuxLib/Linux.c]
cc9195
cc9195
    OvmfPkg/Library/LoadLinuxLib ports the efilinux bootloader project into
cc9195
    OvmfPkg.
cc9195
cc9195
(2) OVMF seeks to comply with the boot order specification passed down by QEMU
cc9195
    over fw_cfg.
cc9195
cc9195
    (a) About Boot Modes
cc9195
cc9195
      During the PEI phase, OVMF determines and stores the Boot Mode in the
cc9195
      PHIT HOB (already mentioned in "S3 (suspend to RAM and resume)"). The
cc9195
      boot mode is supposed to influence the rest of the system, for example it
cc9195
      distinguishes S3 resume (BOOT_ON_S3_RESUME) from a "normal" boot.
cc9195
cc9195
      In general, "normal" boots can be further differentiated from each other;
cc9195
      for example for speed reasons. When the firmware can tell during PEI that
cc9195
      the chassis has not been opened since last power-up, then it might want
cc9195
      to save time by not connecting all devices and not enumerating all boot
cc9195
      options from scratch; it could just rely on the stored results of the
cc9195
      last enumeration. The matching BootMode value, to be set during PEI,
cc9195
      would be BOOT_ASSUMING_NO_CONFIGURATION_CHANGES.
cc9195
cc9195
      OVMF only sets one of the following two boot modes, based on CMOS
cc9195
      contents:
cc9195
      - BOOT_ON_S3_RESUME,
cc9195
      - BOOT_WITH_FULL_CONFIGURATION.
cc9195
cc9195
      For BOOT_ON_S3_RESUME, please refer to "S3 (suspend to RAM and resume)".
cc9195
      The other boot mode supported by OVMF, BOOT_WITH_FULL_CONFIGURATION, is
cc9195
      an appropriate "catch-all" for a virtual machine, where hardware can
cc9195
      easily change from boot to boot.
cc9195
cc9195
    (b) Auto-generation of boot options
cc9195
cc9195
      Accordingly, when not resuming from S3 sleep (*), OVMF always connects
cc9195
      all devices, and enumerates all bootable devices as new boot options
cc9195
      (non-volatile variables called Boot####).
cc9195
cc9195
      (*) During S3 resume, DXE is not reached, hence BDS isn't either.
cc9195
cc9195
      The auto-enumerated boot options are stored in the BootOrder non-volatile
cc9195
      variable after any preexistent options. (Boot options may exist before
cc9195
      auto-enumeration eg. because the user added them manually with the Boot
cc9195
      Maintenance Manager or the efibootmgr utility. They could also originate
cc9195
      from an earlier auto-enumeration.)
cc9195
cc9195
      PlatformBdsPolicyBehavior()                   [OvmfPkg/.../BdsPlatform.c]
cc9195
        TryRunningQemuKernel()                       [OvmfPkg/.../QemuKernel.c]
cc9195
        BdsLibConnectAll()           [IntelFrameworkModulePkg/.../BdsConnect.c]
cc9195
        BdsLibEnumerateAllBootOption()  [IntelFrameworkModulePkg/.../BdsBoot.c]
cc9195
          BdsLibBuildOptionFromHandle() [IntelFrameworkModulePkg/.../BdsBoot.c]
cc9195
            BdsLibRegisterNewOption()   [IntelFrameworkModulePkg/.../BdsMisc.c]
cc9195
              //
cc9195
              // Append the new option number to the original option order
cc9195
              //
cc9195
cc9195
    (c) Relative UEFI device paths in boot options
cc9195
cc9195
      The handling of relative ("short-form") UEFI device paths is best
cc9195
      demonstrated through an example, and by quoting the UEFI 2.4A
cc9195
      specification.
cc9195
cc9195
      A short-form hard drive UEFI device path could be (displaying each device
cc9195
      path node on a separate line for readability):
cc9195
cc9195
        HD(1,GPT,14DD1CC5-D576-4BBF-8858-BAF877C8DF61,0x800,0x64000)/
cc9195
        \EFI\fedora\shim.efi
cc9195
cc9195
      This device path lacks prefix nodes (eg. hardware or messaging type
cc9195
      nodes) that would lead to the hard drive. During load option processing,
cc9195
      the above short-form or relative device path could be matched against the
cc9195
      following absolute device path:
cc9195
cc9195
        PciRoot(0x0)/
cc9195
        Pci(0x4,0x0)/
cc9195
        HD(1,GPT,14DD1CC5-D576-4BBF-8858-BAF877C8DF61,0x800,0x64000)/
cc9195
        \EFI\fedora\shim.efi
cc9195
cc9195
      The motivation for this type of device path matching / completion is to
cc9195
      allow the user to move around the hard drive (for example, to plug a
cc9195
      controller in a different PCI slot, or to expose the block device on a
cc9195
      different iSCSI path) and still enable the firmware to find the hard
cc9195
      drive.
cc9195
cc9195
      The UEFI specification says,
cc9195
cc9195
        9.3.6 Media Device Path
cc9195
        9.3.6.1 Hard Drive
cc9195
cc9195
          [...] Section 3.1.2 defines special rules for processing the Hard
cc9195
          Drive Media Device Path. These special rules enable a disk's location
cc9195
          to change and still have the system boot from the disk. [...]
cc9195
cc9195
        3.1.2 Load Option Processing
cc9195
cc9195
          [...] The boot manager must [...] support booting from a short-form
cc9195
          device path that starts with the first element being a hard drive
cc9195
          media device path [...]. The boot manager must use the GUID or
cc9195
          signature and partition number in the hard drive device path to match
cc9195
          it to a device in the system. If the drive supports the GPT
cc9195
          partitioning scheme the GUID in the hard drive media device path is
cc9195
          compared with the UniquePartitionGuid field of the GUID Partition
cc9195
          Entry [...]. If the drive supports the PC-AT MBR scheme the signature
cc9195
          in the hard drive media device path is compared with the
cc9195
          UniqueMBRSignature in the Legacy Master Boot Record [...]. If a
cc9195
          signature match is made, then the partition number must also be
cc9195
          matched. The hard drive device path can be appended to the matching
cc9195
          hardware device path and normal boot behavior can then be used. If
cc9195
          more than one device matches the hard drive device path, the boot
cc9195
          manager will pick one arbitrarily. Thus the operating system must
cc9195
          ensure the uniqueness of the signatures on hard drives to guarantee
cc9195
          deterministic boot behavior.
cc9195
cc9195
      Edk2 implements and exposes the device path completion logic in the
cc9195
      already referenced "IntelFrameworkModulePkg/Library/GenericBdsLib"
cc9195
      library, in the BdsExpandPartitionPartialDevicePathToFull() function.
cc9195
cc9195
    (d) Filtering and reordering the boot options based on fw_cfg
cc9195
cc9195
      Once we have an "all-inclusive", partly preexistent, partly freshly
cc9195
      auto-generated boot option list from bullet (b), OVMF loads QEMU's
cc9195
      requested boot order from fw_cfg, and filters and reorders the list from
cc9195
      (b) with it:
cc9195
cc9195
      PlatformBdsPolicyBehavior()                   [OvmfPkg/.../BdsPlatform.c]
cc9195
        TryRunningQemuKernel()                       [OvmfPkg/.../QemuKernel.c]
cc9195
        BdsLibConnectAll()           [IntelFrameworkModulePkg/.../BdsConnect.c]
cc9195
        BdsLibEnumerateAllBootOption()  [IntelFrameworkModulePkg/.../BdsBoot.c]
cc9195
        SetBootOrderFromQemu()                    [OvmfPkg/.../QemuBootOrder.c]
cc9195
cc9195
      According to the (preferred) "-device ...,bootindex=N" and the (legacy)
cc9195
      '-boot order=drives' command line options, QEMU requests a boot order
cc9195
      from the firmware through the "bootorder" fw_cfg file. (For a bootindex
cc9195
      example, refer to the "Example qemu invocation" section.)
cc9195
cc9195
      This fw_cfg file consists of OpenFirmware (OFW) device paths -- note: not
cc9195
      UEFI device paths! --, one per line. An example list is:
cc9195
cc9195
        /pci@i0cf8/scsi@4/disk@0,0
cc9195
        /pci@i0cf8/ide@1,1/drive@1/disk@0
cc9195
        /pci@i0cf8/ethernet@3/ethernet-phy@0
cc9195
cc9195
      OVMF filters and reorders the boot option list from bullet (b) with the
cc9195
      following nested loops algorithm:
cc9195
cc9195
        new_uefi_order := <empty>
cc9195
        for each qemu_ofw_path in QEMU's OpenFirmware device path list:
cc9195
          qemu_uefi_path_prefix := translate(qemu_ofw_path)
cc9195
cc9195
          for each boot_option in current_uefi_order:
cc9195
            full_boot_option := complete(boot_option)
cc9195
cc9195
            if match(qemu_uefi_path_prefix, full_boot_option):
cc9195
              append(new_uefi_order, boot_option)
cc9195
              break
cc9195
cc9195
        for each unmatched boot_option in current_uefi_order:
cc9195
          if survives(boot_option):
cc9195
            append(new_uefi_order, boot_option)
cc9195
cc9195
        current_uefi_order := new_uefi_order
cc9195
cc9195
      OVMF iterates over QEMU's OFW device paths in order, translates each to a
cc9195
      UEFI device path prefix, tries to match the translated prefix against the
cc9195
      UEFI boot options (which are completed from relative form to absolute
cc9195
      form for the purpose of prefix matching), and if there's a match, the
cc9195
      matching boot option is appended to the new boot order (which starts out
cc9195
      empty).
cc9195
cc9195
      (We elaborate on the translate() function under bullet (e). The
cc9195
      complete() function has been explained in bullet (c).)
cc9195
cc9195
      In addition, UEFI boot options that remain unmatched after filtering and
cc9195
      reordering are post-processed, and some of them "survive". Due to the
cc9195
      fact that OpenFirmware device paths have less expressive power than their
cc9195
      UEFI counterparts, some UEFI boot options are simply inexpressible (hence
cc9195
      unmatchable) by the nested loops algorithm.
cc9195
cc9195
      An important example is the memory-mapped UEFI shell, whose UEFI device
cc9195
      path is inexpressible by QEMU's OFW device paths:
cc9195
cc9195
        MemoryMapped(0xB,0x900000,0x10FFFFF)/
cc9195
        FvFile(7C04A583-9E3E-4F1C-AD65-E05268D0B4D1)
cc9195
cc9195
      (Side remark: notice that the address range visible in the MemoryMapped()
cc9195
      node corresponds to DXEFV under "comprehensive memory map of OVMF"! In
cc9195
      addition, the FvFile() node's GUID originates from the FILE_GUID entry of
cc9195
      "ShellPkg/Application/Shell/Shell.inf".)
cc9195
cc9195
      The UEFI shell can be booted by pressing ESC in OVMF on the TianoCore
cc9195
      splash screen, and navigating to Boot Manager | EFI Internal Shell. If
cc9195
      the "survival policy" was not implemented, the UEFI shell's boot option
cc9195
      would always be filtered out.
cc9195
cc9195
      The current "survival policy" preserves all boot options that start with
cc9195
      neither PciRoot() nor HD().
cc9195
cc9195
    (e) Translating QEMU's OpenFirmware device paths to UEFI device path
cc9195
        prefixes
cc9195
cc9195
      In this section we list the (strictly heuristical) mappings currently
cc9195
      performed by OVMF.
cc9195
cc9195
      The "prefix only" nature of the translation output is rooted minimally in
cc9195
      the fact that QEMU's OpenFirmware device paths cannot carry pathnames
cc9195
      within filesystems. There's no way to specify eg.
cc9195
cc9195
        \EFI\fedora\shim.efi
cc9195
cc9195
      in an OFW device path, therefore a UEFI device path translated from an
cc9195
      OFW device path can at best be a prefix (not a full match) of a UEFI
cc9195
      device path that ends with "\EFI\fedora\shim.efi".
cc9195
cc9195
      - IDE disk, IDE CD-ROM:
cc9195
cc9195
        OpenFirmware device path:
cc9195
cc9195
          /pci@i0cf8/ide@1,1/drive@0/disk@0
cc9195
               ^         ^ ^       ^      ^
cc9195
               |         | |       |      master or slave
cc9195
               |         | |       primary or secondary
cc9195
               |         PCI slot & function holding IDE controller
cc9195
               PCI root at system bus port, PIO
cc9195
cc9195
        UEFI device path prefix:
cc9195
cc9195
          PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
cc9195
                                                       ^
cc9195
                                                       fixed LUN
cc9195
cc9195
      - Floppy disk:
cc9195
cc9195
        OpenFirmware device path:
cc9195
cc9195
          /pci@i0cf8/isa@1/fdc@03f0/floppy@0
cc9195
               ^         ^     ^           ^
cc9195
               |         |     |           A: or B:
cc9195
               |         |     ISA controller io-port (hex)
cc9195
               |         PCI slot holding ISA controller
cc9195
               PCI root at system bus port, PIO
cc9195
cc9195
        UEFI device path prefix:
cc9195
cc9195
          PciRoot(0x0)/Pci(0x1,0x0)/Floppy(0x0)
cc9195
                                           ^
cc9195
                                           ACPI UID (A: or B:)
cc9195
cc9195
      - Virtio-block disk:
cc9195
cc9195
        OpenFirmware device path:
cc9195
cc9195
          /pci@i0cf8/scsi@6[,3]/disk@0,0
cc9195
               ^          ^  ^       ^ ^
cc9195
               |          |  |       fixed
cc9195
               |          |  PCI function corresponding to disk (optional)
cc9195
               |          PCI slot holding disk
cc9195
               PCI root at system bus port, PIO
cc9195
cc9195
        UEFI device path prefixes (dependent on the presence of a nonzero PCI
cc9195
        function in the OFW device path):
cc9195
cc9195
          PciRoot(0x0)/Pci(0x6,0x0)/HD(
cc9195
          PciRoot(0x0)/Pci(0x6,0x3)/HD(
cc9195
cc9195
      - Virtio-scsi disk and virtio-scsi passthrough:
cc9195
cc9195
        OpenFirmware device path:
cc9195
cc9195
          /pci@i0cf8/scsi@7[,3]/channel@0/disk@2,3
cc9195
               ^          ^             ^      ^ ^
cc9195
               |          |             |      | LUN
cc9195
               |          |             |      target
cc9195
               |          |             channel (unused, fixed 0)
cc9195
               |          PCI slot[, function] holding SCSI controller
cc9195
               PCI root at system bus port, PIO
cc9195
cc9195
        UEFI device path prefixes (dependent on the presence of a nonzero PCI
cc9195
        function in the OFW device path):
cc9195
cc9195
          PciRoot(0x0)/Pci(0x7,0x0)/Scsi(0x2,0x3)
cc9195
          PciRoot(0x0)/Pci(0x7,0x3)/Scsi(0x2,0x3)
cc9195
cc9195
      - Emulated and passed-through (physical) network cards:
cc9195
cc9195
        OpenFirmware device path:
cc9195
cc9195
          /pci@i0cf8/ethernet@3[,2]
cc9195
               ^              ^
cc9195
               |              PCI slot[, function] holding Ethernet card
cc9195
               PCI root at system bus port, PIO
cc9195
cc9195
        UEFI device path prefixes (dependent on the presence of a nonzero PCI
cc9195
        function in the OFW device path):
cc9195
cc9195
          PciRoot(0x0)/Pci(0x3,0x0)
cc9195
          PciRoot(0x0)/Pci(0x3,0x2)
cc9195
cc9195
Virtio drivers
cc9195
..............
cc9195
cc9195
UEFI abstracts various types of hardware resources into protocols, and allows
cc9195
firmware developers to implement those protocols in device drivers. The Virtio
cc9195
Specification defines various types of virtual hardware for virtual machines.
cc9195
Connecting the two specifications, OVMF provides UEFI drivers for QEMU's
cc9195
virtio-block, virtio-scsi, and virtio-net devices.
cc9195
cc9195
The following diagram presents the protocol and driver stack related to Virtio
cc9195
devices in edk2 and OVMF. Each node in the graph identifies a protocol and/or
cc9195
the edk2 driver that produces it. Nodes on the top are more abstract.
cc9195
cc9195
  EFI_BLOCK_IO_PROTOCOL                             EFI_SIMPLE_NETWORK_PROTOCOL
cc9195
  [OvmfPkg/VirtioBlkDxe]                              [OvmfPkg/VirtioNetDxe]
cc9195
             |                                                   |
cc9195
             |         EFI_EXT_SCSI_PASS_THRU_PROTOCOL           |
cc9195
             |             [OvmfPkg/VirtioScsiDxe]               |
cc9195
             |                        |                          |
cc9195
             +------------------------+--------------------------+
cc9195
                                      |
cc9195
                           VIRTIO_DEVICE_PROTOCOL
cc9195
                                      |
cc9195
                +---------------------+---------------------+
cc9195
                |                                           |
cc9195
  [OvmfPkg/VirtioPciDeviceDxe]                  [custom platform drivers]
cc9195
                |                                           |
cc9195
                |                                           |
cc9195
       EFI_PCI_IO_PROTOCOL                [OvmfPkg/Library/VirtioMmioDeviceLib]
cc9195
 [MdeModulePkg/Bus/Pci/PciBusDxe]              direct MMIO register access
cc9195
cc9195
The top three drivers produce standard UEFI abstractions: the Block IO
cc9195
Protocol, the Extended SCSI Pass Thru Protocol, and the Simple Network
cc9195
Protocol, for virtio-block, virtio-scsi, and virtio-net devices, respectively.
cc9195
cc9195
Comparing these device-specific virtio drivers to each other, we can determine:
cc9195
cc9195
- They all conform to the UEFI Driver Model. This means that their entry point
cc9195
  functions don't immediately start to search for devices and to drive them,
cc9195
  they only register instances of the EFI_DRIVER_BINDING_PROTOCOL. The UEFI
cc9195
  Driver Model then enumerates devices and chains matching drivers
cc9195
  automatically.
cc9195
cc9195
- They are as minimal as possible, while remaining correct (refer to source
cc9195
  code comments for details). For example, VirtioBlkDxe and VirtioScsiDxe both
cc9195
  support only one request in flight.
cc9195
cc9195
  In theory, VirtioBlkDxe could implement EFI_BLOCK_IO2_PROTOCOL, which allows
cc9195
  queueing. Similarly, VirtioScsiDxe does not support the non-blocking mode of
cc9195
  EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru(). (Which is permitted by the UEFI
cc9195
  specification.) Both VirtioBlkDxe and VirtioScsiDxe delegate synchronous
cc9195
  request handling to "OvmfPkg/Library/VirtioLib". This limitation helps keep
cc9195
  the implementation simple, and testing thus far seems to imply satisfactory
cc9195
  performance, for a virtual boot firmware.
cc9195
cc9195
  VirtioNetDxe cannot avoid queueing, because EFI_SIMPLE_NETWORK_PROTOCOL
cc9195
  requires it on the interface level. Consequently, VirtioNetDxe is
cc9195
  significantly more complex than VirtioBlkDxe and VirtioScsiDxe. Technical
cc9195
  notes are provided in "OvmfPkg/VirtioNetDxe/TechNotes.txt".
cc9195
cc9195
- None of these drivers access hardware directly. Instead, the Virtio Device
cc9195
  Protocol (OvmfPkg/Include/Protocol/VirtioDevice.h) collects / extracts virtio
cc9195
  operations defined in the Virtio Specification, and these backend-independent
cc9195
  virtio device drivers go through the abstract VIRTIO_DEVICE_PROTOCOL.
cc9195
cc9195
  IMPORTANT: the VIRTIO_DEVICE_PROTOCOL is not a standard UEFI protocol. It is
cc9195
  internal to edk2 and not described in the UEFI specification. It should only
cc9195
  be used by drivers and applications that live inside the edk2 source tree.
cc9195
cc9195
Currently two providers exist for VIRTIO_DEVICE_PROTOCOL:
cc9195
cc9195
- The first one is the "more traditional" virtio-pci backend, implemented by
cc9195
  OvmfPkg/VirtioPciDeviceDxe. This driver also complies with the UEFI Driver
cc9195
  Model. It consumes an instance of the EFI_PCI_IO_PROTOCOL, and, if the PCI
cc9195
  device/function under probing appears to be a virtio device, it produces a
cc9195
  Virtio Device Protocol instance for it. The driver translates abstract virtio
cc9195
  operations to PCI accesses.
cc9195
cc9195
- The second provider, the virtio-mmio backend, is a library, not a driver,
cc9195
  living in OvmfPkg/Library/VirtioMmioDeviceLib. This library translates
cc9195
  abstract virtio operations to MMIO accesses.
cc9195
cc9195
  The virtio-mmio backend is only a library -- rather than a standalone, UEFI
cc9195
  Driver Model-compliant driver -- because the type of resource it consumes, an
cc9195
  MMIO register block base address, is not enumerable.
cc9195
cc9195
  In other words, while the PCI root bridge driver and the PCI bus driver
cc9195
  produce instances of EFI_PCI_IO_PROTOCOL automatically, thereby enabling the
cc9195
  UEFI Driver Model to probe devices and stack up drivers automatically, no
cc9195
  such enumeration exists for MMIO register blocks.
cc9195
cc9195
  For this reason, VirtioMmioDeviceLib needs to be linked into thin, custom
cc9195
  platform drivers that dispose over this kind of information. As soon as a
cc9195
  driver knows about the MMIO register block base addresses, it can pass each
cc9195
  to the library, and then the VIRTIO_DEVICE_PROTOCOL will be instantiated
cc9195
  (assuming a valid virtio-mmio register block of course). From that point on
cc9195
  the UEFI Driver Model again takes care of the chaining.
cc9195
cc9195
  Typically, such a custom driver does not conform to the UEFI Driver Model
cc9195
  (because that would presuppose auto-enumeration for MMIO register blocks).
cc9195
  Hence it has the following responsibilities:
cc9195
cc9195
  - it shall behave as a "wrapper" UEFI driver around the library,
cc9195
cc9195
  - it shall know virtio-mmio base addresses,
cc9195
cc9195
  - in its entry point function, it shall create a new UEFI handle with an
cc9195
    instance of the EFI_DEVICE_PATH_PROTOCOL for each virtio-mmio device it
cc9195
    knows the base address for,
cc9195
cc9195
  - it shall call VirtioMmioInstallDevice() on those handles, with the
cc9195
    corresponding base addresses.
cc9195
cc9195
  OVMF itself does not employ VirtioMmioDeviceLib. However, the library is used
cc9195
  (or has been tested as Proof-of-Concept) in the following 64-bit and 32-bit
cc9195
  ARM emulator setups:
cc9195
cc9195
  - in "RTSM_VE_FOUNDATIONV8_EFI.fd" and "FVP_AARCH64_EFI.fd", on ARM Holdings'
cc9195
    ARM(R) v8-A Foundation Model and ARM(R) AEMv8-A Base Platform FVP
cc9195
    emulators, respectively:
cc9195
cc9195
                           EFI_BLOCK_IO_PROTOCOL
cc9195
                           [OvmfPkg/VirtioBlkDxe]
cc9195
                                      |
cc9195
                           VIRTIO_DEVICE_PROTOCOL
cc9195
        [ArmPlatformPkg/ArmVExpressPkg/ArmVExpressDxe/ArmFvpDxe.inf]
cc9195
                                      |
cc9195
                    [OvmfPkg/Library/VirtioMmioDeviceLib]
cc9195
                         direct MMIO register access
cc9195
cc9195
  - in "RTSM_VE_CORTEX-A15_EFI.fd" and "RTSM_VE_CORTEX-A15_MPCORE_EFI.fd", on
cc9195
    "qemu-system-arm -M vexpress-a15":
cc9195
cc9195
        EFI_BLOCK_IO_PROTOCOL            EFI_SIMPLE_NETWORK_PROTOCOL
cc9195
        [OvmfPkg/VirtioBlkDxe]             [OvmfPkg/VirtioNetDxe]
cc9195
                   |                                  |
cc9195
                   +------------------+---------------+
cc9195
                                      |
cc9195
                           VIRTIO_DEVICE_PROTOCOL
cc9195
        [ArmPlatformPkg/ArmVExpressPkg/ArmVExpressDxe/ArmFvpDxe.inf]
cc9195
                                      |
cc9195
                    [OvmfPkg/Library/VirtioMmioDeviceLib]
cc9195
                         direct MMIO register access
cc9195
cc9195
  In the above ARM / VirtioMmioDeviceLib configurations, VirtioBlkDxe was
cc9195
  tested with booting Linux distributions, while VirtioNetDxe was tested with
cc9195
  pinging public IPv4 addresses from the UEFI shell.
cc9195
cc9195
Platform Driver
cc9195
...............
cc9195
cc9195
Sometimes, elements of persistent firmware configuration are best exposed to
cc9195
the user in a friendly way. OVMF's platform driver (OvmfPkg/PlatformDxe)
cc9195
presents such settings on the "OVMF Platform Configuration" dialog:
cc9195
cc9195
- Press ESC on the TianoCore splash screen,
cc9195
- Navigate to Device Manager | OVMF Platform Configuration.
cc9195
cc9195
At the moment, OVMF's platform driver handles only one setting: the preferred
cc9195
graphics resolution. This is useful for two purposes:
cc9195
cc9195
- Some UEFI shell commands, like DRIVERS and DEVICES, benefit from a wide
cc9195
  display. Using the MODE shell command, the user can switch to a larger text
cc9195
  resolution (limited by the graphics resolution), and see the command output
cc9195
  in a more easily consumable way.
cc9195
cc9195
  [RHEL] The list of text modes available to the MODE command is also limited
cc9195
         by ConSplitterDxe (found under MdeModulePkg/Universal/Console).
cc9195
         ConSplitterDxe builds an intersection of text modes that are
cc9195
         simultaneously supported by all consoles that ConSplitterDxe
cc9195
         multiplexes console output to.
cc9195
cc9195
         In practice, the strongest text mode restriction comes from
cc9195
         TerminalDxe, which provides console I/O on serial ports. TerminalDxe
cc9195
         has a very limited built-in list of text modes, heavily pruning the
cc9195
         intersection built by ConSplitterDxe, and made available to the MODE
cc9195
         command.
cc9195
cc9195
         On the Red Hat Enterprise Linux 7.1 host, TerminalDxe's list of modes
cc9195
         has been extended with text resolutions that match the Spice QXL GPU's
cc9195
         common graphics resolutions. This way a "full screen" text mode should
cc9195
         always be available in the MODE command.
cc9195
cc9195
- The other advantage of controlling the graphics resolution lies with UEFI
cc9195
  operating systems that don't (yet) have a native driver for QEMU's virtual
cc9195
  video cards  -- eg. the Spice QXL GPU. Such OSes may choose to inherit the
cc9195
  properties of OVMF's EFI_GRAPHICS_OUTPUT_PROTOCOL (provided by
cc9195
  OvmfPkg/QemuVideoDxe, see later).
cc9195
cc9195
  Although the display can be used at runtime in such cases, by direct
cc9195
  framebuffer access, its properties, for example, the resolution, cannot be
cc9195
  modified. The platform driver allows the user to select the preferred GOP
cc9195
  resolution, reboot, and let the guest OS inherit that preferred resolution.
cc9195
cc9195
The platform driver has three access points: the "normal" driver entry point, a
cc9195
set of HII callbacks, and a GOP installation callback.
cc9195
cc9195
(1) Driver entry point: the PlatformInit() function.
cc9195
cc9195
    (a) First, this function loads any available settings, and makes them take
cc9195
        effect. For the preferred graphics resolution in particular, this means
cc9195
        setting the following PCDs:
cc9195
cc9195
          gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution
cc9195
          gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution
cc9195
cc9195
        These PCDs influence the GraphicsConsoleDxe driver (located under
cc9195
        MdeModulePkg/Universal/Console), which switches to the preferred
cc9195
        graphics mode, and produces EFI_SIMPLE_TEXT_OUTPUT_PROTOCOLs on GOPs:
cc9195
cc9195
                    EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL
cc9195
          [MdeModulePkg/Universal/Console/GraphicsConsoleDxe]
cc9195
                                   |
cc9195
                      EFI_GRAPHICS_OUTPUT_PROTOCOL
cc9195
                         [OvmfPkg/QemuVideoDxe]
cc9195
                                   |
cc9195
                          EFI_PCI_IO_PROTOCOL
cc9195
                   [MdeModulePkg/Bus/Pci/PciBusDxe]
cc9195
cc9195
  (b) Second, the driver entry point registers the user interface, including
cc9195
      HII callbacks.
cc9195
cc9195
  (c) Third, the driver entry point registers a GOP installation callback.
cc9195
cc9195
(2) HII callbacks and the user interface.
cc9195
cc9195
    The Human Interface Infrastructure (HII) "is a set of protocols that allow
cc9195
    a UEFI driver to provide the ability to register user interface and
cc9195
    configuration content with the platform firmware".
cc9195
cc9195
    OVMF's platform driver:
cc9195
cc9195
    - provides a static, basic, visual form (PlatformForms.vfr), written in the
cc9195
      Visual Forms Representation language,
cc9195
cc9195
    - includes a UCS-16 encoded message catalog (Platform.uni),
cc9195
cc9195
    - includes source code that dynamically populates parts of the form, with
cc9195
      the help of MdeModulePkg/Library/UefiHiiLib -- this library simplifies
cc9195
      the handling of IFR (Internal Forms Representation) opcodes,
cc9195
cc9195
    - processes form actions that the user takes (Callback() function),
cc9195
cc9195
    - loads and saves platform configuration in a private, non-volatile
cc9195
      variable (ExtractConfig() and RouteConfig() functions).
cc9195
cc9195
    The ExtractConfig() HII callback implements the following stack of
cc9195
    conversions, for loading configuration and presenting it to the user:
cc9195
cc9195
          MultiConfigAltResp       -- form engine / HII communication
cc9195
                  ^
cc9195
                  |
cc9195
           [BlockToConfig]
cc9195
                  |
cc9195
           MAIN_FORM_STATE         -- binary representation of form/widget
cc9195
                  ^                   state
cc9195
                  |
cc9195
      [PlatformConfigToFormState]
cc9195
                  |
cc9195
           PLATFORM_CONFIG         -- accessible to DXE and UEFI drivers
cc9195
                  ^
cc9195
                  |
cc9195
         [PlatformConfigLoad]
cc9195
                  |
cc9195
        UEFI non-volatile variable -- accessible to external utilities
cc9195
cc9195
    The layers are very similar for the reverse direction, ie. when taking
cc9195
    input from the user, and saving the configuration (RouteConfig() HII
cc9195
    callback):
cc9195
cc9195
             ConfigResp            -- form engine / HII communication
cc9195
                  |
cc9195
           [ConfigToBlock]
cc9195
                  |
cc9195
                  v
cc9195
           MAIN_FORM_STATE         -- binary representation of form/widget
cc9195
                  |                   state
cc9195
      [FormStateToPlatformConfig]
cc9195
                  |
cc9195
                  v
cc9195
           PLATFORM_CONFIG         -- accessible to DXE and UEFI drivers
cc9195
                  |
cc9195
         [PlatformConfigSave]
cc9195
                  |
cc9195
                  v
cc9195
        UEFI non-volatile variable -- accessible to external utilities
cc9195
cc9195
(3) When the platform driver starts, a GOP may not be available yet. Thus the
cc9195
    driver entry point registers a callback (the GopInstalled() function) for
cc9195
    GOP installations.
cc9195
cc9195
    When the first GOP is produced (usually by QemuVideoDxe, or potentially by
cc9195
    a third party video driver), PlatformDxe retrieves the list of graphics
cc9195
    modes the GOP supports, and dynamically populates the drop-down list of
cc9195
    available resolutions on the form. The GOP installation callback is then
cc9195
    removed.
cc9195
cc9195
Video driver
cc9195
............
cc9195
cc9195
OvmfPkg/QemuVideoDxe is OVMF's built-in video driver. We can divide its
cc9195
services in two parts: graphics output protocol (primary), and Int10h (VBE)
cc9195
shim (secondary).
cc9195
cc9195
(1) QemuVideoDxe conforms to the UEFI Driver Model; it produces an instance of
cc9195
    the EFI_GRAPHICS_OUTPUT_PROTOCOL (GOP) on each PCI display that it supports
cc9195
    and is connected to:
cc9195
cc9195
                      EFI_GRAPHICS_OUTPUT_PROTOCOL
cc9195
                         [OvmfPkg/QemuVideoDxe]
cc9195
                                   |
cc9195
                          EFI_PCI_IO_PROTOCOL
cc9195
                   [MdeModulePkg/Bus/Pci/PciBusDxe]
cc9195
cc9195
    It supports the following QEMU video cards:
cc9195
cc9195
    - Cirrus 5430 ("-device cirrus-vga"),
cc9195
    - Standard VGA ("-device VGA"),
cc9195
    - QXL VGA ("-device qxl-vga", "-device qxl").
cc9195
cc9195
    For Cirrus the following resolutions and color depths are available:
cc9195
    640x480x32, 800x600x32, 1024x768x24. On stdvga and QXL a long list of
cc9195
    resolutions is available. The list is filtered against the frame buffer
cc9195
    size during initialization.
cc9195
cc9195
    The size of the QXL VGA compatibility framebuffer can be changed with the
cc9195
cc9195
      -device qxl-vga,vgamem_mb=$NUM_MB
cc9195
cc9195
    QEMU option. If $NUM_MB exceeds 32, then the following is necessary
cc9195
    instead:
cc9195
cc9195
      -device qxl-vga,vgamem_mb=$NUM_MB,ram_size_mb=$((NUM_MB*2))
cc9195
cc9195
    because the compatibility framebuffer can't cover more than half of PCI BAR
cc9195
    #0. The latter defaults to 64MB in size, and is controlled by the
cc9195
    "ram_size_mb" property.
cc9195
cc9195
(2) When QemuVideoDxe binds the first Standard VGA or QXL VGA device, and there
cc9195
    is no real VGA BIOS present in the C to F segments (which could originate
cc9195
    from a legacy PCI option ROM -- refer to "Compatibility Support Module
cc9195
    (CSM)"), then QemuVideoDxe installs a minimal, "fake" VGA BIOS -- an Int10h
cc9195
    (VBE) "shim".
cc9195
cc9195
    The shim is implemented in 16-bit assembly in
cc9195
    "OvmfPkg/QemuVideoDxe/VbeShim.asm". The "VbeShim.sh" shell script assembles
cc9195
    it and formats it as a C array ("VbeShim.h") with the help of the "nasm"
cc9195
    utility. The driver's InstallVbeShim() function copies the shim in place
cc9195
    (the C segment), and fills in the VBE Info and VBE Mode Info structures.
cc9195
    The real-mode 10h interrupt vector is pointed to the shim's handler.
cc9195
cc9195
    The shim is (correctly) irrelevant and invisible for all UEFI operating
cc9195
    systems we know about -- except Windows Server 2008 R2 and other Windows
cc9195
    operating systems in that family.
cc9195
cc9195
    Namely, the Windows 2008 R2 SP1 (and Windows 7) UEFI guest's default video
cc9195
    driver dereferences the real mode Int10h vector, loads the pointed-to
cc9195
    handler code, and executes what it thinks to be VGA BIOS services in an
cc9195
    internal real-mode emulator. Consequently, video mode switching used not to
cc9195
    work in Windows 2008 R2 SP1 when it ran on the "pure UEFI" build of OVMF,
cc9195
    making the guest uninstallable. Hence the (otherwise optional, non-default)
cc9195
    Compatibility Support Module (CSM) ended up a requirement for running such
cc9195
    guests.
cc9195
cc9195
    The hard dependency on the sophisticated SeaBIOS CSM and the complex
cc9195
    supporting edk2 infrastructure, for enabling this family of guests, was
cc9195
    considered suboptimal by some members of the upstream community,
cc9195
cc9195
    [RHEL] and was certainly considered a serious maintenance disadvantage for
cc9195
           Red Hat Enterprise Linux 7.1 hosts.
cc9195
cc9195
    Thus, the shim has been collaboratively developed for the Windows 7 /
cc9195
    Windows Server 2008 R2 family. The shim provides a real stdvga / QXL
cc9195
    implementation for the few services that are in fact necessary for the
cc9195
    Windows 2008 R2 SP1 (and Windows 7) UEFI guest, plus some "fakes" that the
cc9195
    guest invokes but whose effect is not important. The only supported mode is
cc9195
    1024x768x32, which is enough to install the guest and then upgrade its
cc9195
    video driver to the full-featured QXL XDDM one.
cc9195
cc9195
    The C segment is not present in the UEFI memory map prepared by OVMF.
cc9195
    Memory space that would cover it is never added (either in PEI, in the form
cc9195
    of memory resource descriptor HOBs, or in DXE, via gDS->AddMemorySpace()).
cc9195
    This way the handler body is invisible to all other UEFI guests, and the
cc9195
    rest of edk2.
cc9195
cc9195
    The Int10h real-mode IVT entry is covered with a Boot Services Code page,
cc9195
    making that too inaccessible to the rest of edk2. Due to the allocation
cc9195
    type, UEFI guest OSes different from the Windows Server 2008 family can
cc9195
    reclaim the page at zero. (The Windows 2008 family accesses that page
cc9195
    regardless of the allocation type.)
cc9195
cc9195
Afterword
cc9195
---------
cc9195
cc9195
After the bulk of this document was written in July 2014, OVMF development has
cc9195
not stopped. To name two significant code contributions from the community: in
cc9195
January 2015, OVMF runs on the "q35" machine type of QEMU, and it features a
cc9195
driver for Xen paravirtual block devices (and another for the underlying Xen
cc9195
bus).
cc9195
cc9195
Furthermore, a dedicated virtualization platform has been contributed to
cc9195
ArmPlatformPkg that plays a role parallel to OvmfPkg's. It targets the "virt"
cc9195
machine type of qemu-system-arm and qemu-system-aarch64. Parts of OvmfPkg are
cc9195
being refactored and modularized so they can be reused in
cc9195
"ArmPlatformPkg/ArmVirtualizationPkg/ArmVirtualizationQemu.dsc".