pci,pc,virtio: features, tests, fixes, cleanups

lots of acpi rework
 first version of biosbits infrastructure
 ASID support in vhost-vdpa
 core_count2 support in smbios
 PCIe DOE emulation
 virtio vq reset
 HMAT support
 part of infrastructure for viommu support in vhost-vdpa
 VTD PASID support
 fixes, tests all over the place
 
 Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
 -----BEGIN PGP SIGNATURE-----
 
 iQFDBAABCAAtFiEEXQn9CHHI+FuUyooNKB8NuNKNVGkFAmNpXDkPHG1zdEByZWRo
 YXQuY29tAAoJECgfDbjSjVRpD0AH/2G8ZPrgrxJC9y3uD5/5J6QRzO+TsDYbg5ut
 uBf4rKSHHzcu6zdyAfsrhbAKKzyD4HrEGNXZrBjnKM1xCiB/SGBcDIWntwrca2+s
 5Dpbi4xvd4tg6tVD4b47XNDCcn2uUbeI0e2M5QIbtCmzdi/xKbFAfl5G8DQp431X
 Kmz79G4CdKWyjVlM0HoYmdCw/4FxkdjD02tE/Uc5YMrePNaEg5Bw4hjCHbx1b6ur
 6gjeXAtncm9s4sO0l+sIdyiqlxiTry9FSr35WaQ0qPU+Og5zaf1EiWfdl8TRo4qU
 EAATw5A4hyw11GfOGp7oOVkTGvcNB/H7aIxD7emdWZV8+BMRPKo=
 =zTCn
 -----END PGP SIGNATURE-----

Merge tag 'for_upstream' of https://git.kernel.org/pub/scm/virt/kvm/mst/qemu into staging

pci,pc,virtio: features, tests, fixes, cleanups

lots of acpi rework
first version of biosbits infrastructure
ASID support in vhost-vdpa
core_count2 support in smbios
PCIe DOE emulation
virtio vq reset
HMAT support
part of infrastructure for viommu support in vhost-vdpa
VTD PASID support
fixes, tests all over the place

Signed-off-by: Michael S. Tsirkin <mst@redhat.com>

# -----BEGIN PGP SIGNATURE-----
#
# iQFDBAABCAAtFiEEXQn9CHHI+FuUyooNKB8NuNKNVGkFAmNpXDkPHG1zdEByZWRo
# YXQuY29tAAoJECgfDbjSjVRpD0AH/2G8ZPrgrxJC9y3uD5/5J6QRzO+TsDYbg5ut
# uBf4rKSHHzcu6zdyAfsrhbAKKzyD4HrEGNXZrBjnKM1xCiB/SGBcDIWntwrca2+s
# 5Dpbi4xvd4tg6tVD4b47XNDCcn2uUbeI0e2M5QIbtCmzdi/xKbFAfl5G8DQp431X
# Kmz79G4CdKWyjVlM0HoYmdCw/4FxkdjD02tE/Uc5YMrePNaEg5Bw4hjCHbx1b6ur
# 6gjeXAtncm9s4sO0l+sIdyiqlxiTry9FSr35WaQ0qPU+Og5zaf1EiWfdl8TRo4qU
# EAATw5A4hyw11GfOGp7oOVkTGvcNB/H7aIxD7emdWZV8+BMRPKo=
# =zTCn
# -----END PGP SIGNATURE-----
# gpg: Signature made Mon 07 Nov 2022 14:27:53 EST
# gpg:                using RSA key 5D09FD0871C8F85B94CA8A0D281F0DB8D28D5469
# gpg:                issuer "mst@redhat.com"
# gpg: Good signature from "Michael S. Tsirkin <mst@kernel.org>" [full]
# gpg:                 aka "Michael S. Tsirkin <mst@redhat.com>" [full]
# Primary key fingerprint: 0270 606B 6F3C DF3D 0B17  0970 C350 3912 AFBE 8E67
#      Subkey fingerprint: 5D09 FD08 71C8 F85B 94CA  8A0D 281F 0DB8 D28D 5469

* tag 'for_upstream' of https://git.kernel.org/pub/scm/virt/kvm/mst/qemu: (83 commits)
  checkpatch: better pattern for inline comments
  hw/virtio: introduce virtio_device_should_start
  tests/acpi: update tables for new core count test
  bios-tables-test: add test for number of cores > 255
  tests/acpi: allow changes for core_count2 test
  bios-tables-test: teach test to use smbios 3.0 tables
  hw/smbios: add core_count2 to smbios table type 4
  vhost-user: Support vhost_dev_start
  vhost: Change the sequence of device start
  intel-iommu: PASID support
  intel-iommu: convert VTD_PE_GET_FPD_ERR() to be a function
  intel-iommu: drop VTDBus
  intel-iommu: don't warn guest errors when getting rid2pasid entry
  vfio: move implement of vfio_get_xlat_addr() to memory.c
  tests: virt: Update expected *.acpihmatvirt tables
  tests: acpi: aarch64/virt: add a test for hmat nodes with no initiators
  hw/arm/virt: Enable HMAT on arm virt machine
  tests: Add HMAT AArch64/virt empty table files
  tests: acpi: q35: update expected blobs *.hmat-noinitiators expected HMAT:
  tests: acpi: q35: add test for hmat nodes without initiators
  ...

Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
This commit is contained in:
Stefan Hajnoczi 2022-11-07 18:43:56 -05:00
commit f21f1cfeb9
155 changed files with 7996 additions and 1020 deletions

396
tests/avocado/acpi-bits.py Normal file
View file

