Skip to contentSkip to conversation

qtest: add test framework

PATCH In review Anthony Liguori 6 participants 24 messages Jan 13, 2012 – Jan 18, 2012 Kbuild

lore
Share & tools
lore
#0 lore raw

PATCH 1/6 qtest: add test framework

The idea behind qtest is pretty simple. Instead of executing a CPU via TCG or KVM, rely on an external process to send events to the device model that the CPU would normally generate.

qtest presents itself as an accelerator. In addition, a new option is added to establish a qtest server (-qtest) that takes a character device. This is what allows the external process to send CPU events to the device model.

This is currently modelled after Xen since the Xen device model does something very similar. Instead of hooking cpu_exec, Xen sticks the CPU in the halted state making sure it never gets to execute. In addition, Xen replaces the LAPIC with a dummy interrupt controller that forwards interrupt requests.

qtest does the exact same thing and uses a simple line based protocol to send the events. Documentation of that protocol is in qtest.c.

I considered reusing the monitor for this job. Adding interrupts would be a bit difficult. In addition, logging would also be difficult.

qtest has extensive logging support. All protocol commands are logged with time stamps using a new command line option (-qtest-log). Logging is important since ultimately, this is a feature for debugging.

---
 Makefile.objs   |    2 +
 cpu-exec.c      |    5 +
 qemu-options.hx |    8 ++
 qtest.c         |  357 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 qtest.h         |   37 ++++++
 vl.c            |    8 ++
 6 files changed, 417 insertions(+), 0 deletions(-)
 create mode 100644 qtest.c
 create mode 100644 qtest.h
Makefile.objs +2 -0
index 4f6d26c..52b2faf 100644
@@ -292,6 +292,8 @@ hw-obj-$(CONFIG_DP8393X) += dp8393x.o
 hw-obj-$(CONFIG_DS1225Y) += ds1225y.o
 hw-obj-$(CONFIG_MIPSNET) += mipsnet.o
 
+hw-obj-y += qtest.o
+
 # Sound
 sound-obj-y =
 sound-obj-$(CONFIG_SB16) += sb16.o
cpu-exec.c +5 -0
index a9fa608..bf5a2aa 100644
@@ -21,6 +21,7 @@
 #include "disas.h"
 #include "tcg.h"
 #include "qemu-barrier.h"
+#include "qtest.h"
 
 int tb_invalidated_flag;
 
@@ -188,6 +189,10 @@ int cpu_exec(CPUState *env)
     uint8_t *tc_ptr;
     unsigned long next_tb;
 
