Blame SOURCES/ovmf-whitepaper-c770f8c.txt

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