Blame SOURCES/ovmf-whitepaper-c770f8c.txt

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