+    if (qtest_enabled()) {
+        env->halted = 1;
+    }
+
     if (env->halted) {
         if (!cpu_has_work(env)) {
             return EXCP_HALTED;
qemu-options.hx +8 -0
index 6295cde..da0c648 100644
@@ -2622,6 +2622,14 @@ the @var{simple} tracing backend.
 @end table
 ETEXI
 
+DEF("qtest", HAS_ARG, QEMU_OPTION_qtest,
+    "-qtest CHR      specify tracing options\n",
+    QEMU_ARCH_ALL)
+
+DEF("qtest-log", HAS_ARG, QEMU_OPTION_qtest_log,
+    "-qtest-log LOG  specify tracing options\n",
+    QEMU_ARCH_ALL)
+
 HXCOMM This is the last statement. Insert new options before this line!
 STEXI
 @end table
qtest.c new file +357 -0

357 lines not on this page · raw message

qtest.h new file +37 -0
new file mode 100644
index 0000000..f0e1377
@@ -0,0 +1,37 @@
+/*
+ * Test Server
+ *
+ * Copyright IBM, Corp. 2011
+ *
+ * Authors:
+ *  Anthony Liguori   <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#ifndef QTEST_H
+#define QTEST_H
+
+#include "qemu-common.h"
+
+extern int qtest_allowed;
+extern const char *qtest_chrdev;
+extern const char *qtest_log;
+
+static inline bool qtest_enabled(void)
+{
+    return qtest_allowed;
+}
+
+static inline int qtest_available(void)
+{
+    return 1;
+}
+
+int qtest_init(void);
+
+qemu_irq *qtest_interrupt_controller_init(void);
+
+#endif
vl.c +8 -0
index ba55b35..58fb5d9 100644
@@ -152,6 +152,7 @@ int main(int argc, char **argv)
 #ifdef CONFIG_VIRTFS
 #include "fsdev/qemu-fsdev.h"
 #endif
+#include "qtest.h"
 
 #include "disas.h"
 
@@ -1988,6 +1989,7 @@ static struct {
     { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
     { "xen", "Xen", xen_available, xen_init, &xen_allowed },
     { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
+    { "qtest", "QTest", qtest_available, qtest_init, &qtest_allowed },
 };
 
 static int configure_accelerator(void)
@@ -3053,6 +3055,12 @@ int main(int argc, char **argv, char **envp)
                     fclose(fp);
                     break;
                 }
+            case QEMU_OPTION_qtest:
+                qtest_chrdev = optarg;
+                break;
+            case QEMU_OPTION_qtest_log:
+                qtest_log = optarg;
+                break;
             default:
                 os_parse_cmd_args(popt->index, optarg);
             }
Signature · 1 line
1.7.4.1
#1 lore raw

PATCH 2/6 qtest: add support for -M pc

This involves replacing the local APIC with the qtest interrupt controller.

It should be pretty straight forward to do the same for other machine types.

---
 hw/pc_piix.c |    9 ++++++---
 1 files changed, 6 insertions(+), 3 deletions(-)
hw/pc_piix.c +6 -3
index b70431f..2aba89c 100644
@@ -46,6 +46,7 @@
 #ifdef CONFIG_XEN
 #  include <xen/hvm/hvm_info_table.h>
 #endif
+#include "qtest.h"
 
 #define MAX_IDE_BUS 2
 
@@ -154,11 +155,13 @@ static void pc_init1(MemoryRegion *system_memory,
     }
     isa_bus_irqs(isa_bus, gsi);
 
-    if (!xen_enabled()) {
+    if (xen_enabled()) {
+        i8259 = xen_interrupt_controller_init();
+    } else if (qtest_enabled()) {
+        i8259 = qtest_interrupt_controller_init();
+    } else {
         cpu_irq = pc_allocate_cpu_irq();
         i8259 = i8259_init(isa_bus, cpu_irq[0]);
-    } else {
-        i8259 = xen_interrupt_controller_init();
     }
 
     for (i = 0; i < ISA_NUM_IRQS; i++) {
Signature · 1 line
1.7.4.1
#2 lore raw

PATCH 3/6 qtest: add C version of test infrastructure

In reply to Anthony Liguori

This also includes a qtest wrapper script to make it easier to launch qtest tests directly.

---
 scripts/qtest    |    5 +
 tests/Makefile   |    2 +
 tests/libqtest.c |  334 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 tests/libqtest.h |   63 ++++++++++
 4 files changed, 404 insertions(+), 0 deletions(-)
 create mode 100755 scripts/qtest
 create mode 100644 tests/libqtest.c
 create mode 100644 tests/libqtest.h
scripts/qtest new file +5 -0
new file mode 100755
index 0000000..5cff3d4
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+export QTEST_QEMU_BINARY=$1
+shift
+eval "$@"
tests/Makefile +2 -0
index efde63a..92d462a 100644
@@ -34,6 +34,8 @@ test-qmp-input-visitor: test-qmp-input-visitor.o $(qobject-obj-y) $(qapi-obj-y)
 test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) $(qapi-obj-y)
 test-qmp-commands: test-qmp-commands.o $(qobject-obj-y) $(qapi-obj-y) $(tools-obj-y) $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o
 
+tests/rtc-test: tests/rtc-test.o tests/libqtest.o
+
 .PHONY: check
 check: $(CHECKS)
 	gtester $(CHECKS)
tests/libqtest.c new file +334 -0

334 lines not on this page · raw message

tests/libqtest.h new file +63 -0

63 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#3 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

Quoted 4 lines · Anthony Liguori

+    pid = fork();
+    if (pid == 0) {
+        command = g_strdup_printf("%s "
+                                  "-qtest unix:%s,server,nowait "

Quoted 8 lines

+                                  "-qtest-log /dev/null "
+                                  "-pidfile %s "
+                                  "-machine accel=qtest "
+                                  "%s", qemu_binary, socket_path,
+                                  pid_file,
+                                  extra_args ?: "");
+
+        ret = system(command);

qtest_init() launches qemu with a pidfile so that we can send SIGTERM later. But we never get around to doing that if g_assert() fails - it calls abort(3). The result is a run-away qemu process. I find the qemu process consumes 100% in send_all() trying to write to the closed qtest socket and SIGTERM no longer works since we're stuck in a tight loop that never runs the event loop.

A simple solution is to handle SIGABRT in tests/libqtest.c and sent SIGTERM to qemu when the test aborts. The downside is that this only covers the abort(3) case - a segfault or other abnormal termination would still leave the run-away qemu process.

I was wondering about a qemu-side solution where a closed qtest socket means we need to shut down, but am not sure if the chardev code lets us do that. (Really we want POLLHUP but we only seem to have POLLIN/POLLOUT handlers.)

Thoughts?

Stefan

#4 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

Quoted 4 lines · Stefan Hajnoczi

I was wondering about a qemu-side solution where a closed qtest socket means we need to shut down, but am not sure if the chardev code lets us do that. (Really we want POLLHUP but we only seem to have POLLIN/POLLOUT handlers.)

For poll, both POLLIN and POLLOUT are always reported together with POLLHUP. I think the same happens with select(). If you get a zero-read in the qtest chardev handler you can shut down.

Paolo

#5 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

Quoted 11 lines · Paolo Bonzini
Quoted 5 lines · Stefan Hajnoczi

I was wondering about a qemu-side solution where a closed qtest socket means we need to shut down, but am not sure if the chardev code lets us do that.  (Really we want POLLHUP but we only seem to have POLLIN/POLLOUT handlers.)

For poll, both POLLIN and POLLOUT are always reported together with POLLHUP. I think the same happens with select().  If you get a zero-read in the qtest chardev handler you can shut down.

There is already open/closed logic in qemu-char.c that acts on select(2) becoming readable. However, it isn't kicking in - we're still ending up in send_all(), which should only be called when we thing the socket is connected. I'll investigate some more.

Stefan

#6 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

In reply to Anthony Liguori
Quoted 4 lines · Anthony Liguori

This also includes a qtest wrapper script to make it easier to launch qtest tests directly.

Here is a Python test harness for qtest. I haven't tried merging them with the makefiles.

Feel free to add my s-o-b and include the files in your patches.

Paolo

#! /usr/bin/env python
#
# GTester-compatible main program for pyunit
#
# Copyright (C) 2011 Red Hat, Inc.
# Author: Paolo Bonzini <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any

# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# This file defines replacements for unittest.main and unittest.TextTestRunner. # They are command-line compatible with glib test suites, including gtester # support, and even in standalone mode the output is similar to gtest-based # C unit tests. The only unsupported features are -m and --GTestSkipCount. #
# Use this instead of unittest.main:
#
# if __name__ == "__main__":
# gtest_main.main() # run all tests

import sys
import os
import types

import fnmatch
import random
import re
import struct
import time
import traceback

import unittest
from unittest.signals import registerResult, installHandler

# Ugly implementation dependency... used by TestResult to skip internal

# frames in the traceback
__unittest = True

def test_id(test, module='__main__'):
"""Retrieve a GTest-like path from a TestCase.""" id = test.id().replace('.', '/')
if module is not None:
id = id[len(module.__name__):]
return id

class SelectTestsSuite(unittest.TestSuite):
"""A wrapper for other TestSuites that processes -p and -s options.
Perhaps it could also use decorators to implement -m?"""

re = None
module = None

def __init__(self, tests=(), module='__main__', path='*', skipPath=None):
super(unittest.TestSuite, self).__init__(tests=tests) self.module = module

regex = ''
if path != '*':
regex = fnmatch.translate(path)
if skipPath is not None:
regex = '(?!' + fnmatch.translate(skipPath) + ')' + regex
if regex != '':
self.re = re.compile(regex)

def __iter__(self):
iter = super(unittest.TestSuite, self).__iter__() if self.re is not None:
iter = (x for x in iter if self.accept(x))
return iter

def addTest(self, test):
if isinstance(test, unittest.TestSuite):
self.addTests(test)
else:
unittest.TestSuite.addTest(self, test)

def accept(self, test):
id = test_id(test, self.module) return self.re is None or self.re.match(id)

class GTestResult(unittest.TestResult):
"""A test result class that can print formatted text results to a stream
and can talk to gtester using the glib test protocol. Roughly based on TextTestResult, used internally by instances of GAbstractTestRunner."""

separator1 = '=' * 70 + "\n"
separator2 = '-' * 70 + "\n"

def defaultSeed(self):
"""Return a default random number seed. GLib expects this to be
the string 'R02S' followed by four zero-padded 32-bit integers. We need to return a properly formatted seed so that the value can be passed to gtester even when Python and C tests are mixed on the command line."""
try:
s = os.urandom(16)
a, b, c, d = struct.unpack(">IIII", s)
except NotImplementedError:
t = time.time()
a = int(t)
b = int((t - a) * 1000000)
c = os.getpid()
d = os.name = 'posix' and os.getppid() or 0
return "R02S{0:>08x}{1:>08x}{2:>08x}{3:>08x}".format(a,b,c,d)

def __init__(self, log, stream, progName=None, module='__main__', verbosity=1,
seed=None):
super(GTestResult, self).__init__()
self.stream = stream
self.log = log
self.showAll = verbosity > 1
self.quiet = verbosity == 0
self.module = module
self.seed = seed or self.defaultSeed()
self.progName = progName or os.path.basename(sys.argv[0])

# These methods implement the glib test protocol. G_TEST_LOG_NONE = 0
G_TEST_LOG_ERROR = 1 # s:msg
G_TEST_LOG_START_BINARY = 2 # s:binaryname s:seed
G_TEST_LOG_LIST_CASE = 3 # s:testpath
G_TEST_LOG_SKIP_CASE = 4 # s:testpath, TODO
G_TEST_LOG_START_CASE = 5 # s:testpath
G_TEST_LOG_STOP_CASE = 6 # d:status d:nforks d:elapsed
G_TEST_LOG_MIN_RESULT = 7 # s:blurb d:result
G_TEST_LOG_MAX_RESULT = 8 # s:blurb d:result
G_TEST_LOG_MESSAGE = 9 # s:blurb

def pack_log(self, typ, strings=(), nums=()):
out = struct.pack(">iiii", typ, len(strings), len(nums), 0) for s in strings:
out = out + struct.pack(">i", len(s)) + s
for n in nums:
out = out + struct.pack(">d", float(n))
out = struct.pack(">i", len(out) + 4) + out self.log.write(out)

def logStartBinary(self):
self.pack_log(self.G_TEST_LOG_START_BINARY, (self.progName, self.seed))

def logStartCase(self, test):
id = test_id(test, self.module) self.pack_log(self.G_TEST_LOG_START_CASE, (id,))

def logListCase(self, test):
id = test_id(test, self.module) self.pack_log(self.G_TEST_LOG_LIST_CASE, (id,))

def logError(self, msg):
self.pack_log(self.G_TEST_LOG_ERROR, (msg,))

def logMessage(self, msg):
self.pack_log(self.G_TEST_LOG_MESSAGE, (msg,))

def logStopCase(self, status):
try:
elapsed = time.clock() - self.startCaseTime self.pack_log(self.G_TEST_LOG_STOP_CASE, nums=(status,0,elapsed))
except:
# This happens when class setup fails. startCaseTime has not # been set, do nothing
assert status != 0
pass

def logException(self, test, kind, err, skip=1):
"""Return a representation for the exception passed to addError
or addFailure."""
type, inst, trace=err
try:
file, line, func, text = traceback.extract_tb(trace, skip+1)[skip] msg = "%s:%s:%s:%s: %s\n" % (kind, file, line, type.__name__, inst)
except:
msg = "%s:%s: %s\n" % (kind, type.__name__, inst)
self.write("**\n" + msg)
self.logError(msg + self.separator1 + self._exc_info_to_string(err, test))

# These methods implement text output.
def write(self, str):
self.stream.write(str)

def flush(self):
self.stream.flush()

# These methods implement the standard TestResult protocol. def startTestRun(self):
self.logStartBinary()
self.startTime = time.clock()

def stopTestRun(self):
self.stopTime = time.clock()

def startTest(self, test):
super(GTestResult, self).startTest(test) random.seed(self.seed) self.startCaseTime = time.clock() self.logStartCase(test)
if not self.quiet:
self.write(test_id(test, self.module)) self.write(": ")
self.flush()

def addSuccess(self, test):
super(GTestResult, self).addSuccess(test)
self.logStopCase(0)
if not self.quiet:
self.write("OK\n")

def addError(self, test, err):
self.logException(test, "ERROR", err) self.logStopCase(1) super(GTestResult, self).addError(test, err)

def addFailure(self, test, err):
self.logException(test, "FAIL", err) self.logStopCase(1) super(GTestResult, self).addFailure(test, err)

def addSkip(self, test, reason):
self.logStopCase(0) super(GTestResult, self).addSkip(test, reason) if not self.quiet:
self.write("SKIP {0!r}\n".format(reason))

def addExpectedFailure(self, test, err):
self.logException("XFAIL", err) self.logStopCase(0)
super(GTestResult, self).addExpectedFailure(test, err) if not self.quiet:
self.write("XFAIL\n")

def addUnexpectedSuccess(self, test):
self.logError("unexpected success") self.logStopCase(1)
super(GTestResult, self).addUnexpectedSuccess(test) if not self.quiet:
self.write("XPASS\n")

# Additional methods used by GTestLister and GTestRunner. def listTest(self, test):
super(GTestResult, self).startTest(test) self.logListCase(test)
if not self.quiet:
self.write(test_id(test, self.module)) self.write("\n")
self.flush()
super(GTestResult, self).addSuccess(test)

def printErrors(self):
self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) self.write(self.separator2)

def printErrorList(self, kind, errors):
for test, err in errors:
self.write(self.separator1)
self.write("%s: %s\n" % (kind,test_id(test, self.module))) self.write(self.separator2)
self.write("%s\n" % err)

def printSummary(self):
run = self.testsRun
timeTaken = self.stopTime - self.startTime
if not self.quiet:
self.write("Ran %d test%s in %.3fs\n\n" %
(run, run != 1 and "s" or "", timeTaken))

infos = []
failed = len(self.failures)
if failed:
infos.append("failures=%d" % failed)

errored = len(self.errors)
if errored:
infos.append("errors=%d" % errored)

skipped = len(self.skipped)
if skipped:
infos.append("skipped=%d" % skipped)

expectedFails = len(self.expectedFailures)
if expectedFails:
infos.append("expected failures=%d" % expectedFails)

unexpectedSuccesses = len(self.unexpectedSuccesses) if unexpectedSuccesses:
infos.append("unexpected successes=%d" % unexpectedSuccesses)

if not self.wasSuccessful():
self.write("FAILED (%s)\n" % (", ".join(infos),))
elif infos:
self.write("OK (%s)\n" % (", ".join(infos),))
elif not self.quiet:
self.write("OK\n")

def printResults(self):
if self.quiet or self.showAll:
if self.showAll:
self.write("\n")
self.printErrors()
self.printSummary()

class GAbstractTestRunner(object):
"""A test runner class that interfaces to a GTestResult. Compared
to e.g. TextTestRunner, it can pass down some data that is required by the glib test protocol (program name, random number seed)."""

def __init__(self, log=None, stream=sys.stdout, verbosity=1, progName=None,
module='__main__', failfast=True, seed=None, buffer=False):
self.module = module
self.verbosity = verbosity
self.failfast = failfast
self.buffer = buffer
self.progName = progName
self.seed = seed

class _DummyStream(object):
def write(self, s):
pass

self.log = log or _DummyStream() self.stream = log and _DummyStream() or stream

def _makeResult(self):
return GTestResult(stream=self.stream, log=self.log, module=self.module,
seed=self.seed, progName=self.progName, verbosity=self.verbosity)

def run(self, test):
"Run the given test case or test suite." result = self._makeResult() registerResult(result)
result.failfast = self.failfast result.buffer = self.buffer
startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None:
startTestRun()
try:
self.doRun(test, result)
finally:
stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None:
stopTestRun()
return result

def doRun(self, test, result):
"Run the given test case or test suite."
test(result)

class GTestLister(GAbstractTestRunner):
"""A test runner class that only prints the names of test cases.
in the suite.

When run in standalone mode it prints out the names of tests that have been selected. When run in gtester mode, it logs the same information using the glib test protocol."""

def doRun(self, test, result):
"""Run the given test case or test suite (actually just ask the
GTestResult to list the test case)."""
for t in test:
result.listTest(t)

class GTestRunner(GAbstractTestRunner):
"""A test runner class that emits results in textual and GLib form.

When run in standalone mode it prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run, depending on the verbosity level. When run in gtester mode, it logs the entire run using the glib test protocol."""

def run(self, test):
"Run the given test case or test suite." result = super(GTestRunner, self).run(test) result.printResults()
return result

USAGE = """\
Usage: %(progName)s [options]

Help Options:
-?, --help Show help options
Test Options:
-l List test cases available in a test executable
-seed=RANDOMSEED Provide a random seed to reproduce test
runs using random numbers

  -v, --verbose                  Run tests verbosely
  -q, --quiet                    Run tests quietly
  -p TESTPATH                    execute all tests matching TESTPATH
  -s TESTPATH                    skip all tests matching TESTPATH
  -m {perf|slow|thorough|quick}  (unsupported) Execute tests according to mode
  -k, --keep-going               Keep running after the first failure
  --runner=CLASS                 Use an alternative test runner

(e.g. unittest.TextTestRunner)
--GTestLogFD=N file descriptor for communication with GTester
--GTestSkipCount=N (unsupported) gtester-specific argument

-p and -s accept slash-separated paths. They work even in combination with --runner. -l and --GTestLogFD are only supported without --runner. """

class GTestProgram(object):
"""A command-line program that runs a set of tests, used to make test
modules conveniently executable and to interface them with gtester."""

failfast = True
progName = None
seed = None
exit = True
logFD = None
verbosity = 1
path = '*'
skipPath = None

def getModule(self, module):
if isinstance(module, basestring):
m = __import__(module)
for part in module.split('.')[1:]:
m = getattr(m, part)
return m
else:
return module

def getClass(self, name):
if isinstance(name, basestring):
parts = name.split('.')
module = ".".join(parts[:-1])
m = self.getModule(module)
return getattr(m, parts[-1])
else:
return name

def __init__(self, module='__main__', argv=None,
testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, seed=None):
argv = argv or sys.argv
self.module = self.getModule(module)
self.exit = exit
self.seed = seed
self.testRunner = testRunner
self.testLoader = testLoader
self.progName = os.path.basename(argv[0]) self.parseArgs(argv)
self.suite = self.createTests()
self.runTests()

def usageExit(self, msg=None):
if msg:
print msg
print USAGE % {'progName': self.progName}
if self.exit:
sys.exit(2)

def parseArgs(self, argv):
import getopt
long_opts = ['seed=', 'keep-going', 'verbose', 'quiet', 'GTestLogFD=',
'runner=', 'GTestSkipCount=']
list = False
try:
options, args = getopt.getopt(argv[1:], '?hHlvqs:p:m:k', long_opts) for opt, value in options:
# quirk in the gtest option parser...
if opt[1] != '-' and value != '' and value[0] == '=':
value = value[1:]

if opt in ('-h','-H','-?','--help'):
self.usageExit()
if opt in ('-q','--quiet'):
self.verbosity = 0
if opt in ('-v','--verbose'):
self.verbosity = 2
if opt in ('-k','--keep-going'):
self.failfast = False
if opt in ('-l'):
list = True
if opt in ('-p'):
self.path = value
if opt in ('-s'):
self.skipPath = value
if opt in ('--seed'):
self.seed = value
if opt in ('--runner'):
self.testRunner = self.getClass(value)
if opt in ('--GTestLogFD'):
self.logFD = int(value)
except getopt.error, msg:
self.usageExit(msg)

if self.testRunner is None:
self.testRunner = list and GTestLister or GTestRunner
else:
# Set the seed now for user-specified runners. GTestRunners # resets it for each testcase, so that results are reproducible # even if other tests change. random.seed(self.seed)

def createTests(self):
allTests = self.testLoader.loadTestsFromModule(self.module) return SelectTestsSuite(tests=allTests, path=self.path, skipPath=self.skipPath,
module=self.module)

def runTests(self):
installHandler()
if isinstance(self.testRunner, type) and \
issubclass(self.testRunner, GAbstractTestRunner):
# pass GTest-specific options to GAbstractTestRunner subclasses testRunner = self.testRunner(verbosity=self.verbosity,
failfast=self.failfast, module=self.module, progName=self.progName, seed=self.seed,
log=self.logFD and os.fdopen(self.logFD, 'w'))
elif isinstance(self.testRunner, (type, types.ClassType)):
try:
testRunner = self.testRunner(verbosity=self.verbosity,
failfast=self.failfast)
except TypeError:
testRunner = self.testRunner()
else:
# it is assumed to be a TestRunner instance
testRunner = self.testRunner

self.result = testRunner.run(self.suite) if self.exit:
sys.exit(not self.result.wasSuccessful())

main = GTestProgram

#! /usr/bin/env python
#

# qtest harness for PyUnit
#
#    Copyright (C) 2011 Red Hat, Inc.
#    Author: Paolo Bonzini <[email protected]>
#
# This file is licensed under the terms of the GNU GPL, version 2 or later.
# See the COPYING file in the top-level directory.

import os
import struct
import socket
import unittest

class ClientDisconnected(Exception):
pass

class QTestCase(unittest.TestCase):
@classmethod
def supportedArches():
return ['all']

@classmethod
def extraArgs():
return ()

@classmethod
def isSupportedArch(self, arch):
return any(x == 'all' or x == arch for x in self.supportedArches())

@classmethod
def _raiseIRQ(self, irq):
self._irqs.add(irq)

@classmethod
def _lowerIRQ(self, irq):
self._irqs.discard(irq)

@classmethod
def setUpClass(self):
qemu_binary = os.getenv('QTEST_QEMU_BINARY')
arch = os.path.basename(qemu_binary).replace('qemu-system-','') if not self.isSupportedArch(arch):
self._classSetupFailed = True
return

socket_path = '/tmp/qtest-%d.sock' % os.getpid() server_socket = socket.socket(socket.AF_UNIX) server_socket.bind(socket_path) server_socket.listen(1)

self.pid = os.spawnl(os.P_NOWAIT, qemu_binary,
qemu_binary,
'-qtest', 'unix:%s' % socket_path, '-qtest-log', '/dev/null', '-machine', 'accel=qtest', *self.extraArgs())

self._socket, addr = server_socket.accept() self._irqs = set()
self._buffer = ''
self._reply = None server_socket.close()

@classmethod
def tearDownClass(self):
self._socket.close()
self._socket = None
os.kill(self.pid, 15)
os.waitpid(self.pid, 0)

@classmethod
def _qtestResponse(self, buf):
tokens = buf.split()
if tokens[0] == 'OK':
self._reply = tokens
return

if tokens[0] == 'IRQ':
if tokens[1] == 'raise':
self._raiseIRQ(int(tokens[2]))
else:
self._lowerIRQ(int(tokens[2]))
return

@classmethod
def waitForEvents(self, blocking=True):
self._socket.setblocking(int(blocking))
while True:
i = self._buffer.find('\n')
if i != -1:
response, self._buffer = self._buffer[:i], self._buffer[i+1:] self._qtestResponse(response) self._socket.setblocking(0)
continue

try:
data = self._socket.recv(4096) self._buffer = self._buffer + data if (len(data) == 0):
raise ClientDisconnected
except:
return

@classmethod
def _send(self, str):
assert self._reply is None
self._socket.sendall(str + '\n')
while self._reply is None:
self.waitForEvents()
reply, self._reply = self._reply, None
return reply

# IRQ access
def getIRQ(self, irq):
self.waitForEvents(False)
return irq in self._irqs

def waitIRQ(self, irq, level=True):
self.waitForEvents(False)
while (irq in self._irqs) != level:
self.waitForEvents(True)

# PIO reads
def inb(self, port):
return int(self._send('inb 0x%x' % port)[1][2:], 16)

def inw(self, port):
return int(self._send('inw 0x%x' % port)[1][2:], 16)

def inl(self, port):
return int(self._send('inl 0x%x' % port)[1][2:], 16)

# Memory reads
def memread_unpack(self, addr, format):
size = struct.calcsize(format)
str = 'read 0x%x 0x%x' % (addr, size)
reply = self._send(str)[1]
bytes = reply[2:].decode('hex_codec')
return struct.unpack(format, bytes)

def memread(self, addr, size):
return self.memread_unpack('%dB' % size)

def ldb(self, addr):
return self.memread_unpack(addr, 'B')[0]

def ldw_le(self, addr):
return self.memread_unpack(addr, '<H')[0]

def ldl_le(self, addr):
return self.memread_unpack(addr, '<I')[0]

def ldw_be(self, addr):
return self.memread_unpack(addr, '>H')[0]

def ldl_be(self, addr):
return self.memread_unpack(addr, '>I')[0]

# PIO writes
def outb(self, port, val):
self._send('outb 0x%x 0x%x' % (port, val))

def outw(self, port, val):
self._send('outw 0x%x 0x%x' % (port, val))

def outl(self, port, val):
self._send('outl 0x%x 0x%x' % (port, val))

# Memory writes
def memwrite_pack(self, addr, format, *data):
bytes = struct.pack(format, *data)
str = 'write 0x%x 0x%x 0x%s' % (
addr, len(bytes), bytes.encode('hex_codec'))
self._send(str)

def memwrite(self, addr, *data):
self.memwrite_pack('%dB' % len(data), *data)

def stb(self, addr, datum):
self.memwrite_pack(addr, 'B', datum)

def stw_le(self, addr, datum):
self.memwrite_pack(addr, '<H', datum)

def stl_le(self, addr, datum):
self.memwrite_pack(addr, '<I', datum)

def stw_be(self, addr, datum):
self.memwrite_pack(addr, '>H', datum)

def stl_be(self, addr, datum):
self.memwrite_pack(addr, '>I', datum)

#! /usr/bin/env python
#
# Sample qtest written in Python
#
# Copyright (C) 2011 Red Hat, Inc.
# Author: Paolo Bonzini <[email protected]>
#
# This file is licensed under the terms of the GNU GPL, version 2 or later. # See the COPYING file in the top-level directory.

import time
import qtest
import gtest_main

class QTestCase(qtest.QTestCase):

    @classmethod
    def supportedArches(self):
        return ['i386', 'x86_64']

    @classmethod
    def extraArgs(self):
        return ('-vga', 'none')

    BASE = 0x70
    RTC_SECONDS = 0
    RTC_MINUTES = 2
    RTC_HOURS = 4

    def read(self, reg):
        self.outb(self.BASE, reg)
        return self.inb(self.BASE + 1)

    def write(self, reg, value):
        self.outb(self.BASE, reg)
        self.outb(self.BASE + 1, value)

    def testRead(self):
        self.write(self.RTC_HOURS, 0x01)
        self.write(self.RTC_MINUTES, 0x15)
        self.write(self.RTC_SECONDS, 0x29)
        assert self.read(self.RTC_MINUTES) == 0x15
        assert self.read(self.RTC_HOURS) == 0x01

    def testUpdate(self):
        self.write(self.RTC_HOURS, 0x01)
        self.write(self.RTC_MINUTES, 0x15)
        self.write(self.RTC_SECONDS, 0x29)
        while self.read(self.RTC_SECONDS) == 0x29:
            time.sleep(0.2)
        assert self.read(self.RTC_SECONDS) == 0x30

if __name__ == '__main__':
gtest_main.main()

#7 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

In reply to Anthony Liguori

Am 13.01.2012 19:32, schrieb Anthony Liguori:

Quoted 38 lines

This also includes a qtest wrapper script to make it easier to launch qtest tests directly.

tests/libqtest.c new file +33 -0
+QTestState *qtest_init(const char *extra_args)
+{
+    QTestState *s;
+    struct sockaddr_un addr;
+    int sock, ret, i;
+    gchar *socket_path;
+    gchar *pid_file;
+    gchar *command;
+    const char *qemu_binary;
+    pid_t pid;
+
+    qemu_binary = getenv("QTEST_QEMU_BINARY");
+    g_assert(qemu_binary != NULL);
+
+    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
+    pid_file = g_strdup_printf("/tmp/qtest-%d.pid", getpid());
+
+    s = g_malloc(sizeof(*s));
+
+    sock = socket(PF_UNIX, SOCK_STREAM, 0);
+    g_assert_no_errno(sock);
+
+    addr.sun_family = AF_UNIX;
+    snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
+
+    pid = fork();
+    if (pid == 0) {
+        command = g_strdup_printf("%s "
+                                  "-qtest unix:%s,server,nowait "
+                                  "-qtest-log /dev/null "
+                                  "-pidfile %s "
+                                  "-machine accel=qtest "
+                                  "%s", qemu_binary, socket_path,

tests/libqtest.c line 84

Quoted 10 lines
tests/libqtest.c new file +10 -0
+                                  pid_file,
+                                  extra_args ?: "");
+
+        ret = system(command);
+        exit(ret);
+        g_free(command);
+    }
+
+    do {
+        sleep(1);

This is the line that takes the greatest part of the time for make check-qtest. Can we use some shorter delay if it's required at all?

Quoted 5 lines
tests/libqtest.c new file +5 -0
+        ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
+    } while (ret == -1);
+    g_assert_no_errno(ret);
+
+    s->fd = sock;

tests/libqtest.c line 99

Quoted 10 lines
tests/libqtest.c new file +10 -0
+    s->rx = g_string_new("");
+    s->pid_file = pid_file;
+    for (i = 0; i < MAX_IRQ; i++) {
+        s->irq_level[i] = false;
+    }
+
+    g_free(socket_path);
+
+    return s;
+}

Kevin

#8 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

Quoted 4 lines · Kevin Wolf
Quoted 2 lines
Quoted 2 lines

+ do {
+ sleep(1);

This is the line that takes the greatest part of the time for make check-qtest. Can we use some shorter delay if it's required at all?

You can use a client socket, listen before spawning QEMU and accept afterwards. It's what I did in the Python version.

Paolo

#9 lore raw

Re: [Qemu-devel] [PATCH 3/6] qtest: add C version of test infrastructure

In reply to Kevin Wolf
Quoted 44 lines · Kevin Wolf

Am 13.01.2012 19:32, schrieb Anthony Liguori:

Quoted 43 lines

This also includes a qtest wrapper script to make it easier to launch qtest tests directly.

tests/libqtest.c new file +38 -0
+QTestState *qtest_init(const char *extra_args)
+{
+    QTestState *s;
+    struct sockaddr_un addr;
+    int sock, ret, i;
+    gchar *socket_path;
+    gchar *pid_file;
+    gchar *command;
+    const char *qemu_binary;
+    pid_t pid;
+
+    qemu_binary = getenv("QTEST_QEMU_BINARY");
+    g_assert(qemu_binary != NULL);
+
+    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
+    pid_file = g_strdup_printf("/tmp/qtest-%d.pid", getpid());
+
+    s = g_malloc(sizeof(*s));
+
+    sock = socket(PF_UNIX, SOCK_STREAM, 0);
+    g_assert_no_errno(sock);
+
+    addr.sun_family = AF_UNIX;
+    snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
+
+    pid = fork();
+    if (pid == 0) {
+        command = g_strdup_printf("%s "
+                                  "-qtest unix:%s,server,nowait "
+                                  "-qtest-log /dev/null "
+                                  "-pidfile %s "
+                                  "-machine accel=qtest "
+                                  "%s", qemu_binary, socket_path,
+                                  pid_file,
+                                  extra_args ?: "");
+
+        ret = system(command);
+        exit(ret);
Quoted 8 lines

tests/libqtest.c line 84

Quoted 5 lines
tests/libqtest.c new file +5 -0
+        g_free(command);
+    }
+
+    do {
+        sleep(1);

This is the line that takes the greatest part of the time for make check-qtest. Can we use some shorter delay if it's required at all?

Ah, good catch. It should change to a usleep().

It is needed, you can't guarantee that qemu is listening yet on the sockets when you try to connect.

Regards,

Anthony Liguori

Quoted 19 lines
Quoted 6 lines
tests/libqtest.c new file +5 -0
+        ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
+    } while (ret == -1);
+    g_assert_no_errno(ret);
+
+    s->fd = sock;

tests/libqtest.c line 99

Quoted 10 lines
tests/libqtest.c new file +10 -0
+    s->rx = g_string_new("");
+    s->pid_file = pid_file;
+    for (i = 0; i<  MAX_IRQ; i++) {
+        s->irq_level[i] = false;
+    }
+
+    g_free(socket_path);
+
+    return s;
+}

Kevin

#10 lore raw

PATCH 4/6 make: add check targets based on gtester

In reply to Anthony Liguori

This will run all tests through gtester. The main targets are:

$ make check

Which will run each unit test and:

$ make check-report.html

Which will generate a nice HTML report of the test status.

---
 scripts/gtester-cat |   32 ++++++++++++++++++++++++++++
 tests/Makefile      |   58 ++++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 87 insertions(+), 3 deletions(-)
 create mode 100755 scripts/gtester-cat
scripts/gtester-cat new file +32 -0
new file mode 100755
index 0000000..afd8c3e
@@ -0,0 +1,32 @@
+#!/bin/sh
+#
+# Copyright IBM, Corp. 2012
+#
+# Authors:
+#  Anthony Liguori <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPLv2 or later.
+# See the COPYING file in the top-level directory.
+
+cat <<EOF
+<?xml version="1.0"?>
+<gtester>
+EOF
+
+for file in "$@"; do
+    first="yes"
+    cat $file | while read LINE; do
+	if test "$first" = "yes"; then
+	    first="no"
+	    continue
+	fi
+	if test "$LINE" = "<gtester>" -o "$LINE" = "</gtester>"; then
+	    continue
+	fi
+	echo $LINE
+    done
+done
+
+cat<<EOF
+</gtester>
+EOF
tests/Makefile +55 -3

67 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#11 lore raw

Re: [Qemu-devel] [PATCH 4/6] make: add check targets based on gtester

Quoted 9 lines · Anthony Liguori

This will run all tests through gtester. The main targets are:

$ make check

Which will run each unit test and:

$ make check-report.html

Which will generate a nice HTML report of the test status.

Looks like there isn't any documentation about the protocol that gtester uses, and no Python implementation of the same in any other language. Or dually, no support for TAP output in gtester. :/

I would have expected a bit less NIH from glib, but oh well...

Paolo

#12 lore raw

Re: [Qemu-devel] [PATCH 4/6] make: add check targets based on gtester

Quoted 9 lines · Paolo Bonzini
Quoted 8 lines · Anthony Liguori

This will run all tests through gtester. The main targets are:

$ make check

Which will run each unit test and:

$ make check-report.html
Quoted 7 lines
Quoted 1 line

Which will generate a nice HTML report of the test status.

Looks like there isn't any documentation about the protocol that gtester uses, and no Python implementation of the same in any other language. Or dually, no support for TAP output in gtester. :/

I would have expected a bit less NIH from glib, but oh well...

Yes, I had a similar reaction.

But it's good enough for our purposes and only depends on our mandatory dependencies.

Regards,

Anthony Liguori

Quoted 4 lines

Paolo

#13 lore raw

Re: [Qemu-devel] [PATCH 4/6] make: add check targets based on gtester

Quoted 7 lines · Anthony Liguori
Quoted 7 lines

Looks like there isn't any documentation about the protocol that gtester uses,
and no Python implementation of the same in any other language. Or dually, no
support for TAP output in gtester. :/

Quoted 6 lines
Quoted 1 line

I would have expected a bit less NIH from glib, but oh well...

Yes, I had a similar reaction.

But it's good enough for our purposes and only depends on our mandatory dependencies.

Agreed. I'm looking into writing a gtest runner for pyunit.

Paolo

#14 lore raw

Re: [Qemu-devel] [PATCH 4/6] make: add check targets based on gtester

In reply to Anthony Liguori
Quoted 9 lines · Anthony Liguori

This will run all tests through gtester. The main targets are:

$ make check

Which will run each unit test and:

$ make check-report.html

Which will generate a nice HTML report of the test status.

gtester-report here (Fedora 16) has a bug where it needs something like this:

<info>
<package>qemu</package>
<version>0.0</version>
<revision>rev</revision>
</info>

inside the <gtester> tag. Any chance you could generate these tags from gtester-cat so that gtester-report actually works?

Paolo

#15 lore raw

Re: [Qemu-devel] [PATCH 4/6] make: add check targets based on gtester

Quoted 13 lines · Paolo Bonzini
Quoted 9 lines · Anthony Liguori

This will run all tests through gtester. The main targets are:

$ make check

Which will run each unit test and:

$ make check-report.html

Which will generate a nice HTML report of the test status.

gtester-report here (Fedora 16) has a bug where it needs something like this:

Quoted 8 lines

<info>
<package>qemu</package>
<version>0.0</version>
<revision>rev</revision>
</info>

inside the <gtester> tag. Any chance you could generate these tags from gtester-cat so that gtester-report actually works?

Sure.

Regards,

Anthony Liguori

Quoted 1 line

Paolo

#16 lore raw

PATCH 5/6 rtc: split out macros into a header file and use in test case

In reply to Anthony Liguori
---
 hw/mc146818rtc.c      |   33 --------------------------
 hw/mc146818rtc.h      |    3 +-
 hw/mc146818rtc_regs.h |   62 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 63 insertions(+), 35 deletions(-)
 create mode 100644 hw/mc146818rtc_regs.h
hw/mc146818rtc.c +0 -33
index 657fa10..258d3a8 100644
@@ -46,39 +46,6 @@
 
 #define RTC_REINJECT_ON_ACK_COUNT 20
 
-#define RTC_SECONDS             0
-#define RTC_SECONDS_ALARM       1
-#define RTC_MINUTES             2
-#define RTC_MINUTES_ALARM       3
-#define RTC_HOURS               4
-#define RTC_HOURS_ALARM         5
-#define RTC_ALARM_DONT_CARE    0xC0
-
-#define RTC_DAY_OF_WEEK         6
-#define RTC_DAY_OF_MONTH        7
-#define RTC_MONTH               8
-#define RTC_YEAR                9
-
-#define RTC_REG_A               10
-#define RTC_REG_B               11
-#define RTC_REG_C               12
-#define RTC_REG_D               13
-
-#define REG_A_UIP 0x80
-
-#define REG_B_SET  0x80
-#define REG_B_PIE  0x40
-#define REG_B_AIE  0x20
-#define REG_B_UIE  0x10
-#define REG_B_SQWE 0x08
-#define REG_B_DM   0x04
-#define REG_B_24H  0x02
-
-#define REG_C_UF   0x10
-#define REG_C_IRQF 0x80
-#define REG_C_PF   0x40
-#define REG_C_AF   0x20
-
 typedef struct RTCState {
     ISADevice dev;
     MemoryRegion io;
hw/mc146818rtc.h +1 -2
index f119930..f286b6a 100644
@@ -2,8 +2,7 @@
 #define MC146818RTC_H
 
 #include "isa.h"
-
-#define RTC_ISA_IRQ 8
+#include "mc146818rtc_regs.h"
 
 ISADevice *rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq);
 void rtc_set_memory(ISADevice *dev, int addr, int val);
hw/mc146818rtc_regs.h new file +62 -0

62 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#17 lore raw

PATCH 6/6 qtest: add rtc-test test-case

In reply to Anthony Liguori
---
 tests/Makefile   |    2 +-
 tests/rtc-test.c |  281 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 282 insertions(+), 1 deletions(-)
 create mode 100644 tests/rtc-test.c
tests/Makefile +1 -1
index 9db8553..a6b993c 100644
@@ -2,7 +2,7 @@ CHECKS = check-qdict check-qfloat check-qint check-qstring check-qlist
 CHECKS += check-qjson test-qmp-output-visitor test-qmp-input-visitor
 CHECKS += test-coroutine
 
-HW_TESTS=
+HW_TESTS=tests/rtc-test
 
 TARGETS=$(patsubst %-softmmu,%, $(filter %-softmmu,$(TARGET_DIRS)))
 
tests/rtc-test.c new file +281 -0

281 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#18 lore raw
In reply to Anthony Liguori
Quoted 27 lines · Anthony Liguori

+    if (strcmp(words[0], "outb") == 0 ||
+        strcmp(words[0], "outw") == 0 ||
+        strcmp(words[0], "outl") == 0) {
+        uint16_t addr;
+        uint32_t value;

qtest.c new file +22 -0
+
+        g_assert(words[1] && words[2]);
+        addr = strtol(words[1], NULL, 0);
+        value = strtol(words[2], NULL, 0);
+
+        if (words[0][3] == 'b') {
+            cpu_outb(addr, value);
+        } else if (words[0][3] == 'w') {
+            cpu_outw(addr, value);
+        } else if (words[0][3] == 'l') {
+            cpu_outl(addr, value);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK\n");
+    } else if (strcmp(words[0], "inb") == 0 ||
+        strcmp(words[0], "inw") == 0 ||
+        strcmp(words[0], "inl") == 0) {
+        uint16_t addr;
+        uint32_t value = -1U;
+
+        g_assert(words[1]);
+        addr = strtol(words[1], NULL, 0);

qtest.c line 194

Quoted 10 lines
qtest.c new file +10 -0
+
+        if (words[0][2] == 'b') {
+            value = cpu_inb(addr);
+        } else if (words[0][2] == 'w') {
+            value = cpu_inw(addr);
+        } else if (words[0][2] == 'l') {
+            value = cpu_inl(addr);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here. memory.c will byteswap if target and device endianness differ.

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian). Since ppc (target endian) is big-endian and the device is little-endian the value read/written will be byteswapped. However, our qtest runs on the host and therefore we don't want that automatic swap (or we need to neutralize it by performing another byteswap on top).

Stefan

#19 lore raw
Quoted 7 lines · Stefan Hajnoczi

qtest.c line 194

Quoted 3 lines
qtest.c new file +3 -0
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here. memory.c will byteswap if target and device endianness differ.

Quoted 7 lines

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian). Since ppc (target endian) is big-endian and the device is little-endian the value read/written will be byteswapped. However, our qtest runs on the host and therefore we don't want that automatic swap (or we need to neutralize it by performing another byteswap on top).

Good catch. This is another example of how an access depends not only on the destination, but also on the source. Here the source is not the cpu; it's qtest.

Signature · 1 line
error compiling committee.c: too many arguments to function
#20 lore raw
Quoted 16 lines · Avi Kivity
Quoted 7 lines · Stefan Hajnoczi

qtest.c line 194

Quoted 3 lines
qtest.c new file +3 -0
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here. memory.c will byteswap if target and device endianness differ.

Quoted 7 lines

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian). Since ppc (target endian) is big-endian and the device is little-endian the value read/written will be byteswapped. However, our qtest runs on the host and therefore we don't want that automatic swap (or we need to neutralize it by performing another byteswap on top).

Quoted 3 lines

Good catch. This is another example of how an access depends not only on the destination, but also on the source. Here the source is not the cpu; it's qtest.

target-ppc never calls cpu_out. It's prep_pci.c that calls it based on an MMIO operation and that's where the endianess conversion happens.

You wouldn't use outw() in a qtest harness when talking to a PCI device over PPC.

What we really want is to be able to send I/O directly to MemoryRegions but that's a bit different than what qtest is.

Regards,

Anthony Liguori

Quoted 1 line
#21 lore raw
In reply to Stefan Hajnoczi
Quoted 42 lines · Stefan Hajnoczi
Quoted 27 lines · Anthony Liguori
qtest.c new file +27 -0
+    if (strcmp(words[0], "outb") == 0 ||
+        strcmp(words[0], "outw") == 0 ||
+        strcmp(words[0], "outl") == 0) {
+        uint16_t addr;
+        uint32_t value;
+
+        g_assert(words[1]&&  words[2]);
+        addr = strtol(words[1], NULL, 0);
+        value = strtol(words[2], NULL, 0);
+
+        if (words[0][3] == 'b') {
+            cpu_outb(addr, value);
+        } else if (words[0][3] == 'w') {
+            cpu_outw(addr, value);
+        } else if (words[0][3] == 'l') {
+            cpu_outl(addr, value);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK\n");
+    } else if (strcmp(words[0], "inb") == 0 ||
+        strcmp(words[0], "inw") == 0 ||
+        strcmp(words[0], "inl") == 0) {
+        uint16_t addr;
+        uint32_t value = -1U;
+
+        g_assert(words[1]);
+        addr = strtol(words[1], NULL, 0);

qtest.c line 194

Quoted 10 lines
qtest.c new file +10 -0
+
+        if (words[0][2] == 'b') {
+            value = cpu_inb(addr);
+        } else if (words[0][2] == 'w') {
+            value = cpu_inw(addr);
+        } else if (words[0][2] == 'l') {
+            value = cpu_inl(addr);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here. memory.c will byteswap if target and device endianness differ.

Quoted 2 lines

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian).

These functions expect to get host native endian. The qtest wire protocol is a string (which has no endianness) and converts it to host native endian.

Quoted 5 lines

Since ppc
(target endian) is big-endian and the device is little-endian the value read/written will be byteswapped. However, our qtest runs on the host and therefore we don't want that automatic swap (or we need to neutralize it by performing another byteswap on top).

ppc wouldn't use outb/inb. It would do mmio to the PIO region which would send it through the host controller (which would do byte swapping as necessary).

So a qtest test case would have to do little endian MMIO to interact with the PCI bus.

Regards,

Anthony Liguori

Quoted 3 lines

Stefan

#22 lore raw
Quoted 47 lines · Anthony Liguori
Quoted 46 lines · Stefan Hajnoczi
Quoted 28 lines · Anthony Liguori

+    if (strcmp(words[0], "outb") == 0 ||
+        strcmp(words[0], "outw") == 0 ||
+        strcmp(words[0], "outl") == 0) {
+        uint16_t addr;
+        uint32_t value;

qtest.c new file +22 -0
+
+        g_assert(words[1]&&  words[2]);
+        addr = strtol(words[1], NULL, 0);
+        value = strtol(words[2], NULL, 0);
+
+        if (words[0][3] == 'b') {
+            cpu_outb(addr, value);
+        } else if (words[0][3] == 'w') {
+            cpu_outw(addr, value);
+        } else if (words[0][3] == 'l') {
+            cpu_outl(addr, value);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK\n");
+    } else if (strcmp(words[0], "inb") == 0 ||
+        strcmp(words[0], "inw") == 0 ||
+        strcmp(words[0], "inl") == 0) {
+        uint16_t addr;
+        uint32_t value = -1U;
+
+        g_assert(words[1]);
+        addr = strtol(words[1], NULL, 0);

qtest.c line 194

Quoted 10 lines
qtest.c new file +10 -0
+
+        if (words[0][2] == 'b') {
+            value = cpu_inb(addr);
+        } else if (words[0][2] == 'w') {
+            value = cpu_inw(addr);
+        } else if (words[0][2] == 'l') {
+            value = cpu_inl(addr);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here.  memory.c will byteswap if target and device endianness differ.

Quoted 6 lines
Quoted 2 lines

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian).

These functions expect to get host native endian.  The qtest wire protocol is a string (which has no endianness) and converts it to host native endian.

The cpu_inl() return value is not host native endian. We perform a byteswap if the memory region endianness is different from the target endianness. For example, big-endian target and little-endian device means we byteswap. Little-endian target and little-endian device means we do not byteswap.

Running the same test binary against qemu-system-x86_64 and qemu-system-$be_arch results in 0 and 1 byteswaps, respectively. Both can't be right.

Quoted 7 lines
Quoted 5 lines

 Since ppc
(target endian) is big-endian and the device is little-endian the value read/written will be byteswapped.  However, our qtest runs on the host and therefore we don't want that automatic swap (or we need to neutralize it by performing another byteswap on top).

Quoted 6 lines

ppc wouldn't use outb/inb.  It would do mmio to the PIO region which would send it through the host controller (which would do byte swapping as necessary).

So a qtest test case would have to do little endian MMIO to interact with the PCI bus.

Maybe ppc is a bad example, but are there other targets where in/out is used?

Stefan

#23 lore raw
Quoted 52 lines · Stefan Hajnoczi
Quoted 51 lines · Anthony Liguori
Quoted 48 lines · Stefan Hajnoczi
Quoted 28 lines · Anthony Liguori

+    if (strcmp(words[0], "outb") == 0 ||
+        strcmp(words[0], "outw") == 0 ||
+        strcmp(words[0], "outl") == 0) {
+        uint16_t addr;
+        uint32_t value;

qtest.c new file +22 -0
+
+        g_assert(words[1]&&  words[2]);
+        addr = strtol(words[1], NULL, 0);
+        value = strtol(words[2], NULL, 0);
+
+        if (words[0][3] == 'b') {
+            cpu_outb(addr, value);
+        } else if (words[0][3] == 'w') {
+            cpu_outw(addr, value);
+        } else if (words[0][3] == 'l') {
+            cpu_outl(addr, value);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK\n");
+    } else if (strcmp(words[0], "inb") == 0 ||
+        strcmp(words[0], "inw") == 0 ||
+        strcmp(words[0], "inl") == 0) {
+        uint16_t addr;
+        uint32_t value = -1U;
+
+        g_assert(words[1]);
+        addr = strtol(words[1], NULL, 0);

qtest.c line 194

Quoted 10 lines
qtest.c new file +10 -0
+
+        if (words[0][2] == 'b') {
+            value = cpu_inb(addr);
+        } else if (words[0][2] == 'w') {
+            value = cpu_inw(addr);
+        } else if (words[0][2] == 'l') {
+            value = cpu_inl(addr);
+        }
+        qtest_send_prefix(chr);
+        qtest_send(chr, "OK 0x%04x\n", value);

Endianness is a little weird here.  memory.c will byteswap if target and device endianness differ.

Imagine the case where we're on an x86 host, running a ppc guest, reading from PCI configuration space (little-endian).

Quoted 6 lines
Quoted 2 lines

These functions expect to get host native endian.  The qtest wire protocol is a string (which has no endianness) and converts it to host native endian.

The cpu_inl() return value is not host native endian.  We perform a byteswap if the memory region endianness is different from the target endianness.

After our chat yesterday I inspected cpu_inl() under gdb. You are right that cpu_inl() returns a value in host endian. The memory region endianness is ignored and no byteswapping is performed.

This means qtests do not need to byteswap - it's already in the correct endianness, no matter which device, target, or host.

Stefan