@ -0,0 +1,396 @@
#!/usr/bin/env python3
# group: rw quick
# Exercize QEMU generated ACPI/SMBIOS tables using biosbits,
# https://biosbits.org/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# Author:
# Ani Sinha <ani@anisinha.ca>
# pylint: disable=invalid-name
# pylint: disable=consider-using-f-string
"""
This is QEMU ACPI/SMBIOS avocado tests using biosbits.
Biosbits is available originally at https://biosbits.org/.
This test uses a fork of the upstream bits and has numerous fixes
including an upgraded acpica. The fork is located here:
https://gitlab.com/qemu-project/biosbits-bits .
"""
import logging
import os
import platform
import re
import shutil
import subprocess
import tarfile
import tempfile
import time
import zipfile
from typing import (
List,
Optional,
Sequence,
)
from qemu.machine import QEMUMachine
from avocado import skipIf
from avocado_qemu import QemuBaseTest
deps = ["xorriso"] # dependent tools needed in the test setup/box.
supported_platforms = ['x86_64'] # supported test platforms.
def which(tool):
""" looks up the full path for @tool, returns None if not found
or if @tool does not have executable permissions.
"""
paths=os.getenv('PATH')
for p in paths.split(os.path.pathsep):
p = os.path.join(p, tool)
if os.path.exists(p) and os.access(p, os.X_OK):
return p
return None
def missing_deps():
""" returns True if any of the test dependent tools are absent.
"""
for dep in deps:
if which(dep) is None:
return True
return False
def supported_platform():
""" checks if the test is running on a supported platform.
"""
return platform.machine() in supported_platforms
class QEMUBitsMachine(QEMUMachine): # pylint: disable=too-few-public-methods
"""
A QEMU VM, with isa-debugcon enabled and bits iso passed
using -cdrom to QEMU commandline.
"""
def __init__(self,
binary: str,
args: Sequence[str] = (),
wrapper: Sequence[str] = (),
name: Optional[str] = None,
base_temp_dir: str = "/var/tmp",
debugcon_log: str = "debugcon-log.txt",
debugcon_addr: str = "0x403",
sock_dir: Optional[str] = None,
qmp_timer: Optional[float] = None):
# pylint: disable=too-many-arguments
if name is None:
name = "qemu-bits-%d" % os.getpid()
if sock_dir is None:
sock_dir = base_temp_dir
super().__init__(binary, args, wrapper=wrapper, name=name,
base_temp_dir=base_temp_dir,
sock_dir=sock_dir, qmp_timer=qmp_timer)
self.debugcon_log = debugcon_log
self.debugcon_addr = debugcon_addr
self.base_temp_dir = base_temp_dir
@property
def _base_args(self) -> List[str]:
args = super()._base_args
args.extend([
'-chardev',
'file,path=%s,id=debugcon' %os.path.join(self.base_temp_dir,
self.debugcon_log),
'-device',
'isa-debugcon,iobase=%s,chardev=debugcon' %self.debugcon_addr,
])
return args
def base_args(self):
"""return the base argument to QEMU binary"""
return self._base_args
@skipIf(not supported_platform() or missing_deps() or os.getenv('GITLAB_CI'),
'incorrect platform or dependencies (%s) not installed ' \
'or running on GitLab' % ','.join(deps))
class AcpiBitsTest(QemuBaseTest): #pylint: disable=too-many-instance-attributes
"""
ACPI and SMBIOS tests using biosbits.
:avocado: tags=arch:x86_64
:avocado: tags=acpi
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._vm = None
self._workDir = None
self._baseDir = None
# following are some standard configuration constants
self._bitsInternalVer = 2020
self._bitsCommitHash = 'b48b88ff' # commit hash must match
# the artifact tag below
self._bitsTag = "qemu-bits-10182022" # this is the latest bits
# release as of today.
self._bitsArtSHA1Hash = 'b04790ac9b99b5662d0416392c73b97580641fe5'
self._bitsArtURL = ("https://gitlab.com/qemu-project/"
"biosbits-bits/-/jobs/artifacts/%s/"
"download?job=qemu-bits-build" %self._bitsTag)
self._debugcon_addr = '0x403'
self._debugcon_log = 'debugcon-log.txt'
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger('acpi-bits')
def _print_log(self, log):
self.logger.info('\nlogs from biosbits follows:')
self.logger.info('==========================================\n')
self.logger.info(log)
self.logger.info('==========================================\n')
def copy_bits_config(self):
""" copies the bios bits config file into bits.
"""
config_file = 'bits-cfg.txt'
bits_config_dir = os.path.join(self._baseDir, 'acpi-bits',
'bits-config')
target_config_dir = os.path.join(self._workDir,
'bits-%d' %self._bitsInternalVer,
'boot')
self.assertTrue(os.path.exists(bits_config_dir))
self.assertTrue(os.path.exists(target_config_dir))
self.assertTrue(os.access(os.path.join(bits_config_dir,
config_file), os.R_OK))
shutil.copy2(os.path.join(bits_config_dir, config_file),
target_config_dir)
self.logger.info('copied config file %s to %s',
config_file, target_config_dir)
def copy_test_scripts(self):
"""copies the python test scripts into bits. """
bits_test_dir = os.path.join(self._baseDir, 'acpi-bits',
'bits-tests')
target_test_dir = os.path.join(self._workDir,
'bits-%d' %self._bitsInternalVer,
'boot', 'python')
self.assertTrue(os.path.exists(bits_test_dir))
self.assertTrue(os.path.exists(target_test_dir))
for filename in os.listdir(bits_test_dir):
if os.path.isfile(os.path.join(bits_test_dir, filename)) and \
filename.endswith('.py2'):
# all test scripts are named with extension .py2 so that
# avocado does not try to load them. These scripts are
# written for python 2.7 not python 3 and hence if avocado
# loaded them, it would complain about python 3 specific
# syntaxes.
newfilename = os.path.splitext(filename)[0] + '.py'
shutil.copy2(os.path.join(bits_test_dir, filename),
os.path.join(target_test_dir, newfilename))
self.logger.info('copied test file %s to %s',
filename, target_test_dir)
# now remove the pyc test file if it exists, otherwise the
# changes in the python test script won't be executed.
testfile_pyc = os.path.splitext(filename)[0] + '.pyc'
if os.access(os.path.join(target_test_dir, testfile_pyc),
os.F_OK):
os.remove(os.path.join(target_test_dir, testfile_pyc))
self.logger.info('removed compiled file %s',
os.path.join(target_test_dir,
testfile_pyc))
def fix_mkrescue(self, mkrescue):
""" grub-mkrescue is a bash script with two variables, 'prefix' and
'libdir'. They must be pointed to the right location so that the
iso can be generated appropriately. We point the two variables to
the directory where we have extracted our pre-built bits grub
tarball.
"""
grub_x86_64_mods = os.path.join(self._workDir, 'grub-inst-x86_64-efi')
grub_i386_mods = os.path.join(self._workDir, 'grub-inst')
self.assertTrue(os.path.exists(grub_x86_64_mods))
self.assertTrue(os.path.exists(grub_i386_mods))
new_script = ""
with open(mkrescue, 'r', encoding='utf-8') as filehandle:
orig_script = filehandle.read()
new_script = re.sub('(^prefix=)(.*)',
r'\1"%s"' %grub_x86_64_mods,
orig_script, flags=re.M)
new_script = re.sub('(^libdir=)(.*)', r'\1"%s/lib"' %grub_i386_mods,
new_script, flags=re.M)
with open(mkrescue, 'w', encoding='utf-8') as filehandle:
filehandle.write(new_script)
def generate_bits_iso(self):
""" Uses grub-mkrescue to generate a fresh bits iso with the python
test scripts
"""
bits_dir = os.path.join(self._workDir,
'bits-%d' %self._bitsInternalVer)
iso_file = os.path.join(self._workDir,
'bits-%d.iso' %self._bitsInternalVer)
mkrescue_script = os.path.join(self._workDir,
'grub-inst-x86_64-efi', 'bin',
'grub-mkrescue')
self.assertTrue(os.access(mkrescue_script,
os.R_OK | os.W_OK | os.X_OK))
self.fix_mkrescue(mkrescue_script)
self.logger.info('using grub-mkrescue for generating biosbits iso ...')
try:
if os.getenv('V'):
subprocess.check_call([mkrescue_script, '-o', iso_file,
bits_dir], stderr=subprocess.STDOUT)
else:
subprocess.check_call([mkrescue_script, '-o',
iso_file, bits_dir],
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
except Exception as e: # pylint: disable=broad-except
self.skipTest("Error while generating the bits iso. "
"Pass V=1 in the environment to get more details. "
+ str(e))
self.assertTrue(os.access(iso_file, os.R_OK))
self.logger.info('iso file %s successfully generated.', iso_file)
def setUp(self): # pylint: disable=arguments-differ
super().setUp('qemu-system-')
self._baseDir = os.getenv('AVOCADO_TEST_BASEDIR')
# workdir could also be avocado's own workdir in self.workdir.
# At present, I prefer to maintain my own temporary working
# directory. It gives us more control over the generated bits
# log files and also for debugging, we may chose not to remove
# this working directory so that the logs and iso can be
# inspected manually and archived if needed.
self._workDir = tempfile.mkdtemp(prefix='acpi-bits-',
suffix='.tmp')
self.logger.info('working dir: %s', self._workDir)
prebuiltDir = os.path.join(self._workDir, 'prebuilt')
if not os.path.isdir(prebuiltDir):
os.mkdir(prebuiltDir, mode=0o775)
bits_zip_file = os.path.join(prebuiltDir, 'bits-%d-%s.zip'
%(self._bitsInternalVer,
self._bitsCommitHash))
grub_tar_file = os.path.join(prebuiltDir,
'bits-%d-%s-grub.tar.gz'
%(self._bitsInternalVer,
self._bitsCommitHash))
bitsLocalArtLoc = self.fetch_asset(self._bitsArtURL,
asset_hash=self._bitsArtSHA1Hash)
self.logger.info("downloaded bits artifacts to %s", bitsLocalArtLoc)
# extract the bits artifact in the temp working directory
with zipfile.ZipFile(bitsLocalArtLoc, 'r') as zref:
zref.extractall(prebuiltDir)
# extract the bits software in the temp working directory
with zipfile.ZipFile(bits_zip_file, 'r') as zref:
zref.extractall(self._workDir)
with tarfile.open(grub_tar_file, 'r', encoding='utf-8') as tarball:
tarball.extractall(self._workDir)
self.copy_test_scripts()
self.copy_bits_config()
self.generate_bits_iso()
def parse_log(self):
"""parse the log generated by running bits tests and
check for failures.
"""
debugconf = os.path.join(self._workDir, self._debugcon_log)
log = ""
with open(debugconf, 'r', encoding='utf-8') as filehandle:
log = filehandle.read()
matchiter = re.finditer(r'(.*Summary: )(\d+ passed), (\d+ failed).*',
log)
for match in matchiter:
# verify that no test cases failed.
try:
self.assertEqual(match.group(3).split()[0], '0',
'Some bits tests seems to have failed. ' \
'Please check the test logs for more info.')
except AssertionError as e:
self._print_log(log)
raise e
else:
if os.getenv('V'):
self._print_log(log)
def tearDown(self):
"""
Lets do some cleanups.
"""
if self._vm:
self.assertFalse(not self._vm.is_running)
self.logger.info('removing the work directory %s', self._workDir)
shutil.rmtree(self._workDir)
super().tearDown()
def test_acpi_smbios_bits(self):
"""The main test case implementaion."""
iso_file = os.path.join(self._workDir,
'bits-%d.iso' %self._bitsInternalVer)
self.assertTrue(os.access(iso_file, os.R_OK))
self._vm = QEMUBitsMachine(binary=self.qemu_bin,
base_temp_dir=self._workDir,
debugcon_log=self._debugcon_log,
debugcon_addr=self._debugcon_addr)
self._vm.add_args('-cdrom', '%s' %iso_file)
# the vm needs to be run under icount so that TCG emulation is
# consistent in terms of timing. smilatency tests have consistent
# timing requirements.
self._vm.add_args('-icount', 'auto')
args = " ".join(str(arg) for arg in self._vm.base_args()) + \
" " + " ".join(str(arg) for arg in self._vm.args)
self.logger.info("launching QEMU vm with the following arguments: %s",
args)
self._vm.launch()
# biosbits has been configured to run all the specified test suites
# in batch mode and then automatically initiate a vm shutdown.
# sleep for maximum of one minute
max_sleep_time = time.monotonic() + 60
while self._vm.is_running() and time.monotonic() < max_sleep_time:
time.sleep(1)
self.assertFalse(time.monotonic() > max_sleep_time,
'The VM seems to have failed to shutdown in time')
self.parse_log()

View file

@ -0,0 +1,18 @@
# BITS configuration file
[bits]
# To run BITS in batch mode, set batch to a list of one or more of the
# following keywords; BITS will then run all of the requested operations, then
# save the log file to disk.
#
# test: Run the full BITS testsuite.
# acpi: Dump all ACPI structures.
# smbios: Dump all SMBIOS structures.
#
# Leave batch set to an empty string to disable batch mode.
# batch =
# Uncomment the following to run all available batch operations
# please take a look at boot/python/init.py in bits zip file
# to see how these options are parsed and used.
batch = test acpi smbios

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,283 @@
# Copyright (c) 2015, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for ACPI"""
import acpi
import bits
import bits.mwait
import struct
import testutil
import testsuite
import time
def register_tests():
testsuite.add_test("ACPI _MAT (Multiple APIC Table Entry) under Processor objects", test_mat, submenu="ACPI Tests")
# testsuite.add_test("ACPI _PSS (Pstate) table conformance tests", test_pss, submenu="ACPI Tests")
# testsuite.add_test("ACPI _PSS (Pstate) runtime tests", test_pstates, submenu="ACPI Tests")
testsuite.add_test("ACPI DSDT (Differentiated System Description Table)", test_dsdt, submenu="ACPI Tests")
testsuite.add_test("ACPI FACP (Fixed ACPI Description Table)", test_facp, submenu="ACPI Tests")
testsuite.add_test("ACPI HPET (High Precision Event Timer Table)", test_hpet, submenu="ACPI Tests")
testsuite.add_test("ACPI MADT (Multiple APIC Description Table)", test_apic, submenu="ACPI Tests")
testsuite.add_test("ACPI MPST (Memory Power State Table)", test_mpst, submenu="ACPI Tests")
testsuite.add_test("ACPI RSDP (Root System Description Pointer Structure)", test_rsdp, submenu="ACPI Tests")
testsuite.add_test("ACPI XSDT (Extended System Description Table)", test_xsdt, submenu="ACPI Tests")
def test_mat():
cpupaths = acpi.get_cpupaths()
apic = acpi.parse_apic()
procid_apicid = apic.procid_apicid
uid_x2apicid = apic.uid_x2apicid
for cpupath in cpupaths:
# Find the ProcId defined by the processor object
processor = acpi.evaluate(cpupath)
# Find the UID defined by the processor object's _UID method
uid = acpi.evaluate(cpupath + "._UID")
mat_buffer = acpi.evaluate(cpupath + "._MAT")
if mat_buffer is None:
continue
# Process each _MAT subtable
mat = acpi._MAT(mat_buffer)
for index, subtable in enumerate(mat):
if subtable.subtype == acpi.MADT_TYPE_LOCAL_APIC:
if subtable.flags.bits.enabled:
testsuite.test("{} Processor declaration ProcId = _MAT ProcId".format(cpupath), processor.ProcId == subtable.proc_id)
testsuite.print_detail("{} ProcId ({:#02x}) != _MAT ProcId ({:#02x})".format(cpupath, processor.ProcId, subtable.proc_id))
testsuite.print_detail("Processor Declaration: {}".format(processor))
testsuite.print_detail("_MAT entry[{}]: {}".format(index, subtable))
if testsuite.test("{} with local APIC in _MAT has local APIC in MADT".format(cpupath), processor.ProcId in procid_apicid):
testsuite.test("{} ApicId derived using Processor declaration ProcId = _MAT ApicId".format(cpupath), procid_apicid[processor.ProcId] == subtable.apic_id)
testsuite.print_detail("{} ApicId derived from MADT ({:#02x}) != _MAT ApicId ({:#02x})".format(cpupath, procid_apicid[processor.ProcId], subtable.apic_id))
testsuite.print_detail("Processor Declaration: {}".format(processor))
testsuite.print_detail("_MAT entry[{}]: {}".format(index, subtable))
if subtable.subtype == acpi.MADT_TYPE_LOCAL_X2APIC:
if subtable.flags.bits.enabled:
if testsuite.test("{} with x2Apic in _MAT has _UID".format(cpupath), uid is not None):
testsuite.test("{}._UID = _MAT UID".format(cpupath), uid == subtable.uid)
testsuite.print_detail("{}._UID ({:#x}) != _MAT UID ({:#x})".format(cpupath, uid, subtable.uid))
testsuite.print_detail("_MAT entry[{}]: {}".format(index, subtable))
if testsuite.test("{} with _MAT x2Apic has x2Apic in MADT".format(cpupath), subtable.uid in uid_x2apicid):
testsuite.test("{} x2ApicId derived from MADT using UID = _MAT x2ApicId".format(cpupath), uid_x2apicid[subtable.uid] == subtable.x2apicid)
testsuite.print_detail("{} x2ApicId derived from MADT ({:#02x}) != _MAT x2ApicId ({:#02x})".format(cpupath, uid_x2apicid[subtable.uid], subtable.x2apicid))
testsuite.print_detail("_MAT entry[{}]: {}".format(index, subtable))
def test_pss():
uniques = acpi.parse_cpu_method("_PSS")
# We special-case None here to avoid a double-failure for CPUs without a _PSS
testsuite.test("_PSS must be identical for all CPUs", len(uniques) <= 1 or (len(uniques) == 2 and None in uniques))
for pss, cpupaths in uniques.iteritems():
if not testsuite.test("_PSS must exist", pss is not None):
testsuite.print_detail(acpi.factor_commonprefix(cpupaths))
testsuite.print_detail('No _PSS exists')
continue
if not testsuite.test("_PSS must not be empty", pss.pstates):
testsuite.print_detail(acpi.factor_commonprefix(cpupaths))
testsuite.print_detail('_PSS is empty')
continue
testsuite.print_detail(acpi.factor_commonprefix(cpupaths))
for index, pstate in enumerate(pss.pstates):
testsuite.print_detail("P[{}]: {}".format(index, pstate))
testsuite.test("_PSS must contain at most 16 Pstates", len(pss.pstates) <= 16)
testsuite.test("_PSS must have no duplicate Pstates", len(pss.pstates) == len(set(pss.pstates)))
frequencies = [p.core_frequency for p in pss.pstates]
testsuite.test("_PSS must list Pstates in descending order of frequency", frequencies == sorted(frequencies, reverse=True))
testsuite.test("_PSS must have Pstates with no duplicate frequencies", len(frequencies) == len(set(frequencies)))
dissipations = [p.power for p in pss.pstates]
testsuite.test("_PSS must list Pstates in descending order of power dissipation", dissipations == sorted(dissipations, reverse=True))
def test_pstates():
"""Execute and verify frequency for each Pstate in the _PSS"""
IA32_PERF_CTL = 0x199
with bits.mwait.use_hint(), bits.preserve_msr(IA32_PERF_CTL):
cpupath_procid = acpi.find_procid()
cpupath_uid = acpi.find_uid()
apic = acpi.parse_apic()
procid_apicid = apic.procid_apicid
uid_x2apicid = apic.uid_x2apicid
def cpupath_apicid(cpupath):
if procid_apicid is not None:
procid = cpupath_procid.get(cpupath, None)
if procid is not None:
apicid = procid_apicid.get(procid, None)
if apicid is not None:
return apicid
if uid_x2apicid is not None:
uid = cpupath_uid.get(cpupath, None)
if uid is not None:
apicid = uid_x2apicid.get(uid, None)
if apicid is not None:
return apicid
return bits.cpus()[0]
bclk = testutil.adjust_to_nearest(bits.bclk(), 100.0/12) * 1000000
uniques = acpi.parse_cpu_method("_PSS")
for pss, cpupaths in uniques.iteritems():
if not testsuite.test("_PSS must exist", pss is not None):
testsuite.print_detail(acpi.factor_commonprefix(cpupaths))
testsuite.print_detail('No _PSS exists')
continue
for n, pstate in enumerate(pss.pstates):
for cpupath in cpupaths:
apicid = cpupath_apicid(cpupath)
if apicid is None:
print 'Failed to find apicid for cpupath {}'.format(cpupath)
continue
bits.wrmsr(apicid, IA32_PERF_CTL, pstate.control)
# Detecting Turbo frequency requires at least 2 pstates
# since turbo frequency = max non-turbo frequency + 1
turbo = False
if len(pss.pstates) >= 2:
turbo = (n == 0 and pstate.core_frequency == (pss.pstates[1].core_frequency + 1))
if turbo:
# Needs to busywait, not sleep
start = time.time()
while (time.time() - start < 2):
pass
for duration in (0.1, 1.0):
frequency_data = bits.cpu_frequency(duration)
# Abort the test if no cpu frequency is not available
if frequency_data is None:
continue
aperf = frequency_data[1]
aperf = testutil.adjust_to_nearest(aperf, bclk/2)
aperf = int(aperf / 1000000)
if turbo:
if aperf >= pstate.core_frequency:
break
else:
if aperf == pstate.core_frequency:
break
if turbo:
testsuite.test("P{}: Turbo measured frequency {} >= expected {} MHz".format(n, aperf, pstate.core_frequency), aperf >= pstate.core_frequency)
else:
testsuite.test("P{}: measured frequency {} MHz == expected {} MHz".format(n, aperf, pstate.core_frequency), aperf == pstate.core_frequency)
def test_psd_thread_scope():
uniques = acpi.parse_cpu_method("_PSD")
if not testsuite.test("_PSD (P-State Dependency) must exist for each processor", None not in uniques):
testsuite.print_detail(acpi.factor_commonprefix(uniques[None]))
testsuite.print_detail('No _PSD exists')
return
unique_num_dependencies = {}
unique_num_entries = {}
unique_revision = {}
unique_domain = {}
unique_coordination_type = {}
unique_num_processors = {}
for value, cpupaths in uniques.iteritems():
unique_num_dependencies.setdefault(len(value.dependencies), []).extend(cpupaths)
unique_num_entries.setdefault(value.dependencies[0].num_entries, []).extend(cpupaths)
unique_revision.setdefault(value.dependencies[0].revision, []).extend(cpupaths)
unique_domain.setdefault(value.dependencies[0].domain, []).extend(cpupaths)
unique_coordination_type.setdefault(value.dependencies[0].coordination_type, []).extend(cpupaths)
unique_num_processors.setdefault(value.dependencies[0].num_processors, []).extend(cpupaths)
def detail(d, fmt):
for value, cpupaths in sorted(d.iteritems(), key=(lambda (k,v): v)):
testsuite.print_detail(acpi.factor_commonprefix(cpupaths))
testsuite.print_detail(fmt.format(value))
testsuite.test('Dependency count for each processor must be 1', unique_num_dependencies.keys() == [1])
detail(unique_num_dependencies, 'Dependency count for each processor = {} (Expected 1)')
testsuite.test('_PSD.num_entries must be 5', unique_num_entries.keys() == [5])
detail(unique_num_entries, 'num_entries = {} (Expected 5)')
testsuite.test('_PSD.revision must be 0', unique_revision.keys() == [0])
detail(unique_revision, 'revision = {}')
testsuite.test('_PSD.coordination_type must be 0xFE (HW_ALL)', unique_coordination_type.keys() == [0xfe])
detail(unique_coordination_type, 'coordination_type = {:#x} (Expected 0xFE HW_ALL)')
testsuite.test('_PSD.domain must be unique (thread-scoped) for each processor', len(unique_domain) == len(acpi.get_cpupaths()))
detail(unique_domain, 'domain = {:#x} (Expected a unique value for each processor)')
testsuite.test('_PSD.num_processors must be 1', unique_num_processors.keys() == [1])
detail(unique_num_processors, 'num_processors = {} (Expected 1)')
def test_table_checksum(data):
csum = sum(ord(c) for c in data) % 0x100
testsuite.test('ACPI table cumulative checksum must equal 0', csum == 0)
testsuite.print_detail("Cumulative checksum = {} (Expected 0)".format(csum))
def test_apic():
data = acpi.get_table("APIC")
if data is None:
return
test_table_checksum(data)
apic = acpi.parse_apic()
def test_dsdt():
data = acpi.get_table("DSDT")
if data is None:
return
test_table_checksum(data)
def test_facp():
data = acpi.get_table("FACP")
if data is None:
return
test_table_checksum(data)
facp = acpi.parse_facp()
def test_hpet():
data = acpi.get_table("HPET")
if data is None:
return
test_table_checksum(data)
hpet = acpi.parse_hpet()
def test_mpst():
data = acpi.get_table("MPST")
if data is None:
return
test_table_checksum(data)
mpst = acpi.MPST(data)
def test_rsdp():
data = acpi.get_table("RSD PTR ")
if data is None:
return
# Checksum the first 20 bytes per ACPI 1.0
csum = sum(ord(c) for c in data[:20]) % 0x100
testsuite.test('ACPI 1.0 table first 20 bytes cummulative checksum must equal 0', csum == 0)
testsuite.print_detail("Cummulative checksum = {} (Expected 0)".format(csum))
test_table_checksum(data)
rsdp = acpi.parse_rsdp()
def test_xsdt():
data = acpi.get_table("XSDT")
if data is None:
return
test_table_checksum(data)
xsdt = acpi.parse_xsdt()

