Skip to contentSkip to conversation

roadtest: a driver testing framework

RFC In review Vincent Whitchurch 6 participants 30 messages Mar 11, 2022 – Apr 18, 2022

Subsystems (6)
lore
Share & tools
lore
#0 lore raw

cover roadtest: a driver testing framework

This patchset proposes roadtest, a device-driver testing framework. Drivers are tested under User Mode Linux (UML) and interact with mocked/modelled hardware. The tests and hardware models are written in Python, the former using Python's built-in unittest framework.

Drivers are tested via their userspace interfaces. The hardware models allow tests to inject values into registers and assert that drivers control the hardware in the right way and react as expected to stimuli.

Roadtest is meant to be used for relatively simple drivers, such as the ones part of the IIO, regulator and RTC subsystems.

Questions and answers:

= Why do we need this?

There are a large amount of these kind of drivers in the kernel. Most of the hardware is not available in current CI systems so most drivers can only, at best, be build-tested there. Even basic soundness such as a driver successfully probing and binding to the devices it tries to be support cannot be tested. Drivers cannot be easily regression-tested to ensure that bugs fixed once do not get reintroduced.

Many drivers support multiple related hardware variants, and far from all patch submitters have access to all the variants which the driver that they are patching supports, so there is no way for them to easily verify that they haven't broken something basic on a variant which they do not own.

Furthermore, hardware can be used in many different configurations with drivers supporting many different devicetree properties, so even just having access to all the variants would be insufficient.

On top of that, some of the chips measure environmental conditions such as temperature, so testing extreme cases may not be simple even if one has access to the hardware.

All this makes development, modification, maintenance, and reviewing of these drivers harder than it necessarily needs to be. Roadtest hopes to make some of these things slightly easier by providing a framework to create hardware models/mocks and to write testcases which exercise drivers using these models.

= Do you have some specific examples of the kind of code this could be used to
test?

Here is an example of a patch which can easily be regression-tested using roadtest (in fact, this series includes such a regression test) but is much harder to do so automatically with real hardware since it requires specific environmental conditions:

iio: light: opt3001: Fixed timeout error when 0 lux
https://lore.kernel.org/lkml/[email protected]/

Here is another example. This driver has code which correctly parses a documented devicetree property (amstaos,proximity-diodes) but which then fails to actually communicate this setting to the hardware in any way. Such code can be easily tested with roadtest since the framework integrates devicetree support and provides functions to assert that drivers writes expected registers with expected values:

drivers/iio/light/tsl2772.c tsl2772_read_prox_diodes()

(Both the above examples happen to be from the same subsystem but that should in no way be taken to imply that such issues are unique to that subsystem or that that subsystem has more of them.)

= How does this relate to kselftests?

Tests in kselftests also test kernel code using the userspace interfaces, but that's about what's common between the frameworks. kselftests has other goals and does not provide any kind of mechanism for hardware mocking.

= How does this relate to kunit?

Kunit is for unit testing of functions in kernel code, and is not meant for testing kernel code via userspace interfaces. It could in theory be used to test some of the simple drivers too, but that would require (1) a large amount of mocking code in various kernel frameworks, and, more importantly, (2) refactoring of the drivers to be tested.

This can be contrasted with roadtest which works with mostly unmodified drivers and which mocks the hardware at the lowest level without having to change kernel frameworks.

= How do I use it?

See Documentation/dev-tools/roadtest.rst added by the documentation patch for more information about running and writing tests using this framework.

= What's included in the patchset?

The current framework allows developing tests for hardware which uses the I2C bus. Hardware models can also control GPIOs and use them to trigger interrupts.

This series includes tests for some IIO, regulator and RTC drivers. The regulator and RTC tests depend on a few driver patches which are either in review or in linux-next. These are noted in the commit messages.

The entire patch set, including the required dependencies, is also available in a git tree:

https://github.com/vwax/linux/commits/roadtest/rfc-v1

Vincent Whitchurch (10):
roadtest: import libvhost-user from QEMU
roadtest: add C backend
roadtest: add framework
roadtest: add base config
roadtest: add build files
roadtest: add documentation
iio: light: opt3001: add roadtest
iio: light: vcnl4000: add roadtest
regulator: tps62864: add roadtest
rtc: pcf8563: add roadtest

 Documentation/dev-tools/index.rst             |    1 +
 Documentation/dev-tools/roadtest.rst          |  669 ++++
 tools/testing/roadtest/.gitignore             |    2 +
 tools/testing/roadtest/Dockerfile             |   25 +
 tools/testing/roadtest/Makefile               |   84 +
 tools/testing/roadtest/init.sh                |   19 +
 tools/testing/roadtest/pyproject.toml         |   10 +
 tools/testing/roadtest/requirements.txt       |    4 +
 tools/testing/roadtest/roadtest/__init__.py   |    2 +
 .../roadtest/roadtest/backend/__init__.py     |    0
 .../roadtest/roadtest/backend/backend.py      |   32 +
 .../testing/roadtest/roadtest/backend/gpio.py |  111 +
 .../testing/roadtest/roadtest/backend/i2c.py  |  123 +
 .../testing/roadtest/roadtest/backend/main.py |   13 +
 .../testing/roadtest/roadtest/backend/mock.py |   20 +
 .../roadtest/roadtest/backend/test_gpio.py    |   98 +
 .../roadtest/roadtest/backend/test_i2c.py     |   84 +
 .../testing/roadtest/roadtest/cmd/__init__.py |    0
 tools/testing/roadtest/roadtest/cmd/main.py   |  146 +
 tools/testing/roadtest/roadtest/cmd/remote.py |   48 +
 .../roadtest/roadtest/core/__init__.py        |    0
 .../testing/roadtest/roadtest/core/control.py |   52 +
 .../roadtest/roadtest/core/devicetree.py      |  155 +
 .../roadtest/roadtest/core/hardware.py        |   94 +
 tools/testing/roadtest/roadtest/core/log.py   |   42 +
 .../testing/roadtest/roadtest/core/modules.py |   38 +
 .../testing/roadtest/roadtest/core/opslog.py  |   35 +
 tools/testing/roadtest/roadtest/core/proxy.py |   48 +
 tools/testing/roadtest/roadtest/core/suite.py |  286 ++
 tools/testing/roadtest/roadtest/core/sysfs.py |   77 +
 .../roadtest/roadtest/core/test_control.py    |   35 +
 .../roadtest/roadtest/core/test_devicetree.py |   31 +
 .../roadtest/roadtest/core/test_hardware.py   |   41 +
 .../roadtest/roadtest/core/test_log.py        |   54 +
 .../roadtest/roadtest/core/test_opslog.py     |   27 +
 .../roadtest/roadtest/tests/__init__.py       |    0
 .../roadtest/roadtest/tests/base/config       |   84 +
 .../roadtest/roadtest/tests/iio/__init__.py   |    0
 .../roadtest/roadtest/tests/iio/config        |    1 +
 .../roadtest/roadtest/tests/iio/iio.py        |  112 +
 .../roadtest/tests/iio/light/__init__.py      |    0
 .../roadtest/roadtest/tests/iio/light/config  |    2 +
 .../roadtest/tests/iio/light/test_opt3001.py  |   95 +
 .../roadtest/tests/iio/light/test_vcnl4000.py |  132 +
 .../roadtest/tests/iio/light/test_vcnl4010.py |  282 ++
 .../roadtest/tests/iio/light/test_vcnl4040.py |  104 +
 .../roadtest/tests/iio/light/test_vcnl4200.py |   96 +
 .../roadtest/tests/regulator/__init__.py      |    0
 .../roadtest/roadtest/tests/regulator/config  |    4 +
 .../roadtest/tests/regulator/test_tps62864.py |  187 ++
 .../roadtest/roadtest/tests/rtc/__init__.py   |    0
 .../roadtest/roadtest/tests/rtc/config        |    1 +
 .../roadtest/roadtest/tests/rtc/rtc.py        |   73 +
 .../roadtest/tests/rtc/test_pcf8563.py        |  348 ++
 tools/testing/roadtest/src/.gitignore         |    1 +
 tools/testing/roadtest/src/backend.c          |  884 +++++
 .../src/libvhost-user/include/atomic.h        |  310 ++
 .../src/libvhost-user/libvhost-user.c         | 2885 +++++++++++++++++
 .../src/libvhost-user/libvhost-user.h         |  691 ++++
 59 files changed, 8798 insertions(+)
 create mode 100644 Documentation/dev-tools/roadtest.rst
 create mode 100644 tools/testing/roadtest/.gitignore
 create mode 100644 tools/testing/roadtest/Dockerfile
 create mode 100644 tools/testing/roadtest/Makefile
 create mode 100755 tools/testing/roadtest/init.sh
 create mode 100644 tools/testing/roadtest/pyproject.toml
 create mode 100644 tools/testing/roadtest/requirements.txt
 create mode 100644 tools/testing/roadtest/roadtest/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/backend.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/main.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/mock.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/main.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/remote.py
 create mode 100644 tools/testing/roadtest/roadtest/core/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/core/control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/modules.py
 create mode 100644 tools/testing/roadtest/roadtest/core/opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/core/proxy.py
 create mode 100644 tools/testing/roadtest/roadtest/core/suite.py
 create mode 100644 tools/testing/roadtest/roadtest/core/sysfs.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/base/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/iio.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/rtc.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/test_pcf8563.py
 create mode 100644 tools/testing/roadtest/src/.gitignore
 create mode 100644 tools/testing/roadtest/src/backend.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/include/atomic.h
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.h
Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#1 lore raw

RFC 1/10 roadtest: import libvhost-user from QEMU

Import the libvhost-user from QEMU for use in the implementation of the virtio devices in the roadtest backend.

The files are from the following paths in v6.2.0 of QEMU:

include/qemu/atomic.h
subprojects/libvhost-user/libvhost-user.c
subprojects/libvhost-user/libvhost-user.h

In order to keep further imports strightforward, the files have been copied as-is with only the following essential modifications:

- Addition of SPDX lines (GPL-2.0-or-later, in conformance with the existing copyright messages in the files)

- Change of "standard-headers/linux/virtio_ring.h" to <linux/virtio_ring.h> in libvhost-user.h. It will be built with the headers from the current kernel.

---
 .../src/libvhost-user/include/atomic.h        |  310 ++
 .../src/libvhost-user/libvhost-user.c         | 2885 +++++++++++++++++
 .../src/libvhost-user/libvhost-user.h         |  691 ++++
 3 files changed, 3886 insertions(+)
 create mode 100644 tools/testing/roadtest/src/libvhost-user/include/atomic.h
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.h
tools/testing/roadtest/src/libvhost-user/include/atomic.h new file +310 -0
new file mode 100644
index 000000000000..65026bf54406
@@ -0,0 +1,310 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Simple interface for atomic operations.
+ *
+ * Copyright (C) 2013 Red Hat, Inc.
+ *
+ * Author: Paolo Bonzini <[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.
+ *
+ * See docs/devel/atomics.rst for discussion about the guarantees each
+ * atomic primitive is meant to provide.
+ */
+
+#ifndef QEMU_ATOMIC_H
+#define QEMU_ATOMIC_H
+
+/* Compiler barrier */
+#define barrier()   ({ asm volatile("" ::: "memory"); (void)0; })
+
+/* The variable that receives the old value of an atomically-accessed
+ * variable must be non-qualified, because atomic builtins return values
+ * through a pointer-type argument as in __atomic_load(&var, &old, MODEL).
+ *
+ * This macro has to handle types smaller than int manually, because of
+ * implicit promotion.  int and larger types, as well as pointers, can be
+ * converted to a non-qualified type just by applying a binary operator.
+ */
+#define typeof_strip_qual(expr)                                                    \
+  typeof(                                                                          \
+    __builtin_choose_expr(                                                         \
+      __builtin_types_compatible_p(typeof(expr), bool) ||                          \
+        __builtin_types_compatible_p(typeof(expr), const bool) ||                  \
+        __builtin_types_compatible_p(typeof(expr), volatile bool) ||               \
+        __builtin_types_compatible_p(typeof(expr), const volatile bool),           \
+        (bool)1,                                                                   \
+    __builtin_choose_expr(                                                         \
+      __builtin_types_compatible_p(typeof(expr), signed char) ||                   \
+        __builtin_types_compatible_p(typeof(expr), const signed char) ||           \
+        __builtin_types_compatible_p(typeof(expr), volatile signed char) ||        \
+        __builtin_types_compatible_p(typeof(expr), const volatile signed char),    \
+        (signed char)1,                                                            \
+    __builtin_choose_expr(                                                         \
+      __builtin_types_compatible_p(typeof(expr), unsigned char) ||                 \
+        __builtin_types_compatible_p(typeof(expr), const unsigned char) ||         \
+        __builtin_types_compatible_p(typeof(expr), volatile unsigned char) ||      \
+        __builtin_types_compatible_p(typeof(expr), const volatile unsigned char),  \
+        (unsigned char)1,                                                          \
+    __builtin_choose_expr(                                                         \
+      __builtin_types_compatible_p(typeof(expr), signed short) ||                  \
+        __builtin_types_compatible_p(typeof(expr), const signed short) ||          \
+        __builtin_types_compatible_p(typeof(expr), volatile signed short) ||       \
+        __builtin_types_compatible_p(typeof(expr), const volatile signed short),   \
+        (signed short)1,                                                           \
+    __builtin_choose_expr(                                                         \
+      __builtin_types_compatible_p(typeof(expr), unsigned short) ||                \
+        __builtin_types_compatible_p(typeof(expr), const unsigned short) ||        \
+        __builtin_types_compatible_p(typeof(expr), volatile unsigned short) ||     \
+        __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \
+        (unsigned short)1,                                                         \
+      (expr)+0))))))
+
+#ifndef __ATOMIC_RELAXED
+#error "Expecting C11 atomic ops"
+#endif
+
+/* Manual memory barriers
+ *
+ *__atomic_thread_fence does not include a compiler barrier; instead,
+ * the barrier is part of __atomic_load/__atomic_store's "volatile-like"
+ * semantics. If smp_wmb() is a no-op, absence of the barrier means that
+ * the compiler is free to reorder stores on each side of the barrier.
+ * Add one here, and similarly in smp_rmb() and smp_read_barrier_depends().
+ */
+
+#define smp_mb()                     ({ barrier(); __atomic_thread_fence(__ATOMIC_SEQ_CST); })
+#define smp_mb_release()             ({ barrier(); __atomic_thread_fence(__ATOMIC_RELEASE); })
+#define smp_mb_acquire()             ({ barrier(); __atomic_thread_fence(__ATOMIC_ACQUIRE); })
+
+/* Most compilers currently treat consume and acquire the same, but really
+ * no processors except Alpha need a barrier here.  Leave it in if
+ * using Thread Sanitizer to avoid warnings, otherwise optimize it away.
+ */
+#if defined(__SANITIZE_THREAD__)
+#define smp_read_barrier_depends()   ({ barrier(); __atomic_thread_fence(__ATOMIC_CONSUME); })
+#elif defined(__alpha__)
+#define smp_read_barrier_depends()   asm volatile("mb":::"memory")
+#else
+#define smp_read_barrier_depends()   barrier()
+#endif
+
+/*
+ * A signal barrier forces all pending local memory ops to be observed before
+ * a SIGSEGV is delivered to the *same* thread.  In practice this is exactly
+ * the same as barrier(), but since we have the correct builtin, use it.
+ */
+#define signal_barrier()    __atomic_signal_fence(__ATOMIC_SEQ_CST)
+
+/* Sanity check that the size of an atomic operation isn't "overly large".
+ * Despite the fact that e.g. i686 has 64-bit atomic operations, we do not
+ * want to use them because we ought not need them, and this lets us do a
+ * bit of sanity checking that other 32-bit hosts might build.
+ *
+ * That said, we have a problem on 64-bit ILP32 hosts in that in order to
+ * sync with TCG_OVERSIZED_GUEST, this must match TCG_TARGET_REG_BITS.
+ * We'd prefer not want to pull in everything else TCG related, so handle
+ * those few cases by hand.
+ *
+ * Note that x32 is fully detected with __x86_64__ + _ILP32, and that for
+ * Sparc we always force the use of sparcv9 in configure. MIPS n32 (ILP32) &
+ * n64 (LP64) ABIs are both detected using __mips64.
+ */
+#if defined(__x86_64__) || defined(__sparc__) || defined(__mips64)
+# define ATOMIC_REG_SIZE  8
+#else
+# define ATOMIC_REG_SIZE  sizeof(void *)
+#endif
+
+/* Weak atomic operations prevent the compiler moving other
+ * loads/stores past the atomic operation load/store. However there is
+ * no explicit memory barrier for the processor.
+ *
+ * The C11 memory model says that variables that are accessed from
+ * different threads should at least be done with __ATOMIC_RELAXED
+ * primitives or the result is undefined. Generally this has little to
+ * no effect on the generated code but not using the atomic primitives
+ * will get flagged by sanitizers as a violation.
+ */
+#define qatomic_read__nocheck(ptr) \
+    __atomic_load_n(ptr, __ATOMIC_RELAXED)
+
+#define qatomic_read(ptr)                              \
+    ({                                                 \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE); \
+    qatomic_read__nocheck(ptr);                        \
+    })
+
+#define qatomic_set__nocheck(ptr, i) \
+    __atomic_store_n(ptr, i, __ATOMIC_RELAXED)
+
+#define qatomic_set(ptr, i)  do {                      \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE); \
+    qatomic_set__nocheck(ptr, i);                      \
+} while(0)
+
+/* See above: most compilers currently treat consume and acquire the
+ * same, but this slows down qatomic_rcu_read unnecessarily.
+ */
+#ifdef __SANITIZE_THREAD__
+#define qatomic_rcu_read__nocheck(ptr, valptr)           \
+    __atomic_load(ptr, valptr, __ATOMIC_CONSUME);
+#else
+#define qatomic_rcu_read__nocheck(ptr, valptr)           \
+    __atomic_load(ptr, valptr, __ATOMIC_RELAXED);        \
+    smp_read_barrier_depends();
+#endif
+
+#define qatomic_rcu_read(ptr)                          \
+    ({                                                 \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE); \
+    typeof_strip_qual(*ptr) _val;                      \
+    qatomic_rcu_read__nocheck(ptr, &_val);             \
+    _val;                                              \
+    })
+
+#define qatomic_rcu_set(ptr, i) do {                   \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE); \
+    __atomic_store_n(ptr, i, __ATOMIC_RELEASE);        \
+} while(0)
+
+#define qatomic_load_acquire(ptr)                       \
+    ({                                                  \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE);  \
+    typeof_strip_qual(*ptr) _val;                       \
+    __atomic_load(ptr, &_val, __ATOMIC_ACQUIRE);        \
+    _val;                                               \
+    })
+
+#define qatomic_store_release(ptr, i)  do {             \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE);  \
+    __atomic_store_n(ptr, i, __ATOMIC_RELEASE);         \
+} while(0)
+
+
+/* All the remaining operations are fully sequentially consistent */
+
+#define qatomic_xchg__nocheck(ptr, i)    ({                 \
+    __atomic_exchange_n(ptr, (i), __ATOMIC_SEQ_CST);        \
+})
+
+#define qatomic_xchg(ptr, i)    ({                          \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE);      \
+    qatomic_xchg__nocheck(ptr, i);                          \
+})
+
+/* Returns the eventual value, failed or not */
+#define qatomic_cmpxchg__nocheck(ptr, old, new)    ({                   \
+    typeof_strip_qual(*ptr) _old = (old);                               \
+    (void)__atomic_compare_exchange_n(ptr, &_old, new, false,           \
+                              __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);      \
+    _old;                                                               \
+})
+
+#define qatomic_cmpxchg(ptr, old, new)    ({                            \
+    QEMU_BUILD_BUG_ON(sizeof(*ptr) > ATOMIC_REG_SIZE);                  \
+    qatomic_cmpxchg__nocheck(ptr, old, new);                            \
+})
+
+/* Provide shorter names for GCC atomic builtins, return old value */
+#define qatomic_fetch_inc(ptr)  __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST)
+#define qatomic_fetch_dec(ptr)  __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST)
+
+#define qatomic_fetch_add(ptr, n) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_fetch_sub(ptr, n) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_fetch_and(ptr, n) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_fetch_or(ptr, n)  __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_fetch_xor(ptr, n) __atomic_fetch_xor(ptr, n, __ATOMIC_SEQ_CST)
+
+#define qatomic_inc_fetch(ptr)    __atomic_add_fetch(ptr, 1, __ATOMIC_SEQ_CST)
+#define qatomic_dec_fetch(ptr)    __atomic_sub_fetch(ptr, 1, __ATOMIC_SEQ_CST)
+#define qatomic_add_fetch(ptr, n) __atomic_add_fetch(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_sub_fetch(ptr, n) __atomic_sub_fetch(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_and_fetch(ptr, n) __atomic_and_fetch(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_or_fetch(ptr, n)  __atomic_or_fetch(ptr, n, __ATOMIC_SEQ_CST)
+#define qatomic_xor_fetch(ptr, n) __atomic_xor_fetch(ptr, n, __ATOMIC_SEQ_CST)
+
+/* And even shorter names that return void.  */
+#define qatomic_inc(ptr) \
+    ((void) __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST))
+#define qatomic_dec(ptr) \
+    ((void) __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST))
+#define qatomic_add(ptr, n) \
+    ((void) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST))
+#define qatomic_sub(ptr, n) \
+    ((void) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST))
+#define qatomic_and(ptr, n) \
+    ((void) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST))
+#define qatomic_or(ptr, n) \
+    ((void) __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST))
+#define qatomic_xor(ptr, n) \
+    ((void) __atomic_fetch_xor(ptr, n, __ATOMIC_SEQ_CST))
+
+#define smp_wmb()   smp_mb_release()
+#define smp_rmb()   smp_mb_acquire()
+
+/* qatomic_mb_read/set semantics map Java volatile variables. They are
+ * less expensive on some platforms (notably POWER) than fully
+ * sequentially consistent operations.
+ *
+ * As long as they are used as paired operations they are safe to
+ * use. See docs/devel/atomics.rst for more discussion.
+ */
+
+#define qatomic_mb_read(ptr)                             \
+    qatomic_load_acquire(ptr)
+
+#if !defined(__SANITIZE_THREAD__) && \
+    (defined(__i386__) || defined(__x86_64__) || defined(__s390x__))
+/* This is more efficient than a store plus a fence.  */
+# define qatomic_mb_set(ptr, i)  ((void)qatomic_xchg(ptr, i))
+#else
+# define qatomic_mb_set(ptr, i) \
+   ({ qatomic_store_release(ptr, i); smp_mb(); })
+#endif
+
+#define qatomic_fetch_inc_nonzero(ptr) ({                               \
+    typeof_strip_qual(*ptr) _oldn = qatomic_read(ptr);                  \
+    while (_oldn && qatomic_cmpxchg(ptr, _oldn, _oldn + 1) != _oldn) {  \
+        _oldn = qatomic_read(ptr);                                      \
+    }                                                                   \
+    _oldn;                                                              \
+})
+
+/*
+ * Abstractions to access atomically (i.e. "once") i64/u64 variables.
+ *
+ * The i386 abi is odd in that by default members are only aligned to
+ * 4 bytes, which means that 8-byte types can wind up mis-aligned.
+ * Clang will then warn about this, and emit a call into libatomic.
+ *
+ * Use of these types in structures when they will be used with atomic
+ * operations can avoid this.
+ */
+typedef int64_t aligned_int64_t __attribute__((aligned(8)));
+typedef uint64_t aligned_uint64_t __attribute__((aligned(8)));
+
+#ifdef CONFIG_ATOMIC64
+/* Use __nocheck because sizeof(void *) might be < sizeof(u64) */
+#define qatomic_read_i64(P) \
+    _Generic(*(P), int64_t: qatomic_read__nocheck(P))
+#define qatomic_read_u64(P) \
+    _Generic(*(P), uint64_t: qatomic_read__nocheck(P))
+#define qatomic_set_i64(P, V) \
+    _Generic(*(P), int64_t: qatomic_set__nocheck(P, V))
+#define qatomic_set_u64(P, V) \
+    _Generic(*(P), uint64_t: qatomic_set__nocheck(P, V))
+
+static inline void qatomic64_init(void)
+{
+}
+#else /* !CONFIG_ATOMIC64 */
+int64_t  qatomic_read_i64(const int64_t *ptr);
+uint64_t qatomic_read_u64(const uint64_t *ptr);
+void qatomic_set_i64(int64_t *ptr, int64_t val);
+void qatomic_set_u64(uint64_t *ptr, uint64_t val);
+void qatomic64_init(void);
+#endif /* !CONFIG_ATOMIC64 */
+
+#endif /* QEMU_ATOMIC_H */
tools/testing/roadtest/src/libvhost-user/libvhost-user.c new file +2885 -0