View file

@ -0,0 +1,83 @@
# Copyright (c) 2012, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests and helpers for CPUID."""
import bits
import testsuite
import testutil
def cpuid_helper(function, index=None, shift=0, mask=~0, eax_mask=~0, ebx_mask=~0, ecx_mask=~0, edx_mask=~0):
if index is None:
index = 0
indexdesc = ""
else:
indexdesc = " index {0:#x}".format(index)
def find_mask(m):
if m == ~0:
return mask
return m
masks = map(find_mask, [eax_mask, ebx_mask, ecx_mask, edx_mask])
uniques = {}
for cpu in bits.cpus():
regs = bits.cpuid_result(*[(r >> shift) & m for r, m in zip(bits.cpuid(cpu, function, index), masks)])
uniques.setdefault(regs, []).append(cpu)
desc = ["CPUID function {:#x}{}".format(function, indexdesc)]
if shift != 0:
desc.append("Register values have been shifted by {}".format(shift))
if mask != ~0 or eax_mask != ~0 or ebx_mask != ~0 or ecx_mask != ~0 or edx_mask != ~0:
desc.append("Register values have been masked:")
shifted_masks = bits.cpuid_result(*[m << shift for m in masks])
desc.append("Masks: eax={eax:#010x} ebx={ebx:#010x} ecx={ecx:#010x} edx={edx:#010x}".format(**shifted_masks._asdict()))
if len(uniques) > 1:
regvalues = zip(*uniques.iterkeys())
common_masks = bits.cpuid_result(*map(testutil.find_common_mask, regvalues))
common_values = bits.cpuid_result(*[v[0] & m for v, m in zip(regvalues, common_masks)])
desc.append('Register values are not unique across all logical processors')
desc.append("Common bits: eax={eax:#010x} ebx={ebx:#010x} ecx={ecx:#010x} edx={edx:#010x}".format(**common_values._asdict()))
desc.append("Mask of common bits: {eax:#010x} {ebx:#010x} {ecx:#010x} {edx:#010x}".format(**common_masks._asdict()))
for regs in sorted(uniques.iterkeys()):
cpus = uniques[regs]
desc.append("Register value: eax={eax:#010x} ebx={ebx:#010x} ecx={ecx:#010x} edx={edx:#010x}".format(**regs._asdict()))
desc.append("On {0} CPUs: {1}".format(len(cpus), testutil.apicid_list(cpus)))
return uniques, desc
def test_cpuid_consistency(text, function, index=None, shift=0, mask=~0, eax_mask=~0, ebx_mask=~0, ecx_mask=~0, edx_mask=~0):
uniques, desc = cpuid_helper(function, index, shift, mask, eax_mask, ebx_mask, ecx_mask, edx_mask)
desc[0] += " Consistency Check"
if text:
desc.insert(0, text)
status = testsuite.test(desc[0], len(uniques) == 1)
for line in desc[1:]:
testsuite.print_detail(line)
return status

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -88,10 +88,12 @@ typedef struct {
uint64_t rsdp_addr;
uint8_t rsdp_table[36 /* ACPI 2.0+ RSDP size */];
GArray *tables;
uint32_t smbios_ep_addr;
struct smbios_21_entry_point smbios_ep_table;
uint64_t smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE__MAX];
SmbiosEntryPoint smbios_ep_table;
uint16_t smbios_cpu_max_speed;
uint16_t smbios_cpu_curr_speed;
uint8_t smbios_core_count;
uint16_t smbios_core_count2;
uint8_t *required_struct_types;
int required_struct_types_len;
QTestState *qts;
@ -533,10 +535,9 @@ static void test_acpi_asl(test_data *data)
free_test_data(&exp_data);
}
static bool smbios_ep_table_ok(test_data *data)
static bool smbios_ep2_table_ok(test_data *data, uint32_t addr)
{
struct smbios_21_entry_point *ep_table = &data->smbios_ep_table;
uint32_t addr = data->smbios_ep_addr;
struct smbios_21_entry_point *ep_table = &data->smbios_ep_table.ep21;
qtest_memread(data->qts, addr, ep_table, sizeof(*ep_table));
if (memcmp(ep_table->anchor_string, "_SM_", 4)) {
@ -559,13 +560,29 @@ static bool smbios_ep_table_ok(test_data *data)
return true;
}
static void test_smbios_entry_point(test_data *data)
static bool smbios_ep3_table_ok(test_data *data, uint64_t addr)
{
struct smbios_30_entry_point *ep_table = &data->smbios_ep_table.ep30;
qtest_memread(data->qts, addr, ep_table, sizeof(*ep_table));
if (memcmp(ep_table->anchor_string, "_SM3_", 5)) {
return false;
}
if (acpi_calc_checksum((uint8_t *)ep_table, sizeof *ep_table)) {
return false;
}
return true;
}
static SmbiosEntryPointType test_smbios_entry_point(test_data *data)
{
uint32_t off;
/* find smbios entry point structure */
for (off = 0xf0000; off < 0x100000; off += 0x10) {
uint8_t sig[] = "_SM_";
uint8_t sig[] = "_SM_", sig3[] = "_SM3_";
int i;
for (i = 0; i < sizeof sig - 1; ++i) {
@ -574,14 +591,30 @@ static void test_smbios_entry_point(test_data *data)
if (!memcmp(sig, "_SM_", sizeof sig)) {
/* signature match, but is this a valid entry point? */
data->smbios_ep_addr = off;
if (smbios_ep_table_ok(data)) {
if (smbios_ep2_table_ok(data, off)) {
data->smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE_32] = off;
}
}
for (i = 0; i < sizeof sig3 - 1; ++i) {
sig3[i] = qtest_readb(data->qts, off + i);
}
if (!memcmp(sig3, "_SM3_", sizeof sig3)) {
if (smbios_ep3_table_ok(data, off)) {
data->smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE_64] = off;
/* found 64-bit entry point, no need to look for 32-bit one */
break;
}
}
}
g_assert_cmphex(off, <, 0x100000);
/* found at least one entry point */
g_assert_true(data->smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE_32] ||
data->smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE_64]);
return data->smbios_ep_addr[SMBIOS_ENTRY_POINT_TYPE_64] ?
SMBIOS_ENTRY_POINT_TYPE_64 : SMBIOS_ENTRY_POINT_TYPE_32;
}
static inline bool smbios_single_instance(uint8_t type)
@ -600,41 +633,61 @@ static inline bool smbios_single_instance(uint8_t type)
}
}
static bool smbios_cpu_test(test_data *data, uint32_t addr)
static void smbios_cpu_test(test_data *data, uint32_t addr,
SmbiosEntryPointType ep_type)
{
uint16_t expect_speed[2];
uint16_t real;
uint8_t core_count, expected_core_count = data->smbios_core_count;
uint16_t speed, expected_speed[2];
uint16_t core_count2, expected_core_count2 = data->smbios_core_count2;
int offset[2];
int i;
/* Check CPU speed for backward compatibility */
offset[0] = offsetof(struct smbios_type_4, max_speed);
offset[1] = offsetof(struct smbios_type_4, current_speed);
expect_speed[0] = data->smbios_cpu_max_speed ? : 2000;
expect_speed[1] = data->smbios_cpu_curr_speed ? : 2000;
expected_speed[0] = data->smbios_cpu_max_speed ? : 2000;
expected_speed[1] = data->smbios_cpu_curr_speed ? : 2000;
for (i = 0; i < 2; i++) {
real = qtest_readw(data->qts, addr + offset[i]);
if (real != expect_speed[i]) {
fprintf(stderr, "Unexpected SMBIOS CPU speed: real %u expect %u\n",
real, expect_speed[i]);
return false;
}
speed = qtest_readw(data->qts, addr + offset[i]);
g_assert_cmpuint(speed, ==, expected_speed[i]);
}
return true;
core_count = qtest_readb(data->qts,
addr + offsetof(struct smbios_type_4, core_count));
if (expected_core_count) {
g_assert_cmpuint(core_count, ==, expected_core_count);
}
if (ep_type == SMBIOS_ENTRY_POINT_TYPE_64) {
core_count2 = qtest_readw(data->qts,
addr + offsetof(struct smbios_type_4, core_count2));
/* Core Count has reached its limit, checking Core Count 2 */
if (expected_core_count == 0xFF && expected_core_count2) {
g_assert_cmpuint(core_count2, ==, expected_core_count2);
}
}
}
static void test_smbios_structs(test_data *data)
static void test_smbios_structs(test_data *data, SmbiosEntryPointType ep_type)
{
DECLARE_BITMAP(struct_bitmap, SMBIOS_MAX_TYPE+1) = { 0 };
struct smbios_21_entry_point *ep_table = &data->smbios_ep_table;
uint32_t addr = le32_to_cpu(ep_table->structure_table_address);
int i, len, max_len = 0;
SmbiosEntryPoint *ep_table = &data->smbios_ep_table;
int i = 0, len, max_len = 0;
uint8_t type, prv, crt;
uint64_t addr;
if (ep_type == SMBIOS_ENTRY_POINT_TYPE_32) {
addr = le32_to_cpu(ep_table->ep21.structure_table_address);
} else {
addr = le64_to_cpu(ep_table->ep30.structure_table_address);
}
/* walk the smbios tables */
for (i = 0; i < le16_to_cpu(ep_table->number_of_structures); i++) {
do {
/* grab type and formatted area length from struct header */
type = qtest_readb(data->qts, addr);
@ -648,7 +701,7 @@ static void test_smbios_structs(test_data *data)
set_bit(type, struct_bitmap);
if (type == 4) {
g_assert(smbios_cpu_test(data, addr));
smbios_cpu_test(data, addr, ep_type);
}
/* seek to end of unformatted string area of this struct ("\0\0") */
@ -660,19 +713,33 @@ static void test_smbios_structs(test_data *data)
}
/* keep track of max. struct size */
if (max_len < len) {
if (ep_type == SMBIOS_ENTRY_POINT_TYPE_32 && max_len < len) {
max_len = len;
g_assert_cmpuint(max_len, <=, ep_table->max_structure_size);
g_assert_cmpuint(max_len, <=, ep_table->ep21.max_structure_size);
}
/* start of next structure */
addr += len;
}
/* total table length and max struct size must match entry point values */
g_assert_cmpuint(le16_to_cpu(ep_table->structure_table_length), ==,
addr - le32_to_cpu(ep_table->structure_table_address));
g_assert_cmpuint(le16_to_cpu(ep_table->max_structure_size), ==, max_len);
/*
* Until all structures have been scanned (ep21)
* or an EOF structure is found (ep30)
*/
} while (ep_type == SMBIOS_ENTRY_POINT_TYPE_32 ?
++i < le16_to_cpu(ep_table->ep21.number_of_structures) :
type != 127);
if (ep_type == SMBIOS_ENTRY_POINT_TYPE_32) {
/*
* Total table length and max struct size
* must match entry point values
*/
g_assert_cmpuint(le16_to_cpu(ep_table->ep21.structure_table_length), ==,
addr - le32_to_cpu(ep_table->ep21.structure_table_address));
g_assert_cmpuint(le16_to_cpu(ep_table->ep21.max_structure_size), ==,
max_len);
}
/* required struct types must all be present */
for (i = 0; i < data->required_struct_types_len; i++) {
@ -756,8 +823,8 @@ static void test_acpi_one(const char *params, test_data *data)
* https://bugs.launchpad.net/qemu/+bug/1821884
*/
if (!use_uefi) {
test_smbios_entry_point(data);
test_smbios_structs(data);
SmbiosEntryPointType ep_type = test_smbios_entry_point(data);
test_smbios_structs(data, ep_type);
}
qtest_quit(data->qts);
@ -856,6 +923,21 @@ static void test_acpi_q35_tcg(void)
free_test_data(&data);
}
static void test_acpi_q35_tcg_core_count2(void)
{
test_data data = {
.machine = MACHINE_Q35,
.variant = ".core-count2",
.required_struct_types = base_required_struct_types,
.required_struct_types_len = ARRAY_SIZE(base_required_struct_types),
.smbios_core_count = 0xFF,
.smbios_core_count2 = 275,
};
test_acpi_one("-machine smbios-entry-point-type=64 -smp 275", &data);
free_test_data(&data);
}
static void test_acpi_q35_tcg_bridge(void)
{
test_data data;
@ -1461,6 +1543,111 @@ static void test_acpi_piix4_tcg_acpi_hmat(void)
test_acpi_tcg_acpi_hmat(MACHINE_PC);
}
static void test_acpi_virt_tcg_acpi_hmat(void)
{
test_data data = {
.machine = "virt",
.tcg_only = true,
.uefi_fl1 = "pc-bios/edk2-aarch64-code.fd",
.uefi_fl2 = "pc-bios/edk2-arm-vars.fd",
.cd = "tests/data/uefi-boot-images/bios-tables-test.aarch64.iso.qcow2",
.ram_start = 0x40000000ULL,
.scan_len = 128ULL * 1024 * 1024,
};
data.variant = ".acpihmatvirt";
test_acpi_one(" -machine hmat=on"
" -cpu cortex-a57"
" -smp 4,sockets=2"
" -m 256M"
" -object memory-backend-ram,size=64M,id=ram0"
" -object memory-backend-ram,size=64M,id=ram1"
" -object memory-backend-ram,size=128M,id=ram2"
" -numa node,nodeid=0,memdev=ram0"
" -numa node,nodeid=1,memdev=ram1"
" -numa node,nodeid=2,memdev=ram2"
" -numa cpu,node-id=0,socket-id=0"
" -numa cpu,node-id=0,socket-id=0"
" -numa cpu,node-id=1,socket-id=1"
" -numa cpu,node-id=1,socket-id=1"
" -numa hmat-lb,initiator=0,target=0,hierarchy=memory,"
"data-type=access-latency,latency=10"
" -numa hmat-lb,initiator=0,target=0,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=10485760"
" -numa hmat-lb,initiator=0,target=1,hierarchy=memory,"
"data-type=access-latency,latency=20"
" -numa hmat-lb,initiator=0,target=1,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=5242880"
" -numa hmat-lb,initiator=0,target=2,hierarchy=memory,"
"data-type=access-latency,latency=30"
" -numa hmat-lb,initiator=0,target=2,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=1048576"
" -numa hmat-lb,initiator=1,target=0,hierarchy=memory,"
"data-type=access-latency,latency=20"
" -numa hmat-lb,initiator=1,target=0,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=5242880"
" -numa hmat-lb,initiator=1,target=1,hierarchy=memory,"
"data-type=access-latency,latency=10"
" -numa hmat-lb,initiator=1,target=1,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=10485760"
" -numa hmat-lb,initiator=1,target=2,hierarchy=memory,"
"data-type=access-latency,latency=30"
" -numa hmat-lb,initiator=1,target=2,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=1048576",
&data);
free_test_data(&data);
}
static void test_acpi_q35_tcg_acpi_hmat_noinitiator(void)
{
test_data data;
memset(&data, 0, sizeof(data));
data.machine = MACHINE_Q35;
data.variant = ".acpihmat-noinitiator";
test_acpi_one(" -machine hmat=on"
" -smp 4,sockets=2"
" -m 128M"
" -object memory-backend-ram,size=32M,id=ram0"
" -object memory-backend-ram,size=32M,id=ram1"
" -object memory-backend-ram,size=64M,id=ram2"
" -numa node,nodeid=0,memdev=ram0"
" -numa node,nodeid=1,memdev=ram1"
" -numa node,nodeid=2,memdev=ram2"
" -numa cpu,node-id=0,socket-id=0"
" -numa cpu,node-id=0,socket-id=0"
" -numa cpu,node-id=1,socket-id=1"
" -numa cpu,node-id=1,socket-id=1"
" -numa hmat-lb,initiator=0,target=0,hierarchy=memory,"
"data-type=access-latency,latency=10"
" -numa hmat-lb,initiator=0,target=0,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=10485760"
" -numa hmat-lb,initiator=0,target=1,hierarchy=memory,"
"data-type=access-latency,latency=20"
" -numa hmat-lb,initiator=0,target=1,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=5242880"
" -numa hmat-lb,initiator=0,target=2,hierarchy=memory,"
"data-type=access-latency,latency=30"
" -numa hmat-lb,initiator=0,target=2,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=1048576"
" -numa hmat-lb,initiator=1,target=0,hierarchy=memory,"
"data-type=access-latency,latency=20"
" -numa hmat-lb,initiator=1,target=0,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=5242880"
" -numa hmat-lb,initiator=1,target=1,hierarchy=memory,"
"data-type=access-latency,latency=10"
" -numa hmat-lb,initiator=1,target=1,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=10485760"
" -numa hmat-lb,initiator=1,target=2,hierarchy=memory,"
"data-type=access-latency,latency=30"
" -numa hmat-lb,initiator=1,target=2,hierarchy=memory,"
"data-type=access-bandwidth,bandwidth=1048576",
&data);
free_test_data(&data);
}
#ifdef CONFIG_POSIX
static void test_acpi_erst(const char *machine)
{
@ -1824,6 +2011,8 @@ int main(int argc, char *argv[])
qtest_add_func("acpi/q35/nohpet", test_acpi_q35_tcg_nohpet);
qtest_add_func("acpi/q35/dimmpxm", test_acpi_q35_tcg_dimm_pxm);
qtest_add_func("acpi/q35/acpihmat", test_acpi_q35_tcg_acpi_hmat);
qtest_add_func("acpi/q35/acpihmat-noinitiator",
test_acpi_q35_tcg_acpi_hmat_noinitiator);
#ifdef CONFIG_POSIX
qtest_add_func("acpi/q35/acpierst", test_acpi_q35_acpi_erst);
#endif
@ -1835,6 +2024,8 @@ int main(int argc, char *argv[])
if (has_kvm) {
qtest_add_func("acpi/q35/kvm/xapic", test_acpi_q35_kvm_xapic);
qtest_add_func("acpi/q35/kvm/dmar", test_acpi_q35_kvm_dmar);
qtest_add_func("acpi/q35/core-count2",
test_acpi_q35_tcg_core_count2);
}
qtest_add_func("acpi/q35/viot", test_acpi_q35_viot);
#ifdef CONFIG_POSIX
@ -1864,6 +2055,8 @@ int main(int argc, char *argv[])
} else if (strcmp(arch, "aarch64") == 0) {
if (has_tcg) {
qtest_add_func("acpi/virt", test_acpi_virt_tcg);
qtest_add_func("acpi/virt/acpihmatvirt",
test_acpi_virt_tcg_acpi_hmat);
qtest_add_func("acpi/virt/numamem", test_acpi_virt_tcg_numamem);
qtest_add_func("acpi/virt/memhp", test_acpi_virt_tcg_memhp);
qtest_add_func("acpi/virt/pxb", test_acpi_virt_tcg_pxb);

View file

@ -147,13 +147,58 @@ static const uint8_t test_rsa2048_priv_key[] =
"\x4e\x2f\x4c\xf9\xab\x97\x38\xe4\x20\x32\x32\x96\xc8\x9e\x79\xd3"
"\x12";
static const uint8_t test_ecdsa_p192_priv_key[] =
"\x30\x53" /* SEQUENCE, offset 0, length 83 */
"\x02\x01\x01" /* INTEGER, offset 2, length 1 */
"\x04\x18" /* OCTET STRING, offset 5, length 24 */
"\xcb\xc8\x86\x0e\x66\x3c\xf7\x5a\x44\x13\xb8\xef\xea\x1d\x7b\xa6"
"\x1c\xda\xf4\x1b\xc7\x67\x6b\x35"
"\xa1\x34" /* CONTEXT SPECIFIC 1, offset 31, length 52 */
"\x03\x32" /* BIT STRING, offset 33, length 50 */
"\x00\x04\xc4\x16\xb3\xff\xac\xd5\x87\x98\xf7\xd9\x45\xfe\xd3\x5c"
"\x17\x9d\xb2\x36\x22\xcc\x07\xb3\x6d\x3c\x4e\x04\x5f\xeb\xb6\x52"
"\x58\xfb\x36\x10\x52\xb7\x01\x62\x0e\x94\x51\x1d\xe2\xef\x10\x82"
"\x88\x78";
static const uint8_t test_ecdsa_p256_priv_key[] =
"\x30\x77" /* SEQUENCE, offset 0, length 119 */
"\x02\x01\x01" /* INTEGER, offset 2, length 1 */
"\x04\x20" /* OCTET STRING, offset 5, length 32 */
"\xf6\x92\xdd\x29\x1c\x6e\xef\xb6\xb2\x73\x9f\x40\x1b\xb3\x2a\x28"
"\xd2\x37\xd6\x4a\x5b\xe4\x40\x4c\x6a\x95\x99\xfa\xf7\x92\x49\xbe"
"\xa0\x0a" /* CONTEXT SPECIFIC 0, offset 39, length 10 */
"\x06\x08" /* OID, offset 41, length 8 */
"\x2a\x86\x48\xce\x3d\x03\x01\x07"
"\xa1\x44" /* CONTEXT SPECIFIC 1, offset 51, length 68 */
"\x03\x42" /* BIT STRING, offset 53, length 66 */
"\x00\x04\xed\x42\x9c\x67\x79\xbe\x46\x83\x88\x3e\x8c\xc1\x33\xf3"
"\xc3\xf6\x2c\xf3\x13\x6a\x00\xc2\xc9\x3e\x87\x7f\x86\x39\xe6\xae"
"\xe3\xb9\xba\x2f\x58\x63\x32\x62\x62\x54\x07\x27\xf9\x5a\x3a\xc7"
"\x3a\x6b\x5b\xbc\x0d\x33\xba\xbb\xd4\xa3\xff\x4f\x9e\xdd\xf5\x59"
"\xc0\xf6";
#define MAX_CHECKER_COUNT 32
static int qcrypto_wrapped_decode_ctx_tag0(const uint8_t **data, size_t *dlen,
QCryptoDERDecodeCb cb, void *opaque,
Error **errp)
{
return qcrypto_der_decode_ctx_tag(data, dlen, 0, cb, opaque, errp);
}
static int qcrypto_wrapped_decode_ctx_tag1(const uint8_t **data, size_t *dlen,
QCryptoDERDecodeCb cb, void *opaque,
Error **errp)
{
return qcrypto_der_decode_ctx_tag(data, dlen, 1, cb, opaque, errp);
}
typedef struct QCryptoAns1DecoderResultChecker QCryptoAns1DecoderResultChecker;
struct QCryptoAns1DecoderResultChecker {
int (*action) (const uint8_t **data, size_t *dlen,
QCryptoDERDecodeCb cb, void *opaque, Error **errp);
QCryptoDERDecodeCb cb;
bool constructed;
const uint8_t *exp_value;
size_t exp_vlen;
};
@ -204,7 +249,7 @@ static void test_ans1(const void *opaque)
g_assert(checker->action(&c->data, &c->dlen, checker_callback,
(void *)checker, &error_abort)
== checker->exp_vlen);
if (checker->action == qcrypto_der_decode_seq) {
if (checker->constructed) {
++seq_depth;
ctx[seq_depth].data = checker->exp_value;
ctx[seq_depth].dlen = checker->exp_vlen;
@ -225,25 +270,25 @@ static QCryptoAns1DecoderTestData test_data[] = {
.test_data = test_rsa512_priv_key,
.test_data_len = sizeof(test_rsa512_priv_key) - 1,
.checker = {
{ qcrypto_der_decode_seq, checker_callback,
{ qcrypto_der_decode_seq, checker_callback, true,
test_rsa512_priv_key + 4, 313 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 4 + 2, 1 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 7 + 2, 65 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 74 + 2, 3 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 79 + 2, 64 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 145 + 2, 33 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 180 + 2, 33 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 215 + 2, 32 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 249 + 2, 32 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa512_priv_key + 283 + 2, 32 },
},
},
@ -252,29 +297,66 @@ static QCryptoAns1DecoderTestData test_data[] = {
.test_data = test_rsa2048_priv_key,
.test_data_len = sizeof(test_rsa2048_priv_key) - 1,
.checker = {
{ qcrypto_der_decode_seq, checker_callback,
{ qcrypto_der_decode_seq, checker_callback, true,
test_rsa2048_priv_key + 4, 1190 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 4 + 2, 1 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 7 + 4, 257 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 268 + 2, 3 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 273 + 4, 257 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 534 + 3, 129 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 666 + 3, 129 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 798 + 3, 129 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 930 + 3, 129 },
{ qcrypto_der_decode_int, checker_callback,
{ qcrypto_der_decode_int, checker_callback, false,
test_rsa2048_priv_key + 1062 + 3, 129 },
},
},
{
.path = "/crypto/der/parse-ecdsa-p192-priv-key",
.test_data = test_ecdsa_p192_priv_key,
.test_data_len = sizeof(test_ecdsa_p192_priv_key) - 1,
.checker = {
{ qcrypto_der_decode_seq, checker_callback, true,
test_ecdsa_p192_priv_key + 2, 83 },
{ qcrypto_der_decode_int, checker_callback, false,
test_ecdsa_p192_priv_key + 2 + 2, 1 },
{ qcrypto_der_decode_octet_str, checker_callback, false,
test_ecdsa_p192_priv_key + 5 + 2, 24 },
{ qcrypto_wrapped_decode_ctx_tag1, checker_callback, true,
test_ecdsa_p192_priv_key + 31 + 2, 52 },
{ qcrypto_der_decode_bit_str , checker_callback, false,
test_ecdsa_p192_priv_key + 33 + 2, 50 },
},
},
{
.path = "/crypto/der/parse-ecdsa-p256-priv-key",
.test_data = test_ecdsa_p256_priv_key,
.test_data_len = sizeof(test_ecdsa_p256_priv_key) - 1,
.checker = {
{ qcrypto_der_decode_seq, checker_callback, true,
test_ecdsa_p256_priv_key + 2, 119 },
{ qcrypto_der_decode_int, checker_callback, false,
test_ecdsa_p256_priv_key + 2 + 2, 1 },
{ qcrypto_der_decode_octet_str, checker_callback, false,
test_ecdsa_p256_priv_key + 5 + 2, 32 },
{ qcrypto_wrapped_decode_ctx_tag0, checker_callback, true,
test_ecdsa_p256_priv_key + 39 + 2, 10 },
{ qcrypto_der_decode_oid, checker_callback, false,
test_ecdsa_p256_priv_key + 41 + 2, 8 },
{ qcrypto_wrapped_decode_ctx_tag1, checker_callback, true,
test_ecdsa_p256_priv_key + 51 + 2, 68 },
{ qcrypto_der_decode_bit_str , checker_callback, false,
test_ecdsa_p256_priv_key + 53 + 2, 66 },
},
},
};
int main(int argc, char **argv)