2,690 lines not on this page · raw message

tools/testing/roadtest/src/libvhost-user/libvhost-user.h new file +691 -0

691 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

Part of the diff is not shown here. View the raw message.

maintainer
#2 lore raw

Re: [RFC v1 01/10] roadtest: import libvhost-user from QEMU

Quoted 3 lines · Vincent Whitchurch

Import the libvhost-user from QEMU for use in the implementation of the virtio devices in the roadtest backend.

So hm, I wonder if this is the sensible thing to do?

Not that I mind importing qemu code, but:

1) the implementation is rather complex in some places, and has support for a LOT of virtio/vhost-user features that are really not needed in these cases, for performance etc. It's also close to 4k LOC.

2) the implementation doesn't support time-travel mode which might come in handy

We have another implementation that might be simpler:
https://github.com/linux-test-project/usfstl/blob/main/src/vhost.c

but it probably has dependencies on other things in this library, but vhost.c itself is only ~1k LOC. (But I need to update it, I'm sure we have some unpublished bugfixes etc. in this code)

johannes

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#3 lore raw

Re: [RFC v1 01/10] roadtest: import libvhost-user from QEMU

Quoted 11 lines · Johannes Berg
Quoted 2 lines · Vincent Whitchurch

Import the libvhost-user from QEMU for use in the implementation of the virtio devices in the roadtest backend.

So hm, I wonder if this is the sensible thing to do?

Not that I mind importing qemu code, but:

1) the implementation is rather complex in some places, and has support for a LOT of virtio/vhost-user features that are really not needed in these cases, for performance etc. It's also close to 4k LOC.

Is this really a problem given that the code is imported as-is? The intention is not to have to make a lot of local modifications to it in the kernel tree. The code is stable and presumably well-tested upstream, and upstream maintains it as a separate library (in the QEMU source tree though) to encourage reuse.

Quoted 2 lines

2) the implementation doesn't support time-travel mode which might come in handy

True, but I don't see the external time-travel controller stuff being too useful for the kinds of tests this framework is targeting.

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#4 lore raw

RFC 2/10 roadtest: add C backend

In reply to Vincent Whitchurch

Add the C parts of the roadtest framework. This uses QEMU's libvhost-user to implement the device side of virtio-user and virtio-gpio and bridge them to the Python portions of the backend.

The C backend is also responsible for starting UML after the virtio device implementations are initialized.

---
 tools/testing/roadtest/src/backend.c | 884 +++++++++++++++++++++++++++
 1 file changed, 884 insertions(+)
 create mode 100644 tools/testing/roadtest/src/backend.c
tools/testing/roadtest/src/backend.c new file +884 -0
new file mode 100644
index 000000000000..d5ac08b20fd9
@@ -0,0 +1,884 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// Copyright Axis Communications AB
+
+#define PY_SSIZE_T_CLEAN
+#include <Python.h>
+
+#include <err.h>
+#include <getopt.h>
+#include <stdlib.h>
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <linux/virtio_gpio.h>
+#include <linux/virtio_i2c.h>
+#include <linux/kernel.h>
+#include <linux/list.h>
+
+#include "libvhost-user.h"
+
+enum watch_type {
+	LISTEN,
+	SOCKET_WATCH,
+	VU_WATCH,
+};
+
+struct watch {
+	VuDev *dev;
+	enum watch_type type;
+	int fd;
+	void *func;
+	void *data;
+	struct list_head list;
+};
+
+struct vhost_user_i2c {
+	VuDev dev;
+	FILE *control;
+};
+
+struct vhost_user_gpio {
+	VuDev dev;
+	FILE *control;
+	VuVirtqElement *irq_elements[64];
+};
+
+#define dbg(...)                                                               \
+	do {                                                                   \
+		if (0) {                                                       \
+			fprintf(stderr, __VA_ARGS__);                          \
+		}                                                              \
+	} while (0)
+
+static LIST_HEAD(watches);
+
+static int epfd;
+
+static PyObject *py_i2c_read, *py_i2c_write, *py_process_control;
+static PyObject *py_gpio_set_irq_type, *py_gpio_unmask;
+
+static const char *opt_main_script;
+static char *opt_gpio_socket;
+static char *opt_i2c_socket;
+
+static struct vhost_user_gpio gpio;
+static struct vhost_user_i2c i2c;
+
+static void dump_iov(const char *what, struct iovec *iovec, unsigned int count)
+{
+	int i;
+
+	dbg("dumping %s with count %u\n", what, count);
+
+	for (i = 0; i < count; i++) {
+		struct iovec *iov = &iovec[0];
+
+		dbg("i %d base %p len %zu\n", i, iov->iov_base, iov->iov_len);
+	}
+}
+
+static bool i2c_read(struct vhost_user_i2c *vi, uint16_t addr, void *data,
+		     size_t len)
+{
+	PyObject *pArgs, *pValue;
+
+	dbg("i2c read addr %#x len %zu\n", addr, len);
+
+	pArgs = PyTuple_New(1);
+	pValue = PyLong_FromLong(len);
+	PyTuple_SetItem(pArgs, 0, pValue);
+
+	pValue = PyObject_CallObject(py_i2c_read, pArgs);
+	Py_DECREF(pArgs);
+	if (!pValue) {
+		PyErr_Print();
+		return false;
+	}
+
+	unsigned char *buffer;
+	Py_ssize_t length;
+
+	if (PyBytes_AsStringAndSize(pValue, (char **)&buffer, &length) < 0) {
+		PyErr_Print();
+		errx(1, "invalid result from i2c.read()");
+	}
+	if (length != len) {
+		errx(1,
+		     "unexpected length from i2c.read(), expected %zu, got %zu",
+		     len, length);
+	}
+
+	memcpy(data, buffer, len);
+
+	return true;
+}
+
+static bool i2c_write(struct vhost_user_i2c *vi, uint16_t addr,
+		      const void *data, size_t len)
+{
+	PyObject *pArgs, *pValue;
+
+	dbg("i2c write addr %#x len %zu\n", addr, len);
+
+	pArgs = PyTuple_New(1);
+	pValue = PyBytes_FromStringAndSize(data, len);
+	PyTuple_SetItem(pArgs, 0, pValue);
+
+	pValue = PyObject_CallObject(py_i2c_write, pArgs);
+	Py_DECREF(pArgs);
+	if (!pValue) {
+		PyErr_Print();
+		return false;
+	}
+
+	return true;
+}
+
+static void gpio_send_irq_response(struct vhost_user_gpio *gpio,
+				   unsigned int pin, unsigned int status);
+
+static PyObject *cbackend_trigger_gpio_irq(PyObject *self, PyObject *args)
+{
+	unsigned int pin;
+
+	if (!PyArg_ParseTuple(args, "I", &pin))
+		return NULL;
+
+	dbg("trigger gpio %u irq\n", pin);
+
+	gpio_send_irq_response(&gpio, pin, VIRTIO_GPIO_IRQ_STATUS_VALID);
+
+	Py_RETURN_NONE;
+}
+
+static PyMethodDef EmbMethods[] = {
+	{ "trigger_gpio_irq", cbackend_trigger_gpio_irq, METH_VARARGS,
+	  "Return the number of arguments received by the process." },
+	{ NULL, NULL, 0, NULL }
+};
+
+static PyModuleDef EmbModule = { PyModuleDef_HEAD_INIT,
+				 "cbackend",
+				 NULL,
+				 -1,
+				 EmbMethods,
+				 NULL,
+				 NULL,
+				 NULL,
+				 NULL };
+
+static PyObject *PyInit_cbackend(void)
+{
+	return PyModule_Create(&EmbModule);
+}
+
+static void init_python_i2c(PyObject *backend)
+{
+	PyObject *i2c = PyObject_GetAttrString(backend, "i2c");
+
+	if (!i2c) {
+		PyErr_Print();
+		errx(1, "Error getting backend.i2c");
+	}
+
+	py_i2c_read = PyObject_GetAttrString(i2c, "read");
+	if (!py_i2c_read) {
+		PyErr_Print();
+		errx(1, "Error getting i2c.read");
+	}
+
+	py_i2c_write = PyObject_GetAttrString(i2c, "write");
+	if (!py_i2c_write) {
+		PyErr_Print();
+		errx(1, "Error getting i2c.write");
+	}
+}
+
+static void init_python_gpio(PyObject *backend)
+{
+	PyObject *gpio = PyObject_GetAttrString(backend, "gpio");
+
+	if (!gpio) {
+		PyErr_Print();
+		errx(1, "error getting backend.gpio");
+	}
+
+	py_gpio_set_irq_type = PyObject_GetAttrString(gpio, "set_irq_type");
+	if (!py_gpio_set_irq_type) {
+		PyErr_Print();
+		errx(1, "error getting gpio.set_irq_type");
+	}
+
+	py_gpio_unmask = PyObject_GetAttrString(gpio, "unmask");
+	if (!py_gpio_unmask) {
+		PyErr_Print();
+		errx(1, "error getting gpio.unmask");
+	}
+}
+
+static void init_python(void)
+{
+	PyObject *mainmod, *backend;
+	FILE *file;
+
+	PyImport_AppendInittab("cbackend", &PyInit_cbackend);
+
+	Py_Initialize();
+
+	file = fopen(opt_main_script, "r");
+	if (!file)
+		err(1, "open %s", opt_main_script);
+
+	if (PyRun_SimpleFile(file, "main.py") < 0) {
+		PyErr_Print();
+		errx(1, "error running %s", opt_main_script);
+	}
+	fclose(file);
+
+	mainmod = PyImport_AddModule("__main__");
+	if (!mainmod) {
+		PyErr_Print();
+		errx(1, "error getting __main__");
+	}
+
+	backend = PyObject_GetAttrString(mainmod, "backend");
+	if (!backend) {
+		PyErr_Print();
+		errx(1, "error getting backend");
+	}
+
+	py_process_control = PyObject_GetAttrString(backend, "process_control");
+	if (!py_process_control) {
+		PyErr_Print();
+		errx(1, "error getting backend.process_control");
+	}
+
+	init_python_i2c(backend);
+	init_python_gpio(backend);
+}
+
+static void i2c_handle_cmdq(VuDev *dev, int qidx)
+{
+	struct vhost_user_i2c *vi =
+		container_of(dev, struct vhost_user_i2c, dev);
+	VuVirtq *vq = vu_get_queue(dev, qidx);
+	VuVirtqElement *elem;
+
+	for (;;) {
+		struct virtio_i2c_out_hdr *hdr;
+		struct iovec *resultv;
+		size_t used = 0;
+		bool ok = true;
+
+		elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
+		if (!elem)
+			break;
+
+		dbg("elem %p index %u out_num %u in_num %u\n", elem,
+		    elem->index, elem->out_num, elem->in_num);
+		dump_iov("out", elem->out_sg, elem->out_num);
+		dump_iov("in", elem->in_sg, elem->in_num);
+
+		assert(elem->out_sg[0].iov_len == sizeof(*hdr));
+		hdr = elem->out_sg[0].iov_base;
+
+		if (elem->out_num == 2 && elem->in_num == 1) {
+			struct iovec *data = &elem->out_sg[1];
+
+			ok = i2c_write(vi, hdr->addr, data->iov_base,
+				       data->iov_len);
+			resultv = &elem->in_sg[0];
+		} else if (elem->out_num == 1 && elem->in_num == 2) {
+			struct iovec *data = &elem->in_sg[0];
+
+			ok = i2c_read(vi, hdr->addr, data->iov_base,
+				      data->iov_len);
+			resultv = &elem->in_sg[1];
+			used += data->iov_len;
+		} else {
+			assert(false);
+		}
+
+		struct virtio_i2c_in_hdr *inhdr = resultv->iov_base;
+
+		inhdr->status = ok ? VIRTIO_I2C_MSG_OK : VIRTIO_I2C_MSG_ERR;
+
+		used += sizeof(*inhdr);
+		vu_queue_push(dev, vq, elem, used);
+		free(elem);
+	}
+
+	vu_queue_notify(&vi->dev, vq);
+}
+
+static void i2c_queue_set_started(VuDev *dev, int qidx, bool started)
+{
+	VuVirtq *vq = vu_get_queue(dev, qidx);
+
+	dbg("queue started %d:%d\n", qidx, started);
+
+	vu_set_queue_handler(dev, vq, started ? i2c_handle_cmdq : NULL);
+}
+
+static bool i2cquit;
+static bool gpioquit;
+
+static void remove_watch(VuDev *dev, int fd);
+
+static int i2c_process_msg(VuDev *dev, VhostUserMsg *vmsg, int *do_reply)
+{
+	if (vmsg->request == VHOST_USER_NONE) {
+		dbg("i2c disconnect");
+		remove_watch(dev, -1);
+		i2cquit = true;
+		return true;
+	}
+	return false;
+}
+static int gpio_process_msg(VuDev *dev, VhostUserMsg *vmsg, int *do_reply)
+{
+	if (vmsg->request == VHOST_USER_NONE) {
+		dbg("gpio disconnect");
+		remove_watch(dev, -1);
+		gpioquit = true;
+		return true;
+	}
+	return false;
+}
+
+static uint64_t i2c_get_features(VuDev *dev)
+{
+	return 1ull << VIRTIO_I2C_F_ZERO_LENGTH_REQUEST;
+}
+
+static const VuDevIface i2c_iface = {
+	.get_features = i2c_get_features,
+	.queue_set_started = i2c_queue_set_started,
+	.process_msg = i2c_process_msg,
+};
+
+static void gpio_send_irq_response(struct vhost_user_gpio *gpio,
+				   unsigned int pin, unsigned int status)
+{
+	assert(pin < ARRAY_SIZE(gpio->irq_elements));
+
+	VuVirtqElement *elem = gpio->irq_elements[pin];
+	VuVirtq *vq = vu_get_queue(&gpio->dev, 1);
+
+	if (!elem) {
+		dbg("no irq buf for pin %d\n", pin);
+		assert(status != VIRTIO_GPIO_IRQ_STATUS_VALID);
+		return;
+	}
+
+	struct virtio_gpio_irq_response *resp;
+
+	assert(elem->out_num == 1);
+	assert(elem->in_sg[0].iov_len == sizeof(*resp));
+
+	resp = elem->in_sg[0].iov_base;
+	resp->status = status;
+
+	vu_queue_push(&gpio->dev, vq, elem, sizeof(*resp));
+	gpio->irq_elements[pin] = NULL;
+	free(elem);
+
+	vu_queue_notify(&gpio->dev, vq);
+}
+
+static void gpio_set_irq_type(struct vhost_user_gpio *gpio, unsigned int pin,
+			      unsigned int type)
+{
+	PyObject *pArgs, *pValue;
+
+	pArgs = PyTuple_New(2);
+	pValue = PyLong_FromLong(pin);
+	PyTuple_SetItem(pArgs, 0, pValue);
+
+	pValue = PyLong_FromLong(type);
+	PyTuple_SetItem(pArgs, 1, pValue);
+
+	pValue = PyObject_CallObject(py_gpio_set_irq_type, pArgs);
+	if (!pValue) {
+		PyErr_Print();
+		errx(1, "error from gpio.set_irq_type()");
+	}
+	Py_DECREF(pArgs);
+
+	if (type == VIRTIO_GPIO_IRQ_TYPE_NONE) {
+		gpio_send_irq_response(gpio, pin,
+				       VIRTIO_GPIO_IRQ_STATUS_INVALID);
+	}
+}
+
+static void gpio_unmask(struct vhost_user_gpio *vi, unsigned int gpio)
+{
+	PyObject *pArgs, *pValue;
+
+	pArgs = PyTuple_New(1);
+	pValue = PyLong_FromLong(gpio);
+	PyTuple_SetItem(pArgs, 0, pValue);
+
+	pValue = PyObject_CallObject(py_gpio_unmask, pArgs);
+	if (!pValue) {
+		PyErr_Print();
+		errx(1, "error from gpio.unmask()");
+	}
+	Py_DECREF(pArgs);
+}
+
+static void gpio_handle_cmdq(VuDev *dev, int qidx)
+{
+	struct vhost_user_gpio *vi =
+		container_of(dev, struct vhost_user_gpio, dev);
+	VuVirtq *vq = vu_get_queue(dev, qidx);
+	VuVirtqElement *elem;
+
+	while (1) {
+		struct virtio_gpio_request *req;
+		struct virtio_gpio_response *resp;
+
+		elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
+		if (!elem)
+			break;
+
+		dbg("elem %p index %u out_num %u in_num %u\n", elem,
+		    elem->index, elem->out_num, elem->in_num);
+
+		dump_iov("out", elem->out_sg, elem->out_num);
+		dump_iov("in", elem->in_sg, elem->in_num);
+
+		assert(elem->out_num == 1);
+		assert(elem->in_num == 1);
+
+		assert(elem->out_sg[0].iov_len == sizeof(*req));
+		assert(elem->in_sg[0].iov_len == sizeof(*resp));
+
+		req = elem->out_sg[0].iov_base;
+		resp = elem->in_sg[0].iov_base;
+
+		dbg("req type %#x gpio %#x value %#x\n", req->type, req->gpio,
+		    req->value);
+
+		switch (req->type) {
+		case VIRTIO_GPIO_MSG_IRQ_TYPE:
+			gpio_set_irq_type(vi, req->gpio, req->value);
+			break;
+		default:
+			/*
+			 * The other types couldhooked up to Python later for
+			 * testing of drivers' control of GPIOs.
+			 */
+			break;
+		}
+
+		resp->status = VIRTIO_GPIO_STATUS_OK;
+		resp->value = 0;
+
+		vu_queue_push(dev, vq, elem, sizeof(*resp));
+		free(elem);
+	}
+
+	vu_queue_notify(&vi->dev, vq);
+}
+
+static void gpio_handle_eventq(VuDev *dev, int qidx)
+{
+	struct vhost_user_gpio *vi =
+		container_of(dev, struct vhost_user_gpio, dev);
+	VuVirtq *vq = vu_get_queue(dev, qidx);
+	VuVirtqElement *elem;
+
+	for (;;) {
+		struct virtio_gpio_irq_request *req;
+		struct virtio_gpio_irq_response *resp;
+
+		elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
+		if (!elem)
+			break;
+
+		dbg("elem %p index %u out_num %u in_num %u\n", elem,
+		    elem->index, elem->out_num, elem->in_num);
+
+		dump_iov("out", elem->out_sg, elem->out_num);
+		dump_iov("in", elem->in_sg, elem->in_num);
+
+		assert(elem->out_num == 1);
+		assert(elem->in_num == 1);
+
+		assert(elem->out_sg[0].iov_len == sizeof(*req));
+		assert(elem->in_sg[0].iov_len == sizeof(*resp));
+
+		req = elem->out_sg[0].iov_base;
+		resp = elem->in_sg[0].iov_base;
+
+		dbg("irq req gpio %#x\n", req->gpio);
+
+		assert(req->gpio < ARRAY_SIZE(vi->irq_elements));
+		assert(vi->irq_elements[req->gpio] == NULL);
+
+		vi->irq_elements[req->gpio] = elem;
+
+		gpio_unmask(vi, req->gpio);
+	}
+}
+
+static void gpio_queue_set_started(VuDev *dev, int qidx, bool started)
+{
+	VuVirtq *vq = vu_get_queue(dev, qidx);
+
+	dbg("%s %d:%d\n", __func__, qidx, started);
+
+	if (qidx == 0)
+		vu_set_queue_handler(dev, vq,
+				     started ? gpio_handle_cmdq : NULL);
+	if (qidx == 1)
+		vu_set_queue_handler(dev, vq,
+				     started ? gpio_handle_eventq : NULL);
+}
+
+static int gpio_get_config(VuDev *dev, uint8_t *config, uint32_t len)
+{
+	struct vhost_user_gpio *gpio =
+		container_of(dev, struct vhost_user_gpio, dev);
+	static struct virtio_gpio_config gpioconfig = {
+		.ngpio = ARRAY_SIZE(gpio->irq_elements),
+	};
+
+	dbg("%s: len %u\n", __func__, len);
+
+	if (len > sizeof(struct virtio_gpio_config))
+		return -1;
+
+	memcpy(config, &gpioconfig, len);
+
+	return 0;
+}
+
+static uint64_t gpio_get_protocol_features(VuDev *dev)
+{
+	return 1ull << VHOST_USER_PROTOCOL_F_CONFIG;
+}
+
+static uint64_t gpio_get_features(VuDev *dev)
+{
+	return 1ull << VIRTIO_GPIO_F_IRQ;
+}
+
+static const VuDevIface gpio_vuiface = {
+	.get_features = gpio_get_features,
+	.queue_set_started = gpio_queue_set_started,
+	.process_msg = gpio_process_msg,
+	.get_config = gpio_get_config,
+	.get_protocol_features = gpio_get_protocol_features,
+};
+
+static void panic(VuDev *dev, const char *err)
+{
+	fprintf(stderr, "panicking!");
+	abort();
+}
+
+static struct watch *new_watch(struct VuDev *dev, int fd, enum watch_type type,
+			       void *func, void *data)
+{
+	struct watch *watch = malloc(sizeof(*watch));
+
+	assert(watch);
+
+	watch->dev = dev;
+	watch->fd = fd;
+	watch->func = func;
+	watch->data = data;
+	watch->type = type;
+
+	list_add(&watch->list, &watches);
+
+	return watch;
+}
+
+static void set_watch(VuDev *dev, int fd, int condition, vu_watch_cb cb,
+		      void *data)
+{
+	struct watch *watch = new_watch(dev, fd, VU_WATCH, cb, data);
+	int ret;
+
+	struct epoll_event ev = {
+		.events = EPOLLIN,
+		.data.ptr = watch,
+	};
+
+	dbg("set watch epfd %d fd %d condition %d cb %p\n", epfd, fd, condition,
+	    cb);
+
+	epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
+
+	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
+	if (ret < 0)
+		err(1, "epoll_ctl");
+}
+
+static void remove_watch(VuDev *dev, int fd)
+{
+	struct watch *watch, *tmp;
+
+	list_for_each_entry_safe(watch, tmp, &watches, list) {
+		if (watch->dev != dev)
+			continue;
+		if (fd >= 0 && watch->fd != fd)
+			continue;
+
+		epoll_ctl(epfd, EPOLL_CTL_DEL, watch->fd, NULL);
+
+		list_del(&watch->list);
+		free(watch);
+	}
+}
+
+static int unix_listen(const char *path)
+{
+	struct sockaddr_un un = {
+		.sun_family = AF_UNIX,
+	};
+	int sock;
+	int ret;
+
+	unlink(path);
+
+	sock = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+	if (sock < 0)
+		err(1, "socket");
+
+	memcpy(&un.sun_path, path, strlen(path));
+
+	ret = bind(sock, (struct sockaddr *)&un, sizeof(un));
+	if (ret < 0)
+		err(1, "bind");
+
+	ret = listen(sock, 1);
+	if (ret < 0)
+		err(1, "listen");
+
+	return sock;
+}
+
+static void dev_add_watch(int epfd, struct watch *watch)
+{
+	struct epoll_event event = {
+		.events = EPOLLIN | EPOLLONESHOT,
+		.data.ptr = watch,
+	};
+	int ret;
+
+	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, watch->fd, &event);
+	if (ret < 0)
+		err(1, "EPOLL_CTL_ADD");
+}
+
+static VuDev *gpio_init(int epfd, const char *path)
+{
+	struct watch *watch;
+	VuDev *dev;
+	int lsock;
+	bool rc;
+
+	lsock = unix_listen(path);
+	if (lsock < 0)
+		err(1, "listen %s", path);
+
+	rc = vu_init(&gpio.dev, 2, lsock, panic, NULL, set_watch,
+		     remove_watch, &gpio_vuiface);
+	assert(rc == true);
+
+	dev = &gpio.dev;
+	watch = new_watch(dev, lsock, LISTEN, vu_dispatch, dev);
+
+	dev_add_watch(epfd, watch);
+
+	return dev;
+}
+
+static VuDev *i2c_init(int epfd, const char *path)
+{
+	static struct vhost_user_i2c i2c = {};
+	VuDev *dev = &i2c.dev;
+	struct watch *watch;
+	int lsock;
+	bool rc;
+
+	lsock = unix_listen(path);
+	if (lsock < 0)
+		err(1, "listen %s", path);
+
+	rc = vu_init(dev, 1, lsock, panic, NULL, set_watch,
+		     remove_watch, &i2c_iface);
+	assert(rc == true);
+
+	watch = new_watch(dev, lsock, LISTEN, vu_dispatch, dev);
+
+	dev_add_watch(epfd, watch);
+
+	return dev;
+}
+
+static pid_t run_uml(char **argv)
+{
+	int log, null, ret;
+	pid_t pid;
+
+	pid = fork();
+	if (pid < 0)
+		err(1, "fork");
+	if (pid > 0)
+		return pid;
+
+	chdir(getenv("ROADTEST_WORK_DIR"));
+
+	log = open("uml.txt", O_WRONLY | O_TRUNC | O_APPEND | O_CREAT, 0600);
+	if (log < 0)
+		err(1, "open uml.txt");
+
+	null = open("/dev/null", O_RDONLY);
+	if (null < 0)
+		err(1, "open null");
+
+	ret = dup2(null, 0);
+	if (ret < 0)
+		err(1, "dup2");
+
+	ret = dup2(log, 1);
+	if (ret < 0)
+		err(1, "dup2");
+
+	ret = dup2(log, 2);
+	if (ret < 0)
+		err(1, "dup2");
+
+	execvpe(argv[0], argv, environ);
+	err(1, "execve");
+
+	return -1;
+}
+
+int main(int argc, char *argv[])
+{
+	static struct option long_option[] = {
+		{ "main-script", required_argument, 0, 'm' },
+		{ "gpio-socket", required_argument, 0, 'g' },
+		{ "i2c-socket", required_argument, 0, 'i' },
+	};
+
+	while (1) {
+		int c = getopt_long(argc, argv, "", long_option, NULL);
+
+		if (c == -1)
+			break;
+
+		switch (c) {
+		case 'm':
+			opt_main_script = optarg;
+			break;
+
+		case 'g':
+			opt_gpio_socket = optarg;
+			break;
+
+		case 'i':
+			opt_i2c_socket = optarg;
+			break;
+
+		default:
+			errx(1, "getopt");
+		}
+	}
+
+	if (!opt_main_script || !opt_gpio_socket || !opt_i2c_socket)
+		errx(1, "Invalid arguments");
+
+	epfd = epoll_create1(EPOLL_CLOEXEC);
+	if (epfd < 0)
+		err(1, "epoll_create1");
+
+	init_python();
+
+	gpio_init(epfd, opt_gpio_socket);
+	i2c_init(epfd, opt_i2c_socket);
+
+	run_uml(&argv[optind]);
+
+	while (1) {
+		struct epoll_event events[10];
+		int nfds;
+		int i;
+
+		nfds = epoll_wait(epfd, events, ARRAY_SIZE(events), -1);
+		if (nfds < 0) {
+			if (errno == EINTR) {
+				continue;
+
+				err(1, "epoll_wait");
+			}
+		}
+
+		if (!PyObject_CallObject(py_process_control, NULL)) {
+			PyErr_Print();
+			errx(1, "error from backend.process_control");
+		}
+
+		for (i = 0; i < nfds; i++) {
+			struct epoll_event *event = &events[i];
+			struct watch *watch = event->data.ptr;
+			int fd;
+
+			switch (watch->type) {
+			case LISTEN:
+				fd = accept(watch->fd, NULL, NULL);
+				close(watch->fd);
+				if (fd == -1)
+					err(1, "accept");
+
+				watch->dev->sock = fd;
+				watch->fd = fd;
+				watch->type = SOCKET_WATCH;
+
+				struct epoll_event event = {
+					.events = EPOLLIN,
+					.data.ptr = watch,
+				};
+
+				int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd,
+						    &event);
+				if (ret < 0)
+					err(1, "epoll_ctl");
+
+				break;
+			case SOCKET_WATCH:
+				vu_dispatch(watch->dev);
+				break;
+			case VU_WATCH:
+				((vu_watch_cb)(watch->func))(watch->dev, POLLIN,
+							     watch->data);
+				break;
+			default:
+				fprintf(stderr, "abort!");
+				abort();
+			}
+		}
+
+		if (i2cquit && gpioquit)
+			break;
+	}
+
+	vu_deinit(&i2c.dev);
+	vu_deinit(&gpio.dev);
+
+	Py_Finalize();
+
+	return 0;
+}
Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#5 lore raw

RFC 3/10 roadtest: add framework

In reply to Vincent Whitchurch

Add the bulk of the roadtest framework. Apart from one init shell script, this is written in Python and includes three closely-related parts:

- The test runner which is invoked from the command line by the user and which starts the backend and sends the test jobs and results to/from UML.

- Test support code which is used by the actual driver tests run inside UML and which interact with the backend via a file-based asynchronous communication method.

- The backend which is run by the Python interpreter embedded in the C backend. This part runs the hardware models and is controlled by the tests and the driver (via virtio in the C backend).

Some unit tests for the framework itself are included and these will be automatically run whenever the driver tests are run.

---
 tools/testing/roadtest/init.sh                |  19 ++
 tools/testing/roadtest/roadtest/__init__.py   |   2 +
 .../roadtest/roadtest/backend/__init__.py     |   0
 .../roadtest/roadtest/backend/backend.py      |  32 ++
 .../testing/roadtest/roadtest/backend/gpio.py | 111 +++++++
 .../testing/roadtest/roadtest/backend/i2c.py  | 123 ++++++++
 .../testing/roadtest/roadtest/backend/main.py |  13 +
 .../testing/roadtest/roadtest/backend/mock.py |  20 ++
 .../roadtest/roadtest/backend/test_gpio.py    |  98 ++++++
 .../roadtest/roadtest/backend/test_i2c.py     |  84 +++++
 .../testing/roadtest/roadtest/cmd/__init__.py |   0
 tools/testing/roadtest/roadtest/cmd/main.py   | 146 +++++++++
 tools/testing/roadtest/roadtest/cmd/remote.py |  48 +++
 .../roadtest/roadtest/core/__init__.py        |   0
 .../testing/roadtest/roadtest/core/control.py |  52 ++++
 .../roadtest/roadtest/core/devicetree.py      | 155 ++++++++++
 .../roadtest/roadtest/core/hardware.py        |  94 ++++++
 tools/testing/roadtest/roadtest/core/log.py   |  42 +++
 .../testing/roadtest/roadtest/core/modules.py |  38 +++
 .../testing/roadtest/roadtest/core/opslog.py  |  35 +++
 tools/testing/roadtest/roadtest/core/proxy.py |  48 +++
 tools/testing/roadtest/roadtest/core/suite.py | 286 ++++++++++++++++++
 tools/testing/roadtest/roadtest/core/sysfs.py |  77 +++++
 .../roadtest/roadtest/core/test_control.py    |  35 +++
 .../roadtest/roadtest/core/test_devicetree.py |  31 ++
 .../roadtest/roadtest/core/test_hardware.py   |  41 +++
 .../roadtest/roadtest/core/test_log.py        |  54 ++++
 .../roadtest/roadtest/core/test_opslog.py     |  27 ++
 .../roadtest/roadtest/tests/__init__.py       |   0
 29 files changed, 1711 insertions(+)
 create mode 100755 tools/testing/roadtest/init.sh
 create mode 100644 tools/testing/roadtest/roadtest/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/backend.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/main.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/mock.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/main.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/remote.py
 create mode 100644 tools/testing/roadtest/roadtest/core/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/core/control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/modules.py
 create mode 100644 tools/testing/roadtest/roadtest/core/opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/core/proxy.py
 create mode 100644 tools/testing/roadtest/roadtest/core/suite.py
 create mode 100644 tools/testing/roadtest/roadtest/core/sysfs.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/__init__.py
tools/testing/roadtest/init.sh new file +19 -0
new file mode 100755
index 000000000000..c5fb28478aa3
@@ -0,0 +1,19 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0-only
+
+mount -t proc proc /proc
+echo 8 > /proc/sys/kernel/printk
+mount -t sysfs nodev /sys
+mount -t debugfs nodev /sys/kernel/debug
+
+echo 0 > /sys/bus/i2c/drivers_autoprobe
+echo 0 > /sys/bus/platform/drivers_autoprobe
+
+python3 -m roadtest.cmd.remote
+status=$?
+[ "${ROADTEST_SHELL}" = "1" ] || {
+    # rsync doesn't handle these zero-sized files correctly.
+    cp -ra --no-preserve=ownership /sys/kernel/debug/gcov ${ROADTEST_WORK_DIR}/gcov
+    echo o > /proc/sysrq-trigger
+}
+exec setsid sh -c 'exec bash </dev/tty0 >/dev/tty0 2>&1'
tools/testing/roadtest/roadtest/__init__.py new file +2 -0
new file mode 100644
index 000000000000..dac3ce6976e5
@@ -0,0 +1,2 @@
+ENV_WORK_DIR = "ROADTEST_WORK_DIR"
+ENV_BUILD_DIR = "ROADTEST_BUILD_DIR"
tools/testing/roadtest/roadtest/backend/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/backend/backend.py new file +32 -0
new file mode 100644
index 000000000000..bfd19fc363c2
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import logging
+import os
+from pathlib import Path
+
+from roadtest import ENV_WORK_DIR
+from roadtest.core.control import ControlReader
+
+from . import gpio, i2c, mock
+
+logger = logging.getLogger(__name__)
+
+try:
+    import cbackend  # type: ignore[import]
+except ModuleNotFoundError:
+    # In unit tests
+    cbackend = None
+
+
+class Backend:
+    def __init__(self) -> None:
+        work = Path(os.environ[ENV_WORK_DIR])
+        self.control = ControlReader(work_dir=work)
+        self.c = cbackend
+        self.i2c = i2c.I2CBackend(self)
+        self.gpio = gpio.GpioBackend(self)
+        self.mock = mock.MockBackend(work)
+
+    def process_control(self) -> None:
+        self.control.process({"backend": self})
tools/testing/roadtest/roadtest/backend/gpio.py new file +111 -0

111 lines not on this page · raw message

tools/testing/roadtest/roadtest/backend/i2c.py new file +123 -0

123 lines not on this page · raw message

tools/testing/roadtest/roadtest/backend/main.py new file +13 -0
new file mode 100644
index 000000000000..25be86ded9ea
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import logging
+
+import roadtest.backend.backend
+
+logging.basicConfig(
+    format="%(asctime)s - %(levelname)s - %(name)s: %(message)s", level=logging.DEBUG
+)
+
+backend = roadtest.backend.backend.Backend()
+backend.process_control()
tools/testing/roadtest/roadtest/backend/mock.py new file +20 -0
new file mode 100644
index 000000000000..8ce33a6bc0f1
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import functools
+from pathlib import Path
+from typing import Any, Callable
+
+from roadtest.core.opslog import OpsLogWriter
+
+
+class MockBackend:
+    def __init__(self, work: Path) -> None:
+        self.opslog = OpsLogWriter(work)
+
+    @functools.cache
+    def __getattr__(self, name: str) -> Callable:
+        def func(*args: Any, **kwargs: Any) -> None:
+            self.opslog.write(f"mock.{name}(*{str(args)}, **{str(kwargs)})")
+
+        return func
tools/testing/roadtest/roadtest/backend/test_gpio.py new file +98 -0

98 lines not on this page · raw message

tools/testing/roadtest/roadtest/backend/test_i2c.py new file +84 -0

84 lines not on this page · raw message

tools/testing/roadtest/roadtest/cmd/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/cmd/main.py new file +146 -0

146 lines not on this page · raw message

tools/testing/roadtest/roadtest/cmd/remote.py new file +48 -0

48 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/core/control.py new file +52 -0

52 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/devicetree.py new file +155 -0

155 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/hardware.py new file +94 -0

94 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/log.py new file +42 -0

42 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/modules.py new file +38 -0
new file mode 100644
index 000000000000..5bd2d92a322b
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import os
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from roadtest import ENV_BUILD_DIR
+
+
+def modprobe(modname: str, remove: bool = False) -> None:
+    moddir = Path(os.environ[ENV_BUILD_DIR]) / "modules"
+    args = []
+    if remove:
+        args.append("--remove")
+    args += [f"--dirname={moddir}", modname]
+    subprocess.check_output(["/sbin/modprobe"] + args)
+
+
+def insmod(modname: str) -> None:
+    modprobe(modname)
+
+
+def rmmod(modname: str) -> None:
+    subprocess.check_output(["/sbin/rmmod", modname])
+
+
+class Module:
+    def __init__(self, name: str) -> None:
+        self.name = name
+
+    def __enter__(self) -> "Module":
+        modprobe(self.name)
+        return self
+
+    def __exit__(self, *_: Any) -> None:
+        rmmod(self.name)
tools/testing/roadtest/roadtest/core/opslog.py new file +35 -0
new file mode 100644
index 000000000000..83bb4f525d03
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import os
+from pathlib import Path
+
+OPSLOG_FILE = "opslog.txt"
+
+
+class OpsLogWriter:
+    def __init__(self, work: Path) -> None:
+        path = work / OPSLOG_FILE
+        path.unlink(missing_ok=True)
+        self.file = open(path, "a", buffering=1)
+
+    def write(self, line: str) -> None:
+        self.file.write(line + "\n")
+
+
+class OpsLogReader:
+    def __init__(self, work: Path) -> None:
+        self.path = work / OPSLOG_FILE
+        self.opslogpos = 0
+
+    def read_next(self) -> list[str]:
+        # There is a problem in hostfs (see Hostfs Caveats) which means
+        # that reads from UML on a file which is extended on the host don't see
+        # the new data unless we open and close the file, so we can't open once
+        # and use readlines().
+        with open(self.path, "r") as f:
+            os.lseek(f.fileno(), self.opslogpos, os.SEEK_SET)
+            opslog = [line.rstrip() for line in f.readlines()]
+            self.opslogpos = os.lseek(f.fileno(), 0, os.SEEK_CUR)
+
+        return opslog
tools/testing/roadtest/roadtest/core/proxy.py new file +48 -0

48 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/suite.py new file +286 -0

286 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/sysfs.py new file +77 -0

77 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/test_control.py new file +35 -0
new file mode 100644
index 000000000000..a8cf9105eb52
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest import TestCase
+
+from .control import ControlReader, ControlWriter
+
+
+class TestControl(TestCase):
+    def test_control(self) -> None:
+        with TemporaryDirectory() as tmpdir:
+            work = Path(tmpdir)
+            reader = ControlReader(work)
+            writer = ControlWriter(work)
+
+            values = []
+
+            def append(new: int) -> None:
+                nonlocal values
+                values.append(new)
+
+            vars = {"append": append}
+            writer.write_cmd("append(1)")
+
+            reader.process(vars)
+            self.assertEqual(values, [1])
+
+            writer.write_cmd("append(2)")
+            writer.write_log("append(4)")
+            writer.write_cmd("append(3)")
+
+            reader.process(vars)
+            self.assertEqual(values, [1, 2, 3])
tools/testing/roadtest/roadtest/core/test_devicetree.py new file +31 -0
new file mode 100644
index 000000000000..db61fd24b39a
@@ -0,0 +1,31 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import tempfile
+import unittest
+from pathlib import Path
+
+from . import devicetree
+
+
+class TestDevicetree(unittest.TestCase):
+    def test_compile(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmpdir = Path(tmp)
+            # We don't have the ksrcdir so we can't test if includes work.
+            dt = devicetree.Devicetree(tmpdir, tmpdir)
+
+            dt.assemble(
+                [
+                    devicetree.DtFragment(
+                        src="""
+&i2c {
+    foo = <1>;
+};
+            """
+                    )
+                ]
+            )
+            dt.compile("test.dtb")
+            dtb = tmpdir / "test.dtb"
+            self.assertTrue((dtb).exists())
tools/testing/roadtest/roadtest/core/test_hardware.py new file +41 -0

41 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/test_log.py new file +54 -0

54 lines not on this page · raw message

tools/testing/roadtest/roadtest/core/test_opslog.py new file +27 -0
new file mode 100644
index 000000000000..bd594c587032
@@ -0,0 +1,27 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest import TestCase
+
+from .opslog import OpsLogReader, OpsLogWriter
+
+
+class TestOpsLOg(TestCase):
+    def test_opslog(self) -> None:
+        with TemporaryDirectory() as tmpdir:
+            work = Path(tmpdir)
+            writer = OpsLogWriter(work)
+            reader = OpsLogReader(work)
+
+            self.assertEqual(reader.read_next(), [])
+
+            writer.write("1")
+            writer.write("2")
+
+            self.assertEqual(reader.read_next(), ["1", "2"])
+            self.assertEqual(reader.read_next(), [])
+
+            writer.write("3")
+            self.assertEqual(reader.read_next(), ["3"])
tools/testing/roadtest/roadtest/tests/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#6 lore raw

RFC 4/10 roadtest: add base config

In reply to Vincent Whitchurch

Add the base config options for the roadtest kernel (generated with "savedefconfig").

roadtest uses a single kernel for all tests and the drivers under test are built as modules. Additional config options are added by merging config fragments from each subsystems' test directory.

The kernel is built with several debug options to catch more problems during testing.

---
 .../roadtest/roadtest/tests/base/config       | 84 +++++++++++++++++++
 1 file changed, 84 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/base/config
tools/testing/roadtest/roadtest/tests/base/config new file +84 -0
new file mode 100644
index 000000000000..c1952d047c8e
@@ -0,0 +1,84 @@
+CONFIG_NO_HZ=y
+CONFIG_HIGH_RES_TIMERS=y
+CONFIG_LOG_BUF_SHIFT=14
+CONFIG_EXPERT=y
+CONFIG_HOSTFS=y
+CONFIG_UML_TIME_TRAVEL_SUPPORT=y
+CONFIG_NULL_CHAN=y
+CONFIG_PORT_CHAN=y
+CONFIG_PTY_CHAN=y
+CONFIG_TTY_CHAN=y
+CONFIG_XTERM_CHAN=y
+CONFIG_CON_CHAN="pts"
+CONFIG_SSL=y
+CONFIG_SSL_CHAN="pts"
+CONFIG_MAGIC_SYSRQ=y
+CONFIG_VIRTIO_UML=y
+CONFIG_UML_PCI_OVER_VIRTIO=y
+CONFIG_UML_PCI_OVER_VIRTIO_DEVICE_ID=1234
+CONFIG_GCOV_KERNEL=y
+CONFIG_MODULES=y
+CONFIG_MODULE_UNLOAD=y
+CONFIG_BINFMT_MISC=m
+# CONFIG_COMPACTION is not set
+CONFIG_DEVTMPFS=y
+CONFIG_DEVTMPFS_MOUNT=y
+CONFIG_OF=y
+# CONFIG_INPUT is not set
+CONFIG_LEGACY_PTY_COUNT=32
+CONFIG_HW_RANDOM=y
+# CONFIG_HW_RANDOM_IXP4XX is not set
+# CONFIG_HW_RANDOM_STM32 is not set
+# CONFIG_HW_RANDOM_MESON is not set
+# CONFIG_HW_RANDOM_CAVIUM is not set
+# CONFIG_HW_RANDOM_MTK is not set
+# CONFIG_HW_RANDOM_EXYNOS is not set
+# CONFIG_HW_RANDOM_NPCM is not set
+# CONFIG_HW_RANDOM_KEYSTONE is not set
+CONFIG_RANDOM_TRUST_BOOTLOADER=y
+CONFIG_I2C=y
+# CONFIG_I2C_COMPAT is not set
+CONFIG_I2C_CHARDEV=y
+CONFIG_I2C_VIRTIO=y
+CONFIG_I2C_STUB=m
+CONFIG_PPS=y
+CONFIG_GPIOLIB=y
+CONFIG_GPIO_VIRTIO=y
+CONFIG_NET=y
+CONFIG_UNIX=y
+CONFIG_NEW_LEDS=y
+CONFIG_LEDS_CLASS=y
+CONFIG_LEDS_GPIO=y
+CONFIG_LEDS_TRIGGERS=y
+CONFIG_LEDS_TRIGGER_HEARTBEAT=y
+CONFIG_RTC_CLASS=y
+# CONFIG_RTC_HCTOSYS is not set
+# CONFIG_RTC_SYSTOHC is not set
+CONFIG_RTC_DEBUG=y
+# CONFIG_RTC_NVMEM is not set
+CONFIG_VIRTIO_INPUT=y
+# CONFIG_BCM_VIDEOCORE is not set
+CONFIG_QUOTA=y
+CONFIG_AUTOFS4_FS=m
+CONFIG_PROC_KCORE=y
+CONFIG_TMPFS=y
+CONFIG_NLS=y
+CONFIG_CRYPTO=y
+CONFIG_CRYPTO_CRC32C=y
+CONFIG_CRYPTO_JITTERENTROPY=y
+CONFIG_CRC16=y
+CONFIG_PRINTK_TIME=y
+CONFIG_PRINTK_CALLER=y
+CONFIG_DYNAMIC_DEBUG=y
+CONFIG_DEBUG_INFO=y
+CONFIG_FRAME_WARN=1024
+CONFIG_READABLE_ASM=y
+CONFIG_DEBUG_FS=y
+CONFIG_UBSAN=y
+CONFIG_PAGE_EXTENSION=y
+CONFIG_DEBUG_OBJECTS=y
+CONFIG_DEBUG_OBJECTS_FREE=y
+CONFIG_DEBUG_OBJECTS_TIMERS=y
+CONFIG_DEBUG_OBJECTS_WORK=y
+CONFIG_PROVE_LOCKING=y
+CONFIG_ENABLE_DEFAULT_TRACERS=y
Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#7 lore raw

RFC 5/10 roadtest: add build files

In reply to Vincent Whitchurch

Add a Makefile and other miscellaneous build-related files for the roadtest framework.

To make it easier to run the tests on systems which do not have the required libraries or Python version, a Dockerfile is included and the Makefile has built-in support for running the tests in a Docker container.

Targets for code formatting and static checking of the Python code are included.

---
 tools/testing/roadtest/.gitignore       |  2 +
 tools/testing/roadtest/Dockerfile       | 25 ++++++++
 tools/testing/roadtest/Makefile         | 84 +++++++++++++++++++++++++
 tools/testing/roadtest/pyproject.toml   | 10 +++
 tools/testing/roadtest/requirements.txt |  4 ++
 tools/testing/roadtest/src/.gitignore   |  1 +
 6 files changed, 126 insertions(+)
 create mode 100644 tools/testing/roadtest/.gitignore
 create mode 100644 tools/testing/roadtest/Dockerfile
 create mode 100644 tools/testing/roadtest/Makefile
 create mode 100644 tools/testing/roadtest/pyproject.toml
 create mode 100644 tools/testing/roadtest/requirements.txt
 create mode 100644 tools/testing/roadtest/src/.gitignore
tools/testing/roadtest/.gitignore new file +2 -0
new file mode 100644
index 000000000000..0cbd00343694
@@ -0,0 +1,2 @@
+__pycache__
+.py[cod]
tools/testing/roadtest/Dockerfile new file +25 -0
new file mode 100644
index 000000000000..f2982179c327
@@ -0,0 +1,25 @@
+FROM debian:bullseye
+
+# Kernel build
+RUN apt-get update && apt-get -y install \
+    bc \
+    build-essential \
+    flex \
+    bison \
+    rsync \
+    kmod
+
+# Running roadtests
+RUN apt-get update && apt-get -y install \
+     python3.9 \
+     libpython3.9-dev \
+     python3 \
+     device-tree-compiler
+
+# Development and debugging
+RUN apt-get update && apt-get -y install \
+     uml-utilities \
+     telnetd \
+     python3-pip
+COPY requirements.txt /tmp/
+RUN pip install --requirement /tmp/requirements.txt
tools/testing/roadtest/Makefile new file +84 -0

84 lines not on this page · raw message

tools/testing/roadtest/pyproject.toml new file +10 -0
new file mode 100644
index 000000000000..6b8b05eb3cad
@@ -0,0 +1,10 @@
+[tool.isort]
+profile = "black"
+
+[tool.mypy]
+disallow_untyped_defs = true
+check_untyped_defs = true
+no_implicit_optional = true
+warn_return_any = true
+warn_unused_ignores = true
+show_error_codes = true
tools/testing/roadtest/requirements.txt new file +4 -0
new file mode 100644
index 000000000000..e1ac403d826e
@@ -0,0 +1,4 @@
+black==22.1.0
+isort==5.10.1
+mypy==0.931
+pyflakes==2.4.0
tools/testing/roadtest/src/.gitignore new file +1 -0
new file mode 100644
index 000000000000..895dab3fe4be
@@ -0,0 +1 @@
+compile_flags.txt
Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#8 lore raw

RFC 6/10 roadtest: add documentation

In reply to Vincent Whitchurch

Add documentation for the roadtest device driver testing framework. This includes a "how to write your first test" tutorial.

---
 Documentation/dev-tools/index.rst    |   1 +
 Documentation/dev-tools/roadtest.rst | 669 +++++++++++++++++++++++++++
 2 files changed, 670 insertions(+)
 create mode 100644 Documentation/dev-tools/roadtest.rst
Documentation/dev-tools/index.rst +1 -0
index 4621eac290f4..44fea7c50dad 100644
@@ -33,6 +33,7 @@ Documentation/dev-tools/testing-overview.rst
    kselftest
    kunit/index
    ktap
+   roadtest
 
 
 .. only::  subproject and html
Documentation/dev-tools/roadtest.rst new file +669 -0

669 lines not on this page · raw message

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#9 lore raw

RFC 7/10 iio: light: opt3001: add roadtest

In reply to Vincent Whitchurch

Add a regression test for the problem fixed by the following patch, which would require specific environmental conditions to be able to be reproduced and regression-tested on real hardware:

iio: light: opt3001: Fixed timeout error when 0 lux
https://lore.kernel.org/lkml/[email protected]/

No other aspects of the driver are tested.

---
 .../roadtest/roadtest/tests/iio/__init__.py   |  0
 .../roadtest/roadtest/tests/iio/config        |  1 +
 .../roadtest/tests/iio/light/__init__.py      |  0
 .../roadtest/roadtest/tests/iio/light/config  |  1 +
 .../roadtest/tests/iio/light/test_opt3001.py  | 95 +++++++++++++++++++
 5 files changed, 97 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py
tools/testing/roadtest/roadtest/tests/iio/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/iio/config new file +1 -0
new file mode 100644
index 000000000000..a08d9e23ce38
@@ -0,0 +1 @@
+CONFIG_IIO=y
tools/testing/roadtest/roadtest/tests/iio/light/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/iio/light/config new file +1 -0
new file mode 100644
index 000000000000..b9753f2d0728
@@ -0,0 +1 @@
+CONFIG_OPT3001=m
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +95 -0

95 lines not on this page · raw message

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#10 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 91 lines · Vincent Whitchurch

Add a regression test for the problem fixed by the following patch, which would require specific environmental conditions to be able to be reproduced and regression-tested on real hardware:

iio: light: opt3001: Fixed timeout error when 0 lux
https://lore.kernel.org/lkml/[email protected]/

No other aspects of the driver are tested.

---
 .../roadtest/roadtest/tests/iio/__init__.py   |  0
 .../roadtest/roadtest/tests/iio/config        |  1 +
 .../roadtest/tests/iio/light/__init__.py      |  0
 .../roadtest/roadtest/tests/iio/light/config  |  1 +
 .../roadtest/tests/iio/light/test_opt3001.py  | 95 +++++++++++++++++++
 5 files changed, 97 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py
tools/testing/roadtest/roadtest/tests/iio/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/iio/config new file +1 -0
new file mode 100644
index 000000000000..a08d9e23ce38
@@ -0,0 +1 @@
+CONFIG_IIO=y
tools/testing/roadtest/roadtest/tests/iio/light/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/iio/light/config new file +1 -0
new file mode 100644
index 000000000000..b9753f2d0728
@@ -0,0 +1 @@
+CONFIG_OPT3001=m
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +41 -0
new file mode 100644
index 000000000000..abf20b8f3516
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+from typing import Any, Final
+
+from roadtest.backend.i2c import SMBusModel
+from roadtest.core.devicetree import DtFragment, DtVar
+from roadtest.core.hardware import Hardware
+from roadtest.core.modules import insmod, rmmod
+from roadtest.core.suite import UMLTestCase
+from roadtest.core.sysfs import I2CDriver, read_float
+
+REG_RESULT: Final = 0x00
+REG_CONFIGURATION: Final = 0x01
+REG_LOW_LIMIT: Final = 0x02
+REG_HIGH_LIMIT: Final = 0x03
+REG_MANUFACTURER_ID: Final = 0x7E
+REG_DEVICE_ID: Final = 0x7F
+
+REG_CONFIGURATION_CRF: Final = 1 << 7
+
+
+class OPT3001(SMBusModel):
+    def __init__(self, **kwargs: Any) -> None:
+        super().__init__(regbytes=2, byteorder="big", **kwargs)
+        # Reset values from datasheet
+        self.regs = {
+            REG_RESULT: 0x0000,
+            REG_CONFIGURATION: 0xC810,
+            REG_LOW_LIMIT: 0xC000,
+            REG_HIGH_LIMIT: 0xBFFF,
+            REG_MANUFACTURER_ID: 0x5449,
+            REG_DEVICE_ID: 0x3001,
+        }
+
+    def reg_read(self, addr: int) -> int:
+        val = self.regs[addr]
+
+        if addr == REG_CONFIGURATION:
+            # Always indicate that the conversion is ready.  This is good
+            # enough for our current purposes.

tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py line 51

Quoted 10 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +10 -0
+            val |= REG_CONFIGURATION_CRF
+
+        return val
+
+    def reg_write(self, addr: int, val: int) -> None:
+        assert addr in self.regs
+        self.regs[addr] = val
+
+
+class TestOPT3001(UMLTestCase):

I am partial to starting with UML since there are a lot of nice easy things about starting there; however, I imagine people will eventually want to use this on other architectures (speaking from experience). How difficult do you think it would be to extend this to support manipulating fake devices in say QEMU?

I also have some colleagues inside of Google that worked on some projects to simulate simple devices on an FPGA to test software and adjacent devices in a conceptually similar way; one of these teams built a Domain Specific Language kind of like roadtest to implement the tests and the environment for the tests. The main reason I mention this here is I am thinking about maybe one day having an API you can implement so you can run your roadtests on UML, QEMU, or on any emulator or hardware testbed that implements the appropriate API.

I'll try to dig up some people who might be interested and add them here.

Quoted 34 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +34 -0
+    dts = DtFragment(
+        src="""
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "ti,opt3001";
+        reg = <0x$addr$>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("opt3001")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("opt3001")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("opt3001")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(OPT3001)
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_illuminance(self) -> None:
+        data = [
+            # Some values from datasheet, and 0
+            (0b_0000_0000_0000_0000, 0),

tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py line 95

Quoted 10 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +10 -0
+            (0b_0000_0000_0000_0001, 0.01),
+            (0b_0011_0100_0101_0110, 88.80),
+            (0b_0111_1000_1001_1010, 2818.56),
+        ]
+        with self.driver.bind(self.dts["addr"]) as dev:
+            luxfile = dev.path / "iio:device0/in_illuminance_input"
+
+            for regval, lux in data:
+                self.hw.reg_write(REG_RESULT, regval)
+                self.assertEqual(read_float(luxfile), lux)

I love the framework; this looks very easy to use.

One nit about this test; it seems like you cover just one test case here - the happy path. Can you cover some other one? Particularly some error paths?

Sorry, I am not trying to be cheeky here; it looks like this driver actually should probably be fully (or very close to fully) testable via roadtest as I understand it. It only looks like there are a handful of cases to cover for the driver: the device is busy, the device returned something invalid, the user requested something invalid, and several SMBus read/write failures - it really only looks like there are a handful of paths and I think they are all accessible via the I2C interface (except for maybe the user requesting something invalid).

#11 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 9 lines · Brendan Higgins
Quoted 1 line · Vincent Whitchurch

+class TestOPT3001(UMLTestCase):

I am partial to starting with UML since there are a lot of nice easy things about starting there; however, I imagine people will eventually want to use this on other architectures (speaking from experience). How difficult do you think it would be to extend this to support manipulating fake devices in say QEMU?

It should be possible, but upstream QEMU doesn't have everything that we need so some work is needed there. Also, of course work is need to provide user space for running the tests and communicating between the virtual machine and the backend:

- We need user space, so build scripts would need to be provided to cross-compile busybox and Python (and whatever libraries it needs) for the target architecture.

- We also use UML's hostfs feature to make things transparent to the user and to avoid having to set up things like networking for communication between the host and the backend. I think QEMU's 9pfs support can be used as a rootfs too but it's not something I've personally tested.

- We use virtio-i2c and virtio-gpio and use virtio-uml which uses the vhost-user API to communicate from UML to the backend. The latest version of QEMU has support for vhost-user-i2c, but vhost-user-gpio doesn't seem to have been merged yet, so work is needed on the QEMU side. This will also be true for other buses in the future, if they are implemented with new virtio devices.

- For MMIO, UML has virtio-mmio which allows implementing any PCIe device (and by extension any platform device) outside of UML, but last I checked, upstream QEMU did not have something similar.

Quoted 62 lines

I also have some colleagues inside of Google that worked on some projects to simulate simple devices on an FPGA to test software and adjacent devices in a conceptually similar way; one of these teams built a Domain Specific Language kind of like roadtest to implement the tests and the environment for the tests. The main reason I mention this here is I am thinking about maybe one day having an API you can implement so you can run your roadtests on UML, QEMU, or on any emulator or hardware testbed that implements the appropriate API.

I'll try to dig up some people who might be interested and add them here.

Quoted 34 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +34 -0
+    dts = DtFragment(
+        src="""
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "ti,opt3001";
+        reg = <0x$addr$>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("opt3001")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("opt3001")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("opt3001")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(OPT3001)
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_illuminance(self) -> None:
+        data = [
+            # Some values from datasheet, and 0
+            (0b_0000_0000_0000_0000, 0),

tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py line 95

Quoted 10 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py new file +10 -0
+            (0b_0000_0000_0000_0001, 0.01),
+            (0b_0011_0100_0101_0110, 88.80),
+            (0b_0111_1000_1001_1010, 2818.56),
+        ]
+        with self.driver.bind(self.dts["addr"]) as dev:
+            luxfile = dev.path / "iio:device0/in_illuminance_input"
+
+            for regval, lux in data:
+                self.hw.reg_write(REG_RESULT, regval)
+                self.assertEqual(read_float(luxfile), lux)

I love the framework; this looks very easy to use.

One nit about this test; it seems like you cover just one test case here - the happy path. Can you cover some other one? Particularly some error paths?

Quoted 9 lines

Sorry, I am not trying to be cheeky here; it looks like this driver actually should probably be fully (or very close to fully) testable via roadtest as I understand it. It only looks like there are a handful of cases to cover for the driver: the device is busy, the device returned something invalid, the user requested something invalid, and several SMBus read/write failures - it really only looks like there are a handful of paths and I think they are all accessible via the I2C interface (except for maybe the user requesting something invalid).

Yes, there are more things that could be tested in this driver. However, as the commit message says, I only indented this particular test to serve as a regression test for the specific bug fix, which would need an environment where the chip detects 0 lux to be able to test on real hardware. There are a few reasons for this:

- Unlike the other drivers being tested in this series, I don't have access to boards with this chip so my interest in this particular piece of hardware is limited.

- I actually started writing more tests for this driver earlier on (specifically, testing the configuration which uses interrupts), but I quickly discovered that this driver has race conditions which result in unbalanced mutex locking (in brief: the ok_to_ignore_lock stuff is broken). This shows the value of the test framework, but I also didn't want to write non-trivial fixes for drivers where I didn't have real hardware to test.

- Also, some paths in this driver needs a modification to be tested under roadtest. It uses wait_event_timeout() with a fixed value, but we cannot guarantee that this constraint is met in the test environment since it depends on things like CPU load on the host.

(Also, we use UML's "time travel" feature which essentially fast-forwards through idle time, so the constraint can never be met in practice.)

So the timeout parameter would have to be made adjustable via say a module parameter, to be able to make it infinite (to test the normal case) and not (to be able to test timeout handling). I think this could be done fairly cleanly with a one- or two-liner patch to the driver and by hiding the details in a header file behind a roadtest-specific config option, but I wanted to avoid having to patch the kernel proper for the initial version of the framework.

For vcnl4000, I have actually inherited some out-of-tree patches which are in need of mainlining so the tests are a bit more complete since I'm hoping to send some patches to that driver soon. The period mode busy handling is not tested there either though, I can try to add that.

As for I2C API failures, I have not added tests for them in any of the drivers. There's not much the test cases could assert, other than perhaps error propagation, so it's unclear if there is enough value compared to the effort required to implement test cases to make sure that every I2C transaction's failure path is tested.

But I think that we do want to at least make sure the error paths are executed, to check that drivers don't crash or deadlock due to faulty cleanups and the like. A way to solve this could be to implement fault injection support in the I2C framework. The fail-nth feature could be used to systemically trigger each and every I2C transaction failure and check that the driver doesn't blow up, while using the roadtest as a means to hit the various code paths in the driver during each of the iterations of fail-nth. Fault injection support would also be helpful when testing on real hardware.

maintainer
#12 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 9 lines · Vincent Whitchurch

It should be possible, but upstream QEMU doesn't have everything that we need so some work is needed there. Also, of course work is need to provide user space for running the tests and communicating between the virtual machine and the backend:

- We need user space, so build scripts would need to be provided to cross-compile busybox and Python (and whatever libraries it needs) for the target architecture.

You could possibly use some nix recipes for all of this, but that's a fairly arcane thing (we use it, but ...)

Quoted 5 lines

- We also use UML's hostfs feature to make things transparent to the user and to avoid having to set up things like networking for communication between the host and the backend. I think QEMU's 9pfs support can be used as a rootfs too but it's not something I've personally tested.

That works just fine, yes. We used to do exactly this in the wireless test suite before we switched to UML, but the switch to UML was due to the "time-travel" feature.

https://w1.fi/cgit/hostap/tree/tests/hwsim/vm

has support for both UML and qemu/kvm.

Quoted 10 lines

- We use virtio-i2c and virtio-gpio and use virtio-uml which uses the vhost-user API to communicate from UML to the backend. The latest version of QEMU has support for vhost-user-i2c, but vhost-user-gpio doesn't seem to have been merged yet, so work is needed on the QEMU side. This will also be true for other buses in the future, if they are implemented with new virtio devices.

- For MMIO, UML has virtio-mmio which allows implementing any PCIe device (and by extension any platform device) outside of UML, but last I checked, upstream QEMU did not have something similar.

I think you have this a bit fuzzy.

The virtio_uml[.c] you speak of is the "bus" driver for virtio in UML. Obviously, qemu has support for virtio, so you don't need those bits.

Now, virtio_uml is actually the virtio (bus) driver inside the kernel, like you'd have virtio-mmio/virtio-pci in qemu. However, virtio_uml doesn't implement the devices in the hypervisor, where most qemu devices are implemented, but uses vhost-user to run the device implementation in a separate userspace. [1]

Now we're talking about vhost-user to talk to the device, and qemu supports this as well, in fact the vhost-user spec is part of qemu:
https://git.qemu.org/?p=qemu.git;a=blob;f=docs/system/devices/vhost-user.rst;h=86128114fa3788a73679f0af38e141021087c828;hb=1d60bb4b14601e38ed17384277aa4c30c57925d3
https://www.qemu.org/docs/master/interop/vhost-user.html

The docs on how to use it are here:
https://www.qemu.org/docs/master/system/devices/vhost-user.html

So once you have a device implementation (regardless of whether it's for use with any of the virtio-i2c, arch/um/drivers/virt-pci.c, virtio-gpio, virtio-net, ... drivers) you can actually connect it to virtual machines running as UML or in qemu.

(Actually, that's not strictly true today since it's arch/um/drivers/virt-pci.c and I didn't get a proper device ID assigned etc since it was for experimentation, I guess if we make this more commonly used then we should move it to drivers/pci/controller/virtio- pci.c and actually specify it in the OASIS virtio spec., at the very least it'd have to be possible to compile this and lib/logic_iomem.c on x86, but that's possible. Anyway I think PCI(e) is probably low on your list of things ...)

Quoted 8 lines

- Also, some paths in this driver needs a modification to be tested under roadtest. It uses wait_event_timeout() with a fixed value, but we cannot guarantee that this constraint is met in the test environment since it depends on things like CPU load on the host.

(Also, we use UML's "time travel" feature which essentially fast-forwards through idle time, so the constraint can never be met in practice.)

Wohoo! This makes me very happy, finally somebody else who uses it :-)

[1] As an aside, you might be interested in usfstl (which you can find at https://github.com/linux-test-project/usfstl) which is one way you could implement the device side - though the focus here is on making a device implementation easy while under "time-travel" mode.

If you ever want to use time-travel with multiple machines or actually with virtio devices, it also contains the necessary controller program to glue the entire simulation together. We use this very successfully to test the (real but compiled for x86) wifi firmware for iwlwifi together with the real driver actually seeing a PCIe device in UML, under time- travel :)

johannes

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#13 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 28 lines · Johannes Berg
Quoted 10 lines · Vincent Whitchurch

- We use virtio-i2c and virtio-gpio and use virtio-uml which uses the vhost-user API to communicate from UML to the backend. The latest version of QEMU has support for vhost-user-i2c, but vhost-user-gpio doesn't seem to have been merged yet, so work is needed on the QEMU side. This will also be true for other buses in the future, if they are implemented with new virtio devices.

- For MMIO, UML has virtio-mmio which allows implementing any PCIe device (and by extension any platform device) outside of UML, but last I checked, upstream QEMU did not have something similar.

I think you have this a bit fuzzy.

The virtio_uml[.c] you speak of is the "bus" driver for virtio in UML. Obviously, qemu has support for virtio, so you don't need those bits.

Now, virtio_uml is actually the virtio (bus) driver inside the kernel, like you'd have virtio-mmio/virtio-pci in qemu. However, virtio_uml doesn't implement the devices in the hypervisor, where most qemu devices are implemented, but uses vhost-user to run the device implementation in a separate userspace. [1]

Now we're talking about vhost-user to talk to the device, and qemu supports this as well, in fact the vhost-user spec is part of qemu:
https://git.qemu.org/?p=qemu.git;a=blob;f=docs/system/devices/vhost-user.rst;h=86128114fa3788a73679f0af38e141021087c828;hb=1d60bb4b14601e38ed17384277aa4c30c57925d3
https://www.qemu.org/docs/master/interop/vhost-user.html

Quoted 7 lines

The docs on how to use it are here:
https://www.qemu.org/docs/master/system/devices/vhost-user.html

So once you have a device implementation (regardless of whether it's for use with any of the virtio-i2c, arch/um/drivers/virt-pci.c, virtio-gpio, virtio-net, ... drivers) you can actually connect it to virtual machines running as UML or in qemu.

I'm aware of vhost-user, but AFAICS QEMU needs glue for each device type to be able to actually hook up vhost-user implementations to the devices it exposes to the guest via the virtio PCI device. See e.g. hw/virtio/vhost-user-i2c-pci.c and hw/virtio/vhost-user-i2c.c in QEMU.

That is what I meant was missing for virtio-gpio, there seems to be an in-progress patch set for that here though:
https://lore.kernel.org/all/[email protected]/

Similarly, glue for something like arch/um/drivers/virt-pci.c does not exist in QEMU.

Or perhaps you are implying that hw/virtio/vhost-user-i2c* in QEMU are not strictly needed?

Quoted 8 lines

(Actually, that's not strictly true today since it's arch/um/drivers/virt-pci.c and I didn't get a proper device ID assigned etc since it was for experimentation, I guess if we make this more commonly used then we should move it to drivers/pci/controller/virtio- pci.c and actually specify it in the OASIS virtio spec., at the very least it'd have to be possible to compile this and lib/logic_iomem.c on x86, but that's possible. Anyway I think PCI(e) is probably low on your list of things ...)

PCI is not that interesting, no, but platform devices are. I did some experiments early on with arch/um/drivers/virt-pci.c and a corresponding backend along with a simple PCI driver which probes all devicetree nodes under it, and I was able to use this to get some platform drivers working.

Quoted 11 lines
Quoted 9 lines

- Also, some paths in this driver needs a modification to be tested under roadtest. It uses wait_event_timeout() with a fixed value, but we cannot guarantee that this constraint is met in the test environment since it depends on things like CPU load on the host.

(Also, we use UML's "time travel" feature which essentially fast-forwards through idle time, so the constraint can never be met in practice.)

Wohoo! This makes me very happy, finally somebody else who uses it :-)

Yes, thanks for that feature, it works well to speed up tests and also has a knack for triggering race conditions (the RTC use-after-free for example).

Time travel however sometimes triggers some WARN_ONs from the core timekeeping code. I haven't seen them when running the test suites, but they show up if the system under UML is idle for several (wall time) seconds. I haven't had a chance to investigate it further though, but I can dig up the splats if you are interested.

maintainer
#14 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 5 lines · Vincent Whitchurch

I'm aware of vhost-user, but AFAICS QEMU needs glue for each device type to be able to actually hook up vhost-user implementations to the devices it exposes to the guest via the virtio PCI device. See e.g. hw/virtio/vhost-user-i2c-pci.c and hw/virtio/vhost-user-i2c.c in QEMU.

Oh, I wasn't aware of that.

Quoted 9 lines

That is what I meant was missing for virtio-gpio, there seems to be an in-progress patch set for that here though:
https://lore.kernel.org/all/[email protected]/

Similarly, glue for something like arch/um/drivers/virt-pci.c does not exist in QEMU.

Or perhaps you are implying that hw/virtio/vhost-user-i2c* in QEMU are not strictly needed?

I _thought_ that was the case, but honestly, that was just from reading about it, not looking at the code. Thinking about it though, I don't need special glue in UML, just passing the device ID on the command line? So not sure what they need the glue for. Looking at the code, it's not really much though? Not sure, I guess you need somebody more familiar with qemu here, sorry.

Quoted 11 lines
Quoted 1 line

Wohoo! This makes me very happy, finally somebody else who uses it :-)

Yes, thanks for that feature, it works well to speed up tests and also has a knack for triggering race conditions (the RTC use-after-free for example).

Time travel however sometimes triggers some WARN_ONs from the core timekeeping code. I haven't seen them when running the test suites, but they show up if the system under UML is idle for several (wall time) seconds. I haven't had a chance to investigate it further though, but I can dig up the splats if you are interested.

Oh, I haven't seen that, and I'm pretty sure I've had systems idle for very long periods of time passing inside (think weeks) ...

So yeah, if you have some splats (ideally with corresponding kernel configs), I'd be interested.

johannes

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

maintainer
#15 lore raw

Re: [RFC v1 07/10] iio: light: opt3001: add roadtest

Quoted 10 lines · Johannes Berg
Quoted 2 lines

Or perhaps you are implying that hw/virtio/vhost-user-i2c* in QEMU are not strictly needed?

I _thought_ that was the case, but honestly, that was just from reading about it, not looking at the code. Thinking about it though, I don't need special glue in UML, just passing the device ID on the command line? So not sure what they need the glue for. Looking at the code, it's not really much though? Not sure, I guess you need somebody more familiar with qemu here, sorry.

So here
https://www.qemu.org/docs/master/system/devices/vhost-user.html#vhost-user-device

the docs say:

These are simple stub devices that ensure the VirtIO device is visible to the guest. The code is mostly boilerplate although each device has a chardev option which specifies the ID of the --chardev device that connects via a socket to the vhost-user daemon.

So maybe if the ID were specified via the command line too, you could have a generic vhost-user stub in qemu?

johannes

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#16 lore raw

RFC 8/10 iio: light: vcnl4000: add roadtest

In reply to Vincent Whitchurch

Add roadtests for the vcnl4000 driver, testing several of the driver's features including buffer and event handling. Since it's the first IIO roadtest testing the non-sysfs parts, some support code for using the IIO ABI is included.

The different variants supported by the driver are in separate tests and models since no two variants have fully identical register interfaces. This duplicates some of the test code, but it:

- Avoids the tests duplicating the same multi-variant logic as the driver, reducing the risk for both the test and the driver being wrong.

- Allows each variant's test and model to be individually understood and modified looking at only one specific datasheet, making it easier to extend tests and implement new features in the driver.

During development of these tests, two oddities were noticed in the driver's handling of VCNL4040, but the tests simply assume that the current driver knows what it's doing (although we may want to fix the first point later):

- The driver reads an invalid/undefined register on the VCNL4040 when attempting to distinguish between that one and VCNL4200.

- The driver uses a lux/step unit which differs from the datasheet (but which is specified in an application note).

---
 .../roadtest/roadtest/tests/iio/iio.py        | 112 +++++++
 .../roadtest/roadtest/tests/iio/light/config  |   1 +
 .../roadtest/tests/iio/light/test_vcnl4000.py | 132 ++++++++
 .../roadtest/tests/iio/light/test_vcnl4010.py | 282 ++++++++++++++++++
 .../roadtest/tests/iio/light/test_vcnl4040.py | 104 +++++++
 .../roadtest/tests/iio/light/test_vcnl4200.py |  96 ++++++
 6 files changed, 727 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/iio.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py
tools/testing/roadtest/roadtest/tests/iio/iio.py new file +112 -0
new file mode 100644
index 000000000000..ea57b28ea9d3
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import contextlib
+import enum
+import fcntl
+import struct
+from dataclasses import dataclass, field
+from typing import Any
+
+IIO_GET_EVENT_FD_IOCTL = 0x80046990
+IIO_BUFFER_GET_FD_IOCTL = 0xC0046991
+
+
+class IIOChanType(enum.IntEnum):
+    IIO_VOLTAGE = 0
+    IIO_CURRENT = 1
+    IIO_POWER = 2
+    IIO_ACCEL = 3
+    IIO_ANGL_VEL = 4
+    IIO_MAGN = 5
+    IIO_LIGHT = 6
+    IIO_INTENSITY = 7
+    IIO_PROXIMITY = 8
+    IIO_TEMP = 9
+    IIO_INCLI = 10
+    IIO_ROT = 11
+    IIO_ANGL = 12
+    IIO_TIMESTAMP = 13
+    IIO_CAPACITANCE = 14
+    IIO_ALTVOLTAGE = 15
+    IIO_CCT = 16
+    IIO_PRESSURE = 17
+    IIO_HUMIDITYRELATIVE = 18
+    IIO_ACTIVITY = 19
+    IIO_STEPS = 20
+    IIO_ENERGY = 21
+    IIO_DISTANCE = 22
+    IIO_VELOCITY = 23
+    IIO_CONCENTRATION = 24
+    IIO_RESISTANCE = 25
+    IIO_PH = 26
+    IIO_UVINDEX = 27
+    IIO_ELECTRICALCONDUCTIVITY = 28
+    IIO_COUNT = 29
+    IIO_INDEX = 30
+    IIO_GRAVITY = 31
+    IIO_POSITIONRELATIVE = 32
+    IIO_PHASE = 33
+    IIO_MASSCONCENTRATION = 34
+
+
+@dataclass
+class IIOEvent:
+    id: int
+    timestamp: int
+    type: IIOChanType = field(init=False)
+
+    def __post_init__(self) -> None:
+        self.type = IIOChanType((self.id >> 32) & 0xFF)
+
+
+class IIOEventMonitor(contextlib.AbstractContextManager):
+    def __init__(self, devname: str) -> None:
+        self.devname = devname
+
+    def __enter__(self) -> "IIOEventMonitor":
+        self.file = open(self.devname, "rb")
+
+        s = struct.Struct("L")
+        buf = bytearray(s.size)
+        fcntl.ioctl(self.file.fileno(), IIO_GET_EVENT_FD_IOCTL, buf)
+        eventfd = s.unpack(buf)[0]
+        self.eventf = open(eventfd, "rb")
+
+        return self
+
+    def read(self) -> IIOEvent:
+        s = struct.Struct("Qq")
+        buf = self.eventf.read(s.size)
+        return IIOEvent(*s.unpack(buf))
+
+    def __exit__(self, *_: Any) -> None:
+        self.eventf.close()
+        self.file.close()
+
+
+class IIOBuffer(contextlib.AbstractContextManager):
+    def __init__(self, devname: str, bufidx: int) -> None:
+        self.devname = devname
+        self.bufidx = bufidx
+
+    def __enter__(self) -> "IIOBuffer":
+        self.file = open(self.devname, "rb")
+
+        s = struct.Struct("L")
+        buf = bytearray(s.size)
+        s.pack_into(buf, 0, self.bufidx)
+        fcntl.ioctl(self.file.fileno(), IIO_BUFFER_GET_FD_IOCTL, buf)
+        eventfd = s.unpack(buf)[0]
+        self.eventf = open(eventfd, "rb")
+
+        return self
+
+    def read(self, spec: str) -> tuple:
+        s = struct.Struct(spec)
+        buf = self.eventf.read(s.size)
+        return s.unpack(buf)
+
+    def __exit__(self, *_: Any) -> None:
+        self.eventf.close()
+        self.file.close()
tools/testing/roadtest/roadtest/tests/iio/light/config +1 -0
index b9753f2d0728..3bd4125cbb6b 100644
@@ -1 +1,2 @@
 CONFIG_OPT3001=m
+CONFIG_VCNL4000=m
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py new file +132 -0

132 lines not on this page · raw message

tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py new file +282 -0

282 lines not on this page · raw message

tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py new file +104 -0

104 lines not on this page · raw message

tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py new file +96 -0

96 lines not on this page · raw message

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
maintainer
#17 lore raw

Re: [RFC v1 08/10] iio: light: vcnl4000: add roadtest

Quoted 22 lines · On Fri, 11 Mar 2022 17:24:43 +0100 Vincent Whitchurch…

Add roadtests for the vcnl4000 driver, testing several of the driver's features including buffer and event handling. Since it's the first IIO roadtest testing the non-sysfs parts, some support code for using the IIO ABI is included.

The different variants supported by the driver are in separate tests and models since no two variants have fully identical register interfaces. This duplicates some of the test code, but it:

- Avoids the tests duplicating the same multi-variant logic as the driver, reducing the risk for both the test and the driver being wrong.

- Allows each variant's test and model to be individually understood and modified looking at only one specific datasheet, making it easier to extend tests and implement new features in the driver.

During development of these tests, two oddities were noticed in the driver's handling of VCNL4040, but the tests simply assume that the current driver knows what it's doing (although we may want to fix the first point later):

Quoted 7 lines

- The driver reads an invalid/undefined register on the VCNL4040 when attempting to distinguish between that one and VCNL4200.

- The driver uses a lux/step unit which differs from the datasheet (but which is specified in an application note).

Hi Vincent,

Very interesting bit of work. My current approach for similar testing is to write a qemu model for the hardware, but that currently requires carefully crafted tests. Most of the time I'm only doing that to verify refactoring of existing drivers.

One thing that makes me nervous here is the python element though as I've not written significant python in about 20 years. That is going to be a burden for kernel developers and maintainers... Nothing quite like badly written tests to make for a mess in the long run and I suspect my python for example would be very very badly written :) Cut and paste will of course get us a long way...

I dream of a world where every driver is testable by people with out hardware but I fear it may be a while yet. Hopefully this will get us a little closer!

I more or less follow what is going on here (good docs btw in the earlier patch definitely helped).

So far I'm thoroughly in favour of road test subject to actually being able to review the tests or getting sufficient support to do so. It's a 'how to scale it' question really...

Jonathan

Quoted 767 lines
---
 .../roadtest/roadtest/tests/iio/iio.py        | 112 +++++++
 .../roadtest/roadtest/tests/iio/light/config  |   1 +
 .../roadtest/tests/iio/light/test_vcnl4000.py | 132 ++++++++
 .../roadtest/tests/iio/light/test_vcnl4010.py | 282 ++++++++++++++++++
 .../roadtest/tests/iio/light/test_vcnl4040.py | 104 +++++++
 .../roadtest/tests/iio/light/test_vcnl4200.py |  96 ++++++
 6 files changed, 727 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/iio.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py
tools/testing/roadtest/roadtest/tests/iio/iio.py new file +112 -0
new file mode 100644
index 000000000000..ea57b28ea9d3
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import contextlib
+import enum
+import fcntl
+import struct
+from dataclasses import dataclass, field
+from typing import Any
+
+IIO_GET_EVENT_FD_IOCTL = 0x80046990
+IIO_BUFFER_GET_FD_IOCTL = 0xC0046991
+
+
+class IIOChanType(enum.IntEnum):
+    IIO_VOLTAGE = 0
+    IIO_CURRENT = 1
+    IIO_POWER = 2
+    IIO_ACCEL = 3
+    IIO_ANGL_VEL = 4
+    IIO_MAGN = 5
+    IIO_LIGHT = 6
+    IIO_INTENSITY = 7
+    IIO_PROXIMITY = 8
+    IIO_TEMP = 9
+    IIO_INCLI = 10
+    IIO_ROT = 11
+    IIO_ANGL = 12
+    IIO_TIMESTAMP = 13
+    IIO_CAPACITANCE = 14
+    IIO_ALTVOLTAGE = 15
+    IIO_CCT = 16
+    IIO_PRESSURE = 17
+    IIO_HUMIDITYRELATIVE = 18
+    IIO_ACTIVITY = 19
+    IIO_STEPS = 20
+    IIO_ENERGY = 21
+    IIO_DISTANCE = 22
+    IIO_VELOCITY = 23
+    IIO_CONCENTRATION = 24
+    IIO_RESISTANCE = 25
+    IIO_PH = 26
+    IIO_UVINDEX = 27
+    IIO_ELECTRICALCONDUCTIVITY = 28
+    IIO_COUNT = 29
+    IIO_INDEX = 30
+    IIO_GRAVITY = 31
+    IIO_POSITIONRELATIVE = 32
+    IIO_PHASE = 33
+    IIO_MASSCONCENTRATION = 34
+
+
+@dataclass
+class IIOEvent:
+    id: int
+    timestamp: int
+    type: IIOChanType = field(init=False)
+
+    def __post_init__(self) -> None:
+        self.type = IIOChanType((self.id >> 32) & 0xFF)
+
+
+class IIOEventMonitor(contextlib.AbstractContextManager):
+    def __init__(self, devname: str) -> None:
+        self.devname = devname
+
+    def __enter__(self) -> "IIOEventMonitor":
+        self.file = open(self.devname, "rb")
+
+        s = struct.Struct("L")
+        buf = bytearray(s.size)
+        fcntl.ioctl(self.file.fileno(), IIO_GET_EVENT_FD_IOCTL, buf)
+        eventfd = s.unpack(buf)[0]
+        self.eventf = open(eventfd, "rb")
+
+        return self
+
+    def read(self) -> IIOEvent:
+        s = struct.Struct("Qq")
+        buf = self.eventf.read(s.size)
+        return IIOEvent(*s.unpack(buf))
+
+    def __exit__(self, *_: Any) -> None:
+        self.eventf.close()
+        self.file.close()
+
+
+class IIOBuffer(contextlib.AbstractContextManager):
+    def __init__(self, devname: str, bufidx: int) -> None:
+        self.devname = devname
+        self.bufidx = bufidx
+
+    def __enter__(self) -> "IIOBuffer":
+        self.file = open(self.devname, "rb")
+
+        s = struct.Struct("L")
+        buf = bytearray(s.size)
+        s.pack_into(buf, 0, self.bufidx)
+        fcntl.ioctl(self.file.fileno(), IIO_BUFFER_GET_FD_IOCTL, buf)
+        eventfd = s.unpack(buf)[0]
+        self.eventf = open(eventfd, "rb")
+
+        return self
+
+    def read(self, spec: str) -> tuple:
+        s = struct.Struct(spec)
+        buf = self.eventf.read(s.size)
+        return s.unpack(buf)
+
+    def __exit__(self, *_: Any) -> None:
+        self.eventf.close()
+        self.file.close()
tools/testing/roadtest/roadtest/tests/iio/light/config +1 -0
index b9753f2d0728..3bd4125cbb6b 100644
@@ -1 +1,2 @@
 CONFIG_OPT3001=m
+CONFIG_VCNL4000=m
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py new file +132 -0
new file mode 100644
index 000000000000..16a5bed18b7e
@@ -0,0 +1,132 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import errno
+import logging
+from typing import Any, Final
+
+from roadtest.backend.i2c import SMBusModel
+from roadtest.core.devicetree import DtFragment, DtVar
+from roadtest.core.hardware import Hardware
+from roadtest.core.modules import insmod, rmmod
+from roadtest.core.suite import UMLTestCase
+from roadtest.core.sysfs import I2CDriver, read_float, read_int, read_str
+
+logger = logging.getLogger(__name__)
+
+REG_COMMAND: Final = 0x80
+REG_PRODUCT_ID_REVISION: Final = 0x81
+REG_IR_LED_CURRENT: Final = 0x83
+REG_ALS_PARAM: Final = 0x84
+REG_ALS_RESULT_HIGH: Final = 0x85
+REG_ALS_RESULT_LOW: Final = 0x86
+REG_PROX_RESULT_HIGH: Final = 0x87
+REG_PROX_RESULT_LOW: Final = 0x88
+REG_PROX_SIGNAL_FREQ: Final = 0x89
+
+REG_COMMAND_ALS_DATA_RDY: Final = 1 << 6
+REG_COMMAND_PROX_DATA_RDY: Final = 1 << 5
+
+
+class VCNL4000(SMBusModel):
+    def __init__(self, **kwargs: Any) -> None:
+        super().__init__(regbytes=1, **kwargs)
+        self.regs = {
+            REG_COMMAND: 0b_1000_0000,
+            REG_PRODUCT_ID_REVISION: 0x11,
+            # Register "without function in current version"
+            0x82: 0x00,
+            REG_IR_LED_CURRENT: 0x00,
+            REG_ALS_PARAM: 0x00,
+            REG_ALS_RESULT_HIGH: 0x00,
+            REG_ALS_RESULT_LOW: 0x00,
+            REG_PROX_RESULT_HIGH: 0x00,
+            REG_PROX_RESULT_LOW: 0x00,
+            REG_PROX_RESULT_LOW: 0x00,
+        }
+
+    def reg_read(self, addr: int) -> int:
+        val = self.regs[addr]
+
+        if addr in (REG_ALS_RESULT_HIGH, REG_ALS_RESULT_LOW):
+            self.regs[REG_COMMAND] &= ~REG_COMMAND_ALS_DATA_RDY
+        if addr in (REG_PROX_RESULT_HIGH, REG_PROX_RESULT_LOW):
+            self.regs[REG_COMMAND] &= ~REG_COMMAND_PROX_DATA_RDY
+
+        return val
+
+    def reg_write(self, addr: int, val: int) -> None:
+        assert addr in self.regs
+
+        if addr == REG_COMMAND:
+            rw = 0b_0001_1000
+            val = (self.regs[addr] & ~rw) | (val & rw)
+
+        self.regs[addr] = val
+
+    def inject(self, addr: int, val: int, mask: int = ~0) -> None:
+        old = self.regs[addr] & ~mask
+        new = old | (val & mask)
+        self.regs[addr] = new
+
+
+class TestVCNL4000(UMLTestCase):
+    dts = DtFragment(
+        src="""
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "vishay,vcnl4000";
+        reg = <0x$addr$>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("vcnl4000")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("vcnl4000")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("vcnl4000")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(VCNL4000)
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_lux(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            scale = read_float(dev.path / "iio:device0/in_illuminance_scale")
+            self.assertEqual(scale, 0.25)
+
+            data = [
+                (0x00, 0x00),
+                (0x12, 0x34),
+                (0xFF, 0xFF),
+            ]
+            luxfile = dev.path / "iio:device0/in_illuminance_raw"
+            for high, low in data:
+                self.hw.inject(REG_ALS_RESULT_HIGH, high)
+                self.hw.inject(REG_ALS_RESULT_LOW, low)
+                self.hw.inject(
+                    REG_COMMAND,
+                    val=REG_COMMAND_ALS_DATA_RDY,
+                    mask=REG_COMMAND_ALS_DATA_RDY,
+                )
+
+                self.assertEqual(read_int(luxfile), high << 8 | low)
+
+    def test_lux_timeout(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            # self.hw.set_never_ready(True)
+            with self.assertRaises(OSError) as cm:
+                luxfile = dev.path / "iio:device0/in_illuminance_raw"
+                read_str(luxfile)
+            self.assertEqual(cm.exception.errno, errno.EIO)
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py new file +282 -0
new file mode 100644
index 000000000000..929db970405f
@@ -0,0 +1,282 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import errno
+import logging
+from pathlib import Path
+from typing import Any, Final, Optional
+
+from roadtest.backend.i2c import SMBusModel
+from roadtest.core.devicetree import DtFragment, DtVar
+from roadtest.core.hardware import Hardware
+from roadtest.core.modules import insmod, rmmod
+from roadtest.core.suite import UMLTestCase
+from roadtest.core.sysfs import (
+    I2CDriver,
+    read_float,
+    read_int,
+    read_str,
+    write_int,
+    write_str,
+)
+from roadtest.tests.iio import iio
+
+logger = logging.getLogger(__name__)
+
+REG_COMMAND: Final = 0x80
+REG_PRODUCT_ID_REVISION: Final = 0x81
+REG_PROXIMITY_RATE: Final = 0x82
+REG_IR_LED_CURRENT: Final = 0x83
+REG_ALS_PARAM: Final = 0x84
+REG_ALS_RESULT_HIGH: Final = 0x85
+REG_ALS_RESULT_LOW: Final = 0x86
+REG_PROX_RESULT_HIGH: Final = 0x87
+REG_PROX_RESULT_LOW: Final = 0x88
+REG_INTERRUPT_CONTROL: Final = 0x89
+REG_LOW_THRESHOLD_HIGH: Final = 0x8A
+REG_LOW_THRESHOLD_LOW: Final = 0x8B
+REG_HIGH_THRESHOLD_HIGH: Final = 0x8C
+REG_HIGH_THRESHOLD_LOW: Final = 0x8D
+REG_INTERRUPT_STATUS: Final = 0x8E
+
+REG_COMMAND_ALS_DATA_RDY: Final = 1 << 6
+REG_COMMAND_PROX_DATA_RDY: Final = 1 << 5
+
+
+class VCNL4010(SMBusModel):
+    def __init__(self, int: Optional[int] = None, **kwargs: Any) -> None:
+        super().__init__(regbytes=1, **kwargs)
+        self.int = int
+        self._set_int(False)
+        self.regs = {
+            REG_COMMAND: 0b_1000_0000,
+            REG_PRODUCT_ID_REVISION: 0x21,
+            REG_PROXIMITY_RATE: 0x00,
+            REG_IR_LED_CURRENT: 0x00,
+            REG_ALS_PARAM: 0x00,
+            REG_ALS_RESULT_HIGH: 0x00,
+            REG_ALS_RESULT_LOW: 0x00,
+            REG_PROX_RESULT_HIGH: 0x00,
+            REG_PROX_RESULT_LOW: 0x00,
+            REG_INTERRUPT_CONTROL: 0x00,
+            REG_LOW_THRESHOLD_HIGH: 0x00,
+            REG_LOW_THRESHOLD_LOW: 0x00,
+            REG_HIGH_THRESHOLD_HIGH: 0x00,
+            REG_HIGH_THRESHOLD_LOW: 0x00,
+            REG_INTERRUPT_STATUS: 0x00,
+        }
+
+    def _set_int(self, active: int) -> None:
+        # Active-low
+        self.backend.gpio.set(self.int, not active)
+
+    def _update_irq(self) -> None:
+        selftimed_en = self.regs[REG_COMMAND] & (1 << 0)
+        prox_en = self.regs[REG_COMMAND] & (1 << 1)
+        prox_data_rdy = self.regs[REG_COMMAND] & REG_COMMAND_PROX_DATA_RDY
+        int_prox_ready_en = self.regs[REG_INTERRUPT_CONTROL] & (1 << 3)
+
+        logger.debug(
+            f"{selftimed_en=:x} {prox_en=:x} {prox_data_rdy=:x} {int_prox_ready_en=:x}"
+        )
+
+        if selftimed_en and prox_en and prox_data_rdy and int_prox_ready_en:
+            self.regs[REG_INTERRUPT_STATUS] |= 1 << 3
+
+        low_threshold = (
+            self.regs[REG_LOW_THRESHOLD_HIGH] << 8 | self.regs[REG_LOW_THRESHOLD_LOW]
+        )
+        high_threshold = (
+            self.regs[REG_HIGH_THRESHOLD_HIGH] << 8 | self.regs[REG_HIGH_THRESHOLD_LOW]
+        )
+        proximity = (
+            self.regs[REG_PROX_RESULT_HIGH] << 8 | self.regs[REG_PROX_RESULT_LOW]
+        )
+        int_thres_en = self.regs[REG_INTERRUPT_CONTROL] & (1 << 1)
+
+        logger.debug(
+            f"{low_threshold=:x} {high_threshold=:x} {proximity=:x} {int_thres_en=:x}"
+        )
+
+        if int_thres_en:
+            if proximity < low_threshold:
+                logger.debug("LOW")
+                self.regs[REG_INTERRUPT_STATUS] |= 1 << 1
+            if proximity > high_threshold:
+                logger.debug("HIGH")
+                self.regs[REG_INTERRUPT_STATUS] |= 1 << 0
+
+        self._set_int(self.regs[REG_INTERRUPT_STATUS])
+
+    def reg_read(self, addr: int) -> int:
+        val = self.regs[addr]
+
+        if addr in (REG_ALS_RESULT_HIGH, REG_ALS_RESULT_LOW):
+            self.regs[REG_COMMAND] &= ~REG_COMMAND_ALS_DATA_RDY
+        if addr in (REG_PROX_RESULT_HIGH, REG_PROX_RESULT_LOW):
+            self.regs[REG_COMMAND] &= ~REG_COMMAND_PROX_DATA_RDY
+
+        return val
+
+    def reg_write(self, addr: int, val: int) -> None:
+        assert addr in self.regs
+
+        if addr == REG_COMMAND:
+            rw = 0b_0001_1111
+            val = (self.regs[addr] & ~rw) | (val & rw)
+        elif addr == REG_INTERRUPT_STATUS:
+            val = self.regs[addr] & ~(val & 0xF)
+
+        self.regs[addr] = val
+        self._update_irq()
+
+    def inject(self, addr: int, val: int, mask: int = ~0) -> None:
+        old = self.regs[addr] & ~mask
+        new = old | (val & mask)
+        self.regs[addr] = new
+        self._update_irq()
+
+    def set_bit(self, addr: int, val: int) -> None:
+        self.inject(addr, val, val)
+
+
+class TestVCNL4010(UMLTestCase):
+    dts = DtFragment(
+        src="""
+#include <dt-bindings/interrupt-controller/irq.h>
+
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "vishay,vcnl4020";
+        reg = <0x$addr$>;
+        interrupt-parent = <&gpio>;
+        interrupts = <$gpio$ IRQ_TYPE_EDGE_FALLING>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+            "gpio": DtVar.GPIO_PIN,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("vcnl4000")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("vcnl4000")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("vcnl4000")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(VCNL4010, int=self.dts["gpio"])
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_lux(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+
+            scale = read_float(dev.path / "iio:device0/in_illuminance_scale")
+            self.assertEqual(scale, 0.25)
+
+            data = [
+                (0x00, 0x00),
+                (0x12, 0x34),
+                (0xFF, 0xFF),
+            ]
+            luxfile = dev.path / "iio:device0/in_illuminance_raw"
+            for high, low in data:
+                self.hw.inject(REG_ALS_RESULT_HIGH, high)
+                self.hw.inject(REG_ALS_RESULT_LOW, low)
+                self.hw.set_bit(REG_COMMAND, REG_COMMAND_ALS_DATA_RDY)
+
+                self.assertEqual(read_int(luxfile), high << 8 | low)
+
+    def test_lux_timeout(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            with self.assertRaises(OSError) as cm:
+                luxfile = dev.path / "iio:device0/in_illuminance_raw"
+                read_str(luxfile)
+            self.assertEqual(cm.exception.errno, errno.EIO)
+
+    def test_proximity_thresh_rising(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            high_thresh = (
+                dev.path / "iio:device0/events/in_proximity_thresh_rising_value"
+            )
+            write_int(high_thresh, 0x1234)
+
+            mock = self.hw.update_mock()
+            mock.assert_last_reg_write(self, REG_HIGH_THRESHOLD_HIGH, 0x12)
+            mock.assert_last_reg_write(self, REG_HIGH_THRESHOLD_LOW, 0x34)
+            mock.reset_mock()
+
+            self.assertEqual(read_int(high_thresh), 0x1234)
+
+            with iio.IIOEventMonitor("/dev/iio:device0") as mon:
+                en = dev.path / "iio:device0/events/in_proximity_thresh_either_en"
+                write_int(en, 1)
+
+                self.hw.inject(REG_PROX_RESULT_HIGH, 0x12)
+                self.hw.inject(REG_PROX_RESULT_LOW, 0x35)
+                self.hw.set_bit(REG_COMMAND, REG_COMMAND_PROX_DATA_RDY)
+                self.hw.kick()
+
+                self.assertEqual(read_int(en), 1)
+
+                event = mon.read()
+                self.assertEqual(event.type, iio.IIOChanType.IIO_PROXIMITY)
+
+    def test_proximity_thresh_falling(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            high_thresh = (
+                dev.path / "iio:device0/events/in_proximity_thresh_falling_value"
+            )
+            write_int(high_thresh, 0x0ABC)
+
+            mock = self.hw.update_mock()
+            mock.assert_last_reg_write(self, REG_LOW_THRESHOLD_HIGH, 0x0A)
+            mock.assert_last_reg_write(self, REG_LOW_THRESHOLD_LOW, 0xBC)
+            mock.reset_mock()
+
+            self.assertEqual(read_int(high_thresh), 0x0ABC)
+
+            with iio.IIOEventMonitor("/dev/iio:device0") as mon:
+                write_int(
+                    dev.path / "iio:device0/events/in_proximity_thresh_either_en", 1
+                )
+
+                event = mon.read()
+                self.assertEqual(event.type, iio.IIOChanType.IIO_PROXIMITY)
+
+    def test_proximity_triggered(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            data = [
+                (0x00, 0x00, 0),
+                (0x00, 0x01, 1),
+                (0xF0, 0x02, 0xF002),
+                (0xFF, 0xFF, 0xFFFF),
+            ]
+
+            trigger = read_str(Path("/sys/bus/iio/devices/trigger0/name"))
+
+            write_int(dev.path / "iio:device0/buffer0/in_proximity_en", 1)
+            write_str(dev.path / "iio:device0/trigger/current_trigger", trigger)
+
+            with iio.IIOBuffer("/dev/iio:device0", bufidx=0) as buffer:
+                write_int(dev.path / "iio:device0/buffer0/length", 128)
+                write_int(dev.path / "iio:device0/buffer0/enable", 1)
+
+                for low, high, expected in data:
+                    self.hw.inject(REG_PROX_RESULT_HIGH, low)
+                    self.hw.inject(REG_PROX_RESULT_LOW, high)
+                    self.hw.set_bit(REG_COMMAND, REG_COMMAND_PROX_DATA_RDY)
+                    self.hw.kick()
+
+                    scanline = buffer.read("H")
+
+                    val = scanline[0]
+                    self.assertEqual(val, expected)
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py new file +104 -0
new file mode 100644
index 000000000000..f2aa2cb9f3d5
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import logging
+from typing import Any
+
+from roadtest.backend.i2c import SMBusModel
+from roadtest.core.devicetree import DtFragment, DtVar
+from roadtest.core.hardware import Hardware
+from roadtest.core.modules import insmod, rmmod
+from roadtest.core.suite import UMLTestCase
+from roadtest.core.sysfs import I2CDriver, read_float, read_int
+
+logger = logging.getLogger(__name__)
+
+
+class VCNL4040(SMBusModel):
+    def __init__(self, **kwargs: Any) -> None:
+        super().__init__(regbytes=2, byteorder="little", **kwargs)
+        self.regs = {
+            0x00: 0x0101,
+            0x01: 0x0000,
+            0x02: 0x0000,
+            0x03: 0x0001,
+            0x04: 0x0000,
+            0x05: 0x0000,
+            0x06: 0x0000,
+            0x07: 0x0000,
+            0x08: 0x0000,
+            0x09: 0x0000,
+            0x0A: 0x0000,
+            0x0A: 0x0000,
+            0x0B: 0x0000,
+            0x0C: 0x0186,
+            # The driver reads this register which is undefined for
+            # VCNL4040.  Perhaps the driver should be fixed instead
+            # of having this here?
+            0x0E: 0x0000,
+        }
+
+    def reg_read(self, addr: int) -> int:
+        return self.regs[addr]
+
+    def reg_write(self, addr: int, val: int) -> None:
+        assert addr in self.regs
+        self.regs[addr] = val
+
+
+class TestVCNL4040(UMLTestCase):
+    dts = DtFragment(
+        src="""
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "vishay,vcnl4040";
+        reg = <0x$addr$>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("vcnl4000")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("vcnl4000")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("vcnl4000")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(VCNL4040)
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_illuminance_scale(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            scalefile = dev.path / "iio:device0/in_illuminance_scale"
+            # The datasheet says 0.10 lux/step, but the driver follows
+            # the application note "Designing the VCNL4040 Into an
+            # Application" which claims a different value.
+            self.assertEqual(read_float(scalefile), 0.12)
+
+    def test_illuminance(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            luxfile = dev.path / "iio:device0/in_illuminance_raw"
+
+            data = [0x0000, 0x1234, 0xFFFF]
+            for regval in data:
+                self.hw.reg_write(0x09, regval)
+                self.assertEqual(read_int(luxfile), regval)
+
+    def test_proximity(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            rawfile = dev.path / "iio:device0/in_proximity_raw"
+
+            data = [0x0000, 0x1234, 0xFFFF]
+            for regval in data:
+                self.hw.reg_write(0x08, regval)
+                self.assertEqual(read_int(rawfile), regval)
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py new file +86 -0
new file mode 100644
index 000000000000..d1cf819e563e
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Copyright Axis Communications AB
+
+import logging
+from typing import Any
+
+from roadtest.backend.i2c import SMBusModel
+from roadtest.core.devicetree import DtFragment, DtVar
+from roadtest.core.hardware import Hardware
+from roadtest.core.modules import insmod, rmmod
+from roadtest.core.suite import UMLTestCase
+from roadtest.core.sysfs import I2CDriver, read_float, read_int
+
+logger = logging.getLogger(__name__)
+
+
+class VCNL4200(SMBusModel):
+    def __init__(self, **kwargs: Any) -> None:
+        super().__init__(regbytes=2, byteorder="little", **kwargs)
+        self.regs = {
+            0x00: 0x0101,
+            0x01: 0x0000,
+            0x02: 0x0000,
+            0x03: 0x0001,
+            0x04: 0x0000,
+            0x05: 0x0000,
+            0x06: 0x0000,
+            0x07: 0x0000,
+            0x08: 0x0000,
+            0x09: 0x0000,
+            0x0A: 0x0000,
+            0x0D: 0x0000,
+            0x0E: 0x1058,
+        }
+
+    def reg_read(self, addr: int) -> int:
+        return self.regs[addr]
+
+    def reg_write(self, addr: int, val: int) -> None:
+        assert addr in self.regs
+        self.regs[addr] = val
+
+
+class TestVCNL4200(UMLTestCase):
+    dts = DtFragment(
+        src="""
+&i2c {
+    light-sensor@$addr$ {
+        compatible = "vishay,vcnl4200";
+        reg = <0x$addr$>;
+    };
+};
+        """,
+        variables={
+            "addr": DtVar.I2C_ADDR,
+        },
+    )
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("vcnl4000")
+
+    @classmethod
+    def tearDownClass(cls) -> None:
+        rmmod("vcnl4000")
+
+    def setUp(self) -> None:
+        self.driver = I2CDriver("vcnl4000")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(VCNL4200)
+
+    def tearDown(self) -> None:
+        self.hw.close()
+
+    def test_illuminance_scale(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            scalefile = dev.path / "iio:device0/in_illuminance_scale"
+            self.assertEqual(read_float(scalefile), 0.024)
+
+    def test_illuminance(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            luxfile = dev.path / "iio:device0/in_illuminance_raw"
+
+            data = [0x0000, 0x1234, 0xFFFF]
+            for regval in data:
+                self.hw.reg_write(0x09, regval)

tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py line 96

Quoted 10 lines
tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py new file +10 -0
+                self.assertEqual(read_int(luxfile), regval)
+
+    def test_proximity(self) -> None:
+        with self.driver.bind(self.dts["addr"]) as dev:
+            rawfile = dev.path / "iio:device0/in_proximity_raw"
+
+            data = [0x0000, 0x1234, 0xFFFF]
+            for regval in data:
+                self.hw.reg_write(0x08, regval)
+                self.assertEqual(read_int(rawfile), regval)

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#18 lore raw

Re: [RFC v1 08/10] iio: light: vcnl4000: add roadtest

Quoted 4 lines · Jonathan Cameron

Very interesting bit of work. My current approach for similar testing is to write a qemu model for the hardware, but that currently requires carefully crafted tests. Most of the time I'm only doing that to verify refactoring of existing drivers.

Thank you for taking a look!

Quoted 5 lines

One thing that makes me nervous here is the python element though as I've not written significant python in about 20 years. That is going to be a burden for kernel developers and maintainers... Nothing quite like badly written tests to make for a mess in the long run and I suspect my python for example would be very very badly written :)

There's a bunch of static checkers to ensure that the code follows some basic guidelines, and CI can check that the tests work consistently, and also calculate metrics such as test execution time and code coverage, so even non-idiomatic Python in the tests wouldn't be entirely broken.

And unlike driver code, if the tests for a particular driver later do turn out to be bad (in what way?), we could just throw those particular tests out without breaking anybody's system.

Quoted 1 line

Cut and paste will of course get us a long way...

Isn't some amount of copy/paste followed by modification to be expected even if the framework is written in say C (just as there's already copy/paste + modification involved when writing drivers)?

As for the core logic of individual driver tests excluding the framework bits, I have a hard time imagining what Python syntax looks like to someone with no knowledge of Python, so yes, I guess it's going to be harder to review.

Quoted 10 lines

I dream of a world where every driver is testable by people with out hardware but I fear it may be a while yet. Hopefully this will get us a little closer!

I more or less follow what is going on here (good docs btw in the earlier patch definitely helped).

So far I'm thoroughly in favour of road test subject to actually being able to review the tests or getting sufficient support to do so. It's a 'how to scale it' question really...

Would rewriting the framework in C and forcing tests to be written in that language mean that maintainers would be able to review tests without external support?

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#19 lore raw

Re: [RFC v1 08/10] iio: light: vcnl4000: add roadtest

Quoted 14 lines · On Tue, 5 Apr 2022 15:48:05 +0200 Vincent Whitchurch…
Quoted 4 lines · Jonathan Cameron

Very interesting bit of work. My current approach for similar testing is to write a qemu model for the hardware, but that currently requires carefully crafted tests. Most of the time I'm only doing that to verify refactoring of existing drivers.

Thank you for taking a look!

Quoted 5 lines

One thing that makes me nervous here is the python element though as I've not written significant python in about 20 years. That is going to be a burden for kernel developers and maintainers... Nothing quite like badly written tests to make for a mess in the long run and I suspect my python for example would be very very badly written :)

Quoted 8 lines

There's a bunch of static checkers to ensure that the code follows some basic guidelines, and CI can check that the tests work consistently, and also calculate metrics such as test execution time and code coverage, so even non-idiomatic Python in the tests wouldn't be entirely broken.

And unlike driver code, if the tests for a particular driver later do turn out to be bad (in what way?), we could just throw those particular tests out without breaking anybody's system.

True. Though CI test triage folk may disagree ;)

Quoted 11 lines
Quoted 2 lines

Cut and paste will of course get us a long way...

Isn't some amount of copy/paste followed by modification to be expected even if the framework is written in say C (just as there's already copy/paste + modification involved when writing drivers)?

As for the core logic of individual driver tests excluding the framework bits, I have a hard time imagining what Python syntax looks like to someone with no knowledge of Python, so yes, I guess it's going to be harder to review.

I messed around the other day with writing tests for drivers/staging/iio/cdc/ad7746.c and wasn't "too bad" and was useful for verifying some refactoring (and identified a possible precision problem in some integer approximation of floating point calcs)
I'll try and find time to flesh that test set out more in the near future and post it so you can see how bad my python is. It amused my wife if nothing else :)

However a future project is to see if I can use this to hook up the SPDM attestation stack via mctp over i2c - just because I like to live dangerously :)

For IIO use more generally we need a sensible path to SPI (and also platform drivers). For my day job I'd like to mess around with doing PCI devices as well. The PCI DOE support for example would be nice to run against a test set that doesn't involve spinning up QEMU.
DOE driver support:
https://lore.kernel.org/all/[email protected]/

Effort wise, it's similar effort to hacking equivalent in QEMU but with the obvious advantage of being in tree and simpler for CI systems etc to use.

It would be nice to only have to use QEMU for complex system CI tests like the ones we are doing for CXL.

Quoted 8 lines
Quoted 8 lines

I dream of a world where every driver is testable by people with out hardware but I fear it may be a while yet. Hopefully this will get us a little closer!

I more or less follow what is going on here (good docs btw in the earlier patch definitely helped).

Quoted 7 lines
Quoted 3 lines

So far I'm thoroughly in favour of road test subject to actually being able to review the tests or getting sufficient support to do so. It's a 'how to scale it' question really...

Would rewriting the framework in C and forcing tests to be written in that language mean that maintainers would be able to review tests without external support?

I was wondering that. If we stayed in python I think we'd definitely want someone to be the 'roadtester/tests' maintainer (or group of maintainers) and their Ack to be expected for all tests we upstream. Idea being they'd sanity check correct use of framework and just how bad the python code us C developers are writing is ;)

However, we'd still need a good chunk of that 'framework' use review even if doing this in C.

Anyhow, very promising bit of work.

Thanks,

Jonathan

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#20 lore raw

Re: [RFC v1 08/10] iio: light: vcnl4000: add roadtest

Quoted 6 lines · Jonathan Cameron

On Tue, 5 Apr 2022 15:48:05 +0200
Vincent Whitchurch <[email protected]> wrote:
I messed around the other day with writing tests for drivers/staging/iio/cdc/ad7746.c and wasn't "too bad" and was useful for verifying some refactoring (and identified a possible precision problem in some integer approximation of floating point calcs)

Good to hear!

Quoted 9 lines

I'll try and find time to flesh that test set out more in the near future and post it so you can see how bad my python is. It amused my wife if nothing else :)

However a future project is to see if I can use this to hook up the SPDM attestation stack via mctp over i2c - just because I like to live dangerously :)

For IIO use more generally we need a sensible path to SPI (and also platform drivers).

I have SPI working now. I was able to do this without patching the kernel by have the Python code emulate an SC18IS602 I2C-SPI bridge which has an existing driver. There is a limitation of 200 bytes per transaction (in the SC18IS602 driver/chip) so not all SPI drivers will work, but many will, and the underlying backend can be changed later without having to change the test cases. I used this to implement a test for drivers/iio/adc/ti-adc084s021.c.

Platform devices are going to take more work. I did do some experiments (using arch/um/drivers/virt-pci.c) a while ago but I need to see how well it works with the rest of the framework in place.

Quoted 28 lines

For my day job I'd like to mess around with doing PCI devices as well. The PCI DOE support for example would be nice to run against a test set that doesn't involve spinning up QEMU.
DOE driver support:
https://lore.kernel.org/all/[email protected]/

Effort wise, it's similar effort to hacking equivalent in QEMU but with the obvious advantage of being in tree and simpler for CI systems etc to use.

It would be nice to only have to use QEMU for complex system CI tests like the ones we are doing for CXL.

Quoted 8 lines
Quoted 8 lines

I dream of a world where every driver is testable by people with out hardware but I fear it may be a while yet. Hopefully this will get us a little closer!

I more or less follow what is going on here (good docs btw in the earlier patch definitely helped).

Quoted 7 lines
Quoted 3 lines

So far I'm thoroughly in favour of road test subject to actually being able to review the tests or getting sufficient support to do so. It's a 'how to scale it' question really...

Would rewriting the framework in C and forcing tests to be written in that language mean that maintainers would be able to review tests without external support?

Quoted 8 lines

I was wondering that. If we stayed in python I think we'd definitely want someone to be the 'roadtester/tests' maintainer (or group of maintainers) and their Ack to be expected for all tests we upstream. Idea being they'd sanity check correct use of framework and just how bad the python code us C developers are writing is ;)

However, we'd still need a good chunk of that 'framework' use review even if doing this in C.

I think this is reasonable, especially for the first tests for each subsystem where there will likely be support code and framework bits missing.

#21 lore raw

RFC 9/10 regulator: tps62864: add roadtest

In reply to Vincent Whitchurch

Add a roadtest for the recently-added tps62864 regulator driver. It tests voltage setting, mode setting, as well as devicetree mode translation. It uses the recently-added devicetree support in regulator-virtual-consumer.

All the variants supported by the driver have identical register interfaces so only one test/model is added.

It requires the following patches which are, as of writing, not in mainline:

- regulator: Add support for TPS6286x
https://lore.kernel.org/lkml/[email protected]/

- regulator: virtual: add devicetree support
https://lore.kernel.org/lkml/[email protected]/

---
 .../roadtest/tests/regulator/__init__.py      |   0
 .../roadtest/roadtest/tests/regulator/config  |   4 +
 .../roadtest/tests/regulator/test_tps62864.py | 187 ++++++++++++++++++
 3 files changed, 191 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py
tools/testing/roadtest/roadtest/tests/regulator/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/regulator/config new file +4 -0
new file mode 100644
index 000000000000..b2b503947e70
@@ -0,0 +1,4 @@
+CONFIG_REGULATOR=y
+CONFIG_REGULATOR_DEBUG=y
+CONFIG_REGULATOR_VIRTUAL_CONSUMER=y
+CONFIG_REGULATOR_TPS6286X=m
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +187 -0

187 lines not on this page · raw message

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#22 lore raw

Re: [RFC v1 09/10] regulator: tps62864: add roadtest

On Fri, Mar 11, 2022 at 05:24:44PM +0100, Vincent Whitchurch wrote:

This looks like it could be useful, modulo the general concerns with mocking stuff. I've not looked at the broader framework stuff in any meanigful way.

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 96

Quoted 3 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +3 -0
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("tps6286x-regulator")

Shouldn't this get figured out when the device gets created in DT (if it doesn't I guess the tests found a bug...)?

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 105

Quoted 4 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +4 -0
+    def setUp(self) -> None:
+        self.driver = I2CDriver("tps6286x")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(TPS62864)

This feels like there could be some syntactic sugar to say "create this I2C device" in one call? In general a lot of the frameworkish stuff feels verbose.

Quoted 7 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +7 -0
+    def test_voltage(self) -> None:
+        with (
+            self.driver.bind(self.dts["normal"]),
+            PlatformDriver("reg-virt-consumer").bind(
+                "tps62864_normal_consumer"
+            ) as consumerdev,
+        ):

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 126

Quoted 10 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +10 -0
+            maxfile = consumerdev.path / "max_microvolts"
+            minfile = consumerdev.path / "min_microvolts"
+
+            write_int(maxfile, 1675000)
+            write_int(minfile, 800000)
+
+            mock = self.hw.update_mock()
+            mock.assert_reg_write_once(self, REG_CONTROL, 1 << 5)
+            mock.assert_reg_write_once(self, REG_VOUT1, 0x50)
+            mock.reset_mock()

Some comments about the assertations here would seem to be in order. It's not altogether clear what this is testing - it looks to be verifying that the regulator is enabled with the voltage set to 800mV mapping to 0x50 in VOUT1 but I'm not sure that the idle reader would pick that up.

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 139

Quoted 12 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +12 -0
+            mV = 1000
+            data = [
+                (400 * mV, 0x00),
+                (900 * mV, 0x64),
+                (1675 * mV, 0xFF),
+            ]
+
+            for voltage, val in data:
+                write_int(minfile, voltage)
+                mock = self.hw.update_mock()
+                mock.assert_reg_write_once(self, REG_VOUT1, val)
+                mock.reset_mock()

For covering regulators in general (especially those like this that use the generic helpers) I'd be inclined to go through every single voltage that can be set which isn't so interesting for this driver with it's linear voltage control but more interesting for something that's not continuous. I'd also put a cross check in that the voltage and enable state that's reported via the read interface in sysfs is the one that we think we've just set, that'd validate that the framework's model of what's going on matches both what the driver did to the "hardware" and what the running kernel thinks is going on so we're joined up top to bottom (for the regulator framework the read values come from the driver so it is actually covering the driver).

This all feels like it could readily be factored out into a generic helper, much as the actual drivers are especially when they're more data driven. Ideally with the ability to override the default I/O operations for things with sequences that need to be followed instead of just a bitfield to update. Callbacks to validate enable state, voltage, mode and so on in the hardware. If we did that then rather than open coding every single test for every single device we could approach things at the framework level and give people working on a given device a pile of off the shelf tests which are more likely to catch things that an individual driver author might've missed, it also avoids the test coverage being more laborious than writing the actual driver.

This does raise the questions I mentioned about how useful the testing really is of course, even more so when someone works out how to generate the data tables for the test and the driver from the same source, but that's just generally an issue for mocked tests at the conceptual level and clearly it's an approach that's fairly widely used and people get value from.

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#23 lore raw

Re: [RFC v1 09/10] regulator: tps62864: add roadtest

Quoted 4 lines · Mark Brown

On Fri, Mar 11, 2022 at 05:24:44PM +0100, Vincent Whitchurch wrote:
This looks like it could be useful, modulo the general concerns with mocking stuff. I've not looked at the broader framework stuff in any meanigful way.

Thank you for having a look!

Here's a bit of background story about how I used this particular test, which hopefully shows an example of where I've seen the benefits of mocking hardware:

When I wrote this tps6286x driver a while ago, I tested it as one usually does, checking with i2cdump that the correct register values are written, measuring the voltages with a multimeter, rising and repeating with different devicetree properties, and so on. (This framework didn't exist at that point.)

Later, when preparing the driver for mainline submission, I wanted a quick way to check that any changes or cleanups that I needed to do during that process didn't invalidate all my and others' earlier testing. The easiest way to do that was to ensure that the driver continued to write the same bits in the same registers when given the same set of inputs and devicetree properties, and that is where I found the mocking to be useful.

In this case where there is no external input, the testing could of course have all been done manually with the real hardware, but there was little reason to do so when the hardware was the one factor which had not changed. The abilitly to create multiple devices with different devicetree properties (such as fast mode on/off) was a real time-saver too.

Quoted 6 lines

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 96

Quoted 3 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +3 -0
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("tps6286x-regulator")

Shouldn't this get figured out when the device gets created in DT (if it doesn't I guess the tests found a bug...)?

The system isn't set up to load modules automatically. The reason for this is to give the test cases full control of when the module is loaded and unload, since the tests could want to load the module with specific options.

Also, the framework splits up logs and shows errors that occurs during each specific test if the tests fail, and this would become less useful if all modules for all the devices in the devicetree get loaded on startup when the devicetree is parsed and one of the modules failed to load or crashed when loaded.

Quoted 9 lines

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 105

Quoted 5 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +4 -0
+    def setUp(self) -> None:
+        self.driver = I2CDriver("tps6286x")
+        self.hw = Hardware("i2c")
+        self.hw.load_model(TPS62864)

This feels like there could be some syntactic sugar to say "create this I2C device" in one call? In general a lot of the frameworkish stuff feels verbose.

Yes, I agree this could be simplified. I think the update_mock/reset_mock dance could also potentially be simplified with a with statement.

Beyond that, yes, there is some boilerplate setup for each test to bind the devices. This can differ between drivers and subsystems so I'm not sure how much could be shared, but I guess some of them could be separated out into a internal function for this particular test.

Quoted 15 lines
Quoted 15 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +15 -0
+    def test_voltage(self) -> None:
+        with (
+            self.driver.bind(self.dts["normal"]),
+            PlatformDriver("reg-virt-consumer").bind(
+                "tps62864_normal_consumer"
+            ) as consumerdev,
+        ):
+            maxfile = consumerdev.path / "max_microvolts"
+            minfile = consumerdev.path / "min_microvolts"
+
+            write_int(maxfile, 1675000)
+            write_int(minfile, 800000)
+
+            mock = self.hw.update_mock()
+            mock.assert_reg_write_once(self, REG_CONTROL, 1 << 5)
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+            mock.assert_reg_write_once(self, REG_VOUT1, 0x50)
+            mock.reset_mock()

Some comments about the assertations here would seem to be in order. It's not altogether clear what this is testing - it looks to be verifying that the regulator is enabled with the voltage set to 800mV mapping to 0x50 in VOUT1 but I'm not sure that the idle reader would pick that up.

Yes, I will add some comments. I also made some of the bit fields use constants in some of the other driver, that could be done here too.

Quoted 14 lines

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 139

Quoted 13 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +12 -0
+            mV = 1000
+            data = [
+                (400 * mV, 0x00),
+                (900 * mV, 0x64),
+                (1675 * mV, 0xFF),
+            ]
+
+            for voltage, val in data:
+                write_int(minfile, voltage)
+                mock = self.hw.update_mock()
+                mock.assert_reg_write_once(self, REG_VOUT1, val)
+                mock.reset_mock()
Quoted 5 lines

For covering regulators in general (especially those like this that use the generic helpers) I'd be inclined to go through every single voltage that can be set which isn't so interesting for this driver with it's linear voltage control but more interesting for something that's not continuous.

That could be useful in some cases, but if going through all the voltages in a loop requires that the test implement the exact same voltage-to-bitfield conversion function as the driver, then the benefit of that part of the test is unclear. That's the reason why for example the OPT3001 test uses known values from the datasheet rather than just copying the conversion function in the driver to Python.

Quoted 7 lines

I'd also put a cross check in that the voltage and enable state that's reported via the read interface in sysfs is the one that we think we've just set, that'd validate that the framework's model of what's going on matches both what the driver did to the "hardware" and what the running kernel thinks is going on so we're joined up top to bottom (for the regulator framework the read values come from the driver so it is actually covering the driver).

Makes sense, I can add that.

Quoted 11 lines

This all feels like it could readily be factored out into a generic helper, much as the actual drivers are especially when they're more data driven. Ideally with the ability to override the default I/O operations for things with sequences that need to be followed instead of just a bitfield to update. Callbacks to validate enable state, voltage, mode and so on in the hardware. If we did that then rather than open coding every single test for every single device we could approach things at the framework level and give people working on a given device a pile of off the shelf tests which are more likely to catch things that an individual driver author might've missed, it also avoids the test coverage being more laborious than writing the actual driver.

Things could certainly be factored out in the future, but I'm a bit wary of attempting to do that when we have a test for only one regulator driver, and a very minimal regulator driver at that.

Quoted 6 lines

This does raise the questions I mentioned about how useful the testing really is of course, even more so when someone works out how to generate the data tables for the test and the driver from the same source, but that's just generally an issue for mocked tests at the conceptual level and clearly it's an approach that's fairly widely used and people get value from.

For the regulator drivers which are purely-data driven such as the ones mostly implemented by setting the various fields in struct regulator_desc along with the helpers in the framework, it could perhaps be useful to implement kunit tests in the regulator subsystem which test that using the various fields actually results in the expected consumer-visible behaviour with the regulator API.

Then, for the indivudal drivers themselves, roadtests could cover things like probe handling, functions implemented without using helpers, checks that the correct variant's registers are used in drivers supporting multiple variants, custom devicetree properties, interrupt handling, and the like.

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#24 lore raw

Re: [RFC v1 09/10] regulator: tps62864: add roadtest

Quoted 6 lines · Vincent Whitchurch
Quoted 3 lines · Mark Brown
Quoted 3 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +3 -0
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("tps6286x-regulator")
Quoted 7 lines
Quoted 2 lines

Shouldn't this get figured out when the device gets created in DT (if it doesn't I guess the tests found a bug...)?

The system isn't set up to load modules automatically. The reason for this is to give the test cases full control of when the module is loaded and unload, since the tests could want to load the module with specific options.

That seems like the uncommon case which could remove the module if it explicitly needed it.

Quoted 5 lines

Also, the framework splits up logs and shows errors that occurs during each specific test if the tests fail, and this would become less useful if all modules for all the devices in the devicetree get loaded on startup when the devicetree is parsed and one of the modules failed to load or crashed when loaded.

That sounds like stuff that would be covered already by normal boot testing?

Quoted 11 lines
Quoted 10 lines

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 139

Quoted 4 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +4 -0
+                write_int(minfile, voltage)
+                mock = self.hw.update_mock()
+                mock.assert_reg_write_once(self, REG_VOUT1, val)
+                mock.reset_mock()

For covering regulators in general (especially those like this that use the generic helpers) I'd be inclined to go through every single voltage that can be set which isn't so interesting for this driver with it's linear voltage control but more interesting for something that's not continuous.

Quoted 6 lines

That could be useful in some cases, but if going through all the voltages in a loop requires that the test implement the exact same voltage-to-bitfield conversion function as the driver, then the benefit of that part of the test is unclear. That's the reason why for example the OPT3001 test uses known values from the datasheet rather than just copying the conversion function in the driver to Python.

That's just a generic problem with mocking though - ultimately you have to type the same values into the mock and the driver somehow, it's just a question of if you type in all the values or some of the values and if you use the same format to type them in. My inclination is to get better coverage since it makes it more likely that the interesting cases will be picked up, and you can make tests that do things like combine multiple settings which might turn something up.

Quoted 12 lines
Quoted 11 lines

This all feels like it could readily be factored out into a generic helper, much as the actual drivers are especially when they're more data driven. Ideally with the ability to override the default I/O operations for things with sequences that need to be followed instead of just a bitfield to update. Callbacks to validate enable state, voltage, mode and so on in the hardware. If we did that then rather than open coding every single test for every single device we could approach things at the framework level and give people working on a given device a pile of off the shelf tests which are more likely to catch things that an individual driver author might've missed, it also avoids the test coverage being more laborious than writing the actual driver.

Quoted 3 lines

Things could certainly be factored out in the future, but I'm a bit wary of attempting to do that when we have a test for only one regulator driver, and a very minimal regulator driver at that.

My thinking here is that since the driver is so minimal and data driven it's clear that any tests for it can also be generalised to cover at the very least all similarly data driven drivers.

Quoted 14 lines
Quoted 6 lines

This does raise the questions I mentioned about how useful the testing really is of course, even more so when someone works out how to generate the data tables for the test and the driver from the same source, but that's just generally an issue for mocked tests at the conceptual level and clearly it's an approach that's fairly widely used and people get value from.

For the regulator drivers which are purely-data driven such as the ones mostly implemented by setting the various fields in struct regulator_desc along with the helpers in the framework, it could perhaps be useful to implement kunit tests in the regulator subsystem which test that using the various fields actually results in the expected consumer-visible behaviour with the regulator API.

Quoted 5 lines

Then, for the indivudal drivers themselves, roadtests could cover things like probe handling, functions implemented without using helpers, checks that the correct variant's registers are used in drivers supporting multiple variants, custom devicetree properties, interrupt handling, and the like.

That would be the more obvious approach than roadtest, but that's what's there in the patch I was reviewing so... There is also the fact that the external pattern for the operations is the same no matter if they're for a simple data driven driver or one using custom ops so you should really be able to get the core coverage for every driver set up in a way that lets you plug in a model of how the I/O performing each operation is expected to work and then have the framework crunch through combinations of actions to make sure that all the corner cases check out.

#25 lore raw

Re: [RFC v1 09/10] regulator: tps62864: add roadtest

Quoted 10 lines · Mark Brown
Quoted 8 lines · Vincent Whitchurch
Quoted 6 lines · Mark Brown

tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py line 96

Quoted 3 lines
tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py new file +3 -0
+    @classmethod
+    def setUpClass(cls) -> None:
+        insmod("tps6286x-regulator")

Shouldn't this get figured out when the device gets created in DT (if it doesn't I guess the tests found a bug...)?

Quoted 7 lines
Quoted 4 lines

The system isn't set up to load modules automatically. The reason for this is to give the test cases full control of when the module is loaded and unload, since the tests could want to load the module with specific options.

That seems like the uncommon case which could remove the module if it explicitly needed it.

Another reason was to get the tests to test module unloading since I've seen a lot of especially new driver writers forget to test that, but I realise that for most normal drivers that should be mostly covered by the fact that we test device unbinding.

So I went ahead and implemented this and it seems to work. As you hinted earlier, this also means that the modalias stuff gets tested, and as we know that's been broken in the recent past for a bunch of drivers, so that's another advantage to automatic module loading, besides the boilerplate reduction in the tests.

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#26 lore raw

RFC 10/10 rtc: pcf8563: add roadtest

In reply to Vincent Whitchurch

Add a roadtest for the PCF8563 RTC driver, testing many of the features including alarm and invalid time handling. Since it's the first roadtest for RTC, some helper code for handling the ABI is included.

The following fixes were posted for problems identified during development of these tests:

- rtc: fix use-after-free on device removal
https://lore.kernel.org/lkml/[email protected]/

- rtc: pcf8563: clear RTC_FEATURE_ALARM if no irq
https://lore.kernel.org/lkml/[email protected]/

- rtc: pcf8523: fix alarm interrupt disabling
https://lore.kernel.org/lkml/[email protected]/
(not the same hardware/driver, but this was the original target for
test development)

---
 .../roadtest/roadtest/tests/rtc/__init__.py   |   0
 .../roadtest/roadtest/tests/rtc/config        |   1 +
 .../roadtest/roadtest/tests/rtc/rtc.py        |  73 ++++
 .../roadtest/tests/rtc/test_pcf8563.py        | 348 ++++++++++++++++++
 4 files changed, 422 insertions(+)
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/rtc.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/test_pcf8563.py
tools/testing/roadtest/roadtest/tests/rtc/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/testing/roadtest/roadtest/tests/rtc/config new file +1 -0
new file mode 100644
index 000000000000..f3654f9d7c19
@@ -0,0 +1 @@
+CONFIG_RTC_DRV_PCF8563=m
tools/testing/roadtest/roadtest/tests/rtc/rtc.py new file +73 -0

73 lines not on this page · raw message

tools/testing/roadtest/roadtest/tests/rtc/test_pcf8563.py new file +348 -0

348 lines not on this page · raw message

Signature · 7 lines
2.34.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
#27 lore raw
In reply to Vincent Whitchurch

+Kees Cook - I imagine you have already seen this, but I figured you would be interested because of your recent work on the KUnit UAPI and the mocking discussions.
+Dmitry Vyukov - This made me think of the syzkaller/KUnit experiments we did a couple of years back - this would probably work a bit better.

Quoted 5 lines · Vincent Whitchurch

This patchset proposes roadtest, a device-driver testing framework. Drivers are tested under User Mode Linux (UML) and interact with mocked/modelled hardware. The tests and hardware models are written in Python, the former using Python's built-in unittest framework.

Wow! This sounds awesome! I was hoping to get some kind of hardware modeling with KUnit eventually. I did some experiments, but this looks way more mature.

Quoted 3 lines

Drivers are tested via their userspace interfaces. The hardware models allow tests to inject values into registers and assert that drivers control the hardware in the right way and react as expected to stimuli.

I already took a look at the documentation patch - I'll comment there more in detail, but I like the hardware modelling and device tree code; it seems very usable.

Quoted 2 lines

Roadtest is meant to be used for relatively simple drivers, such as the ones part of the IIO, regulator and RTC subsystems.

Obviously for an initial version going after simple stuff makes sense, but I would hope there is applicability to any driver stack eventually.

Quoted 20 lines

Questions and answers:

= Why do we need this?

There are a large amount of these kind of drivers in the kernel. Most of the hardware is not available in current CI systems so most drivers can only, at best, be build-tested there. Even basic soundness such as a driver successfully probing and binding to the devices it tries to be support cannot be tested. Drivers cannot be easily regression-tested to ensure that bugs fixed once do not get reintroduced.

Many drivers support multiple related hardware variants, and far from all patch submitters have access to all the variants which the driver that they are patching supports, so there is no way for them to easily verify that they haven't broken something basic on a variant which they do not own.

Furthermore, hardware can be used in many different configurations with drivers supporting many different devicetree properties, so even just having access to all the variants would be insufficient.

Quoted 8 lines

On top of that, some of the chips measure environmental conditions such as temperature, so testing extreme cases may not be simple even if one has access to the hardware.

All this makes development, modification, maintenance, and reviewing of these drivers harder than it necessarily needs to be. Roadtest hopes to make some of these things slightly easier by providing a framework to create hardware models/mocks and to write testcases which exercise drivers using these models.

Very much agree. I used to do driver development and these difficulties are what prompted me to do KUnit.

Quoted 24 lines

= Do you have some specific examples of the kind of code this could be used to
test?

Here is an example of a patch which can easily be regression-tested using roadtest (in fact, this series includes such a regression test) but is much harder to do so automatically with real hardware since it requires specific environmental conditions:

iio: light: opt3001: Fixed timeout error when 0 lux
https://lore.kernel.org/lkml/[email protected]/

Here is another example. This driver has code which correctly parses a documented devicetree property (amstaos,proximity-diodes) but which then fails to actually communicate this setting to the hardware in any way. Such code can be easily tested with roadtest since the framework integrates devicetree support and provides functions to assert that drivers writes expected registers with expected values:

drivers/iio/light/tsl2772.c tsl2772_read_prox_diodes()

(Both the above examples happen to be from the same subsystem but that should in no way be taken to imply that such issues are unique to that subsystem or that that subsystem has more of them.)

Quoted 5 lines

= How does this relate to kselftests?

Tests in kselftests also test kernel code using the userspace interfaces, but that's about what's common between the frameworks. kselftests has other goals and does not provide any kind of mechanism for hardware mocking.

I had a question that after thinking about it; I think I know the answer, so I am going to ask the question anyway and attempt to answer it myself:

I agree in regard to mocking, but why not use kselftest for driving tests that check drivers from userspace? I believe there are other kselftest tests implemented in Python, why can't you just run your tests inside of kselftest?

Now, I believe the answer to this question is that you need to control spinning up your own kernel to run inside your test harness because you need to control the environment that the kernel runs in - is this correct?

Quoted 7 lines

= How does this relate to kunit?

Kunit is for unit testing of functions in kernel code, and is not meant for testing kernel code via userspace interfaces. It could in theory be used to test some of the simple drivers too, but that would require (1) a large amount of mocking code in various kernel frameworks, and, more importantly, (2) refactoring of the drivers to be tested.

I mostly agree, but I think there is something that is missing here:
so roadtest seems to depend on having a user interface to test a driver - for a simple smoke test on a simple driver without a big driver stack on top, that makes sense, but what about testing error paths or a platform driver buried beneath a deep driver stack? I think there is potential for a powerful combination using KUnit to test the low level kernel API and using roadtest to mock the hardware environment and provide configuration.

I am imagining that we could have an in-kernel KUnit/roadtest API that we can use to have an in-kernel test request changes to the environment for creating error cases and the like that can be validated by KUnit test cases.

Going even further, I wonder if we could run kselftests inside of roadtest since roadtest allows us to change the environment on the fly.

Quoted 3 lines

This can be contrasted with roadtest which works with mostly unmodified drivers and which mocks the hardware at the lowest level without having to change kernel frameworks.

I think that is both potentially an advantage and a disadvantage.

The advantage is that your test is very general; roadtests would likely be portable across kernel versions.

The disadvantage is that you don't get as much code introspection: I imagine roadtest is not as good as testing error paths for example.

I also think that having to change code to make it more testable is often an advantage as much as a disadvantage.

Still, I think that is a good set of tradeoffs for roadtest to make when set against KUnit and kselftest since roadtest seems to fit in where kselftest and KUnit are weak.

Quoted 175 lines

= How do I use it?

See Documentation/dev-tools/roadtest.rst added by the documentation patch for more information about running and writing tests using this framework.

= What's included in the patchset?

The current framework allows developing tests for hardware which uses the I2C bus. Hardware models can also control GPIOs and use them to trigger interrupts.

This series includes tests for some IIO, regulator and RTC drivers. The regulator and RTC tests depend on a few driver patches which are either in review or in linux-next. These are noted in the commit messages.

The entire patch set, including the required dependencies, is also available in a git tree:

https://github.com/vwax/linux/commits/roadtest/rfc-v1

Vincent Whitchurch (10):
roadtest: import libvhost-user from QEMU
roadtest: add C backend
roadtest: add framework
roadtest: add base config
roadtest: add build files
roadtest: add documentation
iio: light: opt3001: add roadtest
iio: light: vcnl4000: add roadtest
regulator: tps62864: add roadtest
rtc: pcf8563: add roadtest

 Documentation/dev-tools/index.rst             |    1 +
 Documentation/dev-tools/roadtest.rst          |  669 ++++
 tools/testing/roadtest/.gitignore             |    2 +
 tools/testing/roadtest/Dockerfile             |   25 +
 tools/testing/roadtest/Makefile               |   84 +
 tools/testing/roadtest/init.sh                |   19 +
 tools/testing/roadtest/pyproject.toml         |   10 +
 tools/testing/roadtest/requirements.txt       |    4 +
 tools/testing/roadtest/roadtest/__init__.py   |    2 +
 .../roadtest/roadtest/backend/__init__.py     |    0
 .../roadtest/roadtest/backend/backend.py      |   32 +
 .../testing/roadtest/roadtest/backend/gpio.py |  111 +
 .../testing/roadtest/roadtest/backend/i2c.py  |  123 +
 .../testing/roadtest/roadtest/backend/main.py |   13 +
 .../testing/roadtest/roadtest/backend/mock.py |   20 +
 .../roadtest/roadtest/backend/test_gpio.py    |   98 +
 .../roadtest/roadtest/backend/test_i2c.py     |   84 +
 .../testing/roadtest/roadtest/cmd/__init__.py |    0
 tools/testing/roadtest/roadtest/cmd/main.py   |  146 +
 tools/testing/roadtest/roadtest/cmd/remote.py |   48 +
 .../roadtest/roadtest/core/__init__.py        |    0
 .../testing/roadtest/roadtest/core/control.py |   52 +
 .../roadtest/roadtest/core/devicetree.py      |  155 +
 .../roadtest/roadtest/core/hardware.py        |   94 +
 tools/testing/roadtest/roadtest/core/log.py   |   42 +
 .../testing/roadtest/roadtest/core/modules.py |   38 +
 .../testing/roadtest/roadtest/core/opslog.py  |   35 +
 tools/testing/roadtest/roadtest/core/proxy.py |   48 +
 tools/testing/roadtest/roadtest/core/suite.py |  286 ++
 tools/testing/roadtest/roadtest/core/sysfs.py |   77 +
 .../roadtest/roadtest/core/test_control.py    |   35 +
 .../roadtest/roadtest/core/test_devicetree.py |   31 +
 .../roadtest/roadtest/core/test_hardware.py   |   41 +
 .../roadtest/roadtest/core/test_log.py        |   54 +
 .../roadtest/roadtest/core/test_opslog.py     |   27 +
 .../roadtest/roadtest/tests/__init__.py       |    0
 .../roadtest/roadtest/tests/base/config       |   84 +
 .../roadtest/roadtest/tests/iio/__init__.py   |    0
 .../roadtest/roadtest/tests/iio/config        |    1 +
 .../roadtest/roadtest/tests/iio/iio.py        |  112 +
 .../roadtest/tests/iio/light/__init__.py      |    0
 .../roadtest/roadtest/tests/iio/light/config  |    2 +
 .../roadtest/tests/iio/light/test_opt3001.py  |   95 +
 .../roadtest/tests/iio/light/test_vcnl4000.py |  132 +
 .../roadtest/tests/iio/light/test_vcnl4010.py |  282 ++
 .../roadtest/tests/iio/light/test_vcnl4040.py |  104 +
 .../roadtest/tests/iio/light/test_vcnl4200.py |   96 +
 .../roadtest/tests/regulator/__init__.py      |    0
 .../roadtest/roadtest/tests/regulator/config  |    4 +
 .../roadtest/tests/regulator/test_tps62864.py |  187 ++
 .../roadtest/roadtest/tests/rtc/__init__.py   |    0
 .../roadtest/roadtest/tests/rtc/config        |    1 +
 .../roadtest/roadtest/tests/rtc/rtc.py        |   73 +
 .../roadtest/tests/rtc/test_pcf8563.py        |  348 ++
 tools/testing/roadtest/src/.gitignore         |    1 +
 tools/testing/roadtest/src/backend.c          |  884 +++++
 .../src/libvhost-user/include/atomic.h        |  310 ++
 .../src/libvhost-user/libvhost-user.c         | 2885 +++++++++++++++++
 .../src/libvhost-user/libvhost-user.h         |  691 ++++
 59 files changed, 8798 insertions(+)
 create mode 100644 Documentation/dev-tools/roadtest.rst
 create mode 100644 tools/testing/roadtest/.gitignore
 create mode 100644 tools/testing/roadtest/Dockerfile
 create mode 100644 tools/testing/roadtest/Makefile
 create mode 100755 tools/testing/roadtest/init.sh
 create mode 100644 tools/testing/roadtest/pyproject.toml
 create mode 100644 tools/testing/roadtest/requirements.txt
 create mode 100644 tools/testing/roadtest/roadtest/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/backend.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/main.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/mock.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/main.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/remote.py
 create mode 100644 tools/testing/roadtest/roadtest/core/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/core/control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/modules.py
 create mode 100644 tools/testing/roadtest/roadtest/core/opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/core/proxy.py
 create mode 100644 tools/testing/roadtest/roadtest/core/suite.py
 create mode 100644 tools/testing/roadtest/roadtest/core/sysfs.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/base/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/iio.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/rtc.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/test_pcf8563.py
 create mode 100644 tools/testing/roadtest/src/.gitignore
 create mode 100644 tools/testing/roadtest/src/backend.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/include/atomic.h
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.h

--
2.34.1

#28 lore raw
Quoted 9 lines · Brendan Higgins

+Kees Cook - I imagine you have already seen this, but I figured you would be interested because of your recent work on the KUnit UAPI and the mocking discussions.
+Dmitry Vyukov - This made me think of the syzkaller/KUnit experiments we did a couple of years back - this would probably work a bit better.

Quoted 1 line · Vincent Whitchurch
Quoted 8 lines
Quoted 4 lines

This patchset proposes roadtest, a device-driver testing framework. Drivers are tested under User Mode Linux (UML) and interact with mocked/modelled hardware. The tests and hardware models are written in Python, the former using Python's built-in unittest framework.

Wow! This sounds awesome! I was hoping to get some kind of hardware modeling with KUnit eventually. I did some experiments, but this looks way more mature.

Thank you for the comments!

Quoted 8 lines
Quoted 3 lines

Drivers are tested via their userspace interfaces. The hardware models allow tests to inject values into registers and assert that drivers control the hardware in the right way and react as expected to stimuli.

I already took a look at the documentation patch - I'll comment there more in detail, but I like the hardware modelling and device tree code; it seems very usable.

Quoted 6 lines
Quoted 2 lines

Roadtest is meant to be used for relatively simple drivers, such as the ones part of the IIO, regulator and RTC subsystems.

Obviously for an initial version going after simple stuff makes sense, but I would hope there is applicability to any driver stack eventually.

Yes, there is no inherent restriction to only simple hardware, but these kinds of subsystem are the ones where it's easier to apply the framework since there's simply less stuff to model/mock in the hardware.

Supporting different busses also requires some work in the framework and potentially some new drivers. For I2C we use virtio-i2c but there's no ready-made virtio-spi for example. For MMIO (PCI / platform drivers), I did some basic experiments with UML's virtio-mmio in the early stages of writing this framework.

Quoted 15 lines
Quoted 5 lines

= How does this relate to kselftests?

Tests in kselftests also test kernel code using the userspace interfaces, but that's about what's common between the frameworks. kselftests has other goals and does not provide any kind of mechanism for hardware mocking.

I had a question that after thinking about it; I think I know the answer, so I am going to ask the question anyway and attempt to answer it myself:

I agree in regard to mocking, but why not use kselftest for driving tests that check drivers from userspace? I believe there are other kselftest tests implemented in Python, why can't you just run your tests inside of kselftest?

Quoted 4 lines

Now, I believe the answer to this question is that you need to control spinning up your own kernel to run inside your test harness because you need to control the environment that the kernel runs in - is this correct?

Yes, that is correct. For example, the devicetree stuff requires that the kernel be booted with the devicetree. For the other tests also it's simpler to have a controlled environment without being affected by other stuff going on on the host. And generally it's of course easier if the kernel which is inevitably going to crash and burn due to buggy drivers isn't the one powering your workstation.

Also, there is no currently way to use virtio drivers such as virtio-i2c and virtio-gpio (which roadtest uses) with the virtio device side implemented in userspace on the same system, so that would have also required a fair bit of work to get running.

(On a side note, I've wondered why kselftest doesn't provide a standard way to run all the tests under kvm or something similar with all the correct configs. For example, the kernels I work with are on embedded systems and I rarely recompile my host kernel, and I assume that there are plenty of others in the same situation.)

Quoted 8 lines
Quoted 7 lines

= How does this relate to kunit?

Kunit is for unit testing of functions in kernel code, and is not meant for testing kernel code via userspace interfaces. It could in theory be used to test some of the simple drivers too, but that would require (1) a large amount of mocking code in various kernel frameworks, and, more importantly, (2) refactoring of the drivers to be tested.

Quoted 8 lines

I mostly agree, but I think there is something that is missing here:
so roadtest seems to depend on having a user interface to test a driver - for a simple smoke test on a simple driver without a big driver stack on top, that makes sense, but what about testing error paths or a platform driver buried beneath a deep driver stack? I think there is potential for a powerful combination using KUnit to test the low level kernel API and using roadtest to mock the hardware environment and provide configuration.

Yes, that could be useful. I have previously written some kunit tests for some experimental memory management code which required different devicetree reserved-memory nodes and arm64 (no hardware mocking) to run, and I ran them by having a shell script which ran QEMU several times with appropriate -append kunit.filter_glob=foo and -dtb options and post-processing the logs with kunit.py.

Quoted 8 lines

I am imagining that we could have an in-kernel KUnit/roadtest API that we can use to have an in-kernel test request changes to the environment for creating error cases and the like that can be validated by KUnit test cases.

Going even further, I wonder if we could run kselftests inside of roadtest since roadtest allows us to change the environment on the fly.

Sounds interesting, but I would likely need to see concrete examples to understand what kind of environment we'd want to change from within the kernel.

Quoted 6 lines
Quoted 3 lines

This can be contrasted with roadtest which works with mostly unmodified drivers and which mocks the hardware at the lowest level without having to change kernel frameworks.

I think that is both potentially an advantage and a disadvantage.

Quoted 8 lines

The advantage is that your test is very general; roadtests would likely be portable across kernel versions.

The disadvantage is that you don't get as much code introspection: I imagine roadtest is not as good as testing error paths for example.

I also think that having to change code to make it more testable is often an advantage as much as a disadvantage.

Yes, that's true, but I highlighted the unmodified drivers bit because
(1) the process of refactoring drivers which don't have tests to make them testable in itself carries it with a risk of breaking stuff, and
(2) and there are simply so many existing drivers that it's very unlikely that most of them get refactored, but it should be relatively easy to, for example, add a regression test for a specific bug fix with roadtest.

Quoted 4 lines

Still, I think that is a good set of tradeoffs for roadtest to make when set against KUnit and kselftest since roadtest seems to fit in where kselftest and KUnit are weak.

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

maintainer
#29 lore raw
In reply to Vincent Whitchurch
Quoted 11 lines · On Fri, 11 Mar 2022 17:24:35 +0100 Vincent Whitchurch…

This patchset proposes roadtest, a device-driver testing framework. Drivers are tested under User Mode Linux (UML) and interact with mocked/modelled hardware. The tests and hardware models are written in Python, the former using Python's built-in unittest framework.

Drivers are tested via their userspace interfaces. The hardware models allow tests to inject values into registers and assert that drivers control the hardware in the right way and react as expected to stimuli.

Roadtest is meant to be used for relatively simple drivers, such as the ones part of the IIO, regulator and RTC subsystems.

Hi All,

Just wanted to very briefly report back on my experience of using this framework.

Given I wanted a suitable job to try out it's usefulness when doing refactoring /development, I decided to tidy up one of the remaining IIO drivers in staging and see how things went in developing tests to hit the particular code I was modifying. At some point I might extend this to a more comprehensive test suite for that driver, but for now it does basic channel reading and a few other things
+ verifies some of the register state changes seen on the hardware side of things.

Whilst my python could be said to be decidedly rusty (last time I recall writing some was for an intern project 20 years back), it was fairly easy to get something working using the docs in this series and the fine engineering tool of cut and paste.

Road test worked very well.

Was it easier than my existing hacked up QEMU board emulation that lets me instantiate minimal emulation pretty quickly?

Pretty similar on balance but big advantage here is I'm not having to ask people to go fetch a tree and build QEMU just to sanity check the driver changes. Also note I'm doing a lot of QEMU work for the day job at the moment, so it's not really a fair comparison if the question is what would most kernel driver developers find useful.

So for now I'll probably mix and match depending on the complexity of the device I'm emulating, but roadtest is definitely a good addition to the toolkit.

Note this is putting aside all the advantages of having tests in tree and the much lighter amount of infrastructure needed to run those over QEMU CI.

If anyone is curious patch set with tests and the staging graduation of the AD7746 CDC driver.

https://lore.kernel.org/all/[email protected]/

Great work Vincent. I'm looking forward to using this more.

Thanks,

Jonathan

Quoted 244 lines

Questions and answers:

= Why do we need this?

There are a large amount of these kind of drivers in the kernel. Most of the hardware is not available in current CI systems so most drivers can only, at best, be build-tested there. Even basic soundness such as a driver successfully probing and binding to the devices it tries to be support cannot be tested. Drivers cannot be easily regression-tested to ensure that bugs fixed once do not get reintroduced.

Many drivers support multiple related hardware variants, and far from all patch submitters have access to all the variants which the driver that they are patching supports, so there is no way for them to easily verify that they haven't broken something basic on a variant which they do not own.

Furthermore, hardware can be used in many different configurations with drivers supporting many different devicetree properties, so even just having access to all the variants would be insufficient.

On top of that, some of the chips measure environmental conditions such as temperature, so testing extreme cases may not be simple even if one has access to the hardware.

All this makes development, modification, maintenance, and reviewing of these drivers harder than it necessarily needs to be. Roadtest hopes to make some of these things slightly easier by providing a framework to create hardware models/mocks and to write testcases which exercise drivers using these models.

= Do you have some specific examples of the kind of code this could be used to
test?

Here is an example of a patch which can easily be regression-tested using roadtest (in fact, this series includes such a regression test) but is much harder to do so automatically with real hardware since it requires specific environmental conditions:

iio: light: opt3001: Fixed timeout error when 0 lux
https://lore.kernel.org/lkml/[email protected]/

Here is another example. This driver has code which correctly parses a documented devicetree property (amstaos,proximity-diodes) but which then fails to actually communicate this setting to the hardware in any way. Such code can be easily tested with roadtest since the framework integrates devicetree support and provides functions to assert that drivers writes expected registers with expected values:

drivers/iio/light/tsl2772.c tsl2772_read_prox_diodes()

(Both the above examples happen to be from the same subsystem but that should in no way be taken to imply that such issues are unique to that subsystem or that that subsystem has more of them.)

= How does this relate to kselftests?

Tests in kselftests also test kernel code using the userspace interfaces, but that's about what's common between the frameworks. kselftests has other goals and does not provide any kind of mechanism for hardware mocking.

= How does this relate to kunit?

Kunit is for unit testing of functions in kernel code, and is not meant for testing kernel code via userspace interfaces. It could in theory be used to test some of the simple drivers too, but that would require (1) a large amount of mocking code in various kernel frameworks, and, more importantly, (2) refactoring of the drivers to be tested.

This can be contrasted with roadtest which works with mostly unmodified drivers and which mocks the hardware at the lowest level without having to change kernel frameworks.

= How do I use it?

See Documentation/dev-tools/roadtest.rst added by the documentation patch for more information about running and writing tests using this framework.

= What's included in the patchset?

The current framework allows developing tests for hardware which uses the I2C bus. Hardware models can also control GPIOs and use them to trigger interrupts.

This series includes tests for some IIO, regulator and RTC drivers. The regulator and RTC tests depend on a few driver patches which are either in review or in linux-next. These are noted in the commit messages.

The entire patch set, including the required dependencies, is also available in a git tree:

https://github.com/vwax/linux/commits/roadtest/rfc-v1

Vincent Whitchurch (10):
roadtest: import libvhost-user from QEMU
roadtest: add C backend
roadtest: add framework
roadtest: add base config
roadtest: add build files
roadtest: add documentation
iio: light: opt3001: add roadtest
iio: light: vcnl4000: add roadtest
regulator: tps62864: add roadtest
rtc: pcf8563: add roadtest

 Documentation/dev-tools/index.rst             |    1 +
 Documentation/dev-tools/roadtest.rst          |  669 ++++
 tools/testing/roadtest/.gitignore             |    2 +
 tools/testing/roadtest/Dockerfile             |   25 +
 tools/testing/roadtest/Makefile               |   84 +
 tools/testing/roadtest/init.sh                |   19 +
 tools/testing/roadtest/pyproject.toml         |   10 +
 tools/testing/roadtest/requirements.txt       |    4 +
 tools/testing/roadtest/roadtest/__init__.py   |    2 +
 .../roadtest/roadtest/backend/__init__.py     |    0
 .../roadtest/roadtest/backend/backend.py      |   32 +
 .../testing/roadtest/roadtest/backend/gpio.py |  111 +
 .../testing/roadtest/roadtest/backend/i2c.py  |  123 +
 .../testing/roadtest/roadtest/backend/main.py |   13 +
 .../testing/roadtest/roadtest/backend/mock.py |   20 +
 .../roadtest/roadtest/backend/test_gpio.py    |   98 +
 .../roadtest/roadtest/backend/test_i2c.py     |   84 +
 .../testing/roadtest/roadtest/cmd/__init__.py |    0
 tools/testing/roadtest/roadtest/cmd/main.py   |  146 +
 tools/testing/roadtest/roadtest/cmd/remote.py |   48 +
 .../roadtest/roadtest/core/__init__.py        |    0
 .../testing/roadtest/roadtest/core/control.py |   52 +
 .../roadtest/roadtest/core/devicetree.py      |  155 +
 .../roadtest/roadtest/core/hardware.py        |   94 +
 tools/testing/roadtest/roadtest/core/log.py   |   42 +
 .../testing/roadtest/roadtest/core/modules.py |   38 +
 .../testing/roadtest/roadtest/core/opslog.py  |   35 +
 tools/testing/roadtest/roadtest/core/proxy.py |   48 +
 tools/testing/roadtest/roadtest/core/suite.py |  286 ++
 tools/testing/roadtest/roadtest/core/sysfs.py |   77 +
 .../roadtest/roadtest/core/test_control.py    |   35 +
 .../roadtest/roadtest/core/test_devicetree.py |   31 +
 .../roadtest/roadtest/core/test_hardware.py   |   41 +
 .../roadtest/roadtest/core/test_log.py        |   54 +
 .../roadtest/roadtest/core/test_opslog.py     |   27 +
 .../roadtest/roadtest/tests/__init__.py       |    0
 .../roadtest/roadtest/tests/base/config       |   84 +
 .../roadtest/roadtest/tests/iio/__init__.py   |    0
 .../roadtest/roadtest/tests/iio/config        |    1 +
 .../roadtest/roadtest/tests/iio/iio.py        |  112 +
 .../roadtest/tests/iio/light/__init__.py      |    0
 .../roadtest/roadtest/tests/iio/light/config  |    2 +
 .../roadtest/tests/iio/light/test_opt3001.py  |   95 +
 .../roadtest/tests/iio/light/test_vcnl4000.py |  132 +
 .../roadtest/tests/iio/light/test_vcnl4010.py |  282 ++
 .../roadtest/tests/iio/light/test_vcnl4040.py |  104 +
 .../roadtest/tests/iio/light/test_vcnl4200.py |   96 +
 .../roadtest/tests/regulator/__init__.py      |    0
 .../roadtest/roadtest/tests/regulator/config  |    4 +
 .../roadtest/tests/regulator/test_tps62864.py |  187 ++
 .../roadtest/roadtest/tests/rtc/__init__.py   |    0
 .../roadtest/roadtest/tests/rtc/config        |    1 +
 .../roadtest/roadtest/tests/rtc/rtc.py        |   73 +
 .../roadtest/tests/rtc/test_pcf8563.py        |  348 ++
 tools/testing/roadtest/src/.gitignore         |    1 +
 tools/testing/roadtest/src/backend.c          |  884 +++++
 .../src/libvhost-user/include/atomic.h        |  310 ++
 .../src/libvhost-user/libvhost-user.c         | 2885 +++++++++++++++++
 .../src/libvhost-user/libvhost-user.h         |  691 ++++
 59 files changed, 8798 insertions(+)
 create mode 100644 Documentation/dev-tools/roadtest.rst
 create mode 100644 tools/testing/roadtest/.gitignore
 create mode 100644 tools/testing/roadtest/Dockerfile
 create mode 100644 tools/testing/roadtest/Makefile
 create mode 100755 tools/testing/roadtest/init.sh
 create mode 100644 tools/testing/roadtest/pyproject.toml
 create mode 100644 tools/testing/roadtest/requirements.txt
 create mode 100644 tools/testing/roadtest/roadtest/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/backend.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/main.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/mock.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_gpio.py
 create mode 100644 tools/testing/roadtest/roadtest/backend/test_i2c.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/main.py
 create mode 100644 tools/testing/roadtest/roadtest/cmd/remote.py
 create mode 100644 tools/testing/roadtest/roadtest/core/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/core/control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/modules.py
 create mode 100644 tools/testing/roadtest/roadtest/core/opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/core/proxy.py
 create mode 100644 tools/testing/roadtest/roadtest/core/suite.py
 create mode 100644 tools/testing/roadtest/roadtest/core/sysfs.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_control.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_devicetree.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_hardware.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_log.py
 create mode 100644 tools/testing/roadtest/roadtest/core/test_opslog.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/base/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/iio.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_opt3001.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4000.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4010.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4040.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/iio/light/test_vcnl4200.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/regulator/test_tps62864.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/__init__.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/config
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/rtc.py
 create mode 100644 tools/testing/roadtest/roadtest/tests/rtc/test_pcf8563.py
 create mode 100644 tools/testing/roadtest/src/.gitignore
 create mode 100644 tools/testing/roadtest/src/backend.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/include/atomic.h
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.c
 create mode 100644 tools/testing/roadtest/src/libvhost-user/libvhost-user.h