aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorthead_admin <occ_thead@service.alibaba.com>2022-09-13 11:04:33 +0800
committerthead_admin <occ_thead@service.alibaba.com>2022-09-13 11:04:33 +0800
commit43db9e00d5837c100c0b2fbbee64a08ab807d1e0 (patch)
treeb40c0eed02935b6682e8c5c975e3016b6b2f55fe /test
Linux_SDK_V0.9.5Linux_SDK_V0.9.5
Diffstat (limited to 'test')
-rw-r--r--test/Kconfig53
-rw-r--r--test/Makefile14
-rw-r--r--test/README96
-rw-r--r--test/bloblist.c187
-rw-r--r--test/cmd_ut.c139
-rw-r--r--test/command_ut.c68
-rw-r--r--test/common.sh20
-rw-r--r--test/compression.c544
-rw-r--r--test/dm/Kconfig8
-rw-r--r--test/dm/Makefile68
-rw-r--r--test/dm/adc.c197
-rw-r--r--test/dm/audio.c34
-rw-r--r--test/dm/axi.c77
-rw-r--r--test/dm/blk.c164
-rw-r--r--test/dm/board.c57
-rw-r--r--test/dm/bootcount.c30
-rw-r--r--test/dm/bus.c583
-rw-r--r--test/dm/cache.c22
-rw-r--r--test/dm/clk.c199
-rw-r--r--test/dm/clk_ccf.c98
-rw-r--r--test/dm/core.c906
-rw-r--r--test/dm/cpu.c45
-rw-r--r--test/dm/dma.c123
-rw-r--r--test/dm/dsi_host.c58
-rw-r--r--test/dm/eth.c431
-rw-r--r--test/dm/firmware.c22
-rw-r--r--test/dm/gpio.c249
-rw-r--r--test/dm/hwspinlock.c40
-rw-r--r--test/dm/i2c.c223
-rw-r--r--test/dm/i2s.c32
-rw-r--r--test/dm/led.c142
-rw-r--r--test/dm/mailbox.c30
-rw-r--r--test/dm/mdio.c56
-rw-r--r--test/dm/mdio_mux.c80
-rw-r--r--test/dm/misc.c83
-rw-r--r--test/dm/mmc.c43
-rw-r--r--test/dm/nop.c73
-rw-r--r--test/dm/ofnode.c60
-rw-r--r--test/dm/osd.c210
-rw-r--r--test/dm/panel.c79
-rw-r--r--test/dm/pch.c55
-rw-r--r--test/dm/pci.c341
-rw-r--r--test/dm/pci_ep.c64
-rw-r--r--test/dm/phy.c112
-rw-r--r--test/dm/pmic.c130
-rw-r--r--test/dm/power-domain.c47
-rw-r--r--test/dm/pwm.c31
-rw-r--r--test/dm/ram.c27
-rw-r--r--test/dm/regmap.c186
-rw-r--r--test/dm/regulator.c402
-rw-r--r--test/dm/remoteproc.c188
-rw-r--r--test/dm/reset.c94
-rw-r--r--test/dm/rtc.c175
-rw-r--r--test/dm/serial.c69
-rw-r--r--test/dm/sf.c103
-rw-r--r--test/dm/smem.c27
-rw-r--r--test/dm/sound.c55
-rw-r--r--test/dm/spi.c126
-rw-r--r--test/dm/spmi.c111
-rw-r--r--test/dm/syscon.c81
-rw-r--r--test/dm/sysreset.c112
-rw-r--r--test/dm/tee.c115
-rw-r--r--test/dm/test-driver.c169
-rw-r--r--test/dm/test-fdt.c816
-rw-r--r--test/dm/test-main.c211
-rw-r--r--test/dm/test-uclass.c129
-rw-r--r--test/dm/timer.c24
-rw-r--r--test/dm/usb.c414
-rw-r--r--test/dm/video.c376
-rw-r--r--test/dm/virtio.c122
-rw-r--r--test/dm/wdt.c40
-rw-r--r--test/env/Kconfig9
-rw-r--r--test/env/Makefile7
-rw-r--r--test/env/attr.c88
-rw-r--r--test/env/cmd_ut_env.c19
-rw-r--r--test/env/hashtable.c125
-rwxr-xr-xtest/fs/fat-noncontig-test.sh144
-rwxr-xr-xtest/fs/fs-test.sh627
-rwxr-xr-xtest/image/test-imagetools.sh225
-rw-r--r--test/lib/Makefile10
-rw-r--r--test/lib/asn1.c392
-rw-r--r--test/lib/cmd_ut_lib.c20
-rw-r--r--test/lib/hexdump.c96
-rw-r--r--test/lib/lmb.c657
-rw-r--r--test/lib/string.c194
-rw-r--r--test/lib/test_errno_str.c46
-rw-r--r--test/log/Makefile5
-rw-r--r--test/log/log_test.c217
-rw-r--r--test/optee/Kconfig7
-rw-r--r--test/optee/Makefile13
-rw-r--r--test/optee/cmd_ut_optee.c149
-rw-r--r--test/optee/test-optee-base.dts13
-rw-r--r--test/optee/test-optee-no-optee.dts13
-rw-r--r--test/optee/test-optee-optee.dts32
-rw-r--r--test/overlay/Kconfig10
-rw-r--r--test/overlay/Makefile14
-rw-r--r--test/overlay/cmd_ut_overlay.c284
-rw-r--r--test/overlay/test-fdt-base.dts20
-rw-r--r--test/overlay/test-fdt-overlay-stacked.dts20
-rw-r--r--test/overlay/test-fdt-overlay.dts95
-rw-r--r--test/print_ut.c151
-rw-r--r--test/py/.gitignore1
-rw-r--r--test/py/README.md370
-rw-r--r--test/py/conftest.py596
-rw-r--r--test/py/multiplexed_log.css108
-rw-r--r--test/py/multiplexed_log.py709
-rw-r--r--test/py/pytest.ini13
-rw-r--r--test/py/requirements.txt22
-rwxr-xr-xtest/py/test.py20
-rw-r--r--test/py/tests/test_000_version.py19
-rw-r--r--test/py/tests/test_android/test_ab.py75
-rw-r--r--test/py/tests/test_android/test_avb.py137
-rw-r--r--test/py/tests/test_bind.py179
-rw-r--r--test/py/tests/test_dfu.py320
-rw-r--r--test/py/tests/test_efi_loader.py196
-rw-r--r--test/py/tests/test_efi_selftest.py198
-rw-r--r--test/py/tests/test_env.py338
-rwxr-xr-xtest/py/tests/test_fit.py457
-rw-r--r--test/py/tests/test_fpga.py565
-rw-r--r--test/py/tests/test_fs/conftest.py602
-rw-r--r--test/py/tests/test_fs/fstest_defs.py16
-rw-r--r--test/py/tests/test_fs/fstest_helpers.py13
-rw-r--r--test/py/tests/test_fs/test_basic.py292
-rw-r--r--test/py/tests/test_fs/test_ext.py319
-rw-r--r--test/py/tests/test_fs/test_mkdir.py121
-rw-r--r--test/py/tests/test_fs/test_symlink.py130
-rw-r--r--test/py/tests/test_fs/test_unlink.py118
-rw-r--r--test/py/tests/test_gpt.py178
-rw-r--r--test/py/tests/test_handoff.py15
-rw-r--r--test/py/tests/test_help.py8
-rw-r--r--test/py/tests/test_hush_if_test.py161
-rw-r--r--test/py/tests/test_log.py132
-rw-r--r--test/py/tests/test_md.py36
-rw-r--r--test/py/tests/test_mmc_rd.py286
-rw-r--r--test/py/tests/test_mmc_wr.py105
-rw-r--r--test/py/tests/test_net.py208
-rw-r--r--test/py/tests/test_ofplatdata.py70
-rw-r--r--test/py/tests/test_pinmux.py66
-rw-r--r--test/py/tests/test_sandbox_exit.py21
-rw-r--r--test/py/tests/test_sf.py217
-rw-r--r--test/py/tests/test_shell_basics.py45
-rw-r--r--test/py/tests/test_sleep.py35
-rw-r--r--test/py/tests/test_tpm2.py233
-rw-r--r--test/py/tests/test_ums.py236
-rw-r--r--test/py/tests/test_unknown_cmd.py13
-rw-r--r--test/py/tests/test_ut.py28
-rw-r--r--test/py/tests/test_vboot.py293
-rw-r--r--test/py/tests/vboot/sandbox-kernel.dts7
-rw-r--r--test/py/tests/vboot/sandbox-u-boot.dts10
-rw-r--r--test/py/tests/vboot/sign-configs-sha1-pss.its46
-rw-r--r--test/py/tests/vboot/sign-configs-sha1.its45
-rw-r--r--test/py/tests/vboot/sign-configs-sha256-pss-prod.its46
-rw-r--r--test/py/tests/vboot/sign-configs-sha256-pss.its46
-rw-r--r--test/py/tests/vboot/sign-configs-sha256.its45
-rw-r--r--test/py/tests/vboot/sign-images-sha1-pss.its44
-rw-r--r--test/py/tests/vboot/sign-images-sha1.its42
-rw-r--r--test/py/tests/vboot/sign-images-sha256-pss.its44
-rw-r--r--test/py/tests/vboot/sign-images-sha256.its42
-rw-r--r--test/py/u_boot_console_base.py468
-rw-r--r--test/py/u_boot_console_exec_attach.py70
-rw-r--r--test/py/u_boot_console_sandbox.py108
-rw-r--r--test/py/u_boot_spawn.py209
-rw-r--r--test/py/u_boot_utils.py340
-rwxr-xr-xtest/run64
-rw-r--r--test/stdint/int-types.c12
-rwxr-xr-xtest/stdint/test-includes.sh56
-rw-r--r--test/time_ut.c132
-rwxr-xr-xtest/trace/test-trace.sh64
-rw-r--r--test/unicode_ut.c589
-rw-r--r--test/ut.c34
170 files changed, 25180 insertions, 0 deletions
diff --git a/test/Kconfig b/test/Kconfig
new file mode 100644
index 00000000..cb51b467
--- /dev/null
+++ b/test/Kconfig
@@ -0,0 +1,53 @@
+menuconfig UNIT_TEST
+ bool "Unit tests"
+ help
+ Select this to compile in unit tests for various parts of
+ U-Boot. Test suites will be subcommands of the "ut" command.
+ This does not require sandbox to be included, but it is most
+ often used there.
+
+config UT_LIB
+ bool "Unit tests for library functions"
+ depends on UNIT_TEST
+ default y
+ help
+ Enables the 'ut lib' command which tests library functions like
+ memcat(), memcyp(), memmove() and ASN1 compiler/decoder.
+
+if UT_LIB
+
+config UT_LIB_ASN1
+ bool "Unit test for asn1 compiler and decoder function"
+ default y
+ imply ASYMMETRIC_KEY_TYPE
+ imply ASYMMETRIC_PUBLIC_KEY_SUBTYPE
+ imply X509_CERTIFICATE_PARSER
+ imply PKCS7_MESSAGE_PARSER
+ imply RSA_PUBLIC_KEY_PARSER
+ help
+ Enables a test which exercises asn1 compiler and decoder function
+ via various parsers.
+
+endif
+
+config UT_TIME
+ bool "Unit tests for time functions"
+ depends on UNIT_TEST
+ help
+ Enables the 'ut time' command which tests that the time functions
+ work correctly. The test is fairly simple and will not catch all
+ problems. But if you are having problems with udelay() and the like,
+ this is a good place to start.
+
+config UT_UNICODE
+ bool "Unit tests for Unicode functions"
+ depends on UNIT_TEST
+ default y
+ help
+ Enables the 'ut unicode' command which tests that the functions for
+ manipulating Unicode strings work correctly.
+
+source "test/dm/Kconfig"
+source "test/env/Kconfig"
+source "test/optee/Kconfig"
+source "test/overlay/Kconfig"
diff --git a/test/Makefile b/test/Makefile
new file mode 100644
index 00000000..2fe41f48
--- /dev/null
+++ b/test/Makefile
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# (C) Copyright 2012 The Chromium Authors
+
+obj-$(CONFIG_SANDBOX) += bloblist.o
+obj-$(CONFIG_UNIT_TEST) += cmd_ut.o
+obj-$(CONFIG_UNIT_TEST) += ut.o
+obj-$(CONFIG_SANDBOX) += command_ut.o
+obj-$(CONFIG_SANDBOX) += compression.o
+obj-$(CONFIG_SANDBOX) += print_ut.o
+obj-$(CONFIG_UT_TIME) += time_ut.o
+obj-$(CONFIG_UT_UNICODE) += unicode_ut.o
+obj-$(CONFIG_$(SPL_)LOG) += log/
+obj-$(CONFIG_UNIT_TEST) += lib/
diff --git a/test/README b/test/README
new file mode 100644
index 00000000..4bc9ca3a
--- /dev/null
+++ b/test/README
@@ -0,0 +1,96 @@
+Testing in U-Boot
+=================
+
+U-Boot has a large amount of code. This file describes how this code is
+tested and what tests you should write when adding a new feature.
+
+
+Running tests
+-------------
+
+To run most tests on sandbox, type this:
+
+ make check
+
+in the U-Boot directory. Note that only the pytest suite is run using this
+command.
+
+Some tests take ages to run. To run just the quick ones, type this:
+
+ make qcheck
+
+
+Sandbox
+-------
+U-Boot can be built as a user-space application (e.g. for Linux). This
+allows test to be executed without needing target hardware. The 'sandbox'
+target provides this feature and it is widely used in tests.
+
+
+Pytest Suite
+------------
+
+Many tests are available using the pytest suite, in test/py. This can run
+either on sandbox or on real hardware. It relies on the U-Boot console to
+inject test commands and check the result. It is slower to run than C code,
+but provides the ability to unify lots of tests and summarise their results.
+
+You can run the tests on sandbox with:
+
+ ./test/py/test.py --bd sandbox --build
+
+This will produce HTML output in build-sandbox/test-log.html
+
+See test/py/README.md for more information about the pytest suite.
+
+
+tbot
+----
+
+Tbot provides a way to execute tests on target hardware. It is intended for
+trying out both U-Boot and Linux (and potentially other software) on a
+number of boards automatically. It can be used to create a continuous test
+environment. See http://www.tbot.tools for more information.
+
+
+Ad-hoc tests
+------------
+
+There are several ad-hoc tests which run outside the pytest environment:
+
+ test/fs - File system test (shell script)
+ test/image - FIT and legacy image tests (shell script and Python)
+ test/stdint - A test that stdint.h can be used in U-Boot (shell script)
+ trace - Test for the tracing feature (shell script)
+
+TODO: Move these into pytest.
+
+
+When to write tests
+-------------------
+
+If you add code to U-Boot without a test you are taking a risk. Even if you
+perform thorough manual testing at the time of submission, it may break when
+future changes are made to U-Boot. It may even break when applied to mainline,
+if other changes interact with it. A good mindset is that untested code
+probably doesn't work and should be deleted.
+
+You can assume that the Pytest suite will be run before patches are accepted
+to mainline, so this provides protection against future breakage.
+
+On the other hand there is quite a bit of code that is not covered with tests,
+or is covered sparingly. So here are some suggestions:
+
+- If you are adding a new uclass, add a sandbox driver and a test that uses it
+- If you are modifying code covered by an existing test, add a new test case
+ to cover your changes
+- If the code you are modifying has not tests, consider writing one. Even a
+ very basic test is useful, and may be picked up and enhanced by others. It
+ is much easier to add onto a test - writing a new large test can seem
+ daunting to most contributors.
+
+
+Future work
+-----------
+
+Converting existing shell scripts into pytest tests.
diff --git a/test/bloblist.c b/test/bloblist.c
new file mode 100644
index 00000000..89bdb012
--- /dev/null
+++ b/test/bloblist.c
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ */
+
+#include <common.h>
+#include <bloblist.h>
+#include <log.h>
+#include <mapmem.h>
+#include <test/suites.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* Declare a new compression test */
+#define BLOBLIST_TEST(_name, _flags) \
+ UNIT_TEST(_name, _flags, bloblist_test)
+
+enum {
+ TEST_TAG = 1,
+ TEST_TAG2 = 2,
+ TEST_TAG_MISSING = 3,
+
+ TEST_SIZE = 10,
+ TEST_SIZE2 = 20,
+
+ TEST_ADDR = CONFIG_BLOBLIST_ADDR,
+ TEST_BLOBLIST_SIZE = 0x100,
+};
+
+static struct bloblist_hdr *clear_bloblist(void)
+{
+ struct bloblist_hdr *hdr;
+
+ /* Clear out any existing bloblist so we have a clean slate */
+ hdr = map_sysmem(CONFIG_BLOBLIST_ADDR, TEST_BLOBLIST_SIZE);
+ memset(hdr, '\0', TEST_BLOBLIST_SIZE);
+
+ return hdr;
+}
+
+static int bloblist_test_init(struct unit_test_state *uts)
+{
+ struct bloblist_hdr *hdr;
+
+ hdr = clear_bloblist();
+ ut_asserteq(-ENOENT, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ ut_assertok(bloblist_new(TEST_ADDR, TEST_BLOBLIST_SIZE, 0));
+ hdr->version++;
+ ut_asserteq(-EPROTONOSUPPORT, bloblist_check(TEST_ADDR,
+ TEST_BLOBLIST_SIZE));
+
+ ut_asserteq(-ENOSPC, bloblist_new(TEST_ADDR, 0x10, 0));
+ ut_asserteq(-EFAULT, bloblist_new(1, TEST_BLOBLIST_SIZE, 0));
+ ut_assertok(bloblist_new(TEST_ADDR, TEST_BLOBLIST_SIZE, 0));
+
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ ut_assertok(bloblist_finish());
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ hdr->flags++;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+
+ return 1;
+}
+BLOBLIST_TEST(bloblist_test_init, 0);
+
+static int bloblist_test_blob(struct unit_test_state *uts)
+{
+ struct bloblist_hdr *hdr;
+ struct bloblist_rec *rec, *rec2;
+ char *data;
+
+ /* At the start there should be no records */
+ hdr = clear_bloblist();
+ ut_assertnull(bloblist_find(TEST_TAG, TEST_BLOBLIST_SIZE));
+ ut_assertok(bloblist_new(TEST_ADDR, TEST_BLOBLIST_SIZE, 0));
+
+ /* Add a record and check that we can find it */
+ data = bloblist_add(TEST_TAG, TEST_SIZE);
+ rec = (void *)(hdr + 1);
+ ut_asserteq_ptr(rec + 1, data);
+ data = bloblist_find(TEST_TAG, TEST_SIZE);
+ ut_asserteq_ptr(rec + 1, data);
+
+ /* Check the 'ensure' method */
+ ut_asserteq_ptr(data, bloblist_ensure(TEST_TAG, TEST_SIZE));
+ ut_assertnull(bloblist_ensure(TEST_TAG, TEST_SIZE2));
+ rec2 = (struct bloblist_rec *)(data + ALIGN(TEST_SIZE, BLOBLIST_ALIGN));
+
+ /* Check for a non-existent record */
+ ut_asserteq_ptr(data, bloblist_ensure(TEST_TAG, TEST_SIZE));
+ ut_asserteq_ptr(rec2 + 1, bloblist_ensure(TEST_TAG2, TEST_SIZE2));
+ ut_assertnull(bloblist_find(TEST_TAG_MISSING, 0));
+
+ return 0;
+}
+BLOBLIST_TEST(bloblist_test_blob, 0);
+
+static int bloblist_test_bad_blob(struct unit_test_state *uts)
+{
+ struct bloblist_hdr *hdr;
+ void *data;
+
+ hdr = clear_bloblist();
+ ut_assertok(bloblist_new(TEST_ADDR, TEST_BLOBLIST_SIZE, 0));
+ data = hdr + 1;
+ data += sizeof(struct bloblist_rec);
+ ut_asserteq_ptr(data, bloblist_ensure(TEST_TAG, TEST_SIZE));
+ ut_asserteq_ptr(data, bloblist_ensure(TEST_TAG, TEST_SIZE));
+
+ return 0;
+}
+BLOBLIST_TEST(bloblist_test_bad_blob, 0);
+
+static int bloblist_test_checksum(struct unit_test_state *uts)
+{
+ struct bloblist_hdr *hdr;
+ char *data, *data2;
+
+ hdr = clear_bloblist();
+ ut_assertok(bloblist_new(TEST_ADDR, TEST_BLOBLIST_SIZE, 0));
+ ut_assertok(bloblist_finish());
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+
+ /*
+ * Now change things amd make sure that the checksum notices. We cannot
+ * change the size or alloced fields, since that will crash the code.
+ * It has to rely on these being correct.
+ */
+ hdr->flags--;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ hdr->flags++;
+
+ hdr->size--;
+ ut_asserteq(-EFBIG, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ hdr->size++;
+
+ hdr->spare++;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ hdr->spare--;
+
+ hdr->chksum++;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ hdr->chksum--;
+
+ /* Make sure the checksum changes when we add blobs */
+ data = bloblist_add(TEST_TAG, TEST_SIZE);
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+
+ data2 = bloblist_add(TEST_TAG2, TEST_SIZE2);
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ ut_assertok(bloblist_finish());
+
+ /* It should also change if we change the data */
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ *data += 1;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ *data -= 1;
+
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ *data2 += 1;
+ ut_asserteq(-EIO, bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ *data2 -= 1;
+
+ /*
+ * Changing data outside the range of valid data should not affect
+ * the checksum.
+ */
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+ data[TEST_SIZE]++;
+ data2[TEST_SIZE2]++;
+ ut_assertok(bloblist_check(TEST_ADDR, TEST_BLOBLIST_SIZE));
+
+ return 0;
+}
+
+BLOBLIST_TEST(bloblist_test_checksum, 0);
+
+int do_ut_bloblist(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test,
+ bloblist_test);
+ const int n_ents = ll_entry_count(struct unit_test, bloblist_test);
+
+ return cmd_ut_category("bloblist", tests, n_ents, argc, argv);
+}
diff --git a/test/cmd_ut.c b/test/cmd_ut.c
new file mode 100644
index 00000000..2781f8bd
--- /dev/null
+++ b/test/cmd_ut.c
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * (C) Copyright 2015
+ * Joe Hershberger, National Instruments, joe.hershberger@ni.com
+ */
+
+#include <common.h>
+#include <command.h>
+#include <test/suites.h>
+#include <test/test.h>
+
+static int do_ut_all(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
+
+int cmd_ut_category(const char *name, struct unit_test *tests, int n_ents,
+ int argc, char * const argv[])
+{
+ struct unit_test_state uts = { .fail_count = 0 };
+ struct unit_test *test;
+
+ if (argc == 1)
+ printf("Running %d %s tests\n", n_ents, name);
+
+ for (test = tests; test < tests + n_ents; test++) {
+ if (argc > 1 && strcmp(argv[1], test->name))
+ continue;
+ printf("Test: %s\n", test->name);
+
+ uts.start = mallinfo();
+
+ test->func(&uts);
+ }
+
+ printf("Failures: %d\n", uts.fail_count);
+
+ return uts.fail_count ? CMD_RET_FAILURE : 0;
+}
+
+static cmd_tbl_t cmd_ut_sub[] = {
+ U_BOOT_CMD_MKENT(all, CONFIG_SYS_MAXARGS, 1, do_ut_all, "", ""),
+#if defined(CONFIG_UT_DM)
+ U_BOOT_CMD_MKENT(dm, CONFIG_SYS_MAXARGS, 1, do_ut_dm, "", ""),
+#endif
+#if defined(CONFIG_UT_ENV)
+ U_BOOT_CMD_MKENT(env, CONFIG_SYS_MAXARGS, 1, do_ut_env, "", ""),
+#endif
+#ifdef CONFIG_UT_OPTEE
+ U_BOOT_CMD_MKENT(optee, CONFIG_SYS_MAXARGS, 1, do_ut_optee, "", ""),
+#endif
+#ifdef CONFIG_UT_OVERLAY
+ U_BOOT_CMD_MKENT(overlay, CONFIG_SYS_MAXARGS, 1, do_ut_overlay, "", ""),
+#endif
+#ifdef CONFIG_UT_LIB
+ U_BOOT_CMD_MKENT(lib, CONFIG_SYS_MAXARGS, 1, do_ut_lib, "", ""),
+#endif
+#ifdef CONFIG_UT_TIME
+ U_BOOT_CMD_MKENT(time, CONFIG_SYS_MAXARGS, 1, do_ut_time, "", ""),
+#endif
+#if CONFIG_IS_ENABLED(UT_UNICODE) && !defined(API_BUILD)
+ U_BOOT_CMD_MKENT(unicode, CONFIG_SYS_MAXARGS, 1, do_ut_unicode, "", ""),
+#endif
+#ifdef CONFIG_SANDBOX
+ U_BOOT_CMD_MKENT(compression, CONFIG_SYS_MAXARGS, 1, do_ut_compression,
+ "", ""),
+ U_BOOT_CMD_MKENT(bloblist, CONFIG_SYS_MAXARGS, 1, do_ut_bloblist,
+ "", ""),
+#endif
+};
+
+static int do_ut_all(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ int i;
+ int retval;
+ int any_fail = 0;
+
+ for (i = 1; i < ARRAY_SIZE(cmd_ut_sub); i++) {
+ printf("----Running %s tests----\n", cmd_ut_sub[i].name);
+ retval = cmd_ut_sub[i].cmd(cmdtp, flag, 1, &cmd_ut_sub[i].name);
+ if (!any_fail)
+ any_fail = retval;
+ }
+
+ return any_fail;
+}
+
+static int do_ut(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ cmd_tbl_t *cp;
+
+ if (argc < 2)
+ return CMD_RET_USAGE;
+
+ /* drop initial "ut" arg */
+ argc--;
+ argv++;
+
+ cp = find_cmd_tbl(argv[0], cmd_ut_sub, ARRAY_SIZE(cmd_ut_sub));
+
+ if (cp)
+ return cp->cmd(cmdtp, flag, argc, argv);
+
+ return CMD_RET_USAGE;
+}
+
+#ifdef CONFIG_SYS_LONGHELP
+static char ut_help_text[] =
+ "all - execute all enabled tests\n"
+#ifdef CONFIG_SANDBOX
+ "ut bloblist - Test bloblist implementation\n"
+ "ut compression - Test compressors and bootm decompression\n"
+#endif
+#ifdef CONFIG_UT_DM
+ "ut dm [test-name]\n"
+#endif
+#ifdef CONFIG_UT_ENV
+ "ut env [test-name]\n"
+#endif
+#ifdef CONFIG_UT_LIB
+ "ut lib [test-name] - test library functions\n"
+#endif
+#ifdef CONFIG_UT_OPTEE
+ "ut optee [test-name]\n"
+#endif
+#ifdef CONFIG_UT_OVERLAY
+ "ut overlay [test-name]\n"
+#endif
+#ifdef CONFIG_UT_TIME
+ "ut time - Very basic test of time functions\n"
+#endif
+#if defined(CONFIG_UT_UNICODE) && \
+ !defined(CONFIG_SPL_BUILD) && !defined(API_BUILD)
+ "ut unicode [test-name] - test Unicode functions\n"
+#endif
+ ;
+#endif /* CONFIG_SYS_LONGHELP */
+
+U_BOOT_CMD(
+ ut, CONFIG_SYS_MAXARGS, 1, do_ut,
+ "unit tests", ut_help_text
+);
diff --git a/test/command_ut.c b/test/command_ut.c
new file mode 100644
index 00000000..8e268e5e
--- /dev/null
+++ b/test/command_ut.c
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2012, The Chromium Authors
+ */
+
+#define DEBUG
+
+#include <common.h>
+#include <command.h>
+
+static const char test_cmd[] = "setenv list 1\n setenv list ${list}2; "
+ "setenv list ${list}3\0"
+ "setenv list ${list}4";
+
+static int do_ut_cmd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ printf("%s: Testing commands\n", __func__);
+ run_command("env default -f -a", 0);
+
+ /* commands separated by \n */
+ run_command_list("setenv list 1\n setenv list ${list}1", -1, 0);
+ assert(!strcmp("11", env_get("list")));
+
+ /* command followed by \n and nothing else */
+ run_command_list("setenv list 1${list}\n", -1, 0);
+ assert(!strcmp("111", env_get("list")));
+
+ /* a command string with \0 in it. Stuff after \0 should be ignored */
+ run_command("setenv list", 0);
+ run_command_list(test_cmd, sizeof(test_cmd), 0);
+ assert(!strcmp("123", env_get("list")));
+
+ /*
+ * a command list where we limit execution to only the first command
+ * using the length parameter.
+ */
+ run_command_list("setenv list 1\n setenv list ${list}2; "
+ "setenv list ${list}3", strlen("setenv list 1"), 0);
+ assert(!strcmp("1", env_get("list")));
+
+ assert(run_command("false", 0) == 1);
+ assert(run_command("echo", 0) == 0);
+ assert(run_command_list("false", -1, 0) == 1);
+ assert(run_command_list("echo", -1, 0) == 0);
+
+#ifdef CONFIG_HUSH_PARSER
+ run_command("setenv foo 'setenv black 1\nsetenv adder 2'", 0);
+ run_command("run foo", 0);
+ assert(env_get("black") != NULL);
+ assert(!strcmp("1", env_get("black")));
+ assert(env_get("adder") != NULL);
+ assert(!strcmp("2", env_get("adder")));
+#endif
+
+ assert(run_command("", 0) == 0);
+ assert(run_command(" ", 0) == 0);
+
+ assert(run_command("'", 0) == 1);
+
+ printf("%s: Everything went swimmingly\n", __func__);
+ return 0;
+}
+
+U_BOOT_CMD(
+ ut_cmd, 5, 1, do_ut_cmd,
+ "Very basic test of command parsers",
+ ""
+);
diff --git a/test/common.sh b/test/common.sh
new file mode 100644
index 00000000..702d1ed0
--- /dev/null
+++ b/test/common.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+OUTPUT_DIR=sandbox
+
+fail() {
+ echo "Test failed: $1"
+ if [ -n ${tmp} ]; then
+ rm ${tmp}
+ fi
+ exit 1
+}
+
+build_uboot() {
+ echo "Build sandbox"
+ OPTS="O=${OUTPUT_DIR} $1"
+ NUM_CPUS=$(grep -c processor /proc/cpuinfo)
+ echo ${OPTS}
+ make ${OPTS} sandbox_config
+ make ${OPTS} -s -j${NUM_CPUS}
+}
diff --git a/test/compression.c b/test/compression.c
new file mode 100644
index 00000000..48dccc0e
--- /dev/null
+++ b/test/compression.c
@@ -0,0 +1,544 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2013, The Chromium Authors
+ */
+
+#include <common.h>
+#include <bootm.h>
+#include <command.h>
+#include <gzip.h>
+#include <lz4.h>
+#include <malloc.h>
+#include <mapmem.h>
+#include <asm/io.h>
+
+#include <u-boot/zlib.h>
+#include <bzlib.h>
+
+#include <lzma/LzmaTypes.h>
+#include <lzma/LzmaDec.h>
+#include <lzma/LzmaTools.h>
+
+#include <linux/lzo.h>
+#include <test/compression.h>
+#include <test/suites.h>
+#include <test/ut.h>
+
+static const char plain[] =
+ "I am a highly compressable bit of text.\n"
+ "I am a highly compressable bit of text.\n"
+ "I am a highly compressable bit of text.\n"
+ "There are many like me, but this one is mine.\n"
+ "If I were any shorter, there wouldn't be much sense in\n"
+ "compressing me in the first place. At least with lzo, anyway,\n"
+ "which appears to behave poorly in the face of short text\n"
+ "messages.\n";
+
+/* bzip2 -c /tmp/plain.txt > /tmp/plain.bz2 */
+static const char bzip2_compressed[] =
+ "\x42\x5a\x68\x39\x31\x41\x59\x26\x53\x59\xe5\x63\xdd\x09\x00\x00"
+ "\x28\x57\x80\x00\x10\x40\x85\x20\x20\x04\x00\x3f\xef\xdf\xf0\x30"
+ "\x00\xd6\xd0\x34\x91\x89\xa6\xf5\x4d\x19\x1a\x19\x0d\x02\x34\xd4"
+ "\xc9\x00\x34\x34\x00\x02\x48\x41\x35\x4f\xd4\xc6\x88\xd3\x50\x3d"
+ "\x4f\x51\x82\x4f\x88\xc3\x0d\x05\x62\x4f\x91\xa3\x52\x1b\xd0\x52"
+ "\x41\x4a\xa3\x98\xc2\x6b\xca\xa3\x82\xa5\xac\x8b\x15\x99\x68\xad"
+ "\xdf\x29\xd6\xf1\xf7\x5a\x10\xcd\x8c\x26\x61\x94\x95\xfe\x9e\x16"
+ "\x18\x28\x69\xd4\x23\x64\xcc\x2b\xe5\xe8\x5f\x00\xa4\x70\x26\x2c"
+ "\xee\xbd\x59\x6d\x6a\xec\xfc\x31\xda\x59\x0a\x14\x2a\x60\x1c\xf0"
+ "\x04\x86\x73\x9a\xc5\x5b\x87\x3f\x5b\x4c\x93\xe6\xb5\x35\x0d\xa6"
+ "\xb1\x2e\x62\x7b\xab\x67\xe7\x99\x2a\x14\x5e\x9f\x64\xcb\x96\xf4"
+ "\x0d\x65\xd4\x39\xe6\x8b\x7e\xea\x1c\x03\x69\x97\x83\x58\x91\x96"
+ "\xe1\xf0\x9d\xa4\x15\x8b\xb8\xc6\x93\xdc\x3d\xd9\x3c\x22\x55\xef"
+ "\xfb\xbb\x2a\xd3\x87\xa2\x8b\x04\xd9\x19\xf8\xe2\xfd\x4f\xdb\x1a"
+ "\x07\xc8\x60\xa3\x3f\xf8\xbb\x92\x29\xc2\x84\x87\x2b\x1e\xe8\x48";
+static const unsigned long bzip2_compressed_size = 240;
+
+/* lzma -z -c /tmp/plain.txt > /tmp/plain.lzma */
+static const char lzma_compressed[] =
+ "\x5d\x00\x00\x80\x00\xff\xff\xff\xff\xff\xff\xff\xff\x00\x24\x88"
+ "\x08\x26\xd8\x41\xff\x99\xc8\xcf\x66\x3d\x80\xac\xba\x17\xf1\xc8"
+ "\xb9\xdf\x49\x37\xb1\x68\xa0\x2a\xdd\x63\xd1\xa7\xa3\x66\xf8\x15"
+ "\xef\xa6\x67\x8a\x14\x18\x80\xcb\xc7\xb1\xcb\x84\x6a\xb2\x51\x16"
+ "\xa1\x45\xa0\xd6\x3e\x55\x44\x8a\x5c\xa0\x7c\xe5\xa8\xbd\x04\x57"
+ "\x8f\x24\xfd\xb9\x34\x50\x83\x2f\xf3\x46\x3e\xb9\xb0\x00\x1a\xf5"
+ "\xd3\x86\x7e\x8f\x77\xd1\x5d\x0e\x7c\xe1\xac\xde\xf8\x65\x1f\x4d"
+ "\xce\x7f\xa7\x3d\xaa\xcf\x26\xa7\x58\x69\x1e\x4c\xea\x68\x8a\xe5"
+ "\x89\xd1\xdc\x4d\xc7\xe0\x07\x42\xbf\x0c\x9d\x06\xd7\x51\xa2\x0b"
+ "\x7c\x83\x35\xe1\x85\xdf\xee\xfb\xa3\xee\x2f\x47\x5f\x8b\x70\x2b"
+ "\xe1\x37\xf3\x16\xf6\x27\x54\x8a\x33\x72\x49\xea\x53\x7d\x60\x0b"
+ "\x21\x90\x66\xe7\x9e\x56\x61\x5d\xd8\xdc\x59\xf0\xac\x2f\xd6\x49"
+ "\x6b\x85\x40\x08\x1f\xdf\x26\x25\x3b\x72\x44\xb0\xb8\x21\x2f\xb3"
+ "\xd7\x9b\x24\x30\x78\x26\x44\x07\xc3\x33\xd1\x4d\x03\x1b\xe1\xff"
+ "\xfd\xf5\x50\x8d\xca";
+static const unsigned long lzma_compressed_size = 229;
+
+/* lzop -c /tmp/plain.txt > /tmp/plain.lzo */
+static const char lzo_compressed[] =
+ "\x89\x4c\x5a\x4f\x00\x0d\x0a\x1a\x0a\x10\x30\x20\x60\x09\x40\x01"
+ "\x05\x03\x00\x00\x09\x00\x00\x81\xb4\x52\x09\x54\xf1\x00\x00\x00"
+ "\x00\x09\x70\x6c\x61\x69\x6e\x2e\x74\x78\x74\x65\xb1\x07\x9c\x00"
+ "\x00\x01\x5e\x00\x00\x01\x0f\xc3\xc7\x7a\xe0\x00\x16\x49\x20\x61"
+ "\x6d\x20\x61\x20\x68\x69\x67\x68\x6c\x79\x20\x63\x6f\x6d\x70\x72"
+ "\x65\x73\x73\x61\x62\x6c\x65\x20\x62\x69\x74\x20\x6f\x66\x20\x74"
+ "\x65\x78\x74\x2e\x0a\x20\x2f\x9c\x00\x00\x22\x54\x68\x65\x72\x65"
+ "\x20\x61\x72\x65\x20\x6d\x61\x6e\x79\x20\x6c\x69\x6b\x65\x20\x6d"
+ "\x65\x2c\x20\x62\x75\x74\x20\x74\x68\x69\x73\x20\x6f\x6e\x65\x20"
+ "\x69\x73\x20\x6d\x69\x6e\x65\x2e\x0a\x49\x66\x20\x49\x20\x77\x84"
+ "\x06\x0a\x6e\x79\x20\x73\x68\x6f\x72\x74\x65\x72\x2c\x20\x74\x90"
+ "\x08\x00\x08\x77\x6f\x75\x6c\x64\x6e\x27\x74\x20\x62\x65\x20\x6d"
+ "\x75\x63\x68\x20\x73\x65\x6e\x73\x65\x20\x69\x6e\x0a\xf8\x19\x02"
+ "\x69\x6e\x67\x20\x6d\x64\x02\x64\x06\x00\x5a\x20\x66\x69\x72\x73"
+ "\x74\x20\x70\x6c\x61\x63\x65\x2e\x20\x41\x74\x20\x6c\x65\x61\x73"
+ "\x74\x20\x77\x69\x74\x68\x20\x6c\x7a\x6f\x2c\x20\x61\x6e\x79\x77"
+ "\x61\x79\x2c\x0a\x77\x68\x69\x63\x68\x20\x61\x70\x70\x65\x61\x72"
+ "\x73\x20\x74\x6f\x20\x62\x65\x68\x61\x76\x65\x20\x70\x6f\x6f\x72"
+ "\x6c\x79\x20\x69\x6e\x20\x74\x68\x65\x20\x66\x61\x63\x65\x20\x6f"
+ "\x66\x20\x73\x68\x6f\x72\x74\x20\x74\x65\x78\x74\x0a\x6d\x65\x73"
+ "\x73\x61\x67\x65\x73\x2e\x0a\x11\x00\x00\x00\x00\x00\x00";
+static const unsigned long lzo_compressed_size = 334;
+
+/* lz4 -z /tmp/plain.txt > /tmp/plain.lz4 */
+static const char lz4_compressed[] =
+ "\x04\x22\x4d\x18\x64\x70\xb9\x01\x01\x00\x00\xff\x19\x49\x20\x61"
+ "\x6d\x20\x61\x20\x68\x69\x67\x68\x6c\x79\x20\x63\x6f\x6d\x70\x72"
+ "\x65\x73\x73\x61\x62\x6c\x65\x20\x62\x69\x74\x20\x6f\x66\x20\x74"
+ "\x65\x78\x74\x2e\x0a\x28\x00\x3d\xf1\x25\x54\x68\x65\x72\x65\x20"
+ "\x61\x72\x65\x20\x6d\x61\x6e\x79\x20\x6c\x69\x6b\x65\x20\x6d\x65"
+ "\x2c\x20\x62\x75\x74\x20\x74\x68\x69\x73\x20\x6f\x6e\x65\x20\x69"
+ "\x73\x20\x6d\x69\x6e\x65\x2e\x0a\x49\x66\x20\x49\x20\x77\x32\x00"
+ "\xd1\x6e\x79\x20\x73\x68\x6f\x72\x74\x65\x72\x2c\x20\x74\x45\x00"
+ "\xf4\x0b\x77\x6f\x75\x6c\x64\x6e\x27\x74\x20\x62\x65\x20\x6d\x75"
+ "\x63\x68\x20\x73\x65\x6e\x73\x65\x20\x69\x6e\x0a\xcf\x00\x50\x69"
+ "\x6e\x67\x20\x6d\x12\x00\x00\x32\x00\xf0\x11\x20\x66\x69\x72\x73"
+ "\x74\x20\x70\x6c\x61\x63\x65\x2e\x20\x41\x74\x20\x6c\x65\x61\x73"
+ "\x74\x20\x77\x69\x74\x68\x20\x6c\x7a\x6f\x2c\x63\x00\xf5\x14\x77"
+ "\x61\x79\x2c\x0a\x77\x68\x69\x63\x68\x20\x61\x70\x70\x65\x61\x72"
+ "\x73\x20\x74\x6f\x20\x62\x65\x68\x61\x76\x65\x20\x70\x6f\x6f\x72"
+ "\x6c\x79\x4e\x00\x30\x61\x63\x65\x27\x01\x01\x95\x00\x01\x2d\x01"
+ "\xb0\x0a\x6d\x65\x73\x73\x61\x67\x65\x73\x2e\x0a\x00\x00\x00\x00"
+ "\x9d\x12\x8c\x9d";
+static const unsigned long lz4_compressed_size = 276;
+
+
+#define TEST_BUFFER_SIZE 512
+
+typedef int (*mutate_func)(struct unit_test_state *uts, void *, unsigned long,
+ void *, unsigned long, unsigned long *);
+
+static int compress_using_gzip(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ unsigned long inout_size = out_max;
+
+ ret = gzip(out, &inout_size, in, in_size);
+ if (out_size)
+ *out_size = inout_size;
+
+ return ret;
+}
+
+static int uncompress_using_gzip(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ unsigned long inout_size = in_size;
+
+ ret = gunzip(out, out_max, in, &inout_size);
+ if (out_size)
+ *out_size = inout_size;
+
+ return ret;
+}
+
+static int compress_using_bzip2(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ /* There is no bzip2 compression in u-boot, so fake it. */
+ ut_asserteq(in_size, strlen(plain));
+ ut_asserteq(0, memcmp(plain, in, in_size));
+
+ if (bzip2_compressed_size > out_max)
+ return -1;
+
+ memcpy(out, bzip2_compressed, bzip2_compressed_size);
+ if (out_size)
+ *out_size = bzip2_compressed_size;
+
+ return 0;
+}
+
+static int uncompress_using_bzip2(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ unsigned int inout_size = out_max;
+
+ ret = BZ2_bzBuffToBuffDecompress(out, &inout_size, in, in_size,
+ CONFIG_SYS_MALLOC_LEN < (4096 * 1024), 0);
+ if (out_size)
+ *out_size = inout_size;
+
+ return (ret != BZ_OK);
+}
+
+static int compress_using_lzma(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ /* There is no lzma compression in u-boot, so fake it. */
+ ut_asserteq(in_size, strlen(plain));
+ ut_asserteq(0, memcmp(plain, in, in_size));
+
+ if (lzma_compressed_size > out_max)
+ return -1;
+
+ memcpy(out, lzma_compressed, lzma_compressed_size);
+ if (out_size)
+ *out_size = lzma_compressed_size;
+
+ return 0;
+}
+
+static int uncompress_using_lzma(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ SizeT inout_size = out_max;
+
+ ret = lzmaBuffToBuffDecompress(out, &inout_size, in, in_size);
+ if (out_size)
+ *out_size = inout_size;
+
+ return (ret != SZ_OK);
+}
+
+static int compress_using_lzo(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ /* There is no lzo compression in u-boot, so fake it. */
+ ut_asserteq(in_size, strlen(plain));
+ ut_asserteq(0, memcmp(plain, in, in_size));
+
+ if (lzo_compressed_size > out_max)
+ return -1;
+
+ memcpy(out, lzo_compressed, lzo_compressed_size);
+ if (out_size)
+ *out_size = lzo_compressed_size;
+
+ return 0;
+}
+
+static int uncompress_using_lzo(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ size_t input_size = in_size;
+ size_t output_size = out_max;
+
+ ret = lzop_decompress(in, input_size, out, &output_size);
+ if (out_size)
+ *out_size = output_size;
+
+ return (ret != LZO_E_OK);
+}
+
+static int compress_using_lz4(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ /* There is no lz4 compression in u-boot, so fake it. */
+ ut_asserteq(in_size, strlen(plain));
+ ut_asserteq(0, memcmp(plain, in, in_size));
+
+ if (lz4_compressed_size > out_max)
+ return -1;
+
+ memcpy(out, lz4_compressed, lz4_compressed_size);
+ if (out_size)
+ *out_size = lz4_compressed_size;
+
+ return 0;
+}
+
+static int uncompress_using_lz4(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ int ret;
+ size_t input_size = in_size;
+ size_t output_size = out_max;
+
+ ret = ulz4fn(in, input_size, out, &output_size);
+ if (out_size)
+ *out_size = output_size;
+
+ return (ret != 0);
+}
+
+#define errcheck(statement) if (!(statement)) { \
+ fprintf(stderr, "\tFailed: %s\n", #statement); \
+ ret = 1; \
+ goto out; \
+}
+
+struct buf_state {
+ ulong orig_size;
+ ulong compressed_size;
+ ulong uncompressed_size;
+ void *orig_buf;
+ void *compressed_buf;
+ void *uncompressed_buf;
+ void *compare_buf;
+};
+
+static int run_test_internal(struct unit_test_state *uts, char *name,
+ mutate_func compress, mutate_func uncompress,
+ struct buf_state *buf)
+{
+ int ret;
+
+ /* Compress works as expected. */
+ printf("\torig_size:%lu\n", buf->orig_size);
+ memset(buf->compressed_buf, 'A', TEST_BUFFER_SIZE);
+ errcheck(compress(uts, buf->orig_buf, buf->orig_size,
+ buf->compressed_buf, buf->compressed_size,
+ &buf->compressed_size) == 0);
+ printf("\tcompressed_size:%lu\n", buf->compressed_size);
+ errcheck(buf->compressed_size > 0);
+ errcheck(buf->compressed_size < buf->orig_size);
+ errcheck(((char *)buf->compressed_buf)[buf->compressed_size - 1] !=
+ 'A');
+ errcheck(((char *)buf->compressed_buf)[buf->compressed_size] == 'A');
+
+ /* Uncompresses with space remaining. */
+ errcheck(uncompress(uts, buf->compressed_buf, buf->compressed_size,
+ buf->uncompressed_buf, buf->uncompressed_size,
+ &buf->uncompressed_size) == 0);
+ printf("\tuncompressed_size:%lu\n", buf->uncompressed_size);
+ errcheck(buf->uncompressed_size == buf->orig_size);
+ errcheck(memcmp(buf->orig_buf, buf->uncompressed_buf,
+ buf->orig_size) == 0);
+
+ /* Uncompresses with exactly the right size output buffer. */
+ memset(buf->uncompressed_buf, 'A', TEST_BUFFER_SIZE);
+ errcheck(uncompress(uts, buf->compressed_buf, buf->compressed_size,
+ buf->uncompressed_buf, buf->orig_size,
+ &buf->uncompressed_size) == 0);
+ errcheck(buf->uncompressed_size == buf->orig_size);
+ errcheck(memcmp(buf->orig_buf, buf->uncompressed_buf,
+ buf->orig_size) == 0);
+ errcheck(((char *)buf->uncompressed_buf)[buf->orig_size] == 'A');
+
+ /* Make sure compression does not over-run. */
+ memset(buf->compare_buf, 'A', TEST_BUFFER_SIZE);
+ ret = compress(uts, buf->orig_buf, buf->orig_size,
+ buf->compare_buf, buf->compressed_size - 1,
+ NULL);
+ errcheck(((char *)buf->compare_buf)[buf->compressed_size] == 'A');
+ errcheck(ret != 0);
+ printf("\tcompress does not overrun\n");
+
+ /* Make sure decompression does not over-run. */
+ memset(buf->compare_buf, 'A', TEST_BUFFER_SIZE);
+ ret = uncompress(uts, buf->compressed_buf, buf->compressed_size,
+ buf->compare_buf, buf->uncompressed_size - 1,
+ NULL);
+ errcheck(((char *)buf->compare_buf)[buf->uncompressed_size - 1] == 'A');
+ errcheck(ret != 0);
+ printf("\tuncompress does not overrun\n");
+
+ /* Got here, everything is fine. */
+ ret = 0;
+
+out:
+ return ret;
+}
+
+static int run_test(struct unit_test_state *uts, char *name,
+ mutate_func compress, mutate_func uncompress)
+{
+ struct buf_state sbuf, *buf = &sbuf;
+ int ret;
+
+ printf(" testing %s ...\n", name);
+
+ buf->orig_buf = (void *)plain;
+ buf->orig_size = strlen(buf->orig_buf); /* Trailing NUL not included */
+ errcheck(buf->orig_size > 0);
+
+ buf->compressed_size = TEST_BUFFER_SIZE;
+ buf->uncompressed_size = TEST_BUFFER_SIZE;
+ buf->compressed_buf = malloc(buf->compressed_size);
+ errcheck(buf->compressed_buf);
+ buf->uncompressed_buf = malloc(buf->uncompressed_size);
+ errcheck(buf->uncompressed_buf);
+ buf->compare_buf = malloc(buf->uncompressed_size);
+ errcheck(buf->compare_buf);
+
+ ret = run_test_internal(uts, name, compress, uncompress, buf);
+out:
+ printf(" %s: %s\n", name, ret == 0 ? "ok" : "FAILED");
+
+ free(buf->compare_buf);
+ free(buf->uncompressed_buf);
+ free(buf->compressed_buf);
+
+ return ret;
+}
+
+static int compression_test_gzip(struct unit_test_state *uts)
+{
+ return run_test(uts, "gzip", compress_using_gzip,
+ uncompress_using_gzip);
+}
+COMPRESSION_TEST(compression_test_gzip, 0);
+
+static int compression_test_bzip2(struct unit_test_state *uts)
+{
+ return run_test(uts, "bzip2", compress_using_bzip2,
+ uncompress_using_bzip2);
+}
+COMPRESSION_TEST(compression_test_bzip2, 0);
+
+static int compression_test_lzma(struct unit_test_state *uts)
+{
+ return run_test(uts, "lzma", compress_using_lzma,
+ uncompress_using_lzma);
+}
+COMPRESSION_TEST(compression_test_lzma, 0);
+
+static int compression_test_lzo(struct unit_test_state *uts)
+{
+ return run_test(uts, "lzo", compress_using_lzo, uncompress_using_lzo);
+}
+COMPRESSION_TEST(compression_test_lzo, 0);
+
+static int compression_test_lz4(struct unit_test_state *uts)
+{
+ return run_test(uts, "lz4", compress_using_lz4, uncompress_using_lz4);
+}
+COMPRESSION_TEST(compression_test_lz4, 0);
+
+static int compress_using_none(struct unit_test_state *uts,
+ void *in, unsigned long in_size,
+ void *out, unsigned long out_max,
+ unsigned long *out_size)
+{
+ /* Here we just copy */
+ memcpy(out, in, in_size);
+ *out_size = in_size;
+
+ return 0;
+}
+
+/**
+ * run_bootm_test() - Run tests on the bootm decopmression function
+ *
+ * @comp_type: Compression type to test
+ * @compress: Our function to compress data
+ * @return 0 if OK, non-zero on failure
+ */
+static int run_bootm_test(struct unit_test_state *uts, int comp_type,
+ mutate_func compress)
+{
+ ulong compress_size = 1024;
+ void *compress_buff;
+ int unc_len;
+ int err = 0;
+ const ulong image_start = 0;
+ const ulong load_addr = 0x1000;
+ ulong load_end;
+
+ printf("Testing: %s\n", genimg_get_comp_name(comp_type));
+ compress_buff = map_sysmem(image_start, 0);
+ unc_len = strlen(plain);
+ compress(uts, (void *)plain, unc_len, compress_buff, compress_size,
+ &compress_size);
+ err = image_decomp(comp_type, load_addr, image_start,
+ IH_TYPE_KERNEL, map_sysmem(load_addr, 0),
+ compress_buff, compress_size, unc_len,
+ &load_end);
+ ut_assertok(err);
+ err = image_decomp(comp_type, load_addr, image_start,
+ IH_TYPE_KERNEL, map_sysmem(load_addr, 0),
+ compress_buff, compress_size, unc_len - 1,
+ &load_end);
+ ut_assert(err);
+
+ /* We can't detect corruption when not decompressing */
+ if (comp_type == IH_COMP_NONE)
+ return 0;
+ memset(compress_buff + compress_size / 2, '\x49',
+ compress_size / 2);
+ err = image_decomp(comp_type, load_addr, image_start,
+ IH_TYPE_KERNEL, map_sysmem(load_addr, 0),
+ compress_buff, compress_size, 0x10000,
+ &load_end);
+ ut_assert(err);
+
+ return 0;
+}
+
+static int compression_test_bootm_gzip(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_GZIP, compress_using_gzip);
+}
+COMPRESSION_TEST(compression_test_bootm_gzip, 0);
+
+static int compression_test_bootm_bzip2(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_BZIP2, compress_using_bzip2);
+}
+COMPRESSION_TEST(compression_test_bootm_bzip2, 0);
+
+static int compression_test_bootm_lzma(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_LZMA, compress_using_lzma);
+}
+COMPRESSION_TEST(compression_test_bootm_lzma, 0);
+
+static int compression_test_bootm_lzo(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_LZO, compress_using_lzo);
+}
+COMPRESSION_TEST(compression_test_bootm_lzo, 0);
+
+static int compression_test_bootm_lz4(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_LZ4, compress_using_lz4);
+}
+COMPRESSION_TEST(compression_test_bootm_lz4, 0);
+
+static int compression_test_bootm_none(struct unit_test_state *uts)
+{
+ return run_bootm_test(uts, IH_COMP_NONE, compress_using_none);
+}
+COMPRESSION_TEST(compression_test_bootm_none, 0);
+
+int do_ut_compression(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test,
+ compression_test);
+ const int n_ents = ll_entry_count(struct unit_test, compression_test);
+
+ return cmd_ut_category("compression", tests, n_ents, argc, argv);
+}
diff --git a/test/dm/Kconfig b/test/dm/Kconfig
new file mode 100644
index 00000000..e5b341e5
--- /dev/null
+++ b/test/dm/Kconfig
@@ -0,0 +1,8 @@
+config UT_DM
+ bool "Enable driver model unit test command"
+ depends on SANDBOX && UNIT_TEST
+ help
+ This enables the 'ut dm' command which runs a series of unit
+ tests on the driver model code. Each subsystem (uclass) is tested.
+ If all is well then all tests pass although there will be a few
+ messages printed along the way.
diff --git a/test/dm/Makefile b/test/dm/Makefile
new file mode 100644
index 00000000..0c2fd5cb
--- /dev/null
+++ b/test/dm/Makefile
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright (c) 2013 Google, Inc
+
+obj-$(CONFIG_UT_DM) += bus.o
+obj-$(CONFIG_UT_DM) += nop.o
+obj-$(CONFIG_UT_DM) += test-driver.o
+obj-$(CONFIG_UT_DM) += test-fdt.o
+obj-$(CONFIG_UT_DM) += test-main.o
+obj-$(CONFIG_UT_DM) += test-uclass.o
+
+# Tests for particular subsystems - when enabling driver model for a new
+# subsystem you must add sandbox tests here.
+obj-$(CONFIG_UT_DM) += core.o
+ifneq ($(CONFIG_SANDBOX),)
+obj-$(CONFIG_SOUND) += audio.o
+obj-$(CONFIG_BLK) += blk.o
+obj-$(CONFIG_BOARD) += board.o
+obj-$(CONFIG_DM_BOOTCOUNT) += bootcount.o
+obj-$(CONFIG_CLK) += clk.o clk_ccf.o
+obj-$(CONFIG_VIDEO_MIPI_DSI) += dsi_host.o
+obj-$(CONFIG_DM_ETH) += eth.o
+obj-$(CONFIG_FIRMWARE) += firmware.o
+obj-$(CONFIG_DM_GPIO) += gpio.o
+obj-$(CONFIG_DM_HWSPINLOCK) += hwspinlock.o
+obj-$(CONFIG_DM_I2C) += i2c.o
+obj-$(CONFIG_SOUND) += i2s.o
+obj-$(CONFIG_LED) += led.o
+obj-$(CONFIG_DM_MAILBOX) += mailbox.o
+obj-$(CONFIG_DM_MMC) += mmc.o
+obj-y += ofnode.o
+obj-$(CONFIG_OSD) += osd.o
+obj-$(CONFIG_DM_VIDEO) += panel.o
+obj-$(CONFIG_DM_PCI) += pci.o
+obj-$(CONFIG_PCI_ENDPOINT) += pci_ep.o
+obj-$(CONFIG_PCH) += pch.o
+obj-$(CONFIG_PHY) += phy.o
+obj-$(CONFIG_POWER_DOMAIN) += power-domain.o
+obj-$(CONFIG_DM_PWM) += pwm.o
+obj-$(CONFIG_RAM) += ram.o
+obj-y += regmap.o
+obj-$(CONFIG_REMOTEPROC) += remoteproc.o
+obj-$(CONFIG_DM_RESET) += reset.o
+obj-$(CONFIG_SYSRESET) += sysreset.o
+obj-$(CONFIG_DM_RTC) += rtc.o
+obj-$(CONFIG_DM_SPI_FLASH) += sf.o
+obj-$(CONFIG_SMEM) += smem.o
+obj-$(CONFIG_DM_SPI) += spi.o
+obj-y += syscon.o
+obj-$(CONFIG_DM_USB) += usb.o
+obj-$(CONFIG_DM_PMIC) += pmic.o
+obj-$(CONFIG_DM_REGULATOR) += regulator.o
+obj-$(CONFIG_TIMER) += timer.o
+obj-$(CONFIG_DM_VIDEO) += video.o
+obj-$(CONFIG_ADC) += adc.o
+obj-$(CONFIG_SPMI) += spmi.o
+obj-$(CONFIG_WDT) += wdt.o
+obj-$(CONFIG_AXI) += axi.o
+obj-$(CONFIG_MISC) += misc.o
+obj-$(CONFIG_DM_SERIAL) += serial.o
+obj-$(CONFIG_CPU) += cpu.o
+obj-$(CONFIG_SOUND) += sound.o
+obj-$(CONFIG_TEE) += tee.o
+obj-$(CONFIG_VIRTIO_SANDBOX) += virtio.o
+obj-$(CONFIG_DMA) += dma.o
+obj-$(CONFIG_DM_MDIO) += mdio.o
+obj-$(CONFIG_DM_MDIO_MUX) += mdio_mux.o
+endif
diff --git a/test/dm/adc.c b/test/dm/adc.c
new file mode 100644
index 00000000..da7bd4bf
--- /dev/null
+++ b/test/dm/adc.c
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Tests for the driver model ADC API
+ *
+ * Copyright (c) 2015 Samsung Electronics
+ * Przemyslaw Marczak <p.marczak@samsung.com>
+ */
+
+#include <common.h>
+#include <adc.h>
+#include <dm.h>
+#include <dm/root.h>
+#include <dm/util.h>
+#include <dm/test.h>
+#include <errno.h>
+#include <fdtdec.h>
+#include <power/regulator.h>
+#include <power/sandbox_pmic.h>
+#include <sandbox-adc.h>
+#include <test/ut.h>
+
+static int dm_test_adc_bind(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ unsigned int channel_mask;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+ ut_asserteq_str(SANDBOX_ADC_DEVNAME, dev->name);
+
+ ut_assertok(adc_channel_mask(dev, &channel_mask));
+ ut_asserteq((1 << SANDBOX_ADC_CHANNELS) - 1, channel_mask);
+
+ return 0;
+}
+DM_TEST(dm_test_adc_bind, DM_TESTF_SCAN_FDT);
+
+static int dm_test_adc_wrong_channel_selection(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+ ut_asserteq(-EINVAL, adc_start_channel(dev, SANDBOX_ADC_CHANNELS));
+
+ return 0;
+}
+DM_TEST(dm_test_adc_wrong_channel_selection, DM_TESTF_SCAN_FDT);
+
+static int dm_test_adc_supply(struct unit_test_state *uts)
+{
+ struct udevice *supply;
+ struct udevice *dev;
+ int uV;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+
+ /* Test Vss value - predefined 0 uV */
+ ut_assertok(adc_vss_value(dev, &uV));
+ ut_asserteq(SANDBOX_ADC_VSS_VALUE, uV);
+
+ /* Test Vdd initial value - buck2 */
+ ut_assertok(adc_vdd_value(dev, &uV));
+ ut_asserteq(SANDBOX_BUCK2_INITIAL_EXPECTED_UV, uV);
+
+ /* Change Vdd value - buck2 manual preset */
+ ut_assertok(regulator_get_by_devname(SANDBOX_BUCK2_DEVNAME, &supply));
+ ut_assertok(regulator_set_value(supply, SANDBOX_BUCK2_SET_UV));
+ ut_asserteq(SANDBOX_BUCK2_SET_UV, regulator_get_value(supply));
+
+ /* Update ADC platdata and get new Vdd value */
+ ut_assertok(adc_vdd_value(dev, &uV));
+ ut_asserteq(SANDBOX_BUCK2_SET_UV, uV);
+
+ /* Disable buck2 and test ADC supply enable function */
+ ut_assertok(regulator_set_enable(supply, false));
+ ut_asserteq(false, regulator_get_enable(supply));
+ /* adc_start_channel() should enable the supply regulator */
+ ut_assertok(adc_start_channel(dev, 0));
+ ut_asserteq(true, regulator_get_enable(supply));
+
+ return 0;
+}
+DM_TEST(dm_test_adc_supply, DM_TESTF_SCAN_FDT);
+
+struct adc_channel adc_channel_test_data[] = {
+ { 0, SANDBOX_ADC_CHANNEL0_DATA },
+ { 1, SANDBOX_ADC_CHANNEL1_DATA },
+ { 2, SANDBOX_ADC_CHANNEL2_DATA },
+ { 3, SANDBOX_ADC_CHANNEL3_DATA },
+};
+
+static int dm_test_adc_single_channel_conversion(struct unit_test_state *uts)
+{
+ struct adc_channel *tdata = adc_channel_test_data;
+ unsigned int i, data;
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+ /* Test each ADC channel's value */
+ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) {
+ ut_assertok(adc_start_channel(dev, tdata->id));
+ ut_assertok(adc_channel_data(dev, tdata->id, &data));
+ ut_asserteq(tdata->data, data);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_adc_single_channel_conversion, DM_TESTF_SCAN_FDT);
+
+static int dm_test_adc_multi_channel_conversion(struct unit_test_state *uts)
+{
+ struct adc_channel channels[SANDBOX_ADC_CHANNELS];
+ struct udevice *dev;
+ struct adc_channel *tdata = adc_channel_test_data;
+ unsigned int i, channel_mask;
+
+ channel_mask = ADC_CHANNEL(0) | ADC_CHANNEL(1) |
+ ADC_CHANNEL(2) | ADC_CHANNEL(3);
+
+ /* Start multi channel conversion */
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+ ut_assertok(adc_start_channels(dev, channel_mask));
+ ut_assertok(adc_channels_data(dev, channel_mask, channels));
+
+ /* Compare the expected and returned conversion data. */
+ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++)
+ ut_asserteq(tdata->data, channels[i].data);
+
+ return 0;
+}
+DM_TEST(dm_test_adc_multi_channel_conversion, DM_TESTF_SCAN_FDT);
+
+static int dm_test_adc_single_channel_shot(struct unit_test_state *uts)
+{
+ struct adc_channel *tdata = adc_channel_test_data;
+ unsigned int i, data;
+
+ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) {
+ /* Start single channel conversion */
+ ut_assertok(adc_channel_single_shot("adc@0", tdata->id, &data));
+ /* Compare the expected and returned conversion data. */
+ ut_asserteq(tdata->data, data);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_adc_single_channel_shot, DM_TESTF_SCAN_FDT);
+
+static int dm_test_adc_multi_channel_shot(struct unit_test_state *uts)
+{
+ struct adc_channel channels[SANDBOX_ADC_CHANNELS];
+ struct adc_channel *tdata = adc_channel_test_data;
+ unsigned int i, channel_mask;
+
+ channel_mask = ADC_CHANNEL(0) | ADC_CHANNEL(1) |
+ ADC_CHANNEL(2) | ADC_CHANNEL(3);
+
+ /* Start single call and multi channel conversion */
+ ut_assertok(adc_channels_single_shot("adc@0", channel_mask, channels));
+
+ /* Compare the expected and returned conversion data. */
+ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++)
+ ut_asserteq(tdata->data, channels[i].data);
+
+ return 0;
+}
+DM_TEST(dm_test_adc_multi_channel_shot, DM_TESTF_SCAN_FDT);
+
+static const int dm_test_adc_uV_data[SANDBOX_ADC_CHANNELS] = {
+ ((u64)SANDBOX_ADC_CHANNEL0_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) /
+ SANDBOX_ADC_DATA_MASK,
+ ((u64)SANDBOX_ADC_CHANNEL1_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) /
+ SANDBOX_ADC_DATA_MASK,
+ ((u64)SANDBOX_ADC_CHANNEL2_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) /
+ SANDBOX_ADC_DATA_MASK,
+ ((u64)SANDBOX_ADC_CHANNEL3_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) /
+ SANDBOX_ADC_DATA_MASK,
+};
+
+static int dm_test_adc_raw_to_uV(struct unit_test_state *uts)
+{
+ struct adc_channel *tdata = adc_channel_test_data;
+ unsigned int i, data;
+ struct udevice *dev;
+ int uV;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev));
+ /* Test each ADC channel's value in microvolts */
+ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) {
+ ut_assertok(adc_start_channel(dev, tdata->id));
+ ut_assertok(adc_channel_data(dev, tdata->id, &data));
+ ut_assertok(adc_raw_to_uV(dev, data, &uV));
+ ut_asserteq(dm_test_adc_uV_data[i], uV);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_adc_raw_to_uV, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/audio.c b/test/dm/audio.c
new file mode 100644
index 00000000..77c3a362
--- /dev/null
+++ b/test/dm/audio.c
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2018 Google LLC
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <audio_codec.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <asm/test.h>
+
+/* Basic test of the audio codec uclass */
+static int dm_test_audio(struct unit_test_state *uts)
+{
+ int interface, rate, mclk_freq, bits_per_sample;
+ struct udevice *dev;
+ uint channels;
+
+ /* check probe success */
+ ut_assertok(uclass_first_device_err(UCLASS_AUDIO_CODEC, &dev));
+ ut_assertok(audio_codec_set_params(dev, 1, 2, 3, 4, 5));
+ sandbox_get_codec_params(dev, &interface, &rate, &mclk_freq,
+ &bits_per_sample, &channels);
+ ut_asserteq(1, interface);
+ ut_asserteq(2, rate);
+ ut_asserteq(3, mclk_freq);
+ ut_asserteq(4, bits_per_sample);
+ ut_asserteq(5, channels);
+
+ return 0;
+}
+DM_TEST(dm_test_audio, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/axi.c b/test/dm/axi.c
new file mode 100644
index 00000000..e234ab82
--- /dev/null
+++ b/test/dm/axi.c
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <axi.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <asm/axi.h>
+
+/* Test that sandbox AXI works correctly */
+static int dm_test_axi_base(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+
+ ut_assertok(uclass_get_device(UCLASS_AXI, 0, &bus));
+
+ return 0;
+}
+
+DM_TEST(dm_test_axi_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that sandbox PCI bus numbering works correctly */
+static int dm_test_axi_busnum(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_AXI, 0, &bus));
+
+ return 0;
+}
+
+DM_TEST(dm_test_axi_busnum, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can use the store device correctly */
+static int dm_test_axi_store(struct unit_test_state *uts)
+{
+ struct udevice *store;
+ u8 tdata1[] = {0x55, 0x66, 0x77, 0x88};
+ u8 tdata2[] = {0xaa, 0xbb, 0xcc, 0xdd};
+ u32 val;
+ u8 *data;
+
+ /* Check that asking for the device automatically fires up AXI */
+ ut_assertok(uclass_get_device(UCLASS_AXI_EMUL, 0, &store));
+ ut_assert(device_active(store));
+
+ axi_get_store(store, &data);
+
+ /* Test reading */
+ memcpy(data, tdata1, ARRAY_SIZE(tdata1));
+ axi_read(store, 0, &val, AXI_SIZE_32);
+ ut_asserteq(0x55667788, val);
+
+ memcpy(data + 3, tdata2, ARRAY_SIZE(tdata2));
+ axi_read(store, 3, &val, AXI_SIZE_32);
+ ut_asserteq(0xaabbccdd, val);
+
+ /* Reset data store */
+ memset(data, 0, 16);
+
+ /* Test writing */
+ val = 0x55667788;
+ axi_write(store, 0, &val, AXI_SIZE_32);
+ ut_asserteq(0, memcmp(data, tdata1, ARRAY_SIZE(tdata1)));
+
+ val = 0xaabbccdd;
+ axi_write(store, 3, &val, AXI_SIZE_32);
+ ut_asserteq(0, memcmp(data + 3, tdata2, ARRAY_SIZE(tdata1)));
+
+ return 0;
+}
+
+DM_TEST(dm_test_axi_store, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/blk.c b/test/dm/blk.c
new file mode 100644
index 00000000..9c71adc6
--- /dev/null
+++ b/test/dm/blk.c
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <usb.h>
+#include <asm/state.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* Test that block devices can be created */
+static int dm_test_blk_base(struct unit_test_state *uts)
+{
+ struct udevice *blk1, *blk3, *dev;
+
+ /* Make sure there are no block devices */
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_BLK, 0, &dev));
+
+ /* Create two, one the parent of the other */
+ ut_assertok(blk_create_device(gd->dm_root, "sandbox_host_blk", "test",
+ IF_TYPE_HOST, 1, 512, 2, &blk1));
+ ut_assertok(blk_create_device(blk1, "sandbox_host_blk", "test",
+ IF_TYPE_HOST, 3, 512, 2, &blk3));
+
+ /* Check we can find them */
+ ut_asserteq(-ENODEV, blk_get_device(IF_TYPE_HOST, 0, &dev));
+ ut_assertok(blk_get_device(IF_TYPE_HOST, 1, &dev));
+ ut_asserteq_ptr(blk1, dev);
+ ut_assertok(blk_get_device(IF_TYPE_HOST, 3, &dev));
+ ut_asserteq_ptr(blk3, dev);
+
+ /* Check we can iterate */
+ ut_assertok(blk_first_device(IF_TYPE_HOST, &dev));
+ ut_asserteq_ptr(blk1, dev);
+ ut_assertok(blk_next_device(&dev));
+ ut_asserteq_ptr(blk3, dev);
+
+ return 0;
+}
+DM_TEST(dm_test_blk_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int count_blk_devices(void)
+{
+ struct udevice *blk;
+ struct uclass *uc;
+ int count = 0;
+ int ret;
+
+ ret = uclass_get(UCLASS_BLK, &uc);
+ if (ret)
+ return ret;
+
+ uclass_foreach_dev(blk, uc)
+ count++;
+
+ return count;
+}
+
+/* Test that block devices work correctly with USB */
+static int dm_test_blk_usb(struct unit_test_state *uts)
+{
+ struct udevice *usb_dev, *dev;
+ struct blk_desc *dev_desc;
+
+ /* Get a flash device */
+ state_set_skip_delays(true);
+ ut_assertok(usb_init());
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 0, &usb_dev));
+ ut_assertok(blk_get_device_by_str("usb", "0", &dev_desc));
+
+ /* The parent should be a block device */
+ ut_assertok(blk_get_device(IF_TYPE_USB, 0, &dev));
+ ut_asserteq_ptr(usb_dev, dev_get_parent(dev));
+
+ /* Check we have one block device for each mass storage device */
+ ut_asserteq(6, count_blk_devices());
+
+ /* Now go around again, making sure the old devices were unbound */
+ ut_assertok(usb_stop());
+ ut_assertok(usb_init());
+ ut_asserteq(6, count_blk_devices());
+ ut_assertok(usb_stop());
+
+ return 0;
+}
+DM_TEST(dm_test_blk_usb, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can find block devices without probing them */
+static int dm_test_blk_find(struct unit_test_state *uts)
+{
+ struct udevice *blk, *dev;
+
+ ut_assertok(blk_create_device(gd->dm_root, "sandbox_host_blk", "test",
+ IF_TYPE_HOST, 1, 512, 2, &blk));
+ ut_asserteq(-ENODEV, blk_find_device(IF_TYPE_HOST, 0, &dev));
+ ut_assertok(blk_find_device(IF_TYPE_HOST, 1, &dev));
+ ut_asserteq_ptr(blk, dev);
+ ut_asserteq(false, device_active(dev));
+
+ /* Now activate it */
+ ut_assertok(blk_get_device(IF_TYPE_HOST, 1, &dev));
+ ut_asserteq_ptr(blk, dev);
+ ut_asserteq(true, device_active(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_blk_find, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that block device numbering works as expected */
+static int dm_test_blk_devnum(struct unit_test_state *uts)
+{
+ struct udevice *dev, *mmc_dev, *parent;
+ int i;
+
+ /*
+ * Probe the devices, with the first one being probed last. This is the
+ * one with no alias / sequence numnber.
+ */
+ ut_assertok(uclass_get_device(UCLASS_MMC, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MMC, 2, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MMC, 0, &dev));
+ for (i = 0; i < 3; i++) {
+ struct blk_desc *desc;
+
+ /* Check that the bblock device is attached */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_MMC, i, &mmc_dev));
+ ut_assertok(blk_find_device(IF_TYPE_MMC, i, &dev));
+ parent = dev_get_parent(dev);
+ ut_asserteq_ptr(parent, mmc_dev);
+ ut_asserteq(trailing_strtol(mmc_dev->name), i);
+
+ /*
+ * Check that the block device devnum matches its parent's
+ * sequence number
+ */
+ desc = dev_get_uclass_platdata(dev);
+ ut_asserteq(desc->devnum, i);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_blk_devnum, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can get a block from its parent */
+static int dm_test_blk_get_from_parent(struct unit_test_state *uts)
+{
+ struct udevice *dev, *blk;
+
+ ut_assertok(uclass_get_device(UCLASS_MMC, 0, &dev));
+ ut_assertok(blk_get_from_parent(dev, &blk));
+
+ ut_assertok(uclass_get_device(UCLASS_I2C, 0, &dev));
+ ut_asserteq(-ENOTBLK, blk_get_from_parent(dev, &blk));
+
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 0, &dev));
+ ut_asserteq(-ENODEV, blk_get_from_parent(dev, &blk));
+
+ return 0;
+}
+DM_TEST(dm_test_blk_get_from_parent, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/board.c b/test/dm/board.c
new file mode 100644
index 00000000..0f267a19
--- /dev/null
+++ b/test/dm/board.c
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <board.h>
+#include <test/ut.h>
+
+#include "../../drivers/board/sandbox.h"
+
+static int dm_test_board(struct unit_test_state *uts)
+{
+ struct udevice *board;
+ bool called_detect;
+ char str[64];
+ int i;
+
+ board_get(&board);
+ ut_assert(board);
+
+ board_get_bool(board, BOOL_CALLED_DETECT, &called_detect);
+ ut_assert(!called_detect);
+
+ board_detect(board);
+
+ board_get_bool(board, BOOL_CALLED_DETECT, &called_detect);
+ ut_assert(called_detect);
+
+ board_get_str(board, STR_VACATIONSPOT, sizeof(str), str);
+ ut_assertok(strcmp(str, "R'lyeh"));
+
+ board_get_int(board, INT_TEST1, &i);
+ ut_asserteq(0, i);
+
+ board_get_int(board, INT_TEST2, &i);
+ ut_asserteq(100, i);
+
+ board_get_str(board, STR_VACATIONSPOT, sizeof(str), str);
+ ut_assertok(strcmp(str, "Carcosa"));
+
+ board_get_int(board, INT_TEST1, &i);
+ ut_asserteq(1, i);
+
+ board_get_int(board, INT_TEST2, &i);
+ ut_asserteq(99, i);
+
+ board_get_str(board, STR_VACATIONSPOT, sizeof(str), str);
+ ut_assertok(strcmp(str, "Yuggoth"));
+
+ return 0;
+}
+
+DM_TEST(dm_test_board, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/bootcount.c b/test/dm/bootcount.c
new file mode 100644
index 00000000..0817b7d3
--- /dev/null
+++ b/test/dm/bootcount.c
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) 2018 Theobroma Systems Design und Consulting GmbH
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <bootcount.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+static int dm_test_bootcount(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u32 val;
+
+ ut_assertok(uclass_get_device(UCLASS_BOOTCOUNT, 0, &dev));
+ ut_assertok(dm_bootcount_set(dev, 0));
+ ut_assertok(dm_bootcount_get(dev, &val));
+ ut_assert(val == 0);
+ ut_assertok(dm_bootcount_set(dev, 0xab));
+ ut_assertok(dm_bootcount_get(dev, &val));
+ ut_assert(val == 0xab);
+
+ return 0;
+}
+
+DM_TEST(dm_test_bootcount, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
diff --git a/test/dm/bus.c b/test/dm/bus.c
new file mode 100644
index 00000000..1ad45adb
--- /dev/null
+++ b/test/dm/bus.c
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2014 Google, Inc
+ */
+
+#include <common.h>
+#ifdef CONFIG_SANDBOX
+#include <os.h>
+#endif
+#include <dm.h>
+#include <dm/device.h>
+#include <dm/device-internal.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <dm/util.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+struct dm_test_parent_platdata {
+ int count;
+ int bind_flag;
+ int uclass_bind_flag;
+};
+
+enum {
+ FLAG_CHILD_PROBED = 10,
+ FLAG_CHILD_REMOVED = -7,
+};
+
+static struct dm_test_state *test_state;
+
+static int testbus_drv_probe(struct udevice *dev)
+{
+ return dm_scan_fdt_dev(dev);
+}
+
+static int testbus_child_post_bind(struct udevice *dev)
+{
+ struct dm_test_parent_platdata *plat;
+
+ plat = dev_get_parent_platdata(dev);
+ plat->bind_flag = 1;
+ plat->uclass_bind_flag = 2;
+
+ return 0;
+}
+
+static int testbus_child_pre_probe(struct udevice *dev)
+{
+ struct dm_test_parent_data *parent_data = dev_get_parent_priv(dev);
+
+ parent_data->flag += FLAG_CHILD_PROBED;
+
+ return 0;
+}
+
+static int testbus_child_pre_probe_uclass(struct udevice *dev)
+{
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ priv->uclass_flag++;
+
+ return 0;
+}
+
+static int testbus_child_post_probe_uclass(struct udevice *dev)
+{
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ priv->uclass_postp++;
+
+ return 0;
+}
+
+static int testbus_child_post_remove(struct udevice *dev)
+{
+ struct dm_test_parent_data *parent_data = dev_get_parent_priv(dev);
+ struct dm_test_state *dms = test_state;
+
+ parent_data->flag += FLAG_CHILD_REMOVED;
+ if (dms)
+ dms->removed = dev;
+
+ return 0;
+}
+
+static const struct udevice_id testbus_ids[] = {
+ {
+ .compatible = "denx,u-boot-test-bus",
+ .data = DM_TEST_TYPE_FIRST },
+ { }
+};
+
+U_BOOT_DRIVER(testbus_drv) = {
+ .name = "testbus_drv",
+ .of_match = testbus_ids,
+ .id = UCLASS_TEST_BUS,
+ .probe = testbus_drv_probe,
+ .child_post_bind = testbus_child_post_bind,
+ .priv_auto_alloc_size = sizeof(struct dm_test_priv),
+ .platdata_auto_alloc_size = sizeof(struct dm_test_pdata),
+ .per_child_auto_alloc_size = sizeof(struct dm_test_parent_data),
+ .per_child_platdata_auto_alloc_size =
+ sizeof(struct dm_test_parent_platdata),
+ .child_pre_probe = testbus_child_pre_probe,
+ .child_post_remove = testbus_child_post_remove,
+};
+
+UCLASS_DRIVER(testbus) = {
+ .name = "testbus",
+ .id = UCLASS_TEST_BUS,
+ .flags = DM_UC_FLAG_SEQ_ALIAS,
+ .child_pre_probe = testbus_child_pre_probe_uclass,
+ .child_post_probe = testbus_child_post_probe_uclass,
+};
+
+/* Test that we can probe for children */
+static int dm_test_bus_children(struct unit_test_state *uts)
+{
+ int num_devices = 8;
+ struct udevice *bus;
+ struct uclass *uc;
+
+ ut_assertok(uclass_get(UCLASS_TEST_FDT, &uc));
+ ut_asserteq(num_devices, list_count_items(&uc->dev_head));
+
+ /* Probe the bus, which should yield 3 more devices */
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ num_devices += 3;
+
+ ut_assertok(uclass_get(UCLASS_TEST_FDT, &uc));
+ ut_asserteq(num_devices, list_count_items(&uc->dev_head));
+
+ ut_assert(!dm_check_devices(uts, num_devices));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_children, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test our functions for accessing children */
+static int dm_test_bus_children_funcs(struct unit_test_state *uts)
+{
+ const void *blob = gd->fdt_blob;
+ struct udevice *bus, *dev;
+ int node;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+
+ /* device_get_child() */
+ ut_assertok(device_get_child(bus, 0, &dev));
+ ut_asserteq(-ENODEV, device_get_child(bus, 4, &dev));
+ ut_assertok(device_get_child_by_seq(bus, 5, &dev));
+ ut_assert(dev->flags & DM_FLAG_ACTIVATED);
+ ut_asserteq_str("c-test@5", dev->name);
+
+ /* Device with sequence number 0 should be accessible */
+ ut_asserteq(-ENODEV, device_find_child_by_seq(bus, -1, true, &dev));
+ ut_assertok(device_find_child_by_seq(bus, 0, true, &dev));
+ ut_assert(!(dev->flags & DM_FLAG_ACTIVATED));
+ ut_asserteq(-ENODEV, device_find_child_by_seq(bus, 0, false, &dev));
+ ut_assertok(device_get_child_by_seq(bus, 0, &dev));
+ ut_assert(dev->flags & DM_FLAG_ACTIVATED);
+
+ /* There is no device with sequence number 2 */
+ ut_asserteq(-ENODEV, device_find_child_by_seq(bus, 2, false, &dev));
+ ut_asserteq(-ENODEV, device_find_child_by_seq(bus, 2, true, &dev));
+ ut_asserteq(-ENODEV, device_get_child_by_seq(bus, 2, &dev));
+
+ /* Looking for something that is not a child */
+ node = fdt_path_offset(blob, "/junk");
+ ut_asserteq(-ENODEV, device_find_child_by_of_offset(bus, node, &dev));
+ node = fdt_path_offset(blob, "/d-test");
+ ut_asserteq(-ENODEV, device_find_child_by_of_offset(bus, node, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_children_funcs, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_bus_children_of_offset(struct unit_test_state *uts)
+{
+ const void *blob = gd->fdt_blob;
+ struct udevice *bus, *dev;
+ int node;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ ut_assertnonnull(bus);
+
+ /* Find a valid child */
+ node = fdt_path_offset(blob, "/some-bus/c-test@1");
+ ut_assert(node > 0);
+ ut_assertok(device_find_child_by_of_offset(bus, node, &dev));
+ ut_assertnonnull(dev);
+ ut_assert(!(dev->flags & DM_FLAG_ACTIVATED));
+ ut_assertok(device_get_child_by_of_offset(bus, node, &dev));
+ ut_assertnonnull(dev);
+ ut_assert(dev->flags & DM_FLAG_ACTIVATED);
+
+ return 0;
+}
+DM_TEST(dm_test_bus_children_of_offset,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT | DM_TESTF_FLAT_TREE);
+
+/* Test that we can iterate through children */
+static int dm_test_bus_children_iterators(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev, *child;
+
+ /* Walk through the children one by one */
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ ut_assertok(device_find_first_child(bus, &dev));
+ ut_asserteq_str("c-test@5", dev->name);
+ ut_assertok(device_find_next_child(&dev));
+ ut_asserteq_str("c-test@0", dev->name);
+ ut_assertok(device_find_next_child(&dev));
+ ut_asserteq_str("c-test@1", dev->name);
+ ut_assertok(device_find_next_child(&dev));
+ ut_asserteq_ptr(dev, NULL);
+
+ /* Move to the next child without using device_find_first_child() */
+ ut_assertok(device_find_child_by_seq(bus, 5, true, &dev));
+ ut_asserteq_str("c-test@5", dev->name);
+ ut_assertok(device_find_next_child(&dev));
+ ut_asserteq_str("c-test@0", dev->name);
+
+ /* Try a device with no children */
+ ut_assertok(device_find_first_child(dev, &child));
+ ut_asserteq_ptr(child, NULL);
+
+ return 0;
+}
+DM_TEST(dm_test_bus_children_iterators,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that the bus can store data about each child */
+static int test_bus_parent_data(struct unit_test_state *uts)
+{
+ struct dm_test_parent_data *parent_data;
+ struct udevice *bus, *dev;
+ struct uclass *uc;
+ int value;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+
+ /* Check that parent data is allocated */
+ ut_assertok(device_find_child_by_seq(bus, 0, true, &dev));
+ ut_asserteq_ptr(NULL, dev_get_parent_priv(dev));
+ ut_assertok(device_get_child_by_seq(bus, 0, &dev));
+ parent_data = dev_get_parent_priv(dev);
+ ut_assert(NULL != parent_data);
+
+ /* Check that it starts at 0 and goes away when device is removed */
+ parent_data->sum += 5;
+ ut_asserteq(5, parent_data->sum);
+ device_remove(dev, DM_REMOVE_NORMAL);
+ ut_asserteq_ptr(NULL, dev_get_parent_priv(dev));
+
+ /* Check that we can do this twice */
+ ut_assertok(device_get_child_by_seq(bus, 0, &dev));
+ parent_data = dev_get_parent_priv(dev);
+ ut_assert(NULL != parent_data);
+ parent_data->sum += 5;
+ ut_asserteq(5, parent_data->sum);
+
+ /* Add parent data to all children */
+ ut_assertok(uclass_get(UCLASS_TEST_FDT, &uc));
+ value = 5;
+ uclass_foreach_dev(dev, uc) {
+ /* Ignore these if they are not on this bus */
+ if (dev->parent != bus) {
+ ut_asserteq_ptr(NULL, dev_get_parent_priv(dev));
+ continue;
+ }
+ ut_assertok(device_probe(dev));
+ parent_data = dev_get_parent_priv(dev);
+
+ parent_data->sum = value;
+ value += 5;
+ }
+
+ /* Check it is still there */
+ value = 5;
+ uclass_foreach_dev(dev, uc) {
+ /* Ignore these if they are not on this bus */
+ if (dev->parent != bus)
+ continue;
+ parent_data = dev_get_parent_priv(dev);
+
+ ut_asserteq(value, parent_data->sum);
+ value += 5;
+ }
+
+ return 0;
+}
+/* Test that the bus can store data about each child */
+static int dm_test_bus_parent_data(struct unit_test_state *uts)
+{
+ return test_bus_parent_data(uts);
+}
+DM_TEST(dm_test_bus_parent_data, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* As above but the size is controlled by the uclass */
+static int dm_test_bus_parent_data_uclass(struct unit_test_state *uts)
+{
+ struct driver *drv;
+ struct udevice *bus;
+ int size;
+ int ret;
+
+ /* Set the driver size to 0 so that the uclass size is used */
+ ut_assertok(uclass_find_device(UCLASS_TEST_BUS, 0, &bus));
+ drv = (struct driver *)bus->driver;
+ size = drv->per_child_auto_alloc_size;
+
+#ifdef CONFIG_SANDBOX
+ os_mprotect_allow(bus->uclass->uc_drv, sizeof(*bus->uclass->uc_drv));
+ os_mprotect_allow(drv, sizeof(*drv));
+#endif
+ bus->uclass->uc_drv->per_child_auto_alloc_size = size;
+ drv->per_child_auto_alloc_size = 0;
+ ret = test_bus_parent_data(uts);
+ if (ret)
+ return ret;
+ bus->uclass->uc_drv->per_child_auto_alloc_size = 0;
+ drv->per_child_auto_alloc_size = size;
+
+ return 0;
+}
+DM_TEST(dm_test_bus_parent_data_uclass,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that the bus ops are called when a child is probed/removed */
+static int dm_test_bus_parent_ops(struct unit_test_state *uts)
+{
+ struct dm_test_parent_data *parent_data;
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *bus, *dev;
+ struct uclass *uc;
+
+ test_state = dms;
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ ut_assertok(uclass_get(UCLASS_TEST_FDT, &uc));
+
+ uclass_foreach_dev(dev, uc) {
+ /* Ignore these if they are not on this bus */
+ if (dev->parent != bus)
+ continue;
+ ut_asserteq_ptr(NULL, dev_get_parent_priv(dev));
+
+ ut_assertok(device_probe(dev));
+ parent_data = dev_get_parent_priv(dev);
+ ut_asserteq(FLAG_CHILD_PROBED, parent_data->flag);
+ }
+
+ uclass_foreach_dev(dev, uc) {
+ /* Ignore these if they are not on this bus */
+ if (dev->parent != bus)
+ continue;
+ parent_data = dev_get_parent_priv(dev);
+ ut_asserteq(FLAG_CHILD_PROBED, parent_data->flag);
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_asserteq_ptr(NULL, dev_get_parent_priv(dev));
+ ut_asserteq_ptr(dms->removed, dev);
+ }
+ test_state = NULL;
+
+ return 0;
+}
+DM_TEST(dm_test_bus_parent_ops, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int test_bus_parent_platdata(struct unit_test_state *uts)
+{
+ struct dm_test_parent_platdata *plat;
+ struct udevice *bus, *dev;
+
+ /* Check that the bus has no children */
+ ut_assertok(uclass_find_device(UCLASS_TEST_BUS, 0, &bus));
+ device_find_first_child(bus, &dev);
+ ut_asserteq_ptr(NULL, dev);
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ /* Check that platform data is allocated */
+ plat = dev_get_parent_platdata(dev);
+ ut_assert(plat != NULL);
+
+ /*
+ * Check that it is not affected by the device being
+ * probed/removed
+ */
+ plat->count++;
+ ut_asserteq(1, plat->count);
+ device_probe(dev);
+ device_remove(dev, DM_REMOVE_NORMAL);
+
+ ut_asserteq_ptr(plat, dev_get_parent_platdata(dev));
+ ut_asserteq(1, plat->count);
+ ut_assertok(device_probe(dev));
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ /* Removing the bus should also have no effect (it is still bound) */
+ device_remove(bus, DM_REMOVE_NORMAL);
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ /* Check that platform data is allocated */
+ plat = dev_get_parent_platdata(dev);
+ ut_assert(plat != NULL);
+ ut_asserteq(1, plat->count);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ /* Unbind all the children */
+ do {
+ device_find_first_child(bus, &dev);
+ if (dev)
+ device_unbind(dev);
+ } while (dev);
+
+ /* Now the child platdata should be removed and re-added */
+ device_probe(bus);
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ /* Check that platform data is allocated */
+ plat = dev_get_parent_platdata(dev);
+ ut_assert(plat != NULL);
+ ut_asserteq(0, plat->count);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ return 0;
+}
+
+/* Test that the bus can store platform data about each child */
+static int dm_test_bus_parent_platdata(struct unit_test_state *uts)
+{
+ return test_bus_parent_platdata(uts);
+}
+DM_TEST(dm_test_bus_parent_platdata, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* As above but the size is controlled by the uclass */
+static int dm_test_bus_parent_platdata_uclass(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+ struct driver *drv;
+ int size;
+ int ret;
+
+ /* Set the driver size to 0 so that the uclass size is used */
+ ut_assertok(uclass_find_device(UCLASS_TEST_BUS, 0, &bus));
+ drv = (struct driver *)bus->driver;
+ size = drv->per_child_platdata_auto_alloc_size;
+#ifdef CONFIG_SANDBOX
+ os_mprotect_allow(bus->uclass->uc_drv, sizeof(*bus->uclass->uc_drv));
+ os_mprotect_allow(drv, sizeof(*drv));
+#endif
+ bus->uclass->uc_drv->per_child_platdata_auto_alloc_size = size;
+ drv->per_child_platdata_auto_alloc_size = 0;
+ ret = test_bus_parent_platdata(uts);
+ if (ret)
+ return ret;
+ bus->uclass->uc_drv->per_child_platdata_auto_alloc_size = 0;
+ drv->per_child_platdata_auto_alloc_size = size;
+
+ return 0;
+}
+DM_TEST(dm_test_bus_parent_platdata_uclass,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that the child post_bind method is called */
+static int dm_test_bus_child_post_bind(struct unit_test_state *uts)
+{
+ struct dm_test_parent_platdata *plat;
+ struct udevice *bus, *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ /* Check that platform data is allocated */
+ plat = dev_get_parent_platdata(dev);
+ ut_assert(plat != NULL);
+ ut_asserteq(1, plat->bind_flag);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_child_post_bind, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that the child post_bind method is called */
+static int dm_test_bus_child_post_bind_uclass(struct unit_test_state *uts)
+{
+ struct dm_test_parent_platdata *plat;
+ struct udevice *bus, *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ /* Check that platform data is allocated */
+ plat = dev_get_parent_platdata(dev);
+ ut_assert(plat != NULL);
+ ut_asserteq(2, plat->uclass_bind_flag);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_child_post_bind_uclass,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/*
+ * Test that the bus' uclass' child_pre_probe() is called before the
+ * device's probe() method
+ */
+static int dm_test_bus_child_pre_probe_uclass(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+
+ /*
+ * See testfdt_drv_probe() which effectively checks that the uclass
+ * flag is set before that method is called
+ */
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ /* Check that things happened in the right order */
+ ut_asserteq_ptr(NULL, priv);
+ ut_assertok(device_probe(dev));
+
+ priv = dev_get_priv(dev);
+ ut_assert(priv != NULL);
+ ut_asserteq(1, priv->uclass_flag);
+ ut_asserteq(1, priv->uclass_total);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_child_pre_probe_uclass,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/*
+ * Test that the bus' uclass' child_post_probe() is called after the
+ * device's probe() method
+ */
+static int dm_test_bus_child_post_probe_uclass(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+
+ /*
+ * See testfdt_drv_probe() which effectively initializes that
+ * the uclass postp flag is set to a value
+ */
+ ut_assertok(uclass_get_device(UCLASS_TEST_BUS, 0, &bus));
+ for (device_find_first_child(bus, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ /* Check that things happened in the right order */
+ ut_asserteq_ptr(NULL, priv);
+ ut_assertok(device_probe(dev));
+
+ priv = dev_get_priv(dev);
+ ut_assert(priv != NULL);
+ ut_asserteq(0, priv->uclass_postp);
+ }
+ ut_asserteq(3, device_get_child_count(bus));
+
+ return 0;
+}
+DM_TEST(dm_test_bus_child_post_probe_uclass,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/cache.c b/test/dm/cache.c
new file mode 100644
index 00000000..2e244b10
--- /dev/null
+++ b/test/dm/cache.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2019 Intel Corporation <www.intel.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+
+static int dm_test_reset(struct unit_test_state *uts)
+{
+ struct udevice *dev_cache;
+ struct cache_info;
+
+ ut_assertok(uclass_get_device(UCLASS_CACHE, 0, &dev_cache));
+ ut_assertok(cache_get_info(dev, &info));
+ ut_assertok(cache_enable(dev));
+ ut_assertok(cache_disable(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_reset, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/clk.c b/test/dm/clk.c
new file mode 100644
index 00000000..31335a54
--- /dev/null
+++ b/test/dm/clk.c
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <clk.h>
+#include <dm.h>
+#include <asm/clk.h>
+#include <dm/test.h>
+#include <dm/device-internal.h>
+#include <linux/err.h>
+#include <test/ut.h>
+
+/* Base test of the clk uclass */
+static int dm_test_clk_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct clk clk_method1;
+ struct clk clk_method2;
+
+ /* Get the device using the clk device */
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "clk-test", &dev));
+
+ /* Get the same clk port in 2 different ways and compare */
+ ut_assertok(clk_get_by_index(dev, 1, &clk_method1));
+ ut_assertok(clk_get_by_index_nodev(dev_ofnode(dev), 1, &clk_method2));
+ ut_asserteq(clk_is_match(&clk_method1, &clk_method2), true);
+ ut_asserteq(clk_method1.id, clk_method2.id);
+
+ return 0;
+}
+
+DM_TEST(dm_test_clk_base, DM_TESTF_SCAN_FDT);
+
+static int dm_test_clk(struct unit_test_state *uts)
+{
+ struct udevice *dev_fixed, *dev_fixed_factor, *dev_clk, *dev_test;
+ ulong rate;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_CLK, "clk-fixed",
+ &dev_fixed));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_CLK, "clk-fixed-factor",
+ &dev_fixed_factor));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_CLK, "clk-sbox",
+ &dev_clk));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+ ut_asserteq(0, sandbox_clk_query_rate(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_rate(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "clk-test",
+ &dev_test));
+ ut_assertok(sandbox_clk_test_get(dev_test));
+ ut_assertok(sandbox_clk_test_devm_get(dev_test));
+ ut_assertok(sandbox_clk_test_valid(dev_test));
+
+ ut_asserteq(0, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM_NULL));
+ ut_asserteq(0, sandbox_clk_test_set_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM_NULL,
+ 0));
+ ut_asserteq(0, sandbox_clk_test_enable(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM_NULL));
+ ut_asserteq(0, sandbox_clk_test_disable(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM_NULL));
+
+ ut_asserteq(1234,
+ sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_FIXED));
+ ut_asserteq(0, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI));
+ ut_asserteq(0, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C));
+ ut_asserteq(321, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM1));
+ ut_asserteq(0, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_DEVM2));
+
+ rate = sandbox_clk_test_set_rate(dev_test, SANDBOX_CLK_TEST_ID_FIXED,
+ 12345);
+ ut_assert(IS_ERR_VALUE(rate));
+ rate = sandbox_clk_test_get_rate(dev_test, SANDBOX_CLK_TEST_ID_FIXED);
+ ut_asserteq(1234, rate);
+
+ ut_asserteq(0, sandbox_clk_test_set_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI,
+ 1000));
+ ut_asserteq(0, sandbox_clk_test_set_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C,
+ 2000));
+
+ ut_asserteq(1000, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI));
+ ut_asserteq(2000, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C));
+
+ ut_asserteq(1000, sandbox_clk_test_set_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI,
+ 10000));
+ ut_asserteq(2000, sandbox_clk_test_set_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C,
+ 20000));
+
+ rate = sandbox_clk_test_set_rate(dev_test, SANDBOX_CLK_TEST_ID_SPI, 0);
+ ut_assert(IS_ERR_VALUE(rate));
+ rate = sandbox_clk_test_set_rate(dev_test, SANDBOX_CLK_TEST_ID_I2C, 0);
+ ut_assert(IS_ERR_VALUE(rate));
+
+ ut_asserteq(10000, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI));
+ ut_asserteq(20000, sandbox_clk_test_get_rate(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C));
+
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+ ut_asserteq(10000, sandbox_clk_query_rate(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(20000, sandbox_clk_query_rate(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_assertok(sandbox_clk_test_enable(dev_test, SANDBOX_CLK_TEST_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_assertok(sandbox_clk_test_enable(dev_test, SANDBOX_CLK_TEST_ID_I2C));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_assertok(sandbox_clk_test_disable(dev_test,
+ SANDBOX_CLK_TEST_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_assertok(sandbox_clk_test_disable(dev_test,
+ SANDBOX_CLK_TEST_ID_I2C));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ ut_asserteq(1, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_I2C));
+ ut_asserteq(1, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_UART2));
+ ut_assertok(sandbox_clk_test_free(dev_test));
+ ut_asserteq(0, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_I2C));
+ ut_asserteq(0, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_UART2));
+
+ ut_asserteq(1, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_UART1));
+ ut_assertok(device_remove(dev_test, DM_REMOVE_NORMAL));
+ ut_asserteq(0, sandbox_clk_query_requested(dev_clk,
+ SANDBOX_CLK_ID_UART1));
+ return 0;
+}
+DM_TEST(dm_test_clk, DM_TESTF_SCAN_FDT);
+
+static int dm_test_clk_bulk(struct unit_test_state *uts)
+{
+ struct udevice *dev_clk, *dev_test;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_CLK, "clk-sbox",
+ &dev_clk));
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "clk-test",
+ &dev_test));
+ ut_assertok(sandbox_clk_test_get_bulk(dev_test));
+
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ /* Fixed clock does not support enable, thus should not fail */
+ ut_assertok(sandbox_clk_test_enable_bulk(dev_test));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ /* Fixed clock does not support disable, thus should not fail */
+ ut_assertok(sandbox_clk_test_disable_bulk(dev_test));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ /* Fixed clock does not support enable, thus should not fail */
+ ut_assertok(sandbox_clk_test_enable_bulk(dev_test));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(1, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+
+ /* Fixed clock does not support disable, thus should not fail */
+ ut_assertok(sandbox_clk_test_release_bulk(dev_test));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_SPI));
+ ut_asserteq(0, sandbox_clk_query_enable(dev_clk, SANDBOX_CLK_ID_I2C));
+ ut_assertok(device_remove(dev_test, DM_REMOVE_NORMAL));
+
+ return 0;
+}
+DM_TEST(dm_test_clk_bulk, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/clk_ccf.c b/test/dm/clk_ccf.c
new file mode 100644
index 00000000..ae3a4d8a
--- /dev/null
+++ b/test/dm/clk_ccf.c
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019
+ * Lukasz Majewski, DENX Software Engineering, lukma@denx.de
+ */
+
+#include <common.h>
+#include <clk.h>
+#include <dm.h>
+#include <asm/clk.h>
+#include <dm/test.h>
+#include <dm/uclass.h>
+#include <linux/err.h>
+#include <test/ut.h>
+#include <sandbox-clk.h>
+
+/* Tests for Common Clock Framework driver */
+static int dm_test_clk_ccf(struct unit_test_state *uts)
+{
+ struct clk *clk, *pclk;
+ struct udevice *dev;
+ long long rate;
+ int ret;
+
+ /* Get the device using the clk device */
+ ut_assertok(uclass_get_device_by_name(UCLASS_CLK, "clk-ccf", &dev));
+
+ /* Test for clk_get_by_id() */
+ ret = clk_get_by_id(SANDBOX_CLK_ECSPI_ROOT, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("ecspi_root", clk->dev->name);
+
+ /* Test for clk_get_parent_rate() */
+ ret = clk_get_by_id(SANDBOX_CLK_ECSPI1, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("ecspi1", clk->dev->name);
+
+ rate = clk_get_parent_rate(clk);
+ ut_asserteq(rate, 20000000);
+
+ /* Test the mux of CCF */
+ ret = clk_get_by_id(SANDBOX_CLK_USDHC1_SEL, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("usdhc1_sel", clk->dev->name);
+
+ rate = clk_get_parent_rate(clk);
+ ut_asserteq(rate, 60000000);
+
+ ret = clk_get_by_id(SANDBOX_CLK_USDHC2_SEL, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("usdhc2_sel", clk->dev->name);
+
+ rate = clk_get_parent_rate(clk);
+ ut_asserteq(rate, 80000000);
+
+ pclk = clk_get_parent(clk);
+ ut_asserteq_str("pll3_80m", pclk->dev->name);
+
+ /* Test the composite of CCF */
+ ret = clk_get_by_id(SANDBOX_CLK_I2C, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("i2c", clk->dev->name);
+
+ rate = clk_get_rate(clk);
+ ut_asserteq(rate, 60000000);
+
+#if CONFIG_IS_ENABLED(CLK_CCF)
+ /* Test clk tree enable/disable */
+ ret = clk_get_by_id(SANDBOX_CLK_I2C_ROOT, &clk);
+ ut_assertok(ret);
+ ut_asserteq_str("i2c_root", clk->dev->name);
+
+ ret = clk_enable(clk);
+ ut_assertok(ret);
+
+ ret = sandbox_clk_enable_count(clk);
+ ut_asserteq(ret, 1);
+
+ ret = clk_get_by_id(SANDBOX_CLK_I2C, &pclk);
+ ut_assertok(ret);
+
+ ret = sandbox_clk_enable_count(pclk);
+ ut_asserteq(ret, 1);
+
+ ret = clk_disable(clk);
+ ut_assertok(ret);
+
+ ret = sandbox_clk_enable_count(clk);
+ ut_asserteq(ret, 0);
+
+ ret = sandbox_clk_enable_count(pclk);
+ ut_asserteq(ret, 0);
+#endif
+
+ return 1;
+}
+
+DM_TEST(dm_test_clk_ccf, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/core.c b/test/dm/core.c
new file mode 100644
index 00000000..f74c4308
--- /dev/null
+++ b/test/dm/core.c
@@ -0,0 +1,906 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Tests for the core driver model code
+ *
+ * Copyright (c) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <errno.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <malloc.h>
+#include <dm/device-internal.h>
+#include <dm/root.h>
+#include <dm/util.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+enum {
+ TEST_INTVAL1 = 0,
+ TEST_INTVAL2 = 3,
+ TEST_INTVAL3 = 6,
+ TEST_INTVAL_MANUAL = 101112,
+ TEST_INTVAL_PRE_RELOC = 7,
+};
+
+static const struct dm_test_pdata test_pdata[] = {
+ { .ping_add = TEST_INTVAL1, },
+ { .ping_add = TEST_INTVAL2, },
+ { .ping_add = TEST_INTVAL3, },
+};
+
+static const struct dm_test_pdata test_pdata_manual = {
+ .ping_add = TEST_INTVAL_MANUAL,
+};
+
+static const struct dm_test_pdata test_pdata_pre_reloc = {
+ .ping_add = TEST_INTVAL_PRE_RELOC,
+};
+
+U_BOOT_DEVICE(dm_test_info1) = {
+ .name = "test_drv",
+ .platdata = &test_pdata[0],
+};
+
+U_BOOT_DEVICE(dm_test_info2) = {
+ .name = "test_drv",
+ .platdata = &test_pdata[1],
+};
+
+U_BOOT_DEVICE(dm_test_info3) = {
+ .name = "test_drv",
+ .platdata = &test_pdata[2],
+};
+
+static struct driver_info driver_info_manual = {
+ .name = "test_manual_drv",
+ .platdata = &test_pdata_manual,
+};
+
+static struct driver_info driver_info_pre_reloc = {
+ .name = "test_pre_reloc_drv",
+ .platdata = &test_pdata_pre_reloc,
+};
+
+static struct driver_info driver_info_act_dma = {
+ .name = "test_act_dma_drv",
+};
+
+void dm_leak_check_start(struct unit_test_state *uts)
+{
+ uts->start = mallinfo();
+ if (!uts->start.uordblks)
+ puts("Warning: Please add '#define DEBUG' to the top of common/dlmalloc.c\n");
+}
+
+int dm_leak_check_end(struct unit_test_state *uts)
+{
+ struct mallinfo end;
+ int id, diff;
+
+ /* Don't delete the root class, since we started with that */
+ for (id = UCLASS_ROOT + 1; id < UCLASS_COUNT; id++) {
+ struct uclass *uc;
+
+ uc = uclass_find(id);
+ if (!uc)
+ continue;
+ ut_assertok(uclass_destroy(uc));
+ }
+
+ end = mallinfo();
+ diff = end.uordblks - uts->start.uordblks;
+ if (diff > 0)
+ printf("Leak: lost %#xd bytes\n", diff);
+ else if (diff < 0)
+ printf("Leak: gained %#xd bytes\n", -diff);
+ ut_asserteq(uts->start.uordblks, end.uordblks);
+
+ return 0;
+}
+
+/* Test that binding with platdata occurs correctly */
+static int dm_test_autobind(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *dev;
+
+ /*
+ * We should have a single class (UCLASS_ROOT) and a single root
+ * device with no children.
+ */
+ ut_assert(dms->root);
+ ut_asserteq(1, list_count_items(&gd->uclass_root));
+ ut_asserteq(0, list_count_items(&gd->dm_root->child_head));
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_POST_BIND]);
+
+ ut_assertok(dm_scan_platdata(false));
+
+ /* We should have our test class now at least, plus more children */
+ ut_assert(1 < list_count_items(&gd->uclass_root));
+ ut_assert(0 < list_count_items(&gd->dm_root->child_head));
+
+ /* Our 3 dm_test_infox children should be bound to the test uclass */
+ ut_asserteq(3, dm_testdrv_op_count[DM_TEST_OP_POST_BIND]);
+
+ /* No devices should be probed */
+ list_for_each_entry(dev, &gd->dm_root->child_head, sibling_node)
+ ut_assert(!(dev->flags & DM_FLAG_ACTIVATED));
+
+ /* Our test driver should have been bound 3 times */
+ ut_assert(dm_testdrv_op_count[DM_TEST_OP_BIND] == 3);
+
+ return 0;
+}
+DM_TEST(dm_test_autobind, 0);
+
+/* Test that binding with uclass platdata allocation occurs correctly */
+static int dm_test_autobind_uclass_pdata_alloc(struct unit_test_state *uts)
+{
+ struct dm_test_perdev_uc_pdata *uc_pdata;
+ struct udevice *dev;
+ struct uclass *uc;
+
+ ut_assertok(uclass_get(UCLASS_TEST, &uc));
+ ut_assert(uc);
+
+ /**
+ * Test if test uclass driver requires allocation for the uclass
+ * platform data and then check the dev->uclass_platdata pointer.
+ */
+ ut_assert(uc->uc_drv->per_device_platdata_auto_alloc_size);
+
+ for (uclass_find_first_device(UCLASS_TEST, &dev);
+ dev;
+ uclass_find_next_device(&dev)) {
+ ut_assert(dev);
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_autobind_uclass_pdata_alloc, DM_TESTF_SCAN_PDATA);
+
+/* Test that binding with uclass platdata setting occurs correctly */
+static int dm_test_autobind_uclass_pdata_valid(struct unit_test_state *uts)
+{
+ struct dm_test_perdev_uc_pdata *uc_pdata;
+ struct udevice *dev;
+
+ /**
+ * In the test_postbind() method of test uclass driver, the uclass
+ * platform data should be set to three test int values - test it.
+ */
+ for (uclass_find_first_device(UCLASS_TEST, &dev);
+ dev;
+ uclass_find_next_device(&dev)) {
+ ut_assert(dev);
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+ ut_assert(uc_pdata->intval1 == TEST_UC_PDATA_INTVAL1);
+ ut_assert(uc_pdata->intval2 == TEST_UC_PDATA_INTVAL2);
+ ut_assert(uc_pdata->intval3 == TEST_UC_PDATA_INTVAL3);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_autobind_uclass_pdata_valid, DM_TESTF_SCAN_PDATA);
+
+/* Test that autoprobe finds all the expected devices */
+static int dm_test_autoprobe(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ int expected_base_add;
+ struct udevice *dev;
+ struct uclass *uc;
+ int i;
+
+ ut_assertok(uclass_get(UCLASS_TEST, &uc));
+ ut_assert(uc);
+
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_INIT]);
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_PRE_PROBE]);
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_POST_PROBE]);
+
+ /* The root device should not be activated until needed */
+ ut_assert(dms->root->flags & DM_FLAG_ACTIVATED);
+
+ /*
+ * We should be able to find the three test devices, and they should
+ * all be activated as they are used (lazy activation, required by
+ * U-Boot)
+ */
+ for (i = 0; i < 3; i++) {
+ ut_assertok(uclass_find_device(UCLASS_TEST, i, &dev));
+ ut_assert(dev);
+ ut_assertf(!(dev->flags & DM_FLAG_ACTIVATED),
+ "Driver %d/%s already activated", i, dev->name);
+
+ /* This should activate it */
+ ut_assertok(uclass_get_device(UCLASS_TEST, i, &dev));
+ ut_assert(dev);
+ ut_assert(dev->flags & DM_FLAG_ACTIVATED);
+
+ /* Activating a device should activate the root device */
+ if (!i)
+ ut_assert(dms->root->flags & DM_FLAG_ACTIVATED);
+ }
+
+ /*
+ * Our 3 dm_test_info children should be passed to pre_probe and
+ * post_probe
+ */
+ ut_asserteq(3, dm_testdrv_op_count[DM_TEST_OP_POST_PROBE]);
+ ut_asserteq(3, dm_testdrv_op_count[DM_TEST_OP_PRE_PROBE]);
+
+ /* Also we can check the per-device data */
+ expected_base_add = 0;
+ for (i = 0; i < 3; i++) {
+ struct dm_test_uclass_perdev_priv *priv;
+ struct dm_test_pdata *pdata;
+
+ ut_assertok(uclass_find_device(UCLASS_TEST, i, &dev));
+ ut_assert(dev);
+
+ priv = dev_get_uclass_priv(dev);
+ ut_assert(priv);
+ ut_asserteq(expected_base_add, priv->base_add);
+
+ pdata = dev->platdata;
+ expected_base_add += pdata->ping_add;
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_autoprobe, DM_TESTF_SCAN_PDATA);
+
+/* Check that we see the correct platdata in each device */
+static int dm_test_platdata(struct unit_test_state *uts)
+{
+ const struct dm_test_pdata *pdata;
+ struct udevice *dev;
+ int i;
+
+ for (i = 0; i < 3; i++) {
+ ut_assertok(uclass_find_device(UCLASS_TEST, i, &dev));
+ ut_assert(dev);
+ pdata = dev->platdata;
+ ut_assert(pdata->ping_add == test_pdata[i].ping_add);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_platdata, DM_TESTF_SCAN_PDATA);
+
+/* Test that we can bind, probe, remove, unbind a driver */
+static int dm_test_lifecycle(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ int op_count[DM_TEST_OP_COUNT];
+ struct udevice *dev, *test_dev;
+ int pingret;
+ int ret;
+
+ memcpy(op_count, dm_testdrv_op_count, sizeof(op_count));
+
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev));
+ ut_assert(dev);
+ ut_assert(dm_testdrv_op_count[DM_TEST_OP_BIND]
+ == op_count[DM_TEST_OP_BIND] + 1);
+ ut_assert(!dev->priv);
+
+ /* Probe the device - it should fail allocating private data */
+ dms->force_fail_alloc = 1;
+ ret = device_probe(dev);
+ ut_assert(ret == -ENOMEM);
+ ut_assert(dm_testdrv_op_count[DM_TEST_OP_PROBE]
+ == op_count[DM_TEST_OP_PROBE] + 1);
+ ut_assert(!dev->priv);
+
+ /* Try again without the alloc failure */
+ dms->force_fail_alloc = 0;
+ ut_assertok(device_probe(dev));
+ ut_assert(dm_testdrv_op_count[DM_TEST_OP_PROBE]
+ == op_count[DM_TEST_OP_PROBE] + 2);
+ ut_assert(dev->priv);
+
+ /* This should be device 3 in the uclass */
+ ut_assertok(uclass_find_device(UCLASS_TEST, 3, &test_dev));
+ ut_assert(dev == test_dev);
+
+ /* Try ping */
+ ut_assertok(test_ping(dev, 100, &pingret));
+ ut_assert(pingret == 102);
+
+ /* Now remove device 3 */
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_PRE_REMOVE]);
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_PRE_REMOVE]);
+
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_UNBIND]);
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_PRE_UNBIND]);
+ ut_assertok(device_unbind(dev));
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_UNBIND]);
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_PRE_UNBIND]);
+
+ return 0;
+}
+DM_TEST(dm_test_lifecycle, DM_TESTF_SCAN_PDATA | DM_TESTF_PROBE_TEST);
+
+/* Test that we can bind/unbind and the lists update correctly */
+static int dm_test_ordering(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *dev, *dev_penultimate, *dev_last, *test_dev;
+ int pingret;
+
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev));
+ ut_assert(dev);
+
+ /* Bind two new devices (numbers 4 and 5) */
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev_penultimate));
+ ut_assert(dev_penultimate);
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev_last));
+ ut_assert(dev_last);
+
+ /* Now remove device 3 */
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_assertok(device_unbind(dev));
+
+ /* The device numbering should have shifted down one */
+ ut_assertok(uclass_find_device(UCLASS_TEST, 3, &test_dev));
+ ut_assert(dev_penultimate == test_dev);
+ ut_assertok(uclass_find_device(UCLASS_TEST, 4, &test_dev));
+ ut_assert(dev_last == test_dev);
+
+ /* Add back the original device 3, now in position 5 */
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev));
+ ut_assert(dev);
+
+ /* Try ping */
+ ut_assertok(test_ping(dev, 100, &pingret));
+ ut_assert(pingret == 102);
+
+ /* Remove 3 and 4 */
+ ut_assertok(device_remove(dev_penultimate, DM_REMOVE_NORMAL));
+ ut_assertok(device_unbind(dev_penultimate));
+ ut_assertok(device_remove(dev_last, DM_REMOVE_NORMAL));
+ ut_assertok(device_unbind(dev_last));
+
+ /* Our device should now be in position 3 */
+ ut_assertok(uclass_find_device(UCLASS_TEST, 3, &test_dev));
+ ut_assert(dev == test_dev);
+
+ /* Now remove device 3 */
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_assertok(device_unbind(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_ordering, DM_TESTF_SCAN_PDATA);
+
+/* Check that we can perform operations on a device (do a ping) */
+int dm_check_operations(struct unit_test_state *uts, struct udevice *dev,
+ uint32_t base, struct dm_test_priv *priv)
+{
+ int expected;
+ int pingret;
+
+ /* Getting the child device should allocate platdata / priv */
+ ut_assertok(testfdt_ping(dev, 10, &pingret));
+ ut_assert(dev->priv);
+ ut_assert(dev->platdata);
+
+ expected = 10 + base;
+ ut_asserteq(expected, pingret);
+
+ /* Do another ping */
+ ut_assertok(testfdt_ping(dev, 20, &pingret));
+ expected = 20 + base;
+ ut_asserteq(expected, pingret);
+
+ /* Now check the ping_total */
+ priv = dev->priv;
+ ut_asserteq(DM_TEST_START_TOTAL + 10 + 20 + base * 2,
+ priv->ping_total);
+
+ return 0;
+}
+
+/* Check that we can perform operations on devices */
+static int dm_test_operations(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int i;
+
+ /*
+ * Now check that the ping adds are what we expect. This is using the
+ * ping-add property in each node.
+ */
+ for (i = 0; i < ARRAY_SIZE(test_pdata); i++) {
+ uint32_t base;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST, i, &dev));
+
+ /*
+ * Get the 'reg' property, which tells us what the ping add
+ * should be. We don't use the platdata because we want
+ * to test the code that sets that up (testfdt_drv_probe()).
+ */
+ base = test_pdata[i].ping_add;
+ debug("dev=%d, base=%d\n", i, base);
+
+ ut_assert(!dm_check_operations(uts, dev, base, dev->priv));
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_operations, DM_TESTF_SCAN_PDATA);
+
+/* Remove all drivers and check that things work */
+static int dm_test_remove(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int i;
+
+ for (i = 0; i < 3; i++) {
+ ut_assertok(uclass_find_device(UCLASS_TEST, i, &dev));
+ ut_assert(dev);
+ ut_assertf(dev->flags & DM_FLAG_ACTIVATED,
+ "Driver %d/%s not activated", i, dev->name);
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_assertf(!(dev->flags & DM_FLAG_ACTIVATED),
+ "Driver %d/%s should have deactivated", i,
+ dev->name);
+ ut_assert(!dev->priv);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_remove, DM_TESTF_SCAN_PDATA | DM_TESTF_PROBE_TEST);
+
+/* Remove and recreate everything, check for memory leaks */
+static int dm_test_leak(struct unit_test_state *uts)
+{
+ int i;
+
+ for (i = 0; i < 2; i++) {
+ struct udevice *dev;
+ int ret;
+ int id;
+
+ dm_leak_check_start(uts);
+
+ ut_assertok(dm_scan_platdata(false));
+ ut_assertok(dm_scan_fdt(gd->fdt_blob, false));
+
+ /* Scanning the uclass is enough to probe all the devices */
+ for (id = UCLASS_ROOT; id < UCLASS_COUNT; id++) {
+ for (ret = uclass_first_device(UCLASS_TEST, &dev);
+ dev;
+ ret = uclass_next_device(&dev))
+ ;
+ ut_assertok(ret);
+ }
+
+ ut_assertok(dm_leak_check_end(uts));
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_leak, 0);
+
+/* Test uclass init/destroy methods */
+static int dm_test_uclass(struct unit_test_state *uts)
+{
+ struct uclass *uc;
+
+ ut_assertok(uclass_get(UCLASS_TEST, &uc));
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_INIT]);
+ ut_asserteq(0, dm_testdrv_op_count[DM_TEST_OP_DESTROY]);
+ ut_assert(uc->priv);
+
+ ut_assertok(uclass_destroy(uc));
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_INIT]);
+ ut_asserteq(1, dm_testdrv_op_count[DM_TEST_OP_DESTROY]);
+
+ return 0;
+}
+DM_TEST(dm_test_uclass, 0);
+
+/**
+ * create_children() - Create children of a parent node
+ *
+ * @dms: Test system state
+ * @parent: Parent device
+ * @count: Number of children to create
+ * @key: Key value to put in first child. Subsequence children
+ * receive an incrementing value
+ * @child: If not NULL, then the child device pointers are written into
+ * this array.
+ * @return 0 if OK, -ve on error
+ */
+static int create_children(struct unit_test_state *uts, struct udevice *parent,
+ int count, int key, struct udevice *child[])
+{
+ struct udevice *dev;
+ int i;
+
+ for (i = 0; i < count; i++) {
+ struct dm_test_pdata *pdata;
+
+ ut_assertok(device_bind_by_name(parent, false,
+ &driver_info_manual, &dev));
+ pdata = calloc(1, sizeof(*pdata));
+ pdata->ping_add = key + i;
+ dev->platdata = pdata;
+ if (child)
+ child[i] = dev;
+ }
+
+ return 0;
+}
+
+#define NODE_COUNT 10
+
+static int dm_test_children(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *top[NODE_COUNT];
+ struct udevice *child[NODE_COUNT];
+ struct udevice *grandchild[NODE_COUNT];
+ struct udevice *dev;
+ int total;
+ int ret;
+ int i;
+
+ /* We don't care about the numbering for this test */
+ dms->skip_post_probe = 1;
+
+ ut_assert(NODE_COUNT > 5);
+
+ /* First create 10 top-level children */
+ ut_assertok(create_children(uts, dms->root, NODE_COUNT, 0, top));
+
+ /* Now a few have their own children */
+ ut_assertok(create_children(uts, top[2], NODE_COUNT, 2, NULL));
+ ut_assertok(create_children(uts, top[5], NODE_COUNT, 5, child));
+
+ /* And grandchildren */
+ for (i = 0; i < NODE_COUNT; i++)
+ ut_assertok(create_children(uts, child[i], NODE_COUNT, 50 * i,
+ i == 2 ? grandchild : NULL));
+
+ /* Check total number of devices */
+ total = NODE_COUNT * (3 + NODE_COUNT);
+ ut_asserteq(total, dm_testdrv_op_count[DM_TEST_OP_BIND]);
+
+ /* Try probing one of the grandchildren */
+ ut_assertok(uclass_get_device(UCLASS_TEST,
+ NODE_COUNT * 3 + 2 * NODE_COUNT, &dev));
+ ut_asserteq_ptr(grandchild[0], dev);
+
+ /*
+ * This should have probed the child and top node also, for a total
+ * of 3 nodes.
+ */
+ ut_asserteq(3, dm_testdrv_op_count[DM_TEST_OP_PROBE]);
+
+ /* Probe the other grandchildren */
+ for (i = 1; i < NODE_COUNT; i++)
+ ut_assertok(device_probe(grandchild[i]));
+
+ ut_asserteq(2 + NODE_COUNT, dm_testdrv_op_count[DM_TEST_OP_PROBE]);
+
+ /* Probe everything */
+ for (ret = uclass_first_device(UCLASS_TEST, &dev);
+ dev;
+ ret = uclass_next_device(&dev))
+ ;
+ ut_assertok(ret);
+
+ ut_asserteq(total, dm_testdrv_op_count[DM_TEST_OP_PROBE]);
+
+ /* Remove a top-level child and check that the children are removed */
+ ut_assertok(device_remove(top[2], DM_REMOVE_NORMAL));
+ ut_asserteq(NODE_COUNT + 1, dm_testdrv_op_count[DM_TEST_OP_REMOVE]);
+ dm_testdrv_op_count[DM_TEST_OP_REMOVE] = 0;
+
+ /* Try one with grandchildren */
+ ut_assertok(uclass_get_device(UCLASS_TEST, 5, &dev));
+ ut_asserteq_ptr(dev, top[5]);
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+ ut_asserteq(1 + NODE_COUNT * (1 + NODE_COUNT),
+ dm_testdrv_op_count[DM_TEST_OP_REMOVE]);
+
+ /* Try the same with unbind */
+ ut_assertok(device_unbind(top[2]));
+ ut_asserteq(NODE_COUNT + 1, dm_testdrv_op_count[DM_TEST_OP_UNBIND]);
+ dm_testdrv_op_count[DM_TEST_OP_UNBIND] = 0;
+
+ /* Try one with grandchildren */
+ ut_assertok(uclass_get_device(UCLASS_TEST, 5, &dev));
+ ut_asserteq_ptr(dev, top[6]);
+ ut_assertok(device_unbind(top[5]));
+ ut_asserteq(1 + NODE_COUNT * (1 + NODE_COUNT),
+ dm_testdrv_op_count[DM_TEST_OP_UNBIND]);
+
+ return 0;
+}
+DM_TEST(dm_test_children, 0);
+
+/* Test that pre-relocation devices work as expected */
+static int dm_test_pre_reloc(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *dev;
+
+ /* The normal driver should refuse to bind before relocation */
+ ut_asserteq(-EPERM, device_bind_by_name(dms->root, true,
+ &driver_info_manual, &dev));
+
+ /* But this one is marked pre-reloc */
+ ut_assertok(device_bind_by_name(dms->root, true,
+ &driver_info_pre_reloc, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_pre_reloc, 0);
+
+/*
+ * Test that removal of devices, either via the "normal" device_remove()
+ * API or via the device driver selective flag works as expected
+ */
+static int dm_test_remove_active_dma(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *dev;
+
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_act_dma,
+ &dev));
+ ut_assert(dev);
+
+ /* Probe the device */
+ ut_assertok(device_probe(dev));
+
+ /* Test if device is active right now */
+ ut_asserteq(true, device_active(dev));
+
+ /* Remove the device via selective remove flag */
+ dm_remove_devices_flags(DM_REMOVE_ACTIVE_ALL);
+
+ /* Test if device is inactive right now */
+ ut_asserteq(false, device_active(dev));
+
+ /* Probe the device again */
+ ut_assertok(device_probe(dev));
+
+ /* Test if device is active right now */
+ ut_asserteq(true, device_active(dev));
+
+ /* Remove the device via "normal" remove API */
+ ut_assertok(device_remove(dev, DM_REMOVE_NORMAL));
+
+ /* Test if device is inactive right now */
+ ut_asserteq(false, device_active(dev));
+
+ /*
+ * Test if a device without the active DMA flags is not removed upon
+ * the active DMA remove call
+ */
+ ut_assertok(device_unbind(dev));
+ ut_assertok(device_bind_by_name(dms->root, false, &driver_info_manual,
+ &dev));
+ ut_assert(dev);
+
+ /* Probe the device */
+ ut_assertok(device_probe(dev));
+
+ /* Test if device is active right now */
+ ut_asserteq(true, device_active(dev));
+
+ /* Remove the device via selective remove flag */
+ dm_remove_devices_flags(DM_REMOVE_ACTIVE_ALL);
+
+ /* Test if device is still active right now */
+ ut_asserteq(true, device_active(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_remove_active_dma, 0);
+
+static int dm_test_uclass_before_ready(struct unit_test_state *uts)
+{
+ struct uclass *uc;
+
+ ut_assertok(uclass_get(UCLASS_TEST, &uc));
+
+ gd->dm_root = NULL;
+ gd->dm_root_f = NULL;
+ memset(&gd->uclass_root, '\0', sizeof(gd->uclass_root));
+
+ ut_asserteq_ptr(NULL, uclass_find(UCLASS_TEST));
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_before_ready, 0);
+
+static int dm_test_uclass_devices_find(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int ret;
+
+ for (ret = uclass_find_first_device(UCLASS_TEST, &dev);
+ dev;
+ ret = uclass_find_next_device(&dev)) {
+ ut_assert(!ret);
+ ut_assert(dev);
+ }
+
+ ut_assertok(uclass_find_first_device(UCLASS_TEST_DUMMY, &dev));
+ ut_assert(!dev);
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_devices_find, DM_TESTF_SCAN_PDATA);
+
+static int dm_test_uclass_devices_find_by_name(struct unit_test_state *uts)
+{
+ struct udevice *finddev;
+ struct udevice *testdev;
+ int findret, ret;
+
+ /*
+ * For each test device found in fdt like: "a-test", "b-test", etc.,
+ * use its name and try to find it by uclass_find_device_by_name().
+ * Then, on success check if:
+ * - current 'testdev' name is equal to the returned 'finddev' name
+ * - current 'testdev' pointer is equal to the returned 'finddev'
+ *
+ * We assume that, each uclass's device name is unique, so if not, then
+ * this will fail on checking condition: testdev == finddev, since the
+ * uclass_find_device_by_name(), returns the first device by given name.
+ */
+ for (ret = uclass_find_first_device(UCLASS_TEST_FDT, &testdev);
+ testdev;
+ ret = uclass_find_next_device(&testdev)) {
+ ut_assertok(ret);
+ ut_assert(testdev);
+
+ findret = uclass_find_device_by_name(UCLASS_TEST_FDT,
+ testdev->name,
+ &finddev);
+
+ ut_assertok(findret);
+ ut_assert(testdev);
+ ut_asserteq_str(testdev->name, finddev->name);
+ ut_asserteq_ptr(testdev, finddev);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_devices_find_by_name, DM_TESTF_SCAN_FDT);
+
+static int dm_test_uclass_devices_get(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int ret;
+
+ for (ret = uclass_first_device(UCLASS_TEST, &dev);
+ dev;
+ ret = uclass_next_device(&dev)) {
+ ut_assert(!ret);
+ ut_assert(dev);
+ ut_assert(device_active(dev));
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_devices_get, DM_TESTF_SCAN_PDATA);
+
+static int dm_test_uclass_devices_get_by_name(struct unit_test_state *uts)
+{
+ struct udevice *finddev;
+ struct udevice *testdev;
+ int ret, findret;
+
+ /*
+ * For each test device found in fdt like: "a-test", "b-test", etc.,
+ * use its name and try to get it by uclass_get_device_by_name().
+ * On success check if:
+ * - returned finddev' is active
+ * - current 'testdev' name is equal to the returned 'finddev' name
+ * - current 'testdev' pointer is equal to the returned 'finddev'
+ *
+ * We asserts that the 'testdev' is active on each loop entry, so we
+ * could be sure that the 'finddev' is activated too, but for sure
+ * we check it again.
+ *
+ * We assume that, each uclass's device name is unique, so if not, then
+ * this will fail on checking condition: testdev == finddev, since the
+ * uclass_get_device_by_name(), returns the first device by given name.
+ */
+ for (ret = uclass_first_device(UCLASS_TEST_FDT, &testdev);
+ testdev;
+ ret = uclass_next_device(&testdev)) {
+ ut_assertok(ret);
+ ut_assert(testdev);
+ ut_assert(device_active(testdev));
+
+ findret = uclass_get_device_by_name(UCLASS_TEST_FDT,
+ testdev->name,
+ &finddev);
+
+ ut_assertok(findret);
+ ut_assert(finddev);
+ ut_assert(device_active(finddev));
+ ut_asserteq_str(testdev->name, finddev->name);
+ ut_asserteq_ptr(testdev, finddev);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_devices_get_by_name, DM_TESTF_SCAN_FDT);
+
+static int dm_test_device_get_uclass_id(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST, 0, &dev));
+ ut_asserteq(UCLASS_TEST, device_get_uclass_id(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_device_get_uclass_id, DM_TESTF_SCAN_PDATA);
+
+static int dm_test_uclass_names(struct unit_test_state *uts)
+{
+ ut_asserteq_str("test", uclass_get_name(UCLASS_TEST));
+ ut_asserteq(UCLASS_TEST, uclass_get_by_name("test"));
+
+ return 0;
+}
+DM_TEST(dm_test_uclass_names, DM_TESTF_SCAN_PDATA);
+
+static int dm_test_inactive_child(struct unit_test_state *uts)
+{
+ struct dm_test_state *dms = uts->priv;
+ struct udevice *parent, *dev1, *dev2;
+
+ /* Skip the behaviour in test_post_probe() */
+ dms->skip_post_probe = 1;
+
+ ut_assertok(uclass_first_device_err(UCLASS_TEST, &parent));
+
+ /*
+ * Create a child but do not activate it. Calling the function again
+ * should return the same child.
+ */
+ ut_asserteq(-ENODEV, device_find_first_inactive_child(parent,
+ UCLASS_TEST, &dev1));
+ ut_assertok(device_bind_ofnode(parent, DM_GET_DRIVER(test_drv),
+ "test_child", 0, ofnode_null(), &dev1));
+
+ ut_assertok(device_find_first_inactive_child(parent, UCLASS_TEST,
+ &dev2));
+ ut_asserteq_ptr(dev1, dev2);
+
+ ut_assertok(device_probe(dev1));
+ ut_asserteq(-ENODEV, device_find_first_inactive_child(parent,
+ UCLASS_TEST, &dev2));
+
+ return 0;
+}
+DM_TEST(dm_test_inactive_child, DM_TESTF_SCAN_PDATA);
diff --git a/test/dm/cpu.c b/test/dm/cpu.c
new file mode 100644
index 00000000..f5f1caef
--- /dev/null
+++ b/test/dm/cpu.c
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <cpu.h>
+#include <test/ut.h>
+
+static int dm_test_cpu(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ char text[128];
+ struct cpu_info info;
+
+ ut_assertok(cpu_probe_all());
+
+ /* Check that cpu_probe_all really activated all CPUs */
+ for (uclass_find_first_device(UCLASS_CPU, &dev);
+ dev;
+ uclass_find_next_device(&dev))
+ ut_assert(dev->flags & DM_FLAG_ACTIVATED);
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_CPU, "cpu-test1", &dev));
+
+ ut_assertok(cpu_get_desc(dev, text, sizeof(text)));
+ ut_assertok(strcmp(text, "LEG Inc. SuperMegaUltraTurbo CPU No. 1"));
+
+ ut_assertok(cpu_get_info(dev, &info));
+ ut_asserteq(info.cpu_freq, 42 * 42 * 42 * 42 * 42);
+ ut_asserteq(info.features, 0x42424242);
+
+ ut_asserteq(cpu_get_count(dev), 42);
+
+ ut_assertok(cpu_get_vendor(dev, text, sizeof(text)));
+ ut_assertok(strcmp(text, "Languid Example Garbage Inc."));
+
+ return 0;
+}
+
+DM_TEST(dm_test_cpu, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/dma.c b/test/dm/dma.c
new file mode 100644
index 00000000..b56d1773
--- /dev/null
+++ b/test/dm/dma.c
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Direct Memory Access U-Class tests
+ *
+ * Copyright (C) 2018 Texas Instruments Incorporated <www.ti.com>
+ * Grygorii Strashko <grygorii.strashko@ti.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <dma.h>
+#include <test/ut.h>
+
+static int dm_test_dma_m2m(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct dma dma_m2m;
+ u8 src_buf[512];
+ u8 dst_buf[512];
+ size_t len = 512;
+ int i;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_DMA, "dma", &dev));
+ ut_assertok(dma_get_by_name(dev, "m2m", &dma_m2m));
+
+ memset(dst_buf, 0, len);
+ for (i = 0; i < len; i++)
+ src_buf[i] = i;
+
+ ut_assertok(dma_memcpy(dst_buf, src_buf, len));
+
+ ut_assertok(memcmp(src_buf, dst_buf, len));
+ return 0;
+}
+DM_TEST(dm_test_dma_m2m, DM_TESTF_SCAN_FDT);
+
+static int dm_test_dma(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct dma dma_tx, dma_rx;
+ u8 src_buf[512];
+ u8 dst_buf[512];
+ void *dst_ptr;
+ size_t len = 512;
+ u32 meta1, meta2;
+ int i;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_DMA, "dma", &dev));
+
+ ut_assertok(dma_get_by_name(dev, "tx0", &dma_tx));
+ ut_assertok(dma_get_by_name(dev, "rx0", &dma_rx));
+
+ ut_assertok(dma_enable(&dma_tx));
+ ut_assertok(dma_enable(&dma_rx));
+
+ memset(dst_buf, 0, len);
+ for (i = 0; i < len; i++)
+ src_buf[i] = i;
+ meta1 = 0xADADDEAD;
+ meta2 = 0;
+ dst_ptr = &dst_buf;
+
+ ut_assertok(dma_send(&dma_tx, src_buf, len, &meta1));
+
+ ut_asserteq(len, dma_receive(&dma_rx, &dst_ptr, &meta2));
+ ut_asserteq(0xADADDEAD, meta2);
+
+ ut_assertok(dma_disable(&dma_tx));
+ ut_assertok(dma_disable(&dma_rx));
+
+ ut_assertok(dma_free(&dma_tx));
+ ut_assertok(dma_free(&dma_rx));
+ ut_assertok(memcmp(src_buf, dst_buf, len));
+
+ return 0;
+}
+DM_TEST(dm_test_dma, DM_TESTF_SCAN_FDT);
+
+static int dm_test_dma_rx(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct dma dma_tx, dma_rx;
+ u8 src_buf[512];
+ u8 dst_buf[512];
+ void *dst_ptr;
+ size_t len = 512;
+ u32 meta1, meta2;
+ int i;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_DMA, "dma", &dev));
+
+ ut_assertok(dma_get_by_name(dev, "tx0", &dma_tx));
+ ut_assertok(dma_get_by_name(dev, "rx0", &dma_rx));
+
+ ut_assertok(dma_enable(&dma_tx));
+ ut_assertok(dma_enable(&dma_rx));
+
+ memset(dst_buf, 0, len);
+ for (i = 0; i < len; i++)
+ src_buf[i] = i;
+ meta1 = 0xADADDEAD;
+ meta2 = 0;
+ dst_ptr = NULL;
+
+ ut_assertok(dma_prepare_rcv_buf(&dma_tx, dst_buf, len));
+
+ ut_assertok(dma_send(&dma_tx, src_buf, len, &meta1));
+
+ ut_asserteq(len, dma_receive(&dma_rx, &dst_ptr, &meta2));
+ ut_asserteq(0xADADDEAD, meta2);
+ ut_asserteq_ptr(dst_buf, dst_ptr);
+
+ ut_assertok(dma_disable(&dma_tx));
+ ut_assertok(dma_disable(&dma_rx));
+
+ ut_assertok(dma_free(&dma_tx));
+ ut_assertok(dma_free(&dma_rx));
+ ut_assertok(memcmp(src_buf, dst_buf, len));
+
+ return 0;
+}
+DM_TEST(dm_test_dma_rx, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/dsi_host.c b/test/dm/dsi_host.c
new file mode 100644
index 00000000..59fcd555
--- /dev/null
+++ b/test/dm/dsi_host.c
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
+/*
+ * Copyright (C) 2019 STMicroelectronics - All Rights Reserved
+ * Author(s): Yannick Fertre <yannick.fertre@st.com> for STMicroelectronics.
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dsi_host.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+static int dm_test_dsi_host_phy_init(void *priv_data)
+{
+ return 0;
+}
+
+static void dm_test_dsi_host_phy_post_set_mode(void *priv_data,
+ unsigned long mode_flags)
+{
+}
+
+static int dm_test_dsi_host_phy_get_lane_mbps(void *priv_data,
+ struct display_timing *timings,
+ u32 lanes,
+ u32 format,
+ unsigned int *lane_mbps)
+{
+ return 0;
+}
+
+static const struct mipi_dsi_phy_ops dm_test_dsi_host_phy_ops = {
+ .init = dm_test_dsi_host_phy_init,
+ .get_lane_mbps = dm_test_dsi_host_phy_get_lane_mbps,
+ .post_set_mode = dm_test_dsi_host_phy_post_set_mode,
+};
+
+/* Test that dsi_host driver functions are called */
+static int dm_test_dsi_host(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct mipi_dsi_device device;
+ struct display_timing timings;
+ unsigned int max_data_lanes = 4;
+
+ ut_assertok(uclass_first_device_err(UCLASS_DSI_HOST, &dev));
+
+ ut_assertok(dsi_host_init(dev, &device, &timings, max_data_lanes,
+ &dm_test_dsi_host_phy_ops));
+
+ ut_assertok(dsi_host_enable(dev));
+
+ return 0;
+}
+
+DM_TEST(dm_test_dsi_host, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/eth.c b/test/dm/eth.c
new file mode 100644
index 00000000..ad5354b4
--- /dev/null
+++ b/test/dm/eth.c
@@ -0,0 +1,431 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2015 National Instruments
+ *
+ * (C) Copyright 2015
+ * Joe Hershberger <joe.hershberger@ni.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <env.h>
+#include <fdtdec.h>
+#include <malloc.h>
+#include <net.h>
+#include <dm/test.h>
+#include <dm/device-internal.h>
+#include <dm/uclass-internal.h>
+#include <asm/eth.h>
+#include <test/ut.h>
+
+#define DM_TEST_ETH_NUM 4
+
+static int dm_test_eth(struct unit_test_state *uts)
+{
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ env_set("ethact", "eth@10002000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ env_set("ethact", "eth@10003000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10003000", env_get("ethact"));
+
+ env_set("ethact", "eth@10004000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10004000", env_get("ethact"));
+
+ return 0;
+}
+DM_TEST(dm_test_eth, DM_TESTF_SCAN_FDT);
+
+static int dm_test_eth_alias(struct unit_test_state *uts)
+{
+ net_ping_ip = string_to_ip("1.1.2.2");
+ env_set("ethact", "eth0");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ env_set("ethact", "eth1");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10004000", env_get("ethact"));
+
+ /* Expected to fail since eth2 is not defined in the device tree */
+ env_set("ethact", "eth2");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ env_set("ethact", "eth5");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10003000", env_get("ethact"));
+
+ return 0;
+}
+DM_TEST(dm_test_eth_alias, DM_TESTF_SCAN_FDT);
+
+static int dm_test_eth_prime(struct unit_test_state *uts)
+{
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ /* Expected to be "eth@10003000" because of ethprime variable */
+ env_set("ethact", NULL);
+ env_set("ethprime", "eth5");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10003000", env_get("ethact"));
+
+ /* Expected to be "eth@10002000" because it is first */
+ env_set("ethact", NULL);
+ env_set("ethprime", NULL);
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ return 0;
+}
+DM_TEST(dm_test_eth_prime, DM_TESTF_SCAN_FDT);
+
+/**
+ * This test case is trying to test the following scenario:
+ * - All ethernet devices are not probed
+ * - "ethaddr" for all ethernet devices are not set
+ * - "ethact" is set to a valid ethernet device name
+ *
+ * With Sandbox default test configuration, all ethernet devices are
+ * probed after power-up, so we have to manually create such scenario:
+ * - Remove all ethernet devices
+ * - Remove all "ethaddr" environment variables
+ * - Set "ethact" to the first ethernet device
+ *
+ * Do a ping test to see if anything goes wrong.
+ */
+static int dm_test_eth_act(struct unit_test_state *uts)
+{
+ struct udevice *dev[DM_TEST_ETH_NUM];
+ const char *ethname[DM_TEST_ETH_NUM] = {"eth@10002000", "eth@10003000",
+ "sbe5", "eth@10004000"};
+ const char *addrname[DM_TEST_ETH_NUM] = {"ethaddr", "eth5addr",
+ "eth3addr", "eth1addr"};
+ char ethaddr[DM_TEST_ETH_NUM][18];
+ int i;
+
+ memset(ethaddr, '\0', sizeof(ethaddr));
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ /* Prepare the test scenario */
+ for (i = 0; i < DM_TEST_ETH_NUM; i++) {
+ ut_assertok(uclass_find_device_by_name(UCLASS_ETH,
+ ethname[i], &dev[i]));
+ ut_assertok(device_remove(dev[i], DM_REMOVE_NORMAL));
+
+ /* Invalidate MAC address */
+ strncpy(ethaddr[i], env_get(addrname[i]), 17);
+ /* Must disable access protection for ethaddr before clearing */
+ env_set(".flags", addrname[i]);
+ env_set(addrname[i], NULL);
+ }
+
+ /* Set ethact to "eth@10002000" */
+ env_set("ethact", ethname[0]);
+
+ /* Segment fault might happen if something is wrong */
+ ut_asserteq(-ENODEV, net_loop(PING));
+
+ for (i = 0; i < DM_TEST_ETH_NUM; i++) {
+ /* Restore the env */
+ env_set(".flags", addrname[i]);
+ env_set(addrname[i], ethaddr[i]);
+
+ /* Probe the device again */
+ ut_assertok(device_probe(dev[i]));
+ }
+ env_set(".flags", NULL);
+ env_set("ethact", NULL);
+
+ return 0;
+}
+DM_TEST(dm_test_eth_act, DM_TESTF_SCAN_FDT);
+
+/* The asserts include a return on fail; cleanup in the caller */
+static int _dm_test_eth_rotate1(struct unit_test_state *uts)
+{
+ /* Make sure that the default is to rotate to the next interface */
+ env_set("ethact", "eth@10004000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ /* If ethrotate is no, then we should fail on a bad MAC */
+ env_set("ethact", "eth@10004000");
+ env_set("ethrotate", "no");
+ ut_asserteq(-EINVAL, net_loop(PING));
+ ut_asserteq_str("eth@10004000", env_get("ethact"));
+
+ return 0;
+}
+
+static int _dm_test_eth_rotate2(struct unit_test_state *uts)
+{
+ /* Make sure we can skip invalid devices */
+ env_set("ethact", "eth@10004000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10004000", env_get("ethact"));
+
+ /* Make sure we can handle device name which is not eth# */
+ env_set("ethact", "sbe5");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("sbe5", env_get("ethact"));
+
+ return 0;
+}
+
+static int dm_test_eth_rotate(struct unit_test_state *uts)
+{
+ char ethaddr[18];
+ int retval;
+
+ /* Set target IP to mock ping */
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ /* Invalidate eth1's MAC address */
+ memset(ethaddr, '\0', sizeof(ethaddr));
+ strncpy(ethaddr, env_get("eth1addr"), 17);
+ /* Must disable access protection for eth1addr before clearing */
+ env_set(".flags", "eth1addr");
+ env_set("eth1addr", NULL);
+
+ retval = _dm_test_eth_rotate1(uts);
+
+ /* Restore the env */
+ env_set("eth1addr", ethaddr);
+ env_set("ethrotate", NULL);
+
+ if (!retval) {
+ /* Invalidate eth0's MAC address */
+ strncpy(ethaddr, env_get("ethaddr"), 17);
+ /* Must disable access protection for ethaddr before clearing */
+ env_set(".flags", "ethaddr");
+ env_set("ethaddr", NULL);
+
+ retval = _dm_test_eth_rotate2(uts);
+
+ /* Restore the env */
+ env_set("ethaddr", ethaddr);
+ }
+ /* Restore the env */
+ env_set(".flags", NULL);
+
+ return retval;
+}
+DM_TEST(dm_test_eth_rotate, DM_TESTF_SCAN_FDT);
+
+/* The asserts include a return on fail; cleanup in the caller */
+static int _dm_test_net_retry(struct unit_test_state *uts)
+{
+ /*
+ * eth1 is disabled and netretry is yes, so the ping should succeed and
+ * the active device should be eth0
+ */
+ sandbox_eth_disable_response(1, true);
+ env_set("ethact", "eth@10004000");
+ env_set("netretry", "yes");
+ sandbox_eth_skip_timeout();
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ /*
+ * eth1 is disabled and netretry is no, so the ping should fail and the
+ * active device should be eth1
+ */
+ env_set("ethact", "eth@10004000");
+ env_set("netretry", "no");
+ sandbox_eth_skip_timeout();
+ ut_asserteq(-ENONET, net_loop(PING));
+ ut_asserteq_str("eth@10004000", env_get("ethact"));
+
+ return 0;
+}
+
+static int dm_test_net_retry(struct unit_test_state *uts)
+{
+ int retval;
+
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ retval = _dm_test_net_retry(uts);
+
+ /* Restore the env */
+ env_set("netretry", NULL);
+ sandbox_eth_disable_response(1, false);
+
+ return retval;
+}
+DM_TEST(dm_test_net_retry, DM_TESTF_SCAN_FDT);
+
+static int sb_check_arp_reply(struct udevice *dev, void *packet,
+ unsigned int len)
+{
+ struct eth_sandbox_priv *priv = dev_get_priv(dev);
+ struct ethernet_hdr *eth = packet;
+ struct arp_hdr *arp;
+ /* Used by all of the ut_assert macros */
+ struct unit_test_state *uts = priv->priv;
+
+ if (ntohs(eth->et_protlen) != PROT_ARP)
+ return 0;
+
+ arp = packet + ETHER_HDR_SIZE;
+
+ if (ntohs(arp->ar_op) != ARPOP_REPLY)
+ return 0;
+
+ /* This test would be worthless if we are not waiting */
+ ut_assert(arp_is_waiting());
+
+ /* Validate response */
+ ut_assert(memcmp(eth->et_src, net_ethaddr, ARP_HLEN) == 0);
+ ut_assert(memcmp(eth->et_dest, priv->fake_host_hwaddr, ARP_HLEN) == 0);
+ ut_assert(eth->et_protlen == htons(PROT_ARP));
+
+ ut_assert(arp->ar_hrd == htons(ARP_ETHER));
+ ut_assert(arp->ar_pro == htons(PROT_IP));
+ ut_assert(arp->ar_hln == ARP_HLEN);
+ ut_assert(arp->ar_pln == ARP_PLEN);
+ ut_assert(memcmp(&arp->ar_sha, net_ethaddr, ARP_HLEN) == 0);
+ ut_assert(net_read_ip(&arp->ar_spa).s_addr == net_ip.s_addr);
+ ut_assert(memcmp(&arp->ar_tha, priv->fake_host_hwaddr, ARP_HLEN) == 0);
+ ut_assert(net_read_ip(&arp->ar_tpa).s_addr ==
+ string_to_ip("1.1.2.4").s_addr);
+
+ return 0;
+}
+
+static int sb_with_async_arp_handler(struct udevice *dev, void *packet,
+ unsigned int len)
+{
+ struct eth_sandbox_priv *priv = dev_get_priv(dev);
+ struct ethernet_hdr *eth = packet;
+ struct arp_hdr *arp = packet + ETHER_HDR_SIZE;
+ int ret;
+
+ /*
+ * If we are about to generate a reply to ARP, first inject a request
+ * from another host
+ */
+ if (ntohs(eth->et_protlen) == PROT_ARP &&
+ ntohs(arp->ar_op) == ARPOP_REQUEST) {
+ /* Make sure sandbox_eth_recv_arp_req() knows who is asking */
+ priv->fake_host_ipaddr = string_to_ip("1.1.2.4");
+
+ ret = sandbox_eth_recv_arp_req(dev);
+ if (ret)
+ return ret;
+ }
+
+ sandbox_eth_arp_req_to_reply(dev, packet, len);
+ sandbox_eth_ping_req_to_reply(dev, packet, len);
+
+ return sb_check_arp_reply(dev, packet, len);
+}
+
+static int dm_test_eth_async_arp_reply(struct unit_test_state *uts)
+{
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ sandbox_eth_set_tx_handler(0, sb_with_async_arp_handler);
+ /* Used by all of the ut_assert macros in the tx_handler */
+ sandbox_eth_set_priv(0, uts);
+
+ env_set("ethact", "eth@10002000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ sandbox_eth_set_tx_handler(0, NULL);
+
+ return 0;
+}
+
+DM_TEST(dm_test_eth_async_arp_reply, DM_TESTF_SCAN_FDT);
+
+static int sb_check_ping_reply(struct udevice *dev, void *packet,
+ unsigned int len)
+{
+ struct eth_sandbox_priv *priv = dev_get_priv(dev);
+ struct ethernet_hdr *eth = packet;
+ struct ip_udp_hdr *ip;
+ struct icmp_hdr *icmp;
+ /* Used by all of the ut_assert macros */
+ struct unit_test_state *uts = priv->priv;
+
+ if (ntohs(eth->et_protlen) != PROT_IP)
+ return 0;
+
+ ip = packet + ETHER_HDR_SIZE;
+
+ if (ip->ip_p != IPPROTO_ICMP)
+ return 0;
+
+ icmp = (struct icmp_hdr *)&ip->udp_src;
+
+ if (icmp->type != ICMP_ECHO_REPLY)
+ return 0;
+
+ /* This test would be worthless if we are not waiting */
+ ut_assert(arp_is_waiting());
+
+ /* Validate response */
+ ut_assert(memcmp(eth->et_src, net_ethaddr, ARP_HLEN) == 0);
+ ut_assert(memcmp(eth->et_dest, priv->fake_host_hwaddr, ARP_HLEN) == 0);
+ ut_assert(eth->et_protlen == htons(PROT_IP));
+
+ ut_assert(net_read_ip(&ip->ip_src).s_addr == net_ip.s_addr);
+ ut_assert(net_read_ip(&ip->ip_dst).s_addr ==
+ string_to_ip("1.1.2.4").s_addr);
+
+ return 0;
+}
+
+static int sb_with_async_ping_handler(struct udevice *dev, void *packet,
+ unsigned int len)
+{
+ struct eth_sandbox_priv *priv = dev_get_priv(dev);
+ struct ethernet_hdr *eth = packet;
+ struct arp_hdr *arp = packet + ETHER_HDR_SIZE;
+ int ret;
+
+ /*
+ * If we are about to generate a reply to ARP, first inject a request
+ * from another host
+ */
+ if (ntohs(eth->et_protlen) == PROT_ARP &&
+ ntohs(arp->ar_op) == ARPOP_REQUEST) {
+ /* Make sure sandbox_eth_recv_arp_req() knows who is asking */
+ priv->fake_host_ipaddr = string_to_ip("1.1.2.4");
+
+ ret = sandbox_eth_recv_ping_req(dev);
+ if (ret)
+ return ret;
+ }
+
+ sandbox_eth_arp_req_to_reply(dev, packet, len);
+ sandbox_eth_ping_req_to_reply(dev, packet, len);
+
+ return sb_check_ping_reply(dev, packet, len);
+}
+
+static int dm_test_eth_async_ping_reply(struct unit_test_state *uts)
+{
+ net_ping_ip = string_to_ip("1.1.2.2");
+
+ sandbox_eth_set_tx_handler(0, sb_with_async_ping_handler);
+ /* Used by all of the ut_assert macros in the tx_handler */
+ sandbox_eth_set_priv(0, uts);
+
+ env_set("ethact", "eth@10002000");
+ ut_assertok(net_loop(PING));
+ ut_asserteq_str("eth@10002000", env_get("ethact"));
+
+ sandbox_eth_set_tx_handler(0, NULL);
+
+ return 0;
+}
+
+DM_TEST(dm_test_eth_async_ping_reply, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/firmware.c b/test/dm/firmware.c
new file mode 100644
index 00000000..60fdcbb3
--- /dev/null
+++ b/test/dm/firmware.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2018 Xilinx, Inc.
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <syscon.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Base test of firmware probe */
+static int dm_test_firmware_probe(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_FIRMWARE,
+ "sandbox-firmware", &dev));
+ return 0;
+}
+DM_TEST(dm_test_firmware_probe, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/gpio.c b/test/dm/gpio.c
new file mode 100644
index 00000000..bb4b20ce
--- /dev/null
+++ b/test/dm/gpio.c
@@ -0,0 +1,249 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <fdtdec.h>
+#include <dm.h>
+#include <dm/root.h>
+#include <dm/test.h>
+#include <dm/util.h>
+#include <asm/gpio.h>
+#include <test/ut.h>
+
+/* Test that sandbox GPIOs work correctly */
+static int dm_test_gpio(struct unit_test_state *uts)
+{
+ unsigned int offset, gpio;
+ struct dm_gpio_ops *ops;
+ struct udevice *dev;
+ const char *name;
+ int offset_count;
+ char buf[80];
+
+ /*
+ * We expect to get 3 banks. One is anonymous (just numbered) and
+ * comes from platdata. The other two are named a (20 gpios)
+ * and b (10 gpios) and come from the device tree. See
+ * test/dm/test.dts.
+ */
+ ut_assertok(gpio_lookup_name("b4", &dev, &offset, &gpio));
+ ut_asserteq_str(dev->name, "extra-gpios");
+ ut_asserteq(4, offset);
+ ut_asserteq(CONFIG_SANDBOX_GPIO_COUNT + 20 + 4, gpio);
+
+ name = gpio_get_bank_info(dev, &offset_count);
+ ut_asserteq_str("b", name);
+ ut_asserteq(10, offset_count);
+
+ /* Get the operations for this device */
+ ops = gpio_get_ops(dev);
+ ut_assert(ops->get_function);
+
+ /* Cannot get a value until it is reserved */
+ ut_asserteq(-EBUSY, gpio_get_value(gpio + 1));
+ /*
+ * Now some tests that use the 'sandbox' back door. All GPIOs
+ * should default to input, include b4 that we are using here.
+ */
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: input: 0 [ ]", buf);
+
+ /* Change it to an output */
+ sandbox_gpio_set_direction(dev, offset, 1);
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: output: 0 [ ]", buf);
+
+ sandbox_gpio_set_value(dev, offset, 1);
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: output: 1 [ ]", buf);
+
+ ut_assertok(gpio_request(gpio, "testing"));
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: output: 1 [x] testing", buf);
+
+ /* Change the value a bit */
+ ut_asserteq(1, ops->get_value(dev, offset));
+ ut_assertok(ops->set_value(dev, offset, 0));
+ ut_asserteq(0, ops->get_value(dev, offset));
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: output: 0 [x] testing", buf);
+ ut_assertok(ops->set_value(dev, offset, 1));
+ ut_asserteq(1, ops->get_value(dev, offset));
+
+ /* Make it an open drain output, and reset it */
+ ut_asserteq(0, sandbox_gpio_get_open_drain(dev, offset));
+ ut_assertok(ops->set_open_drain(dev, offset, 1));
+ ut_asserteq(1, sandbox_gpio_get_open_drain(dev, offset));
+ ut_assertok(ops->set_open_drain(dev, offset, 0));
+ ut_asserteq(0, sandbox_gpio_get_open_drain(dev, offset));
+
+ /* Make it an input */
+ ut_assertok(ops->direction_input(dev, offset));
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: input: 1 [x] testing", buf);
+ sandbox_gpio_set_value(dev, offset, 0);
+ ut_asserteq(0, sandbox_gpio_get_value(dev, offset));
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: input: 0 [x] testing", buf);
+
+ ut_assertok(gpio_free(gpio));
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b4: input: 0 [ ]", buf);
+
+ /* Check the 'a' bank also */
+ ut_assertok(gpio_lookup_name("a15", &dev, &offset, &gpio));
+ ut_asserteq_str(dev->name, "base-gpios");
+ ut_asserteq(15, offset);
+ ut_asserteq(CONFIG_SANDBOX_GPIO_COUNT + 15, gpio);
+
+ name = gpio_get_bank_info(dev, &offset_count);
+ ut_asserteq_str("a", name);
+ ut_asserteq(20, offset_count);
+
+ return 0;
+}
+DM_TEST(dm_test_gpio, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that sandbox anonymous GPIOs work correctly */
+static int dm_test_gpio_anon(struct unit_test_state *uts)
+{
+ unsigned int offset, gpio;
+ struct udevice *dev;
+ const char *name;
+ int offset_count;
+
+ /* And the anonymous bank */
+ ut_assertok(gpio_lookup_name("14", &dev, &offset, &gpio));
+ ut_asserteq_str(dev->name, "gpio_sandbox");
+ ut_asserteq(14, offset);
+ ut_asserteq(14, gpio);
+
+ name = gpio_get_bank_info(dev, &offset_count);
+ ut_asserteq_ptr(NULL, name);
+ ut_asserteq(CONFIG_SANDBOX_GPIO_COUNT, offset_count);
+
+ return 0;
+}
+DM_TEST(dm_test_gpio_anon, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that gpio_requestf() works as expected */
+static int dm_test_gpio_requestf(struct unit_test_state *uts)
+{
+ unsigned int offset, gpio;
+ struct udevice *dev;
+ char buf[80];
+
+ ut_assertok(gpio_lookup_name("b5", &dev, &offset, &gpio));
+ ut_assertok(gpio_requestf(gpio, "testing %d %s", 1, "hi"));
+ sandbox_gpio_set_direction(dev, offset, 1);
+ sandbox_gpio_set_value(dev, offset, 1);
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b5: output: 1 [x] testing 1 hi", buf);
+
+ return 0;
+}
+DM_TEST(dm_test_gpio_requestf, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that gpio_request() copies its string */
+static int dm_test_gpio_copy(struct unit_test_state *uts)
+{
+ unsigned int offset, gpio;
+ struct udevice *dev;
+ char buf[80], name[10];
+
+ ut_assertok(gpio_lookup_name("b6", &dev, &offset, &gpio));
+ strcpy(name, "odd_name");
+ ut_assertok(gpio_request(gpio, name));
+ sandbox_gpio_set_direction(dev, offset, 1);
+ sandbox_gpio_set_value(dev, offset, 1);
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b6: output: 1 [x] odd_name", buf);
+ strcpy(name, "nothing");
+ ut_assertok(gpio_get_status(dev, offset, buf, sizeof(buf)));
+ ut_asserteq_str("b6: output: 1 [x] odd_name", buf);
+
+ return 0;
+}
+DM_TEST(dm_test_gpio_copy, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we don't leak memory with GPIOs */
+static int dm_test_gpio_leak(struct unit_test_state *uts)
+{
+ ut_assertok(dm_test_gpio(uts));
+ ut_assertok(dm_test_gpio_anon(uts));
+ ut_assertok(dm_test_gpio_requestf(uts));
+ ut_assertok(dm_leak_check_end(uts));
+
+ return 0;
+}
+DM_TEST(dm_test_gpio_leak, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can find GPIOs using phandles */
+static int dm_test_gpio_phandles(struct unit_test_state *uts)
+{
+ struct gpio_desc desc, desc_list[8], desc_list2[8];
+ struct udevice *dev, *gpio_a, *gpio_b;
+
+ ut_assertok(uclass_get_device(UCLASS_TEST_FDT, 0, &dev));
+ ut_asserteq_str("a-test", dev->name);
+
+ ut_assertok(gpio_request_by_name(dev, "test-gpios", 1, &desc, 0));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 1, &gpio_a));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 2, &gpio_b));
+ ut_asserteq_str("base-gpios", gpio_a->name);
+ ut_asserteq(true, !!device_active(gpio_a));
+ ut_asserteq_ptr(gpio_a, desc.dev);
+ ut_asserteq(4, desc.offset);
+ /* GPIOF_INPUT is the sandbox GPIO driver default */
+ ut_asserteq(GPIOF_INPUT, gpio_get_function(gpio_a, 4, NULL));
+ ut_assertok(dm_gpio_free(dev, &desc));
+
+ ut_asserteq(-ENOENT, gpio_request_by_name(dev, "test-gpios", 3, &desc,
+ 0));
+ ut_asserteq_ptr(NULL, desc.dev);
+ ut_asserteq(desc.offset, 0);
+ ut_asserteq(-ENOENT, gpio_request_by_name(dev, "test-gpios", 5, &desc,
+ 0));
+
+ /* Last GPIO is ignord as it comes after <0> */
+ ut_asserteq(3, gpio_request_list_by_name(dev, "test-gpios", desc_list,
+ ARRAY_SIZE(desc_list), 0));
+ ut_asserteq(-EBUSY, gpio_request_list_by_name(dev, "test-gpios",
+ desc_list2,
+ ARRAY_SIZE(desc_list2),
+ 0));
+ ut_assertok(gpio_free_list(dev, desc_list, 3));
+ ut_asserteq(3, gpio_request_list_by_name(dev, "test-gpios", desc_list,
+ ARRAY_SIZE(desc_list),
+ GPIOD_IS_OUT |
+ GPIOD_IS_OUT_ACTIVE));
+ ut_asserteq_ptr(gpio_a, desc_list[0].dev);
+ ut_asserteq(1, desc_list[0].offset);
+ ut_asserteq_ptr(gpio_a, desc_list[1].dev);
+ ut_asserteq(4, desc_list[1].offset);
+ ut_asserteq_ptr(gpio_b, desc_list[2].dev);
+ ut_asserteq(5, desc_list[2].offset);
+ ut_asserteq(1, dm_gpio_get_value(desc_list));
+ ut_assertok(gpio_free_list(dev, desc_list, 3));
+
+ ut_asserteq(6, gpio_request_list_by_name(dev, "test2-gpios", desc_list,
+ ARRAY_SIZE(desc_list), 0));
+ /* This was set to output previously, so still will be */
+ ut_asserteq(GPIOF_OUTPUT, gpio_get_function(gpio_a, 1, NULL));
+
+ /* Active low should invert the input value */
+ ut_asserteq(GPIOF_INPUT, gpio_get_function(gpio_b, 6, NULL));
+ ut_asserteq(1, dm_gpio_get_value(&desc_list[2]));
+
+ ut_asserteq(GPIOF_INPUT, gpio_get_function(gpio_b, 7, NULL));
+ ut_asserteq(GPIOF_OUTPUT, gpio_get_function(gpio_b, 8, NULL));
+ ut_asserteq(0, dm_gpio_get_value(&desc_list[4]));
+ ut_asserteq(GPIOF_OUTPUT, gpio_get_function(gpio_b, 9, NULL));
+ ut_asserteq(1, dm_gpio_get_value(&desc_list[5]));
+
+
+ return 0;
+}
+DM_TEST(dm_test_gpio_phandles, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/hwspinlock.c b/test/dm/hwspinlock.c
new file mode 100644
index 00000000..09ec38b4
--- /dev/null
+++ b/test/dm/hwspinlock.c
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
+/*
+ * Copyright (C) 2018, STMicroelectronics - All Rights Reserved
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <hwspinlock.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Test that hwspinlock driver functions are called */
+static int dm_test_hwspinlock_base(struct unit_test_state *uts)
+{
+ struct sandbox_state *state = state_get_current();
+ struct hwspinlock hws;
+
+ ut_assertok(uclass_get_device(UCLASS_HWSPINLOCK, 0, &hws.dev));
+ ut_assertnonnull(hws.dev);
+ ut_asserteq(false, state->hwspinlock);
+
+ hws.id = 0;
+ ut_assertok(hwspinlock_lock_timeout(&hws, 1));
+ ut_asserteq(true, state->hwspinlock);
+
+ ut_assertok(hwspinlock_unlock(&hws));
+ ut_asserteq(false, state->hwspinlock);
+
+ ut_assertok(hwspinlock_lock_timeout(&hws, 1));
+ ut_assertok(!hwspinlock_lock_timeout(&hws, 1));
+
+ ut_assertok(hwspinlock_unlock(&hws));
+ ut_assertok(!hwspinlock_unlock(&hws));
+
+ return 0;
+}
+
+DM_TEST(dm_test_hwspinlock_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/i2c.c b/test/dm/i2c.c
new file mode 100644
index 00000000..cbbd4aa2
--- /dev/null
+++ b/test/dm/i2c.c
@@ -0,0 +1,223 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2013 Google, Inc
+ *
+ * Note: Test coverage does not include 10-bit addressing
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <i2c.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/device-internal.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <dm/util.h>
+#include <test/ut.h>
+
+static const int busnum;
+static const int chip = 0x2c;
+
+/* Test that we can find buses and chips */
+static int dm_test_i2c_find(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ const int no_chip = 0x10;
+
+ ut_asserteq(-ENODEV, uclass_find_device_by_seq(UCLASS_I2C, busnum,
+ false, &bus));
+
+ /*
+ * The post_bind() method will bind devices to chip selects. Check
+ * this then remove the emulation and the slave device.
+ */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+ ut_assertok(dm_i2c_probe(bus, chip, 0, &dev));
+ ut_asserteq(-ENOENT, dm_i2c_probe(bus, no_chip, 0, &dev));
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_I2C, 1, &bus));
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_find, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_read_write(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ uint8_t buf[5];
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+ ut_assertok(i2c_get_chip(bus, chip, 1, &dev));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0\0\0\0", sizeof(buf)));
+ ut_assertok(dm_i2c_write(dev, 2, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0AB\0", sizeof(buf)));
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_read_write, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_speed(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ uint8_t buf[5];
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+
+ /* Use test mode so we create the required errors for invalid speeds */
+ sandbox_i2c_set_test_mode(bus, true);
+ ut_assertok(i2c_get_chip(bus, chip, 1, &dev));
+ ut_assertok(dm_i2c_set_bus_speed(bus, 100000));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(dm_i2c_set_bus_speed(bus, 400000));
+ ut_asserteq(400000, dm_i2c_get_bus_speed(bus));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_asserteq(-EINVAL, dm_i2c_write(dev, 0, buf, 5));
+ sandbox_i2c_set_test_mode(bus, false);
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_speed, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_offset_len(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ uint8_t buf[5];
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+ ut_assertok(i2c_get_chip(bus, chip, 1, &dev));
+ ut_assertok(i2c_set_chip_offset_len(dev, 1));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+
+ /* This is not supported by the uclass */
+ ut_asserteq(-EINVAL, i2c_set_chip_offset_len(dev, 5));
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_offset_len, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_probe_empty(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+
+ /* Use test mode so that this chip address will always probe */
+ sandbox_i2c_set_test_mode(bus, true);
+ ut_assertok(dm_i2c_probe(bus, SANDBOX_I2C_TEST_ADDR, 0, &dev));
+ sandbox_i2c_set_test_mode(bus, false);
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_probe_empty, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_bytewise(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ struct udevice *eeprom;
+ uint8_t buf[5];
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_I2C, busnum, &bus));
+ ut_assertok(i2c_get_chip(bus, chip, 1, &dev));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0\0\0\0", sizeof(buf)));
+
+ /* Tell the EEPROM to only read/write one register at a time */
+ ut_assertok(uclass_first_device(UCLASS_I2C_EMUL, &eeprom));
+ ut_assertnonnull(eeprom);
+ sandbox_i2c_eeprom_set_test_mode(eeprom, SIE_TEST_MODE_SINGLE_BYTE);
+
+ /* Now we only get the first byte - the rest will be 0xff */
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\xff\xff\xff\xff", sizeof(buf)));
+
+ /* If we do a separate transaction for each byte, it works */
+ ut_assertok(i2c_set_chip_flags(dev, DM_I2C_CHIP_RD_ADDRESS));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0\0\0\0", sizeof(buf)));
+
+ /* This will only write A */
+ ut_assertok(i2c_set_chip_flags(dev, 0));
+ ut_assertok(dm_i2c_write(dev, 2, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\xff\xff\xff\xff", sizeof(buf)));
+
+ /* Check that the B was ignored */
+ ut_assertok(i2c_set_chip_flags(dev, DM_I2C_CHIP_RD_ADDRESS));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0A\0\0\0", sizeof(buf)));
+
+ /* Now write it again with the new flags, it should work */
+ ut_assertok(i2c_set_chip_flags(dev, DM_I2C_CHIP_WR_ADDRESS));
+ ut_assertok(dm_i2c_write(dev, 2, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\xff\xff\xff\xff", sizeof(buf)));
+
+ ut_assertok(i2c_set_chip_flags(dev, DM_I2C_CHIP_WR_ADDRESS |
+ DM_I2C_CHIP_RD_ADDRESS));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "\0\0AB\0\0", sizeof(buf)));
+
+ /* Restore defaults */
+ sandbox_i2c_eeprom_set_test_mode(eeprom, SIE_TEST_MODE_NONE);
+ ut_assertok(i2c_set_chip_flags(dev, 0));
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_bytewise, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_i2c_offset(struct unit_test_state *uts)
+{
+ struct udevice *eeprom;
+ struct udevice *dev;
+ uint8_t buf[5];
+
+ ut_assertok(i2c_get_chip_for_busnum(busnum, chip, 1, &dev));
+
+ /* Do a transfer so we can find the emulator */
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(uclass_first_device(UCLASS_I2C_EMUL, &eeprom));
+
+ /* Offset length 0 */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 0);
+ ut_assertok(i2c_set_chip_offset_len(dev, 0));
+ ut_assertok(dm_i2c_write(dev, 10 /* ignored */, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "AB\0\0\0\0", sizeof(buf)));
+
+ /* Offset length 1 */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 1);
+ ut_assertok(i2c_set_chip_offset_len(dev, 1));
+ ut_assertok(dm_i2c_write(dev, 2, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0, buf, 5));
+ ut_assertok(memcmp(buf, "ABAB\0", sizeof(buf)));
+
+ /* Offset length 2 */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 2);
+ ut_assertok(i2c_set_chip_offset_len(dev, 2));
+ ut_assertok(dm_i2c_write(dev, 0x210, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0x210, buf, 5));
+ ut_assertok(memcmp(buf, "AB\0\0\0", sizeof(buf)));
+
+ /* Offset length 3 */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 2);
+ ut_assertok(i2c_set_chip_offset_len(dev, 2));
+ ut_assertok(dm_i2c_write(dev, 0x410, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0x410, buf, 5));
+ ut_assertok(memcmp(buf, "AB\0\0\0", sizeof(buf)));
+
+ /* Offset length 4 */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 2);
+ ut_assertok(i2c_set_chip_offset_len(dev, 2));
+ ut_assertok(dm_i2c_write(dev, 0x420, (uint8_t *)"AB", 2));
+ ut_assertok(dm_i2c_read(dev, 0x420, buf, 5));
+ ut_assertok(memcmp(buf, "AB\0\0\0", sizeof(buf)));
+
+ /* Restore defaults */
+ sandbox_i2c_eeprom_set_offset_len(eeprom, 1);
+
+ return 0;
+}
+DM_TEST(dm_test_i2c_offset, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/i2s.c b/test/dm/i2s.c
new file mode 100644
index 00000000..49ebc352
--- /dev/null
+++ b/test/dm/i2s.c
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2018 Google LLC
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <i2s.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <asm/test.h>
+
+/* Basic test of the i2s codec uclass */
+static int dm_test_i2s(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u8 data[3];
+
+ /* check probe success */
+ ut_assertok(uclass_first_device_err(UCLASS_I2S, &dev));
+ data[0] = 1;
+ data[1] = 4;
+ data[2] = 6;
+ ut_assertok(i2s_tx_data(dev, data, ARRAY_SIZE(data)));
+ ut_asserteq(11, sandbox_get_i2s_sum(dev));
+ ut_assertok(i2s_tx_data(dev, data, 1));
+ ut_asserteq(12, sandbox_get_i2s_sum(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_i2s, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/led.c b/test/dm/led.c
new file mode 100644
index 00000000..00de7b39
--- /dev/null
+++ b/test/dm/led.c
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <led.h>
+#include <asm/gpio.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Base test of the led uclass */
+static int dm_test_led_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* Get the top-level device */
+ ut_assertok(uclass_get_device(UCLASS_LED, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 2, &dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 3, &dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 4, &dev));
+ ut_asserteq(-ENODEV, uclass_get_device(UCLASS_LED, 5, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_led_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test of the LED 'default-state' device tree property */
+static int dm_test_led_default_state(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* configure the default state (auto-probe) */
+ led_default_state();
+
+ /* Check that we handle the default-state property correctly. */
+ ut_assertok(led_get_by_label("sandbox:default_on", &dev));
+ ut_asserteq(LEDST_ON, led_get_state(dev));
+
+ ut_assertok(led_get_by_label("sandbox:default_off", &dev));
+ ut_asserteq(LEDST_OFF, led_get_state(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_led_default_state, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test of the led uclass using the led_gpio driver */
+static int dm_test_led_gpio(struct unit_test_state *uts)
+{
+ const int offset = 1;
+ struct udevice *dev, *gpio;
+
+ /*
+ * Check that we can manipulate an LED. LED 1 is connected to GPIO
+ * bank gpio_a, offset 1.
+ */
+ ut_assertok(uclass_get_device(UCLASS_LED, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 1, &gpio));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_assertok(led_set_state(dev, LEDST_ON));
+ ut_asserteq(1, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(LEDST_ON, led_get_state(dev));
+
+ ut_assertok(led_set_state(dev, LEDST_OFF));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(LEDST_OFF, led_get_state(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_led_gpio, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can toggle LEDs */
+static int dm_test_led_toggle(struct unit_test_state *uts)
+{
+ const int offset = 1;
+ struct udevice *dev, *gpio;
+
+ /*
+ * Check that we can manipulate an LED. LED 1 is connected to GPIO
+ * bank gpio_a, offset 1.
+ */
+ ut_assertok(uclass_get_device(UCLASS_LED, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 1, &gpio));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_assertok(led_set_state(dev, LEDST_TOGGLE));
+ ut_asserteq(1, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(LEDST_ON, led_get_state(dev));
+
+ ut_assertok(led_set_state(dev, LEDST_TOGGLE));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(LEDST_OFF, led_get_state(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_led_toggle, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test obtaining an LED by label */
+static int dm_test_led_label(struct unit_test_state *uts)
+{
+ struct udevice *dev, *cmp;
+
+ ut_assertok(led_get_by_label("sandbox:red", &dev));
+ ut_asserteq(1, device_active(dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 1, &cmp));
+ ut_asserteq_ptr(dev, cmp);
+
+ ut_assertok(led_get_by_label("sandbox:green", &dev));
+ ut_asserteq(1, device_active(dev));
+ ut_assertok(uclass_get_device(UCLASS_LED, 2, &cmp));
+ ut_asserteq_ptr(dev, cmp);
+
+ ut_asserteq(-ENODEV, led_get_by_label("sandbox:blue", &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_led_label, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test LED blinking */
+#ifdef CONFIG_LED_BLINK
+static int dm_test_led_blink(struct unit_test_state *uts)
+{
+ const int offset = 1;
+ struct udevice *dev, *gpio;
+
+ /*
+ * Check that we get an error when trying to blink an LED, since it is
+ * not supported by the GPIO LED driver.
+ */
+ ut_assertok(uclass_get_device(UCLASS_LED, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 1, &gpio));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(-ENOSYS, led_set_state(dev, LEDST_BLINK));
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, offset));
+ ut_asserteq(LEDST_OFF, led_get_state(dev));
+ ut_asserteq(-ENOSYS, led_set_period(dev, 100));
+
+ return 0;
+}
+DM_TEST(dm_test_led_blink, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+#endif
diff --git a/test/dm/mailbox.c b/test/dm/mailbox.c
new file mode 100644
index 00000000..4562d2ac
--- /dev/null
+++ b/test/dm/mailbox.c
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2016, NVIDIA CORPORATION.
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <asm/mbox.h>
+#include <test/ut.h>
+
+static int dm_test_mailbox(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ uint32_t msg;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "mbox-test", &dev));
+ ut_assertok(sandbox_mbox_test_get(dev));
+
+ ut_asserteq(-ETIMEDOUT, sandbox_mbox_test_recv(dev, &msg));
+ ut_assertok(sandbox_mbox_test_send(dev, 0xaaff9955UL));
+ ut_assertok(sandbox_mbox_test_recv(dev, &msg));
+ ut_asserteq(msg, 0xaaff9955UL ^ SANDBOX_MBOX_PING_XOR);
+ ut_asserteq(-ETIMEDOUT, sandbox_mbox_test_recv(dev, &msg));
+
+ ut_assertok(sandbox_mbox_test_free(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_mailbox, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/mdio.c b/test/dm/mdio.c
new file mode 100644
index 00000000..dc229aed
--- /dev/null
+++ b/test/dm/mdio.c
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2019
+ * Alex Marginean, NXP
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <misc.h>
+#include <test/ut.h>
+#include <miiphy.h>
+
+/* macros copied over from mdio_sandbox.c */
+#define SANDBOX_PHY_ADDR 5
+#define SANDBOX_PHY_REG_CNT 2
+
+/* test using 1st register, 0 */
+#define SANDBOX_PHY_REG 0
+
+#define TEST_REG_VALUE 0xabcd
+
+static int dm_test_mdio(struct unit_test_state *uts)
+{
+ struct uclass *uc;
+ struct udevice *dev;
+ struct mdio_ops *ops;
+ u16 reg;
+
+ ut_assertok(uclass_get(UCLASS_MDIO, &uc));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MDIO, "mdio-test", &dev));
+
+ ops = mdio_get_ops(dev);
+ ut_assertnonnull(ops);
+ ut_assertnonnull(ops->read);
+ ut_assertnonnull(ops->write);
+
+ ut_assertok(ops->write(dev, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG, TEST_REG_VALUE));
+ reg = ops->read(dev, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG);
+ ut_asserteq(reg, TEST_REG_VALUE);
+
+ ut_assert(ops->read(dev, SANDBOX_PHY_ADDR + 1, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG) != 0);
+
+ ut_assertok(ops->reset(dev));
+ reg = ops->read(dev, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG);
+ ut_asserteq(reg, 0);
+
+ return 0;
+}
+
+DM_TEST(dm_test_mdio, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/mdio_mux.c b/test/dm/mdio_mux.c
new file mode 100644
index 00000000..f962e09d
--- /dev/null
+++ b/test/dm/mdio_mux.c
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2019
+ * Alex Marginean, NXP
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <misc.h>
+#include <test/ut.h>
+#include <miiphy.h>
+
+/* macros copied over from mdio_sandbox.c */
+#define SANDBOX_PHY_ADDR 5
+#define SANDBOX_PHY_REG_CNT 2
+
+#define TEST_REG_VALUE 0xabcd
+
+static int dm_test_mdio_mux(struct unit_test_state *uts)
+{
+ struct uclass *uc;
+ struct udevice *mux;
+ struct udevice *mdio_ch0, *mdio_ch1, *mdio;
+ struct mdio_ops *ops, *ops_parent;
+ struct mdio_mux_ops *mmops;
+ u16 reg;
+
+ ut_assertok(uclass_get(UCLASS_MDIO_MUX, &uc));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MDIO_MUX, "mdio-mux-test",
+ &mux));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MDIO, "mdio-ch-test@0",
+ &mdio_ch0));
+ ut_assertok(uclass_get_device_by_name(UCLASS_MDIO, "mdio-ch-test@1",
+ &mdio_ch1));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MDIO, "mdio-test", &mdio));
+
+ ops = mdio_get_ops(mdio_ch0);
+ ut_assertnonnull(ops);
+ ut_assertnonnull(ops->read);
+ ut_assertnonnull(ops->write);
+
+ mmops = mdio_mux_get_ops(mux);
+ ut_assertnonnull(mmops);
+ ut_assertnonnull(mmops->select);
+
+ ops_parent = mdio_get_ops(mdio);
+ ut_assertnonnull(ops);
+ ut_assertnonnull(ops->read);
+
+ /*
+ * mux driver sets last register on the emulated PHY whenever a group
+ * is selected to the selection #. Just reading that register from
+ * either of the child buses should return the id of the child bus
+ */
+ reg = ops->read(mdio_ch0, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG_CNT - 1);
+ ut_asserteq(reg, 0);
+
+ reg = ops->read(mdio_ch1, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG_CNT - 1);
+ ut_asserteq(reg, 1);
+
+ mmops->select(mux, MDIO_MUX_SELECT_NONE, 5);
+ reg = ops_parent->read(mdio, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG_CNT - 1);
+ ut_asserteq(reg, 5);
+
+ mmops->deselect(mux, 5);
+ reg = ops_parent->read(mdio, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
+ SANDBOX_PHY_REG_CNT - 1);
+ ut_asserteq(reg, (u16)MDIO_MUX_SELECT_NONE);
+
+ return 0;
+}
+
+DM_TEST(dm_test_mdio_mux, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/misc.c b/test/dm/misc.c
new file mode 100644
index 00000000..4d4232ad
--- /dev/null
+++ b/test/dm/misc.c
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <misc.h>
+#include <test/ut.h>
+
+static int dm_test_misc(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u8 buf[16];
+ int id;
+ ulong last_ioctl;
+ bool enabled;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "misc-test", &dev));
+
+ /* Read / write tests */
+ ut_asserteq(4, misc_write(dev, 0, "TEST", 4));
+ ut_asserteq(5, misc_write(dev, 4, "WRITE", 5));
+ ut_asserteq(9, misc_read(dev, 0, buf, 9));
+
+ ut_assertok(memcmp(buf, "TESTWRITE", 9));
+
+ /* Call tests */
+
+ id = 0;
+ ut_assertok(misc_call(dev, 0, &id, 4, buf, 16));
+ ut_assertok(memcmp(buf, "Zero", 4));
+
+ id = 2;
+ ut_assertok(misc_call(dev, 0, &id, 4, buf, 16));
+ ut_assertok(memcmp(buf, "Two", 3));
+
+ ut_assertok(misc_call(dev, 1, &id, 4, buf, 16));
+ ut_assertok(memcmp(buf, "Forty-two", 9));
+
+ id = 1;
+ ut_assertok(misc_call(dev, 1, &id, 4, buf, 16));
+ ut_assertok(memcmp(buf, "Forty-one", 9));
+
+ /* IOCTL tests */
+
+ ut_assertok(misc_ioctl(dev, 6, NULL));
+ /* Read back last issued ioctl */
+ ut_assertok(misc_call(dev, 2, NULL, 0, &last_ioctl,
+ sizeof(last_ioctl)));
+ ut_asserteq(6, last_ioctl)
+
+ ut_assertok(misc_ioctl(dev, 23, NULL));
+ /* Read back last issued ioctl */
+ ut_assertok(misc_call(dev, 2, NULL, 0, &last_ioctl,
+ sizeof(last_ioctl)));
+ ut_asserteq(23, last_ioctl)
+
+ /* Enable / disable tests */
+
+ /* Read back enable/disable status */
+ ut_assertok(misc_call(dev, 3, NULL, 0, &enabled,
+ sizeof(enabled)));
+ ut_asserteq(true, enabled);
+
+ ut_assertok(misc_set_enabled(dev, false));
+ /* Read back enable/disable status */
+ ut_assertok(misc_call(dev, 3, NULL, 0, &enabled,
+ sizeof(enabled)));
+ ut_asserteq(false, enabled);
+
+ ut_assertok(misc_set_enabled(dev, true));
+ /* Read back enable/disable status */
+ ut_assertok(misc_call(dev, 3, NULL, 0, &enabled,
+ sizeof(enabled)));
+ ut_asserteq(true, enabled);
+
+ return 0;
+}
+
+DM_TEST(dm_test_misc, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/mmc.c b/test/dm/mmc.c
new file mode 100644
index 00000000..9ab0db1b
--- /dev/null
+++ b/test/dm/mmc.c
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <mmc.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/*
+ * Basic test of the mmc uclass. We could expand this by implementing an MMC
+ * stack for sandbox, or at least implementing the basic operation.
+ */
+static int dm_test_mmc_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_MMC, 0, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_mmc_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_mmc_blk(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct blk_desc *dev_desc;
+ char cmp[1024];
+
+ ut_assertok(uclass_get_device(UCLASS_MMC, 0, &dev));
+ ut_assertok(blk_get_device_by_str("mmc", "0", &dev_desc));
+
+ /* Read a few blocks and look for the string we expect */
+ ut_asserteq(512, dev_desc->blksz);
+ memset(cmp, '\0', sizeof(cmp));
+ ut_asserteq(2, blk_dread(dev_desc, 0, 2, cmp));
+ ut_assertok(strcmp(cmp, "this is a test"));
+
+ return 0;
+}
+DM_TEST(dm_test_mmc_blk, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/nop.c b/test/dm/nop.c
new file mode 100644
index 00000000..2df29f3d
--- /dev/null
+++ b/test/dm/nop.c
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test for the NOP uclass
+ *
+ * (C) Copyright 2019 - Texas Instruments Incorporated - http://www.ti.com/
+ * Jean-Jacques Hiblot <jjhiblot@ti.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/ofnode.h>
+#include <dm/lists.h>
+#include <dm/device.h>
+#include <dm/test.h>
+#include <misc.h>
+#include <test/ut.h>
+
+static int noptest_bind(struct udevice *parent)
+{
+ ofnode ofnode = dev_read_first_subnode(parent);
+
+ while (ofnode_valid(ofnode)) {
+ struct udevice *dev;
+ const char *bind_flag = ofnode_read_string(ofnode, "bind");
+
+ if (bind_flag && (strcmp(bind_flag, "True") == 0))
+ lists_bind_fdt(parent, ofnode, &dev, false);
+ ofnode = dev_read_next_subnode(ofnode);
+ }
+
+ return 0;
+}
+
+static const struct udevice_id noptest1_ids[] = {
+ {
+ .compatible = "sandbox,nop_sandbox1",
+ },
+ { }
+};
+
+U_BOOT_DRIVER(noptest_drv1) = {
+ .name = "noptest1_drv",
+ .of_match = noptest1_ids,
+ .id = UCLASS_NOP,
+ .bind = noptest_bind,
+};
+
+static const struct udevice_id noptest2_ids[] = {
+ {
+ .compatible = "sandbox,nop_sandbox2",
+ },
+ { }
+};
+
+U_BOOT_DRIVER(noptest_drv2) = {
+ .name = "noptest2_drv",
+ .of_match = noptest2_ids,
+ .id = UCLASS_NOP,
+};
+
+static int dm_test_nop(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_NOP, "nop-test_0", &dev));
+ ut_assertok(uclass_get_device_by_name(UCLASS_NOP, "nop-test_1", &dev));
+ ut_asserteq(-ENODEV,
+ uclass_get_device_by_name(UCLASS_NOP, "nop-test_2", &dev));
+
+ return 0;
+}
+
+DM_TEST(dm_test_nop, DM_TESTF_FLAT_TREE | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/ofnode.c b/test/dm/ofnode.c
new file mode 100644
index 00000000..745de50c
--- /dev/null
+++ b/test/dm/ofnode.c
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+#include <common.h>
+#include <dm.h>
+#include <dm/of_extra.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+static int dm_test_ofnode_compatible(struct unit_test_state *uts)
+{
+ ofnode root_node = ofnode_path("/");
+
+ ut_assert(ofnode_valid(root_node));
+ ut_assert(ofnode_device_is_compatible(root_node, "sandbox"));
+
+ return 0;
+}
+DM_TEST(dm_test_ofnode_compatible, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_ofnode_by_prop_value(struct unit_test_state *uts)
+{
+ const char propname[] = "compatible";
+ const char propval[] = "denx,u-boot-fdt-test";
+ const char *str;
+ ofnode node = ofnode_null();
+
+ /* Find first matching node, there should be at least one */
+ node = ofnode_by_prop_value(node, propname, propval, sizeof(propval));
+ ut_assert(ofnode_valid(node));
+ str = ofnode_read_string(node, propname);
+ ut_assert(str && !strcmp(str, propval));
+
+ /* Find the rest of the matching nodes */
+ while (true) {
+ node = ofnode_by_prop_value(node, propname, propval,
+ sizeof(propval));
+ if (!ofnode_valid(node))
+ break;
+ str = ofnode_read_string(node, propname);
+ ut_assert(str && !strcmp(str, propval));
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_ofnode_by_prop_value, DM_TESTF_SCAN_FDT);
+
+static int dm_test_ofnode_fmap(struct unit_test_state *uts)
+{
+ struct fmap_entry entry;
+ ofnode node;
+
+ node = ofnode_path("/cros-ec/flash");
+ ut_assert(ofnode_valid(node));
+ ut_assertok(ofnode_read_fmap_entry(node, &entry));
+ ut_asserteq(0x08000000, entry.offset);
+ ut_asserteq(0x20000, entry.length);
+
+ return 0;
+}
+DM_TEST(dm_test_ofnode_fmap, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/osd.c b/test/dm/osd.c
new file mode 100644
index 00000000..6910690b
--- /dev/null
+++ b/test/dm/osd.c
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <display_options.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <video_osd.h>
+#include <asm/test.h>
+
+#include "../../drivers/video/sandbox_osd.h"
+
+const uint memsize = 2 * 10 * 10;
+
+static void split(u8 *mem, uint size, u8 *text, u8 *colors)
+{
+ int i;
+ u16 *p = (u16 *)mem;
+
+ for (i = 0; i < size; i++) {
+ colors[i] = p[i] % 0x100;
+ text[i] = p[i] / 0x100;
+ }
+}
+
+static void print_mem(u8 *mem, uint width, uint height)
+{
+ const uint memsize = 2 * 10 * 10;
+ u8 colors[memsize / 2];
+ u8 text[memsize / 2];
+ int i;
+
+ split(mem, memsize / 2, text, colors);
+
+ for (i = 0; i < width * height; i++) {
+ printf("%c", text[i]);
+ if (i > 0 && ((i + 1) % width) == 0)
+ printf("\n");
+ }
+
+ printf("\n");
+
+ for (i = 0; i < width * height; i++) {
+ printf("%c", colors[i]);
+ if (i > 0 && ((i + 1) % width) == 0)
+ printf("\n");
+ }
+}
+
+static int dm_test_osd_basics(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u8 mem[memsize + 1];
+ u8 colors[memsize / 2];
+ u8 text[memsize / 2];
+ struct video_osd_info info;
+
+ ut_assertok(uclass_first_device_err(UCLASS_VIDEO_OSD, &dev));
+
+ video_osd_get_info(dev, &info);
+
+ ut_asserteq(10, info.width);
+ ut_asserteq(10, info.height);
+ ut_asserteq(1, info.major_version);
+ ut_asserteq(0, info.minor_version);
+
+ ut_assertok(sandbox_osd_get_mem(dev, mem, memsize));
+ split(mem, memsize / 2, text, colors);
+
+ ut_assertok(memcmp(text, " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " ", memsize / 2));
+
+ ut_assertok(memcmp(colors, "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk", memsize / 2));
+
+ print_mem(mem, 10, 10);
+
+ ut_assertok(video_osd_print(dev, 1, 1, COLOR_RED, "Blah"));
+
+ ut_assertok(sandbox_osd_get_mem(dev, mem, memsize));
+ split(mem, memsize / 2, text, colors);
+
+ ut_assertok(memcmp(text, " "
+ " Blah "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " ", memsize / 2));
+
+ ut_assertok(memcmp(colors, "kkkkkkkkkk"
+ "krrrrkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk"
+ "kkkkkkkkkk", memsize / 2));
+
+ print_mem(mem, 10, 10);
+
+ return 0;
+}
+
+DM_TEST(dm_test_osd_basics, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_osd_extended(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u8 mem[memsize + 1];
+ u8 colors[memsize / 2];
+ u8 text[memsize / 2];
+ struct video_osd_info info;
+ u16 val;
+
+ ut_assertok(uclass_first_device_err(UCLASS_VIDEO_OSD, &dev));
+
+ ut_assertok(video_osd_set_size(dev, 20, 5));
+
+ video_osd_get_info(dev, &info);
+
+ ut_asserteq(20, info.width);
+ ut_asserteq(5, info.height);
+ ut_asserteq(1, info.major_version);
+ ut_asserteq(0, info.minor_version);
+
+ ut_assertok(sandbox_osd_get_mem(dev, mem, memsize));
+ split(mem, memsize / 2, text, colors);
+
+ ut_assertok(memcmp(text, " "
+ " "
+ " "
+ " "
+ " ", memsize / 2));
+
+ ut_assertok(memcmp(colors, "kkkkkkkkkkkkkkkkkkkk"
+ "kkkkkkkkkkkkkkkkkkkk"
+ "kkkkkkkkkkkkkkkkkkkk"
+ "kkkkkkkkkkkkkkkkkkkk"
+ "kkkkkkkkkkkkkkkkkkkk", memsize / 2));
+
+ print_mem(mem, 20, 5);
+
+ /* Draw green border */
+ val = '-' * 0x100 + 'g';
+ ut_assertok(video_osd_set_mem(dev, 1, 0, (u8 *)&val, 2, 18));
+ ut_assertok(video_osd_set_mem(dev, 1, 4, (u8 *)&val, 2, 18));
+ ut_assertok(video_osd_print(dev, 0, 1, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 0, 2, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 0, 3, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 19, 1, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 19, 2, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 19, 3, COLOR_GREEN, "|"));
+ ut_assertok(video_osd_print(dev, 0, 0, COLOR_GREEN, "+"));
+ ut_assertok(video_osd_print(dev, 19, 0, COLOR_GREEN, "+"));
+ ut_assertok(video_osd_print(dev, 19, 4, COLOR_GREEN, "+"));
+ ut_assertok(video_osd_print(dev, 0, 4, COLOR_GREEN, "+"));
+
+ /* Add menu caption and entries */
+ ut_assertok(video_osd_print(dev, 5, 0, COLOR_GREEN, " OSD menu "));
+ ut_assertok(video_osd_print(dev, 2, 1, COLOR_BLUE, " * Entry 1"));
+ ut_assertok(video_osd_print(dev, 2, 2, COLOR_BLUE, "(*) Entry 2"));
+ ut_assertok(video_osd_print(dev, 2, 3, COLOR_BLUE, " * Entry 3"));
+
+ ut_assertok(sandbox_osd_get_mem(dev, mem, memsize));
+ split(mem, memsize / 2, text, colors);
+
+ print_mem(mem, 20, 5);
+
+ ut_assertok(memcmp(text, "+---- OSD menu ----+"
+ "| * Entry 1 |"
+ "| (*) Entry 2 |"
+ "| * Entry 3 |"
+ "+------------------+", memsize / 2));
+
+ ut_assertok(memcmp(colors, "gggggggggggggggggggg"
+ "gkbbbbbbbbbbbkkkkkkg"
+ "gkbbbbbbbbbbbkkkkkkg"
+ "gkbbbbbbbbbbbkkkkkkg"
+ "gggggggggggggggggggg", memsize / 2));
+
+ return 0;
+}
+
+DM_TEST(dm_test_osd_extended, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/panel.c b/test/dm/panel.c
new file mode 100644
index 00000000..7e4ebd6d
--- /dev/null
+++ b/test/dm/panel.c
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test for panel uclass
+ *
+ * Copyright (c) 2018 Google, Inc
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <backlight.h>
+#include <dm.h>
+#include <panel.h>
+#include <video.h>
+#include <asm/gpio.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <power/regulator.h>
+
+/* Basic test of the panel uclass */
+static int dm_test_panel(struct unit_test_state *uts)
+{
+ struct udevice *dev, *pwm, *gpio, *reg;
+ uint period_ns;
+ uint duty_ns;
+ bool enable;
+ bool polarity;
+
+ ut_assertok(uclass_first_device_err(UCLASS_PANEL, &dev));
+ ut_assertok(uclass_first_device_err(UCLASS_PWM, &pwm));
+ ut_assertok(uclass_get_device(UCLASS_GPIO, 1, &gpio));
+ ut_assertok(regulator_get_by_platname("VDD_EMMC_1.8V", &reg));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(false, enable);
+ ut_asserteq(false, regulator_get_enable(reg));
+
+ ut_assertok(panel_enable_backlight(dev));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(1000, period_ns);
+ ut_asserteq(170 * 1000 / 256, duty_ns);
+ ut_asserteq(true, enable);
+ ut_asserteq(false, polarity);
+ ut_asserteq(1, sandbox_gpio_get_value(gpio, 1));
+ ut_asserteq(true, regulator_get_enable(reg));
+
+ ut_assertok(panel_set_backlight(dev, 40));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(64 * 1000 / 256, duty_ns);
+
+ ut_assertok(panel_set_backlight(dev, BACKLIGHT_MAX));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(255 * 1000 / 256, duty_ns);
+
+ ut_assertok(panel_set_backlight(dev, BACKLIGHT_MIN));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(0 * 1000 / 256, duty_ns);
+ ut_asserteq(1, sandbox_gpio_get_value(gpio, 1));
+
+ ut_assertok(panel_set_backlight(dev, BACKLIGHT_DEFAULT));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(true, enable);
+ ut_asserteq(170 * 1000 / 256, duty_ns);
+
+ ut_assertok(panel_set_backlight(dev, BACKLIGHT_OFF));
+ ut_assertok(sandbox_pwm_get_config(pwm, 0, &period_ns, &duty_ns,
+ &enable, &polarity));
+ ut_asserteq(0 * 1000 / 256, duty_ns);
+ ut_asserteq(0, sandbox_gpio_get_value(gpio, 1));
+ ut_asserteq(false, regulator_get_enable(reg));
+
+ return 0;
+}
+DM_TEST(dm_test_panel, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/pch.c b/test/dm/pch.c
new file mode 100644
index 00000000..54e33d18
--- /dev/null
+++ b/test/dm/pch.c
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2018 Google LLC
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <pch.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Test that sandbox PCH works correctly */
+static int dm_test_pch_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u32 gbase, iobase;
+ ulong sbase;
+
+ ut_assertok(uclass_first_device_err(UCLASS_PCH, &dev));
+ ut_assertok(pch_get_spi_base(dev, &sbase));
+ ut_asserteq(0x10, sbase);
+
+ ut_asserteq(0, sandbox_get_pch_spi_protect(dev));
+ ut_assertok(pch_set_spi_protect(dev, true));
+ ut_asserteq(1, sandbox_get_pch_spi_protect(dev));
+
+ ut_assertok(pch_get_gpio_base(dev, &gbase));
+ ut_asserteq(0x20, gbase);
+
+ ut_assertok(pch_get_io_base(dev, &iobase));
+ ut_asserteq(0x30, iobase);
+
+ return 0;
+}
+DM_TEST(dm_test_pch_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test sandbox PCH ioctl */
+static int dm_test_pch_ioctl(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ char data;
+
+ ut_assertok(uclass_first_device_err(UCLASS_PCH, &dev));
+
+ ut_asserteq(-ENOSYS, pch_ioctl(dev, PCH_REQ_TEST1, NULL, 0));
+
+ ut_asserteq('a', pch_ioctl(dev, PCH_REQ_TEST2, "a", 1));
+
+ ut_asserteq(1, pch_ioctl(dev, PCH_REQ_TEST3, &data, 1));
+ ut_asserteq('x', data);
+
+ return 0;
+}
+DM_TEST(dm_test_pch_ioctl, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/pci.c b/test/dm/pci.c
new file mode 100644
index 00000000..fb93e4c7
--- /dev/null
+++ b/test/dm/pci.c
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <asm/io.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Test that sandbox PCI works correctly */
+static int dm_test_pci_base(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+
+ ut_assertok(uclass_get_device(UCLASS_PCI, 0, &bus));
+
+ return 0;
+}
+DM_TEST(dm_test_pci_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that sandbox PCI bus numbering and device works correctly */
+static int dm_test_pci_busdev(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+ struct udevice *swap;
+ u16 vendor, device;
+
+ /* Test bus#0 and its devices */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 0, &bus));
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x00, 0), &swap));
+ vendor = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_VENDOR_ID, &vendor));
+ ut_asserteq(SANDBOX_PCI_VENDOR_ID, vendor);
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1f, 0), &swap));
+ device = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_DEVICE_ID, &device));
+ ut_asserteq(SANDBOX_PCI_SWAP_CASE_EMUL_ID, device);
+
+ /* Test bus#1 and its devices */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 1, &bus));
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x08, 0), &swap));
+ vendor = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_VENDOR_ID, &vendor));
+ ut_asserteq(SANDBOX_PCI_VENDOR_ID, vendor);
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x0c, 0), &swap));
+ device = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_DEVICE_ID, &device));
+ ut_asserteq(SANDBOX_PCI_SWAP_CASE_EMUL_ID, device);
+
+ return 0;
+}
+DM_TEST(dm_test_pci_busdev, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can use the swapcase device correctly */
+static int dm_test_pci_swapcase(struct unit_test_state *uts)
+{
+ struct udevice *swap;
+ ulong io_addr, mem_addr;
+ char *ptr;
+
+ /* Check that asking for the device 0 automatically fires up PCI */
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x00, 0), &swap));
+
+ /* First test I/O */
+ io_addr = dm_pci_read_bar32(swap, 0);
+ outb(2, io_addr);
+ ut_asserteq(2, inb(io_addr));
+
+ /*
+ * Now test memory mapping - note we must unmap and remap to cause
+ * the swapcase emulation to see our data and response.
+ */
+ mem_addr = dm_pci_read_bar32(swap, 1);
+ ptr = map_sysmem(mem_addr, 20);
+ strcpy(ptr, "This is a TesT");
+ unmap_sysmem(ptr);
+
+ ptr = map_sysmem(mem_addr, 20);
+ ut_asserteq_str("tHIS IS A tESt", ptr);
+ unmap_sysmem(ptr);
+
+ /* Check that asking for the device 1 automatically fires up PCI */
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1f, 0), &swap));
+
+ /* First test I/O */
+ io_addr = dm_pci_read_bar32(swap, 0);
+ outb(2, io_addr);
+ ut_asserteq(2, inb(io_addr));
+
+ /*
+ * Now test memory mapping - note we must unmap and remap to cause
+ * the swapcase emulation to see our data and response.
+ */
+ mem_addr = dm_pci_read_bar32(swap, 1);
+ ptr = map_sysmem(mem_addr, 20);
+ strcpy(ptr, "This is a TesT");
+ unmap_sysmem(ptr);
+
+ ptr = map_sysmem(mem_addr, 20);
+ ut_asserteq_str("tHIS IS A tESt", ptr);
+ unmap_sysmem(ptr);
+
+ return 0;
+}
+DM_TEST(dm_test_pci_swapcase, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can dynamically bind the device driver correctly */
+static int dm_test_pci_drvdata(struct unit_test_state *uts)
+{
+ struct udevice *bus, *swap;
+
+ /* Check that asking for the device automatically fires up PCI */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 1, &bus));
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x08, 0), &swap));
+ ut_asserteq(SWAP_CASE_DRV_DATA, swap->driver_data);
+ ut_assertok(dev_of_valid(swap));
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x0c, 0), &swap));
+ ut_asserteq(SWAP_CASE_DRV_DATA, swap->driver_data);
+ ut_assertok(dev_of_valid(swap));
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x10, 0), &swap));
+ ut_asserteq(SWAP_CASE_DRV_DATA, swap->driver_data);
+ ut_assertok(!dev_of_valid(swap));
+
+ return 0;
+}
+DM_TEST(dm_test_pci_drvdata, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that devices on PCI bus#2 can be accessed correctly */
+static int dm_test_pci_mixed(struct unit_test_state *uts)
+{
+ /* PCI bus#2 has both statically and dynamic declared devices */
+ struct udevice *bus, *swap;
+ u16 vendor, device;
+ ulong io_addr, mem_addr;
+ char *ptr;
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 2, &bus));
+
+ /* Test the dynamic device */
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(2, 0x08, 0), &swap));
+ vendor = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_VENDOR_ID, &vendor));
+ ut_asserteq(SANDBOX_PCI_VENDOR_ID, vendor);
+
+ /* First test I/O */
+ io_addr = dm_pci_read_bar32(swap, 0);
+ outb(2, io_addr);
+ ut_asserteq(2, inb(io_addr));
+
+ /*
+ * Now test memory mapping - note we must unmap and remap to cause
+ * the swapcase emulation to see our data and response.
+ */
+ mem_addr = dm_pci_read_bar32(swap, 1);
+ ptr = map_sysmem(mem_addr, 30);
+ strcpy(ptr, "This is a TesT oN dYNAMIc");
+ unmap_sysmem(ptr);
+
+ ptr = map_sysmem(mem_addr, 30);
+ ut_asserteq_str("tHIS IS A tESt On DynamiC", ptr);
+ unmap_sysmem(ptr);
+
+ /* Test the static device */
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(2, 0x1f, 0), &swap));
+ device = 0;
+ ut_assertok(dm_pci_read_config16(swap, PCI_DEVICE_ID, &device));
+ ut_asserteq(SANDBOX_PCI_SWAP_CASE_EMUL_ID, device);
+
+ /* First test I/O */
+ io_addr = dm_pci_read_bar32(swap, 0);
+ outb(2, io_addr);
+ ut_asserteq(2, inb(io_addr));
+
+ /*
+ * Now test memory mapping - note we must unmap and remap to cause
+ * the swapcase emulation to see our data and response.
+ */
+ mem_addr = dm_pci_read_bar32(swap, 1);
+ ptr = map_sysmem(mem_addr, 30);
+ strcpy(ptr, "This is a TesT oN sTATIc");
+ unmap_sysmem(ptr);
+
+ ptr = map_sysmem(mem_addr, 30);
+ ut_asserteq_str("tHIS IS A tESt On StatiC", ptr);
+ unmap_sysmem(ptr);
+
+ return 0;
+}
+DM_TEST(dm_test_pci_mixed, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test looking up PCI capability and extended capability */
+static int dm_test_pci_cap(struct unit_test_state *uts)
+{
+ struct udevice *bus, *swap;
+ int cap;
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 0, &bus));
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1f, 0), &swap));
+
+ /* look up PCI_CAP_ID_EXP */
+ cap = dm_pci_find_capability(swap, PCI_CAP_ID_EXP);
+ ut_asserteq(PCI_CAP_ID_EXP_OFFSET, cap);
+
+ /* look up PCI_CAP_ID_PCIX */
+ cap = dm_pci_find_capability(swap, PCI_CAP_ID_PCIX);
+ ut_asserteq(0, cap);
+
+ /* look up PCI_CAP_ID_MSIX starting from PCI_CAP_ID_PM_OFFSET */
+ cap = dm_pci_find_next_capability(swap, PCI_CAP_ID_PM_OFFSET,
+ PCI_CAP_ID_MSIX);
+ ut_asserteq(PCI_CAP_ID_MSIX_OFFSET, cap);
+
+ /* look up PCI_CAP_ID_VNDR starting from PCI_CAP_ID_EXP_OFFSET */
+ cap = dm_pci_find_next_capability(swap, PCI_CAP_ID_EXP_OFFSET,
+ PCI_CAP_ID_VNDR);
+ ut_asserteq(0, cap);
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 1, &bus));
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(1, 0x08, 0), &swap));
+
+ /* look up PCI_EXT_CAP_ID_DSN */
+ cap = dm_pci_find_ext_capability(swap, PCI_EXT_CAP_ID_DSN);
+ ut_asserteq(PCI_EXT_CAP_ID_DSN_OFFSET, cap);
+
+ /* look up PCI_EXT_CAP_ID_SRIOV */
+ cap = dm_pci_find_ext_capability(swap, PCI_EXT_CAP_ID_SRIOV);
+ ut_asserteq(0, cap);
+
+ /* look up PCI_EXT_CAP_ID_DSN starting from PCI_EXT_CAP_ID_ERR_OFFSET */
+ cap = dm_pci_find_next_ext_capability(swap, PCI_EXT_CAP_ID_ERR_OFFSET,
+ PCI_EXT_CAP_ID_DSN);
+ ut_asserteq(PCI_EXT_CAP_ID_DSN_OFFSET, cap);
+
+ /* look up PCI_EXT_CAP_ID_RCRB starting from PCI_EXT_CAP_ID_VC_OFFSET */
+ cap = dm_pci_find_next_ext_capability(swap, PCI_EXT_CAP_ID_VC_OFFSET,
+ PCI_EXT_CAP_ID_RCRB);
+ ut_asserteq(0, cap);
+
+ return 0;
+}
+DM_TEST(dm_test_pci_cap, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test looking up BARs in EA capability structure */
+static int dm_test_pci_ea(struct unit_test_state *uts)
+{
+ struct udevice *bus, *swap;
+ void *bar;
+ int cap;
+
+ /*
+ * use emulated device mapping function, we're not using real physical
+ * addresses in this test
+ */
+ sandbox_set_enable_pci_map(true);
+
+ ut_assertok(uclass_get_device_by_seq(UCLASS_PCI, 0, &bus));
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x01, 0), &swap));
+
+ /* look up PCI_CAP_ID_EA */
+ cap = dm_pci_find_capability(swap, PCI_CAP_ID_EA);
+ ut_asserteq(PCI_CAP_ID_EA_OFFSET, cap);
+
+ /* test swap case in BAR 1 */
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_0, 0);
+ ut_assertnonnull(bar);
+ *(int *)bar = 2; /* swap upper/lower */
+
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_1, 0);
+ ut_assertnonnull(bar);
+ strcpy(bar, "ea TEST");
+ unmap_sysmem(bar);
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_1, 0);
+ ut_assertnonnull(bar);
+ ut_asserteq_str("EA test", bar);
+
+ /* test magic values in BARs2, 4; BAR 3 is n/a */
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_2, 0);
+ ut_assertnonnull(bar);
+ ut_asserteq(PCI_EA_BAR2_MAGIC, *(u32 *)bar);
+
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_3, 0);
+ ut_assertnull(bar);
+
+ bar = dm_pci_map_bar(swap, PCI_BASE_ADDRESS_4, 0);
+ ut_assertnonnull(bar);
+ ut_asserteq(PCI_EA_BAR4_MAGIC, *(u32 *)bar);
+
+ return 0;
+}
+DM_TEST(dm_test_pci_ea, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test the dev_read_addr_pci() function */
+static int dm_test_pci_addr_flat(struct unit_test_state *uts)
+{
+ struct udevice *swap1f, *swap1;
+ ulong io_addr, mem_addr;
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1f, 0), &swap1f));
+ io_addr = dm_pci_read_bar32(swap1f, 0);
+ ut_asserteq(io_addr, dev_read_addr_pci(swap1f));
+
+ /*
+ * This device has both I/O and MEM spaces but the MEM space appears
+ * first
+ */
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1, 0), &swap1));
+ mem_addr = dm_pci_read_bar32(swap1, 1);
+ ut_asserteq(mem_addr, dev_read_addr_pci(swap1));
+
+ return 0;
+}
+DM_TEST(dm_test_pci_addr_flat, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT |
+ DM_TESTF_FLAT_TREE);
+
+/*
+ * Test the dev_read_addr_pci() function with livetree. That function is
+ * not currently fully implemented, in that it fails to return the BAR address.
+ * Once that is implemented this test can be removed and dm_test_pci_addr_flat()
+ * can be used for both flattree and livetree by removing the DM_TESTF_FLAT_TREE
+ * flag above.
+ */
+static int dm_test_pci_addr_live(struct unit_test_state *uts)
+{
+ struct udevice *swap1f, *swap1;
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1f, 0), &swap1f));
+ ut_asserteq(FDT_ADDR_T_NONE, dev_read_addr_pci(swap1f));
+
+ ut_assertok(dm_pci_bus_find_bdf(PCI_BDF(0, 0x1, 0), &swap1));
+ ut_asserteq(FDT_ADDR_T_NONE, dev_read_addr_pci(swap1));
+
+ return 0;
+}
+DM_TEST(dm_test_pci_addr_live, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT |
+ DM_TESTF_LIVE_TREE);
diff --git a/test/dm/pci_ep.c b/test/dm/pci_ep.c
new file mode 100644
index 00000000..101f8617
--- /dev/null
+++ b/test/dm/pci_ep.c
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019 Ramon Fried
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <asm/io.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <hexdump.h>
+#include <pci_ep.h>
+
+/* Test that sandbox PCI EP works correctly */
+static int dm_test_pci_ep_base(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+ struct pci_bar tmp_bar;
+ struct pci_ep_header tmp_header;
+ int i;
+
+ struct pci_ep_header ep_header = {
+ .vendorid = 0x1234,
+ .deviceid = 0x2020,
+ .revid = 1,
+ .interrupt_pin = PCI_INTERRUPT_INTA,
+ };
+
+ struct pci_bar bar = {
+ .phys_addr = 0x80000000,
+ .size = 0x100000,
+ .barno = BAR_0,
+ .flags = PCI_BASE_ADDRESS_MEM_TYPE_64 |
+ PCI_BASE_ADDRESS_MEM_PREFETCH,
+ };
+
+ ut_assertok(uclass_get_device(UCLASS_PCI_EP, 0, &bus));
+ ut_assertnonnull(bus);
+
+ ut_assertok(pci_ep_write_header(bus, 0, &ep_header));
+ ut_assertok(pci_ep_read_header(bus, 0, &tmp_header));
+ ut_asserteq_mem(&tmp_header, &ep_header, sizeof(ep_header));
+
+ ut_assertok(pci_ep_set_msi(bus, 0, 4));
+ ut_asserteq(pci_ep_get_msi(bus, 0), 4);
+
+ ut_assertok(pci_ep_set_msix(bus, 0, 360));
+ ut_asserteq(pci_ep_get_msix(bus, 0), 360);
+
+ ut_assertok(pci_ep_set_bar(bus, 0, &bar));
+
+ ut_assertok(pci_ep_read_bar(bus, 0, &tmp_bar, BAR_0));
+ ut_asserteq_mem(&tmp_bar, &bar, sizeof(bar));
+
+ for (i = 0; i < 10; i++)
+ ut_assertok(pci_ep_raise_irq(bus, 0, 1, PCI_EP_IRQ_LEGACY));
+
+ ut_asserteq(sandbox_get_pci_ep_irq_count(bus), 10);
+ return 0;
+}
+
+DM_TEST(dm_test_pci_ep_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
diff --git a/test/dm/phy.c b/test/dm/phy.c
new file mode 100644
index 00000000..21d92194
--- /dev/null
+++ b/test/dm/phy.c
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2017 Texas Instruments Incorporated - http://www.ti.com/
+ * Written by Jean-Jacques Hiblot <jjhiblot@ti.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <generic-phy.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Base test of the phy uclass */
+static int dm_test_phy_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct phy phy1_method1;
+ struct phy phy1_method2;
+ struct phy phy2;
+ struct phy phy3;
+ struct udevice *parent;
+
+ /* Get the device using the phy device*/
+ ut_assertok(uclass_get_device_by_name(UCLASS_SIMPLE_BUS,
+ "gen_phy_user", &parent));
+ /*
+ * Get the same phy port in 2 different ways and compare.
+ */
+ ut_assertok(generic_phy_get_by_name(parent, "phy1", &phy1_method1))
+ ut_assertok(generic_phy_get_by_index(parent, 0, &phy1_method2))
+ ut_asserteq(phy1_method1.id, phy1_method2.id);
+
+ /*
+ * Get the second phy port. Check that the same phy provider (device)
+ * provides this 2nd phy port, but that the IDs are different
+ */
+ ut_assertok(generic_phy_get_by_name(parent, "phy2", &phy2))
+ ut_asserteq_ptr(phy1_method2.dev, phy2.dev);
+ ut_assert(phy1_method1.id != phy2.id);
+
+ /*
+ * Get the third phy port. Check that the phy provider is different
+ */
+ ut_assertok(generic_phy_get_by_name(parent, "phy3", &phy3))
+ ut_assert(phy2.dev != phy3.dev);
+
+ /* Try to get a non-existing phy */
+ ut_asserteq(-ENODEV, uclass_get_device(UCLASS_PHY, 3, &dev));
+ ut_asserteq(-ENODATA, generic_phy_get_by_name(parent,
+ "phy_not_existing", &phy1_method1));
+
+ return 0;
+}
+DM_TEST(dm_test_phy_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test of the phy uclass using the sandbox phy driver operations */
+static int dm_test_phy_ops(struct unit_test_state *uts)
+{
+ struct phy phy1;
+ struct phy phy2;
+ struct phy phy3;
+ struct udevice *parent;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_SIMPLE_BUS,
+ "gen_phy_user", &parent));
+
+ ut_assertok(generic_phy_get_by_name(parent, "phy1", &phy1));
+ ut_asserteq(0, phy1.id);
+ ut_assertok(generic_phy_get_by_name(parent, "phy2", &phy2));
+ ut_asserteq(1, phy2.id);
+ ut_assertok(generic_phy_get_by_name(parent, "phy3", &phy3));
+ ut_asserteq(0, phy3.id);
+
+ /* test normal operations */
+ ut_assertok(generic_phy_init(&phy1));
+ ut_assertok(generic_phy_power_on(&phy1));
+ ut_assertok(generic_phy_power_off(&phy1));
+
+ /*
+ * test operations after exit().
+ * The sandbox phy driver does not allow it.
+ */
+ ut_assertok(generic_phy_exit(&phy1));
+ ut_assert(generic_phy_power_on(&phy1) != 0);
+ ut_assert(generic_phy_power_off(&phy1) != 0);
+
+ /*
+ * test normal operations again (after re-init)
+ */
+ ut_assertok(generic_phy_init(&phy1));
+ ut_assertok(generic_phy_power_on(&phy1));
+ ut_assertok(generic_phy_power_off(&phy1));
+
+ /*
+ * test calling unimplemented feature.
+ * The call is expected to succeed
+ */
+ ut_assertok(generic_phy_reset(&phy1));
+
+ /* PHY2 has a known problem with power off */
+ ut_assertok(generic_phy_init(&phy2));
+ ut_assertok(generic_phy_power_on(&phy2));
+ ut_asserteq(-EIO, generic_phy_power_off(&phy2));
+
+ /* PHY3 has a known problem with power off and power on */
+ ut_assertok(generic_phy_init(&phy3));
+ ut_asserteq(-EIO, generic_phy_power_off(&phy3));
+ ut_asserteq(-EIO, generic_phy_power_off(&phy3));
+
+ return 0;
+}
+DM_TEST(dm_test_phy_ops, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/pmic.c b/test/dm/pmic.c
new file mode 100644
index 00000000..b582329a
--- /dev/null
+++ b/test/dm/pmic.c
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Tests for the driver model pmic API
+ *
+ * Copyright (c) 2015 Samsung Electronics
+ * Przemyslaw Marczak <p.marczak@samsung.com>
+ */
+
+#include <common.h>
+#include <errno.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <malloc.h>
+#include <dm/device-internal.h>
+#include <dm/root.h>
+#include <dm/util.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <power/pmic.h>
+#include <power/sandbox_pmic.h>
+#include <test/ut.h>
+#include <fsl_pmic.h>
+
+/* Test PMIC get method */
+
+static inline int power_pmic_get(struct unit_test_state *uts, char *name)
+{
+ struct udevice *dev;
+
+ ut_assertok(pmic_get(name, &dev));
+ ut_assertnonnull(dev);
+
+ /* Check PMIC's name */
+ ut_asserteq_str(name, dev->name);
+
+ return 0;
+}
+
+/* Test PMIC get method */
+static int dm_test_power_pmic_get(struct unit_test_state *uts)
+{
+ power_pmic_get(uts, "sandbox_pmic");
+
+ return 0;
+}
+DM_TEST(dm_test_power_pmic_get, DM_TESTF_SCAN_FDT);
+
+/* PMIC get method - MC34708 - for 3 bytes transmission */
+static int dm_test_power_pmic_mc34708_get(struct unit_test_state *uts)
+{
+ power_pmic_get(uts, "pmic@41");
+
+ return 0;
+}
+
+DM_TEST(dm_test_power_pmic_mc34708_get, DM_TESTF_SCAN_FDT);
+
+/* Test PMIC I/O */
+static int dm_test_power_pmic_io(struct unit_test_state *uts)
+{
+ const char *name = "sandbox_pmic";
+ uint8_t out_buffer, in_buffer;
+ struct udevice *dev;
+ int reg_count, i;
+
+ ut_assertok(pmic_get(name, &dev));
+
+ reg_count = pmic_reg_count(dev);
+ ut_asserteq(reg_count, SANDBOX_PMIC_REG_COUNT);
+
+ /*
+ * Test PMIC I/O - write and read a loop counter.
+ * usually we can't write to all PMIC's registers in the real hardware,
+ * but we can to the sandbox pmic.
+ */
+ for (i = 0; i < reg_count; i++) {
+ out_buffer = i;
+ ut_assertok(pmic_write(dev, i, &out_buffer, 1));
+ ut_assertok(pmic_read(dev, i, &in_buffer, 1));
+ ut_asserteq(out_buffer, in_buffer);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_power_pmic_io, DM_TESTF_SCAN_FDT);
+
+#define MC34708_PMIC_REG_COUNT 64
+#define MC34708_PMIC_TEST_VAL 0x125534
+static int dm_test_power_pmic_mc34708_regs_check(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int reg_count;
+
+ ut_assertok(pmic_get("pmic@41", &dev));
+
+ /* Check number of PMIC registers */
+ reg_count = pmic_reg_count(dev);
+ ut_asserteq(reg_count, MC34708_PMIC_REG_COUNT);
+
+ return 0;
+}
+
+DM_TEST(dm_test_power_pmic_mc34708_regs_check, DM_TESTF_SCAN_FDT);
+
+static int dm_test_power_pmic_mc34708_rw_val(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int val;
+
+ ut_assertok(pmic_get("pmic@41", &dev));
+
+ /* Check if single 3 byte read is successful */
+ val = pmic_reg_read(dev, REG_POWER_CTL2);
+ ut_asserteq(val, 0x422100);
+
+ /* Check if RW works */
+ val = 0;
+ ut_assertok(pmic_reg_write(dev, REG_RTC_TIME, val));
+ ut_assertok(pmic_reg_write(dev, REG_RTC_TIME, MC34708_PMIC_TEST_VAL));
+ val = pmic_reg_read(dev, REG_RTC_TIME);
+ ut_asserteq(val, MC34708_PMIC_TEST_VAL);
+
+ pmic_clrsetbits(dev, REG_POWER_CTL2, 0x3 << 8, 1 << 9);
+ val = pmic_reg_read(dev, REG_POWER_CTL2);
+ ut_asserteq(val, (0x422100 & ~(0x3 << 8)) | (1 << 9));
+
+ return 0;
+}
+
+DM_TEST(dm_test_power_pmic_mc34708_rw_val, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/power-domain.c b/test/dm/power-domain.c
new file mode 100644
index 00000000..48318218
--- /dev/null
+++ b/test/dm/power-domain.c
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2016, NVIDIA CORPORATION.
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <asm/power-domain.h>
+#include <test/ut.h>
+
+/* This must match the specifier for power-domains in the DT node */
+#define TEST_POWER_DOMAIN 2
+
+static int dm_test_power_domain(struct unit_test_state *uts)
+{
+ struct udevice *dev_power_domain;
+ struct udevice *dev_test;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_POWER_DOMAIN,
+ "power-domain",
+ &dev_power_domain));
+ ut_asserteq(0, sandbox_power_domain_query(dev_power_domain, 0));
+ ut_asserteq(0, sandbox_power_domain_query(dev_power_domain,
+ TEST_POWER_DOMAIN));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "power-domain-test",
+ &dev_test));
+ ut_asserteq(1, sandbox_power_domain_query(dev_power_domain,
+ TEST_POWER_DOMAIN));
+ ut_assertok(sandbox_power_domain_test_get(dev_test));
+
+ ut_assertok(sandbox_power_domain_test_on(dev_test));
+ ut_asserteq(0, sandbox_power_domain_query(dev_power_domain, 0));
+ ut_asserteq(1, sandbox_power_domain_query(dev_power_domain,
+ TEST_POWER_DOMAIN));
+
+ ut_assertok(sandbox_power_domain_test_off(dev_test));
+ ut_asserteq(0, sandbox_power_domain_query(dev_power_domain, 0));
+ ut_asserteq(0, sandbox_power_domain_query(dev_power_domain,
+ TEST_POWER_DOMAIN));
+
+ ut_assertok(sandbox_power_domain_test_free(dev_test));
+
+ return 0;
+}
+DM_TEST(dm_test_power_domain, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/pwm.c b/test/dm/pwm.c
new file mode 100644
index 00000000..b52ee21a
--- /dev/null
+++ b/test/dm/pwm.c
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2017 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <pwm.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Basic test of the pwm uclass */
+static int dm_test_pwm_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_PWM, 0, &dev));
+ ut_assertnonnull(dev);
+ ut_assertok(pwm_set_config(dev, 0, 100, 50));
+ ut_assertok(pwm_set_enable(dev, 0, true));
+ ut_assertok(pwm_set_enable(dev, 1, true));
+ ut_assertok(pwm_set_enable(dev, 2, true));
+ ut_asserteq(-ENOSPC, pwm_set_enable(dev, 3, true));
+ ut_assertok(pwm_set_invert(dev, 0, true));
+
+ ut_assertok(uclass_get_device(UCLASS_PWM, 1, &dev));
+ ut_asserteq(-ENODEV, uclass_get_device(UCLASS_PWM, 2, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_pwm_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/ram.c b/test/dm/ram.c
new file mode 100644
index 00000000..3efdb6b8
--- /dev/null
+++ b/test/dm/ram.c
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <ram.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* Basic test of the ram uclass */
+static int dm_test_ram_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct ram_info info;
+
+ ut_assertok(uclass_get_device(UCLASS_RAM, 0, &dev));
+ ut_assertok(ram_get_info(dev, &info));
+ ut_asserteq(0, info.base);
+ ut_asserteq(gd->ram_size, info.size);
+
+ return 0;
+}
+DM_TEST(dm_test_ram_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/regmap.c b/test/dm/regmap.c
new file mode 100644
index 00000000..6fd1f206
--- /dev/null
+++ b/test/dm/regmap.c
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <mapmem.h>
+#include <regmap.h>
+#include <syscon.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Base test of register maps */
+static int dm_test_regmap_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct regmap *map;
+ ofnode node;
+ int i;
+
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 0, &dev));
+ map = syscon_get_regmap(dev);
+ ut_assertok_ptr(map);
+ ut_asserteq(1, map->range_count);
+ ut_asserteq(0x10, map->ranges[0].start);
+ ut_asserteq(16, map->ranges[0].size);
+ ut_asserteq(0x10, map_to_sysmem(regmap_get_range(map, 0)));
+
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 1, &dev));
+ map = syscon_get_regmap(dev);
+ ut_assertok_ptr(map);
+ ut_asserteq(4, map->range_count);
+ ut_asserteq(0x20, map->ranges[0].start);
+ for (i = 0; i < 4; i++) {
+ const unsigned long addr = 0x20 + 8 * i;
+
+ ut_asserteq(addr, map->ranges[i].start);
+ ut_asserteq(5 + i, map->ranges[i].size);
+ ut_asserteq(addr, map_to_sysmem(regmap_get_range(map, i)));
+ }
+
+ /* Check that we can't pretend a different device is a syscon */
+ ut_assertok(uclass_get_device(UCLASS_I2C, 0, &dev));
+ map = syscon_get_regmap(dev);
+ ut_asserteq_ptr(ERR_PTR(-ENOEXEC), map);
+
+ /* A different device can be a syscon by using Linux-compat API */
+ node = ofnode_path("/syscon@2");
+ ut_assert(ofnode_valid(node));
+
+ map = syscon_node_to_regmap(node);
+ ut_assertok_ptr(map);
+ ut_asserteq(4, map->range_count);
+ ut_asserteq(0x40, map->ranges[0].start);
+ for (i = 0; i < 4; i++) {
+ const unsigned long addr = 0x40 + 8 * i;
+
+ ut_asserteq(addr, map->ranges[i].start);
+ ut_asserteq(5 + i, map->ranges[i].size);
+ ut_asserteq(addr, map_to_sysmem(regmap_get_range(map, i)));
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_regmap_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test we can access a regmap through syscon */
+static int dm_test_regmap_syscon(struct unit_test_state *uts)
+{
+ struct regmap *map;
+
+ map = syscon_get_regmap_by_driver_data(SYSCON0);
+ ut_assertok_ptr(map);
+ ut_asserteq(1, map->range_count);
+
+ map = syscon_get_regmap_by_driver_data(SYSCON1);
+ ut_assertok_ptr(map);
+ ut_asserteq(4, map->range_count);
+
+ map = syscon_get_regmap_by_driver_data(SYSCON_COUNT);
+ ut_asserteq_ptr(ERR_PTR(-ENODEV), map);
+
+ ut_asserteq(0x10, map_to_sysmem(syscon_get_first_range(SYSCON0)));
+ ut_asserteq(0x20, map_to_sysmem(syscon_get_first_range(SYSCON1)));
+ ut_asserteq_ptr(ERR_PTR(-ENODEV),
+ syscon_get_first_range(SYSCON_COUNT));
+
+ return 0;
+}
+
+DM_TEST(dm_test_regmap_syscon, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Read/Write/Modify test */
+static int dm_test_regmap_rw(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct regmap *map;
+ uint reg;
+
+ sandbox_set_enable_memio(true);
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 0, &dev));
+ map = syscon_get_regmap(dev);
+ ut_assertok_ptr(map);
+
+ ut_assertok(regmap_write(map, 0, 0xcacafafa));
+ ut_assertok(regmap_write(map, 5, 0x55aa2211));
+
+ ut_assertok(regmap_read(map, 0, &reg));
+ ut_asserteq(0xcacafafa, reg);
+ ut_assertok(regmap_read(map, 5, &reg));
+ ut_asserteq(0x55aa2211, reg);
+
+ ut_assertok(regmap_read(map, 0, &reg));
+ ut_asserteq(0xcacafafa, reg);
+ ut_assertok(regmap_update_bits(map, 0, 0xff00ff00, 0x55aa2211));
+ ut_assertok(regmap_read(map, 0, &reg));
+ ut_asserteq(0x55ca22fa, reg);
+ ut_assertok(regmap_update_bits(map, 5, 0x00ff00ff, 0xcacafada));
+ ut_assertok(regmap_read(map, 5, &reg));
+ ut_asserteq(0x55ca22da, reg);
+
+ return 0;
+}
+
+DM_TEST(dm_test_regmap_rw, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Get/Set test */
+static int dm_test_regmap_getset(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct regmap *map;
+ uint reg;
+ struct layout {
+ u32 val0;
+ u32 val1;
+ u32 val2;
+ u32 val3;
+ };
+
+ sandbox_set_enable_memio(true);
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 0, &dev));
+ map = syscon_get_regmap(dev);
+ ut_assertok_ptr(map);
+
+ regmap_set(map, struct layout, val0, 0xcacafafa);
+ regmap_set(map, struct layout, val3, 0x55aa2211);
+
+ ut_assertok(regmap_get(map, struct layout, val0, &reg));
+ ut_asserteq(0xcacafafa, reg);
+ ut_assertok(regmap_get(map, struct layout, val3, &reg));
+ ut_asserteq(0x55aa2211, reg);
+
+ return 0;
+}
+
+DM_TEST(dm_test_regmap_getset, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Read polling test */
+static int dm_test_regmap_poll(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct regmap *map;
+ uint reg;
+ unsigned long start;
+
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 0, &dev));
+ map = syscon_get_regmap(dev);
+ ut_assertok_ptr(map);
+
+ start = get_timer(0);
+
+ ut_assertok(regmap_write(map, 0, 0x0));
+ ut_asserteq(-ETIMEDOUT,
+ regmap_read_poll_timeout_test(map, 0, reg,
+ (reg == 0xcacafafa),
+ 1, 5 * CONFIG_SYS_HZ,
+ 5 * CONFIG_SYS_HZ));
+
+ ut_assert(get_timer(start) > (5 * CONFIG_SYS_HZ));
+
+ return 0;
+}
+
+DM_TEST(dm_test_regmap_poll, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/regulator.c b/test/dm/regulator.c
new file mode 100644
index 00000000..b9679024
--- /dev/null
+++ b/test/dm/regulator.c
@@ -0,0 +1,402 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Tests for the driver model regulator API
+ *
+ * Copyright (c) 2015 Samsung Electronics
+ * Przemyslaw Marczak <p.marczak@samsung.com>
+ */
+
+#include <common.h>
+#include <errno.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <malloc.h>
+#include <dm/device-internal.h>
+#include <dm/root.h>
+#include <dm/util.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <power/pmic.h>
+#include <power/regulator.h>
+#include <power/sandbox_pmic.h>
+#include <test/ut.h>
+
+enum {
+ BUCK1,
+ BUCK2,
+ BUCK3,
+ LDO1,
+ LDO2,
+ OUTPUT_COUNT,
+};
+
+enum {
+ DEVNAME = 0,
+ PLATNAME,
+ OUTPUT_NAME_COUNT,
+};
+
+static const char *regulator_names[OUTPUT_COUNT][OUTPUT_NAME_COUNT] = {
+ /* devname, platname */
+ { SANDBOX_BUCK1_DEVNAME, SANDBOX_BUCK1_PLATNAME },
+ { SANDBOX_BUCK2_DEVNAME, SANDBOX_BUCK2_PLATNAME },
+ { SANDBOX_BUCK3_DEVNAME, SANDBOX_BUCK3_PLATNAME },
+ { SANDBOX_LDO1_DEVNAME, SANDBOX_LDO1_PLATNAME},
+ { SANDBOX_LDO2_DEVNAME, SANDBOX_LDO2_PLATNAME},
+};
+
+/* Test regulator get method */
+static int dm_test_power_regulator_get(struct unit_test_state *uts)
+{
+ struct dm_regulator_uclass_platdata *uc_pdata;
+ struct udevice *dev_by_devname;
+ struct udevice *dev_by_platname;
+ const char *devname;
+ const char *platname;
+ int i;
+
+ for (i = 0; i < OUTPUT_COUNT; i++) {
+ /*
+ * Do the test for each regulator's devname and platname,
+ * which are related to a single device.
+ */
+ devname = regulator_names[i][DEVNAME];
+ platname = regulator_names[i][PLATNAME];
+
+ /*
+ * Check, that regulator_get_by_devname() function, returns
+ * a device with the name equal to the requested one.
+ */
+ ut_assertok(regulator_get_by_devname(devname, &dev_by_devname));
+ ut_asserteq_str(devname, dev_by_devname->name);
+
+ /*
+ * Check, that regulator_get_by_platname() function, returns
+ * a device with the name equal to the requested one.
+ */
+ ut_assertok(regulator_get_by_platname(platname, &dev_by_platname));
+ uc_pdata = dev_get_uclass_platdata(dev_by_platname);
+ ut_assert(uc_pdata);
+ ut_asserteq_str(platname, uc_pdata->name);
+
+ /*
+ * Check, that the pointers returned by both get functions,
+ * points to the same regulator device.
+ */
+ ut_asserteq_ptr(dev_by_devname, dev_by_platname);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_get, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get Voltage method */
+static int dm_test_power_regulator_set_get_voltage(struct unit_test_state *uts)
+{
+ struct dm_regulator_uclass_platdata *uc_pdata;
+ struct udevice *dev;
+ const char *platname;
+ int val_set, val_get;
+
+ /* Set and get Voltage of BUCK1 - set to 'min' constraint */
+ platname = regulator_names[BUCK1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+
+ val_set = uc_pdata->min_uV;
+ ut_assertok(regulator_set_value(dev, val_set));
+
+ val_get = regulator_get_value(dev);
+ ut_assert(val_get >= 0);
+
+ ut_asserteq(val_set, val_get);
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_voltage, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get Current method */
+static int dm_test_power_regulator_set_get_current(struct unit_test_state *uts)
+{
+ struct dm_regulator_uclass_platdata *uc_pdata;
+ struct udevice *dev;
+ const char *platname;
+ int val_set, val_get;
+
+ /* Set and get the Current of LDO1 - set to 'min' constraint */
+ platname = regulator_names[LDO1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+
+ val_set = uc_pdata->min_uA;
+ ut_assertok(regulator_set_current(dev, val_set));
+
+ val_get = regulator_get_current(dev);
+ ut_assert(val_get >= 0);
+
+ ut_asserteq(val_set, val_get);
+
+ /* Check LDO2 current limit constraints - should be -ENODATA */
+ platname = regulator_names[LDO2][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+ ut_asserteq(-ENODATA, uc_pdata->min_uA);
+ ut_asserteq(-ENODATA, uc_pdata->max_uA);
+
+ /* Try set the Current of LDO2 - should return -ENOSYS */
+ ut_asserteq(-ENOSYS, regulator_set_current(dev, 0));
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_current, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get Enable method */
+static int dm_test_power_regulator_set_get_enable(struct unit_test_state *uts)
+{
+ const char *platname;
+ struct udevice *dev;
+ bool val_set = true;
+
+ /* Set the Enable of LDO1 - default is disabled */
+ platname = regulator_names[LDO1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+ ut_assertok(regulator_set_enable(dev, val_set));
+
+ /* Get the Enable state of LDO1 and compare it with the requested one */
+ ut_asserteq(regulator_get_enable(dev), val_set);
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_enable, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get enable if allowed method */
+static
+int dm_test_power_regulator_set_enable_if_allowed(struct unit_test_state *uts)
+{
+ const char *platname;
+ struct udevice *dev, *dev_autoset;
+ bool val_set = false;
+
+ /* Get BUCK1 - always on regulator */
+ platname = regulator_names[BUCK1][PLATNAME];
+ ut_assertok(regulator_autoset_by_name(platname, &dev_autoset));
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ /* Try disabling always-on regulator */
+ ut_assertok(regulator_set_enable_if_allowed(dev, val_set));
+ ut_asserteq(regulator_get_enable(dev), !val_set);
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_enable_if_allowed, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get mode method */
+static int dm_test_power_regulator_set_get_mode(struct unit_test_state *uts)
+{
+ const char *platname;
+ struct udevice *dev;
+ int val_set = LDO_OM_SLEEP;
+
+ /* Set the mode id to LDO_OM_SLEEP of LDO1 - default is LDO_OM_OFF */
+ platname = regulator_names[LDO1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+ ut_assertok(regulator_set_mode(dev, val_set));
+
+ /* Get the mode id of LDO1 and compare it with the requested one */
+ ut_asserteq(regulator_get_mode(dev), val_set);
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_mode, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get suspend Voltage method */
+static int dm_test_power_regulator_set_get_suspend_voltage(struct unit_test_state *uts)
+{
+ struct dm_regulator_uclass_platdata *uc_pdata;
+ const struct dm_regulator_ops *ops;
+ struct udevice *dev;
+ const char *platname;
+ int val_set, val_get;
+
+ /* Set and get Voltage of BUCK1 - set to 'min' constraint */
+ platname = regulator_names[BUCK1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+
+ ops = dev_get_driver_ops(dev);
+
+ if (ops->set_suspend_value && ops->get_suspend_value) {
+ val_set = uc_pdata->suspend_uV;
+ ut_assertok(regulator_set_suspend_value(dev, val_set));
+ val_get = regulator_get_suspend_value(dev);
+ ut_assert(val_get >= 0);
+
+ ut_asserteq(val_set, val_get);
+ }
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_suspend_voltage, DM_TESTF_SCAN_FDT);
+
+/* Test regulator set and get suspend Enable method */
+static int dm_test_power_regulator_set_get_suspend_enable(struct unit_test_state *uts)
+{
+ const struct dm_regulator_ops *ops;
+ const char *platname;
+ struct udevice *dev;
+ bool val_set = true;
+
+ /* Set the Enable of LDO1 - default is disabled */
+ platname = regulator_names[LDO1][PLATNAME];
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+
+ ops = dev_get_driver_ops(dev);
+
+ if (ops->set_suspend_enable && ops->get_suspend_enable) {
+ ut_assertok(regulator_set_suspend_enable(dev, val_set));
+
+ /*
+ * Get the Enable state of LDO1 and
+ * compare it with the requested one
+ */
+ ut_asserteq(regulator_get_suspend_enable(dev), val_set);
+ }
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_set_get_suspend_enable, DM_TESTF_SCAN_FDT);
+
+/* Test regulator autoset method */
+static int dm_test_power_regulator_autoset(struct unit_test_state *uts)
+{
+ const char *platname;
+ struct udevice *dev, *dev_autoset;
+
+ /*
+ * Test the BUCK1 with fdt properties
+ * - min-microvolt = max-microvolt = 1200000
+ * - min-microamp = max-microamp = 200000
+ * - always-on = set
+ * - boot-on = not set
+ * Expected output state: uV=1200000; uA=200000; output enabled
+ */
+ platname = regulator_names[BUCK1][PLATNAME];
+ ut_assertok(regulator_autoset_by_name(platname, &dev_autoset));
+
+ /* Check, that the returned device is proper */
+ ut_assertok(regulator_get_by_platname(platname, &dev));
+ ut_asserteq_ptr(dev, dev_autoset);
+
+ /* Check the setup after autoset */
+ ut_asserteq(regulator_get_value(dev),
+ SANDBOX_BUCK1_AUTOSET_EXPECTED_UV);
+ ut_asserteq(regulator_get_current(dev),
+ SANDBOX_BUCK1_AUTOSET_EXPECTED_UA);
+ ut_asserteq(regulator_get_enable(dev),
+ SANDBOX_BUCK1_AUTOSET_EXPECTED_ENABLE);
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_autoset, DM_TESTF_SCAN_FDT);
+
+/*
+ * Struct setting: to keep the expected output settings.
+ * @voltage: Voltage value [uV]
+ * @current: Current value [uA]
+ * @enable: output enable state: true/false
+ */
+struct setting {
+ int voltage;
+ int current;
+ bool enable;
+};
+
+/*
+ * platname_list: an array of regulator platform names.
+ * For testing regulator_list_autoset() for outputs:
+ * - LDO1
+ * - LDO2
+ */
+static const char *platname_list[] = {
+ SANDBOX_LDO1_PLATNAME,
+ SANDBOX_LDO2_PLATNAME,
+ NULL,
+};
+
+/*
+ * expected_setting_list: an array of regulator output setting, expected after
+ * call of the regulator_list_autoset() for the "platname_list" array.
+ * For testing results of regulator_list_autoset() for outputs:
+ * - LDO1
+ * - LDO2
+ * The settings are defined in: include/power/sandbox_pmic.h
+ */
+static const struct setting expected_setting_list[] = {
+ [0] = { /* LDO1 */
+ .voltage = SANDBOX_LDO1_AUTOSET_EXPECTED_UV,
+ .current = SANDBOX_LDO1_AUTOSET_EXPECTED_UA,
+ .enable = SANDBOX_LDO1_AUTOSET_EXPECTED_ENABLE,
+ },
+ [1] = { /* LDO2 */
+ .voltage = SANDBOX_LDO2_AUTOSET_EXPECTED_UV,
+ .current = SANDBOX_LDO2_AUTOSET_EXPECTED_UA,
+ .enable = SANDBOX_LDO2_AUTOSET_EXPECTED_ENABLE,
+ },
+};
+
+static int list_count = ARRAY_SIZE(expected_setting_list);
+
+/* Test regulator list autoset method */
+static int dm_test_power_regulator_autoset_list(struct unit_test_state *uts)
+{
+ struct udevice *dev_list[2], *dev;
+ int i;
+
+ /*
+ * Test the settings of the regulator list:
+ * LDO1 with fdt properties:
+ * - min-microvolt = max-microvolt = 1800000
+ * - min-microamp = max-microamp = 100000
+ * - always-on = not set
+ * - boot-on = set
+ * Expected output state: uV=1800000; uA=100000; output enabled
+ *
+ * LDO2 with fdt properties:
+ * - min-microvolt = max-microvolt = 3300000
+ * - always-on = not set
+ * - boot-on = not set
+ * Expected output state: uV=300000(default); output disabled(default)
+ * The expected settings are defined in: include/power/sandbox_pmic.h.
+ */
+ ut_assertok(regulator_list_autoset(platname_list, dev_list, false));
+
+ for (i = 0; i < list_count; i++) {
+ /* Check, that the returned device is non-NULL */
+ ut_assert(dev_list[i]);
+
+ /* Check, that the returned device is proper */
+ ut_assertok(regulator_get_by_platname(platname_list[i], &dev));
+ ut_asserteq_ptr(dev_list[i], dev);
+
+ /* Check, that regulator output Voltage value is as expected */
+ ut_asserteq(regulator_get_value(dev_list[i]),
+ expected_setting_list[i].voltage);
+
+ /* Check, that regulator output Current value is as expected */
+ ut_asserteq(regulator_get_current(dev_list[i]),
+ expected_setting_list[i].current);
+
+ /* Check, that regulator output Enable state is as expected */
+ ut_asserteq(regulator_get_enable(dev_list[i]),
+ expected_setting_list[i].enable);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_power_regulator_autoset_list, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/remoteproc.c b/test/dm/remoteproc.c
new file mode 100644
index 00000000..1d9a9b32
--- /dev/null
+++ b/test/dm/remoteproc.c
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2015
+ * Texas Instruments Incorporated - http://www.ti.com/
+ */
+#include <common.h>
+#include <dm.h>
+#include <elf.h>
+#include <errno.h>
+#include <remoteproc.h>
+#include <asm/io.h>
+#include <dm/test.h>
+#include <test/ut.h>
+/**
+ * dm_test_remoteproc_base() - test the operations after initializations
+ * @uts: unit test state
+ *
+ * Return: 0 if test passed, else error
+ */
+static int dm_test_remoteproc_base(struct unit_test_state *uts)
+{
+ if (!rproc_is_initialized())
+ ut_assertok(rproc_init());
+
+ /* Ensure we are initialized */
+ ut_asserteq(true, rproc_is_initialized());
+
+
+ /* platform data device 1 */
+ ut_assertok(rproc_stop(0));
+ ut_assertok(rproc_reset(0));
+ /* -> invalid attempt tests */
+ ut_asserteq(-EINVAL, rproc_start(0));
+ ut_asserteq(-EINVAL, rproc_ping(0));
+ /* Valid tests */
+ ut_assertok(rproc_load(0, 1, 0));
+ ut_assertok(rproc_start(0));
+ ut_assertok(rproc_is_running(0));
+ ut_assertok(rproc_ping(0));
+ ut_assertok(rproc_reset(0));
+ ut_assertok(rproc_stop(0));
+
+ /* dt device device 1 */
+ ut_assertok(rproc_stop(1));
+ ut_assertok(rproc_reset(1));
+ ut_assertok(rproc_load(1, 1, 0));
+ ut_assertok(rproc_start(1));
+ ut_assertok(rproc_is_running(1));
+ ut_assertok(rproc_ping(1));
+ ut_assertok(rproc_reset(1));
+ ut_assertok(rproc_stop(1));
+
+ /* dt device device 2 */
+ ut_assertok(rproc_stop(0));
+ ut_assertok(rproc_reset(0));
+ /* -> invalid attempt tests */
+ ut_asserteq(-EINVAL, rproc_start(0));
+ ut_asserteq(-EINVAL, rproc_ping(0));
+ /* Valid tests */
+ ut_assertok(rproc_load(2, 1, 0));
+ ut_assertok(rproc_start(2));
+ ut_assertok(rproc_is_running(2));
+ ut_assertok(rproc_ping(2));
+ ut_assertok(rproc_reset(2));
+ ut_assertok(rproc_stop(2));
+
+ return 0;
+}
+DM_TEST(dm_test_remoteproc_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+#define DEVICE_TO_PHYSICAL_OFFSET 0x1000
+/**
+ * dm_test_remoteproc_elf() - test the ELF operations
+ * @uts: unit test state
+ *
+ * Return: 0 if test passed, else error
+ */
+static int dm_test_remoteproc_elf(struct unit_test_state *uts)
+{
+ u8 valid_elf32[] = {
+ /* @0x00 - ELF HEADER - */
+ /* ELF magic */
+ 0x7f, 0x45, 0x4c, 0x46,
+ /* 32 Bits */
+ 0x01,
+ /* Endianness */
+#ifdef __LITTLE_ENDIAN
+ 0x01,
+#else
+ 0x02,
+#endif
+ /* Version */
+ 0x01,
+ /* Padding */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ /* Type : executable */
+ 0x02, 0x00,
+ /* Machine: ARM */
+ 0x28, 0x00,
+ /* Version */
+ 0x01, 0x00, 0x00, 0x00,
+ /* Entry */
+ 0x00, 0x00, 0x00, 0x08,
+ /* phoff (program header offset @ 0x40)*/
+ 0x40, 0x00, 0x00, 0x00,
+ /* shoff (section header offset : none) */
+ 0x00, 0x00, 0x00, 0x00,
+ /* flags */
+ 0x00, 0x00, 0x00, 0x00,
+ /* ehsize (elf header size = 0x34) */
+ 0x34, 0x00,
+ /* phentsize (program header size = 0x20) */
+ 0x20, 0x00,
+ /* phnum (program header number : 1) */
+ 0x01, 0x00,
+ /* shentsize (section heade size : none) */
+ 0x00, 0x00,
+ /* shnum (section header number: none) */
+ 0x00, 0x00,
+ /* shstrndx (section header name section index: none) */
+ 0x00, 0x00,
+ /* padding */
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* @0x40 - PROGRAM HEADER TABLE - */
+ /* type : PT_LOAD */
+ 0x01, 0x00, 0x00, 0x00,
+ /* offset */
+ 0x00, 0x00, 0x00, 0x00,
+ /* vaddr */
+ 0x00, 0x00, 0x00, 0x00,
+ /* paddr : physical address */
+ 0x00, 0x00, 0x00, 0x00,
+ /* filesz : 0x20 bytes (program header size) */
+ 0x20, 0x00, 0x00, 0x00,
+ /* memsz = filesz */
+ 0x20, 0x00, 0x00, 0x00,
+ /* flags : readable and exectuable */
+ 0x05, 0x00, 0x00, 0x00,
+ /* padding */
+ 0x00, 0x00, 0x00, 0x00,
+ };
+ unsigned int size = ARRAY_SIZE(valid_elf32);
+ struct udevice *dev;
+ phys_addr_t loaded_firmware_paddr;
+ void *loaded_firmware;
+ u32 loaded_firmware_size;
+ Elf32_Ehdr *ehdr = (Elf32_Ehdr *)valid_elf32;
+ Elf32_Phdr *phdr = (Elf32_Phdr *)(valid_elf32 + ehdr->e_phoff);
+
+ ut_assertok(uclass_get_device(UCLASS_REMOTEPROC, 0, &dev));
+
+ /*
+ * In its Program Header Table, let the firmware specifies to be loaded
+ * at SDRAM_BASE *device* address (p_paddr field).
+ * Its size is defined by the p_filesz field.
+ */
+ phdr->p_paddr = CONFIG_SYS_SDRAM_BASE;
+ loaded_firmware_size = phdr->p_filesz;
+
+ /*
+ * This *device* address is converted to a *physical* address by the
+ * device_to_virt() operation of sandbox_test_rproc which returns
+ * DeviceAddress + DEVICE_TO_PHYSICAL_OFFSET.
+ * This is where we expect to get the firmware loaded.
+ */
+ loaded_firmware_paddr = phdr->p_paddr + DEVICE_TO_PHYSICAL_OFFSET;
+ loaded_firmware = map_physmem(loaded_firmware_paddr,
+ loaded_firmware_size, MAP_NOCACHE);
+ ut_assertnonnull(loaded_firmware);
+ memset(loaded_firmware, 0, loaded_firmware_size);
+
+ /* Load firmware in loaded_firmware, and verify it */
+ ut_assertok(rproc_elf32_load_image(dev, (ulong)valid_elf32, size));
+ ut_assertok(memcmp(loaded_firmware, valid_elf32, loaded_firmware_size));
+ ut_asserteq(rproc_elf_get_boot_addr(dev, (unsigned long)valid_elf32),
+ 0x08000000);
+ unmap_physmem(loaded_firmware, MAP_NOCACHE);
+
+ /* Invalid ELF Magic */
+ valid_elf32[0] = 0;
+ ut_asserteq(-EPROTONOSUPPORT,
+ rproc_elf32_sanity_check((ulong)valid_elf32, size));
+
+ return 0;
+}
+DM_TEST(dm_test_remoteproc_elf, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/reset.c b/test/dm/reset.c
new file mode 100644
index 00000000..c61daed4
--- /dev/null
+++ b/test/dm/reset.c
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2016, NVIDIA CORPORATION.
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <reset.h>
+#include <dm/test.h>
+#include <asm/reset.h>
+#include <test/ut.h>
+
+/* This must match the specifier for mbox-names="test" in the DT node */
+#define TEST_RESET_ID 2
+
+/* This is the other reset phandle specifier handled by bulk */
+#define OTHER_RESET_ID 2
+
+/* Base test of the reset uclass */
+static int dm_test_reset_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct reset_ctl reset_method1;
+ struct reset_ctl reset_method2;
+
+ /* Get the device using the reset device */
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "reset-ctl-test",
+ &dev));
+
+ /* Get the same reset port in 2 different ways and compare */
+ ut_assertok(reset_get_by_index(dev, 1, &reset_method1));
+ ut_assertok(reset_get_by_index_nodev(dev_ofnode(dev), 1,
+ &reset_method2));
+ ut_asserteq(reset_method1.id, reset_method2.id);
+
+ return 0;
+}
+
+DM_TEST(dm_test_reset_base, DM_TESTF_SCAN_FDT);
+
+static int dm_test_reset(struct unit_test_state *uts)
+{
+ struct udevice *dev_reset;
+ struct udevice *dev_test;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_RESET, "reset-ctl",
+ &dev_reset));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "reset-ctl-test",
+ &dev_test));
+ ut_assertok(sandbox_reset_test_get(dev_test));
+
+ ut_assertok(sandbox_reset_test_assert(dev_test));
+ ut_asserteq(1, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+
+ ut_assertok(sandbox_reset_test_deassert(dev_test));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+
+ ut_assertok(sandbox_reset_test_free(dev_test));
+
+ return 0;
+}
+DM_TEST(dm_test_reset, DM_TESTF_SCAN_FDT);
+
+static int dm_test_reset_bulk(struct unit_test_state *uts)
+{
+ struct udevice *dev_reset;
+ struct udevice *dev_test;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_RESET, "reset-ctl",
+ &dev_reset));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, OTHER_RESET_ID));
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_MISC, "reset-ctl-test",
+ &dev_test));
+ ut_assertok(sandbox_reset_test_get_bulk(dev_test));
+
+ ut_assertok(sandbox_reset_test_assert_bulk(dev_test));
+ ut_asserteq(1, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+ ut_asserteq(1, sandbox_reset_query(dev_reset, OTHER_RESET_ID));
+
+ ut_assertok(sandbox_reset_test_deassert_bulk(dev_test));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+ ut_asserteq(0, sandbox_reset_query(dev_reset, OTHER_RESET_ID));
+
+ ut_assertok(sandbox_reset_test_release_bulk(dev_test));
+ ut_asserteq(1, sandbox_reset_query(dev_reset, TEST_RESET_ID));
+ ut_asserteq(1, sandbox_reset_query(dev_reset, OTHER_RESET_ID));
+
+ return 0;
+}
+DM_TEST(dm_test_reset_bulk, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/rtc.c b/test/dm/rtc.c
new file mode 100644
index 00000000..71887427
--- /dev/null
+++ b/test/dm/rtc.c
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <i2c.h>
+#include <rtc.h>
+#include <asm/io.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Simple RTC sanity check */
+static int dm_test_rtc_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_RTC, 2, &dev));
+ ut_assertok(uclass_get_device(UCLASS_RTC, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_RTC, 1, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_rtc_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static void show_time(const char *msg, struct rtc_time *time)
+{
+ printf("%s: %02d/%02d/%04d %02d:%02d:%02d\n", msg,
+ time->tm_mday, time->tm_mon, time->tm_year,
+ time->tm_hour, time->tm_min, time->tm_sec);
+}
+
+static int cmp_times(struct rtc_time *expect, struct rtc_time *time, bool show)
+{
+ bool same;
+
+ same = expect->tm_sec == time->tm_sec;
+ same &= expect->tm_min == time->tm_min;
+ same &= expect->tm_hour == time->tm_hour;
+ same &= expect->tm_mday == time->tm_mday;
+ same &= expect->tm_mon == time->tm_mon;
+ same &= expect->tm_year == time->tm_year;
+ if (!same && show) {
+ show_time("expected", expect);
+ show_time("actual", time);
+ }
+
+ return same ? 0 : -EINVAL;
+}
+
+/* Set and get the time */
+static int dm_test_rtc_set_get(struct unit_test_state *uts)
+{
+ struct rtc_time now, time, cmp;
+ struct udevice *dev, *emul;
+ long offset, old_offset, old_base_time;
+
+ ut_assertok(uclass_get_device(UCLASS_RTC, 0, &dev));
+ ut_assertok(dm_rtc_get(dev, &now));
+
+ ut_assertok(i2c_emul_find(dev, &emul));
+ ut_assert(emul != NULL);
+
+ /* Tell the RTC to go into manual mode */
+ old_offset = sandbox_i2c_rtc_set_offset(emul, false, 0);
+ old_base_time = sandbox_i2c_rtc_get_set_base_time(emul, -1);
+
+ memset(&time, '\0', sizeof(time));
+ time.tm_mday = 25;
+ time.tm_mon = 8;
+ time.tm_year = 2004;
+ time.tm_sec = 0;
+ time.tm_min = 18;
+ time.tm_hour = 18;
+ ut_assertok(dm_rtc_set(dev, &time));
+
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev, &cmp));
+ ut_assertok(cmp_times(&time, &cmp, true));
+
+ /* Increment by 1 second */
+ offset = sandbox_i2c_rtc_set_offset(emul, false, 0);
+ sandbox_i2c_rtc_set_offset(emul, false, offset + 1);
+
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev, &cmp));
+ ut_asserteq(1, cmp.tm_sec);
+
+ /* Check against original offset */
+ sandbox_i2c_rtc_set_offset(emul, false, old_offset);
+ ut_assertok(dm_rtc_get(dev, &cmp));
+ ut_assertok(cmp_times(&now, &cmp, true));
+
+ /* Back to the original offset */
+ sandbox_i2c_rtc_set_offset(emul, false, 0);
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev, &cmp));
+ ut_assertok(cmp_times(&now, &cmp, true));
+
+ /* Increment the base time by 1 emul */
+ sandbox_i2c_rtc_get_set_base_time(emul, old_base_time + 1);
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev, &cmp));
+ if (now.tm_sec == 59) {
+ ut_asserteq(0, cmp.tm_sec);
+ } else {
+ ut_asserteq(now.tm_sec + 1, cmp.tm_sec);
+ }
+
+ old_offset = sandbox_i2c_rtc_set_offset(emul, true, 0);
+
+ return 0;
+}
+DM_TEST(dm_test_rtc_set_get, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Reset the time */
+static int dm_test_rtc_reset(struct unit_test_state *uts)
+{
+ struct rtc_time now;
+ struct udevice *dev, *emul;
+ long old_base_time, base_time;
+
+ ut_assertok(uclass_get_device(UCLASS_RTC, 0, &dev));
+ ut_assertok(dm_rtc_get(dev, &now));
+
+ ut_assertok(i2c_emul_find(dev, &emul));
+ ut_assert(emul != NULL);
+
+ old_base_time = sandbox_i2c_rtc_get_set_base_time(emul, 0);
+
+ ut_asserteq(0, sandbox_i2c_rtc_get_set_base_time(emul, -1));
+
+ /* Resetting the RTC should put he base time back to normal */
+ ut_assertok(dm_rtc_reset(dev));
+ base_time = sandbox_i2c_rtc_get_set_base_time(emul, -1);
+ ut_asserteq(old_base_time, base_time);
+
+ return 0;
+}
+DM_TEST(dm_test_rtc_reset, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Check that two RTC devices can be used independently */
+static int dm_test_rtc_dual(struct unit_test_state *uts)
+{
+ struct rtc_time now1, now2, cmp;
+ struct udevice *dev1, *dev2;
+ struct udevice *emul1, *emul2;
+ long offset;
+
+ ut_assertok(uclass_get_device(UCLASS_RTC, 0, &dev1));
+ ut_assertok(dm_rtc_get(dev1, &now1));
+ ut_assertok(uclass_get_device(UCLASS_RTC, 1, &dev2));
+ ut_assertok(dm_rtc_get(dev2, &now2));
+
+ ut_assertok(i2c_emul_find(dev1, &emul1));
+ ut_assert(emul1 != NULL);
+ ut_assertok(i2c_emul_find(dev2, &emul2));
+ ut_assert(emul2 != NULL);
+
+ offset = sandbox_i2c_rtc_set_offset(emul1, false, -1);
+ sandbox_i2c_rtc_set_offset(emul2, false, offset + 1);
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev2, &cmp));
+ ut_asserteq(-EINVAL, cmp_times(&now1, &cmp, false));
+
+ memset(&cmp, '\0', sizeof(cmp));
+ ut_assertok(dm_rtc_get(dev1, &cmp));
+ ut_assertok(cmp_times(&now1, &cmp, true));
+
+ return 0;
+}
+DM_TEST(dm_test_rtc_dual, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/serial.c b/test/dm/serial.c
new file mode 100644
index 00000000..3d741a8c
--- /dev/null
+++ b/test/dm/serial.c
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2018, STMicroelectronics
+ */
+
+#include <common.h>
+#include <serial.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+static int dm_test_serial(struct unit_test_state *uts)
+{
+ struct serial_device_info info_serial = {0};
+ struct udevice *dev_serial;
+ uint value_serial;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_SERIAL, "serial",
+ &dev_serial));
+
+ ut_assertok(serial_tstc());
+ /*
+ * test with default config which is the only one supported by
+ * sandbox_serial driver
+ */
+ ut_assertok(serial_setconfig(dev_serial, SERIAL_DEFAULT_CONFIG));
+ ut_assertok(serial_getconfig(dev_serial, &value_serial));
+ ut_assert(value_serial == SERIAL_DEFAULT_CONFIG);
+ ut_assertok(serial_getinfo(dev_serial, &info_serial));
+ ut_assert(info_serial.type == SERIAL_CHIP_UNKNOWN);
+ ut_assert(info_serial.addr == SERIAL_DEFAULT_ADDRESS);
+ /*
+ * test with a parameter which is NULL pointer
+ */
+ ut_asserteq(-EINVAL, serial_getconfig(dev_serial, NULL));
+ ut_asserteq(-EINVAL, serial_getinfo(dev_serial, NULL));
+ /*
+ * test with a serial config which is not supported by
+ * sandbox_serial driver: test with wrong parity
+ */
+ ut_asserteq(-ENOTSUPP,
+ serial_setconfig(dev_serial,
+ SERIAL_CONFIG(SERIAL_PAR_ODD,
+ SERIAL_8_BITS,
+ SERIAL_ONE_STOP)));
+ /*
+ * test with a serial config which is not supported by
+ * sandbox_serial driver: test with wrong bits number
+ */
+ ut_asserteq(-ENOTSUPP,
+ serial_setconfig(dev_serial,
+ SERIAL_CONFIG(SERIAL_PAR_NONE,
+ SERIAL_6_BITS,
+ SERIAL_ONE_STOP)));
+
+ /*
+ * test with a serial config which is not supported by
+ * sandbox_serial driver: test with wrong stop bits number
+ */
+ ut_asserteq(-ENOTSUPP,
+ serial_setconfig(dev_serial,
+ SERIAL_CONFIG(SERIAL_PAR_NONE,
+ SERIAL_8_BITS,
+ SERIAL_TWO_STOP)));
+
+ return 0;
+}
+
+DM_TEST(dm_test_serial, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/sf.c b/test/dm/sf.c
new file mode 100644
index 00000000..7805af74
--- /dev/null
+++ b/test/dm/sf.c
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <command.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <mapmem.h>
+#include <os.h>
+#include <spi.h>
+#include <spi_flash.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <dm/util.h>
+#include <test/ut.h>
+
+/* Simple test of sandbox SPI flash */
+static int dm_test_spi_flash(struct unit_test_state *uts)
+{
+ struct udevice *dev, *emul;
+ int full_size = 0x200000;
+ int size = 0x10000;
+ u8 *src, *dst;
+ uint map_size;
+ ulong map_base;
+ uint offset;
+ int i;
+
+ src = map_sysmem(0x20000, full_size);
+ ut_assertok(os_write_file("spi.bin", src, full_size));
+ ut_assertok(uclass_first_device_err(UCLASS_SPI_FLASH, &dev));
+
+ dst = map_sysmem(0x20000 + full_size, full_size);
+ ut_assertok(spi_flash_read_dm(dev, 0, size, dst));
+ ut_assertok(memcmp(src, dst, size));
+
+ /* Erase */
+ ut_assertok(spi_flash_erase_dm(dev, 0, size));
+ ut_assertok(spi_flash_read_dm(dev, 0, size, dst));
+ for (i = 0; i < size; i++)
+ ut_asserteq(dst[i], 0xff);
+
+ /* Write some new data */
+ for (i = 0; i < size; i++)
+ src[i] = i;
+ ut_assertok(spi_flash_write_dm(dev, 0, size, src));
+ ut_assertok(spi_flash_read_dm(dev, 0, size, dst));
+ ut_assertok(memcmp(src, dst, size));
+
+ /* Try the write-protect stuff */
+ ut_assertok(uclass_first_device_err(UCLASS_SPI_EMUL, &emul));
+ ut_asserteq(0, spl_flash_get_sw_write_prot(dev));
+ sandbox_sf_set_block_protect(emul, 1);
+ ut_asserteq(1, spl_flash_get_sw_write_prot(dev));
+ sandbox_sf_set_block_protect(emul, 0);
+ ut_asserteq(0, spl_flash_get_sw_write_prot(dev));
+
+ /* Check mapping */
+ ut_assertok(dm_spi_get_mmap(dev, &map_base, &map_size, &offset));
+ ut_asserteq(0x1000, map_base);
+ ut_asserteq(0x2000, map_size);
+ ut_asserteq(0x100, offset);
+
+ /*
+ * Since we are about to destroy all devices, we must tell sandbox
+ * to forget the emulation device
+ */
+ sandbox_sf_unbind_emul(state_get_current(), 0, 0);
+
+ return 0;
+}
+DM_TEST(dm_test_spi_flash, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Functional test that sandbox SPI flash works correctly */
+static int dm_test_spi_flash_func(struct unit_test_state *uts)
+{
+ /*
+ * Create an empty test file and run the SPI flash tests. This is a
+ * long way from being a unit test, but it does test SPI device and
+ * emulator binding, probing, the SPI flash emulator including
+ * device tree decoding, plus the file-based backing store of SPI.
+ *
+ * More targeted tests could be created to perform the above steps
+ * one at a time. This might not increase test coverage much, but
+ * it would make bugs easier to find. It's not clear whether the
+ * benefit is worth the extra complexity.
+ */
+ ut_asserteq(0, run_command_list(
+ "host save hostfs - 0 spi.bin 200000;"
+ "sf probe;"
+ "sf test 0 10000", -1, 0));
+ /*
+ * Since we are about to destroy all devices, we must tell sandbox
+ * to forget the emulation device
+ */
+ sandbox_sf_unbind_emul(state_get_current(), 0, 0);
+
+ return 0;
+}
+DM_TEST(dm_test_spi_flash_func, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/smem.c b/test/dm/smem.c
new file mode 100644
index 00000000..4099a5f6
--- /dev/null
+++ b/test/dm/smem.c
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2018 Ramon Fried <ramon.fried@gmail.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <smem.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Basic test of the smem uclass */
+static int dm_test_smem_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ size_t size;
+
+ ut_assertok(uclass_get_device(UCLASS_SMEM, 0, &dev));
+ ut_assertnonnull(dev);
+ ut_assertok(smem_alloc(dev, -1, 0, 16));
+ ut_asserteq(0, smem_get_free_space(dev, -1));
+ ut_assertnull(smem_get(dev, -1, 0, &size));
+
+ return 0;
+}
+DM_TEST(dm_test_smem_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
diff --git a/test/dm/sound.c b/test/dm/sound.c
new file mode 100644
index 00000000..3767abbd
--- /dev/null
+++ b/test/dm/sound.c
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2018 Google LLC
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <sound.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <asm/test.h>
+
+/* Basic test of the sound codec uclass */
+static int dm_test_sound(struct unit_test_state *uts)
+{
+ struct sound_uc_priv *uc_priv;
+ struct udevice *dev;
+
+ /* check probe success */
+ ut_assertok(uclass_first_device_err(UCLASS_SOUND, &dev));
+ uc_priv = dev_get_uclass_priv(dev);
+ ut_asserteq_str("audio-codec", uc_priv->codec->name);
+ ut_asserteq_str("i2s", uc_priv->i2s->name);
+ ut_asserteq(0, sandbox_get_setup_called(dev));
+
+ ut_assertok(sound_beep(dev, 1, 100));
+ ut_asserteq(4560, sandbox_get_sound_sum(dev));
+ ut_assertok(sound_beep(dev, 1, 100));
+ ut_asserteq(9120, sandbox_get_sound_sum(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_sound, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test of the 'start beep' operations */
+static int dm_test_sound_beep(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* check probe success */
+ ut_assertok(uclass_first_device_err(UCLASS_SOUND, &dev));
+ ut_asserteq(-ENOSYS, sound_start_beep(dev, 100));
+ ut_asserteq(0, sandbox_get_beep_frequency(dev));
+
+ sandbox_set_allow_beep(dev, true);
+ ut_asserteq(0, sound_start_beep(dev, 100));
+ ut_asserteq(100, sandbox_get_beep_frequency(dev));
+
+ ut_asserteq(0, sound_stop_beep(dev));
+ ut_asserteq(0, sandbox_get_beep_frequency(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_sound_beep, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/spi.c b/test/dm/spi.c
new file mode 100644
index 00000000..ffd789cd
--- /dev/null
+++ b/test/dm/spi.c
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <spi.h>
+#include <spi_flash.h>
+#include <asm/state.h>
+#include <dm/device-internal.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <dm/util.h>
+#include <test/ut.h>
+
+/* Test that we can find buses and chip-selects */
+static int dm_test_spi_find(struct unit_test_state *uts)
+{
+ struct sandbox_state *state = state_get_current();
+ struct spi_slave *slave;
+ struct udevice *bus, *dev;
+ const int busnum = 0, cs = 0, mode = 0, speed = 1000000, cs_b = 1;
+ struct spi_cs_info info;
+ ofnode node;
+
+ ut_asserteq(-ENODEV, uclass_find_device_by_seq(UCLASS_SPI, busnum,
+ false, &bus));
+
+ /*
+ * The post_bind() method will bind devices to chip selects. Check
+ * this then remove the emulation and the slave device.
+ */
+ ut_asserteq(0, uclass_get_device_by_seq(UCLASS_SPI, busnum, &bus));
+ ut_assertok(spi_cs_info(bus, cs, &info));
+ node = dev_ofnode(info.dev);
+ device_remove(info.dev, DM_REMOVE_NORMAL);
+ device_unbind(info.dev);
+
+ /*
+ * Even though the device is gone, the sandbox SPI drivers always
+ * reports that CS 0 is present
+ */
+ ut_assertok(spi_cs_info(bus, cs, &info));
+ ut_asserteq_ptr(NULL, info.dev);
+
+ /* This finds nothing because we removed the device */
+ ut_asserteq(-ENODEV, spi_find_bus_and_cs(busnum, cs, &bus, &dev));
+ ut_asserteq(-ENODEV, spi_get_bus_and_cs(busnum, cs, speed, mode,
+ NULL, 0, &bus, &slave));
+
+ /*
+ * This forces the device to be re-added, but there is no emulation
+ * connected so the probe will fail. We require that bus is left
+ * alone on failure, and that the spi_get_bus_and_cs() does not add
+ * a 'partially-inited' device.
+ */
+ ut_asserteq(-ENODEV, spi_find_bus_and_cs(busnum, cs, &bus, &dev));
+ ut_asserteq(-ENOENT, spi_get_bus_and_cs(busnum, cs, speed, mode,
+ "spi_flash_std", "name", &bus,
+ &slave));
+ sandbox_sf_unbind_emul(state_get_current(), busnum, cs);
+ ut_assertok(spi_cs_info(bus, cs, &info));
+ ut_asserteq_ptr(NULL, info.dev);
+
+ /* Add the emulation and try again */
+ ut_assertok(sandbox_sf_bind_emul(state, busnum, cs, bus, node,
+ "name"));
+ ut_assertok(spi_find_bus_and_cs(busnum, cs, &bus, &dev));
+ ut_assertok(spi_get_bus_and_cs(busnum, cs, speed, mode,
+ "spi_flash_std", "name", &bus, &slave));
+
+ ut_assertok(spi_cs_info(bus, cs, &info));
+ ut_asserteq_ptr(info.dev, slave->dev);
+
+ /* We should be able to add something to another chip select */
+ ut_assertok(sandbox_sf_bind_emul(state, busnum, cs_b, bus, node,
+ "name"));
+ ut_assertok(spi_get_bus_and_cs(busnum, cs_b, speed, mode,
+ "spi_flash_std", "name", &bus, &slave));
+ ut_assertok(spi_cs_info(bus, cs_b, &info));
+ ut_asserteq_ptr(info.dev, slave->dev);
+
+ /*
+ * Since we are about to destroy all devices, we must tell sandbox
+ * to forget the emulation device
+ */
+ sandbox_sf_unbind_emul(state_get_current(), busnum, cs);
+ sandbox_sf_unbind_emul(state_get_current(), busnum, cs_b);
+
+ return 0;
+}
+DM_TEST(dm_test_spi_find, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that sandbox SPI works correctly */
+static int dm_test_spi_xfer(struct unit_test_state *uts)
+{
+ struct spi_slave *slave;
+ struct udevice *bus;
+ const int busnum = 0, cs = 0, mode = 0;
+ const char dout[5] = {0x9f};
+ unsigned char din[5];
+
+ ut_assertok(spi_get_bus_and_cs(busnum, cs, 1000000, mode, NULL, 0,
+ &bus, &slave));
+ ut_assertok(spi_claim_bus(slave));
+ ut_assertok(spi_xfer(slave, 40, dout, din,
+ SPI_XFER_BEGIN | SPI_XFER_END));
+ ut_asserteq(0xff, din[0]);
+ ut_asserteq(0x20, din[1]);
+ ut_asserteq(0x20, din[2]);
+ ut_asserteq(0x15, din[3]);
+ spi_release_bus(slave);
+
+ /*
+ * Since we are about to destroy all devices, we must tell sandbox
+ * to forget the emulation device
+ */
+#ifdef CONFIG_DM_SPI_FLASH
+ sandbox_sf_unbind_emul(state_get_current(), busnum, cs);
+#endif
+
+ return 0;
+}
+DM_TEST(dm_test_spi_xfer, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/spmi.c b/test/dm/spmi.c
new file mode 100644
index 00000000..e6a91085
--- /dev/null
+++ b/test/dm/spmi.c
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2015 Mateusz Kulikowski <mateusz.kulikowski@gmail.com>
+ */
+
+#include <common.h>
+#include <fdtdec.h>
+#include <dm.h>
+#include <dm/device.h>
+#include <dm/root.h>
+#include <dm/test.h>
+#include <dm/util.h>
+#include <power/pmic.h>
+#include <spmi/spmi.h>
+#include <asm/gpio.h>
+#include <test/ut.h>
+
+/* Test if bus childs got probed propperly*/
+static int dm_test_spmi_probe(struct unit_test_state *uts)
+{
+ const char *name = "spmi@0";
+ struct udevice *bus, *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_SPMI, 0, &bus));
+
+ /* Check bus name */
+ ut_asserteq_str(name, bus->name);
+
+ /* Check that it has some devices */
+ ut_asserteq(device_has_children(bus), true);
+
+ ut_assertok(device_find_first_child(bus, &dev));
+
+ /* There should be at least one child */
+ ut_assertnonnull(dev);
+
+ /* Check that only PMICs are connected to the bus */
+ while (dev) {
+ ut_asserteq(device_get_uclass_id(dev), UCLASS_PMIC);
+ device_find_next_child(&dev);
+ }
+
+ return 0;
+}
+DM_TEST(dm_test_spmi_probe, DM_TESTF_SCAN_FDT);
+
+/* Test if it's possible to read bus directly and indirectly */
+static int dm_test_spmi_access(struct unit_test_state *uts)
+{
+ const char *pmic_name = "pm8916@0";
+ struct udevice *bus, *pmic;
+
+ ut_assertok(uclass_get_device(UCLASS_SPMI, 0, &bus));
+
+ ut_assertok(device_get_child(bus, 0, &pmic));
+
+ /* Sanity check if it's proper PMIC */
+ ut_asserteq_str(pmic_name, pmic->name);
+
+ /* Read PMIC ID reg using SPMI bus - it assumes it has slaveID == 0*/
+ ut_asserteq(spmi_reg_read(bus, 0, 0xC0, 0x4), 0x10);
+ ut_asserteq(spmi_reg_read(bus, 0, 0xC0, 0x5), 0x5);
+
+ /* Read ID reg via pmic interface */
+ ut_asserteq(pmic_reg_read(pmic, 0xC004), 0x10);
+ ut_asserteq(pmic_reg_read(pmic, 0xC005), 0x5);
+
+ return 0;
+}
+DM_TEST(dm_test_spmi_access, DM_TESTF_SCAN_FDT);
+
+
+/* Test if it's possible to access GPIO that should be in pmic */
+static int dm_test_spmi_access_peripheral(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ unsigned int offset, gpio;
+ const char *name;
+ int offset_count;
+
+ /* Get second pin of PMIC GPIO */
+ ut_assertok(gpio_lookup_name("spmi1", &dev, &offset, &gpio));
+
+ /* Check if PMIC is parent */
+ ut_asserteq(device_get_uclass_id(dev->parent), UCLASS_PMIC);
+
+ /* This should be second gpio */
+ ut_asserteq(1, offset);
+
+ name = gpio_get_bank_info(dev, &offset_count);
+
+ /* Check bank name */
+ ut_asserteq_str("spmi", name);
+ /* Check pin count */
+ ut_asserteq(4, offset_count);
+
+ ut_assertok(gpio_request(gpio, "testing"));
+
+ /* Try to set/clear gpio */
+ ut_assertok(gpio_direction_output(gpio, 0));
+ ut_asserteq(gpio_get_value(gpio), 0);
+ ut_assertok(gpio_direction_output(gpio, 1));
+ ut_asserteq(gpio_get_value(gpio), 1);
+ ut_assertok(gpio_direction_input(gpio));
+ ut_asserteq(gpio_get_value(gpio), 1);
+
+ ut_assertok(gpio_free(gpio));
+
+ return 0;
+}
+DM_TEST(dm_test_spmi_access_peripheral, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/syscon.c b/test/dm/syscon.c
new file mode 100644
index 00000000..0ff9da7e
--- /dev/null
+++ b/test/dm/syscon.c
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <syscon.h>
+#include <regmap.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Base test of system controllers */
+static int dm_test_syscon_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 0, &dev));
+ ut_asserteq(SYSCON0, dev->driver_data);
+
+ ut_assertok(uclass_get_device(UCLASS_SYSCON, 1, &dev));
+ ut_asserteq(SYSCON1, dev->driver_data);
+
+ ut_asserteq(-ENODEV, uclass_get_device(UCLASS_SYSCON, 2, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_syscon_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test system controller finding */
+static int dm_test_syscon_by_driver_data(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(syscon_get_by_driver_data(SYSCON0, &dev));
+ ut_asserteq(SYSCON0, dev->driver_data);
+
+ ut_assertok(syscon_get_by_driver_data(SYSCON1, &dev));
+ ut_asserteq(SYSCON1, dev->driver_data);
+
+ ut_asserteq(-ENODEV, syscon_get_by_driver_data(2, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_syscon_by_driver_data, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test system controller by phandle */
+static int dm_test_syscon_by_phandle(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct regmap *map;
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_TEST_PROBE, "test4",
+ &dev));
+
+ ut_assertok_ptr(syscon_regmap_lookup_by_phandle(dev, "first-syscon"));
+ map = syscon_regmap_lookup_by_phandle(dev, "first-syscon");
+ ut_assert(map);
+ ut_assert(!IS_ERR(map));
+ ut_asserteq(1, map->range_count);
+
+ ut_assertok_ptr(syscon_regmap_lookup_by_phandle(dev,
+ "second-sys-ctrl"));
+ map = syscon_regmap_lookup_by_phandle(dev, "second-sys-ctrl");
+ ut_assert(map);
+ ut_assert(!IS_ERR(map));
+ ut_asserteq(4, map->range_count);
+
+ ut_assertok_ptr(syscon_regmap_lookup_by_phandle(dev,
+ "third-syscon"));
+ map = syscon_regmap_lookup_by_phandle(dev, "third-syscon");
+ ut_assert(map);
+ ut_assert(!IS_ERR(map));
+ ut_asserteq(4, map->range_count);
+
+ ut_assert(IS_ERR(syscon_regmap_lookup_by_phandle(dev, "not-present")));
+
+ return 0;
+}
+DM_TEST(dm_test_syscon_by_phandle, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/sysreset.c b/test/dm/sysreset.c
new file mode 100644
index 00000000..5b2358ef
--- /dev/null
+++ b/test/dm/sysreset.c
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <sysreset.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Test that we can use particular sysreset devices */
+static int dm_test_sysreset_base(struct unit_test_state *uts)
+{
+ struct sandbox_state *state = state_get_current();
+ struct udevice *dev;
+
+ /* Device 0 is the platform data device - it should never respond */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 0, &dev));
+ ut_asserteq(-ENODEV, sysreset_request(dev, SYSRESET_WARM));
+ ut_asserteq(-ENODEV, sysreset_request(dev, SYSRESET_COLD));
+ ut_asserteq(-ENODEV, sysreset_request(dev, SYSRESET_POWER));
+
+ /* Device 1 is the warm sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 1, &dev));
+ ut_asserteq(-EACCES, sysreset_request(dev, SYSRESET_WARM));
+ ut_asserteq(-ENOSYS, sysreset_request(dev, SYSRESET_COLD));
+ ut_asserteq(-ENOSYS, sysreset_request(dev, SYSRESET_POWER));
+
+ state->sysreset_allowed[SYSRESET_WARM] = true;
+ ut_asserteq(-EINPROGRESS, sysreset_request(dev, SYSRESET_WARM));
+ state->sysreset_allowed[SYSRESET_WARM] = false;
+
+ /* Device 2 is the cold sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 2, &dev));
+ ut_asserteq(-ENOSYS, sysreset_request(dev, SYSRESET_WARM));
+ ut_asserteq(-EACCES, sysreset_request(dev, SYSRESET_COLD));
+ state->sysreset_allowed[SYSRESET_POWER] = false;
+ ut_asserteq(-EACCES, sysreset_request(dev, SYSRESET_POWER));
+ state->sysreset_allowed[SYSRESET_POWER] = true;
+
+ return 0;
+}
+DM_TEST(dm_test_sysreset_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_sysreset_get_status(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ char msg[64];
+
+ /* Device 1 is the warm sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 1, &dev));
+ ut_assertok(sysreset_get_status(dev, msg, sizeof(msg)));
+ ut_asserteq_str("Reset Status: WARM", msg);
+
+ /* Device 2 is the cold sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 2, &dev));
+ ut_assertok(sysreset_get_status(dev, msg, sizeof(msg)));
+ ut_asserteq_str("Reset Status: COLD", msg);
+
+ return 0;
+}
+DM_TEST(dm_test_sysreset_get_status, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can walk through the sysreset devices */
+static int dm_test_sysreset_walk(struct unit_test_state *uts)
+{
+ struct sandbox_state *state = state_get_current();
+
+ /* If we generate a power sysreset, we will exit sandbox! */
+ state->sysreset_allowed[SYSRESET_POWER] = false;
+ state->sysreset_allowed[SYSRESET_POWER_OFF] = false;
+ ut_asserteq(-EACCES, sysreset_walk(SYSRESET_WARM));
+ ut_asserteq(-EACCES, sysreset_walk(SYSRESET_COLD));
+ ut_asserteq(-EACCES, sysreset_walk(SYSRESET_POWER));
+
+ /*
+ * Enable cold system reset - this should make cold system reset work,
+ * plus a warm system reset should be promoted to cold, since this is
+ * the next step along.
+ */
+ state->sysreset_allowed[SYSRESET_COLD] = true;
+ ut_asserteq(-EINPROGRESS, sysreset_walk(SYSRESET_WARM));
+ ut_asserteq(-EINPROGRESS, sysreset_walk(SYSRESET_COLD));
+ ut_asserteq(-EACCES, sysreset_walk(SYSRESET_POWER));
+ state->sysreset_allowed[SYSRESET_COLD] = false;
+ state->sysreset_allowed[SYSRESET_POWER] = true;
+
+ return 0;
+}
+DM_TEST(dm_test_sysreset_walk, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_sysreset_get_last(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* Device 1 is the warm sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 1, &dev));
+ ut_asserteq(SYSRESET_WARM, sysreset_get_last(dev));
+
+ /* Device 2 is the cold sysreset device */
+ ut_assertok(uclass_get_device(UCLASS_SYSRESET, 2, &dev));
+ ut_asserteq(SYSRESET_POWER, sysreset_get_last(dev));
+
+ /* This is device 0, the non-DT one */
+ ut_asserteq(SYSRESET_POWER, sysreset_get_last_walk());
+
+ return 0;
+}
+DM_TEST(dm_test_sysreset_get_last, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/tee.c b/test/dm/tee.c
new file mode 100644
index 00000000..22f05a42
--- /dev/null
+++ b/test/dm/tee.c
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2018 Linaro Limited
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <dm/test.h>
+#include <sandboxtee.h>
+#include <tee.h>
+#include <test/ut.h>
+#include <tee/optee_ta_avb.h>
+
+static int open_session(struct udevice *dev, u32 *session)
+{
+ struct tee_open_session_arg arg;
+ const struct tee_optee_ta_uuid uuid = TA_AVB_UUID;
+ int rc;
+
+ memset(&arg, 0, sizeof(arg));
+ tee_optee_ta_uuid_to_octets(arg.uuid, &uuid);
+ rc = tee_open_session(dev, &arg, 0, NULL);
+ if (rc)
+ return rc;
+ if (arg.ret)
+ return -EIO;
+ *session = arg.session;
+
+ return 0;
+}
+
+static int invoke_func(struct udevice *dev, u32 session)
+{
+ struct tee_param param = { .attr = TEE_PARAM_ATTR_TYPE_VALUE_OUTPUT };
+ struct tee_invoke_arg arg;
+
+ memset(&arg, 0, sizeof(arg));
+ arg.session = session;
+ arg.func = TA_AVB_CMD_READ_LOCK_STATE;
+
+ if (tee_invoke_func(dev, &arg, 1, &param) || arg.ret)
+ return -1;
+
+ return 0;
+}
+
+static int match(struct tee_version_data *vers, const void *data)
+{
+ return vers->gen_caps & TEE_GEN_CAP_GP;
+}
+
+struct test_tee_vars {
+ struct tee_shm *reg_shm;
+ struct tee_shm *alloc_shm;
+};
+
+static int test_tee(struct unit_test_state *uts, struct test_tee_vars *vars)
+{
+ struct tee_version_data vers;
+ struct udevice *dev;
+ struct sandbox_tee_state *state;
+ u32 session = 0;
+ int rc;
+ u8 data[128];
+
+ dev = tee_find_device(NULL, match, NULL, &vers);
+ ut_assert(dev);
+ state = dev_get_priv(dev);
+ ut_assert(!state->session);
+
+ rc = open_session(dev, &session);
+ ut_assert(!rc);
+ ut_assert(session == state->session);
+
+ rc = invoke_func(dev, session);
+ ut_assert(!rc);
+
+ rc = tee_close_session(dev, session);
+ ut_assert(!rc);
+ ut_assert(!state->session);
+
+ ut_assert(!state->num_shms);
+ rc = tee_shm_register(dev, data, sizeof(data), 0, &vars->reg_shm);
+ ut_assert(!rc);
+ ut_assert(state->num_shms == 1);
+
+ rc = tee_shm_alloc(dev, 256, 0, &vars->alloc_shm);
+ ut_assert(!rc);
+ ut_assert(state->num_shms == 2);
+
+ ut_assert(tee_shm_is_registered(vars->reg_shm, dev));
+ ut_assert(tee_shm_is_registered(vars->alloc_shm, dev));
+
+ tee_shm_free(vars->reg_shm);
+ vars->reg_shm = NULL;
+ tee_shm_free(vars->alloc_shm);
+ vars->alloc_shm = NULL;
+ ut_assert(!state->num_shms);
+
+ return 0;
+}
+
+static int dm_test_tee(struct unit_test_state *uts)
+{
+ struct test_tee_vars vars = { NULL, NULL };
+ int rc = test_tee(uts, &vars);
+
+ /* In case test_tee() asserts these may still remain allocated */
+ tee_shm_free(vars.reg_shm);
+ tee_shm_free(vars.alloc_shm);
+
+ return rc;
+}
+
+DM_TEST(dm_test_tee, DM_TESTF_SCAN_FDT);
diff --git a/test/dm/test-driver.c b/test/dm/test-driver.c
new file mode 100644
index 00000000..abb5b711
--- /dev/null
+++ b/test/dm/test-driver.c
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2013 Google, Inc
+ *
+ * (C) Copyright 2012
+ * Pavel Herrmann <morpheus.ibis@gmail.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <errno.h>
+#include <malloc.h>
+#include <dm/test.h>
+#include <test/ut.h>
+#include <asm/io.h>
+
+int dm_testdrv_op_count[DM_TEST_OP_COUNT];
+static struct unit_test_state *uts = &global_dm_test_state;
+
+static int testdrv_ping(struct udevice *dev, int pingval, int *pingret)
+{
+ const struct dm_test_pdata *pdata = dev_get_platdata(dev);
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ *pingret = pingval + pdata->ping_add;
+ priv->ping_total += *pingret;
+
+ return 0;
+}
+
+static const struct test_ops test_ops = {
+ .ping = testdrv_ping,
+};
+
+static int test_bind(struct udevice *dev)
+{
+ /* Private data should not be allocated */
+ ut_assert(!dev_get_priv(dev));
+
+ dm_testdrv_op_count[DM_TEST_OP_BIND]++;
+ return 0;
+}
+
+static int test_probe(struct udevice *dev)
+{
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ /* Private data should be allocated */
+ ut_assert(priv);
+
+ dm_testdrv_op_count[DM_TEST_OP_PROBE]++;
+ priv->ping_total += DM_TEST_START_TOTAL;
+ return 0;
+}
+
+static int test_remove(struct udevice *dev)
+{
+ /* Private data should still be allocated */
+ ut_assert(dev_get_priv(dev));
+
+ dm_testdrv_op_count[DM_TEST_OP_REMOVE]++;
+ return 0;
+}
+
+static int test_unbind(struct udevice *dev)
+{
+ /* Private data should not be allocated */
+ ut_assert(!dev->priv);
+
+ dm_testdrv_op_count[DM_TEST_OP_UNBIND]++;
+ return 0;
+}
+
+U_BOOT_DRIVER(test_drv) = {
+ .name = "test_drv",
+ .id = UCLASS_TEST,
+ .ops = &test_ops,
+ .bind = test_bind,
+ .probe = test_probe,
+ .remove = test_remove,
+ .unbind = test_unbind,
+ .priv_auto_alloc_size = sizeof(struct dm_test_priv),
+};
+
+U_BOOT_DRIVER(test2_drv) = {
+ .name = "test2_drv",
+ .id = UCLASS_TEST,
+ .ops = &test_ops,
+ .bind = test_bind,
+ .probe = test_probe,
+ .remove = test_remove,
+ .unbind = test_unbind,
+ .priv_auto_alloc_size = sizeof(struct dm_test_priv),
+};
+
+static int test_manual_drv_ping(struct udevice *dev, int pingval, int *pingret)
+{
+ *pingret = pingval + 2;
+
+ return 0;
+}
+
+static const struct test_ops test_manual_ops = {
+ .ping = test_manual_drv_ping,
+};
+
+static int test_manual_bind(struct udevice *dev)
+{
+ dm_testdrv_op_count[DM_TEST_OP_BIND]++;
+
+ return 0;
+}
+
+static int test_manual_probe(struct udevice *dev)
+{
+ struct dm_test_state *dms = uts->priv;
+
+ dm_testdrv_op_count[DM_TEST_OP_PROBE]++;
+ if (!dms->force_fail_alloc)
+ dev->priv = calloc(1, sizeof(struct dm_test_priv));
+ if (!dev->priv)
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int test_manual_remove(struct udevice *dev)
+{
+ dm_testdrv_op_count[DM_TEST_OP_REMOVE]++;
+ return 0;
+}
+
+static int test_manual_unbind(struct udevice *dev)
+{
+ dm_testdrv_op_count[DM_TEST_OP_UNBIND]++;
+ return 0;
+}
+
+U_BOOT_DRIVER(test_manual_drv) = {
+ .name = "test_manual_drv",
+ .id = UCLASS_TEST,
+ .ops = &test_manual_ops,
+ .bind = test_manual_bind,
+ .probe = test_manual_probe,
+ .remove = test_manual_remove,
+ .unbind = test_manual_unbind,
+};
+
+U_BOOT_DRIVER(test_pre_reloc_drv) = {
+ .name = "test_pre_reloc_drv",
+ .id = UCLASS_TEST,
+ .ops = &test_manual_ops,
+ .bind = test_manual_bind,
+ .probe = test_manual_probe,
+ .remove = test_manual_remove,
+ .unbind = test_manual_unbind,
+ .flags = DM_FLAG_PRE_RELOC,
+};
+
+U_BOOT_DRIVER(test_act_dma_drv) = {
+ .name = "test_act_dma_drv",
+ .id = UCLASS_TEST,
+ .ops = &test_manual_ops,
+ .bind = test_manual_bind,
+ .probe = test_manual_probe,
+ .remove = test_manual_remove,
+ .unbind = test_manual_unbind,
+ .flags = DM_FLAG_ACTIVE_DMA,
+};
diff --git a/test/dm/test-fdt.c b/test/dm/test-fdt.c
new file mode 100644
index 00000000..1fb8b5c2
--- /dev/null
+++ b/test/dm/test-fdt.c
@@ -0,0 +1,816 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <errno.h>
+#include <fdtdec.h>
+#include <malloc.h>
+#include <asm/io.h>
+#include <dm/test.h>
+#include <dm/root.h>
+#include <dm/device-internal.h>
+#include <dm/uclass-internal.h>
+#include <dm/util.h>
+#include <dm/lists.h>
+#include <dm/of_access.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+static int testfdt_drv_ping(struct udevice *dev, int pingval, int *pingret)
+{
+ const struct dm_test_pdata *pdata = dev->platdata;
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ *pingret = pingval + pdata->ping_add;
+ priv->ping_total += *pingret;
+
+ return 0;
+}
+
+static const struct test_ops test_ops = {
+ .ping = testfdt_drv_ping,
+};
+
+static int testfdt_ofdata_to_platdata(struct udevice *dev)
+{
+ struct dm_test_pdata *pdata = dev_get_platdata(dev);
+
+ pdata->ping_add = fdtdec_get_int(gd->fdt_blob, dev_of_offset(dev),
+ "ping-add", -1);
+ pdata->base = fdtdec_get_addr(gd->fdt_blob, dev_of_offset(dev),
+ "ping-expect");
+
+ return 0;
+}
+
+static int testfdt_drv_probe(struct udevice *dev)
+{
+ struct dm_test_priv *priv = dev_get_priv(dev);
+
+ priv->ping_total += DM_TEST_START_TOTAL;
+
+ /*
+ * If this device is on a bus, the uclass_flag will be set before
+ * calling this function. In the meantime the uclass_postp is
+ * initlized to a value -1. These are used respectively by
+ * dm_test_bus_child_pre_probe_uclass() and
+ * dm_test_bus_child_post_probe_uclass().
+ */
+ priv->uclass_total += priv->uclass_flag;
+ priv->uclass_postp = -1;
+
+ return 0;
+}
+
+static const struct udevice_id testfdt_ids[] = {
+ {
+ .compatible = "denx,u-boot-fdt-test",
+ .data = DM_TEST_TYPE_FIRST },
+ {
+ .compatible = "google,another-fdt-test",
+ .data = DM_TEST_TYPE_SECOND },
+ { }
+};
+
+U_BOOT_DRIVER(testfdt_drv) = {
+ .name = "testfdt_drv",
+ .of_match = testfdt_ids,
+ .id = UCLASS_TEST_FDT,
+ .ofdata_to_platdata = testfdt_ofdata_to_platdata,
+ .probe = testfdt_drv_probe,
+ .ops = &test_ops,
+ .priv_auto_alloc_size = sizeof(struct dm_test_priv),
+ .platdata_auto_alloc_size = sizeof(struct dm_test_pdata),
+};
+
+static const struct udevice_id testfdt1_ids[] = {
+ {
+ .compatible = "denx,u-boot-fdt-test1",
+ .data = DM_TEST_TYPE_FIRST },
+ { }
+};
+
+U_BOOT_DRIVER(testfdt1_drv) = {
+ .name = "testfdt1_drv",
+ .of_match = testfdt1_ids,
+ .id = UCLASS_TEST_FDT,
+ .ofdata_to_platdata = testfdt_ofdata_to_platdata,
+ .probe = testfdt_drv_probe,
+ .ops = &test_ops,
+ .priv_auto_alloc_size = sizeof(struct dm_test_priv),
+ .platdata_auto_alloc_size = sizeof(struct dm_test_pdata),
+ .flags = DM_FLAG_PRE_RELOC,
+};
+
+/* From here is the testfdt uclass code */
+int testfdt_ping(struct udevice *dev, int pingval, int *pingret)
+{
+ const struct test_ops *ops = device_get_ops(dev);
+
+ if (!ops->ping)
+ return -ENOSYS;
+
+ return ops->ping(dev, pingval, pingret);
+}
+
+UCLASS_DRIVER(testfdt) = {
+ .name = "testfdt",
+ .id = UCLASS_TEST_FDT,
+ .flags = DM_UC_FLAG_SEQ_ALIAS,
+};
+
+struct dm_testprobe_pdata {
+ int probe_err;
+};
+
+static int testprobe_drv_probe(struct udevice *dev)
+{
+ struct dm_testprobe_pdata *pdata = dev_get_platdata(dev);
+
+ return pdata->probe_err;
+}
+
+static const struct udevice_id testprobe_ids[] = {
+ { .compatible = "denx,u-boot-probe-test" },
+ { }
+};
+
+U_BOOT_DRIVER(testprobe_drv) = {
+ .name = "testprobe_drv",
+ .of_match = testprobe_ids,
+ .id = UCLASS_TEST_PROBE,
+ .probe = testprobe_drv_probe,
+ .platdata_auto_alloc_size = sizeof(struct dm_testprobe_pdata),
+};
+
+UCLASS_DRIVER(testprobe) = {
+ .name = "testprobe",
+ .id = UCLASS_TEST_PROBE,
+ .flags = DM_UC_FLAG_SEQ_ALIAS,
+};
+
+int dm_check_devices(struct unit_test_state *uts, int num_devices)
+{
+ struct udevice *dev;
+ int ret;
+ int i;
+
+ /*
+ * Now check that the ping adds are what we expect. This is using the
+ * ping-add property in each node.
+ */
+ for (i = 0; i < num_devices; i++) {
+ uint32_t base;
+
+ ret = uclass_get_device(UCLASS_TEST_FDT, i, &dev);
+ ut_assert(!ret);
+
+ /*
+ * Get the 'ping-expect' property, which tells us what the
+ * ping add should be. We don't use the platdata because we
+ * want to test the code that sets that up
+ * (testfdt_drv_probe()).
+ */
+ base = fdtdec_get_addr(gd->fdt_blob, dev_of_offset(dev),
+ "ping-expect");
+ debug("dev=%d, base=%d: %s\n", i, base,
+ fdt_get_name(gd->fdt_blob, dev_of_offset(dev), NULL));
+
+ ut_assert(!dm_check_operations(uts, dev, base,
+ dev_get_priv(dev)));
+ }
+
+ return 0;
+}
+
+/* Test that FDT-based binding works correctly */
+static int dm_test_fdt(struct unit_test_state *uts)
+{
+ const int num_devices = 8;
+ struct udevice *dev;
+ struct uclass *uc;
+ int ret;
+ int i;
+
+ ret = dm_scan_fdt(gd->fdt_blob, false);
+ ut_assert(!ret);
+
+ ret = uclass_get(UCLASS_TEST_FDT, &uc);
+ ut_assert(!ret);
+
+ /* These are num_devices compatible root-level device tree nodes */
+ ut_asserteq(num_devices, list_count_items(&uc->dev_head));
+
+ /* Each should have platform data but no private data */
+ for (i = 0; i < num_devices; i++) {
+ ret = uclass_find_device(UCLASS_TEST_FDT, i, &dev);
+ ut_assert(!ret);
+ ut_assert(!dev_get_priv(dev));
+ ut_assert(dev->platdata);
+ }
+
+ ut_assertok(dm_check_devices(uts, num_devices));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt, 0);
+
+static int dm_test_alias_highest_id(struct unit_test_state *uts)
+{
+ int ret;
+
+ ret = dev_read_alias_highest_id("eth");
+ ut_asserteq(5, ret);
+
+ ret = dev_read_alias_highest_id("gpio");
+ ut_asserteq(2, ret);
+
+ ret = dev_read_alias_highest_id("pci");
+ ut_asserteq(2, ret);
+
+ ret = dev_read_alias_highest_id("i2c");
+ ut_asserteq(0, ret);
+
+ ret = dev_read_alias_highest_id("deadbeef");
+ ut_asserteq(-1, ret);
+
+ return 0;
+}
+DM_TEST(dm_test_alias_highest_id, 0);
+
+static int dm_test_fdt_pre_reloc(struct unit_test_state *uts)
+{
+ struct uclass *uc;
+ int ret;
+
+ ret = dm_scan_fdt(gd->fdt_blob, true);
+ ut_assert(!ret);
+
+ ret = uclass_get(UCLASS_TEST_FDT, &uc);
+ ut_assert(!ret);
+
+ /*
+ * These are 2 pre-reloc devices:
+ * one with "u-boot,dm-pre-reloc" property (a-test node), and the other
+ * one whose driver marked with DM_FLAG_PRE_RELOC flag (h-test node).
+ */
+ ut_asserteq(2, list_count_items(&uc->dev_head));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_pre_reloc, 0);
+
+/* Test that sequence numbers are allocated properly */
+static int dm_test_fdt_uclass_seq(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* A few basic santiy tests */
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_FDT, 3, true, &dev));
+ ut_asserteq_str("b-test", dev->name);
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_FDT, 8, true, &dev));
+ ut_asserteq_str("a-test", dev->name);
+
+ ut_asserteq(-ENODEV, uclass_find_device_by_seq(UCLASS_TEST_FDT, 5,
+ true, &dev));
+ ut_asserteq_ptr(NULL, dev);
+
+ /* Test aliases */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_TEST_FDT, 6, &dev));
+ ut_asserteq_str("e-test", dev->name);
+
+ ut_asserteq(-ENODEV, uclass_find_device_by_seq(UCLASS_TEST_FDT, 7,
+ true, &dev));
+
+ /*
+ * Note that c-test nodes are not probed since it is not a top-level
+ * node
+ */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_TEST_FDT, 3, &dev));
+ ut_asserteq_str("b-test", dev->name);
+
+ /*
+ * d-test wants sequence number 3 also, but it can't have it because
+ * b-test gets it first.
+ */
+ ut_assertok(uclass_get_device(UCLASS_TEST_FDT, 2, &dev));
+ ut_asserteq_str("d-test", dev->name);
+
+ /* d-test actually gets 0 */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_TEST_FDT, 0, &dev));
+ ut_asserteq_str("d-test", dev->name);
+
+ /* initially no one wants seq 1 */
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_TEST_FDT, 1,
+ &dev));
+ ut_assertok(uclass_get_device(UCLASS_TEST_FDT, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_TEST_FDT, 4, &dev));
+
+ /* But now that it is probed, we can find it */
+ ut_assertok(uclass_get_device_by_seq(UCLASS_TEST_FDT, 1, &dev));
+ ut_asserteq_str("f-test", dev->name);
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_uclass_seq, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test that we can find a device by device tree offset */
+static int dm_test_fdt_offset(struct unit_test_state *uts)
+{
+ const void *blob = gd->fdt_blob;
+ struct udevice *dev;
+ int node;
+
+ node = fdt_path_offset(blob, "/e-test");
+ ut_assert(node > 0);
+ ut_assertok(uclass_get_device_by_of_offset(UCLASS_TEST_FDT, node,
+ &dev));
+ ut_asserteq_str("e-test", dev->name);
+
+ /* This node should not be bound */
+ node = fdt_path_offset(blob, "/junk");
+ ut_assert(node > 0);
+ ut_asserteq(-ENODEV, uclass_get_device_by_of_offset(UCLASS_TEST_FDT,
+ node, &dev));
+
+ /* This is not a top level node so should not be probed */
+ node = fdt_path_offset(blob, "/some-bus/c-test@5");
+ ut_assert(node > 0);
+ ut_asserteq(-ENODEV, uclass_get_device_by_of_offset(UCLASS_TEST_FDT,
+ node, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_offset,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT | DM_TESTF_FLAT_TREE);
+
+/**
+ * Test various error conditions with uclass_first_device() and
+ * uclass_next_device()
+ */
+static int dm_test_first_next_device(struct unit_test_state *uts)
+{
+ struct dm_testprobe_pdata *pdata;
+ struct udevice *dev, *parent = NULL;
+ int count;
+ int ret;
+
+ /* There should be 4 devices */
+ for (ret = uclass_first_device(UCLASS_TEST_PROBE, &dev), count = 0;
+ dev;
+ ret = uclass_next_device(&dev)) {
+ count++;
+ parent = dev_get_parent(dev);
+ }
+ ut_assertok(ret);
+ ut_asserteq(4, count);
+
+ /* Remove them and try again, with an error on the second one */
+ ut_assertok(uclass_get_device(UCLASS_TEST_PROBE, 1, &dev));
+ pdata = dev_get_platdata(dev);
+ pdata->probe_err = -ENOMEM;
+ device_remove(parent, DM_REMOVE_NORMAL);
+ ut_assertok(uclass_first_device(UCLASS_TEST_PROBE, &dev));
+ ut_asserteq(-ENOMEM, uclass_next_device(&dev));
+ ut_asserteq_ptr(dev, NULL);
+
+ /* Now an error on the first one */
+ ut_assertok(uclass_get_device(UCLASS_TEST_PROBE, 0, &dev));
+ pdata = dev_get_platdata(dev);
+ pdata->probe_err = -ENOENT;
+ device_remove(parent, DM_REMOVE_NORMAL);
+ ut_asserteq(-ENOENT, uclass_first_device(UCLASS_TEST_PROBE, &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_first_next_device, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/**
+ * check_devices() - Check return values and pointers
+ *
+ * This runs through a full sequence of uclass_first_device_check()...
+ * uclass_next_device_check() checking that the return values and devices
+ * are correct.
+ *
+ * @uts: Test state
+ * @devlist: List of expected devices
+ * @mask: Indicates which devices should return an error. Device n should
+ * return error (-NOENT - n) if bit n is set, or no error (i.e. 0) if
+ * bit n is clear.
+ */
+static int check_devices(struct unit_test_state *uts,
+ struct udevice *devlist[], int mask)
+{
+ int expected_ret;
+ struct udevice *dev;
+ int i;
+
+ expected_ret = (mask & 1) ? -ENOENT : 0;
+ mask >>= 1;
+ ut_asserteq(expected_ret,
+ uclass_first_device_check(UCLASS_TEST_PROBE, &dev));
+ for (i = 0; i < 4; i++) {
+ ut_asserteq_ptr(devlist[i], dev);
+ expected_ret = (mask & 1) ? -ENOENT - (i + 1) : 0;
+ mask >>= 1;
+ ut_asserteq(expected_ret, uclass_next_device_check(&dev));
+ }
+ ut_asserteq_ptr(NULL, dev);
+
+ return 0;
+}
+
+/* Test uclass_first_device_check() and uclass_next_device_check() */
+static int dm_test_first_next_ok_device(struct unit_test_state *uts)
+{
+ struct dm_testprobe_pdata *pdata;
+ struct udevice *dev, *parent = NULL, *devlist[4];
+ int count;
+ int ret;
+
+ /* There should be 4 devices */
+ count = 0;
+ for (ret = uclass_first_device_check(UCLASS_TEST_PROBE, &dev);
+ dev;
+ ret = uclass_next_device_check(&dev)) {
+ ut_assertok(ret);
+ devlist[count++] = dev;
+ parent = dev_get_parent(dev);
+ }
+ ut_asserteq(4, count);
+ ut_assertok(uclass_first_device_check(UCLASS_TEST_PROBE, &dev));
+ ut_assertok(check_devices(uts, devlist, 0));
+
+ /* Remove them and try again, with an error on the second one */
+ pdata = dev_get_platdata(devlist[1]);
+ pdata->probe_err = -ENOENT - 1;
+ device_remove(parent, DM_REMOVE_NORMAL);
+ ut_assertok(check_devices(uts, devlist, 1 << 1));
+
+ /* Now an error on the first one */
+ pdata = dev_get_platdata(devlist[0]);
+ pdata->probe_err = -ENOENT - 0;
+ device_remove(parent, DM_REMOVE_NORMAL);
+ ut_assertok(check_devices(uts, devlist, 3 << 0));
+
+ /* Now errors on all */
+ pdata = dev_get_platdata(devlist[2]);
+ pdata->probe_err = -ENOENT - 2;
+ pdata = dev_get_platdata(devlist[3]);
+ pdata->probe_err = -ENOENT - 3;
+ device_remove(parent, DM_REMOVE_NORMAL);
+ ut_assertok(check_devices(uts, devlist, 0xf << 0));
+
+ return 0;
+}
+DM_TEST(dm_test_first_next_ok_device, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static const struct udevice_id fdt_dummy_ids[] = {
+ { .compatible = "denx,u-boot-fdt-dummy", },
+ { }
+};
+
+UCLASS_DRIVER(fdt_dummy) = {
+ .name = "fdt-dummy",
+ .id = UCLASS_TEST_DUMMY,
+ .flags = DM_UC_FLAG_SEQ_ALIAS,
+};
+
+U_BOOT_DRIVER(fdt_dummy_drv) = {
+ .name = "fdt_dummy_drv",
+ .of_match = fdt_dummy_ids,
+ .id = UCLASS_TEST_DUMMY,
+};
+
+static int dm_test_fdt_translation(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt32_t dma_addr[2];
+
+ /* Some simple translations */
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+ ut_asserteq_str("dev@0,0", dev->name);
+ ut_asserteq(0x8000, dev_read_addr(dev));
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 1, true, &dev));
+ ut_asserteq_str("dev@1,100", dev->name);
+ ut_asserteq(0x9000, dev_read_addr(dev));
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 2, true, &dev));
+ ut_asserteq_str("dev@2,200", dev->name);
+ ut_asserteq(0xA000, dev_read_addr(dev));
+
+ /* No translation for busses with #size-cells == 0 */
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 3, true, &dev));
+ ut_asserteq_str("dev@42", dev->name);
+ ut_asserteq(0x42, dev_read_addr(dev));
+
+ /* dma address translation */
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+ dma_addr[0] = cpu_to_be32(0);
+ dma_addr[1] = cpu_to_be32(0);
+ ut_asserteq(0x10000000, dev_translate_dma_address(dev, dma_addr));
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 1, true, &dev));
+ dma_addr[0] = cpu_to_be32(1);
+ dma_addr[1] = cpu_to_be32(0x100);
+ ut_asserteq(0x20000000, dev_translate_dma_address(dev, dma_addr));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_translation, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_fdt_remap_addr_flat(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = devfdt_get_addr(dev);
+ ut_asserteq(0x8000, addr);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, devfdt_remap_addr(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_flat,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT | DM_TESTF_FLAT_TREE);
+
+static int dm_test_fdt_remap_addr_index_flat(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = devfdt_get_addr_size_index(dev, 0, &size);
+ ut_asserteq(0x8000, addr);
+ ut_asserteq(0x1000, size);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, devfdt_remap_addr_index(dev, 0));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_index_flat,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT | DM_TESTF_FLAT_TREE);
+
+static int dm_test_fdt_remap_addr_name_flat(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = devfdt_get_addr_size_name(dev, "sandbox-dummy-0", &size);
+ ut_asserteq(0x8000, addr);
+ ut_asserteq(0x1000, size);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, devfdt_remap_addr_name(dev, "sandbox-dummy-0"));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_name_flat,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT | DM_TESTF_FLAT_TREE);
+
+static int dm_test_fdt_remap_addr_live(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = dev_read_addr(dev);
+ ut_asserteq(0x8000, addr);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, dev_remap_addr(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_live,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_fdt_remap_addr_index_live(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = dev_read_addr_size_index(dev, 0, &size);
+ ut_asserteq(0x8000, addr);
+ ut_asserteq(0x1000, size);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, dev_remap_addr_index(dev, 0));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_index_live,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_fdt_remap_addr_name_live(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ void *paddr;
+
+ ut_assertok(uclass_find_device_by_seq(UCLASS_TEST_DUMMY, 0, true, &dev));
+
+ addr = dev_read_addr_size_name(dev, "sandbox-dummy-0", &size);
+ ut_asserteq(0x8000, addr);
+ ut_asserteq(0x1000, size);
+
+ paddr = map_physmem(addr, 0, MAP_NOCACHE);
+ ut_assertnonnull(paddr);
+ ut_asserteq_ptr(paddr, dev_remap_addr_name(dev, "sandbox-dummy-0"));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_remap_addr_name_live,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_fdt_livetree_writing(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ ofnode node;
+
+ if (!of_live_active()) {
+ printf("Live tree not active; ignore test\n");
+ return 0;
+ }
+
+ /* Test enabling devices */
+
+ node = ofnode_path("/usb@2");
+
+ ut_assert(!of_device_is_available(ofnode_to_np(node)));
+ ofnode_set_enabled(node, true);
+ ut_assert(of_device_is_available(ofnode_to_np(node)));
+
+ device_bind_driver_to_node(dm_root(), "usb_sandbox", "usb@2", node,
+ &dev);
+ ut_assertok(uclass_find_device_by_seq(UCLASS_USB, 2, true, &dev));
+
+ /* Test string property setting */
+
+ ut_assert(device_is_compatible(dev, "sandbox,usb"));
+ ofnode_write_string(node, "compatible", "gdsys,super-usb");
+ ut_assert(device_is_compatible(dev, "gdsys,super-usb"));
+ ofnode_write_string(node, "compatible", "sandbox,usb");
+ ut_assert(device_is_compatible(dev, "sandbox,usb"));
+
+ /* Test setting generic properties */
+
+ /* Non-existent in DTB */
+ ut_asserteq(FDT_ADDR_T_NONE, dev_read_addr(dev));
+ /* reg = 0x42, size = 0x100 */
+ ut_assertok(ofnode_write_prop(node, "reg", 8,
+ "\x00\x00\x00\x42\x00\x00\x01\x00"));
+ ut_asserteq(0x42, dev_read_addr(dev));
+
+ /* Test disabling devices */
+
+ device_remove(dev, DM_REMOVE_NORMAL);
+ device_unbind(dev);
+
+ ut_assert(of_device_is_available(ofnode_to_np(node)));
+ ofnode_set_enabled(node, false);
+ ut_assert(!of_device_is_available(ofnode_to_np(node)));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_livetree_writing, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int dm_test_fdt_disable_enable_by_path(struct unit_test_state *uts)
+{
+ ofnode node;
+
+ if (!of_live_active()) {
+ printf("Live tree not active; ignore test\n");
+ return 0;
+ }
+
+ node = ofnode_path("/usb@2");
+
+ /* Test enabling devices */
+
+ ut_assert(!of_device_is_available(ofnode_to_np(node)));
+ dev_enable_by_path("/usb@2");
+ ut_assert(of_device_is_available(ofnode_to_np(node)));
+
+ /* Test disabling devices */
+
+ ut_assert(of_device_is_available(ofnode_to_np(node)));
+ dev_disable_by_path("/usb@2");
+ ut_assert(!of_device_is_available(ofnode_to_np(node)));
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_disable_enable_by_path, DM_TESTF_SCAN_PDATA |
+ DM_TESTF_SCAN_FDT);
+
+/* Test a few uclass phandle functions */
+static int dm_test_fdt_phandle(struct unit_test_state *uts)
+{
+ struct udevice *back, *dev, *dev2;
+
+ ut_assertok(uclass_find_first_device(UCLASS_PANEL_BACKLIGHT, &back));
+ ut_asserteq(-ENOENT, uclass_find_device_by_phandle(UCLASS_REGULATOR,
+ back, "missing", &dev));
+ ut_assertok(uclass_find_device_by_phandle(UCLASS_REGULATOR, back,
+ "power-supply", &dev));
+ ut_asserteq(0, device_active(dev));
+ ut_asserteq_str("ldo1", dev->name);
+ ut_assertok(uclass_get_device_by_phandle(UCLASS_REGULATOR, back,
+ "power-supply", &dev2));
+ ut_asserteq_ptr(dev, dev2);
+
+ return 0;
+}
+DM_TEST(dm_test_fdt_phandle, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test device_find_first_child_by_uclass() */
+static int dm_test_first_child(struct unit_test_state *uts)
+{
+ struct udevice *i2c, *dev, *dev2;
+
+ ut_assertok(uclass_first_device_err(UCLASS_I2C, &i2c));
+ ut_assertok(device_find_first_child_by_uclass(i2c, UCLASS_RTC, &dev));
+ ut_asserteq_str("rtc@43", dev->name);
+ ut_assertok(device_find_child_by_name(i2c, "rtc@43", &dev2));
+ ut_asserteq_ptr(dev, dev2);
+ ut_assertok(device_find_child_by_name(i2c, "rtc@61", &dev2));
+ ut_asserteq_str("rtc@61", dev2->name);
+
+ ut_assertok(device_find_first_child_by_uclass(i2c, UCLASS_I2C_EEPROM,
+ &dev));
+ ut_asserteq_str("eeprom@2c", dev->name);
+ ut_assertok(device_find_child_by_name(i2c, "eeprom@2c", &dev2));
+ ut_asserteq_ptr(dev, dev2);
+
+ ut_asserteq(-ENODEV, device_find_first_child_by_uclass(i2c,
+ UCLASS_VIDEO, &dev));
+ ut_asserteq(-ENODEV, device_find_child_by_name(i2c, "missing", &dev));
+
+ return 0;
+}
+DM_TEST(dm_test_first_child, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test integer functions in dm_read_...() */
+static int dm_test_read_int(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ u32 val32;
+ s32 sval;
+ uint val;
+
+ ut_assertok(uclass_first_device_err(UCLASS_TEST_FDT, &dev));
+ ut_asserteq_str("a-test", dev->name);
+ ut_assertok(dev_read_u32(dev, "int-value", &val32));
+ ut_asserteq(1234, val32);
+
+ ut_asserteq(-EINVAL, dev_read_u32(dev, "missing", &val32));
+ ut_asserteq(6, dev_read_u32_default(dev, "missing", 6));
+
+ ut_asserteq(1234, dev_read_u32_default(dev, "int-value", 6));
+ ut_asserteq(1234, val32);
+
+ ut_asserteq(-EINVAL, dev_read_s32(dev, "missing", &sval));
+ ut_asserteq(6, dev_read_s32_default(dev, "missing", 6));
+
+ ut_asserteq(-1234, dev_read_s32_default(dev, "uint-value", 6));
+ ut_assertok(dev_read_s32(dev, "uint-value", &sval));
+ ut_asserteq(-1234, sval);
+
+ val = 0;
+ ut_asserteq(-EINVAL, dev_read_u32u(dev, "missing", &val));
+ ut_assertok(dev_read_u32u(dev, "uint-value", &val));
+ ut_asserteq(-1234, val);
+
+ return 0;
+}
+DM_TEST(dm_test_read_int, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/test-main.c b/test/dm/test-main.c
new file mode 100644
index 00000000..72648162
--- /dev/null
+++ b/test/dm/test-main.c
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <command.h>
+#include <console.h>
+#include <dm.h>
+#include <errno.h>
+#include <malloc.h>
+#include <asm/state.h>
+#include <dm/test.h>
+#include <dm/root.h>
+#include <dm/uclass-internal.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+struct unit_test_state global_dm_test_state;
+static struct dm_test_state _global_priv_dm_test_state;
+
+/* Get ready for testing */
+static int dm_test_init(struct unit_test_state *uts, bool of_live)
+{
+ struct dm_test_state *dms = uts->priv;
+
+ memset(dms, '\0', sizeof(*dms));
+ gd->dm_root = NULL;
+ memset(dm_testdrv_op_count, '\0', sizeof(dm_testdrv_op_count));
+ state_reset_for_test(state_get_current());
+
+#ifdef CONFIG_OF_LIVE
+ /* Determine whether to make the live tree available */
+ gd->of_root = of_live ? uts->of_root : NULL;
+#endif
+ ut_assertok(dm_init(of_live));
+ dms->root = dm_root();
+
+ return 0;
+}
+
+/* Ensure all the test devices are probed */
+static int do_autoprobe(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ int ret;
+
+ /* Scanning the uclass is enough to probe all the devices */
+ for (ret = uclass_first_device(UCLASS_TEST, &dev);
+ dev;
+ ret = uclass_next_device(&dev))
+ ;
+
+ return ret;
+}
+
+static int dm_test_destroy(struct unit_test_state *uts)
+{
+ int id;
+
+ for (id = 0; id < UCLASS_COUNT; id++) {
+ struct uclass *uc;
+
+ /*
+ * If the uclass doesn't exist we don't want to create it. So
+ * check that here before we call uclass_find_device().
+ */
+ uc = uclass_find(id);
+ if (!uc)
+ continue;
+ ut_assertok(uclass_destroy(uc));
+ }
+
+ return 0;
+}
+
+static int dm_do_test(struct unit_test_state *uts, struct unit_test *test,
+ bool of_live)
+{
+ struct sandbox_state *state = state_get_current();
+ const char *fname = strrchr(test->file, '/') + 1;
+
+ printf("Test: %s: %s%s\n", test->name, fname,
+ !of_live ? " (flat tree)" : "");
+ ut_assertok(dm_test_init(uts, of_live));
+
+ uts->start = mallinfo();
+ if (test->flags & DM_TESTF_SCAN_PDATA)
+ ut_assertok(dm_scan_platdata(false));
+ if (test->flags & DM_TESTF_PROBE_TEST)
+ ut_assertok(do_autoprobe(uts));
+ if (test->flags & DM_TESTF_SCAN_FDT)
+ ut_assertok(dm_extended_scan_fdt(gd->fdt_blob, false));
+
+ /*
+ * Silence the console and rely on console recording to get
+ * our output.
+ */
+ console_record_reset();
+ if (!state->show_test_output)
+ gd->flags |= GD_FLG_SILENT;
+ test->func(uts);
+ gd->flags &= ~GD_FLG_SILENT;
+ state_set_skip_delays(false);
+
+ ut_assertok(dm_test_destroy(uts));
+
+ return 0;
+}
+
+/**
+ * dm_test_run_on_flattree() - Check if we should run a test with flat DT
+ *
+ * This skips long/slow tests where there is not much value in running a flat
+ * DT test in addition to a live DT test.
+ *
+ * @return true to run the given test on the flat device tree
+ */
+static bool dm_test_run_on_flattree(struct unit_test *test)
+{
+ const char *fname = strrchr(test->file, '/') + 1;
+
+ return !strstr(fname, "video") || strstr(test->name, "video_base");
+}
+
+static int dm_test_main(const char *test_name)
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test, dm_test);
+ const int n_ents = ll_entry_count(struct unit_test, dm_test);
+ struct unit_test_state *uts = &global_dm_test_state;
+ struct unit_test *test;
+ int found;
+
+ uts->priv = &_global_priv_dm_test_state;
+ uts->fail_count = 0;
+
+ /*
+ * If we have no device tree, or it only has a root node, then these
+ * tests clearly aren't going to work...
+ */
+ if (!gd->fdt_blob || fdt_next_node(gd->fdt_blob, 0, NULL) < 0) {
+ puts("Please run with test device tree:\n"
+ " ./u-boot -d arch/sandbox/dts/test.dtb\n");
+ ut_assert(gd->fdt_blob);
+ }
+
+ if (!test_name)
+ printf("Running %d driver model tests\n", n_ents);
+
+ found = 0;
+#ifdef CONFIG_OF_LIVE
+ uts->of_root = gd->of_root;
+#endif
+ for (test = tests; test < tests + n_ents; test++) {
+ const char *name = test->name;
+ int runs;
+
+ /* All tests have this prefix */
+ if (!strncmp(name, "dm_test_", 8))
+ name += 8;
+ if (test_name && strcmp(test_name, name))
+ continue;
+
+ /* Run with the live tree if possible */
+ runs = 0;
+ if (IS_ENABLED(CONFIG_OF_LIVE)) {
+ if (!(test->flags & DM_TESTF_FLAT_TREE)) {
+ ut_assertok(dm_do_test(uts, test, true));
+ runs++;
+ }
+ }
+
+ /*
+ * Run with the flat tree if we couldn't run it with live tree,
+ * or it is a core test.
+ */
+ if (!(test->flags & DM_TESTF_LIVE_TREE) &&
+ (!runs || dm_test_run_on_flattree(test))) {
+ ut_assertok(dm_do_test(uts, test, false));
+ runs++;
+ }
+ found++;
+ }
+
+ if (test_name && !found)
+ printf("Test '%s' not found\n", test_name);
+ else
+ printf("Failures: %d\n", uts->fail_count);
+
+ /* Put everything back to normal so that sandbox works as expected */
+#ifdef CONFIG_OF_LIVE
+ gd->of_root = uts->of_root;
+#endif
+ gd->dm_root = NULL;
+ ut_assertok(dm_init(IS_ENABLED(CONFIG_OF_LIVE)));
+ dm_scan_platdata(false);
+ dm_scan_fdt(gd->fdt_blob, false);
+
+ return uts->fail_count ? CMD_RET_FAILURE : 0;
+}
+
+int do_ut_dm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ const char *test_name = NULL;
+
+ if (argc > 1)
+ test_name = argv[1];
+
+ return dm_test_main(test_name);
+}
diff --git a/test/dm/test-uclass.c b/test/dm/test-uclass.c
new file mode 100644
index 00000000..25271c6b
--- /dev/null
+++ b/test/dm/test-uclass.c
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2013 Google, Inc
+ *
+ * (C) Copyright 2012
+ * Pavel Herrmann <morpheus.ibis@gmail.com>
+ */
+
+#include <common.h>
+#include <malloc.h>
+#include <dm.h>
+#include <errno.h>
+#include <asm/io.h>
+#include <dm/test.h>
+#include <linux/list.h>
+#include <test/ut.h>
+
+static struct unit_test_state *uts = &global_dm_test_state;
+
+int test_ping(struct udevice *dev, int pingval, int *pingret)
+{
+ const struct test_ops *ops = device_get_ops(dev);
+
+ if (!ops->ping)
+ return -ENOSYS;
+
+ return ops->ping(dev, pingval, pingret);
+}
+
+static int test_post_bind(struct udevice *dev)
+{
+ struct dm_test_perdev_uc_pdata *uc_pdata;
+
+ dm_testdrv_op_count[DM_TEST_OP_POST_BIND]++;
+ ut_assert(!device_active(dev));
+
+ uc_pdata = dev_get_uclass_platdata(dev);
+ ut_assert(uc_pdata);
+
+ uc_pdata->intval1 = TEST_UC_PDATA_INTVAL1;
+ uc_pdata->intval2 = TEST_UC_PDATA_INTVAL2;
+ uc_pdata->intval3 = TEST_UC_PDATA_INTVAL3;
+
+ return 0;
+}
+
+static int test_pre_unbind(struct udevice *dev)
+{
+ dm_testdrv_op_count[DM_TEST_OP_PRE_UNBIND]++;
+
+ return 0;
+}
+
+static int test_pre_probe(struct udevice *dev)
+{
+ struct dm_test_uclass_perdev_priv *priv = dev_get_uclass_priv(dev);
+
+ dm_testdrv_op_count[DM_TEST_OP_PRE_PROBE]++;
+ ut_assert(priv);
+ ut_assert(device_active(dev));
+
+ return 0;
+}
+
+static int test_post_probe(struct udevice *dev)
+{
+ struct udevice *prev = list_entry(dev->uclass_node.prev,
+ struct udevice, uclass_node);
+
+ struct dm_test_uclass_perdev_priv *priv = dev_get_uclass_priv(dev);
+ struct uclass *uc = dev->uclass;
+ struct dm_test_state *dms = uts->priv;
+
+ dm_testdrv_op_count[DM_TEST_OP_POST_PROBE]++;
+ ut_assert(priv);
+ ut_assert(device_active(dev));
+ priv->base_add = 0;
+ if (dms->skip_post_probe)
+ return 0;
+ if (&prev->uclass_node != &uc->dev_head) {
+ struct dm_test_uclass_perdev_priv *prev_uc_priv
+ = dev_get_uclass_priv(prev);
+ struct dm_test_pdata *pdata = prev->platdata;
+
+ ut_assert(pdata);
+ ut_assert(prev_uc_priv);
+ priv->base_add = prev_uc_priv->base_add + pdata->ping_add;
+ }
+
+ return 0;
+}
+
+static int test_pre_remove(struct udevice *dev)
+{
+ dm_testdrv_op_count[DM_TEST_OP_PRE_REMOVE]++;
+
+ return 0;
+}
+
+static int test_init(struct uclass *uc)
+{
+ dm_testdrv_op_count[DM_TEST_OP_INIT]++;
+ ut_assert(uc->priv);
+
+ return 0;
+}
+
+static int test_destroy(struct uclass *uc)
+{
+ dm_testdrv_op_count[DM_TEST_OP_DESTROY]++;
+
+ return 0;
+}
+
+UCLASS_DRIVER(test) = {
+ .name = "test",
+ .id = UCLASS_TEST,
+ .post_bind = test_post_bind,
+ .pre_unbind = test_pre_unbind,
+ .pre_probe = test_pre_probe,
+ .post_probe = test_post_probe,
+ .pre_remove = test_pre_remove,
+ .init = test_init,
+ .destroy = test_destroy,
+ .priv_auto_alloc_size = sizeof(struct dm_test_uclass_priv),
+ .per_device_auto_alloc_size = sizeof(struct dm_test_uclass_perdev_priv),
+ .per_device_platdata_auto_alloc_size =
+ sizeof(struct dm_test_perdev_uc_pdata),
+};
diff --git a/test/dm/timer.c b/test/dm/timer.c
new file mode 100644
index 00000000..9367dab5
--- /dev/null
+++ b/test/dm/timer.c
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Thomas Chou <thomas@wytron.com.tw>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <timer.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/*
+ * Basic test of the timer uclass.
+ */
+static int dm_test_timer_base(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_TIMER, 0, &dev));
+ ut_asserteq(1000000, timer_get_rate(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_timer_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/usb.c b/test/dm/usb.c
new file mode 100644
index 00000000..e396c2a0
--- /dev/null
+++ b/test/dm/usb.c
@@ -0,0 +1,414 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2015 Google, Inc
+ */
+
+#include <common.h>
+#include <console.h>
+#include <dm.h>
+#include <usb.h>
+#include <asm/io.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/device-internal.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <test/ut.h>
+
+struct keyboard_test_data {
+ const char modifiers;
+ const char scancode;
+ const char result[6];
+};
+
+/* Test that sandbox USB works correctly */
+static int dm_test_usb_base(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_USB, 0, &bus));
+ ut_assertok(uclass_get_device(UCLASS_USB, 0, &bus));
+ ut_asserteq(-ENODEV, uclass_get_device_by_seq(UCLASS_USB, 2, &bus));
+
+ return 0;
+}
+DM_TEST(dm_test_usb_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/*
+ * Test that we can use the flash stick. This is more of a functional test. It
+ * covers scanning the bug, setting up a hub and a flash stick and reading
+ * data from the flash stick.
+ */
+static int dm_test_usb_flash(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ struct blk_desc *dev_desc;
+ char cmp[1024];
+
+ state_set_skip_delays(true);
+ ut_assertok(usb_init());
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 0, &dev));
+ ut_assertok(blk_get_device_by_str("usb", "0", &dev_desc));
+
+ /* Read a few blocks and look for the string we expect */
+ ut_asserteq(512, dev_desc->blksz);
+ memset(cmp, '\0', sizeof(cmp));
+ ut_asserteq(2, blk_dread(dev_desc, 0, 2, cmp));
+ ut_assertok(strcmp(cmp, "this is a test"));
+ ut_assertok(usb_stop());
+
+ return 0;
+}
+DM_TEST(dm_test_usb_flash, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* test that we can handle multiple storage devices */
+static int dm_test_usb_multi(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ state_set_skip_delays(true);
+ ut_assertok(usb_init());
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 2, &dev));
+ ut_assertok(usb_stop());
+
+ return 0;
+}
+DM_TEST(dm_test_usb_multi, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int count_usb_devices(void)
+{
+ struct udevice *hub;
+ struct uclass *uc;
+ int count = 0;
+ int ret;
+
+ ret = uclass_get(UCLASS_USB_HUB, &uc);
+ if (ret)
+ return ret;
+
+ uclass_foreach_dev(hub, uc) {
+ struct udevice *dev;
+
+ count++;
+ for (device_find_first_child(hub, &dev);
+ dev;
+ device_find_next_child(&dev)) {
+ count++;
+ }
+ }
+
+ return count;
+}
+
+/* test that no USB devices are found after we stop the stack */
+static int dm_test_usb_stop(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+
+ /* Scan and check that all devices are present */
+ state_set_skip_delays(true);
+ ut_assertok(usb_init());
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 1, &dev));
+ ut_assertok(uclass_get_device(UCLASS_MASS_STORAGE, 2, &dev));
+ ut_asserteq(6, count_usb_devices());
+ ut_assertok(usb_stop());
+ ut_asserteq(0, count_usb_devices());
+
+ return 0;
+}
+DM_TEST(dm_test_usb_stop, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/**
+ * dm_test_usb_keyb() - test USB keyboard driver
+ *
+ * This test copies USB keyboard scan codes into the key buffer of the USB
+ * keyboard emulation driver. These are picked up during emulated interrupts
+ * by the USB keyboard driver and converted to characters and escape sequences.
+ * The test then reads and verifies these characters and escape sequences from
+ * the standard input.
+ *
+ * TODO: The following features are not yet tested:
+ *
+ * * LED status
+ * * caps-lock
+ * * num-lock
+ * * numerical pad keys
+ *
+ * TODO: The following features are not yet implemented by the USB keyboard
+ * driver and therefore not tested:
+ *
+ * * modifiers for non-alpha-numeric keys, e.g. <SHIFT><TAB> and <ALT><F4>
+ * * some special keys, e.g. <PRINT>
+ * * some modifiers, e.g. <ALT> and <META>
+ * * alternative keyboard layouts
+ *
+ * @uts: unit test state
+ * Return: 0 on success
+ */
+static int dm_test_usb_keyb(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ const struct keyboard_test_data *pos;
+ const struct keyboard_test_data kbd_test_data[] = {
+ /* <A> */
+ {0x00, 0x04, "a"},
+ /* <B> */
+ {0x00, 0x05, "b"},
+ /* <C> */
+ {0x00, 0x06, "c"},
+ /* <D> */
+ {0x00, 0x07, "d"},
+ /* <E> */
+ {0x00, 0x08, "e"},
+ /* <F> */
+ {0x00, 0x09, "f"},
+ /* <G> */
+ {0x00, 0x0a, "g"},
+ /* <H> */
+ {0x00, 0x0b, "h"},
+ /* <I> */
+ {0x00, 0x0c, "i"},
+ /* <J> */
+ {0x00, 0x0d, "j"},
+ /* <K> */
+ {0x00, 0x0e, "k"},
+ /* <L> */
+ {0x00, 0x0f, "l"},
+ /* <M> */
+ {0x00, 0x10, "m"},
+ /* <N> */
+ {0x00, 0x11, "n"},
+ /* <O> */
+ {0x00, 0x12, "o"},
+ /* <P> */
+ {0x00, 0x13, "p"},
+ /* <Q> */
+ {0x00, 0x14, "q"},
+ /* <R> */
+ {0x00, 0x15, "r"},
+ /* <S> */
+ {0x00, 0x16, "s"},
+ /* <T> */
+ {0x00, 0x17, "t"},
+ /* <U> */
+ {0x00, 0x18, "u"},
+ /* <V> */
+ {0x00, 0x19, "v"},
+ /* <W> */
+ {0x00, 0x1a, "w"},
+ /* <X> */
+ {0x00, 0x1b, "x"},
+ /* <Y> */
+ {0x00, 0x1c, "y"},
+ /* <Z> */
+ {0x00, 0x1d, "z"},
+
+ /* <LEFT-SHIFT><A> */
+ {0x02, 0x04, "A"},
+ /* <RIGHT-SHIFT><Z> */
+ {0x20, 0x1d, "Z"},
+
+ /* <LEFT-CONTROL><A> */
+ {0x01, 0x04, "\x01"},
+ /* <RIGHT-CONTROL><Z> */
+ {0x10, 0x1d, "\x1a"},
+
+ /* <1> */
+ {0x00, 0x1e, "1"},
+ /* <2> */
+ {0x00, 0x1f, "2"},
+ /* <3> */
+ {0x00, 0x20, "3"},
+ /* <4> */
+ {0x00, 0x21, "4"},
+ /* <5> */
+ {0x00, 0x22, "5"},
+ /* <6> */
+ {0x00, 0x23, "6"},
+ /* <7> */
+ {0x00, 0x24, "7"},
+ /* <8> */
+ {0x00, 0x25, "8"},
+ /* <9> */
+ {0x00, 0x26, "9"},
+ /* <0> */
+ {0x00, 0x27, "0"},
+
+ /* <LEFT-SHIFT><1> */
+ {0x02, 0x1e, "!"},
+ /* <RIGHT-SHIFT><2> */
+ {0x20, 0x1f, "@"},
+ /* <LEFT-SHIFT><3> */
+ {0x02, 0x20, "#"},
+ /* <RIGHT-SHIFT><4> */
+ {0x20, 0x21, "$"},
+ /* <LEFT-SHIFT><5> */
+ {0x02, 0x22, "%"},
+ /* <RIGHT-SHIFT><6> */
+ {0x20, 0x23, "^"},
+ /* <LEFT-SHIFT><7> */
+ {0x02, 0x24, "&"},
+ /* <RIGHT-SHIFT><8> */
+ {0x20, 0x25, "*"},
+ /* <LEFT-SHIFT><9> */
+ {0x02, 0x26, "("},
+ /* <RIGHT-SHIFT><0> */
+ {0x20, 0x27, ")"},
+
+ /* <ENTER> */
+ {0x00, 0x28, "\r"},
+ /* <ESCAPE> */
+ {0x00, 0x29, "\x1b"},
+ /* <BACKSPACE> */
+ {0x00, 0x2a, "\x08"},
+ /* <TAB> */
+ {0x00, 0x2b, "\x09"},
+ /* <SPACE> */
+ {0x00, 0x2c, " "},
+ /* <MINUS> */
+ {0x00, 0x2d, "-"},
+ /* <EQUAL> */
+ {0x00, 0x2e, "="},
+ /* <LEFT BRACE> */
+ {0x00, 0x2f, "["},
+ /* <RIGHT BRACE> */
+ {0x00, 0x30, "]"},
+ /* <BACKSLASH> */
+ {0x00, 0x31, "\\"},
+ /* <HASH-TILDE> */
+ {0x00, 0x32, "#"},
+ /* <SEMICOLON> */
+ {0x00, 0x33, ";"},
+ /* <APOSTROPHE> */
+ {0x00, 0x34, "'"},
+ /* <GRAVE> */
+ {0x00, 0x35, "`"},
+ /* <COMMA> */
+ {0x00, 0x36, ","},
+ /* <DOT> */
+ {0x00, 0x37, "."},
+ /* <SLASH> */
+ {0x00, 0x38, "/"},
+
+ /* <LEFT-SHIFT><ENTER> */
+ {0x02, 0x28, "\r"},
+ /* <RIGHT-SHIFT><ESCAPE> */
+ {0x20, 0x29, "\x1b"},
+ /* <LEFT-SHIFT><BACKSPACE> */
+ {0x02, 0x2a, "\x08"},
+ /* <RIGHT-SHIFT><TAB> */
+ {0x20, 0x2b, "\x09"},
+ /* <LEFT-SHIFT><SPACE> */
+ {0x02, 0x2c, " "},
+ /* <MINUS> */
+ {0x20, 0x2d, "_"},
+ /* <LEFT-SHIFT><EQUAL> */
+ {0x02, 0x2e, "+"},
+ /* <RIGHT-SHIFT><LEFT BRACE> */
+ {0x20, 0x2f, "{"},
+ /* <LEFT-SHIFT><RIGHT BRACE> */
+ {0x02, 0x30, "}"},
+ /* <RIGHT-SHIFT><BACKSLASH> */
+ {0x20, 0x31, "|"},
+ /* <LEFT-SHIFT><HASH-TILDE> */
+ {0x02, 0x32, "~"},
+ /* <RIGHT-SHIFT><SEMICOLON> */
+ {0x20, 0x33, ":"},
+ /* <LEFT-SHIFT><APOSTROPHE> */
+ {0x02, 0x34, "\""},
+ /* <RIGHT-SHIFT><GRAVE> */
+ {0x20, 0x35, "~"},
+ /* <LEFT-SHIFT><COMMA> */
+ {0x02, 0x36, "<"},
+ /* <RIGHT-SHIFT><DOT> */
+ {0x20, 0x37, ">"},
+ /* <LEFT-SHIFT><SLASH> */
+ {0x02, 0x38, "?"},
+#ifdef CONFIG_USB_KEYBOARD_FN_KEYS
+ /* <F1> */
+ {0x00, 0x3a, "\x1bOP"},
+ /* <F2> */
+ {0x00, 0x3b, "\x1bOQ"},
+ /* <F3> */
+ {0x00, 0x3c, "\x1bOR"},
+ /* <F4> */
+ {0x00, 0x3d, "\x1bOS"},
+ /* <F5> */
+ {0x00, 0x3e, "\x1b[15~"},
+ /* <F6> */
+ {0x00, 0x3f, "\x1b[17~"},
+ /* <F7> */
+ {0x00, 0x40, "\x1b[18~"},
+ /* <F8> */
+ {0x00, 0x41, "\x1b[19~"},
+ /* <F9> */
+ {0x00, 0x42, "\x1b[20~"},
+ /* <F10> */
+ {0x00, 0x43, "\x1b[21~"},
+ /* <F11> */
+ {0x00, 0x44, "\x1b[23~"},
+ /* <F12> */
+ {0x00, 0x45, "\x1b[24~"},
+ /* <INSERT> */
+ {0x00, 0x49, "\x1b[2~"},
+ /* <HOME> */
+ {0x00, 0x4a, "\x1b[H"},
+ /* <PAGE UP> */
+ {0x00, 0x4b, "\x1b[5~"},
+ /* <DELETE> */
+ {0x00, 0x4c, "\x1b[3~"},
+ /* <END> */
+ {0x00, 0x4d, "\x1b[F"},
+ /* <PAGE DOWN> */
+ {0x00, 0x4e, "\x1b[6~"},
+ /* <RIGHT> */
+ {0x00, 0x4f, "\x1b[C"},
+ /* <LEFT> */
+ {0x00, 0x50, "\x1b[D"},
+ /* <DOWN> */
+ {0x00, 0x51, "\x1b[B"},
+ /* <UP> */
+ {0x00, 0x52, "\x1b[A"},
+#endif /* CONFIG_USB_KEYBOARD_FN_KEYS */
+
+ /* End of list */
+ {0x00, 0x00, "\0"}
+ };
+
+
+ state_set_skip_delays(true);
+ ut_assertok(usb_init());
+
+ /* Initially there should be no characters */
+ ut_asserteq(0, tstc());
+
+ ut_assertok(uclass_get_device_by_name(UCLASS_USB_EMUL, "keyb@3",
+ &dev));
+
+ /*
+ * Add scan codes to the USB keyboard buffer. They should appear as
+ * corresponding characters and escape sequences in stdin.
+ */
+ for (pos = kbd_test_data; pos->scancode; ++pos) {
+ const char *c;
+ char scancodes[USB_KBD_BOOT_REPORT_SIZE] = {0};
+
+ scancodes[0] = pos->modifiers;
+ scancodes[2] = pos->scancode;
+
+ ut_assertok(sandbox_usb_keyb_add_string(dev, scancodes));
+
+ for (c = pos->result; *c; ++c) {
+ ut_asserteq(1, tstc());
+ ut_asserteq(*c, getc());
+ }
+ ut_asserteq(0, tstc());
+ }
+ ut_assertok(usb_stop());
+
+ return 0;
+}
+DM_TEST(dm_test_usb_keyb, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/video.c b/test/dm/video.c
new file mode 100644
index 00000000..3151ebb7
--- /dev/null
+++ b/test/dm/video.c
@@ -0,0 +1,376 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2014 Google, Inc
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <bzlib.h>
+#include <dm.h>
+#include <mapmem.h>
+#include <os.h>
+#include <video.h>
+#include <video_console.h>
+#include <dm/test.h>
+#include <dm/uclass-internal.h>
+#include <test/ut.h>
+
+/*
+ * These tests use the standard sandbox frame buffer, the resolution of which
+ * is defined in the device tree. This only supports 16bpp so the tests only
+ * test that code path. It would be possible to adjust this fairly easily,
+ * by adjusting the bpix value in struct sandbox_sdl_plat. However the code
+ * in sandbox_sdl_sync() would also need to change to handle the different
+ * surface depth.
+ */
+/* Basic test of the video uclass */
+static int dm_test_video_base(struct unit_test_state *uts)
+{
+ struct video_priv *priv;
+ struct udevice *dev;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_asserteq(1366, video_get_xsize(dev));
+ ut_asserteq(768, video_get_ysize(dev));
+ priv = dev_get_uclass_priv(dev);
+ ut_asserteq(priv->fb_size, 1366 * 768 * 2);
+
+ return 0;
+}
+DM_TEST(dm_test_video_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/**
+ * compress_frame_buffer() - Compress the frame buffer and return its size
+ *
+ * We want to write tests which perform operations on the video console and
+ * check that the frame buffer ends up with the correct contents. But it is
+ * painful to store 'known good' images for comparison with the frame
+ * buffer. As an alternative, we can compress the frame buffer and check the
+ * size of the compressed data. This provides a pretty good level of
+ * certainty and the resulting tests need only check a single value.
+ *
+ * @dev: Video device
+ * @return compressed size of the frame buffer, or -ve on error
+ */
+static int compress_frame_buffer(struct udevice *dev)
+{
+ struct video_priv *priv = dev_get_uclass_priv(dev);
+ uint destlen;
+ void *dest;
+ int ret;
+
+ destlen = priv->fb_size;
+ dest = malloc(priv->fb_size);
+ if (!dest)
+ return -ENOMEM;
+ ret = BZ2_bzBuffToBuffCompress(dest, &destlen,
+ priv->fb, priv->fb_size,
+ 3, 0, 0);
+ free(dest);
+ if (ret)
+ return ret;
+
+ return destlen;
+}
+
+/*
+ * Call this function at any point to halt and show the current display. Be
+ * sure to run the test with the -l flag.
+ */
+static void __maybe_unused see_output(void)
+{
+ video_sync_all();
+ while (1);
+}
+
+/* Select the video console driver to use for a video device */
+static int select_vidconsole(struct unit_test_state *uts, const char *drv_name)
+{
+ struct sandbox_sdl_plat *plat;
+ struct udevice *dev;
+
+ ut_assertok(uclass_find_device(UCLASS_VIDEO, 0, &dev));
+ ut_assert(!device_active(dev));
+ plat = dev_get_platdata(dev);
+ plat->vidconsole_drv_name = "vidconsole0";
+
+ return 0;
+}
+
+/* Test text output works on the video console */
+static int dm_test_video_text(struct unit_test_state *uts)
+{
+ struct udevice *dev, *con;
+ int i;
+
+#define WHITE 0xffff
+#define SCROLL_LINES 100
+
+ ut_assertok(select_vidconsole(uts, "vidconsole0"));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ vidconsole_putc_xy(con, 0, 0, 'a');
+ ut_asserteq(79, compress_frame_buffer(dev));
+
+ vidconsole_putc_xy(con, 0, 0, ' ');
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ for (i = 0; i < 20; i++)
+ vidconsole_putc_xy(con, VID_TO_POS(i * 8), 0, ' ' + i);
+ ut_asserteq(273, compress_frame_buffer(dev));
+
+ vidconsole_set_row(con, 0, WHITE);
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ for (i = 0; i < 20; i++)
+ vidconsole_putc_xy(con, VID_TO_POS(i * 8), 0, ' ' + i);
+ ut_asserteq(273, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_text, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test handling of special characters in the console */
+static int dm_test_video_chars(struct unit_test_state *uts)
+{
+ struct udevice *dev, *con;
+ const char *test_string = "Well\b\b\b\bxhe is\r \n\ta very \amodest \bman\n\t\tand Has much to\b\bto be modest about.";
+
+ ut_assertok(select_vidconsole(uts, "vidconsole0"));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ vidconsole_put_string(con, test_string);
+ ut_asserteq(466, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_chars, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+#ifdef CONFIG_VIDEO_ANSI
+#define ANSI_ESC "\x1b"
+/* Test handling of ANSI escape sequences */
+static int dm_test_video_ansi(struct unit_test_state *uts)
+{
+ struct udevice *dev, *con;
+
+ ut_assertok(select_vidconsole(uts, "vidconsole0"));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+
+ /* reference clear: */
+ video_clear(con->parent);
+ video_sync(con->parent, false);
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ /* test clear escape sequence: [2J */
+ vidconsole_put_string(con, "A\tB\tC"ANSI_ESC"[2J");
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ /* test set-cursor: [%d;%df */
+ vidconsole_put_string(con, "abc"ANSI_ESC"[2;2fab"ANSI_ESC"[4;4fcd");
+ ut_asserteq(143, compress_frame_buffer(dev));
+
+ /* test colors (30-37 fg color, 40-47 bg color) */
+ vidconsole_put_string(con, ANSI_ESC"[30;41mfoo"); /* black on red */
+ vidconsole_put_string(con, ANSI_ESC"[33;44mbar"); /* yellow on blue */
+ ut_asserteq(272, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_ansi, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+#endif
+
+/**
+ * check_vidconsole_output() - Run a text console test
+ *
+ * @uts: Test state
+ * @rot: Console rotation (0, 90, 180, 270)
+ * @wrap_size: Expected size of compressed frame buffer for the wrap test
+ * @scroll_size: Same for the scroll test
+ * @return 0 on success
+ */
+static int check_vidconsole_output(struct unit_test_state *uts, int rot,
+ int wrap_size, int scroll_size)
+{
+ struct udevice *dev, *con;
+ struct sandbox_sdl_plat *plat;
+ int i;
+
+ ut_assertok(uclass_find_device(UCLASS_VIDEO, 0, &dev));
+ ut_assert(!device_active(dev));
+ plat = dev_get_platdata(dev);
+ plat->rot = rot;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ /* Check display wrap */
+ for (i = 0; i < 120; i++)
+ vidconsole_put_char(con, 'A' + i % 50);
+ ut_asserteq(wrap_size, compress_frame_buffer(dev));
+
+ /* Check display scrolling */
+ for (i = 0; i < SCROLL_LINES; i++) {
+ vidconsole_put_char(con, 'A' + i % 50);
+ vidconsole_put_char(con, '\n');
+ }
+ ut_asserteq(scroll_size, compress_frame_buffer(dev));
+
+ /* If we scroll enough, the screen becomes blank again */
+ for (i = 0; i < SCROLL_LINES; i++)
+ vidconsole_put_char(con, '\n');
+ ut_asserteq(46, compress_frame_buffer(dev));
+
+ return 0;
+}
+
+/* Test text output through the console uclass */
+static int dm_test_video_context(struct unit_test_state *uts)
+{
+ ut_assertok(select_vidconsole(uts, "vidconsole0"));
+ ut_assertok(check_vidconsole_output(uts, 0, 788, 453));
+
+ return 0;
+}
+DM_TEST(dm_test_video_context, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test rotated text output through the console uclass */
+static int dm_test_video_rotation1(struct unit_test_state *uts)
+{
+ ut_assertok(check_vidconsole_output(uts, 1, 1112, 680));
+
+ return 0;
+}
+DM_TEST(dm_test_video_rotation1, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test rotated text output through the console uclass */
+static int dm_test_video_rotation2(struct unit_test_state *uts)
+{
+ ut_assertok(check_vidconsole_output(uts, 2, 785, 446));
+
+ return 0;
+}
+DM_TEST(dm_test_video_rotation2, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test rotated text output through the console uclass */
+static int dm_test_video_rotation3(struct unit_test_state *uts)
+{
+ ut_assertok(check_vidconsole_output(uts, 3, 1134, 681));
+
+ return 0;
+}
+DM_TEST(dm_test_video_rotation3, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Read a file into memory and return a pointer to it */
+static int read_file(struct unit_test_state *uts, const char *fname,
+ ulong *addrp)
+{
+ int buf_size = 100000;
+ ulong addr = 0;
+ int size, fd;
+ char *buf;
+
+ buf = map_sysmem(addr, 0);
+ ut_assert(buf != NULL);
+ fd = os_open(fname, OS_O_RDONLY);
+ ut_assert(fd >= 0);
+ size = os_read(fd, buf, buf_size);
+ os_close(fd);
+ ut_assert(size >= 0);
+ ut_assert(size < buf_size);
+ *addrp = addr;
+
+ return 0;
+}
+
+/* Test drawing a bitmap file */
+static int dm_test_video_bmp(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ ulong addr;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(read_file(uts, "tools/logos/denx.bmp", &addr));
+
+ ut_assertok(video_bmp_display(dev, addr, 0, 0, false));
+ ut_asserteq(1368, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_bmp, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test drawing a compressed bitmap file */
+static int dm_test_video_bmp_comp(struct unit_test_state *uts)
+{
+ struct udevice *dev;
+ ulong addr;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(read_file(uts, "tools/logos/denx-comp.bmp", &addr));
+
+ ut_assertok(video_bmp_display(dev, addr, 0, 0, false));
+ ut_asserteq(1368, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_bmp_comp, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test TrueType console */
+static int dm_test_video_truetype(struct unit_test_state *uts)
+{
+ struct udevice *dev, *con;
+ const char *test_string = "Criticism may not be agreeable, but it is necessary. It fulfils the same function as pain in the human body. It calls attention to an unhealthy state of things. Some see private enterprise as a predatory target to be shot, others as a cow to be milked, but few are those who see it as a sturdy horse pulling the wagon. The \aprice OF\b\bof greatness\n\tis responsibility.\n\nBye";
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ vidconsole_put_string(con, test_string);
+ ut_asserteq(12237, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_truetype, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test scrolling TrueType console */
+static int dm_test_video_truetype_scroll(struct unit_test_state *uts)
+{
+ struct sandbox_sdl_plat *plat;
+ struct udevice *dev, *con;
+ const char *test_string = "Criticism may not be agreeable, but it is necessary. It fulfils the same function as pain in the human body. It calls attention to an unhealthy state of things. Some see private enterprise as a predatory target to be shot, others as a cow to be milked, but few are those who see it as a sturdy horse pulling the wagon. The \aprice OF\b\bof greatness\n\tis responsibility.\n\nBye";
+
+ ut_assertok(uclass_find_device(UCLASS_VIDEO, 0, &dev));
+ ut_assert(!device_active(dev));
+ plat = dev_get_platdata(dev);
+ plat->font_size = 100;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ vidconsole_put_string(con, test_string);
+ ut_asserteq(35030, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_truetype_scroll, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test TrueType backspace, within and across lines */
+static int dm_test_video_truetype_bs(struct unit_test_state *uts)
+{
+ struct sandbox_sdl_plat *plat;
+ struct udevice *dev, *con;
+ const char *test_string = "...Criticism may or may\b\b\b\b\b\bnot be agreeable, but seldom it is necessary\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bit is necessary. It fulfils the same function as pain in the human body. It calls attention to an unhealthy state of things.";
+
+ ut_assertok(uclass_find_device(UCLASS_VIDEO, 0, &dev));
+ ut_assert(!device_active(dev));
+ plat = dev_get_platdata(dev);
+ plat->font_size = 100;
+
+ ut_assertok(uclass_get_device(UCLASS_VIDEO, 0, &dev));
+ ut_assertok(uclass_get_device(UCLASS_VIDEO_CONSOLE, 0, &con));
+ vidconsole_put_string(con, test_string);
+ ut_asserteq(29018, compress_frame_buffer(dev));
+
+ return 0;
+}
+DM_TEST(dm_test_video_truetype_bs, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/virtio.c b/test/dm/virtio.c
new file mode 100644
index 00000000..4b317d2e
--- /dev/null
+++ b/test/dm/virtio.c
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2018, Bin Meng <bmeng.cn@gmail.com>
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <virtio_types.h>
+#include <virtio.h>
+#include <virtio_ring.h>
+#include <dm/device-internal.h>
+#include <dm/uclass-internal.h>
+#include <dm/root.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Basic test of the virtio uclass */
+static int dm_test_virtio_base(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ u8 status;
+
+ /* check probe success */
+ ut_assertok(uclass_first_device(UCLASS_VIRTIO, &bus));
+
+ /* check the child virtio-blk device is bound */
+ ut_assertok(device_find_first_child(bus, &dev));
+ ut_assertok(strcmp(dev->name, "virtio-blk#0"));
+
+ /* check driver status */
+ ut_assertok(virtio_get_status(dev, &status));
+ ut_asserteq(VIRTIO_CONFIG_S_ACKNOWLEDGE, status);
+
+ return 0;
+}
+DM_TEST(dm_test_virtio_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test all of the virtio uclass ops */
+static int dm_test_virtio_all_ops(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+ struct virtio_dev_priv *uc_priv;
+ uint offset = 0, len = 0, nvqs = 1;
+ void *buffer = NULL;
+ u8 status;
+ u32 counter;
+ u64 features;
+ struct virtqueue *vqs[2];
+
+ /* check probe success */
+ ut_assertok(uclass_first_device(UCLASS_VIRTIO, &bus));
+
+ /* check the child virtio-blk device is bound */
+ ut_assertok(device_find_first_child(bus, &dev));
+
+ /*
+ * fake the virtio device probe by filling in uc_priv->vdev
+ * which is used by virtio_find_vqs/virtio_del_vqs.
+ */
+ uc_priv = dev_get_uclass_priv(bus);
+ uc_priv->vdev = dev;
+
+ /* test virtio_xxx APIs */
+ ut_assertok(virtio_get_config(dev, offset, buffer, len));
+ ut_assertok(virtio_set_config(dev, offset, buffer, len));
+ ut_asserteq(-ENOSYS, virtio_generation(dev, &counter));
+ ut_assertok(virtio_set_status(dev, VIRTIO_CONFIG_S_DRIVER_OK));
+ ut_assertok(virtio_get_status(dev, &status));
+ ut_asserteq(VIRTIO_CONFIG_S_DRIVER_OK, status);
+ ut_assertok(virtio_reset(dev));
+ ut_assertok(virtio_get_status(dev, &status));
+ ut_asserteq(0, status);
+ ut_assertok(virtio_get_features(dev, &features));
+ ut_asserteq(VIRTIO_F_VERSION_1, features);
+ ut_assertok(virtio_set_features(dev));
+ ut_assertok(virtio_find_vqs(dev, nvqs, vqs));
+ ut_assertok(virtio_del_vqs(dev));
+ ut_assertok(virtio_notify(dev, vqs[0]));
+
+ return 0;
+}
+DM_TEST(dm_test_virtio_all_ops, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test of the virtio driver that does not have required driver ops */
+static int dm_test_virtio_missing_ops(struct unit_test_state *uts)
+{
+ struct udevice *bus;
+
+ /* find the virtio device */
+ ut_assertok(uclass_find_device(UCLASS_VIRTIO, 1, &bus));
+
+ /*
+ * Probe the device should fail with error -ENOENT.
+ * See ops check in virtio_uclass_pre_probe().
+ */
+ ut_asserteq(-ENOENT, device_probe(bus));
+
+ return 0;
+}
+DM_TEST(dm_test_virtio_missing_ops, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Test removal of virtio device driver */
+static int dm_test_virtio_remove(struct unit_test_state *uts)
+{
+ struct udevice *bus, *dev;
+
+ /* check probe success */
+ ut_assertok(uclass_first_device(UCLASS_VIRTIO, &bus));
+
+ /* check the child virtio-blk device is bound */
+ ut_assertok(device_find_first_child(bus, &dev));
+
+ /* set driver status to VIRTIO_CONFIG_S_DRIVER_OK */
+ ut_assertok(virtio_set_status(dev, VIRTIO_CONFIG_S_DRIVER_OK));
+
+ /* check the device can be successfully removed */
+ dev->flags |= DM_FLAG_ACTIVATED;
+ ut_assertok(device_remove(bus, DM_REMOVE_ACTIVE_ALL));
+
+ return 0;
+}
+DM_TEST(dm_test_virtio_remove, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/dm/wdt.c b/test/dm/wdt.c
new file mode 100644
index 00000000..1d31ec55
--- /dev/null
+++ b/test/dm/wdt.c
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2017 Google, Inc
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <wdt.h>
+#include <asm/state.h>
+#include <asm/test.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+/* Test that watchdog driver functions are called */
+static int dm_test_wdt_base(struct unit_test_state *uts)
+{
+ struct sandbox_state *state = state_get_current();
+ struct udevice *dev;
+ const u64 timeout = 42;
+
+ ut_assertok(uclass_get_device(UCLASS_WDT, 0, &dev));
+ ut_assertnonnull(dev);
+ ut_asserteq(0, state->wdt.counter);
+ ut_asserteq(false, state->wdt.running);
+
+ ut_assertok(wdt_start(dev, timeout, 0));
+ ut_asserteq(timeout, state->wdt.counter);
+ ut_asserteq(true, state->wdt.running);
+
+ uint reset_count = state->wdt.reset_count;
+ ut_assertok(wdt_reset(dev));
+ ut_asserteq(reset_count + 1, state->wdt.reset_count);
+ ut_asserteq(true, state->wdt.running);
+
+ ut_assertok(wdt_stop(dev));
+ ut_asserteq(false, state->wdt.running);
+
+ return 0;
+}
+DM_TEST(dm_test_wdt_base, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/env/Kconfig b/test/env/Kconfig
new file mode 100644
index 00000000..6cb82337
--- /dev/null
+++ b/test/env/Kconfig
@@ -0,0 +1,9 @@
+config UT_ENV
+ bool "Enable env unit tests"
+ depends on UNIT_TEST
+ default y
+ help
+ This enables the 'ut env' command which runs a series of unit
+ tests on the env code.
+ If all is well then all tests pass although there will be a few
+ messages printed along the way.
diff --git a/test/env/Makefile b/test/env/Makefile
new file mode 100644
index 00000000..5c8eae31
--- /dev/null
+++ b/test/env/Makefile
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright (c) 2015 National Instruments, Inc
+
+obj-y += cmd_ut_env.o
+obj-y += attr.o
+obj-y += hashtable.o
diff --git a/test/env/attr.c b/test/env/attr.c
new file mode 100644
index 00000000..8d5c0f1c
--- /dev/null
+++ b/test/env/attr.c
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * (C) Copyright 2015
+ * Joe Hershberger, National Instruments, joe.hershberger@ni.com
+ */
+
+#include <common.h>
+#include <command.h>
+#include <env_attr.h>
+#include <test/env.h>
+#include <test/ut.h>
+
+static int env_test_attrs_lookup(struct unit_test_state *uts)
+{
+ char attrs[32];
+
+ ut_assertok(env_attr_lookup("foo:bar", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(",foo:bar", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(",foo:bar,", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(" foo:bar", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup("foo : bar", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(" foo: bar ", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup("foo:bar ", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(",foo:bar,goo:baz", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_asserteq(-ENOENT, env_attr_lookup(",,", "foo", attrs));
+
+ ut_asserteq(-ENOENT, env_attr_lookup("goo:baz", "foo", attrs));
+
+ ut_assertok(env_attr_lookup("foo:bar,foo:bat,foo:baz", "foo", attrs));
+ ut_asserteq_str("baz", attrs);
+
+ ut_assertok(env_attr_lookup(
+ " foo : bar , foo : bat , foot : baz ", "foo", attrs));
+ ut_asserteq_str("bat", attrs);
+
+ ut_assertok(env_attr_lookup(
+ " foo : bar , foo : bat , ufoo : baz ", "foo", attrs));
+ ut_asserteq_str("bat", attrs);
+
+ ut_asserteq(-EINVAL, env_attr_lookup(NULL, "foo", attrs));
+ ut_asserteq(-EINVAL, env_attr_lookup("foo:bar", "foo", NULL));
+
+ return 0;
+}
+ENV_TEST(env_test_attrs_lookup, 0);
+
+#ifdef CONFIG_REGEX
+static int env_test_attrs_lookup_regex(struct unit_test_state *uts)
+{
+ char attrs[32];
+
+ ut_assertok(env_attr_lookup("foo1?:bar", "foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup("foo1?:bar", "foo1", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(".foo:bar", ".foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup(".foo:bar", "ufoo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_assertok(env_attr_lookup("\\.foo:bar", ".foo", attrs));
+ ut_asserteq_str("bar", attrs);
+
+ ut_asserteq(-ENOENT, env_attr_lookup("\\.foo:bar", "ufoo", attrs));
+
+ return 0;
+}
+ENV_TEST(env_test_attrs_lookup_regex, 0);
+#endif
diff --git a/test/env/cmd_ut_env.c b/test/env/cmd_ut_env.c
new file mode 100644
index 00000000..54041a02
--- /dev/null
+++ b/test/env/cmd_ut_env.c
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * (C) Copyright 2015
+ * Joe Hershberger, National Instruments, joe.hershberger@ni.com
+ */
+
+#include <common.h>
+#include <command.h>
+#include <test/env.h>
+#include <test/suites.h>
+#include <test/ut.h>
+
+int do_ut_env(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test, env_test);
+ const int n_ents = ll_entry_count(struct unit_test, env_test);
+
+ return cmd_ut_category("environment", tests, n_ents, argc, argv);
+}
diff --git a/test/env/hashtable.c b/test/env/hashtable.c
new file mode 100644
index 00000000..5242c4cc
--- /dev/null
+++ b/test/env/hashtable.c
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * (C) Copyright 2019
+ * Roman Kapl, SYSGO, rka@sysgo.com
+ */
+
+#include <common.h>
+#include <command.h>
+#include <search.h>
+#include <stdio.h>
+#include <test/env.h>
+#include <test/ut.h>
+
+#define SIZE 32
+#define ITERATIONS 10000
+
+static int htab_fill(struct unit_test_state *uts,
+ struct hsearch_data *htab, size_t size)
+{
+ size_t i;
+ struct env_entry item;
+ struct env_entry *ritem;
+ char key[20];
+
+ for (i = 0; i < size; i++) {
+ sprintf(key, "%d", (int)i);
+ item.callback = NULL;
+ item.data = key;
+ item.flags = 0;
+ item.key = key;
+ ut_asserteq(1, hsearch_r(item, ENV_ENTER, &ritem, htab, 0));
+ }
+
+ return 0;
+}
+
+static int htab_check_fill(struct unit_test_state *uts,
+ struct hsearch_data *htab, size_t size)
+{
+ size_t i;
+ struct env_entry item;
+ struct env_entry *ritem;
+ char key[20];
+
+ for (i = 0; i < size; i++) {
+ sprintf(key, "%d", (int)i);
+ item.callback = NULL;
+ item.flags = 0;
+ item.data = key;
+ item.key = key;
+ hsearch_r(item, ENV_FIND, &ritem, htab, 0);
+ ut_assert(ritem);
+ ut_asserteq_str(key, ritem->key);
+ ut_asserteq_str(key, ritem->data);
+ }
+
+ return 0;
+}
+
+static int htab_create_delete(struct unit_test_state *uts,
+ struct hsearch_data *htab, size_t iterations)
+{
+ size_t i;
+ struct env_entry item;
+ struct env_entry *ritem;
+ char key[20];
+
+ for (i = 0; i < iterations; i++) {
+ sprintf(key, "cd-%d", (int)i);
+ item.callback = NULL;
+ item.flags = 0;
+ item.data = key;
+ item.key = key;
+ hsearch_r(item, ENV_ENTER, &ritem, htab, 0);
+ ritem = NULL;
+
+ hsearch_r(item, ENV_FIND, &ritem, htab, 0);
+ ut_assert(ritem);
+ ut_asserteq_str(key, ritem->key);
+ ut_asserteq_str(key, ritem->data);
+
+ ut_asserteq(1, hdelete_r(key, htab, 0));
+ }
+
+ return 0;
+}
+
+/* Completely fill up the hash table */
+static int env_test_htab_fill(struct unit_test_state *uts)
+{
+ struct hsearch_data htab;
+
+ memset(&htab, 0, sizeof(htab));
+ ut_asserteq(1, hcreate_r(SIZE, &htab));
+
+ ut_assertok(htab_fill(uts, &htab, SIZE));
+ ut_assertok(htab_check_fill(uts, &htab, SIZE));
+ ut_asserteq(SIZE, htab.filled);
+
+ hdestroy_r(&htab);
+ return 0;
+}
+
+ENV_TEST(env_test_htab_fill, 0);
+
+/* Fill the hashtable up halfway an repeateadly delete/create elements
+ * and check for corruption
+ */
+static int env_test_htab_deletes(struct unit_test_state *uts)
+{
+ struct hsearch_data htab;
+
+ memset(&htab, 0, sizeof(htab));
+ ut_asserteq(1, hcreate_r(SIZE, &htab));
+
+ ut_assertok(htab_fill(uts, &htab, SIZE / 2));
+ ut_assertok(htab_create_delete(uts, &htab, ITERATIONS));
+ ut_assertok(htab_check_fill(uts, &htab, SIZE / 2));
+ ut_asserteq(SIZE / 2, htab.filled);
+
+ hdestroy_r(&htab);
+ return 0;
+}
+
+ENV_TEST(env_test_htab_deletes, 0);
diff --git a/test/fs/fat-noncontig-test.sh b/test/fs/fat-noncontig-test.sh
new file mode 100755
index 00000000..b02dae76
--- /dev/null
+++ b/test/fs/fat-noncontig-test.sh
@@ -0,0 +1,144 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0+
+
+# (C) Copyright 2015 Stephen Warren
+
+# This script tests U-Boot's FAT filesystem code's ability to read non-
+# contiguous files.
+
+# When porting the ff.c FAT parsing code into U-Boot, it was found that ff.c
+# always reads files cluster-by-cluster, which results in poor performance.
+# This was solved by adding a patch to ff.c to coalesce reads of adjacent
+# clusters. Since this patch needed to correctly handle non-contiguous files,
+# this test was written to validate that.
+#
+# To execute the test, simply run it from the U-Boot source root directory:
+#
+# cd u-boot
+# ./test/fs/fat-noncontig-test.sh
+#
+# The test will create a FAT filesystem image, record the CRC of a randomly
+# generated file in the image, build U-Boot sandbox, invoke U-Boot sandbox to
+# read the file and validate that the CRCs match. Expected output is shown
+# below. The important part of the log is the penultimate line that contains
+# either "PASS" or "FAILURE".
+#
+# mkfs.fat 3.0.26 (2014-03-07)
+#
+#
+# U-Boot 2015.10-rc4-00018-g4b22a3e5513f (Oct 03 2015 - 13:49:23 -0600)
+#
+# DRAM: 128 MiB
+# Using default environment
+#
+# In: serial
+# Out: lcd
+# Err: lcd
+# Net: No ethernet found.
+# => host bind 0 sandbox/fat-noncontig.img
+# => load host 0:0 1000 noncontig.img
+# 33584964 bytes read in 18 ms (1.7 GiB/s)
+# => crc32 1000 $filesize 0
+# crc32 for 00001000 ... 02008743 ==> 6a080523
+# => if itest.l *0 != 2305086a; then echo FAILURE; else echo PASS; fi
+# PASS
+# => reset
+#
+# All temporary files used by this script are created in ./sandbox to avoid
+# polluting the source tree. test/fs/fs-test.sh also uses this directory for
+# the same purpose.
+#
+# TODO: Integrate this (and many other corner-cases e.g. different types of
+# FAT) with fs-test.sh so that a single script tests everything filesystem-
+# related.
+
+odir=sandbox
+img=${odir}/fat-noncontig.img
+mnt=${odir}/mnt
+fill=/dev/urandom
+testfn=noncontig.img
+mnttestfn=${mnt}/${testfn}
+crcaddr=0
+loadaddr=1000
+
+for prereq in fallocate mkfs.fat dd crc32; do
+ if [ ! -x "`which $prereq`" ]; then
+ echo "Missing $prereq binary. Exiting!"
+ exit 1
+ fi
+done
+
+make O=${odir} -s sandbox_defconfig && make O=${odir} -s -j8
+
+mkdir -p ${mnt}
+if [ ! -f ${img} ]; then
+ fallocate -l 40M ${img}
+ if [ $? -ne 0 ]; then
+ echo fallocate failed - using dd instead
+ dd if=/dev/zero of=${img} bs=1024 count=$((40 * 1024))
+ if [ $? -ne 0 ]; then
+ echo Could not create empty disk image
+ exit $?
+ fi
+ fi
+ mkfs.fat ${img}
+ if [ $? -ne 0 ]; then
+ echo Could not create FAT filesystem
+ exit $?
+ fi
+
+ sudo mount -o loop,uid=$(id -u) ${img} ${mnt}
+ if [ $? -ne 0 ]; then
+ echo Could not mount test filesystem
+ exit $?
+ fi
+
+ for ((sects=8; sects < 512; sects += 8)); do
+ fn=${mnt}/keep-${sects}.img
+ dd if=${fill} of=${fn} bs=512 count=${sects} >/dev/null 2>&1
+ fn=${mnt}/remove-${sects}.img
+ dd if=${fill} of=${fn} bs=512 count=${sects} >/dev/null 2>&1
+ done
+
+ rm -f ${mnt}/remove-*.img
+
+ # 511 deliberately to trigger a file size that's not a multiple of the
+ # sector size (ignoring sizes that are multiples of both).
+ dd if=${fill} of=${mnttestfn} bs=511 >/dev/null 2>&1
+
+ sudo umount ${mnt}
+ if [ $? -ne 0 ]; then
+ echo Could not unmount test filesystem
+ exit $?
+ fi
+fi
+
+sudo mount -o ro,loop,uid=$(id -u) ${img} ${mnt}
+if [ $? -ne 0 ]; then
+ echo Could not mount test filesystem
+ exit $?
+fi
+crc=0x`crc32 ${mnttestfn}`
+sudo umount ${mnt}
+if [ $? -ne 0 ]; then
+ echo Could not unmount test filesystem
+ exit $?
+fi
+
+crc=`printf %02x%02x%02x%02x \
+ $((${crc} & 0xff)) \
+ $(((${crc} >> 8) & 0xff)) \
+ $(((${crc} >> 16) & 0xff)) \
+ $((${crc} >> 24))`
+
+./sandbox/u-boot << EOF
+host bind 0 ${img}
+load host 0:0 ${loadaddr} ${testfn}
+crc32 ${loadaddr} \$filesize ${crcaddr}
+if itest.l *${crcaddr} != ${crc}; then echo FAILURE; else echo PASS; fi
+reset
+EOF
+if [ $? -ne 0 ]; then
+ echo U-Boot exit status indicates an error
+ exit $?
+fi
diff --git a/test/fs/fs-test.sh b/test/fs/fs-test.sh
new file mode 100755
index 00000000..721af71d
--- /dev/null
+++ b/test/fs/fs-test.sh
@@ -0,0 +1,627 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0+
+#
+# (C) Copyright 2014 Suriyan Ramasami
+
+# Invoke this test script from U-Boot base directory as ./test/fs/fs-test.sh
+# It currently tests the fs/sb and native commands for ext4 and fat partitions
+# Expected results are as follows:
+# EXT4 tests:
+# fs-test.sb.ext4 Summary: PASS: 24 FAIL: 0
+# fs-test.nonfs.ext4 Summary: PASS: 24 FAIL: 0
+# fs-test.fs.ext4 Summary: PASS: 24 FAIL: 0
+# FAT16 tests:
+# fs-test.sb.fat16 Summary: PASS: 24 FAIL: 0
+# fs-test.nonfs.fat16 Summary: PASS: 24 FAIL: 0
+# fs-test.fs.fat16 Summary: PASS: 24 FAIL: 0
+# FAT32 tests:
+# fs-test.sb.fat32 Summary: PASS: 24 FAIL: 0
+# fs-test.nonfs.fat32 Summary: PASS: 24 FAIL: 0
+# fs-test.fs.fat32 Summary: PASS: 24 FAIL: 0
+# --------------------------------------------
+# Total Summary: TOTAL PASS: 216 TOTAL FAIL: 0
+# --------------------------------------------
+
+# pre-requisite binaries list.
+PREREQ_BINS="md5sum mkfs mount umount dd fallocate mkdir"
+
+# All generated output files from this test will be in $OUT_DIR
+# Hence everything is sandboxed.
+OUT_DIR="sandbox/test/fs"
+
+# Location of generated sandbox u-boot
+UBOOT="./sandbox/u-boot"
+
+# Our mount directory will be in the sandbox
+MOUNT_DIR="${OUT_DIR}/mnt"
+
+# The file system image we create will have the $IMG prefix.
+IMG="${OUT_DIR}/3GB"
+
+# $SMALL_FILE is the name of the 1MB file in the file system image
+SMALL_FILE="1MB.file"
+
+# $BIG_FILE is the name of the 2.5GB file in the file system image
+BIG_FILE="2.5GB.file"
+
+# $MD5_FILE will have the expected md5s when we do the test
+# They shall have a suffix which represents their file system (ext4/fat16/...)
+MD5_FILE="${OUT_DIR}/md5s.list"
+
+# $OUT shall be the prefix of the test output. Their suffix will be .out
+OUT="${OUT_DIR}/fs-test"
+
+# Full Path of the 1 MB file that shall be created in the fs image.
+MB1="${MOUNT_DIR}/${SMALL_FILE}"
+GB2p5="${MOUNT_DIR}/${BIG_FILE}"
+
+# ************************
+# * Functions start here *
+# ************************
+
+# Check if the prereq binaries exist, or exit
+function check_prereq() {
+ for prereq in $PREREQ_BINS; do
+ if [ ! -x "`which $prereq`" ]; then
+ echo "Missing $prereq binary. Exiting!"
+ exit
+ fi
+ done
+
+ # We use /dev/urandom to create files. Check if it exists.
+ if [ ! -c /dev/urandom ]; then
+ echo "Missing character special /dev/urandom. Exiting!"
+ exit
+ fi
+}
+
+# If 1st param is "clean", then clean out the generated files and exit
+function check_clean() {
+ if [ "$1" = "clean" ]; then
+ rm -rf "$OUT_DIR"
+ echo "Cleaned up generated files. Exiting"
+ exit
+ fi
+}
+
+# Generate sandbox U-Boot - gleaned from /test/dm/test-dm.sh
+function compile_sandbox() {
+ unset CROSS_COMPILE
+ NUM_CPUS=$(cat /proc/cpuinfo |grep -c processor)
+ make O=sandbox sandbox_config
+ make O=sandbox -s -j${NUM_CPUS}
+
+ # Check if U-Boot exists
+ if [ ! -x "$UBOOT" ]; then
+ echo "$UBOOT does not exist or is not executable"
+ echo "Build error?"
+ echo "Please run this script as ./test/fs/`basename $0`"
+ exit
+ fi
+}
+
+# Clean out all generated files other than the file system images
+# We save time by not deleting and recreating the file system images
+function prepare_env() {
+ rm -f ${MD5_FILE}.* ${OUT}.*
+ mkdir -p ${OUT_DIR}
+}
+
+# 1st parameter is the name of the image file to be created
+# 2nd parameter is the filesystem - fat16 ext4 etc
+# -F cant be used with fat as it means something else.
+function create_image() {
+ # Create image if not already present - saves time, while debugging
+ case "$2" in
+ fat16)
+ MKFS_OPTION="-F 16"
+ FS_TYPE="fat"
+ ;;
+ fat32)
+ MKFS_OPTION="-F 32"
+ FS_TYPE="fat"
+ ;;
+ ext4)
+ MKFS_OPTION="-F"
+ FS_TYPE="ext4"
+ ;;
+ esac
+
+ if [ ! -f "$1" ]; then
+ fallocate -l 3G "$1" &> /dev/null
+ if [ $? -ne 0 ]; then
+ echo fallocate failed - using dd instead
+ dd if=/dev/zero of=$1 bs=1024 count=$((3 * 1024 * 1024))
+ if [ $? -ne 0 ]; then
+ echo Could not create empty disk image
+ exit $?
+ fi
+ fi
+ mkfs -t "$FS_TYPE" $MKFS_OPTION "$1" &> /dev/null
+ if [ $? -ne 0 -a "$FS_TYPE" = "fat" ]; then
+ # If we fail and we did fat, try vfat.
+ mkfs -t vfat $MKFS_OPTION "$1" &> /dev/null
+ fi
+ if [ $? -ne 0 ]; then
+ echo Could not create filesystem
+ exit $?
+ fi
+ fi
+}
+
+# 1st parameter is image file
+# 2nd parameter is file system type - fat16/ext4/...
+# 3rd parameter is name of small file
+# 4th parameter is name of big file
+# 5th parameter is fs/nonfs/sb - to dictate generic fs commands or
+# otherwise or sb hostfs
+# 6th parameter is the directory path for the files. Its "" for generic
+# fs and ext4/fat and full patch for sb hostfs
+# UBOOT is set in env
+function test_image() {
+ addr="0x01000008"
+ length="0x00100000"
+
+ case "$2" in
+ fat*)
+ FPATH=""
+ PREFIX="fat"
+ WRITE="write"
+ ;;
+
+ ext4)
+ # ext4 needs absolute path
+ FPATH="/"
+ PREFIX="ext4"
+ WRITE="write"
+ ;;
+
+ *)
+ echo "Unhandled filesystem $2. Exiting!"
+ exit
+ ;;
+ esac
+
+ case "$5" in
+ fs)
+ PREFIX=""
+ WRITE="save"
+ SUFFIX=" 0:0"
+ ;;
+
+ nonfs)
+ SUFFIX=" 0:0"
+ ;;
+
+ sb)
+ PREFIX="host "
+ WRITE="save"
+ SUFFIX="fs -"
+ ;;
+
+ *)
+ echo "Unhandled mode $5. Exiting!"
+ exit
+ ;;
+
+ esac
+
+ # sb always uses full path to mointpoint, irrespective of filesystem
+ if [ "$5" = "sb" ]; then
+ FPATH=${6}/
+ fi
+
+ FILE_WRITE=${3}.w
+ FILE_SMALL=$3
+ FILE_BIG=$4
+
+ # In u-boot commands, <interface> stands for host or hostfs
+ # hostfs maps to the host fs.
+ # host maps to the "host bind" that we do
+
+ $UBOOT << EOF
+sb=$5
+setenv bind 'if test "\$sb" != sb; then host bind 0 "$1"; fi'
+run bind
+# Test Case 1 - ls
+${PREFIX}ls host${SUFFIX} $6
+# In addition, test with a nonexistent directory to see if we crash.
+${PREFIX}ls host${SUFFIX} invalid_d
+#
+# We want ${PREFIX}size host 0:0 $3 for host commands and
+# host size hostfs - $3 for hostfs commands.
+# 1MB is 0x0010 0000
+# Test Case 2a - size of small file
+${PREFIX}size host${SUFFIX} ${FPATH}$FILE_SMALL
+printenv filesize
+setenv filesize
+# Test Case 2b - size of small file via a path using '..'
+${PREFIX}size host${SUFFIX} ${FPATH}SUBDIR/../$FILE_SMALL
+printenv filesize
+setenv filesize
+
+# 2.5GB (1024*1024*2500) is 0x9C40 0000
+# Test Case 3 - size of big file
+${PREFIX}size host${SUFFIX} ${FPATH}$FILE_BIG
+printenv filesize
+setenv filesize
+
+# Notes about load operation
+# If I use 0x01000000 I get DMA misaligned error message
+# Last two parameters are size and offset.
+
+# Test Case 4a - Read full 1MB of small file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL
+printenv filesize
+# Test Case 4b - Read full 1MB of small file
+md5sum $addr \$filesize
+setenv filesize
+
+# Test Case 5a - First 1MB of big file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x0
+printenv filesize
+# Test Case 5b - First 1MB of big file
+md5sum $addr \$filesize
+setenv filesize
+
+# fails for ext as no offset support
+# Test Case 6a - Last 1MB of big file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x9C300000
+printenv filesize
+# Test Case 6b - Last 1MB of big file
+md5sum $addr \$filesize
+setenv filesize
+
+# fails for ext as no offset support
+# Test Case 7a - One from the last 1MB chunk of 2GB
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x7FF00000
+printenv filesize
+# Test Case 7b - One from the last 1MB chunk of 2GB
+md5sum $addr \$filesize
+setenv filesize
+
+# fails for ext as no offset support
+# Test Case 8a - One from the start 1MB chunk from 2GB
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x80000000
+printenv filesize
+# Test Case 8b - One from the start 1MB chunk from 2GB
+md5sum $addr \$filesize
+setenv filesize
+
+# fails for ext as no offset support
+# Test Case 9a - One 1MB chunk crossing the 2GB boundary
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x7FF80000
+printenv filesize
+# Test Case 9b - One 1MB chunk crossing the 2GB boundary
+md5sum $addr \$filesize
+setenv filesize
+
+# Generic failure case
+# Test Case 10 - 2MB chunk from the last 1MB of big file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG 0x00200000 0x9C300000
+printenv filesize
+#
+
+# Read 1MB from small file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL
+# Write it back to test the writes
+# Test Case 11a - Check that the write succeeded
+${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}$FILE_WRITE \$filesize
+mw.b $addr 00 100
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_WRITE
+# Test Case 11b - Check md5 of written to is same as the one read from
+md5sum $addr \$filesize
+setenv filesize
+#
+
+# Next test case checks writing a file whose dirent
+# is the first in the block, which is always true for "."
+# The write should fail, but the lookup should work
+# Test Case 12 - Check directory traversal
+${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}. 0x10
+
+# Read 1MB from small file
+${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL
+# Write it via "same directory", i.e. "." dirent
+# Test Case 13a - Check directory traversal
+${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}./${FILE_WRITE}2 \$filesize
+mw.b $addr 00 100
+${PREFIX}load host${SUFFIX} $addr ${FPATH}./${FILE_WRITE}2
+# Test Case 13b - Check md5 of written to is same as the one read from
+md5sum $addr \$filesize
+setenv filesize
+mw.b $addr 00 100
+${PREFIX}load host${SUFFIX} $addr ${FPATH}${FILE_WRITE}2
+# Test Case 13c - Check md5 of written to is same as the one read from
+md5sum $addr \$filesize
+setenv filesize
+#
+reset
+
+EOF
+}
+
+# 1st argument is the name of the image file.
+# 2nd argument is the file where we generate the md5s of the files
+# generated with the appropriate start and length that we use to test.
+# It creates the necessary files in the image to test.
+# $GB2p5 is the path of the big file (2.5 GB)
+# $MB1 is the path of the small file (1 MB)
+# $MOUNT_DIR is the path we can use to mount the image file.
+function create_files() {
+ # Mount the image so we can populate it.
+ mkdir -p "$MOUNT_DIR"
+ sudo mount -o loop,rw "$1" "$MOUNT_DIR"
+
+ # Create a subdirectory.
+ sudo mkdir -p "$MOUNT_DIR/SUBDIR"
+
+ # Create big file in this image.
+ # Note that we work only on the start 1MB, couple MBs in the 2GB range
+ # and the last 1 MB of the huge 2.5GB file.
+ # So, just put random values only in those areas.
+ if [ ! -f "${GB2p5}" ]; then
+ sudo dd if=/dev/urandom of="${GB2p5}" bs=1M count=1 \
+ &> /dev/null
+ sudo dd if=/dev/urandom of="${GB2p5}" bs=1M count=2 seek=2047 \
+ &> /dev/null
+ sudo dd if=/dev/urandom of="${GB2p5}" bs=1M count=1 seek=2499 \
+ &> /dev/null
+ fi
+
+ # Create a small file in this image.
+ if [ ! -f "${MB1}" ]; then
+ sudo dd if=/dev/urandom of="${MB1}" bs=1M count=1 \
+ &> /dev/null
+ fi
+
+ # Delete the small file copies which possibly are written as part of a
+ # previous test.
+ sudo rm -f "${MB1}.w"
+ sudo rm -f "${MB1}.w2"
+
+ # Generate the md5sums of reads that we will test against small file
+ dd if="${MB1}" bs=1M skip=0 count=1 2> /dev/null | md5sum > "$2"
+
+ # Generate the md5sums of reads that we will test against big file
+ # One from beginning of file.
+ dd if="${GB2p5}" bs=1M skip=0 count=1 \
+ 2> /dev/null | md5sum >> "$2"
+
+ # One from end of file.
+ dd if="${GB2p5}" bs=1M skip=2499 count=1 \
+ 2> /dev/null | md5sum >> "$2"
+
+ # One from the last 1MB chunk of 2GB
+ dd if="${GB2p5}" bs=1M skip=2047 count=1 \
+ 2> /dev/null | md5sum >> "$2"
+
+ # One from the start 1MB chunk from 2GB
+ dd if="${GB2p5}" bs=1M skip=2048 count=1 \
+ 2> /dev/null | md5sum >> "$2"
+
+ # One 1MB chunk crossing the 2GB boundary
+ dd if="${GB2p5}" bs=512K skip=4095 count=2 \
+ 2> /dev/null | md5sum >> "$2"
+
+ sync
+ sudo umount "$MOUNT_DIR"
+ rmdir "$MOUNT_DIR"
+}
+
+# 1st parameter is the text to print
+# if $? is 0 its a pass, else a fail
+# As a side effect it shall update env variable PASS and FAIL
+function pass_fail() {
+ if [ $? -eq 0 ]; then
+ echo pass - "$1"
+ PASS=$((PASS + 1))
+ else
+ echo FAIL - "$1"
+ FAIL=$((FAIL + 1))
+ fi
+}
+
+# 1st parameter is the string which leads to an md5 generation
+# 2nd parameter is the file we grep, for that string
+# 3rd parameter is the name of the file which has md5s in it
+# 4th parameter is the line # in the md5 file that we match it against
+# This function checks if the md5 of the file in the sandbox matches
+# that calculated while generating the file
+# 5th parameter is the string to print with the result
+check_md5() {
+ # md5sum in u-boot has output of form:
+ # md5 for 01000008 ... 01100007 ==> <md5>
+ # the 7th field is the actual md5
+ md5_src=`grep -A2 "$1" "$2" | grep "md5 for" | tr -d '\r'`
+ md5_src=($md5_src)
+ md5_src=${md5_src[6]}
+
+ # The md5 list, each line is of the form:
+ # - <md5>
+ # the 2nd field is the actual md5
+ md5_dst=`sed -n $4p $3`
+ md5_dst=($md5_dst)
+ md5_dst=${md5_dst[0]}
+
+ # For a pass they should match.
+ [ "$md5_src" = "$md5_dst" ]
+ pass_fail "$5"
+}
+
+# 1st parameter is the name of the output file to check
+# 2nd parameter is the name of the file containing the md5 expected
+# 3rd parameter is the name of the small file
+# 4th parameter is the name of the big file
+# 5th paramter is the name of the written file
+# This function checks the output file for correct results.
+function check_results() {
+ echo "** Start $1"
+
+ PASS=0
+ FAIL=0
+
+ # Check if the ls is showing correct results for 2.5 gb file
+ grep -A7 "Test Case 1 " "$1" | egrep -iq "2621440000 *$4"
+ pass_fail "TC1: ls of $4"
+
+ # Check if the ls is showing correct results for 1 mb file
+ grep -A7 "Test Case 1 " "$1" | egrep -iq "1048576 *$3"
+ pass_fail "TC1: ls of $3"
+
+ # Check size command on 1MB.file
+ egrep -A3 "Test Case 2a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC2: size of $3"
+ # Check size command on 1MB.file via a path using '..'
+ egrep -A3 "Test Case 2b " "$1" | grep -q "filesize=100000"
+ pass_fail "TC2: size of $3 via a path using '..'"
+
+ # Check size command on 2.5GB.file
+ egrep -A3 "Test Case 3 " "$1" | grep -q "filesize=9c400000"
+ pass_fail "TC3: size of $4"
+
+ # Check read full mb of 1MB.file
+ grep -A4 "Test Case 4a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC4: load of $3 size"
+ check_md5 "Test Case 4b " "$1" "$2" 1 "TC4: load from $3"
+
+ # Check first mb of 2.5GB.file
+ grep -A4 "Test Case 5a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC5: load of 1st MB from $4 size"
+ check_md5 "Test Case 5b " "$1" "$2" 2 "TC5: load of 1st MB from $4"
+
+ # Check last mb of 2.5GB.file
+ grep -A4 "Test Case 6a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC6: load of last MB from $4 size"
+ check_md5 "Test Case 6b " "$1" "$2" 3 "TC6: load of last MB from $4"
+
+ # Check last 1mb chunk of 2gb from 2.5GB file
+ grep -A4 "Test Case 7a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC7: load of last 1mb chunk of 2GB from $4 size"
+ check_md5 "Test Case 7b " "$1" "$2" 4 \
+ "TC7: load of last 1mb chunk of 2GB from $4"
+
+ # Check first 1mb chunk after 2gb from 2.5GB file
+ grep -A4 "Test Case 8a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC8: load 1st MB chunk after 2GB from $4 size"
+ check_md5 "Test Case 8b " "$1" "$2" 5 \
+ "TC8: load 1st MB chunk after 2GB from $4"
+
+ # Check 1mb chunk crossing the 2gb boundary from 2.5GB file
+ grep -A4 "Test Case 9a " "$1" | grep -q "filesize=100000"
+ pass_fail "TC9: load 1MB chunk crossing 2GB boundary from $4 size"
+ check_md5 "Test Case 9b " "$1" "$2" 6 \
+ "TC9: load 1MB chunk crossing 2GB boundary from $4"
+
+ # Check 2mb chunk from the last 1MB of 2.5GB file loads 1MB
+ grep -A5 "Test Case 10 " "$1" | grep -q "filesize=100000"
+ pass_fail "TC10: load 2MB from the last 1MB of $4 loads 1MB"
+
+ # Check 1mb chunk write
+ grep -A2 "Test Case 11a " "$1" | grep -q '1048576 bytes written'
+ pass_fail "TC11: 1MB write to $3.w - write succeeded"
+ check_md5 "Test Case 11b " "$1" "$2" 1 \
+ "TC11: 1MB write to $3.w - content verified"
+
+ # Check lookup of 'dot' directory
+ grep -A4 "Test Case 12 " "$1" | grep -q 'Unable to write'
+ pass_fail "TC12: 1MB write to . - write denied"
+
+ # Check directory traversal
+ grep -A2 "Test Case 13a " "$1" | grep -q '1048576 bytes written'
+ pass_fail "TC13: 1MB write to ./$3.w2 - write succeeded"
+ check_md5 "Test Case 13b " "$1" "$2" 1 \
+ "TC13: 1MB read from ./$3.w2 - content verified"
+ check_md5 "Test Case 13c " "$1" "$2" 1 \
+ "TC13: 1MB read from $3.w2 - content verified"
+
+ echo "** End $1"
+}
+
+# Takes in one parameter which is "fs" or "nonfs", which then dictates
+# if a fs test (size/load/save) or a nonfs test (fatread/extread) needs to
+# be performed.
+function test_fs_nonfs() {
+ echo "Creating files in $fs image if not already present."
+ create_files $IMAGE $MD5_FILE_FS
+
+ OUT_FILE="${OUT}.$1.${fs}.out"
+ test_image $IMAGE $fs $SMALL_FILE $BIG_FILE $1 "" \
+ > ${OUT_FILE} 2>&1
+ # strip out noise from fs code
+ grep -v -e "File System is consistent\|update journal finished" \
+ -e "reading .*\.file\|writing .*\.file.w" \
+ < ${OUT_FILE} > ${OUT_FILE}_clean
+ check_results ${OUT_FILE}_clean $MD5_FILE_FS $SMALL_FILE \
+ $BIG_FILE
+ TOTAL_FAIL=$((TOTAL_FAIL + FAIL))
+ TOTAL_PASS=$((TOTAL_PASS + PASS))
+ echo "Summary: PASS: $PASS FAIL: $FAIL"
+ echo "--------------------------------------------"
+}
+
+# ********************
+# * End of functions *
+# ********************
+
+check_clean "$1"
+check_prereq
+compile_sandbox
+prepare_env
+
+# Track TOTAL_FAIL and TOTAL_PASS
+TOTAL_FAIL=0
+TOTAL_PASS=0
+
+# In each loop, for a given file system image, we test both the
+# fs command, like load/size/write, the file system specific command
+# like: ext4load/ext4size/ext4write and the host load/ls/save commands.
+for fs in ext4 fat16 fat32; do
+
+ echo "Creating $fs image if not already present."
+ IMAGE=${IMG}.${fs}.img
+ MD5_FILE_FS="${MD5_FILE}.${fs}"
+ create_image $IMAGE $fs
+
+ # host commands test
+ echo "Creating files in $fs image if not already present."
+ create_files $IMAGE $MD5_FILE_FS
+
+ # Lets mount the image and test host hostfs commands
+ mkdir -p "$MOUNT_DIR"
+ case "$fs" in
+ fat*)
+ uid="uid=`id -u`"
+ ;;
+ *)
+ uid=""
+ ;;
+ esac
+ sudo mount -o loop,rw,$uid "$IMAGE" "$MOUNT_DIR"
+ sudo chmod 777 "$MOUNT_DIR"
+
+ OUT_FILE="${OUT}.sb.${fs}.out"
+ test_image $IMAGE $fs $SMALL_FILE $BIG_FILE sb `pwd`/$MOUNT_DIR \
+ > ${OUT_FILE} 2>&1
+ sudo umount "$MOUNT_DIR"
+ rmdir "$MOUNT_DIR"
+
+ check_results $OUT_FILE $MD5_FILE_FS $SMALL_FILE $BIG_FILE
+ TOTAL_FAIL=$((TOTAL_FAIL + FAIL))
+ TOTAL_PASS=$((TOTAL_PASS + PASS))
+ echo "Summary: PASS: $PASS FAIL: $FAIL"
+ echo "--------------------------------------------"
+
+ test_fs_nonfs nonfs
+ test_fs_nonfs fs
+done
+
+echo "Total Summary: TOTAL PASS: $TOTAL_PASS TOTAL FAIL: $TOTAL_FAIL"
+echo "--------------------------------------------"
+if [ $TOTAL_FAIL -eq 0 ]; then
+ echo "PASSED"
+ exit 0
+else
+ echo "FAILED"
+ exit 1
+fi
diff --git a/test/image/test-imagetools.sh b/test/image/test-imagetools.sh
new file mode 100755
index 00000000..907f46a7
--- /dev/null
+++ b/test/image/test-imagetools.sh
@@ -0,0 +1,225 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Written by Guilherme Maciel Ferreira <guilherme.maciel.ferreira@gmail.com>
+#
+# Sanity check for mkimage and dumpimage tools
+#
+# To run this:
+#
+# make O=sandbox sandbox_config
+# make O=sandbox
+# ./test/image/test-imagetools.sh
+
+BASEDIR=sandbox
+SRCDIR=${BASEDIR}/boot
+IMAGE_NAME="v1.0-test"
+IMAGE_MULTI=linux.img
+IMAGE_FIT_ITS=linux.its
+IMAGE_FIT_ITB=linux.itb
+DATAFILE0=vmlinuz
+DATAFILE1=initrd.img
+DATAFILE2=System.map
+DATAFILES="${DATAFILE0} ${DATAFILE1} ${DATAFILE2}"
+TEST_OUT=test_output
+MKIMAGE=${BASEDIR}/tools/mkimage
+DUMPIMAGE=${BASEDIR}/tools/dumpimage
+MKIMAGE_LIST=mkimage.list
+DUMPIMAGE_LIST=dumpimage.list
+
+# Remove all the files we created
+cleanup()
+{
+ local file
+
+ for file in ${DATAFILES}; do
+ rm -f ${file} ${SRCDIR}/${file}
+ done
+ rm -f ${IMAGE_MULTI}
+ rm -f ${DUMPIMAGE_LIST}
+ rm -f ${MKIMAGE_LIST}
+ rm -f ${TEST_OUT}
+ rmdir ${SRCDIR}
+}
+
+# Check that two files are the same
+assert_equal()
+{
+ if ! diff -u $1 $2; then
+ echo "Failed."
+ cleanup
+ exit 1
+ fi
+}
+
+# Create some test files
+create_files()
+{
+ local file
+
+ mkdir -p ${SRCDIR}
+ for file in ${DATAFILES}; do
+ head -c $RANDOM /dev/urandom >${SRCDIR}/${file}
+ done
+}
+
+# Run a command, echoing it first
+do_cmd()
+{
+ local cmd="$@"
+
+ echo "# ${cmd}"
+ ${cmd} 2>&1
+}
+
+# Run a command, redirecting output
+# Args:
+# redirect_file
+# command...
+do_cmd_redir()
+{
+ local redir="$1"
+ shift
+ local cmd="$@"
+
+ echo "# ${cmd}"
+ ${cmd} >${redir}
+}
+
+# Write files into an multi-file image
+create_multi_image()
+{
+ local files="${SRCDIR}/${DATAFILE0}:${SRCDIR}/${DATAFILE1}"
+ files+=":${SRCDIR}/${DATAFILE2}"
+
+ echo -e "\nBuilding multi-file image..."
+ do_cmd ${MKIMAGE} -A x86 -O linux -T multi -n \"${IMAGE_NAME}\" \
+ -d ${files} ${IMAGE_MULTI}
+ echo "done."
+}
+
+# Extract files from an multi-file image
+extract_multi_image()
+{
+ echo -e "\nExtracting multi-file image contents..."
+ do_cmd ${DUMPIMAGE} -T multi -p 0 -o ${DATAFILE0} ${IMAGE_MULTI}
+ do_cmd ${DUMPIMAGE} -T multi -p 1 -o ${DATAFILE1} ${IMAGE_MULTI}
+ do_cmd ${DUMPIMAGE} -T multi -p 2 -o ${DATAFILE2} ${IMAGE_MULTI}
+ do_cmd ${DUMPIMAGE} -T multi -p 2 -o ${TEST_OUT} ${IMAGE_MULTI}
+ echo "done."
+}
+
+# Write files into a FIT image
+create_fit_image()
+{
+ echo " \
+ /dts-v1/; \
+ / { \
+ description = \"FIT image\"; \
+ #address-cells = <1>; \
+ \
+ images { \
+ kernel@1 { \
+ description = \"kernel\"; \
+ data = /incbin/(\"${DATAFILE0}\"); \
+ type = \"kernel\"; \
+ arch = \"sandbox\"; \
+ os = \"linux\"; \
+ compression = \"gzip\"; \
+ load = <0x40000>; \
+ entry = <0x8>; \
+ }; \
+ ramdisk@1 { \
+ description = \"filesystem\"; \
+ data = /incbin/(\"${DATAFILE1}\"); \
+ type = \"ramdisk\"; \
+ arch = \"sandbox\"; \
+ os = \"linux\"; \
+ compression = \"none\"; \
+ load = <0x80000>; \
+ entry = <0x16>; \
+ }; \
+ fdt@1 { \
+ description = \"device tree\"; \
+ data = /incbin/(\"${DATAFILE2}\"); \
+ type = \"flat_dt\"; \
+ arch = \"sandbox\"; \
+ compression = \"none\"; \
+ }; \
+ }; \
+ configurations { \
+ default = \"conf@1\"; \
+ conf@1 { \
+ kernel = \"kernel@1\"; \
+ fdt = \"fdt@1\"; \
+ }; \
+ }; \
+ }; \
+ " > ${IMAGE_FIT_ITS}
+
+ echo -e "\nBuilding FIT image..."
+ do_cmd ${MKIMAGE} -f ${IMAGE_FIT_ITS} ${IMAGE_FIT_ITB}
+ echo "done."
+}
+
+# Extract files from a FIT image
+extract_fit_image()
+{
+ echo -e "\nExtracting FIT image contents..."
+ do_cmd ${DUMPIMAGE} -T flat_dt -p 0 -o ${DATAFILE0} ${IMAGE_FIT_ITB}
+ do_cmd ${DUMPIMAGE} -T flat_dt -p 1 -o ${DATAFILE1} ${IMAGE_FIT_ITB}
+ do_cmd ${DUMPIMAGE} -T flat_dt -p 2 -o ${DATAFILE2} ${IMAGE_FIT_ITB}
+ do_cmd ${DUMPIMAGE} -T flat_dt -p 2 -o ${TEST_OUT} ${IMAGE_FIT_ITB}
+ echo "done."
+}
+
+# List the contents of a file
+# Args:
+# image filename
+list_image()
+{
+ local image="$1"
+
+ echo -e "\nListing image contents..."
+ do_cmd_redir ${MKIMAGE_LIST} ${MKIMAGE} -l ${image}
+ do_cmd_redir ${DUMPIMAGE_LIST} ${DUMPIMAGE} -l ${image}
+ echo "done."
+}
+
+main()
+{
+ local file
+
+ create_files
+
+ # Compress and extract multi-file images, compare the result
+ create_multi_image
+ extract_multi_image
+ for file in ${DATAFILES}; do
+ assert_equal ${file} ${SRCDIR}/${file}
+ done
+ assert_equal ${TEST_OUT} ${DATAFILE2}
+
+ # List contents of multi-file image and compares output from tools
+ list_image ${IMAGE_MULTI}
+ assert_equal ${DUMPIMAGE_LIST} ${MKIMAGE_LIST}
+
+ # Compress and extract FIT images, compare the result
+ create_fit_image
+ extract_fit_image
+ for file in ${DATAFILES}; do
+ assert_equal ${file} ${SRCDIR}/${file}
+ done
+ assert_equal ${TEST_OUT} ${DATAFILE2}
+
+ # List contents of FIT image and compares output from tools
+ list_image ${IMAGE_FIT_ITB}
+ assert_equal ${DUMPIMAGE_LIST} ${MKIMAGE_LIST}
+
+ # Remove files created
+ cleanup
+
+ echo "Tests passed."
+}
+
+main
diff --git a/test/lib/Makefile b/test/lib/Makefile
new file mode 100644
index 00000000..72d2ec74
--- /dev/null
+++ b/test/lib/Makefile
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# (C) Copyright 2018
+# Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+obj-y += cmd_ut_lib.o
+obj-y += hexdump.o
+obj-y += lmb.o
+obj-y += string.o
+obj-$(CONFIG_ERRNO_STR) += test_errno_str.o
+obj-$(CONFIG_UT_LIB_ASN1) += asn1.o
diff --git a/test/lib/asn1.c b/test/lib/asn1.c
new file mode 100644
index 00000000..d2b3f67e
--- /dev/null
+++ b/test/lib/asn1.c
@@ -0,0 +1,392 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2019 Linaro Limited
+ * Author: AKASHI Takahiro
+ *
+ * Unit test for asn1 compiler and asn1 decoder function via various parsers
+ */
+
+#include <common.h>
+#include <command.h>
+#include <test/lib.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+#ifdef CONFIG_PKCS7_MESSAGE_PARSER
+#include "../../lib/crypto/pkcs7_parser.h"
+#else
+#ifdef CONFIG_X509_CERTIFICATE_PARSER
+#include "../../lib/crypto/x509_parser.h"
+#endif
+#endif
+
+#ifdef CONFIG_X509_CERTIFICATE_PARSER
+static const unsigned char cert_data[] = {
+ 0x30, 0x82, 0x03, 0xc7, 0x30, 0x82, 0x02, 0xaf, 0xa0, 0x03, 0x02, 0x01,
+ 0x02, 0x02, 0x09, 0x00, 0xd7, 0x17, 0x0a, 0x76, 0xd5, 0xd3, 0x4d, 0xeb,
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x0b, 0x05, 0x00, 0x30, 0x7a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55,
+ 0x04, 0x06, 0x13, 0x02, 0x4a, 0x50, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03,
+ 0x55, 0x04, 0x08, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79, 0x6f, 0x31, 0x0e,
+ 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x54, 0x6f, 0x6b,
+ 0x79, 0x6f, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
+ 0x06, 0x4c, 0x69, 0x6e, 0x61, 0x72, 0x6f, 0x31, 0x0b, 0x30, 0x09, 0x06,
+ 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x53, 0x57, 0x31, 0x0f, 0x30, 0x0d,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x06, 0x54, 0x65, 0x73, 0x74, 0x65,
+ 0x72, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+ 0x0d, 0x01, 0x09, 0x01, 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x40, 0x74,
+ 0x65, 0x73, 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x1e, 0x17, 0x0d, 0x31,
+ 0x39, 0x31, 0x30, 0x31, 0x38, 0x30, 0x33, 0x31, 0x33, 0x33, 0x31, 0x5a,
+ 0x17, 0x0d, 0x32, 0x30, 0x31, 0x30, 0x31, 0x37, 0x30, 0x33, 0x31, 0x33,
+ 0x33, 0x31, 0x5a, 0x30, 0x7a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55,
+ 0x04, 0x06, 0x13, 0x02, 0x4a, 0x50, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03,
+ 0x55, 0x04, 0x08, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79, 0x6f, 0x31, 0x0e,
+ 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x54, 0x6f, 0x6b,
+ 0x79, 0x6f, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
+ 0x06, 0x4c, 0x69, 0x6e, 0x61, 0x72, 0x6f, 0x31, 0x0b, 0x30, 0x09, 0x06,
+ 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x53, 0x57, 0x31, 0x0f, 0x30, 0x0d,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x06, 0x54, 0x65, 0x73, 0x74, 0x65,
+ 0x72, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+ 0x0d, 0x01, 0x09, 0x01, 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x40, 0x74,
+ 0x65, 0x73, 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x82, 0x01, 0x22, 0x30,
+ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,
+ 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02,
+ 0x82, 0x01, 0x01, 0x00, 0x9f, 0x37, 0x4d, 0x95, 0x7e, 0x36, 0xb7, 0xaf,
+ 0xf4, 0xd6, 0xce, 0x39, 0x04, 0xee, 0xbf, 0x36, 0xb2, 0xcc, 0xa3, 0x8b,
+ 0x9e, 0xac, 0x62, 0x8a, 0xe9, 0xae, 0x18, 0xcf, 0xe8, 0x95, 0xfd, 0xcb,
+ 0xad, 0x34, 0x8a, 0x5f, 0x55, 0xe6, 0x0c, 0x5e, 0xf8, 0x76, 0xc1, 0xa2,
+ 0xc3, 0xd4, 0x73, 0x13, 0x8a, 0x71, 0x1b, 0xfd, 0x58, 0x27, 0xea, 0x4d,
+ 0x41, 0xff, 0x63, 0xbb, 0xad, 0x97, 0x62, 0xba, 0xe4, 0xe5, 0x97, 0x45,
+ 0xa3, 0x5b, 0xd5, 0x5b, 0x53, 0x55, 0x10, 0x19, 0xfa, 0xac, 0xbd, 0xdb,
+ 0x77, 0x62, 0x23, 0x50, 0x3f, 0x35, 0xdb, 0x8a, 0xf6, 0xee, 0x7a, 0x31,
+ 0xec, 0x92, 0xf5, 0x78, 0x35, 0x92, 0x76, 0x3c, 0x5f, 0xe7, 0xee, 0xc9,
+ 0xed, 0x01, 0x1c, 0x42, 0x55, 0xd6, 0x7e, 0xa6, 0xca, 0x7c, 0xd1, 0x15,
+ 0x16, 0x87, 0x7c, 0x99, 0x63, 0xc0, 0xa9, 0x25, 0x49, 0xbc, 0x4e, 0xdc,
+ 0x2d, 0x4b, 0xcb, 0x52, 0xd7, 0x67, 0xe9, 0x83, 0x6b, 0x5e, 0x5b, 0x48,
+ 0x80, 0x33, 0xe9, 0xcc, 0xe8, 0xfe, 0x19, 0xc8, 0xc2, 0x61, 0x74, 0x52,
+ 0x25, 0x92, 0x48, 0xea, 0xad, 0x15, 0x16, 0x64, 0x6e, 0x53, 0x30, 0x77,
+ 0xa2, 0xef, 0x61, 0x92, 0x1b, 0x5e, 0xbe, 0x07, 0xf2, 0x3c, 0xf8, 0x35,
+ 0x7d, 0x76, 0x4f, 0x78, 0xa9, 0x2a, 0xf1, 0x32, 0xff, 0xec, 0x89, 0xa9,
+ 0x22, 0x4c, 0x3d, 0xc8, 0x65, 0xca, 0xf4, 0xa2, 0x6d, 0x3f, 0xa4, 0x0a,
+ 0xfa, 0x9e, 0xe4, 0xf0, 0xdb, 0x39, 0xb1, 0xf9, 0xf0, 0xfb, 0x04, 0x81,
+ 0x44, 0xa7, 0xd7, 0x61, 0xdf, 0x2d, 0x13, 0x45, 0x2c, 0xae, 0xf0, 0x0e,
+ 0xc4, 0x07, 0x5d, 0x7d, 0x2b, 0xb2, 0x20, 0x75, 0x33, 0x6b, 0x5b, 0xf7,
+ 0xe7, 0x17, 0x51, 0xf1, 0xab, 0xc1, 0x9e, 0xc6, 0xf0, 0x30, 0xc6, 0x25,
+ 0x26, 0x3e, 0xd7, 0xd7, 0xa3, 0xcc, 0x15, 0x95, 0x02, 0x03, 0x01, 0x00,
+ 0x01, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e,
+ 0x04, 0x16, 0x04, 0x14, 0x45, 0x8a, 0x76, 0xf7, 0x4f, 0xf4, 0x0e, 0xa0,
+ 0xf2, 0x02, 0xe1, 0xe7, 0xe9, 0xc7, 0x7d, 0x51, 0x55, 0x92, 0x33, 0xcd,
+ 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80,
+ 0x14, 0x45, 0x8a, 0x76, 0xf7, 0x4f, 0xf4, 0x0e, 0xa0, 0xf2, 0x02, 0xe1,
+ 0xe7, 0xe9, 0xc7, 0x7d, 0x51, 0x55, 0x92, 0x33, 0xcd, 0x30, 0x0c, 0x06,
+ 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30,
+ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
+ 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x47, 0x93, 0x82, 0x0e, 0x8a,
+ 0x70, 0x9d, 0x6c, 0x7a, 0xdb, 0x04, 0xb4, 0xc9, 0xef, 0x98, 0x28, 0xc6,
+ 0xd9, 0x53, 0x90, 0xc8, 0x25, 0x83, 0x07, 0x23, 0xe7, 0x59, 0x38, 0xc1,
+ 0xc0, 0x50, 0x28, 0x99, 0x92, 0xfb, 0x21, 0x24, 0x72, 0xe5, 0xa6, 0x57,
+ 0x30, 0x31, 0xb3, 0xdf, 0xa0, 0x17, 0xa9, 0x73, 0x9c, 0x39, 0x83, 0xfb,
+ 0xe4, 0xfa, 0x20, 0x1d, 0xfa, 0x33, 0x20, 0x0c, 0x72, 0x2a, 0x50, 0x40,
+ 0xbd, 0x2d, 0x33, 0xa2, 0xfc, 0x06, 0xf9, 0xfe, 0x86, 0x4f, 0x50, 0x1d,
+ 0x65, 0x37, 0xe9, 0x30, 0x33, 0x82, 0xa1, 0x75, 0x8f, 0x5d, 0x33, 0x84,
+ 0x0d, 0xf2, 0x09, 0x04, 0xc0, 0x7a, 0x12, 0x79, 0xdb, 0x4f, 0x77, 0x04,
+ 0xe4, 0xd8, 0x0b, 0x87, 0x19, 0xba, 0xb7, 0x3c, 0xa6, 0x45, 0xaa, 0x91,
+ 0x62, 0x7f, 0x01, 0x7d, 0xc6, 0x20, 0x6d, 0x71, 0x15, 0x74, 0x5e, 0x87,
+ 0xb3, 0x60, 0x17, 0x9c, 0xc0, 0xed, 0x01, 0x4b, 0xb3, 0x23, 0x24, 0xc1,
+ 0xcb, 0x7a, 0x83, 0x03, 0x26, 0x2d, 0xde, 0x47, 0xc5, 0x11, 0x94, 0x28,
+ 0x27, 0x15, 0x92, 0x00, 0x8b, 0x2e, 0x51, 0x42, 0xca, 0x4b, 0x4a, 0x2c,
+ 0x51, 0x37, 0x56, 0xd0, 0xbc, 0x33, 0xd5, 0xd5, 0x3e, 0x79, 0x5c, 0x3f,
+ 0x9d, 0x6e, 0xb1, 0xe9, 0x71, 0xf1, 0x2c, 0xe9, 0xb4, 0x88, 0x2c, 0xd2,
+ 0x49, 0x97, 0xce, 0x29, 0x94, 0x16, 0xc9, 0xf9, 0x64, 0x0e, 0xd0, 0xd9,
+ 0x7a, 0x53, 0x10, 0x1a, 0xee, 0x83, 0x73, 0x93, 0x1b, 0xdf, 0x8a, 0x77,
+ 0xc0, 0x56, 0x63, 0xab, 0x5a, 0x65, 0xc5, 0xc5, 0x3b, 0xf3, 0x30, 0x80,
+ 0xfc, 0x38, 0x8b, 0xc9, 0xcd, 0xc3, 0x4f, 0x2e, 0x2d, 0x67, 0xcc, 0x17,
+ 0x18, 0x9b, 0x3e, 0xc6, 0x47, 0x03, 0xfc, 0x35, 0xa8, 0x35, 0x06, 0x5a,
+ 0x77, 0xe5, 0x97, 0x71, 0xbb, 0x27, 0x93, 0x0d, 0x1f, 0x0e, 0x8c
+};
+
+static unsigned int cert_data_len = 971;
+
+/**
+ * lib_asn1_x509() - unit test for asn1 decoder function
+ * with x509 certificate parser
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_asn1_x509(struct unit_test_state *uts)
+{
+ struct x509_certificate *cert;
+
+ cert = x509_cert_parse(cert_data, cert_data_len);
+
+ ut_assertf(cert != NULL, "decoding failed\n");
+ ut_assertf(!strcmp(cert->subject, "Linaro: Tester"),
+ "subject doesn't match\n");
+ ut_assertf(!strcmp(cert->issuer, "Linaro: Tester"),
+ "issuer doesn't match\n");
+ ut_assertf(cert->pub, "public key doesn't exist\n");
+ ut_assertf(cert->pub->keylen == 0x10e, "key length doesn't match\n");
+ ut_assertf(!strcmp(cert->pub->pkey_algo, "rsa"), "algo isn't rsa\n");
+ ut_assertf(cert->valid_from == 0x5da92ddb,
+ "valid_from doesn't match\n");
+ ut_assertf(cert->valid_to == 0x5f8a615b, "valid_to doesn't match\n");
+
+ x509_free_certificate(cert);
+
+ return CMD_RET_SUCCESS;
+}
+
+LIB_TEST(lib_asn1_x509, 0);
+#endif /* CONFIG_X509_CERTIFICATE_PARSER */
+
+#ifdef CONFIG_PKCS7_MESSAGE_PARSER
+/*
+ * sbsign --key priv.pem --cert cert.pem --detach --out Image.pk Image
+ */
+static const unsigned char image_pk7[] = {
+ 0x30, 0x82, 0x07, 0x0f, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+ 0x01, 0x07, 0x02, 0xa0, 0x82, 0x07, 0x00, 0x30, 0x82, 0x06, 0xfc, 0x02,
+ 0x01, 0x01, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x30, 0x78, 0x06, 0x0a, 0x2b,
+ 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x04, 0xa0, 0x6a, 0x30,
+ 0x68, 0x30, 0x33, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37,
+ 0x02, 0x01, 0x0f, 0x30, 0x25, 0x03, 0x01, 0x00, 0xa0, 0x20, 0xa2, 0x1e,
+ 0x80, 0x1c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f, 0x00, 0x62,
+ 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x74, 0x00, 0x65,
+ 0x00, 0x3e, 0x00, 0x3e, 0x00, 0x3e, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09,
+ 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04,
+ 0x20, 0x9e, 0x90, 0x99, 0x6d, 0xf2, 0xb5, 0x3d, 0x3f, 0xfc, 0x38, 0xb6,
+ 0xf2, 0x1f, 0xd2, 0x24, 0x88, 0x43, 0x77, 0x7d, 0xc1, 0x2c, 0x9e, 0x8a,
+ 0xf6, 0xf7, 0xdd, 0x9e, 0x9c, 0x5f, 0x18, 0x36, 0xc5, 0xa0, 0x82, 0x03,
+ 0xcb, 0x30, 0x82, 0x03, 0xc7, 0x30, 0x82, 0x02, 0xaf, 0xa0, 0x03, 0x02,
+ 0x01, 0x02, 0x02, 0x09, 0x00, 0xd7, 0x17, 0x0a, 0x76, 0xd5, 0xd3, 0x4d,
+ 0xeb, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
+ 0x01, 0x0b, 0x05, 0x00, 0x30, 0x7a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4a, 0x50, 0x31, 0x0e, 0x30, 0x0c, 0x06,
+ 0x03, 0x55, 0x04, 0x08, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79, 0x6f, 0x31,
+ 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x54, 0x6f,
+ 0x6b, 0x79, 0x6f, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a,
+ 0x0c, 0x06, 0x4c, 0x69, 0x6e, 0x61, 0x72, 0x6f, 0x31, 0x0b, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x53, 0x57, 0x31, 0x0f, 0x30,
+ 0x0d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x06, 0x54, 0x65, 0x73, 0x74,
+ 0x65, 0x72, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+ 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x40,
+ 0x74, 0x65, 0x73, 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x1e, 0x17, 0x0d,
+ 0x31, 0x39, 0x31, 0x30, 0x31, 0x38, 0x30, 0x33, 0x31, 0x33, 0x33, 0x31,
+ 0x5a, 0x17, 0x0d, 0x32, 0x30, 0x31, 0x30, 0x31, 0x37, 0x30, 0x33, 0x31,
+ 0x33, 0x33, 0x31, 0x5a, 0x30, 0x7a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4a, 0x50, 0x31, 0x0e, 0x30, 0x0c, 0x06,
+ 0x03, 0x55, 0x04, 0x08, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79, 0x6f, 0x31,
+ 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x54, 0x6f,
+ 0x6b, 0x79, 0x6f, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a,
+ 0x0c, 0x06, 0x4c, 0x69, 0x6e, 0x61, 0x72, 0x6f, 0x31, 0x0b, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x53, 0x57, 0x31, 0x0f, 0x30,
+ 0x0d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x06, 0x54, 0x65, 0x73, 0x74,
+ 0x65, 0x72, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+ 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x40,
+ 0x74, 0x65, 0x73, 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x82, 0x01, 0x22,
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a,
+ 0x02, 0x82, 0x01, 0x01, 0x00, 0x9f, 0x37, 0x4d, 0x95, 0x7e, 0x36, 0xb7,
+ 0xaf, 0xf4, 0xd6, 0xce, 0x39, 0x04, 0xee, 0xbf, 0x36, 0xb2, 0xcc, 0xa3,
+ 0x8b, 0x9e, 0xac, 0x62, 0x8a, 0xe9, 0xae, 0x18, 0xcf, 0xe8, 0x95, 0xfd,
+ 0xcb, 0xad, 0x34, 0x8a, 0x5f, 0x55, 0xe6, 0x0c, 0x5e, 0xf8, 0x76, 0xc1,
+ 0xa2, 0xc3, 0xd4, 0x73, 0x13, 0x8a, 0x71, 0x1b, 0xfd, 0x58, 0x27, 0xea,
+ 0x4d, 0x41, 0xff, 0x63, 0xbb, 0xad, 0x97, 0x62, 0xba, 0xe4, 0xe5, 0x97,
+ 0x45, 0xa3, 0x5b, 0xd5, 0x5b, 0x53, 0x55, 0x10, 0x19, 0xfa, 0xac, 0xbd,
+ 0xdb, 0x77, 0x62, 0x23, 0x50, 0x3f, 0x35, 0xdb, 0x8a, 0xf6, 0xee, 0x7a,
+ 0x31, 0xec, 0x92, 0xf5, 0x78, 0x35, 0x92, 0x76, 0x3c, 0x5f, 0xe7, 0xee,
+ 0xc9, 0xed, 0x01, 0x1c, 0x42, 0x55, 0xd6, 0x7e, 0xa6, 0xca, 0x7c, 0xd1,
+ 0x15, 0x16, 0x87, 0x7c, 0x99, 0x63, 0xc0, 0xa9, 0x25, 0x49, 0xbc, 0x4e,
+ 0xdc, 0x2d, 0x4b, 0xcb, 0x52, 0xd7, 0x67, 0xe9, 0x83, 0x6b, 0x5e, 0x5b,
+ 0x48, 0x80, 0x33, 0xe9, 0xcc, 0xe8, 0xfe, 0x19, 0xc8, 0xc2, 0x61, 0x74,
+ 0x52, 0x25, 0x92, 0x48, 0xea, 0xad, 0x15, 0x16, 0x64, 0x6e, 0x53, 0x30,
+ 0x77, 0xa2, 0xef, 0x61, 0x92, 0x1b, 0x5e, 0xbe, 0x07, 0xf2, 0x3c, 0xf8,
+ 0x35, 0x7d, 0x76, 0x4f, 0x78, 0xa9, 0x2a, 0xf1, 0x32, 0xff, 0xec, 0x89,
+ 0xa9, 0x22, 0x4c, 0x3d, 0xc8, 0x65, 0xca, 0xf4, 0xa2, 0x6d, 0x3f, 0xa4,
+ 0x0a, 0xfa, 0x9e, 0xe4, 0xf0, 0xdb, 0x39, 0xb1, 0xf9, 0xf0, 0xfb, 0x04,
+ 0x81, 0x44, 0xa7, 0xd7, 0x61, 0xdf, 0x2d, 0x13, 0x45, 0x2c, 0xae, 0xf0,
+ 0x0e, 0xc4, 0x07, 0x5d, 0x7d, 0x2b, 0xb2, 0x20, 0x75, 0x33, 0x6b, 0x5b,
+ 0xf7, 0xe7, 0x17, 0x51, 0xf1, 0xab, 0xc1, 0x9e, 0xc6, 0xf0, 0x30, 0xc6,
+ 0x25, 0x26, 0x3e, 0xd7, 0xd7, 0xa3, 0xcc, 0x15, 0x95, 0x02, 0x03, 0x01,
+ 0x00, 0x01, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d,
+ 0x0e, 0x04, 0x16, 0x04, 0x14, 0x45, 0x8a, 0x76, 0xf7, 0x4f, 0xf4, 0x0e,
+ 0xa0, 0xf2, 0x02, 0xe1, 0xe7, 0xe9, 0xc7, 0x7d, 0x51, 0x55, 0x92, 0x33,
+ 0xcd, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16,
+ 0x80, 0x14, 0x45, 0x8a, 0x76, 0xf7, 0x4f, 0xf4, 0x0e, 0xa0, 0xf2, 0x02,
+ 0xe1, 0xe7, 0xe9, 0xc7, 0x7d, 0x51, 0x55, 0x92, 0x33, 0xcd, 0x30, 0x0c,
+ 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff,
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x47, 0x93, 0x82, 0x0e,
+ 0x8a, 0x70, 0x9d, 0x6c, 0x7a, 0xdb, 0x04, 0xb4, 0xc9, 0xef, 0x98, 0x28,
+ 0xc6, 0xd9, 0x53, 0x90, 0xc8, 0x25, 0x83, 0x07, 0x23, 0xe7, 0x59, 0x38,
+ 0xc1, 0xc0, 0x50, 0x28, 0x99, 0x92, 0xfb, 0x21, 0x24, 0x72, 0xe5, 0xa6,
+ 0x57, 0x30, 0x31, 0xb3, 0xdf, 0xa0, 0x17, 0xa9, 0x73, 0x9c, 0x39, 0x83,
+ 0xfb, 0xe4, 0xfa, 0x20, 0x1d, 0xfa, 0x33, 0x20, 0x0c, 0x72, 0x2a, 0x50,
+ 0x40, 0xbd, 0x2d, 0x33, 0xa2, 0xfc, 0x06, 0xf9, 0xfe, 0x86, 0x4f, 0x50,
+ 0x1d, 0x65, 0x37, 0xe9, 0x30, 0x33, 0x82, 0xa1, 0x75, 0x8f, 0x5d, 0x33,
+ 0x84, 0x0d, 0xf2, 0x09, 0x04, 0xc0, 0x7a, 0x12, 0x79, 0xdb, 0x4f, 0x77,
+ 0x04, 0xe4, 0xd8, 0x0b, 0x87, 0x19, 0xba, 0xb7, 0x3c, 0xa6, 0x45, 0xaa,
+ 0x91, 0x62, 0x7f, 0x01, 0x7d, 0xc6, 0x20, 0x6d, 0x71, 0x15, 0x74, 0x5e,
+ 0x87, 0xb3, 0x60, 0x17, 0x9c, 0xc0, 0xed, 0x01, 0x4b, 0xb3, 0x23, 0x24,
+ 0xc1, 0xcb, 0x7a, 0x83, 0x03, 0x26, 0x2d, 0xde, 0x47, 0xc5, 0x11, 0x94,
+ 0x28, 0x27, 0x15, 0x92, 0x00, 0x8b, 0x2e, 0x51, 0x42, 0xca, 0x4b, 0x4a,
+ 0x2c, 0x51, 0x37, 0x56, 0xd0, 0xbc, 0x33, 0xd5, 0xd5, 0x3e, 0x79, 0x5c,
+ 0x3f, 0x9d, 0x6e, 0xb1, 0xe9, 0x71, 0xf1, 0x2c, 0xe9, 0xb4, 0x88, 0x2c,
+ 0xd2, 0x49, 0x97, 0xce, 0x29, 0x94, 0x16, 0xc9, 0xf9, 0x64, 0x0e, 0xd0,
+ 0xd9, 0x7a, 0x53, 0x10, 0x1a, 0xee, 0x83, 0x73, 0x93, 0x1b, 0xdf, 0x8a,
+ 0x77, 0xc0, 0x56, 0x63, 0xab, 0x5a, 0x65, 0xc5, 0xc5, 0x3b, 0xf3, 0x30,
+ 0x80, 0xfc, 0x38, 0x8b, 0xc9, 0xcd, 0xc3, 0x4f, 0x2e, 0x2d, 0x67, 0xcc,
+ 0x17, 0x18, 0x9b, 0x3e, 0xc6, 0x47, 0x03, 0xfc, 0x35, 0xa8, 0x35, 0x06,
+ 0x5a, 0x77, 0xe5, 0x97, 0x71, 0xbb, 0x27, 0x93, 0x0d, 0x1f, 0x0e, 0x8c,
+ 0x31, 0x82, 0x02, 0x9b, 0x30, 0x82, 0x02, 0x97, 0x02, 0x01, 0x01, 0x30,
+ 0x81, 0x87, 0x30, 0x7a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04,
+ 0x06, 0x13, 0x02, 0x4a, 0x50, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55,
+ 0x04, 0x08, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79, 0x6f, 0x31, 0x0e, 0x30,
+ 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x54, 0x6f, 0x6b, 0x79,
+ 0x6f, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x06,
+ 0x4c, 0x69, 0x6e, 0x61, 0x72, 0x6f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x53, 0x57, 0x31, 0x0f, 0x30, 0x0d, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x0c, 0x06, 0x54, 0x65, 0x73, 0x74, 0x65, 0x72,
+ 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+ 0x01, 0x09, 0x01, 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x40, 0x74, 0x65,
+ 0x73, 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x02, 0x09, 0x00, 0xd7, 0x17, 0x0a,
+ 0x76, 0xd5, 0xd3, 0x4d, 0xeb, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
+ 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0xa0, 0x81, 0xe5, 0x30,
+ 0x19, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x03,
+ 0x31, 0x0c, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02,
+ 0x01, 0x04, 0x30, 0x1c, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+ 0x01, 0x09, 0x05, 0x31, 0x0f, 0x17, 0x0d, 0x31, 0x39, 0x31, 0x30, 0x31,
+ 0x38, 0x30, 0x35, 0x35, 0x35, 0x32, 0x36, 0x5a, 0x30, 0x2f, 0x06, 0x09,
+ 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x04, 0x31, 0x22, 0x04,
+ 0x20, 0x13, 0xe9, 0x2d, 0xcd, 0x35, 0x43, 0xe0, 0x13, 0x34, 0xc5, 0x67,
+ 0xde, 0xdd, 0x75, 0xdc, 0x62, 0x97, 0x76, 0x7d, 0x5b, 0xa0, 0xb4, 0x4d,
+ 0x4f, 0xef, 0xb8, 0xa7, 0x95, 0x50, 0xcb, 0x0f, 0xec, 0x30, 0x79, 0x06,
+ 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x0f, 0x31, 0x6c,
+ 0x30, 0x6a, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
+ 0x04, 0x01, 0x2a, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
+ 0x03, 0x04, 0x01, 0x16, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
+ 0x65, 0x03, 0x04, 0x01, 0x02, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48,
+ 0x86, 0xf7, 0x0d, 0x03, 0x07, 0x30, 0x0e, 0x06, 0x08, 0x2a, 0x86, 0x48,
+ 0x86, 0xf7, 0x0d, 0x03, 0x02, 0x02, 0x02, 0x00, 0x80, 0x30, 0x0d, 0x06,
+ 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x02, 0x02, 0x01, 0x40,
+ 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x07, 0x30, 0x0d, 0x06,
+ 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x02, 0x02, 0x01, 0x28,
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x01, 0x05, 0x00, 0x04, 0x82, 0x01, 0x00, 0x38, 0x40, 0x09, 0xc7, 0xc4,
+ 0xf7, 0x78, 0x48, 0x75, 0x1e, 0xb2, 0x50, 0x95, 0x0a, 0x52, 0xee, 0x57,
+ 0x60, 0xc5, 0xf4, 0xdb, 0xca, 0x67, 0xb0, 0x19, 0xad, 0x68, 0xb1, 0xe1,
+ 0x1e, 0xb7, 0xf6, 0x53, 0x3d, 0x13, 0xb1, 0x11, 0x37, 0xa7, 0x6e, 0x9b,
+ 0x18, 0x1d, 0x0e, 0xbd, 0xc4, 0xb2, 0xd0, 0x36, 0x6c, 0x0c, 0x5a, 0x11,
+ 0x50, 0xcc, 0xdb, 0x1f, 0x6b, 0xcb, 0x28, 0x80, 0xd5, 0x3c, 0x4f, 0x93,
+ 0x0b, 0xd1, 0x45, 0x75, 0xa1, 0x89, 0x00, 0x71, 0x7d, 0x55, 0xcc, 0x1c,
+ 0x0a, 0xc9, 0xc4, 0xe6, 0x87, 0xf2, 0x87, 0x0d, 0x2e, 0x79, 0x71, 0x85,
+ 0x01, 0xd7, 0x32, 0x87, 0x9a, 0x11, 0xc6, 0x9a, 0xbb, 0x0a, 0x7b, 0xce,
+ 0xfe, 0xc8, 0xee, 0x10, 0x3c, 0xa6, 0x47, 0xdd, 0xbb, 0xa7, 0xf5, 0x19,
+ 0x50, 0xd5, 0x2a, 0x11, 0x44, 0x2f, 0x65, 0x09, 0x69, 0x50, 0xfa, 0xbd,
+ 0x02, 0xe4, 0x90, 0xdc, 0x2a, 0x7c, 0xdb, 0x82, 0x03, 0xa5, 0x28, 0x91,
+ 0x74, 0x7c, 0xd3, 0x83, 0xc8, 0x11, 0x1a, 0x14, 0x1b, 0xba, 0xb1, 0x82,
+ 0xbd, 0x53, 0xad, 0x9c, 0x34, 0x05, 0xfa, 0x2d, 0x14, 0x58, 0x5e, 0x50,
+ 0x64, 0x60, 0x5c, 0x21, 0x7c, 0xe6, 0xf0, 0x2b, 0xa2, 0xec, 0xe5, 0xeb,
+ 0xda, 0x88, 0xe2, 0x19, 0x36, 0x96, 0x65, 0xf7, 0x4c, 0x62, 0x9b, 0x75,
+ 0x24, 0xb4, 0xb1, 0x34, 0x83, 0xba, 0x05, 0x01, 0xd8, 0xe1, 0x33, 0xd3,
+ 0x1a, 0xd6, 0x09, 0x84, 0x31, 0xd0, 0x67, 0xf3, 0x3b, 0x0e, 0x19, 0x98,
+ 0x7e, 0x07, 0xdc, 0xe1, 0xd8, 0x45, 0x84, 0xa2, 0xdd, 0x8a, 0x04, 0x6a,
+ 0x43, 0xcf, 0xff, 0x7c, 0x9e, 0x83, 0xa8, 0x5d, 0xbc, 0x1f, 0x45, 0x86,
+ 0x5b, 0x2d, 0xcd, 0x9d, 0xa0, 0xba, 0x4d, 0xd2, 0xc6, 0xb9, 0xc5, 0x34,
+ 0x39, 0x29, 0x20, 0xee, 0x27, 0x60, 0x46, 0x9c, 0x62, 0xbe, 0xf2
+};
+
+static unsigned int image_pk7_len = 1811;
+
+/**
+ * lib_asn1_pkcs7() - unit test for asn1 decoder function
+ * with pkcs7 message parser
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_asn1_pkcs7(struct unit_test_state *uts)
+{
+ struct pkcs7_message *pkcs7;
+
+ pkcs7 = pkcs7_parse_message(image_pk7, image_pk7_len);
+
+ ut_assertf(pkcs7 != NULL, "decoding failed\n");
+ ut_assertf(pkcs7->data_len == 104, "signature size doesn't match\n");
+ ut_assertf(pkcs7->signed_infos != NULL, "sign-info doesn't exist\n");
+ ut_assertf(pkcs7->signed_infos->msgdigest_len == 32,
+ "digest size doesn't match\n");
+ ut_assertf(pkcs7->signed_infos->aa_set == 0xf,
+ "authenticated attributes doesn't match\n");
+
+ pkcs7_free_message(pkcs7);
+
+ return CMD_RET_SUCCESS;
+}
+
+LIB_TEST(lib_asn1_pkcs7, 0);
+#endif /* CONFIG_PKCS7_MESSAGE_PARSER */
+
+#ifdef CONFIG_RSA_PUBLIC_KEY_PARSER
+#include <crypto/internal/rsa.h>
+
+/*
+ * openssl genrsa 2048 -out private.pem
+ * openssl rsa -in private.pem -pubout -outform der -out public.der
+ * dd if=public.der of=public.raw bs=24 skip=1
+ */
+static const unsigned char public_key[] = {
+ 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xca, 0x25, 0x23,
+ 0xe0, 0x0a, 0x4d, 0x8f, 0x56, 0xfc, 0xc9, 0x06, 0x4c, 0xcc, 0x94, 0x43,
+ 0xe0, 0x56, 0x44, 0x6e, 0x37, 0x54, 0x87, 0x12, 0x84, 0xf9, 0x07, 0x4f,
+ 0xe4, 0x23, 0x40, 0xc3, 0x43, 0x84, 0x37, 0x86, 0xd3, 0x9d, 0x95, 0x1c,
+ 0xe4, 0x8a, 0x66, 0x02, 0x09, 0xe2, 0x3d, 0xce, 0x2c, 0xc6, 0x02, 0x6a,
+ 0xd4, 0x65, 0x61, 0xff, 0x85, 0x6f, 0x88, 0x63, 0xba, 0x31, 0x62, 0x1e,
+ 0xb7, 0x95, 0xe9, 0x08, 0x3c, 0xe9, 0x35, 0xde, 0xfd, 0x65, 0x92, 0xb8,
+ 0x9e, 0x71, 0xa4, 0xcd, 0x47, 0xfd, 0x04, 0x26, 0xb9, 0x78, 0xbf, 0x05,
+ 0x0d, 0xfc, 0x00, 0x84, 0x08, 0xfc, 0xc4, 0x4b, 0xea, 0xf5, 0x97, 0x68,
+ 0x0d, 0x97, 0xd7, 0xff, 0x4f, 0x92, 0x82, 0xd7, 0xbb, 0xef, 0xb7, 0x67,
+ 0x8e, 0x72, 0x54, 0xe8, 0xc5, 0x9e, 0xfd, 0xd8, 0x38, 0xe9, 0xbe, 0x19,
+ 0x37, 0x5b, 0x36, 0x8b, 0xbf, 0x49, 0xa1, 0x59, 0x3a, 0x9d, 0xad, 0x92,
+ 0x08, 0x0b, 0xe3, 0xa4, 0xa4, 0x7d, 0xd3, 0x70, 0xc0, 0xb8, 0xfb, 0xc7,
+ 0xda, 0xd3, 0x19, 0x86, 0x37, 0x9a, 0xcd, 0xab, 0x30, 0x96, 0xab, 0xa4,
+ 0xa2, 0x31, 0xa0, 0x38, 0xfb, 0xbf, 0x85, 0xd3, 0x24, 0x39, 0xed, 0xbf,
+ 0xe1, 0x31, 0xed, 0x6c, 0x39, 0xc1, 0xe5, 0x05, 0x2e, 0x12, 0x30, 0x36,
+ 0x73, 0x5d, 0x62, 0xf3, 0x82, 0xaf, 0x38, 0xc8, 0xca, 0xfa, 0xa1, 0x99,
+ 0x57, 0x3c, 0xe1, 0xc1, 0x7b, 0x05, 0x0b, 0xcc, 0x2e, 0xa9, 0x10, 0xc8,
+ 0x68, 0xbd, 0x27, 0xb6, 0x19, 0x9c, 0xd2, 0xad, 0xb3, 0x1f, 0xca, 0x35,
+ 0x6e, 0x84, 0x23, 0xa1, 0xe9, 0xa4, 0x4c, 0xab, 0x19, 0x09, 0x79, 0x6e,
+ 0x3c, 0x7b, 0x74, 0xfc, 0x33, 0x05, 0xcf, 0xa4, 0x2e, 0xeb, 0x55, 0x60,
+ 0x05, 0xc7, 0xcf, 0x3f, 0x92, 0xac, 0x2d, 0x69, 0x0b, 0x19, 0x16, 0x79,
+ 0x75, 0x02, 0x03, 0x01, 0x00, 0x01
+};
+
+static unsigned int public_key_len = 270;
+
+/**
+ * lib_asn1_pkey() - unit test for asn1 decoder function
+ * with RSA public key parser
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_asn1_pkey(struct unit_test_state *uts)
+{
+ struct rsa_key pkey;
+ int ret;
+
+ ret = rsa_parse_pub_key(&pkey, public_key, public_key_len);
+
+ ut_assertf(ret == 0, "decoding failed (%d)\n", ret);
+ ut_assertf(pkey.n_sz == 257, "public key modulus size doesn't match\n");
+ ut_assertf(pkey.e_sz == 3, "public key exponent size doesn't match\n");
+ ut_assertf(pkey.e[0] == 0x01 && pkey.e[1] == 0x00 && pkey.e[2] == 0x01,
+ "public key exponent doesn't match\n");
+
+ return CMD_RET_SUCCESS;
+}
+
+LIB_TEST(lib_asn1_pkey, 0);
+#endif /* CONFIG_RSA_PUBLIC_KEY_PARSER */
diff --git a/test/lib/cmd_ut_lib.c b/test/lib/cmd_ut_lib.c
new file mode 100644
index 00000000..eb90e539
--- /dev/null
+++ b/test/lib/cmd_ut_lib.c
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2019 Heinrich Schuchardt <xypron.glpk@gmx.de>
+ *
+ * Unit tests for library functions
+ */
+
+#include <common.h>
+#include <command.h>
+#include <test/lib.h>
+#include <test/suites.h>
+#include <test/ut.h>
+
+int do_ut_lib(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test, lib_test);
+ const int n_ents = ll_entry_count(struct unit_test, lib_test);
+
+ return cmd_ut_category("lib", tests, n_ents, argc, argv);
+}
diff --git a/test/lib/hexdump.c b/test/lib/hexdump.c
new file mode 100644
index 00000000..5dccf438
--- /dev/null
+++ b/test/lib/hexdump.c
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018
+ * Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
+ */
+
+#include <common.h>
+#include <hexdump.h>
+#include <test/lib.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+static int lib_test_hex_to_bin(struct unit_test_state *uts)
+{
+ ut_asserteq(0x0, hex_to_bin('0'));
+ ut_asserteq(0x1, hex_to_bin('1'));
+ ut_asserteq(0x2, hex_to_bin('2'));
+ ut_asserteq(0x3, hex_to_bin('3'));
+ ut_asserteq(0x4, hex_to_bin('4'));
+ ut_asserteq(0x5, hex_to_bin('5'));
+ ut_asserteq(0x6, hex_to_bin('6'));
+ ut_asserteq(0x7, hex_to_bin('7'));
+ ut_asserteq(0x8, hex_to_bin('8'));
+ ut_asserteq(0x9, hex_to_bin('9'));
+ ut_asserteq(0xa, hex_to_bin('a'));
+ ut_asserteq(0xb, hex_to_bin('b'));
+ ut_asserteq(0xc, hex_to_bin('c'));
+ ut_asserteq(0xd, hex_to_bin('d'));
+ ut_asserteq(0xe, hex_to_bin('e'));
+ ut_asserteq(0xf, hex_to_bin('f'));
+ ut_asserteq(-1, hex_to_bin('g'));
+
+ return 0;
+}
+
+LIB_TEST(lib_test_hex_to_bin, 0);
+
+static int lib_test_hex2bin(struct unit_test_state *uts)
+{
+ u8 dst[4];
+
+ hex2bin(dst, "649421de", 4);
+ ut_asserteq_mem("\x64\x94\x21\xde", dst, 4);
+ hex2bin(dst, "aa2e7545", 4);
+ ut_asserteq_mem("\xaa\x2e\x75\x45", dst, 4);
+ hex2bin(dst, "75453bc5", 4);
+ ut_asserteq_mem("\x75\x45\x3b\xc5", dst, 4);
+ hex2bin(dst, "a16884c3", 4);
+ ut_asserteq_mem("\xa1\x68\x84\xc3", dst, 4);
+ hex2bin(dst, "156b2e5e", 4);
+ ut_asserteq_mem("\x15\x6b\x2e\x5e", dst, 4);
+ hex2bin(dst, "2e035fff", 4);
+ ut_asserteq_mem("\x2e\x03\x5f\xff", dst, 4);
+ hex2bin(dst, "0ffce99f", 4);
+ ut_asserteq_mem("\x0f\xfc\xe9\x9f", dst, 4);
+ hex2bin(dst, "d3999443", 4);
+ ut_asserteq_mem("\xd3\x99\x94\x43", dst, 4);
+ hex2bin(dst, "91dd87bc", 4);
+ ut_asserteq_mem("\x91\xdd\x87\xbc", dst, 4);
+ hex2bin(dst, "7fec8963", 4);
+ ut_asserteq_mem("\x7f\xec\x89\x63", dst, 4);
+
+ return 0;
+}
+
+LIB_TEST(lib_test_hex2bin, 0);
+
+static int lib_test_bin2hex(struct unit_test_state *uts)
+{
+ char dst[8 + 1] = "\0";
+
+ bin2hex(dst, "\x64\x94\x21\xde", 4);
+ ut_asserteq_str("649421de", dst);
+ bin2hex(dst, "\xaa\x2e\x75\x45", 4);
+ ut_asserteq_str("aa2e7545", dst);
+ bin2hex(dst, "\x75\x45\x3b\xc5", 4);
+ ut_asserteq_str("75453bc5", dst);
+ bin2hex(dst, "\xa1\x68\x84\xc3", 4);
+ ut_asserteq_str("a16884c3", dst);
+ bin2hex(dst, "\x15\x6b\x2e\x5e", 4);
+ ut_asserteq_str("156b2e5e", dst);
+ bin2hex(dst, "\x2e\x03\x5f\xff", 4);
+ ut_asserteq_str("2e035fff", dst);
+ bin2hex(dst, "\x0f\xfc\xe9\x9f", 4);
+ ut_asserteq_str("0ffce99f", dst);
+ bin2hex(dst, "\xd3\x99\x94\x43", 4);
+ ut_asserteq_str("d3999443", dst);
+ bin2hex(dst, "\x91\xdd\x87\xbc", 4);
+ ut_asserteq_str("91dd87bc", dst);
+ bin2hex(dst, "\x7f\xec\x89\x63", 4);
+ ut_asserteq_str("7fec8963", dst);
+
+ return 0;
+}
+
+LIB_TEST(lib_test_bin2hex, 0);
diff --git a/test/lib/lmb.c b/test/lib/lmb.c
new file mode 100644
index 00000000..ec68227b
--- /dev/null
+++ b/test/lib/lmb.c
@@ -0,0 +1,657 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * (C) Copyright 2018 Simon Goldschmidt
+ */
+
+#include <common.h>
+#include <lmb.h>
+#include <dm/test.h>
+#include <test/ut.h>
+
+static int check_lmb(struct unit_test_state *uts, struct lmb *lmb,
+ phys_addr_t ram_base, phys_size_t ram_size,
+ unsigned long num_reserved,
+ phys_addr_t base1, phys_size_t size1,
+ phys_addr_t base2, phys_size_t size2,
+ phys_addr_t base3, phys_size_t size3)
+{
+ if (ram_size) {
+ ut_asserteq(lmb->memory.cnt, 1);
+ ut_asserteq(lmb->memory.region[0].base, ram_base);
+ ut_asserteq(lmb->memory.region[0].size, ram_size);
+ }
+
+ ut_asserteq(lmb->reserved.cnt, num_reserved);
+ if (num_reserved > 0) {
+ ut_asserteq(lmb->reserved.region[0].base, base1);
+ ut_asserteq(lmb->reserved.region[0].size, size1);
+ }
+ if (num_reserved > 1) {
+ ut_asserteq(lmb->reserved.region[1].base, base2);
+ ut_asserteq(lmb->reserved.region[1].size, size2);
+ }
+ if (num_reserved > 2) {
+ ut_asserteq(lmb->reserved.region[2].base, base3);
+ ut_asserteq(lmb->reserved.region[2].size, size3);
+ }
+ return 0;
+}
+
+#define ASSERT_LMB(lmb, ram_base, ram_size, num_reserved, base1, size1, \
+ base2, size2, base3, size3) \
+ ut_assert(!check_lmb(uts, lmb, ram_base, ram_size, \
+ num_reserved, base1, size1, base2, size2, base3, \
+ size3))
+
+/*
+ * Test helper function that reserves 64 KiB somewhere in the simulated RAM and
+ * then does some alloc + free tests.
+ */
+static int test_multi_alloc(struct unit_test_state *uts, const phys_addr_t ram,
+ const phys_size_t ram_size, const phys_addr_t ram0,
+ const phys_size_t ram0_size,
+ const phys_addr_t alloc_64k_addr)
+{
+ const phys_addr_t ram_end = ram + ram_size;
+ const phys_addr_t alloc_64k_end = alloc_64k_addr + 0x10000;
+
+ struct lmb lmb;
+ long ret;
+ phys_addr_t a, a2, b, b2, c, d;
+
+ /* check for overflow */
+ ut_assert(ram_end == 0 || ram_end > ram);
+ ut_assert(alloc_64k_end > alloc_64k_addr);
+ /* check input addresses + size */
+ ut_assert(alloc_64k_addr >= ram + 8);
+ ut_assert(alloc_64k_end <= ram_end - 8);
+
+ lmb_init(&lmb);
+
+ if (ram0_size) {
+ ret = lmb_add(&lmb, ram0, ram0_size);
+ ut_asserteq(ret, 0);
+ }
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ if (ram0_size) {
+ ut_asserteq(lmb.memory.cnt, 2);
+ ut_asserteq(lmb.memory.region[0].base, ram0);
+ ut_asserteq(lmb.memory.region[0].size, ram0_size);
+ ut_asserteq(lmb.memory.region[1].base, ram);
+ ut_asserteq(lmb.memory.region[1].size, ram_size);
+ } else {
+ ut_asserteq(lmb.memory.cnt, 1);
+ ut_asserteq(lmb.memory.region[0].base, ram);
+ ut_asserteq(lmb.memory.region[0].size, ram_size);
+ }
+
+ /* reserve 64KiB somewhere */
+ ret = lmb_reserve(&lmb, alloc_64k_addr, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 1, alloc_64k_addr, 0x10000,
+ 0, 0, 0, 0);
+
+ /* allocate somewhere, should be at the end of RAM */
+ a = lmb_alloc(&lmb, 4, 1);
+ ut_asserteq(a, ram_end - 4);
+ ASSERT_LMB(&lmb, 0, 0, 2, alloc_64k_addr, 0x10000,
+ ram_end - 4, 4, 0, 0);
+ /* alloc below end of reserved region -> below reserved region */
+ b = lmb_alloc_base(&lmb, 4, 1, alloc_64k_end);
+ ut_asserteq(b, alloc_64k_addr - 4);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 4, 0x10000 + 4, ram_end - 4, 4, 0, 0);
+
+ /* 2nd time */
+ c = lmb_alloc(&lmb, 4, 1);
+ ut_asserteq(c, ram_end - 8);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 4, 0x10000 + 4, ram_end - 8, 8, 0, 0);
+ d = lmb_alloc_base(&lmb, 4, 1, alloc_64k_end);
+ ut_asserteq(d, alloc_64k_addr - 8);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 0x10000 + 8, ram_end - 8, 8, 0, 0);
+
+ ret = lmb_free(&lmb, a, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 0x10000 + 8, ram_end - 8, 4, 0, 0);
+ /* allocate again to ensure we get the same address */
+ a2 = lmb_alloc(&lmb, 4, 1);
+ ut_asserteq(a, a2);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 0x10000 + 8, ram_end - 8, 8, 0, 0);
+ ret = lmb_free(&lmb, a2, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 0x10000 + 8, ram_end - 8, 4, 0, 0);
+
+ ret = lmb_free(&lmb, b, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 3,
+ alloc_64k_addr - 8, 4, alloc_64k_addr, 0x10000,
+ ram_end - 8, 4);
+ /* allocate again to ensure we get the same address */
+ b2 = lmb_alloc_base(&lmb, 4, 1, alloc_64k_end);
+ ut_asserteq(b, b2);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 0x10000 + 8, ram_end - 8, 4, 0, 0);
+ ret = lmb_free(&lmb, b2, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 3,
+ alloc_64k_addr - 8, 4, alloc_64k_addr, 0x10000,
+ ram_end - 8, 4);
+
+ ret = lmb_free(&lmb, c, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 2,
+ alloc_64k_addr - 8, 4, alloc_64k_addr, 0x10000, 0, 0);
+ ret = lmb_free(&lmb, d, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, 0, 0, 1, alloc_64k_addr, 0x10000,
+ 0, 0, 0, 0);
+
+ if (ram0_size) {
+ ut_asserteq(lmb.memory.cnt, 2);
+ ut_asserteq(lmb.memory.region[0].base, ram0);
+ ut_asserteq(lmb.memory.region[0].size, ram0_size);
+ ut_asserteq(lmb.memory.region[1].base, ram);
+ ut_asserteq(lmb.memory.region[1].size, ram_size);
+ } else {
+ ut_asserteq(lmb.memory.cnt, 1);
+ ut_asserteq(lmb.memory.region[0].base, ram);
+ ut_asserteq(lmb.memory.region[0].size, ram_size);
+ }
+
+ return 0;
+}
+
+static int test_multi_alloc_512mb(struct unit_test_state *uts,
+ const phys_addr_t ram)
+{
+ return test_multi_alloc(uts, ram, 0x20000000, 0, 0, ram + 0x10000000);
+}
+
+static int test_multi_alloc_512mb_x2(struct unit_test_state *uts,
+ const phys_addr_t ram,
+ const phys_addr_t ram0)
+{
+ return test_multi_alloc(uts, ram, 0x20000000, ram0, 0x20000000,
+ ram + 0x10000000);
+}
+
+/* Create a memory region with one reserved region and allocate */
+static int lib_test_lmb_simple(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_multi_alloc_512mb(uts, 0x40000000);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_multi_alloc_512mb(uts, 0xE0000000);
+}
+
+DM_TEST(lib_test_lmb_simple, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Create two memory regions with one reserved region and allocate */
+static int lib_test_lmb_simple_x2(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 2GiB and 1 GiB */
+ ret = test_multi_alloc_512mb_x2(uts, 0x80000000, 0x40000000);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 3.5GiB and 1 GiB */
+ return test_multi_alloc_512mb_x2(uts, 0xE0000000, 0x40000000);
+}
+
+DM_TEST(lib_test_lmb_simple_x2, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Simulate 512 MiB RAM, allocate some blocks that fit/don't fit */
+static int test_bigblock(struct unit_test_state *uts, const phys_addr_t ram)
+{
+ const phys_size_t ram_size = 0x20000000;
+ const phys_size_t big_block_size = 0x10000000;
+ const phys_addr_t ram_end = ram + ram_size;
+ const phys_addr_t alloc_64k_addr = ram + 0x10000000;
+ struct lmb lmb;
+ long ret;
+ phys_addr_t a, b;
+
+ /* check for overflow */
+ ut_assert(ram_end == 0 || ram_end > ram);
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ /* reserve 64KiB in the middle of RAM */
+ ret = lmb_reserve(&lmb, alloc_64k_addr, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, alloc_64k_addr, 0x10000,
+ 0, 0, 0, 0);
+
+ /* allocate a big block, should be below reserved */
+ a = lmb_alloc(&lmb, big_block_size, 1);
+ ut_asserteq(a, ram);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, a,
+ big_block_size + 0x10000, 0, 0, 0, 0);
+ /* allocate 2nd big block */
+ /* This should fail, printing an error */
+ b = lmb_alloc(&lmb, big_block_size, 1);
+ ut_asserteq(b, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, a,
+ big_block_size + 0x10000, 0, 0, 0, 0);
+
+ ret = lmb_free(&lmb, a, big_block_size);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, alloc_64k_addr, 0x10000,
+ 0, 0, 0, 0);
+
+ /* allocate too big block */
+ /* This should fail, printing an error */
+ a = lmb_alloc(&lmb, ram_size, 1);
+ ut_asserteq(a, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, alloc_64k_addr, 0x10000,
+ 0, 0, 0, 0);
+
+ return 0;
+}
+
+static int lib_test_lmb_big(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_bigblock(uts, 0x40000000);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_bigblock(uts, 0xE0000000);
+}
+
+DM_TEST(lib_test_lmb_big, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Simulate 512 MiB RAM, allocate a block without previous reservation */
+static int test_noreserved(struct unit_test_state *uts, const phys_addr_t ram,
+ const phys_addr_t alloc_size, const ulong align)
+{
+ const phys_size_t ram_size = 0x20000000;
+ const phys_addr_t ram_end = ram + ram_size;
+ struct lmb lmb;
+ long ret;
+ phys_addr_t a, b;
+ const phys_addr_t alloc_size_aligned = (alloc_size + align - 1) &
+ ~(align - 1);
+
+ /* check for overflow */
+ ut_assert(ram_end == 0 || ram_end > ram);
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 0, 0, 0, 0, 0, 0, 0);
+
+ /* allocate a block */
+ a = lmb_alloc(&lmb, alloc_size, align);
+ ut_assert(a != 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram + ram_size - alloc_size_aligned,
+ alloc_size, 0, 0, 0, 0);
+ /* allocate another block */
+ b = lmb_alloc(&lmb, alloc_size, align);
+ ut_assert(b != 0);
+ if (alloc_size == alloc_size_aligned) {
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram + ram_size -
+ (alloc_size_aligned * 2), alloc_size * 2, 0, 0, 0,
+ 0);
+ } else {
+ ASSERT_LMB(&lmb, ram, ram_size, 2, ram + ram_size -
+ (alloc_size_aligned * 2), alloc_size, ram + ram_size
+ - alloc_size_aligned, alloc_size, 0, 0);
+ }
+ /* and free them */
+ ret = lmb_free(&lmb, b, alloc_size);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram + ram_size - alloc_size_aligned,
+ alloc_size, 0, 0, 0, 0);
+ ret = lmb_free(&lmb, a, alloc_size);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 0, 0, 0, 0, 0, 0, 0);
+
+ /* allocate a block with base*/
+ b = lmb_alloc_base(&lmb, alloc_size, align, ram_end);
+ ut_assert(a == b);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram + ram_size - alloc_size_aligned,
+ alloc_size, 0, 0, 0, 0);
+ /* and free it */
+ ret = lmb_free(&lmb, b, alloc_size);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 0, 0, 0, 0, 0, 0, 0);
+
+ return 0;
+}
+
+static int lib_test_lmb_noreserved(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_noreserved(uts, 0x40000000, 4, 1);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_noreserved(uts, 0xE0000000, 4, 1);
+}
+
+DM_TEST(lib_test_lmb_noreserved, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+static int lib_test_lmb_unaligned_size(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_noreserved(uts, 0x40000000, 5, 8);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_noreserved(uts, 0xE0000000, 5, 8);
+}
+
+DM_TEST(lib_test_lmb_unaligned_size, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+/*
+ * Simulate a RAM that starts at 0 and allocate down to address 0, which must
+ * fail as '0' means failure for the lmb_alloc functions.
+ */
+static int lib_test_lmb_at_0(struct unit_test_state *uts)
+{
+ const phys_addr_t ram = 0;
+ const phys_size_t ram_size = 0x20000000;
+ struct lmb lmb;
+ long ret;
+ phys_addr_t a, b;
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ /* allocate nearly everything */
+ a = lmb_alloc(&lmb, ram_size - 4, 1);
+ ut_asserteq(a, ram + 4);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, a, ram_size - 4,
+ 0, 0, 0, 0);
+ /* allocate the rest */
+ /* This should fail as the allocated address would be 0 */
+ b = lmb_alloc(&lmb, 4, 1);
+ ut_asserteq(b, 0);
+ /* check that this was an error by checking lmb */
+ ASSERT_LMB(&lmb, ram, ram_size, 1, a, ram_size - 4,
+ 0, 0, 0, 0);
+ /* check that this was an error by freeing b */
+ ret = lmb_free(&lmb, b, 4);
+ ut_asserteq(ret, -1);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, a, ram_size - 4,
+ 0, 0, 0, 0);
+
+ ret = lmb_free(&lmb, a, ram_size - 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 0, 0, 0, 0, 0, 0, 0);
+
+ return 0;
+}
+
+DM_TEST(lib_test_lmb_at_0, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Check that calling lmb_reserve with overlapping regions fails. */
+static int lib_test_lmb_overlapping_reserve(struct unit_test_state *uts)
+{
+ const phys_addr_t ram = 0x40000000;
+ const phys_size_t ram_size = 0x20000000;
+ struct lmb lmb;
+ long ret;
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ ret = lmb_reserve(&lmb, 0x40010000, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, 0x40010000, 0x10000,
+ 0, 0, 0, 0);
+ /* allocate overlapping region should fail */
+ ret = lmb_reserve(&lmb, 0x40011000, 0x10000);
+ ut_asserteq(ret, -1);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, 0x40010000, 0x10000,
+ 0, 0, 0, 0);
+ /* allocate 3nd region */
+ ret = lmb_reserve(&lmb, 0x40030000, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 2, 0x40010000, 0x10000,
+ 0x40030000, 0x10000, 0, 0);
+ /* allocate 2nd region */
+ ret = lmb_reserve(&lmb, 0x40020000, 0x10000);
+ ut_assert(ret >= 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, 0x40010000, 0x30000,
+ 0, 0, 0, 0);
+
+ return 0;
+}
+
+DM_TEST(lib_test_lmb_overlapping_reserve,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/*
+ * Simulate 512 MiB RAM, reserve 3 blocks, allocate addresses in between.
+ * Expect addresses outside the memory range to fail.
+ */
+static int test_alloc_addr(struct unit_test_state *uts, const phys_addr_t ram)
+{
+ const phys_size_t ram_size = 0x20000000;
+ const phys_addr_t ram_end = ram + ram_size;
+ const phys_size_t alloc_addr_a = ram + 0x8000000;
+ const phys_size_t alloc_addr_b = ram + 0x8000000 * 2;
+ const phys_size_t alloc_addr_c = ram + 0x8000000 * 3;
+ struct lmb lmb;
+ long ret;
+ phys_addr_t a, b, c, d, e;
+
+ /* check for overflow */
+ ut_assert(ram_end == 0 || ram_end > ram);
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ /* reserve 3 blocks */
+ ret = lmb_reserve(&lmb, alloc_addr_a, 0x10000);
+ ut_asserteq(ret, 0);
+ ret = lmb_reserve(&lmb, alloc_addr_b, 0x10000);
+ ut_asserteq(ret, 0);
+ ret = lmb_reserve(&lmb, alloc_addr_c, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 3, alloc_addr_a, 0x10000,
+ alloc_addr_b, 0x10000, alloc_addr_c, 0x10000);
+
+ /* allocate blocks */
+ a = lmb_alloc_addr(&lmb, ram, alloc_addr_a - ram);
+ ut_asserteq(a, ram);
+ ASSERT_LMB(&lmb, ram, ram_size, 3, ram, 0x8010000,
+ alloc_addr_b, 0x10000, alloc_addr_c, 0x10000);
+ b = lmb_alloc_addr(&lmb, alloc_addr_a + 0x10000,
+ alloc_addr_b - alloc_addr_a - 0x10000);
+ ut_asserteq(b, alloc_addr_a + 0x10000);
+ ASSERT_LMB(&lmb, ram, ram_size, 2, ram, 0x10010000,
+ alloc_addr_c, 0x10000, 0, 0);
+ c = lmb_alloc_addr(&lmb, alloc_addr_b + 0x10000,
+ alloc_addr_c - alloc_addr_b - 0x10000);
+ ut_asserteq(c, alloc_addr_b + 0x10000);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, 0x18010000,
+ 0, 0, 0, 0);
+ d = lmb_alloc_addr(&lmb, alloc_addr_c + 0x10000,
+ ram_end - alloc_addr_c - 0x10000);
+ ut_asserteq(d, alloc_addr_c + 0x10000);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, ram_size,
+ 0, 0, 0, 0);
+
+ /* allocating anything else should fail */
+ e = lmb_alloc(&lmb, 1, 1);
+ ut_asserteq(e, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, ram_size,
+ 0, 0, 0, 0);
+
+ ret = lmb_free(&lmb, d, ram_end - alloc_addr_c - 0x10000);
+ ut_asserteq(ret, 0);
+
+ /* allocate at 3 points in free range */
+
+ d = lmb_alloc_addr(&lmb, ram_end - 4, 4);
+ ut_asserteq(d, ram_end - 4);
+ ASSERT_LMB(&lmb, ram, ram_size, 2, ram, 0x18010000,
+ d, 4, 0, 0);
+ ret = lmb_free(&lmb, d, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, 0x18010000,
+ 0, 0, 0, 0);
+
+ d = lmb_alloc_addr(&lmb, ram_end - 128, 4);
+ ut_asserteq(d, ram_end - 128);
+ ASSERT_LMB(&lmb, ram, ram_size, 2, ram, 0x18010000,
+ d, 4, 0, 0);
+ ret = lmb_free(&lmb, d, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, 0x18010000,
+ 0, 0, 0, 0);
+
+ d = lmb_alloc_addr(&lmb, alloc_addr_c + 0x10000, 4);
+ ut_asserteq(d, alloc_addr_c + 0x10000);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, 0x18010004,
+ 0, 0, 0, 0);
+ ret = lmb_free(&lmb, d, 4);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram, 0x18010000,
+ 0, 0, 0, 0);
+
+ /* allocate at the bottom */
+ ret = lmb_free(&lmb, a, alloc_addr_a - ram);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 1, ram + 0x8000000, 0x10010000,
+ 0, 0, 0, 0);
+ d = lmb_alloc_addr(&lmb, ram, 4);
+ ut_asserteq(d, ram);
+ ASSERT_LMB(&lmb, ram, ram_size, 2, d, 4,
+ ram + 0x8000000, 0x10010000, 0, 0);
+
+ /* check that allocating outside memory fails */
+ if (ram_end != 0) {
+ ret = lmb_alloc_addr(&lmb, ram_end, 1);
+ ut_asserteq(ret, 0);
+ }
+ if (ram != 0) {
+ ret = lmb_alloc_addr(&lmb, ram - 1, 1);
+ ut_asserteq(ret, 0);
+ }
+
+ return 0;
+}
+
+static int lib_test_lmb_alloc_addr(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_alloc_addr(uts, 0x40000000);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_alloc_addr(uts, 0xE0000000);
+}
+
+DM_TEST(lib_test_lmb_alloc_addr, DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
+
+/* Simulate 512 MiB RAM, reserve 3 blocks, check addresses in between */
+static int test_get_unreserved_size(struct unit_test_state *uts,
+ const phys_addr_t ram)
+{
+ const phys_size_t ram_size = 0x20000000;
+ const phys_addr_t ram_end = ram + ram_size;
+ const phys_size_t alloc_addr_a = ram + 0x8000000;
+ const phys_size_t alloc_addr_b = ram + 0x8000000 * 2;
+ const phys_size_t alloc_addr_c = ram + 0x8000000 * 3;
+ struct lmb lmb;
+ long ret;
+ phys_size_t s;
+
+ /* check for overflow */
+ ut_assert(ram_end == 0 || ram_end > ram);
+
+ lmb_init(&lmb);
+
+ ret = lmb_add(&lmb, ram, ram_size);
+ ut_asserteq(ret, 0);
+
+ /* reserve 3 blocks */
+ ret = lmb_reserve(&lmb, alloc_addr_a, 0x10000);
+ ut_asserteq(ret, 0);
+ ret = lmb_reserve(&lmb, alloc_addr_b, 0x10000);
+ ut_asserteq(ret, 0);
+ ret = lmb_reserve(&lmb, alloc_addr_c, 0x10000);
+ ut_asserteq(ret, 0);
+ ASSERT_LMB(&lmb, ram, ram_size, 3, alloc_addr_a, 0x10000,
+ alloc_addr_b, 0x10000, alloc_addr_c, 0x10000);
+
+ /* check addresses in between blocks */
+ s = lmb_get_free_size(&lmb, ram);
+ ut_asserteq(s, alloc_addr_a - ram);
+ s = lmb_get_free_size(&lmb, ram + 0x10000);
+ ut_asserteq(s, alloc_addr_a - ram - 0x10000);
+ s = lmb_get_free_size(&lmb, alloc_addr_a - 4);
+ ut_asserteq(s, 4);
+
+ s = lmb_get_free_size(&lmb, alloc_addr_a + 0x10000);
+ ut_asserteq(s, alloc_addr_b - alloc_addr_a - 0x10000);
+ s = lmb_get_free_size(&lmb, alloc_addr_a + 0x20000);
+ ut_asserteq(s, alloc_addr_b - alloc_addr_a - 0x20000);
+ s = lmb_get_free_size(&lmb, alloc_addr_b - 4);
+ ut_asserteq(s, 4);
+
+ s = lmb_get_free_size(&lmb, alloc_addr_c + 0x10000);
+ ut_asserteq(s, ram_end - alloc_addr_c - 0x10000);
+ s = lmb_get_free_size(&lmb, alloc_addr_c + 0x20000);
+ ut_asserteq(s, ram_end - alloc_addr_c - 0x20000);
+ s = lmb_get_free_size(&lmb, ram_end - 4);
+ ut_asserteq(s, 4);
+
+ return 0;
+}
+
+static int lib_test_lmb_get_free_size(struct unit_test_state *uts)
+{
+ int ret;
+
+ /* simulate 512 MiB RAM beginning at 1GiB */
+ ret = test_get_unreserved_size(uts, 0x40000000);
+ if (ret)
+ return ret;
+
+ /* simulate 512 MiB RAM beginning at 1.5GiB */
+ return test_get_unreserved_size(uts, 0xE0000000);
+}
+
+DM_TEST(lib_test_lmb_get_free_size,
+ DM_TESTF_SCAN_PDATA | DM_TESTF_SCAN_FDT);
diff --git a/test/lib/string.c b/test/lib/string.c
new file mode 100644
index 00000000..8e246ab4
--- /dev/null
+++ b/test/lib/string.c
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2019 Heinrich Schuchardt <xypron.glpk@gmx.de>
+ *
+ * Unit tests for memory functions
+ *
+ * The architecture dependent implementations run through different lines of
+ * code depending on the alignment and length of memory regions copied or set.
+ * This has to be considered in testing.
+ */
+
+#include <common.h>
+#include <command.h>
+#include <test/lib.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+/* Xor mask used for marking memory regions */
+#define MASK 0xA5
+/* Number of different alignment values */
+#define SWEEP 16
+/* Allow for copying up to 32 bytes */
+#define BUFLEN (SWEEP + 33)
+
+/**
+ * init_buffer() - initialize buffer
+ *
+ * The buffer is filled with incrementing values xor'ed with the mask.
+ *
+ * @buf: buffer
+ * @mask: xor mask
+ */
+static void init_buffer(u8 buf[], u8 mask)
+{
+ int i;
+
+ for (i = 0; i < BUFLEN; ++i)
+ buf[i] = i ^ mask;
+}
+
+/**
+ * test_memset() - test result of memset()
+ *
+ * @uts: unit test state
+ * @buf: buffer
+ * @mask: value set by memset()
+ * @offset: relative start of region changed by memset() in buffer
+ * @len: length of region changed by memset()
+ * Return: 0 = success, 1 = failure
+ */
+static int test_memset(struct unit_test_state *uts, u8 buf[], u8 mask,
+ int offset, int len)
+{
+ int i;
+
+ for (i = 0; i < BUFLEN; ++i) {
+ if (i < offset || i >= offset + len) {
+ ut_asserteq(i, buf[i]);
+ } else {
+ ut_asserteq(mask, buf[i]);
+ }
+ }
+ return 0;
+}
+
+/**
+ * lib_memset() - unit test for memset()
+ *
+ * Test memset() with varied alignment and length of the changed buffer.
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_memset(struct unit_test_state *uts)
+{
+ u8 buf[BUFLEN];
+ int offset, len;
+ void *ptr;
+
+ for (offset = 0; offset <= SWEEP; ++offset) {
+ for (len = 1; len < BUFLEN - SWEEP; ++len) {
+ init_buffer(buf, 0);
+ ptr = memset(buf + offset, MASK, len);
+ ut_asserteq_ptr(buf + offset, (u8 *)ptr);
+ if (test_memset(uts, buf, MASK, offset, len)) {
+ debug("%s: failure %d, %d\n",
+ __func__, offset, len);
+ return CMD_RET_FAILURE;
+ }
+ }
+ }
+ return 0;
+}
+
+LIB_TEST(lib_memset, 0);
+
+/**
+ * test_memmove() - test result of memcpy() or memmove()
+ *
+ * @uts: unit test state
+ * @buf: buffer
+ * @mask: xor mask used to initialize source buffer
+ * @offset1: relative start of copied region in source buffer
+ * @offset2: relative start of copied region in destination buffer
+ * @len: length of region changed by memset()
+ * Return: 0 = success, 1 = failure
+ */
+static int test_memmove(struct unit_test_state *uts, u8 buf[], u8 mask,
+ int offset1, int offset2, int len)
+{
+ int i;
+
+ for (i = 0; i < BUFLEN; ++i) {
+ if (i < offset2 || i >= offset2 + len) {
+ ut_asserteq(i, buf[i]);
+ } else {
+ ut_asserteq((i + offset1 - offset2) ^ mask, buf[i]);
+ }
+ }
+ return 0;
+}
+
+/**
+ * lib_memcpy() - unit test for memcpy()
+ *
+ * Test memcpy() with varied alignment and length of the copied buffer.
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_memcpy(struct unit_test_state *uts)
+{
+ u8 buf1[BUFLEN];
+ u8 buf2[BUFLEN];
+ int offset1, offset2, len;
+ void *ptr;
+
+ init_buffer(buf1, MASK);
+
+ for (offset1 = 0; offset1 <= SWEEP; ++offset1) {
+ for (offset2 = 0; offset2 <= SWEEP; ++offset2) {
+ for (len = 1; len < BUFLEN - SWEEP; ++len) {
+ init_buffer(buf2, 0);
+ ptr = memcpy(buf2 + offset2, buf1 + offset1,
+ len);
+ ut_asserteq_ptr(buf2 + offset2, (u8 *)ptr);
+ if (test_memmove(uts, buf2, MASK, offset1,
+ offset2, len)) {
+ debug("%s: failure %d, %d, %d\n",
+ __func__, offset1, offset2, len);
+ return CMD_RET_FAILURE;
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+LIB_TEST(lib_memcpy, 0);
+
+/**
+ * lib_memmove() - unit test for memmove()
+ *
+ * Test memmove() with varied alignment and length of the copied buffer.
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_memmove(struct unit_test_state *uts)
+{
+ u8 buf[BUFLEN];
+ int offset1, offset2, len;
+ void *ptr;
+
+ for (offset1 = 0; offset1 <= SWEEP; ++offset1) {
+ for (offset2 = 0; offset2 <= SWEEP; ++offset2) {
+ for (len = 1; len < BUFLEN - SWEEP; ++len) {
+ init_buffer(buf, 0);
+ ptr = memmove(buf + offset2, buf + offset1,
+ len);
+ ut_asserteq_ptr(buf + offset2, (u8 *)ptr);
+ if (test_memmove(uts, buf, 0, offset1, offset2,
+ len)) {
+ debug("%s: failure %d, %d, %d\n",
+ __func__, offset1, offset2, len);
+ return CMD_RET_FAILURE;
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+LIB_TEST(lib_memmove, 0);
diff --git a/test/lib/test_errno_str.c b/test/lib/test_errno_str.c
new file mode 100644
index 00000000..8a9f1fd9
--- /dev/null
+++ b/test/lib/test_errno_str.c
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2019 Heinrich Schuchardt <xypron.glpk@gmx.de>
+ *
+ * Unit tests for memory functions
+ *
+ * The architecture dependent implementations run through different lines of
+ * code depending on the alignment and length of memory regions copied or set.
+ * This has to be considered in testing.
+ */
+
+#include <common.h>
+#include <command.h>
+#include <errno.h>
+#include <test/lib.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+/**
+ * lib_errno_str() - unit test for errno_str()
+ *
+ * Test errno_str() with varied alignment and length of the copied buffer.
+ *
+ * @uts: unit test state
+ * Return: 0 = success, 1 = failure
+ */
+static int lib_errno_str(struct unit_test_state *uts)
+{
+ const char *msg;
+
+ msg = errno_str(1);
+ ut_asserteq_str("Success", msg);
+
+ msg = errno_str(0);
+ ut_asserteq_str("Success", msg);
+
+ msg = errno_str(-ENOMEM);
+ ut_asserteq_str("Out of memory", msg);
+
+ msg = errno_str(-99999);
+ ut_asserteq_str("Unknown error", msg);
+
+ return 0;
+}
+
+LIB_TEST(lib_errno_str, 0);
diff --git a/test/log/Makefile b/test/log/Makefile
new file mode 100644
index 00000000..e0d0a474
--- /dev/null
+++ b/test/log/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright (c) 2017 Google, Inc
+
+obj-$(CONFIG_LOG_TEST) += log_test.o
diff --git a/test/log/log_test.c b/test/log/log_test.c
new file mode 100644
index 00000000..febc2c12
--- /dev/null
+++ b/test/log/log_test.c
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Logging support test program
+ *
+ * Copyright (c) 2017 Google, Inc
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+
+/* emit some sample log records in different ways, for testing */
+static int log_run(enum uclass_id cat, const char *file)
+{
+ int i;
+
+ debug("debug\n");
+ for (i = LOGL_FIRST; i < LOGL_COUNT; i++) {
+ log(cat, i, "log %d\n", i);
+ _log(log_uc_cat(cat), i, file, 100 + i, "func", "_log %d\n",
+ i);
+ }
+
+ return 0;
+}
+
+static int log_test(int testnum)
+{
+ int ret;
+
+ printf("test %d\n", testnum);
+ switch (testnum) {
+ case 0: {
+ /* Check a category filter using the first category */
+ enum log_category_t cat_list[] = {
+ log_uc_cat(UCLASS_MMC), log_uc_cat(UCLASS_SPI),
+ LOGC_NONE, LOGC_END
+ };
+
+ ret = log_add_filter("console", cat_list, LOGL_MAX, NULL);
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_MMC, "file");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 1: {
+ /* Check a category filter using the second category */
+ enum log_category_t cat_list[] = {
+ log_uc_cat(UCLASS_MMC), log_uc_cat(UCLASS_SPI), LOGC_END
+ };
+
+ ret = log_add_filter("console", cat_list, LOGL_MAX, NULL);
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 2: {
+ /* Check a category filter that should block log entries */
+ enum log_category_t cat_list[] = {
+ log_uc_cat(UCLASS_MMC), LOGC_NONE, LOGC_END
+ };
+
+ ret = log_add_filter("console", cat_list, LOGL_MAX, NULL);
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 3: {
+ /* Check a passing file filter */
+ ret = log_add_filter("console", NULL, LOGL_MAX, "file");
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 4: {
+ /* Check a failing file filter */
+ ret = log_add_filter("console", NULL, LOGL_MAX, "file");
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file2");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 5: {
+ /* Check a passing file filter (second in list) */
+ ret = log_add_filter("console", NULL, LOGL_MAX, "file,file2");
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file2");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 6: {
+ /* Check a passing file filter */
+ ret = log_add_filter("console", NULL, LOGL_MAX,
+ "file,file2,log/log_test.c");
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file2");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 7: {
+ /* Check a log level filter */
+ ret = log_add_filter("console", NULL, LOGL_WARNING, NULL);
+ if (ret < 0)
+ return ret;
+ log_run(UCLASS_SPI, "file");
+ ret = log_remove_filter("console", ret);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 8: {
+ /* Check two filters, one of which passes everything */
+ int filt1, filt2;
+
+ ret = log_add_filter("console", NULL, LOGL_WARNING, NULL);
+ if (ret < 0)
+ return ret;
+ filt1 = ret;
+ ret = log_add_filter("console", NULL, LOGL_MAX, NULL);
+ if (ret < 0)
+ return ret;
+ filt2 = ret;
+ log_run(UCLASS_SPI, "file");
+ ret = log_remove_filter("console", filt1);
+ if (ret < 0)
+ return ret;
+ ret = log_remove_filter("console", filt2);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 9: {
+ /* Check three filters, which together pass everything */
+ int filt1, filt2, filt3;
+
+ ret = log_add_filter("console", NULL, LOGL_MAX, "file)");
+ if (ret < 0)
+ return ret;
+ filt1 = ret;
+ ret = log_add_filter("console", NULL, LOGL_MAX, "file2");
+ if (ret < 0)
+ return ret;
+ filt2 = ret;
+ ret = log_add_filter("console", NULL, LOGL_MAX,
+ "log/log_test.c");
+ if (ret < 0)
+ return ret;
+ filt3 = ret;
+ log_run(UCLASS_SPI, "file2");
+ ret = log_remove_filter("console", filt1);
+ if (ret < 0)
+ return ret;
+ ret = log_remove_filter("console", filt2);
+ if (ret < 0)
+ return ret;
+ ret = log_remove_filter("console", filt3);
+ if (ret < 0)
+ return ret;
+ break;
+ }
+ case 10: {
+ log_err("level %d\n", LOGL_EMERG);
+ log_err("level %d\n", LOGL_ALERT);
+ log_err("level %d\n", LOGL_CRIT);
+ log_err("level %d\n", LOGL_ERR);
+ log_warning("level %d\n", LOGL_WARNING);
+ log_notice("level %d\n", LOGL_NOTICE);
+ log_info("level %d\n", LOGL_INFO);
+ log_debug("level %d\n", LOGL_DEBUG);
+ log_content("level %d\n", LOGL_DEBUG_CONTENT);
+ log_io("level %d\n", LOGL_DEBUG_IO);
+ break;
+ }
+ }
+
+ return 0;
+}
+
+#ifdef CONFIG_LOG_TEST
+int do_log_test(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
+{
+ int testnum = 0;
+ int ret;
+
+ if (argc > 1)
+ testnum = simple_strtoul(argv[1], NULL, 10);
+
+ ret = log_test(testnum);
+ if (ret)
+ printf("Test failure (err=%d)\n", ret);
+
+ return ret ? CMD_RET_FAILURE : 0;
+}
+#endif
diff --git a/test/optee/Kconfig b/test/optee/Kconfig
new file mode 100644
index 00000000..2f6834aa
--- /dev/null
+++ b/test/optee/Kconfig
@@ -0,0 +1,7 @@
+config UT_OPTEE
+ bool "Enable OP-TEE Unit Tests"
+ depends on UNIT_TEST && OF_CONTROL && OPTEE
+ default y
+ help
+ This enables the 'ut optee' command which runs a series of unit
+ tests on the optee library code..
diff --git a/test/optee/Makefile b/test/optee/Makefile
new file mode 100644
index 00000000..8793fd7a
--- /dev/null
+++ b/test/optee/Makefile
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH
+
+# Test files
+obj-y += cmd_ut_optee.o
+
+DTC_FLAGS += -@
+
+# DT overlays
+obj-y += test-optee-base.dtb.o
+obj-y += test-optee-optee.dtb.o
+obj-y += test-optee-no-optee.dtb.o
diff --git a/test/optee/cmd_ut_optee.c b/test/optee/cmd_ut_optee.c
new file mode 100644
index 00000000..670682f3
--- /dev/null
+++ b/test/optee/cmd_ut_optee.c
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH
+ */
+
+#include <common.h>
+#include <command.h>
+#include <errno.h>
+#include <fdt_support.h>
+#include <malloc.h>
+#include <tee/optee.h>
+
+#include <linux/sizes.h>
+
+#include <test/ut.h>
+#include <test/optee.h>
+#include <test/suites.h>
+
+/* 4k ought to be enough for anybody */
+#define FDT_COPY_SIZE (4 * SZ_1K)
+
+extern u32 __dtb_test_optee_base_begin;
+extern u32 __dtb_test_optee_optee_begin;
+extern u32 __dtb_test_optee_no_optee_begin;
+
+static void *fdt;
+static bool expect_success;
+
+static int optee_fdt_firmware(struct unit_test_state *uts)
+{
+ const void *prop;
+ int offs, len;
+
+ offs = fdt_path_offset(fdt, "/firmware/optee");
+ ut_assert(expect_success ? offs >= 0 : offs < 0);
+
+ /* only continue if we have an optee node */
+ if (offs < 0)
+ return CMD_RET_SUCCESS;
+
+ prop = fdt_getprop(fdt, offs, "compatible", &len);
+ ut_assertok(strncmp((const char *)prop, "linaro,optee-tz", len));
+
+ prop = fdt_getprop(fdt, offs, "method", &len);
+ ut_assert(strncmp(prop, "hvc", 3) == 0 || strncmp(prop, "smc", 3) == 0);
+
+ return CMD_RET_SUCCESS;
+}
+OPTEE_TEST(optee_fdt_firmware, 0);
+
+static int optee_fdt_protected_memory(struct unit_test_state *uts)
+{
+ int offs, subnode;
+ bool found;
+
+ offs = fdt_path_offset(fdt, "/firmware/optee");
+ ut_assert(expect_success ? offs >= 0 : offs < 0);
+
+ /* only continue if we have an optee node */
+ if (offs < 0)
+ return CMD_RET_SUCCESS;
+
+ /* optee inserts its memory regions as reserved-memory nodes */
+ offs = fdt_subnode_offset(fdt, 0, "reserved-memory");
+ ut_assert(offs >= 0);
+
+ subnode = fdt_first_subnode(fdt, offs);
+ ut_assert(subnode);
+
+ found = 0;
+ while (subnode >= 0) {
+ const char *name = fdt_get_name(fdt, subnode, NULL);
+ struct fdt_resource res;
+
+ ut_assert(name);
+
+ /* only handle optee reservations */
+ if (strncmp(name, "optee", 5))
+ continue;
+
+ found = true;
+
+ /* check if this subnode has a reg property */
+ ut_assertok(fdt_get_resource(fdt, subnode, "reg", 0, &res));
+ subnode = fdt_next_subnode(fdt, subnode);
+ }
+
+ ut_assert(found);
+
+ return CMD_RET_SUCCESS;
+}
+OPTEE_TEST(optee_fdt_protected_memory, 0);
+
+int do_ut_optee(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test,
+ optee_test);
+ const int n_ents = ll_entry_count(struct unit_test, optee_test);
+ struct unit_test_state *uts;
+ void *fdt_optee = &__dtb_test_optee_optee_begin;
+ void *fdt_no_optee = &__dtb_test_optee_no_optee_begin;
+ void *fdt_base = &__dtb_test_optee_base_begin;
+ int ret = -ENOMEM;
+
+ uts = calloc(1, sizeof(*uts));
+ if (!uts)
+ return -ENOMEM;
+
+ ut_assertok(fdt_check_header(fdt_base));
+ ut_assertok(fdt_check_header(fdt_optee));
+ ut_assertok(fdt_check_header(fdt_no_optee));
+
+ fdt = malloc(FDT_COPY_SIZE);
+ if (!fdt)
+ return ret;
+
+ /*
+ * Resize the FDT to 4k so that we have room to operate on
+ *
+ * (and relocate it since the memory might be mapped
+ * read-only)
+ */
+ ut_assertok(fdt_open_into(fdt_base, fdt, FDT_COPY_SIZE));
+
+ /*
+ * (1) Try to copy optee nodes from empty dt.
+ * This should still run successfully.
+ */
+ ut_assertok(optee_copy_fdt_nodes(fdt_no_optee, fdt));
+
+ expect_success = false;
+ ret = cmd_ut_category("optee", tests, n_ents, argc, argv);
+
+ /* (2) Try to copy optee nodes from prefilled dt */
+ ut_assertok(optee_copy_fdt_nodes(fdt_optee, fdt));
+
+ expect_success = true;
+ ret = cmd_ut_category("optee", tests, n_ents, argc, argv);
+
+ /* (3) Try to copy OP-TEE nodes into a already filled DT */
+ ut_assertok(fdt_open_into(fdt_optee, fdt, FDT_COPY_SIZE));
+ ut_assertok(optee_copy_fdt_nodes(fdt_optee, fdt));
+
+ expect_success = true;
+ ret = cmd_ut_category("optee", tests, n_ents, argc, argv);
+
+ free(fdt);
+ return ret;
+}
diff --git a/test/optee/test-optee-base.dts b/test/optee/test-optee-base.dts
new file mode 100644
index 00000000..3c1d0c60
--- /dev/null
+++ b/test/optee/test-optee-base.dts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH
+ */
+
+/dts-v1/;
+
+/ {
+ #address-cells = <2>;
+ #size-cells = <2>;
+};
+
+
diff --git a/test/optee/test-optee-no-optee.dts b/test/optee/test-optee-no-optee.dts
new file mode 100644
index 00000000..3c1d0c60
--- /dev/null
+++ b/test/optee/test-optee-no-optee.dts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH
+ */
+
+/dts-v1/;
+
+/ {
+ #address-cells = <2>;
+ #size-cells = <2>;
+};
+
+
diff --git a/test/optee/test-optee-optee.dts b/test/optee/test-optee-optee.dts
new file mode 100644
index 00000000..11e26a27
--- /dev/null
+++ b/test/optee/test-optee-optee.dts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH
+ */
+
+/dts-v1/;
+
+/ {
+ #address-cells = <2>;
+ #size-cells = <2>;
+
+ firmware {
+ optee {
+ compatible = "linaro,optee-tz";
+ method = "smc";
+ };
+ };
+
+ reserved-memory {
+ #address-cells = <2>;
+ #size-cells = <2>;
+ ranges;
+
+ optee_shm@32000000 {
+ reg = <0x00 0x32000000 0x00 0x400000>;
+ };
+
+ optee_core@30000000 {
+ reg = <0x00 0x30000000 0x00 0x2000000>;
+ };
+ };
+};
diff --git a/test/overlay/Kconfig b/test/overlay/Kconfig
new file mode 100644
index 00000000..a4f15441
--- /dev/null
+++ b/test/overlay/Kconfig
@@ -0,0 +1,10 @@
+config UT_OVERLAY
+ bool "Enable Device Tree Overlays Unit Tests"
+ depends on UNIT_TEST && OF_CONTROL
+ default y
+ select OF_LIBFDT_OVERLAY
+ help
+ This enables the 'ut overlay' command which runs a series of unit
+ tests on the fdt overlay code.
+ If all is well then all tests pass although there will be a few
+ messages printed along the way.
diff --git a/test/overlay/Makefile b/test/overlay/Makefile
new file mode 100644
index 00000000..2deec929
--- /dev/null
+++ b/test/overlay/Makefile
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright (c) 2016 NextThing Co
+# Copyright (c) 2016 Free Electrons
+
+# Test files
+obj-y += cmd_ut_overlay.o
+
+DTC_FLAGS += -@
+
+# DT overlays
+obj-y += test-fdt-base.dtb.o
+obj-y += test-fdt-overlay.dtb.o
+obj-y += test-fdt-overlay-stacked.dtb.o
diff --git a/test/overlay/cmd_ut_overlay.c b/test/overlay/cmd_ut_overlay.c
new file mode 100644
index 00000000..fc2491d0
--- /dev/null
+++ b/test/overlay/cmd_ut_overlay.c
@@ -0,0 +1,284 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2016 NextThing Co
+ * Copyright (c) 2016 Free Electrons
+ */
+
+#include <common.h>
+#include <command.h>
+#include <errno.h>
+#include <fdt_support.h>
+#include <malloc.h>
+
+#include <linux/sizes.h>
+
+#include <test/ut.h>
+#include <test/overlay.h>
+#include <test/suites.h>
+
+/* 4k ought to be enough for anybody */
+#define FDT_COPY_SIZE (4 * SZ_1K)
+
+extern u32 __dtb_test_fdt_base_begin;
+extern u32 __dtb_test_fdt_overlay_begin;
+extern u32 __dtb_test_fdt_overlay_stacked_begin;
+
+static void *fdt;
+
+static int ut_fdt_getprop_u32_by_index(void *fdt, const char *path,
+ const char *name, int index,
+ u32 *out)
+{
+ const fdt32_t *val;
+ int node_off;
+ int len;
+
+ node_off = fdt_path_offset(fdt, path);
+ if (node_off < 0)
+ return node_off;
+
+ val = fdt_getprop(fdt, node_off, name, &len);
+ if (!val || (len < (sizeof(uint32_t) * (index + 1))))
+ return -FDT_ERR_NOTFOUND;
+
+ *out = fdt32_to_cpu(*(val + index));
+
+ return 0;
+}
+
+static int ut_fdt_getprop_u32(void *fdt, const char *path, const char *name,
+ u32 *out)
+{
+ return ut_fdt_getprop_u32_by_index(fdt, path, name, 0, out);
+}
+
+static int fdt_getprop_str(void *fdt, const char *path, const char *name,
+ const char **out)
+{
+ int node_off;
+ int len;
+
+ node_off = fdt_path_offset(fdt, path);
+ if (node_off < 0)
+ return node_off;
+
+ *out = fdt_stringlist_get(fdt, node_off, name, 0, &len);
+
+ return len < 0 ? len : 0;
+}
+
+static int fdt_overlay_change_int_property(struct unit_test_state *uts)
+{
+ u32 val = 0;
+
+ ut_assertok(ut_fdt_getprop_u32(fdt, "/test-node", "test-int-property",
+ &val));
+ ut_asserteq(43, val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_change_int_property, 0);
+
+static int fdt_overlay_change_str_property(struct unit_test_state *uts)
+{
+ const char *val = NULL;
+
+ ut_assertok(fdt_getprop_str(fdt, "/test-node", "test-str-property",
+ &val));
+ ut_asserteq_str("foobar", val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_change_str_property, 0);
+
+static int fdt_overlay_add_str_property(struct unit_test_state *uts)
+{
+ const char *val = NULL;
+
+ ut_assertok(fdt_getprop_str(fdt, "/test-node", "test-str-property-2",
+ &val));
+ ut_asserteq_str("foobar2", val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_add_str_property, 0);
+
+static int fdt_overlay_add_node_by_phandle(struct unit_test_state *uts)
+{
+ int off;
+
+ off = fdt_path_offset(fdt, "/test-node/new-node");
+ ut_assert(off >= 0);
+
+ ut_assertnonnull(fdt_getprop(fdt, off, "new-property", NULL));
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_add_node_by_phandle, 0);
+
+static int fdt_overlay_add_node_by_path(struct unit_test_state *uts)
+{
+ int off;
+
+ off = fdt_path_offset(fdt, "/new-node");
+ ut_assert(off >= 0);
+
+ ut_assertnonnull(fdt_getprop(fdt, off, "new-property", NULL));
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_add_node_by_path, 0);
+
+static int fdt_overlay_add_subnode_property(struct unit_test_state *uts)
+{
+ int off;
+
+ off = fdt_path_offset(fdt, "/test-node/sub-test-node");
+ ut_assert(off >= 0);
+
+ ut_assertnonnull(fdt_getprop(fdt, off, "sub-test-property", NULL));
+ ut_assertnonnull(fdt_getprop(fdt, off, "new-sub-test-property", NULL));
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_add_subnode_property, 0);
+
+static int fdt_overlay_local_phandle(struct unit_test_state *uts)
+{
+ uint32_t local_phandle;
+ u32 val = 0;
+ int off;
+
+ off = fdt_path_offset(fdt, "/new-local-node");
+ ut_assert(off >= 0);
+
+ local_phandle = fdt_get_phandle(fdt, off);
+ ut_assert(local_phandle);
+
+ ut_assertok(ut_fdt_getprop_u32_by_index(fdt, "/", "test-several-phandle",
+ 0, &val));
+ ut_asserteq(local_phandle, val);
+
+ ut_assertok(ut_fdt_getprop_u32_by_index(fdt, "/", "test-several-phandle",
+ 1, &val));
+ ut_asserteq(local_phandle, val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_local_phandle, 0);
+
+static int fdt_overlay_local_phandles(struct unit_test_state *uts)
+{
+ uint32_t local_phandle, test_phandle;
+ u32 val = 0;
+ int off;
+
+ off = fdt_path_offset(fdt, "/new-local-node");
+ ut_assert(off >= 0);
+
+ local_phandle = fdt_get_phandle(fdt, off);
+ ut_assert(local_phandle);
+
+ off = fdt_path_offset(fdt, "/test-node");
+ ut_assert(off >= 0);
+
+ test_phandle = fdt_get_phandle(fdt, off);
+ ut_assert(test_phandle);
+
+ ut_assertok(ut_fdt_getprop_u32_by_index(fdt, "/", "test-phandle", 0,
+ &val));
+ ut_asserteq(test_phandle, val);
+
+ ut_assertok(ut_fdt_getprop_u32_by_index(fdt, "/", "test-phandle", 1,
+ &val));
+ ut_asserteq(local_phandle, val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_local_phandles, 0);
+
+static int fdt_overlay_stacked(struct unit_test_state *uts)
+{
+ u32 val = 0;
+
+ ut_assertok(ut_fdt_getprop_u32(fdt, "/new-local-node",
+ "stacked-test-int-property", &val));
+ ut_asserteq(43, val);
+
+ return CMD_RET_SUCCESS;
+}
+OVERLAY_TEST(fdt_overlay_stacked, 0);
+
+int do_ut_overlay(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test,
+ overlay_test);
+ const int n_ents = ll_entry_count(struct unit_test, overlay_test);
+ struct unit_test_state *uts;
+ void *fdt_base = &__dtb_test_fdt_base_begin;
+ void *fdt_overlay = &__dtb_test_fdt_overlay_begin;
+ void *fdt_overlay_stacked = &__dtb_test_fdt_overlay_stacked_begin;
+ void *fdt_overlay_copy, *fdt_overlay_stacked_copy;
+ int ret = -ENOMEM;
+
+ uts = calloc(1, sizeof(*uts));
+ if (!uts)
+ return -ENOMEM;
+
+ ut_assertok(fdt_check_header(fdt_base));
+ ut_assertok(fdt_check_header(fdt_overlay));
+
+ fdt = malloc(FDT_COPY_SIZE);
+ if (!fdt)
+ goto err1;
+
+ fdt_overlay_copy = malloc(FDT_COPY_SIZE);
+ if (!fdt_overlay_copy)
+ goto err2;
+
+ fdt_overlay_stacked_copy = malloc(FDT_COPY_SIZE);
+ if (!fdt_overlay_stacked_copy)
+ goto err3;
+
+ /*
+ * Resize the FDT to 4k so that we have room to operate on
+ *
+ * (and relocate it since the memory might be mapped
+ * read-only)
+ */
+ ut_assertok(fdt_open_into(fdt_base, fdt, FDT_COPY_SIZE));
+
+ /*
+ * Resize the overlay to 4k so that we have room to operate on
+ *
+ * (and relocate it since the memory might be mapped
+ * read-only)
+ */
+ ut_assertok(fdt_open_into(fdt_overlay, fdt_overlay_copy,
+ FDT_COPY_SIZE));
+
+ /*
+ * Resize the stacked overlay to 4k so that we have room to operate on
+ *
+ * (and relocate it since the memory might be mapped
+ * read-only)
+ */
+ ut_assertok(fdt_open_into(fdt_overlay_stacked, fdt_overlay_stacked_copy,
+ FDT_COPY_SIZE));
+
+ /* Apply the overlay */
+ ut_assertok(fdt_overlay_apply(fdt, fdt_overlay_copy));
+
+ /* Apply the stacked overlay */
+ ut_assertok(fdt_overlay_apply(fdt, fdt_overlay_stacked_copy));
+
+ ret = cmd_ut_category("overlay", tests, n_ents, argc, argv);
+
+ free(fdt_overlay_stacked_copy);
+err3:
+ free(fdt_overlay_copy);
+err2:
+ free(fdt);
+err1:
+ return ret;
+}
diff --git a/test/overlay/test-fdt-base.dts b/test/overlay/test-fdt-base.dts
new file mode 100644
index 00000000..38278334
--- /dev/null
+++ b/test/overlay/test-fdt-base.dts
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2016 NextThing Co
+ * Copyright (c) 2016 Free Electrons
+ */
+
+/dts-v1/;
+
+/ {
+ test: test-node {
+ test-int-property = <42>;
+ test-str-property = "foo";
+
+ subtest: sub-test-node {
+ sub-test-property;
+ };
+ };
+};
+
+
diff --git a/test/overlay/test-fdt-overlay-stacked.dts b/test/overlay/test-fdt-overlay-stacked.dts
new file mode 100644
index 00000000..6411adec
--- /dev/null
+++ b/test/overlay/test-fdt-overlay-stacked.dts
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2016 NextThing Co
+ * Copyright (c) 2016 Free Electrons
+ * Copyright (c) 2018 Konsulko Group
+ */
+
+/dts-v1/;
+/plugin/;
+
+/ {
+ /* Test that we can reference an overlay symbol */
+ fragment@0 {
+ target = <&local>;
+
+ __overlay__ {
+ stacked-test-int-property = <43>;
+ };
+ };
+};
diff --git a/test/overlay/test-fdt-overlay.dts b/test/overlay/test-fdt-overlay.dts
new file mode 100644
index 00000000..5a21b346
--- /dev/null
+++ b/test/overlay/test-fdt-overlay.dts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2016 NextThing Co
+ * Copyright (c) 2016 Free Electrons
+ */
+
+/dts-v1/;
+/plugin/;
+
+/ {
+ /* Test that we can change an int by another */
+ fragment@0 {
+ target = <&test>;
+
+ __overlay__ {
+ test-int-property = <43>;
+ };
+ };
+
+ /* Test that we can replace a string by a longer one */
+ fragment@1 {
+ target = <&test>;
+
+ __overlay__ {
+ test-str-property = "foobar";
+ };
+ };
+
+ /* Test that we add a new property */
+ fragment@2 {
+ target = <&test>;
+
+ __overlay__ {
+ test-str-property-2 = "foobar2";
+ };
+ };
+
+ /* Test that we add a new node (by phandle) */
+ fragment@3 {
+ target = <&test>;
+
+ __overlay__ {
+ new-node {
+ new-property;
+ };
+ };
+ };
+
+ /* Test that we add a new node (by path) */
+ fragment@4 {
+ target-path = "/";
+
+ __overlay__ {
+ new-node {
+ new-property;
+ };
+ };
+ };
+
+ fragment@5 {
+ target-path = "/";
+
+ __overlay__ {
+ local: new-local-node {
+ new-property;
+ };
+ };
+ };
+
+ fragment@6 {
+ target-path = "/";
+
+ __overlay__ {
+ test-phandle = <&test>, <&local>;
+ };
+ };
+
+ fragment@7 {
+ target-path = "/";
+
+ __overlay__ {
+ test-several-phandle = <&local>, <&local>;
+ };
+ };
+
+ fragment@8 {
+ target = <&test>;
+
+ __overlay__ {
+ sub-test-node {
+ new-sub-test-property;
+ };
+ };
+ };
+};
diff --git a/test/print_ut.c b/test/print_ut.c
new file mode 100644
index 00000000..a3b9974a
--- /dev/null
+++ b/test/print_ut.c
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2012, The Chromium Authors
+ */
+
+#define DEBUG
+
+#include <common.h>
+#if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD)
+#include <efi_api.h>
+#endif
+#include <display_options.h>
+#include <version.h>
+
+#define FAKE_BUILD_TAG "jenkins-u-boot-denx_uboot_dm-master-build-aarch64" \
+ "and a lot more text to come"
+
+/* Test printing GUIDs */
+static void guid_ut_print(void)
+{
+#if CONFIG_IS_ENABLED(LIB_UUID)
+ unsigned char guid[16] = {
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
+ };
+ char str[40];
+
+ sprintf(str, "%pUb", guid);
+ assert(!strcmp("01020304-0506-0708-090a-0b0c0d0e0f10", str));
+ sprintf(str, "%pUB", guid);
+ assert(!strcmp("01020304-0506-0708-090A-0B0C0D0E0F10", str));
+ sprintf(str, "%pUl", guid);
+ assert(!strcmp("04030201-0605-0807-090a-0b0c0d0e0f10", str));
+ sprintf(str, "%pUL", guid);
+ assert(!strcmp("04030201-0605-0807-090A-0B0C0D0E0F10", str));
+#endif
+}
+
+/* Test efi_loader specific printing */
+static void efi_ut_print(void)
+{
+#if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD)
+ char str[10];
+ u8 buf[sizeof(struct efi_device_path_sd_mmc_path) +
+ sizeof(struct efi_device_path)];
+ u8 *pos = buf;
+ struct efi_device_path *dp_end;
+ struct efi_device_path_sd_mmc_path *dp_sd =
+ (struct efi_device_path_sd_mmc_path *)pos;
+
+ /* Create a device path for an SD card */
+ dp_sd->dp.type = DEVICE_PATH_TYPE_MESSAGING_DEVICE;
+ dp_sd->dp.sub_type = DEVICE_PATH_SUB_TYPE_MSG_SD;
+ dp_sd->dp.length = sizeof(struct efi_device_path_sd_mmc_path);
+ dp_sd->slot_number = 3;
+ pos += sizeof(struct efi_device_path_sd_mmc_path);
+ /* Append end node */
+ dp_end = (struct efi_device_path *)pos;
+ dp_end->type = DEVICE_PATH_TYPE_END;
+ dp_end->sub_type = DEVICE_PATH_SUB_TYPE_END;
+ dp_end->length = sizeof(struct efi_device_path);
+
+ snprintf(str, sizeof(str), "_%pD_", buf);
+ assert(!strcmp("_/SD(3)_", str));
+
+ /* NULL device path */
+ snprintf(str, sizeof(str), "_%pD_", NULL);
+ assert(!strcmp("_<NULL>_", str));
+#endif
+}
+
+static int do_ut_print(cmd_tbl_t *cmdtp, int flag, int argc,
+ char *const argv[])
+{
+ char big_str[400];
+ int big_str_len;
+ char str[10], *s;
+ int len;
+
+ printf("%s: Testing print\n", __func__);
+
+ snprintf(str, sizeof(str), "testing");
+ assert(!strcmp("testing", str));
+
+ snprintf(str, sizeof(str), "testing but too long");
+ assert(!strcmp("testing b", str));
+
+ snprintf(str, 1, "testing none");
+ assert(!strcmp("", str));
+
+ *str = 'x';
+ snprintf(str, 0, "testing none");
+ assert(*str == 'x');
+
+ sprintf(big_str, "_%ls_", L"foo");
+ assert(!strcmp("_foo_", big_str));
+
+ /* Test the banner function */
+ s = display_options_get_banner(true, str, sizeof(str));
+ assert(s == str);
+ assert(!strcmp("\n\nU-Boo\n\n", s));
+
+ /* Assert that we do not overwrite memory before the buffer */
+ str[0] = '`';
+ s = display_options_get_banner(true, str + 1, 1);
+ assert(s == str + 1);
+ assert(!strcmp("`", str));
+
+ str[0] = '~';
+ s = display_options_get_banner(true, str + 1, 2);
+ assert(s == str + 1);
+ assert(!strcmp("~\n", str));
+
+ /* The last two characters are set to \n\n for all buffer sizes > 2 */
+ s = display_options_get_banner(false, str, sizeof(str));
+ assert(s == str);
+ assert(!strcmp("U-Boot \n\n", s));
+
+ /* Give it enough space for some of the version */
+ big_str_len = strlen(version_string) - 5;
+ s = display_options_get_banner_priv(false, FAKE_BUILD_TAG, big_str,
+ big_str_len);
+ assert(s == big_str);
+ assert(!strncmp(version_string, s, big_str_len - 3));
+ assert(!strcmp("\n\n", s + big_str_len - 3));
+
+ /* Give it enough space for the version and some of the build tag */
+ big_str_len = strlen(version_string) + 9 + 20;
+ s = display_options_get_banner_priv(false, FAKE_BUILD_TAG, big_str,
+ big_str_len);
+ assert(s == big_str);
+ len = strlen(version_string);
+ assert(!strncmp(version_string, s, len));
+ assert(!strncmp(", Build: ", s + len, 9));
+ assert(!strncmp(FAKE_BUILD_TAG, s + 9 + len, 12));
+ assert(!strcmp("\n\n", s + big_str_len - 3));
+
+ /* Test efi_loader specific printing */
+ efi_ut_print();
+
+ /* Test printing GUIDs */
+ guid_ut_print();
+
+ printf("%s: Everything went swimmingly\n", __func__);
+ return 0;
+}
+
+U_BOOT_CMD(
+ ut_print, 1, 1, do_ut_print,
+ "Very basic test of printf(), etc.",
+ ""
+);
diff --git a/test/py/.gitignore b/test/py/.gitignore
new file mode 100644
index 00000000..0d20b648
--- /dev/null
+++ b/test/py/.gitignore
@@ -0,0 +1 @@
+*.pyc
diff --git a/test/py/README.md b/test/py/README.md
new file mode 100644
index 00000000..3cbe01b7
--- /dev/null
+++ b/test/py/README.md
@@ -0,0 +1,370 @@
+# U-Boot pytest suite
+
+## Introduction
+
+This tool aims to test U-Boot by executing U-Boot shell commands using the
+console interface. A single top-level script exists to execute or attach to the
+U-Boot console, run the entire script of tests against it, and summarize the
+results. Advantages of this approach are:
+
+- Testing is performed in the same way a user or script would interact with
+ U-Boot; there can be no disconnect.
+- There is no need to write or embed test-related code into U-Boot itself.
+ It is asserted that writing test-related code in Python is simpler and more
+ flexible than writing it all in C.
+- It is reasonably simple to interact with U-Boot in this way.
+
+## Requirements
+
+The test suite is implemented using pytest. Interaction with the U-Boot console
+involves executing some binary and interacting with its stdin/stdout. You will
+need to implement various "hook" scripts that are called by the test suite at
+the appropriate time.
+
+In order to run the testsuite at a minimum we require that both python3 and
+pip for python3 be installed. All of the required python modules are
+described in the requirements.txt file in this directory and can be installed
+with the command ```pip install -r requirements.txt```
+
+In order to execute certain tests on their supported platforms other tools
+will be required. The following is an incomplete list:
+
+| Package |
+| -------------- |
+| gdisk |
+| dfu-util |
+| dtc |
+| openssl |
+| sudo OR guestmount |
+| e2fsprogs |
+| dosfstools |
+
+Please use the apporirate commands for your distribution to match these tools
+up with the package that provides them.
+
+The test script supports either:
+
+- Executing a sandbox port of U-Boot on the local machine as a sub-process,
+ and interacting with it over stdin/stdout.
+- Executing an external "hook" scripts to flash a U-Boot binary onto a
+ physical board, attach to the board's console stream, and reset the board.
+ Further details are described later.
+
+### Using `virtualenv` to provide requirements
+
+The recommended way to run the test suite, in order to ensure reproducibility
+is to use `virtualenv` to set up the necessary environment. This can be done
+via the following commands:
+
+```bash
+$ cd /path/to/u-boot
+$ sudo apt-get install python3 python3-virtualenv
+$ virtualenv -p /usr/bin/python3 venv
+$ . ./venv/bin/activate
+$ pip install -r test/py/requirements.txt
+```
+
+## Testing sandbox
+
+To run the testsuite on the sandbox port (U-Boot built as a native user-space
+application), simply execute:
+
+```
+./test/py/test.py --bd sandbox --build
+```
+
+The `--bd` option tells the test suite which board type is being tested. This
+lets the test suite know which features the board has, and hence exactly what
+can be tested.
+
+The `--build` option tells U-Boot to compile U-Boot. Alternatively, you may
+omit this option and build U-Boot yourself, in whatever way you choose, before
+running the test script.
+
+The test script will attach to U-Boot, execute all valid tests for the board,
+then print a summary of the test process. A complete log of the test session
+will be written to `${build_dir}/test-log.html`. This is best viewed in a web
+browser, but may be read directly as plain text, perhaps with the aid of the
+`html2text` utility.
+
+### Testing under a debugger
+
+If you need to run sandbox under a debugger, you may pass the command-line
+option `--gdbserver COMM`. This causes two things to happens:
+
+- Instead of running U-Boot directly, it will be run under gdbserver, with
+ debug communication via the channel `COMM`. You can attach a debugger to the
+ sandbox process in order to debug it. See `man gdbserver` and the example
+ below for details of valid values for `COMM`.
+- All timeouts in tests are disabled, allowing U-Boot an arbitrary amount of
+ time to execute commands. This is useful if U-Boot is stopped at a breakpoint
+ during debugging.
+
+A usage example is:
+
+Window 1:
+```shell
+./test/py/test.py --bd sandbox --gdbserver localhost:1234
+```
+
+Window 2:
+```shell
+gdb ./build-sandbox/u-boot -ex 'target remote localhost:1234'
+```
+
+Alternatively, you could leave off the `-ex` option and type the command
+manually into gdb once it starts.
+
+You can use any debugger you wish, so long as it speaks the gdb remote
+protocol, or any graphical wrapper around gdb.
+
+Some tests deliberately cause the sandbox process to exit, e.g. to test the
+reset command, or sandbox's CTRL-C handling. When this happens, you will need
+to attach the debugger to the new sandbox instance. If these tests are not
+relevant to your debugging session, you can skip them using pytest's -k
+command-line option; see the next section.
+
+## Command-line options
+
+- `--board-type`, `--bd`, `-B` set the type of the board to be tested. For
+ example, `sandbox` or `seaboard`.
+- `--board-identity`, `--id` set the identity of the board to be tested.
+ This allows differentiation between multiple instances of the same type of
+ physical board that are attached to the same host machine. This parameter is
+ not interpreted by the test script in any way, but rather is simply passed
+ to the hook scripts described below, and may be used in any site-specific
+ way deemed necessary.
+- `--build` indicates that the test script should compile U-Boot itself
+ before running the tests. If using this option, make sure that any
+ environment variables required by the build process are already set, such as
+ `$CROSS_COMPILE`.
+- `--build-dir` sets the directory containing the compiled U-Boot binaries.
+ If omitted, this is `${source_dir}/build-${board_type}`.
+- `--result-dir` sets the directory to write results, such as log files,
+ into. If omitted, the build directory is used.
+- `--persistent-data-dir` sets the directory used to store persistent test
+ data. This is test data that may be re-used across test runs, such as file-
+ system images.
+
+`pytest` also implements a number of its own command-line options. Commonly used
+options are mentioned below. Please see `pytest` documentation for complete
+details. Execute `py.test --version` for a brief summary. Note that U-Boot's
+test.py script passes all command-line arguments directly to `pytest` for
+processing.
+
+- `-k` selects which tests to run. The default is to run all known tests. This
+ option takes a single argument which is used to filter test names. Simple
+ logical operators are supported. For example:
+ - `'ums'` runs only tests with "ums" in their name.
+ - `'ut_dm'` runs only tests with "ut_dm" in their name. Note that in this
+ case, "ut_dm" is a parameter to a test rather than the test name. The full
+ test name is e.g. "test_ut[ut_dm_leak]".
+ - `'not reset'` runs everything except tests with "reset" in their name.
+ - `'ut or hush'` runs only tests with "ut" or "hush" in their name.
+ - `'not (ut or hush)'` runs everything except tests with "ut" or "hush" in
+ their name.
+- `-s` prevents pytest from hiding a test's stdout. This allows you to see
+ U-Boot's console log in real time on pytest's stdout.
+
+## Testing real hardware
+
+The tools and techniques used to interact with real hardware will vary
+radically between different host and target systems, and the whims of the user.
+For this reason, the test suite does not attempt to directly interact with real
+hardware in any way. Rather, it executes a standardized set of "hook" scripts
+via `$PATH`. These scripts implement certain actions on behalf of the test
+suite. This keeps the test suite simple and isolated from system variances
+unrelated to U-Boot features.
+
+### Hook scripts
+
+#### Environment variables
+
+The following environment variables are set when running hook scripts:
+
+- `UBOOT_BOARD_TYPE` the board type being tested.
+- `UBOOT_BOARD_IDENTITY` the board identity being tested, or `na` if none was
+ specified.
+- `UBOOT_SOURCE_DIR` the U-Boot source directory.
+- `UBOOT_TEST_PY_DIR` the full path to `test/py/` in the source directory.
+- `UBOOT_BUILD_DIR` the U-Boot build directory.
+- `UBOOT_RESULT_DIR` the test result directory.
+- `UBOOT_PERSISTENT_DATA_DIR` the test persistent data directory.
+
+#### `u-boot-test-console`
+
+This script provides access to the U-Boot console. The script's stdin/stdout
+should be connected to the board's console. This process should continue to run
+indefinitely, until killed. The test suite will run this script in parallel
+with all other hooks.
+
+This script may be implemented e.g. by exec()ing `cu`, `kermit`, `conmux`, etc.
+
+If you are able to run U-Boot under a hardware simulator such as qemu, then
+you would likely spawn that simulator from this script. However, note that
+`u-boot-test-reset` may be called multiple times per test script run, and must
+cause U-Boot to start execution from scratch each time. Hopefully your
+simulator includes a virtual reset button! If not, you can launch the
+simulator from `u-boot-test-reset` instead, while arranging for this console
+process to always communicate with the current simulator instance.
+
+#### `u-boot-test-flash`
+
+Prior to running the test suite against a board, some arrangement must be made
+so that the board executes the particular U-Boot binary to be tested. Often,
+this involves writing the U-Boot binary to the board's flash ROM. The test
+suite calls this hook script for that purpose.
+
+This script should perform the entire flashing process synchronously; the
+script should only exit once flashing is complete, and a board reset will
+cause the newly flashed U-Boot binary to be executed.
+
+It is conceivable that this script will do nothing. This might be useful in
+the following cases:
+
+- Some other process has already written the desired U-Boot binary into the
+ board's flash prior to running the test suite.
+- The board allows U-Boot to be downloaded directly into RAM, and executed
+ from there. Use of this feature will reduce wear on the board's flash, so
+ may be preferable if available, and if cold boot testing of U-Boot is not
+ required. If this feature is used, the `u-boot-test-reset` script should
+ perform this download, since the board could conceivably be reset multiple
+ times in a single test run.
+
+It is up to the user to determine if those situations exist, and to code this
+hook script appropriately.
+
+This script will typically be implemented by calling out to some SoC- or
+board-specific vendor flashing utility.
+
+#### `u-boot-test-reset`
+
+Whenever the test suite needs to reset the target board, this script is
+executed. This is guaranteed to happen at least once, prior to executing the
+first test function. If any test fails, the test infra-structure will execute
+this script again to restore U-Boot to an operational state before running the
+next test function.
+
+This script will likely be implemented by communicating with some form of
+relay or electronic switch attached to the board's reset signal.
+
+The semantics of this script require that when it is executed, U-Boot will
+start running from scratch. If the U-Boot binary to be tested has been written
+to flash, pulsing the board's reset signal is likely all this script need do.
+However, in some scenarios, this script may perform other actions. For
+example, it may call out to some SoC- or board-specific vendor utility in order
+to download the U-Boot binary directly into RAM and execute it. This would
+avoid the need for `u-boot-test-flash` to actually write U-Boot to flash, thus
+saving wear on the flash chip(s).
+
+#### Examples
+
+https://github.com/swarren/uboot-test-hooks contains some working example hook
+scripts, and may be useful as a reference when implementing hook scripts for
+your platform. These scripts are not considered part of U-Boot itself.
+
+### Board-type-specific configuration
+
+Each board has a different configuration and behaviour. Many of these
+differences can be automatically detected by parsing the `.config` file in the
+build directory. However, some differences can't yet be handled automatically.
+
+For each board, an optional Python module `u_boot_board_${board_type}` may exist
+to provide board-specific information to the test script. Any global value
+defined in these modules is available for use by any test function. The data
+contained in these scripts must be purely derived from U-Boot source code.
+Hence, these configuration files are part of the U-Boot source tree too.
+
+### Execution environment configuration
+
+Each user's hardware setup may enable testing different subsets of the features
+implemented by a particular board's configuration of U-Boot. For example, a
+U-Boot configuration may support USB device mode and USB Mass Storage, but this
+can only be tested if a USB cable is connected between the board and the host
+machine running the test script.
+
+For each board, optional Python modules `u_boot_boardenv_${board_type}` and
+`u_boot_boardenv_${board_type}_${board_identity}` may exist to provide
+board-specific and board-identity-specific information to the test script. Any
+global value defined in these modules is available for use by any test
+function. The data contained in these is specific to a particular user's
+hardware configuration. Hence, these configuration files are not part of the
+U-Boot source tree, and should be installed outside of the source tree. Users
+should set `$PYTHONPATH` prior to running the test script to allow these
+modules to be loaded.
+
+### Board module parameter usage
+
+The test scripts rely on the following variables being defined by the board
+module:
+
+- None at present.
+
+### U-Boot `.config` feature usage
+
+The test scripts rely on various U-Boot `.config` features, either directly in
+order to test those features, or indirectly in order to query information from
+the running U-Boot instance in order to test other features.
+
+One example is that testing of the `md` command requires knowledge of a RAM
+address to use for the test. This data is parsed from the output of the
+`bdinfo` command, and hence relies on CONFIG_CMD_BDI being enabled.
+
+For a complete list of dependencies, please search the test scripts for
+instances of:
+
+- `buildconfig.get(...`
+- `@pytest.mark.buildconfigspec(...`
+- `@pytest.mark.notbuildconfigspec(...`
+
+### Complete invocation example
+
+Assuming that you have installed the hook scripts into $HOME/ubtest/bin, and
+any required environment configuration Python modules into $HOME/ubtest/py,
+then you would likely invoke the test script as follows:
+
+If U-Boot has already been built:
+
+```bash
+PATH=$HOME/ubtest/bin:$PATH \
+ PYTHONPATH=${HOME}/ubtest/py/${HOSTNAME}:${PYTHONPATH} \
+ ./test/py/test.py --bd seaboard
+```
+
+If you want the test script to compile U-Boot for you too, then you likely
+need to set `$CROSS_COMPILE` to allow this, and invoke the test script as
+follow:
+
+```bash
+CROSS_COMPILE=arm-none-eabi- \
+ PATH=$HOME/ubtest/bin:$PATH \
+ PYTHONPATH=${HOME}/ubtest/py/${HOSTNAME}:${PYTHONPATH} \
+ ./test/py/test.py --bd seaboard --build
+```
+
+## Writing tests
+
+Please refer to the pytest documentation for details of writing pytest tests.
+Details specific to the U-Boot test suite are described below.
+
+A test fixture named `u_boot_console` should be used by each test function. This
+provides the means to interact with the U-Boot console, and retrieve board and
+environment configuration information.
+
+The function `u_boot_console.run_command()` executes a shell command on the
+U-Boot console, and returns all output from that command. This allows
+validation or interpretation of the command output. This function validates
+that certain strings are not seen on the U-Boot console. These include shell
+error messages and the U-Boot sign-on message (in order to detect unexpected
+board resets). See the source of `u_boot_console_base.py` for a complete list of
+"bad" strings. Some test scenarios are expected to trigger these strings. Use
+`u_boot_console.disable_check()` to temporarily disable checking for specific
+strings. See `test_unknown_cmd.py` for an example.
+
+Board- and board-environment configuration values may be accessed as sub-fields
+of the `u_boot_console.config` object, for example
+`u_boot_console.config.ram_base`.
+
+Build configuration values (from `.config`) may be accessed via the dictionary
+`u_boot_console.config.buildconfig`, with keys equal to the Kconfig variable
+names.
diff --git a/test/py/conftest.py b/test/py/conftest.py
new file mode 100644
index 00000000..bffee6b8
--- /dev/null
+++ b/test/py/conftest.py
@@ -0,0 +1,596 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Implementation of pytest run-time hook functions. These are invoked by
+# pytest at certain points during operation, e.g. startup, for each executed
+# test, at shutdown etc. These hooks perform functions such as:
+# - Parsing custom command-line options.
+# - Pullilng in user-specified board configuration.
+# - Creating the U-Boot console test fixture.
+# - Creating the HTML log file.
+# - Monitoring each test's results.
+# - Implementing custom pytest markers.
+
+import atexit
+import configparser
+import errno
+import io
+import os
+import os.path
+import pytest
+import re
+from _pytest.runner import runtestprotocol
+import sys
+
+# Globals: The HTML log file, and the connection to the U-Boot console.
+log = None
+console = None
+
+def mkdir_p(path):
+ """Create a directory path.
+
+ This includes creating any intermediate/parent directories. Any errors
+ caused due to already extant directories are ignored.
+
+ Args:
+ path: The directory path to create.
+
+ Returns:
+ Nothing.
+ """
+
+ try:
+ os.makedirs(path)
+ except OSError as exc:
+ if exc.errno == errno.EEXIST and os.path.isdir(path):
+ pass
+ else:
+ raise
+
+def pytest_addoption(parser):
+ """pytest hook: Add custom command-line options to the cmdline parser.
+
+ Args:
+ parser: The pytest command-line parser.
+
+ Returns:
+ Nothing.
+ """
+
+ parser.addoption('--build-dir', default=None,
+ help='U-Boot build directory (O=)')
+ parser.addoption('--result-dir', default=None,
+ help='U-Boot test result/tmp directory')
+ parser.addoption('--persistent-data-dir', default=None,
+ help='U-Boot test persistent generated data directory')
+ parser.addoption('--board-type', '--bd', '-B', default='sandbox',
+ help='U-Boot board type')
+ parser.addoption('--board-identity', '--id', default='na',
+ help='U-Boot board identity/instance')
+ parser.addoption('--build', default=False, action='store_true',
+ help='Compile U-Boot before running tests')
+ parser.addoption('--gdbserver', default=None,
+ help='Run sandbox under gdbserver. The argument is the channel '+
+ 'over which gdbserver should communicate, e.g. localhost:1234')
+
+def pytest_configure(config):
+ """pytest hook: Perform custom initialization at startup time.
+
+ Args:
+ config: The pytest configuration.
+
+ Returns:
+ Nothing.
+ """
+
+ global log
+ global console
+ global ubconfig
+
+ test_py_dir = os.path.dirname(os.path.abspath(__file__))
+ source_dir = os.path.dirname(os.path.dirname(test_py_dir))
+
+ board_type = config.getoption('board_type')
+ board_type_filename = board_type.replace('-', '_')
+
+ board_identity = config.getoption('board_identity')
+ board_identity_filename = board_identity.replace('-', '_')
+
+ build_dir = config.getoption('build_dir')
+ if not build_dir:
+ build_dir = source_dir + '/build-' + board_type
+ mkdir_p(build_dir)
+
+ result_dir = config.getoption('result_dir')
+ if not result_dir:
+ result_dir = build_dir
+ mkdir_p(result_dir)
+
+ persistent_data_dir = config.getoption('persistent_data_dir')
+ if not persistent_data_dir:
+ persistent_data_dir = build_dir + '/persistent-data'
+ mkdir_p(persistent_data_dir)
+
+ gdbserver = config.getoption('gdbserver')
+ if gdbserver and not board_type.startswith('sandbox'):
+ raise Exception('--gdbserver only supported with sandbox targets')
+
+ import multiplexed_log
+ log = multiplexed_log.Logfile(result_dir + '/test-log.html')
+
+ if config.getoption('build'):
+ if build_dir != source_dir:
+ o_opt = 'O=%s' % build_dir
+ else:
+ o_opt = ''
+ cmds = (
+ ['make', o_opt, '-s', board_type + '_defconfig'],
+ ['make', o_opt, '-s', '-j8'],
+ )
+ with log.section('make'):
+ runner = log.get_runner('make', sys.stdout)
+ for cmd in cmds:
+ runner.run(cmd, cwd=source_dir)
+ runner.close()
+ log.status_pass('OK')
+
+ class ArbitraryAttributeContainer(object):
+ pass
+
+ ubconfig = ArbitraryAttributeContainer()
+ ubconfig.brd = dict()
+ ubconfig.env = dict()
+
+ modules = [
+ (ubconfig.brd, 'u_boot_board_' + board_type_filename),
+ (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
+ (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
+ board_identity_filename),
+ ]
+ for (dict_to_fill, module_name) in modules:
+ try:
+ module = __import__(module_name)
+ except ImportError:
+ continue
+ dict_to_fill.update(module.__dict__)
+
+ ubconfig.buildconfig = dict()
+
+ for conf_file in ('.config', 'include/autoconf.mk'):
+ dot_config = build_dir + '/' + conf_file
+ if not os.path.exists(dot_config):
+ raise Exception(conf_file + ' does not exist; ' +
+ 'try passing --build option?')
+
+ with open(dot_config, 'rt') as f:
+ ini_str = '[root]\n' + f.read()
+ ini_sio = io.StringIO(ini_str)
+ parser = configparser.RawConfigParser()
+ parser.read_file(ini_sio)
+ ubconfig.buildconfig.update(parser.items('root'))
+
+ ubconfig.test_py_dir = test_py_dir
+ ubconfig.source_dir = source_dir
+ ubconfig.build_dir = build_dir
+ ubconfig.result_dir = result_dir
+ ubconfig.persistent_data_dir = persistent_data_dir
+ ubconfig.board_type = board_type
+ ubconfig.board_identity = board_identity
+ ubconfig.gdbserver = gdbserver
+ ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
+
+ env_vars = (
+ 'board_type',
+ 'board_identity',
+ 'source_dir',
+ 'test_py_dir',
+ 'build_dir',
+ 'result_dir',
+ 'persistent_data_dir',
+ )
+ for v in env_vars:
+ os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
+
+ if board_type.startswith('sandbox'):
+ import u_boot_console_sandbox
+ console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
+ else:
+ import u_boot_console_exec_attach
+ console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
+
+re_ut_test_list = re.compile(r'_u_boot_list_2_(.*)_test_2_\1_test_(.*)\s*$')
+def generate_ut_subtest(metafunc, fixture_name):
+ """Provide parametrization for a ut_subtest fixture.
+
+ Determines the set of unit tests built into a U-Boot binary by parsing the
+ list of symbols generated by the build process. Provides this information
+ to test functions by parameterizing their ut_subtest fixture parameter.
+
+ Args:
+ metafunc: The pytest test function.
+ fixture_name: The fixture name to test.
+
+ Returns:
+ Nothing.
+ """
+
+ fn = console.config.build_dir + '/u-boot.sym'
+ try:
+ with open(fn, 'rt') as f:
+ lines = f.readlines()
+ except:
+ lines = []
+ lines.sort()
+
+ vals = []
+ for l in lines:
+ m = re_ut_test_list.search(l)
+ if not m:
+ continue
+ vals.append(m.group(1) + ' ' + m.group(2))
+
+ ids = ['ut_' + s.replace(' ', '_') for s in vals]
+ metafunc.parametrize(fixture_name, vals, ids=ids)
+
+def generate_config(metafunc, fixture_name):
+ """Provide parametrization for {env,brd}__ fixtures.
+
+ If a test function takes parameter(s) (fixture names) of the form brd__xxx
+ or env__xxx, the brd and env configuration dictionaries are consulted to
+ find the list of values to use for those parameters, and the test is
+ parametrized so that it runs once for each combination of values.
+
+ Args:
+ metafunc: The pytest test function.
+ fixture_name: The fixture name to test.
+
+ Returns:
+ Nothing.
+ """
+
+ subconfigs = {
+ 'brd': console.config.brd,
+ 'env': console.config.env,
+ }
+ parts = fixture_name.split('__')
+ if len(parts) < 2:
+ return
+ if parts[0] not in subconfigs:
+ return
+ subconfig = subconfigs[parts[0]]
+ vals = []
+ val = subconfig.get(fixture_name, [])
+ # If that exact name is a key in the data source:
+ if val:
+ # ... use the dict value as a single parameter value.
+ vals = (val, )
+ else:
+ # ... otherwise, see if there's a key that contains a list of
+ # values to use instead.
+ vals = subconfig.get(fixture_name+ 's', [])
+ def fixture_id(index, val):
+ try:
+ return val['fixture_id']
+ except:
+ return fixture_name + str(index)
+ ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
+ metafunc.parametrize(fixture_name, vals, ids=ids)
+
+def pytest_generate_tests(metafunc):
+ """pytest hook: parameterize test functions based on custom rules.
+
+ Check each test function parameter (fixture name) to see if it is one of
+ our custom names, and if so, provide the correct parametrization for that
+ parameter.
+
+ Args:
+ metafunc: The pytest test function.
+
+ Returns:
+ Nothing.
+ """
+
+ for fn in metafunc.fixturenames:
+ if fn == 'ut_subtest':
+ generate_ut_subtest(metafunc, fn)
+ continue
+ generate_config(metafunc, fn)
+
+@pytest.fixture(scope='session')
+def u_boot_log(request):
+ """Generate the value of a test's log fixture.
+
+ Args:
+ request: The pytest request.
+
+ Returns:
+ The fixture value.
+ """
+
+ return console.log
+
+@pytest.fixture(scope='session')
+def u_boot_config(request):
+ """Generate the value of a test's u_boot_config fixture.
+
+ Args:
+ request: The pytest request.
+
+ Returns:
+ The fixture value.
+ """
+
+ return console.config
+
+@pytest.fixture(scope='function')
+def u_boot_console(request):
+ """Generate the value of a test's u_boot_console fixture.
+
+ Args:
+ request: The pytest request.
+
+ Returns:
+ The fixture value.
+ """
+
+ console.ensure_spawned()
+ return console
+
+anchors = {}
+tests_not_run = []
+tests_failed = []
+tests_xpassed = []
+tests_xfailed = []
+tests_skipped = []
+tests_warning = []
+tests_passed = []
+
+def pytest_itemcollected(item):
+ """pytest hook: Called once for each test found during collection.
+
+ This enables our custom result analysis code to see the list of all tests
+ that should eventually be run.
+
+ Args:
+ item: The item that was collected.
+
+ Returns:
+ Nothing.
+ """
+
+ tests_not_run.append(item.name)
+
+def cleanup():
+ """Clean up all global state.
+
+ Executed (via atexit) once the entire test process is complete. This
+ includes logging the status of all tests, and the identity of any failed
+ or skipped tests.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ if console:
+ console.close()
+ if log:
+ with log.section('Status Report', 'status_report'):
+ log.status_pass('%d passed' % len(tests_passed))
+ if tests_warning:
+ log.status_warning('%d passed with warning' % len(tests_warning))
+ for test in tests_warning:
+ anchor = anchors.get(test, None)
+ log.status_warning('... ' + test, anchor)
+ if tests_skipped:
+ log.status_skipped('%d skipped' % len(tests_skipped))
+ for test in tests_skipped:
+ anchor = anchors.get(test, None)
+ log.status_skipped('... ' + test, anchor)
+ if tests_xpassed:
+ log.status_xpass('%d xpass' % len(tests_xpassed))
+ for test in tests_xpassed:
+ anchor = anchors.get(test, None)
+ log.status_xpass('... ' + test, anchor)
+ if tests_xfailed:
+ log.status_xfail('%d xfail' % len(tests_xfailed))
+ for test in tests_xfailed:
+ anchor = anchors.get(test, None)
+ log.status_xfail('... ' + test, anchor)
+ if tests_failed:
+ log.status_fail('%d failed' % len(tests_failed))
+ for test in tests_failed:
+ anchor = anchors.get(test, None)
+ log.status_fail('... ' + test, anchor)
+ if tests_not_run:
+ log.status_fail('%d not run' % len(tests_not_run))
+ for test in tests_not_run:
+ anchor = anchors.get(test, None)
+ log.status_fail('... ' + test, anchor)
+ log.close()
+atexit.register(cleanup)
+
+def setup_boardspec(item):
+ """Process any 'boardspec' marker for a test.
+
+ Such a marker lists the set of board types that a test does/doesn't
+ support. If tests are being executed on an unsupported board, the test is
+ marked to be skipped.
+
+ Args:
+ item: The pytest test item.
+
+ Returns:
+ Nothing.
+ """
+
+ required_boards = []
+ for boards in item.iter_markers('boardspec'):
+ board = boards.args[0]
+ if board.startswith('!'):
+ if ubconfig.board_type == board[1:]:
+ pytest.skip('board "%s" not supported' % ubconfig.board_type)
+ return
+ else:
+ required_boards.append(board)
+ if required_boards and ubconfig.board_type not in required_boards:
+ pytest.skip('board "%s" not supported' % ubconfig.board_type)
+
+def setup_buildconfigspec(item):
+ """Process any 'buildconfigspec' marker for a test.
+
+ Such a marker lists some U-Boot configuration feature that the test
+ requires. If tests are being executed on an U-Boot build that doesn't
+ have the required feature, the test is marked to be skipped.
+
+ Args:
+ item: The pytest test item.
+
+ Returns:
+ Nothing.
+ """
+
+ for options in item.iter_markers('buildconfigspec'):
+ option = options.args[0]
+ if not ubconfig.buildconfig.get('config_' + option.lower(), None):
+ pytest.skip('.config feature "%s" not enabled' % option.lower())
+ for option in item.iter_markers('notbuildconfigspec'):
+ option = options.args[0]
+ if ubconfig.buildconfig.get('config_' + option.lower(), None):
+ pytest.skip('.config feature "%s" enabled' % option.lower())
+
+def tool_is_in_path(tool):
+ for path in os.environ["PATH"].split(os.pathsep):
+ fn = os.path.join(path, tool)
+ if os.path.isfile(fn) and os.access(fn, os.X_OK):
+ return True
+ return False
+
+def setup_requiredtool(item):
+ """Process any 'requiredtool' marker for a test.
+
+ Such a marker lists some external tool (binary, executable, application)
+ that the test requires. If tests are being executed on a system that
+ doesn't have the required tool, the test is marked to be skipped.
+
+ Args:
+ item: The pytest test item.
+
+ Returns:
+ Nothing.
+ """
+
+ for tools in item.iter_markers('requiredtool'):
+ tool = tools.args[0]
+ if not tool_is_in_path(tool):
+ pytest.skip('tool "%s" not in $PATH' % tool)
+
+def start_test_section(item):
+ anchors[item.name] = log.start_section(item.name)
+
+def pytest_runtest_setup(item):
+ """pytest hook: Configure (set up) a test item.
+
+ Called once for each test to perform any custom configuration. This hook
+ is used to skip the test if certain conditions apply.
+
+ Args:
+ item: The pytest test item.
+
+ Returns:
+ Nothing.
+ """
+
+ start_test_section(item)
+ setup_boardspec(item)
+ setup_buildconfigspec(item)
+ setup_requiredtool(item)
+
+def pytest_runtest_protocol(item, nextitem):
+ """pytest hook: Called to execute a test.
+
+ This hook wraps the standard pytest runtestprotocol() function in order
+ to acquire visibility into, and record, each test function's result.
+
+ Args:
+ item: The pytest test item to execute.
+ nextitem: The pytest test item that will be executed after this one.
+
+ Returns:
+ A list of pytest reports (test result data).
+ """
+
+ log.get_and_reset_warning()
+ reports = runtestprotocol(item, nextitem=nextitem)
+ was_warning = log.get_and_reset_warning()
+
+ # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
+ # the test is skipped. That call is required to create the test's section
+ # in the log file. The call to log.end_section() requires that the log
+ # contain a section for this test. Create a section for the test if it
+ # doesn't already exist.
+ if not item.name in anchors:
+ start_test_section(item)
+
+ failure_cleanup = False
+ if not was_warning:
+ test_list = tests_passed
+ msg = 'OK'
+ msg_log = log.status_pass
+ else:
+ test_list = tests_warning
+ msg = 'OK (with warning)'
+ msg_log = log.status_warning
+ for report in reports:
+ if report.outcome == 'failed':
+ if hasattr(report, 'wasxfail'):
+ test_list = tests_xpassed
+ msg = 'XPASSED'
+ msg_log = log.status_xpass
+ else:
+ failure_cleanup = True
+ test_list = tests_failed
+ msg = 'FAILED:\n' + str(report.longrepr)
+ msg_log = log.status_fail
+ break
+ if report.outcome == 'skipped':
+ if hasattr(report, 'wasxfail'):
+ failure_cleanup = True
+ test_list = tests_xfailed
+ msg = 'XFAILED:\n' + str(report.longrepr)
+ msg_log = log.status_xfail
+ break
+ test_list = tests_skipped
+ msg = 'SKIPPED:\n' + str(report.longrepr)
+ msg_log = log.status_skipped
+
+ if failure_cleanup:
+ console.drain_console()
+
+ test_list.append(item.name)
+ tests_not_run.remove(item.name)
+
+ try:
+ msg_log(msg)
+ except:
+ # If something went wrong with logging, it's better to let the test
+ # process continue, which may report other exceptions that triggered
+ # the logging issue (e.g. console.log wasn't created). Hence, just
+ # squash the exception. If the test setup failed due to e.g. syntax
+ # error somewhere else, this won't be seen. However, once that issue
+ # is fixed, if this exception still exists, it will then be logged as
+ # part of the test's stdout.
+ import traceback
+ print('Exception occurred while logging runtest status:')
+ traceback.print_exc()
+ # FIXME: Can we force a test failure here?
+
+ log.end_section(item.name)
+
+ if failure_cleanup:
+ console.cleanup_spawn()
+
+ return reports
diff --git a/test/py/multiplexed_log.css b/test/py/multiplexed_log.css
new file mode 100644
index 00000000..3db99272
--- /dev/null
+++ b/test/py/multiplexed_log.css
@@ -0,0 +1,108 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (c) 2015 Stephen Warren
+ * Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+ */
+
+/*
+ * This provides pretty formatting of the HTML log file, e.g.
+ * - colored bars beside/above log sections for easily parsed delineation.
+ * - color highlighting of various messages.
+ */
+
+body {
+ background-color: black;
+ color: #ffffff;
+}
+
+pre {
+ margin-top: 0px;
+ margin-bottom: 0px;
+}
+
+.implicit {
+ color: #808080;
+}
+
+.block {
+ border-style: solid;
+ border-color: #303030;
+ border-width: 0px 0px 0px 5px;
+ padding-left: 5px
+}
+
+.block-header {
+ background-color: #303030;
+ margin-left: -5px;
+ margin-top: 5px;
+}
+
+.block-header:hover {
+ text-decoration: underline;
+}
+
+.block-trailer {
+ display: none;
+}
+
+.error {
+ color: #ff0000
+}
+
+.warning {
+ color: #ffff00
+}
+
+.info {
+ color: #808080
+}
+
+.action {
+ color: #8080ff
+}
+
+.timestamp {
+ color: #8080ff
+}
+
+.status-pass {
+ color: #00ff00
+}
+
+.status-warning {
+ color: #ffff00
+}
+
+.status-skipped {
+ color: #ffff00
+}
+
+.status-xfail {
+ color: #ff7f00
+}
+
+.status-xpass {
+ color: #ff7f00
+}
+
+.status-fail {
+ color: #ff0000
+}
+
+.hidden {
+ display: none;
+}
+
+a:link {
+ text-decoration: inherit;
+ color: inherit;
+}
+
+a:visited {
+ text-decoration: inherit;
+ color: inherit;
+}
+
+a:hover {
+ text-decoration: underline;
+}
diff --git a/test/py/multiplexed_log.py b/test/py/multiplexed_log.py
new file mode 100644
index 00000000..545a7743
--- /dev/null
+++ b/test/py/multiplexed_log.py
@@ -0,0 +1,709 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Generate an HTML-formatted log file containing multiple streams of data,
+# each represented in a well-delineated/-structured fashion.
+
+import datetime
+import html
+import os.path
+import shutil
+import subprocess
+
+mod_dir = os.path.dirname(os.path.abspath(__file__))
+
+class LogfileStream(object):
+ """A file-like object used to write a single logical stream of data into
+ a multiplexed log file. Objects of this type should be created by factory
+ functions in the Logfile class rather than directly."""
+
+ def __init__(self, logfile, name, chained_file):
+ """Initialize a new object.
+
+ Args:
+ logfile: The Logfile object to log to.
+ name: The name of this log stream.
+ chained_file: The file-like object to which all stream data should be
+ logged to in addition to logfile. Can be None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.logfile = logfile
+ self.name = name
+ self.chained_file = chained_file
+
+ def close(self):
+ """Dummy function so that this class is "file-like".
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ pass
+
+ def write(self, data, implicit=False):
+ """Write data to the log stream.
+
+ Args:
+ data: The data to write to the file.
+ implicit: Boolean indicating whether data actually appeared in the
+ stream, or was implicitly generated. A valid use-case is to
+ repeat a shell prompt at the start of each separate log
+ section, which makes the log sections more readable in
+ isolation.
+
+ Returns:
+ Nothing.
+ """
+
+ self.logfile.write(self, data, implicit)
+ if self.chained_file:
+ # Chained file is console, convert things a little
+ self.chained_file.write((data.encode('ascii', 'replace')).decode())
+
+ def flush(self):
+ """Flush the log stream, to ensure correct log interleaving.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.logfile.flush()
+ if self.chained_file:
+ self.chained_file.flush()
+
+class RunAndLog(object):
+ """A utility object used to execute sub-processes and log their output to
+ a multiplexed log file. Objects of this type should be created by factory
+ functions in the Logfile class rather than directly."""
+
+ def __init__(self, logfile, name, chained_file):
+ """Initialize a new object.
+
+ Args:
+ logfile: The Logfile object to log to.
+ name: The name of this log stream or sub-process.
+ chained_file: The file-like object to which all stream data should
+ be logged to in addition to logfile. Can be None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.logfile = logfile
+ self.name = name
+ self.chained_file = chained_file
+ self.output = None
+ self.exit_status = None
+
+ def close(self):
+ """Clean up any resources managed by this object."""
+ pass
+
+ def run(self, cmd, cwd=None, ignore_errors=False):
+ """Run a command as a sub-process, and log the results.
+
+ The output is available at self.output which can be useful if there is
+ an exception.
+
+ Args:
+ cmd: The command to execute.
+ cwd: The directory to run the command in. Can be None to use the
+ current directory.
+ ignore_errors: Indicate whether to ignore errors. If True, the
+ function will simply return if the command cannot be executed
+ or exits with an error code, otherwise an exception will be
+ raised if such problems occur.
+
+ Returns:
+ The output as a string.
+ """
+
+ msg = '+' + ' '.join(cmd) + '\n'
+ if self.chained_file:
+ self.chained_file.write(msg)
+ self.logfile.write(self, msg)
+
+ try:
+ p = subprocess.Popen(cmd, cwd=cwd,
+ stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ (stdout, stderr) = p.communicate()
+ if stdout is not None:
+ stdout = stdout.decode('utf-8')
+ if stderr is not None:
+ stderr = stderr.decode('utf-8')
+ output = ''
+ if stdout:
+ if stderr:
+ output += 'stdout:\n'
+ output += stdout
+ if stderr:
+ if stdout:
+ output += 'stderr:\n'
+ output += stderr
+ exit_status = p.returncode
+ exception = None
+ except subprocess.CalledProcessError as cpe:
+ output = cpe.output
+ exit_status = cpe.returncode
+ exception = cpe
+ except Exception as e:
+ output = ''
+ exit_status = 0
+ exception = e
+ if output and not output.endswith('\n'):
+ output += '\n'
+ if exit_status and not exception and not ignore_errors:
+ exception = Exception('Exit code: ' + str(exit_status))
+ if exception:
+ output += str(exception) + '\n'
+ self.logfile.write(self, output)
+ if self.chained_file:
+ self.chained_file.write(output)
+ self.logfile.timestamp()
+
+ # Store the output so it can be accessed if we raise an exception.
+ self.output = output
+ self.exit_status = exit_status
+ if exception:
+ raise exception
+ return output
+
+class SectionCtxMgr(object):
+ """A context manager for Python's "with" statement, which allows a certain
+ portion of test code to be logged to a separate section of the log file.
+ Objects of this type should be created by factory functions in the Logfile
+ class rather than directly."""
+
+ def __init__(self, log, marker, anchor):
+ """Initialize a new object.
+
+ Args:
+ log: The Logfile object to log to.
+ marker: The name of the nested log section.
+ anchor: The anchor value to pass to start_section().
+
+ Returns:
+ Nothing.
+ """
+
+ self.log = log
+ self.marker = marker
+ self.anchor = anchor
+
+ def __enter__(self):
+ self.anchor = self.log.start_section(self.marker, self.anchor)
+
+ def __exit__(self, extype, value, traceback):
+ self.log.end_section(self.marker)
+
+class Logfile(object):
+ """Generates an HTML-formatted log file containing multiple streams of
+ data, each represented in a well-delineated/-structured fashion."""
+
+ def __init__(self, fn):
+ """Initialize a new object.
+
+ Args:
+ fn: The filename to write to.
+
+ Returns:
+ Nothing.
+ """
+
+ self.f = open(fn, 'wt', encoding='utf-8')
+ self.last_stream = None
+ self.blocks = []
+ self.cur_evt = 1
+ self.anchor = 0
+ self.timestamp_start = self._get_time()
+ self.timestamp_prev = self.timestamp_start
+ self.timestamp_blocks = []
+ self.seen_warning = False
+
+ shutil.copy(mod_dir + '/multiplexed_log.css', os.path.dirname(fn))
+ self.f.write('''\
+<html>
+<head>
+<link rel="stylesheet" type="text/css" href="multiplexed_log.css">
+<script src="http://code.jquery.com/jquery.min.js"></script>
+<script>
+$(document).ready(function () {
+ // Copy status report HTML to start of log for easy access
+ sts = $(".block#status_report")[0].outerHTML;
+ $("tt").prepend(sts);
+
+ // Add expand/contract buttons to all block headers
+ btns = "<span class=\\\"block-expand hidden\\\">[+] </span>" +
+ "<span class=\\\"block-contract\\\">[-] </span>";
+ $(".block-header").prepend(btns);
+
+ // Pre-contract all blocks which passed, leaving only problem cases
+ // expanded, to highlight issues the user should look at.
+ // Only top-level blocks (sections) should have any status
+ passed_bcs = $(".block-content:has(.status-pass)");
+ // Some blocks might have multiple status entries (e.g. the status
+ // report), so take care not to hide blocks with partial success.
+ passed_bcs = passed_bcs.not(":has(.status-fail)");
+ passed_bcs = passed_bcs.not(":has(.status-xfail)");
+ passed_bcs = passed_bcs.not(":has(.status-xpass)");
+ passed_bcs = passed_bcs.not(":has(.status-skipped)");
+ passed_bcs = passed_bcs.not(":has(.status-warning)");
+ // Hide the passed blocks
+ passed_bcs.addClass("hidden");
+ // Flip the expand/contract button hiding for those blocks.
+ bhs = passed_bcs.parent().children(".block-header")
+ bhs.children(".block-expand").removeClass("hidden");
+ bhs.children(".block-contract").addClass("hidden");
+
+ // Add click handler to block headers.
+ // The handler expands/contracts the block.
+ $(".block-header").on("click", function (e) {
+ var header = $(this);
+ var content = header.next(".block-content");
+ var expanded = !content.hasClass("hidden");
+ if (expanded) {
+ content.addClass("hidden");
+ header.children(".block-expand").first().removeClass("hidden");
+ header.children(".block-contract").first().addClass("hidden");
+ } else {
+ header.children(".block-contract").first().removeClass("hidden");
+ header.children(".block-expand").first().addClass("hidden");
+ content.removeClass("hidden");
+ }
+ });
+
+ // When clicking on a link, expand the target block
+ $("a").on("click", function (e) {
+ var block = $($(this).attr("href"));
+ var header = block.children(".block-header");
+ var content = block.children(".block-content").first();
+ header.children(".block-contract").first().removeClass("hidden");
+ header.children(".block-expand").first().addClass("hidden");
+ content.removeClass("hidden");
+ });
+});
+</script>
+</head>
+<body>
+<tt>
+''')
+
+ def close(self):
+ """Close the log file.
+
+ After calling this function, no more data may be written to the log.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.f.write('''\
+</tt>
+</body>
+</html>
+''')
+ self.f.close()
+
+ # The set of characters that should be represented as hexadecimal codes in
+ # the log file.
+ _nonprint = {ord('%')}
+ _nonprint.update({c for c in range(0, 32) if c not in (9, 10)})
+ _nonprint.update({c for c in range(127, 256)})
+
+ def _escape(self, data):
+ """Render data format suitable for inclusion in an HTML document.
+
+ This includes HTML-escaping certain characters, and translating
+ control characters to a hexadecimal representation.
+
+ Args:
+ data: The raw string data to be escaped.
+
+ Returns:
+ An escaped version of the data.
+ """
+
+ data = data.replace(chr(13), '')
+ data = ''.join((ord(c) in self._nonprint) and ('%%%02x' % ord(c)) or
+ c for c in data)
+ data = html.escape(data)
+ return data
+
+ def _terminate_stream(self):
+ """Write HTML to the log file to terminate the current stream's data.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.cur_evt += 1
+ if not self.last_stream:
+ return
+ self.f.write('</pre>\n')
+ self.f.write('<div class="stream-trailer block-trailer">End stream: ' +
+ self.last_stream.name + '</div>\n')
+ self.f.write('</div>\n')
+ self.f.write('</div>\n')
+ self.last_stream = None
+
+ def _note(self, note_type, msg, anchor=None):
+ """Write a note or one-off message to the log file.
+
+ Args:
+ note_type: The type of note. This must be a value supported by the
+ accompanying multiplexed_log.css.
+ msg: The note/message to log.
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._terminate_stream()
+ self.f.write('<div class="' + note_type + '">\n')
+ self.f.write('<pre>')
+ if anchor:
+ self.f.write('<a href="#%s">' % anchor)
+ self.f.write(self._escape(msg))
+ if anchor:
+ self.f.write('</a>')
+ self.f.write('\n</pre>\n')
+ self.f.write('</div>\n')
+
+ def start_section(self, marker, anchor=None):
+ """Begin a new nested section in the log file.
+
+ Args:
+ marker: The name of the section that is starting.
+ anchor: The value to use for the anchor. If None, a unique value
+ will be calculated and used
+
+ Returns:
+ Name of the HTML anchor emitted before section.
+ """
+
+ self._terminate_stream()
+ self.blocks.append(marker)
+ self.timestamp_blocks.append(self._get_time())
+ if not anchor:
+ self.anchor += 1
+ anchor = str(self.anchor)
+ blk_path = '/'.join(self.blocks)
+ self.f.write('<div class="section block" id="' + anchor + '">\n')
+ self.f.write('<div class="section-header block-header">Section: ' +
+ blk_path + '</div>\n')
+ self.f.write('<div class="section-content block-content">\n')
+ self.timestamp()
+
+ return anchor
+
+ def end_section(self, marker):
+ """Terminate the current nested section in the log file.
+
+ This function validates proper nesting of start_section() and
+ end_section() calls. If a mismatch is found, an exception is raised.
+
+ Args:
+ marker: The name of the section that is ending.
+
+ Returns:
+ Nothing.
+ """
+
+ if (not self.blocks) or (marker != self.blocks[-1]):
+ raise Exception('Block nesting mismatch: "%s" "%s"' %
+ (marker, '/'.join(self.blocks)))
+ self._terminate_stream()
+ timestamp_now = self._get_time()
+ timestamp_section_start = self.timestamp_blocks.pop()
+ delta_section = timestamp_now - timestamp_section_start
+ self._note("timestamp",
+ "TIME: SINCE-SECTION: " + str(delta_section))
+ blk_path = '/'.join(self.blocks)
+ self.f.write('<div class="section-trailer block-trailer">' +
+ 'End section: ' + blk_path + '</div>\n')
+ self.f.write('</div>\n')
+ self.f.write('</div>\n')
+ self.blocks.pop()
+
+ def section(self, marker, anchor=None):
+ """Create a temporary section in the log file.
+
+ This function creates a context manager for Python's "with" statement,
+ which allows a certain portion of test code to be logged to a separate
+ section of the log file.
+
+ Usage:
+ with log.section("somename"):
+ some test code
+
+ Args:
+ marker: The name of the nested section.
+ anchor: The anchor value to pass to start_section().
+
+ Returns:
+ A context manager object.
+ """
+
+ return SectionCtxMgr(self, marker, anchor)
+
+ def error(self, msg):
+ """Write an error note to the log file.
+
+ Args:
+ msg: A message describing the error.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("error", msg)
+
+ def warning(self, msg):
+ """Write an warning note to the log file.
+
+ Args:
+ msg: A message describing the warning.
+
+ Returns:
+ Nothing.
+ """
+
+ self.seen_warning = True
+ self._note("warning", msg)
+
+ def get_and_reset_warning(self):
+ """Get and reset the log warning flag.
+
+ Args:
+ None
+
+ Returns:
+ Whether a warning was seen since the last call.
+ """
+
+ ret = self.seen_warning
+ self.seen_warning = False
+ return ret
+
+ def info(self, msg):
+ """Write an informational note to the log file.
+
+ Args:
+ msg: An informational message.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("info", msg)
+
+ def action(self, msg):
+ """Write an action note to the log file.
+
+ Args:
+ msg: A message describing the action that is being logged.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("action", msg)
+
+ def _get_time(self):
+ return datetime.datetime.now()
+
+ def timestamp(self):
+ """Write a timestamp to the log file.
+
+ Args:
+ None
+
+ Returns:
+ Nothing.
+ """
+
+ timestamp_now = self._get_time()
+ delta_prev = timestamp_now - self.timestamp_prev
+ delta_start = timestamp_now - self.timestamp_start
+ self.timestamp_prev = timestamp_now
+
+ self._note("timestamp",
+ "TIME: NOW: " + timestamp_now.strftime("%Y/%m/%d %H:%M:%S.%f"))
+ self._note("timestamp",
+ "TIME: SINCE-PREV: " + str(delta_prev))
+ self._note("timestamp",
+ "TIME: SINCE-START: " + str(delta_start))
+
+ def status_pass(self, msg, anchor=None):
+ """Write a note to the log file describing test(s) which passed.
+
+ Args:
+ msg: A message describing the passed test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-pass", msg, anchor)
+
+ def status_warning(self, msg, anchor=None):
+ """Write a note to the log file describing test(s) which passed.
+
+ Args:
+ msg: A message describing the passed test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-warning", msg, anchor)
+
+ def status_skipped(self, msg, anchor=None):
+ """Write a note to the log file describing skipped test(s).
+
+ Args:
+ msg: A message describing the skipped test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-skipped", msg, anchor)
+
+ def status_xfail(self, msg, anchor=None):
+ """Write a note to the log file describing xfailed test(s).
+
+ Args:
+ msg: A message describing the xfailed test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-xfail", msg, anchor)
+
+ def status_xpass(self, msg, anchor=None):
+ """Write a note to the log file describing xpassed test(s).
+
+ Args:
+ msg: A message describing the xpassed test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-xpass", msg, anchor)
+
+ def status_fail(self, msg, anchor=None):
+ """Write a note to the log file describing failed test(s).
+
+ Args:
+ msg: A message describing the failed test(s).
+ anchor: Optional internal link target.
+
+ Returns:
+ Nothing.
+ """
+
+ self._note("status-fail", msg, anchor)
+
+ def get_stream(self, name, chained_file=None):
+ """Create an object to log a single stream's data into the log file.
+
+ This creates a "file-like" object that can be written to in order to
+ write a single stream's data to the log file. The implementation will
+ handle any required interleaving of data (from multiple streams) in
+ the log, in a way that makes it obvious which stream each bit of data
+ came from.
+
+ Args:
+ name: The name of the stream.
+ chained_file: The file-like object to which all stream data should
+ be logged to in addition to this log. Can be None.
+
+ Returns:
+ A file-like object.
+ """
+
+ return LogfileStream(self, name, chained_file)
+
+ def get_runner(self, name, chained_file=None):
+ """Create an object that executes processes and logs their output.
+
+ Args:
+ name: The name of this sub-process.
+ chained_file: The file-like object to which all stream data should
+ be logged to in addition to logfile. Can be None.
+
+ Returns:
+ A RunAndLog object.
+ """
+
+ return RunAndLog(self, name, chained_file)
+
+ def write(self, stream, data, implicit=False):
+ """Write stream data into the log file.
+
+ This function should only be used by instances of LogfileStream or
+ RunAndLog.
+
+ Args:
+ stream: The stream whose data is being logged.
+ data: The data to log.
+ implicit: Boolean indicating whether data actually appeared in the
+ stream, or was implicitly generated. A valid use-case is to
+ repeat a shell prompt at the start of each separate log
+ section, which makes the log sections more readable in
+ isolation.
+
+ Returns:
+ Nothing.
+ """
+
+ if stream != self.last_stream:
+ self._terminate_stream()
+ self.f.write('<div class="stream block">\n')
+ self.f.write('<div class="stream-header block-header">Stream: ' +
+ stream.name + '</div>\n')
+ self.f.write('<div class="stream-content block-content">\n')
+ self.f.write('<pre>')
+ if implicit:
+ self.f.write('<span class="implicit">')
+ self.f.write(self._escape(data))
+ if implicit:
+ self.f.write('</span>')
+ self.last_stream = stream
+
+ def flush(self):
+ """Flush the log stream, to ensure correct log interleaving.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.f.flush()
diff --git a/test/py/pytest.ini b/test/py/pytest.ini
new file mode 100644
index 00000000..e93d010f
--- /dev/null
+++ b/test/py/pytest.ini
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Static configuration data for pytest. pytest reads this at startup time.
+
+[pytest]
+markers =
+ boardspec: U-Boot: Describes the set of boards a test can/can't run on.
+ buildconfigspec: U-Boot: Describes Kconfig/config-header constraints.
+ notbuildconfigspec: U-Boot: Describes required disabled Kconfig options.
+ requiredtool: U-Boot: Required host tools for a test.
+ slow: U-Boot: Specific test will run slowly.
diff --git a/test/py/requirements.txt b/test/py/requirements.txt
new file mode 100644
index 00000000..cf251186
--- /dev/null
+++ b/test/py/requirements.txt
@@ -0,0 +1,22 @@
+atomicwrites==1.3.0
+attrs==19.3.0
+coverage==4.5.4
+extras==1.0.0
+fixtures==3.0.0
+importlib-metadata==0.23
+linecache2==1.0.0
+more-itertools==7.2.0
+packaging==19.2
+pbr==5.4.3
+pluggy==0.13.0
+py==1.8.0
+pyparsing==2.4.2
+pytest==5.2.1
+python-mimeparse==1.6.0
+python-subunit==1.3.0
+six==1.12.0
+testtools==2.3.0
+traceback2==1.4.0
+unittest2==1.1.0
+wcwidth==0.1.7
+zipp==0.6.0
diff --git a/test/py/test.py b/test/py/test.py
new file mode 100755
index 00000000..bee88d96
--- /dev/null
+++ b/test/py/test.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Wrapper script to invoke pytest with the directory name that contains the
+# U-Boot tests.
+
+import os
+import os.path
+import sys
+from pkg_resources import load_entry_point
+
+# argv; py.test test_directory_name user-supplied-arguments
+args = [os.path.dirname(__file__) + '/tests']
+args.extend(sys.argv)
+
+if __name__ == '__main__':
+ sys.exit(load_entry_point('pytest', 'console_scripts', 'pytest')(args))
diff --git a/test/py/tests/test_000_version.py b/test/py/tests/test_000_version.py
new file mode 100644
index 00000000..bd089ab5
--- /dev/null
+++ b/test/py/tests/test_000_version.py
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+# pytest runs tests the order of their module path, which is related to the
+# filename containing the test. This file is named such that it is sorted
+# first, simply as a very basic sanity check of the functionality of the U-Boot
+# command prompt.
+
+def test_version(u_boot_console):
+ """Test that the "version" command prints the U-Boot version."""
+
+ # "version" prints the U-Boot sign-on message. This is usually considered
+ # an error, so that any unexpected reboot causes an error. Here, this
+ # error detection is disabled since the sign-on message is expected.
+ with u_boot_console.disable_check('main_signon'):
+ response = u_boot_console.run_command('version')
+ # Ensure "version" printed what we expected.
+ u_boot_console.validate_version_string_in_text(response)
diff --git a/test/py/tests/test_android/test_ab.py b/test/py/tests/test_android/test_ab.py
new file mode 100644
index 00000000..c79cb07f
--- /dev/null
+++ b/test/py/tests/test_android/test_ab.py
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: GPL-2.0
+# (C) Copyright 2018 Texas Instruments, <www.ti.com>
+
+# Test A/B update commands.
+
+import os
+import pytest
+import u_boot_utils
+
+class ABTestDiskImage(object):
+ """Disk Image used by the A/B tests."""
+
+ def __init__(self, u_boot_console):
+ """Initialize a new ABTestDiskImage object.
+
+ Args:
+ u_boot_console: A U-Boot console.
+
+ Returns:
+ Nothing.
+ """
+
+ filename = 'test_ab_disk_image.bin'
+
+ persistent = u_boot_console.config.persistent_data_dir + '/' + filename
+ self.path = u_boot_console.config.result_dir + '/' + filename
+
+ with u_boot_utils.persistent_file_helper(u_boot_console.log, persistent):
+ if os.path.exists(persistent):
+ u_boot_console.log.action('Disk image file ' + persistent +
+ ' already exists')
+ else:
+ u_boot_console.log.action('Generating ' + persistent)
+ fd = os.open(persistent, os.O_RDWR | os.O_CREAT)
+ os.ftruncate(fd, 524288)
+ os.close(fd)
+ cmd = ('sgdisk', persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+ cmd = ('sgdisk', '--new=1:64:512', '--change-name=1:misc',
+ persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ cmd = ('sgdisk', '--load-backup=' + persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+ cmd = ('cp', persistent, self.path)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+di = None
+@pytest.fixture(scope='function')
+def ab_disk_image(u_boot_console):
+ global di
+ if not di:
+ di = ABTestDiskImage(u_boot_console)
+ return di
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('android_ab')
+@pytest.mark.buildconfigspec('cmd_ab_select')
+@pytest.mark.requiredtool('sgdisk')
+def test_ab(ab_disk_image, u_boot_console):
+ """Test the 'ab_select' command."""
+
+ u_boot_console.run_command('host bind 0 ' + ab_disk_image.path)
+
+ output = u_boot_console.run_command('ab_select slot_name host 0#misc')
+ assert 're-initializing A/B metadata' in output
+ assert 'Attempting slot a, tries remaining 7' in output
+ output = u_boot_console.run_command('printenv slot_name')
+ assert 'slot_name=a' in output
+
+ output = u_boot_console.run_command('ab_select slot_name host 0:1')
+ assert 'Attempting slot b, tries remaining 7' in output
+ output = u_boot_console.run_command('printenv slot_name')
+ assert 'slot_name=b' in output
diff --git a/test/py/tests/test_android/test_avb.py b/test/py/tests/test_android/test_avb.py
new file mode 100644
index 00000000..20ccaf67
--- /dev/null
+++ b/test/py/tests/test_android/test_avb.py
@@ -0,0 +1,137 @@
+# Copyright (c) 2018, Linaro Limited
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Android Verified Boot 2.0 Test
+
+"""
+This tests Android Verified Boot 2.0 support in U-boot:
+
+For additional details about how to build proper vbmeta partition
+check doc/android/avb2.txt
+
+For configuration verification:
+- Corrupt boot partition and check for failure
+- Corrupt vbmeta partition and check for failure
+"""
+
+import pytest
+import u_boot_utils as util
+
+# defauld mmc id
+mmc_dev = 1
+temp_addr = 0x90000000
+temp_addr2 = 0x90002000
+
+@pytest.mark.buildconfigspec('cmd_avb')
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_avb_verify(u_boot_console):
+ """Run AVB 2.0 boot verification chain with avb subset of commands
+ """
+
+ success_str = "Verification passed successfully"
+
+ response = u_boot_console.run_command('avb init %s' %str(mmc_dev))
+ assert response == ''
+ response = u_boot_console.run_command('avb verify')
+ assert response.find(success_str)
+
+
+@pytest.mark.buildconfigspec('cmd_avb')
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_avb_mmc_uuid(u_boot_console):
+ """Check if 'avb get_uuid' works, compare results with
+ 'part list mmc 1' output
+ """
+
+ response = u_boot_console.run_command('avb init %s' % str(mmc_dev))
+ assert response == ''
+
+ response = u_boot_console.run_command('mmc rescan; mmc dev %s' %
+ str(mmc_dev))
+ assert response.find('is current device')
+
+ part_lines = u_boot_console.run_command('mmc part').splitlines()
+ part_list = {}
+ cur_partname = ''
+
+ for line in part_lines:
+ if '"' in line:
+ start_pt = line.find('"')
+ end_pt = line.find('"', start_pt + 1)
+ cur_partname = line[start_pt + 1: end_pt]
+
+ if 'guid:' in line:
+ guid_to_check = line.split('guid:\t')
+ part_list[cur_partname] = guid_to_check[1]
+
+ # lets check all guids with avb get_guid
+ for part, guid in part_list.iteritems():
+ avb_guid_resp = u_boot_console.run_command('avb get_uuid %s' % part)
+ assert guid == avb_guid_resp.split('UUID: ')[1]
+
+
+@pytest.mark.buildconfigspec('cmd_avb')
+def test_avb_read_rb(u_boot_console):
+ """Test reading rollback indexes
+ """
+
+ response = u_boot_console.run_command('avb init %s' % str(mmc_dev))
+ assert response == ''
+
+ response = u_boot_console.run_command('avb read_rb 1')
+ assert response == 'Rollback index: 0'
+
+
+@pytest.mark.buildconfigspec('cmd_avb')
+def test_avb_is_unlocked(u_boot_console):
+ """Test if device is in the unlocked state
+ """
+
+ response = u_boot_console.run_command('avb init %s' % str(mmc_dev))
+ assert response == ''
+
+ response = u_boot_console.run_command('avb is_unlocked')
+ assert response == 'Unlocked = 1'
+
+
+@pytest.mark.buildconfigspec('cmd_avb')
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_avb_mmc_read(u_boot_console):
+ """Test mmc read operation
+ """
+
+ response = u_boot_console.run_command('mmc rescan; mmc dev %s 0' %
+ str(mmc_dev))
+ assert response.find('is current device')
+
+ response = u_boot_console.run_command('mmc read 0x%x 0x100 0x1' % temp_addr)
+ assert response.find('read: OK')
+
+ response = u_boot_console.run_command('avb init %s' % str(mmc_dev))
+ assert response == ''
+
+ response = u_boot_console.run_command('avb read_part xloader 0 100 0x%x' %
+ temp_addr2)
+ assert response.find('Read 512 bytes')
+
+ # Now lets compare two buffers
+ response = u_boot_console.run_command('cmp 0x%x 0x%x 40' %
+ (temp_addr, temp_addr2))
+ assert response.find('64 word')
+
+
+@pytest.mark.buildconfigspec('cmd_avb')
+@pytest.mark.buildconfigspec('optee_ta_avb')
+def test_avb_persistent_values(u_boot_console):
+ """Test reading/writing persistent storage to avb
+ """
+
+ response = u_boot_console.run_command('avb init %s' % str(mmc_dev))
+ assert response == ''
+
+ response = u_boot_console.run_command('avb write_pvalue test value_value')
+ assert response == 'Wrote 12 bytes'
+
+ response = u_boot_console.run_command('avb read_pvalue test 12')
+ assert response == 'Read 12 bytes, value = value_value'
diff --git a/test/py/tests/test_bind.py b/test/py/tests/test_bind.py
new file mode 100644
index 00000000..20c60503
--- /dev/null
+++ b/test/py/tests/test_bind.py
@@ -0,0 +1,179 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+import os.path
+import pytest
+import re
+
+def in_tree(response, name, uclass, drv, depth, last_child):
+ lines = [x.strip() for x in response.splitlines()]
+ leaf = ' ' * 4 * depth;
+ if not last_child:
+ leaf = leaf + r'\|'
+ else:
+ leaf = leaf + '`'
+ leaf = leaf + '-- ' + name
+ line = (r' *{:10.10} [0-9]* \[ [ +] \] {:20.20} {}$'
+ .format(uclass, drv, leaf))
+ prog = re.compile(line)
+ for l in lines:
+ if prog.match(l):
+ return True
+ return False
+
+
+@pytest.mark.buildconfigspec('cmd_bind')
+def test_bind_unbind_with_node(u_boot_console):
+
+ #bind /bind-test. Device should come up as well as its children
+ response = u_boot_console.run_command('bind /bind-test generic_simple_bus')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert in_tree(tree, 'bind-test-child1', 'phy', 'phy_sandbox', 1, False)
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+
+ #Unbind child #1. No error expected and all devices should be there except for bind-test-child1
+ response = u_boot_console.run_command('unbind /bind-test/bind-test-child1')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert 'bind-test-child1' not in tree
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+
+ #bind child #1. No error expected and all devices should be there
+ response = u_boot_console.run_command('bind /bind-test/bind-test-child1 phy_sandbox')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert in_tree(tree, 'bind-test-child1', 'phy', 'phy_sandbox', 1, True)
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, False)
+
+ #Unbind child #2. No error expected and all devices should be there except for bind-test-child2
+ response = u_boot_console.run_command('unbind /bind-test/bind-test-child2')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert in_tree(tree, 'bind-test-child1', 'phy', 'phy_sandbox', 1, True)
+ assert 'bind-test-child2' not in tree
+
+
+ #Bind child #2. No error expected and all devices should be there
+ response = u_boot_console.run_command('bind /bind-test/bind-test-child2 generic_simple_bus')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert in_tree(tree, 'bind-test-child1', 'phy', 'phy_sandbox', 1, False)
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+
+ #Unbind parent. No error expected. All devices should be removed and unbound
+ response = u_boot_console.run_command('unbind /bind-test')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert 'bind-test' not in tree
+ assert 'bind-test-child1' not in tree
+ assert 'bind-test-child2' not in tree
+
+ #try binding invalid node with valid driver
+ response = u_boot_console.run_command('bind /not-a-valid-node generic_simple_bus')
+ assert response != ''
+ tree = u_boot_console.run_command('dm tree')
+ assert 'not-a-valid-node' not in tree
+
+ #try binding valid node with invalid driver
+ response = u_boot_console.run_command('bind /bind-test not_a_driver')
+ assert response != ''
+ tree = u_boot_console.run_command('dm tree')
+ assert 'bind-test' not in tree
+
+ #bind /bind-test. Device should come up as well as its children
+ response = u_boot_console.run_command('bind /bind-test generic_simple_bus')
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test', 'simple_bus', 'generic_simple_bus', 0, True)
+ assert in_tree(tree, 'bind-test-child1', 'phy', 'phy_sandbox', 1, False)
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+
+ response = u_boot_console.run_command('unbind /bind-test')
+ assert response == ''
+
+def get_next_line(tree, name):
+ treelines = [x.strip() for x in tree.splitlines() if x.strip()]
+ child_line = ''
+ for idx, line in enumerate(treelines):
+ if ('-- ' + name) in line:
+ try:
+ child_line = treelines[idx+1]
+ except:
+ pass
+ break
+ return child_line
+
+@pytest.mark.buildconfigspec('cmd_bind')
+def test_bind_unbind_with_uclass(u_boot_console):
+ #bind /bind-test
+ response = u_boot_console.run_command('bind /bind-test generic_simple_bus')
+ assert response == ''
+
+ #make sure bind-test-child2 is there and get its uclass/index pair
+ tree = u_boot_console.run_command('dm tree')
+ child2_line = [x.strip() for x in tree.splitlines() if '-- bind-test-child2' in x]
+ assert len(child2_line) == 1
+
+ child2_uclass = child2_line[0].split()[0]
+ child2_index = int(child2_line[0].split()[1])
+
+ #bind generic_simple_bus as a child of bind-test-child2
+ response = u_boot_console.run_command('bind {} {} generic_simple_bus'.format(child2_uclass, child2_index, 'generic_simple_bus'))
+
+ #check that the child is there and its uclass/index pair is right
+ tree = u_boot_console.run_command('dm tree')
+
+ child_of_child2_line = get_next_line(tree, 'bind-test-child2')
+ assert child_of_child2_line
+ child_of_child2_index = int(child_of_child2_line.split()[1])
+ assert in_tree(tree, 'generic_simple_bus', 'simple_bus', 'generic_simple_bus', 2, True)
+ assert child_of_child2_index == child2_index + 1
+
+ #unbind the child and check it has been removed
+ response = u_boot_console.run_command('unbind simple_bus {}'.format(child_of_child2_index))
+ assert response == ''
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+ assert not in_tree(tree, 'generic_simple_bus', 'simple_bus', 'generic_simple_bus', 2, True)
+ child_of_child2_line = get_next_line(tree, 'bind-test-child2')
+ assert child_of_child2_line == ''
+
+ #bind generic_simple_bus as a child of bind-test-child2
+ response = u_boot_console.run_command('bind {} {} generic_simple_bus'.format(child2_uclass, child2_index, 'generic_simple_bus'))
+
+ #check that the child is there and its uclass/index pair is right
+ tree = u_boot_console.run_command('dm tree')
+ treelines = [x.strip() for x in tree.splitlines() if x.strip()]
+
+ child_of_child2_line = get_next_line(tree, 'bind-test-child2')
+ assert child_of_child2_line
+ child_of_child2_index = int(child_of_child2_line.split()[1])
+ assert in_tree(tree, 'generic_simple_bus', 'simple_bus', 'generic_simple_bus', 2, True)
+ assert child_of_child2_index == child2_index + 1
+
+ #unbind the child and check it has been removed
+ response = u_boot_console.run_command('unbind {} {} generic_simple_bus'.format(child2_uclass, child2_index, 'generic_simple_bus'))
+ assert response == ''
+
+ tree = u_boot_console.run_command('dm tree')
+ assert in_tree(tree, 'bind-test-child2', 'simple_bus', 'generic_simple_bus', 1, True)
+
+ child_of_child2_line = get_next_line(tree, 'bind-test-child2')
+ assert child_of_child2_line == ''
+
+ #unbind the child again and check it doesn't change the tree
+ tree_old = u_boot_console.run_command('dm tree')
+ response = u_boot_console.run_command('unbind {} {} generic_simple_bus'.format(child2_uclass, child2_index, 'generic_simple_bus'))
+ tree_new = u_boot_console.run_command('dm tree')
+
+ assert response == ''
+ assert tree_old == tree_new
+
+ response = u_boot_console.run_command('unbind /bind-test')
+ assert response == ''
diff --git a/test/py/tests/test_dfu.py b/test/py/tests/test_dfu.py
new file mode 100644
index 00000000..5d87eb34
--- /dev/null
+++ b/test/py/tests/test_dfu.py
@@ -0,0 +1,320 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test U-Boot's "dfu" command. The test starts DFU in U-Boot, waits for USB
+# device enumeration on the host, executes dfu-util multiple times to test
+# various transfer sizes, many of which trigger USB driver edge cases, and
+# finally aborts the "dfu" command in U-Boot.
+
+import os
+import os.path
+import pytest
+import u_boot_utils
+
+"""
+Note: This test relies on:
+
+a) boardenv_* to contain configuration values to define which USB ports are
+available for testing. Without this, this test will be automatically skipped.
+For example:
+
+env__usb_dev_ports = (
+ {
+ 'fixture_id': 'micro_b',
+ 'tgt_usb_ctlr': '0',
+ 'host_usb_dev_node': '/dev/usbdev-p2371-2180',
+ # This parameter is optional /if/ you only have a single board
+ # attached to your host at a time.
+ 'host_usb_port_path': '3-13',
+ },
+)
+
+# Optional entries (required only when 'alt_id_test_file' and
+# 'alt_id_dummy_file' are specified).
+test_file_name = '/dfu_test.bin'
+dummy_file_name = '/dfu_dummy.bin'
+# Above files are used to generate proper 'alt_info' entry
+'alt_info': '/%s ext4 0 2;/%s ext4 0 2' % (test_file_name, dummy_file_name),
+
+env__dfu_configs = (
+ # eMMC, partition 1
+ {
+ 'fixture_id': 'emmc',
+ 'alt_info': '/dfu_test.bin ext4 0 1;/dfu_dummy.bin ext4 0 1',
+ 'cmd_params': 'mmc 0',
+ # This value is optional.
+ # If present, it specified the set of transfer sizes tested.
+ # If missing, a default list of sizes will be used, which covers
+ # various useful corner cases.
+ # Manually specifying test sizes is useful if you wish to test 4 DFU
+ # configurations, but don't want to test every single transfer size
+ # on each, to avoid bloating the overall time taken by testing.
+ 'test_sizes': (63, 64, 65),
+ # This value is optional.
+ # The name of the environment variable that the the dfu command reads
+ # alt info from. If unspecified, this defaults to dfu_alt_info, which is
+ # valid for most systems. Some systems use a different variable name.
+ # One example is the Odroid XU3, which automatically generates
+ # $dfu_alt_info, each time the dfu command is run, by concatenating
+ # $dfu_alt_boot and $dfu_alt_system.
+ 'alt_info_env_name': 'dfu_alt_system',
+ # This value is optional.
+ # For boards which require the 'test file' alt setting number other than
+ # default (0) it is possible to specify exact file name to be used as
+ # this parameter.
+ 'alt_id_test_file': test_file_name,
+ # This value is optional.
+ # For boards which require the 'dummy file' alt setting number other
+ # than default (1) it is possible to specify exact file name to be used
+ # as this parameter.
+ 'alt_id_dummy_file': dummy_file_name,
+ },
+)
+
+b) udev rules to set permissions on devices nodes, so that sudo is not
+required. For example:
+
+ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", KERNELS=="3-13", MODE:="666"
+
+(You may wish to change the group ID instead of setting the permissions wide
+open. All that matters is that the user ID running the test can access the
+device.)
+
+c) An optional udev rule to give you a persistent value to use in
+host_usb_dev_node. For example:
+
+IMPORT{builtin}="path_id"
+ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="", SYMLINK+="bus/usb/by-path/$env{ID_PATH}"
+ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="?*", SYMLINK+="bus/usb/by-path/$env{ID_PATH}-port$env{.ID_PORT}"
+"""
+
+# The set of file sizes to test. These values trigger various edge-cases such
+# as one less than, equal to, and one greater than typical USB max packet
+# sizes, and similar boundary conditions.
+test_sizes_default = (
+ 64 - 1,
+ 64,
+ 64 + 1,
+ 128 - 1,
+ 128,
+ 128 + 1,
+ 960 - 1,
+ 960,
+ 960 + 1,
+ 4096 - 1,
+ 4096,
+ 4096 + 1,
+ 1024 * 1024 - 1,
+ 1024 * 1024,
+ 8 * 1024 * 1024,
+)
+
+first_usb_dev_port = None
+
+@pytest.mark.buildconfigspec('cmd_dfu')
+@pytest.mark.requiredtool('dfu-util')
+def test_dfu(u_boot_console, env__usb_dev_port, env__dfu_config):
+ """Test the "dfu" command; the host system must be able to enumerate a USB
+ device when "dfu" is running, various DFU transfers are tested, and the
+ USB device must disappear when "dfu" is aborted.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__usb_dev_port: The single USB device-mode port specification on
+ which to run the test. See the file-level comment above for
+ details of the format.
+ env__dfu_config: The single DFU (memory region) configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ def start_dfu():
+ """Start U-Boot's dfu shell command.
+
+ This also waits for the host-side USB enumeration process to complete.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ u_boot_utils.wait_until_file_open_fails(
+ env__usb_dev_port['host_usb_dev_node'], True)
+ fh = u_boot_utils.attempt_to_open_file(
+ env__usb_dev_port['host_usb_dev_node'])
+ if fh:
+ fh.close()
+ raise Exception('USB device present before dfu command invoked')
+
+ u_boot_console.log.action(
+ 'Starting long-running U-Boot dfu shell command')
+
+ dfu_alt_info_env = env__dfu_config.get('alt_info_env_name', \
+ 'dfu_alt_info')
+
+ cmd = 'setenv "%s" "%s"' % (dfu_alt_info_env,
+ env__dfu_config['alt_info'])
+ u_boot_console.run_command(cmd)
+
+ cmd = 'dfu 0 ' + env__dfu_config['cmd_params']
+ u_boot_console.run_command(cmd, wait_for_prompt=False)
+ u_boot_console.log.action('Waiting for DFU USB device to appear')
+ fh = u_boot_utils.wait_until_open_succeeds(
+ env__usb_dev_port['host_usb_dev_node'])
+ fh.close()
+
+ def stop_dfu(ignore_errors):
+ """Stop U-Boot's dfu shell command from executing.
+
+ This also waits for the host-side USB de-enumeration process to
+ complete.
+
+ Args:
+ ignore_errors: Ignore any errors. This is useful if an error has
+ already been detected, and the code is performing best-effort
+ cleanup. In this case, we do not want to mask the original
+ error by "honoring" any new errors.
+
+ Returns:
+ Nothing.
+ """
+
+ try:
+ u_boot_console.log.action(
+ 'Stopping long-running U-Boot dfu shell command')
+ u_boot_console.ctrlc()
+ u_boot_console.log.action(
+ 'Waiting for DFU USB device to disappear')
+ u_boot_utils.wait_until_file_open_fails(
+ env__usb_dev_port['host_usb_dev_node'], ignore_errors)
+ except:
+ if not ignore_errors:
+ raise
+
+ def run_dfu_util(alt_setting, fn, up_dn_load_arg):
+ """Invoke dfu-util on the host.
+
+ Args:
+ alt_setting: The DFU "alternate setting" identifier to interact
+ with.
+ fn: The host-side file name to transfer.
+ up_dn_load_arg: '-U' or '-D' depending on whether a DFU upload or
+ download operation should be performed.
+
+ Returns:
+ Nothing.
+ """
+
+ cmd = ['dfu-util', '-a', alt_setting, up_dn_load_arg, fn]
+ if 'host_usb_port_path' in env__usb_dev_port:
+ cmd += ['-p', env__usb_dev_port['host_usb_port_path']]
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ u_boot_console.wait_for('Ctrl+C to exit ...')
+
+ def dfu_write(alt_setting, fn):
+ """Write a file to the target board using DFU.
+
+ Args:
+ alt_setting: The DFU "alternate setting" identifier to interact
+ with.
+ fn: The host-side file name to transfer.
+
+ Returns:
+ Nothing.
+ """
+
+ run_dfu_util(alt_setting, fn, '-D')
+
+ def dfu_read(alt_setting, fn):
+ """Read a file from the target board using DFU.
+
+ Args:
+ alt_setting: The DFU "alternate setting" identifier to interact
+ with.
+ fn: The host-side file name to transfer.
+
+ Returns:
+ Nothing.
+ """
+
+ # dfu-util fails reads/uploads if the host file already exists
+ if os.path.exists(fn):
+ os.remove(fn)
+ run_dfu_util(alt_setting, fn, '-U')
+
+ def dfu_write_read_check(size):
+ """Test DFU transfers of a specific size of data
+
+ This function first writes data to the board then reads it back and
+ compares the written and read back data. Measures are taken to avoid
+ certain types of false positives.
+
+ Args:
+ size: The data size to test.
+
+ Returns:
+ Nothing.
+ """
+
+ test_f = u_boot_utils.PersistentRandomFile(u_boot_console,
+ 'dfu_%d.bin' % size, size)
+ readback_fn = u_boot_console.config.result_dir + '/dfu_readback.bin'
+
+ u_boot_console.log.action('Writing test data to DFU primary ' +
+ 'altsetting')
+ dfu_write(alt_setting_test_file, test_f.abs_fn)
+
+ u_boot_console.log.action('Writing dummy data to DFU secondary ' +
+ 'altsetting to clear DFU buffers')
+ dfu_write(alt_setting_dummy_file, dummy_f.abs_fn)
+
+ u_boot_console.log.action('Reading DFU primary altsetting for ' +
+ 'comparison')
+ dfu_read(alt_setting_test_file, readback_fn)
+
+ u_boot_console.log.action('Comparing written and read data')
+ written_hash = test_f.content_hash
+ read_back_hash = u_boot_utils.md5sum_file(readback_fn, size)
+ assert(written_hash == read_back_hash)
+
+ # This test may be executed against multiple USB ports. The test takes a
+ # long time, so we don't want to do the whole thing each time. Instead,
+ # execute the full test on the first USB port, and perform a very limited
+ # test on other ports. In the limited case, we solely validate that the
+ # host PC can enumerate the U-Boot USB device.
+ global first_usb_dev_port
+ if not first_usb_dev_port:
+ first_usb_dev_port = env__usb_dev_port
+ if env__usb_dev_port == first_usb_dev_port:
+ sizes = env__dfu_config.get('test_sizes', test_sizes_default)
+ else:
+ sizes = []
+
+ dummy_f = u_boot_utils.PersistentRandomFile(u_boot_console,
+ 'dfu_dummy.bin', 1024)
+
+ alt_setting_test_file = env__dfu_config.get('alt_id_test_file', '0')
+ alt_setting_dummy_file = env__dfu_config.get('alt_id_dummy_file', '1')
+
+ ignore_cleanup_errors = True
+ try:
+ start_dfu()
+
+ u_boot_console.log.action(
+ 'Overwriting DFU primary altsetting with dummy data')
+ dfu_write(alt_setting_test_file, dummy_f.abs_fn)
+
+ for size in sizes:
+ with u_boot_console.log.section('Data size %d' % size):
+ dfu_write_read_check(size)
+ # Make the status of each sub-test obvious. If the test didn't
+ # pass, an exception was thrown so this code isn't executed.
+ u_boot_console.log.status_pass('OK')
+ ignore_cleanup_errors = False
+ finally:
+ stop_dfu(ignore_cleanup_errors)
diff --git a/test/py/tests/test_efi_loader.py b/test/py/tests/test_efi_loader.py
new file mode 100644
index 00000000..d6b214f8
--- /dev/null
+++ b/test/py/tests/test_efi_loader.py
@@ -0,0 +1,196 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+# Copyright (c) 2016, Alexander Graf <agraf@suse.de>
+#
+# based on test_net.py.
+
+# Test efi loader implementation
+
+import pytest
+import u_boot_utils
+
+"""
+Note: This test relies on boardenv_* containing configuration values to define
+which network environment is available for testing. Without this, the parts
+that rely on network will be automatically skipped.
+
+For example:
+
+# Boolean indicating whether the Ethernet device is attached to USB, and hence
+# USB enumeration needs to be performed prior to network tests.
+# This variable may be omitted if its value is False.
+env__net_uses_usb = False
+
+# Boolean indicating whether the Ethernet device is attached to PCI, and hence
+# PCI enumeration needs to be performed prior to network tests.
+# This variable may be omitted if its value is False.
+env__net_uses_pci = True
+
+# True if a DHCP server is attached to the network, and should be tested.
+# If DHCP testing is not possible or desired, this variable may be omitted or
+# set to False.
+env__net_dhcp_server = True
+
+# A list of environment variables that should be set in order to configure a
+# static IP. If solely relying on DHCP, this variable may be omitted or set to
+# an empty list.
+env__net_static_env_vars = [
+ ('ipaddr', '10.0.0.100'),
+ ('netmask', '255.255.255.0'),
+ ('serverip', '10.0.0.1'),
+]
+
+# Details regarding a file that may be read from a TFTP server. This variable
+# may be omitted or set to None if TFTP testing is not possible or desired.
+env__efi_loader_helloworld_file = {
+ 'fn': 'lib/efi_loader/helloworld.efi',
+ 'size': 5058624,
+ 'crc32': 'c2244b26',
+}
+"""
+
+net_set_up = False
+
+def test_efi_pre_commands(u_boot_console):
+ """Execute any commands required to enable network hardware.
+
+ These commands are provided by the boardenv_* file; see the comment at the
+ beginning of this file.
+ """
+
+ init_usb = u_boot_console.config.env.get('env__net_uses_usb', False)
+ if init_usb:
+ u_boot_console.run_command('usb start')
+
+ init_pci = u_boot_console.config.env.get('env__net_uses_pci', False)
+ if init_pci:
+ u_boot_console.run_command('pci enum')
+
+@pytest.mark.buildconfigspec('cmd_dhcp')
+def test_efi_dhcp(u_boot_console):
+ """Test the dhcp command.
+
+ The boardenv_* file may be used to enable/disable this test; see the
+ comment at the beginning of this file.
+ """
+
+ test_dhcp = u_boot_console.config.env.get('env__net_dhcp_server', False)
+ if not test_dhcp:
+ pytest.skip('No DHCP server available')
+
+ u_boot_console.run_command('setenv autoload no')
+ output = u_boot_console.run_command('dhcp')
+ assert 'DHCP client bound to address ' in output
+
+ global net_set_up
+ net_set_up = True
+
+@pytest.mark.buildconfigspec('net')
+def test_efi_setup_static(u_boot_console):
+ """Set up a static IP configuration.
+
+ The configuration is provided by the boardenv_* file; see the comment at
+ the beginning of this file.
+ """
+
+ env_vars = u_boot_console.config.env.get('env__net_static_env_vars', None)
+ if not env_vars:
+ pytest.skip('No static network configuration is defined')
+
+ for (var, val) in env_vars:
+ u_boot_console.run_command('setenv %s %s' % (var, val))
+
+ global net_set_up
+ net_set_up = True
+
+def fetch_tftp_file(u_boot_console, env_conf):
+ """Grab an env described file via TFTP and return its address
+
+ A file as described by an env config <env_conf> is downloaded from the TFTP
+ server. The address to that file is returned.
+ """
+ if not net_set_up:
+ pytest.skip('Network not initialized')
+
+ f = u_boot_console.config.env.get(env_conf, None)
+ if not f:
+ pytest.skip('No %s binary specified in environment' % env_conf)
+
+ addr = f.get('addr', None)
+ if not addr:
+ addr = u_boot_utils.find_ram_base(u_boot_console)
+
+ fn = f['fn']
+ output = u_boot_console.run_command('tftpboot %x %s' % (addr, fn))
+ expected_text = 'Bytes transferred = '
+ sz = f.get('size', None)
+ if sz:
+ expected_text += '%d' % sz
+ assert expected_text in output
+
+ expected_crc = f.get('crc32', None)
+ if not expected_crc:
+ return addr
+
+ if u_boot_console.config.buildconfig.get('config_cmd_crc32', 'n') != 'y':
+ return addr
+
+ output = u_boot_console.run_command('crc32 %x $filesize' % addr)
+ assert expected_crc in output
+
+ return addr
+
+@pytest.mark.buildconfigspec('cmd_bootefi_hello_compile')
+def test_efi_helloworld_net(u_boot_console):
+ """Run the helloworld.efi binary via TFTP.
+
+ The helloworld.efi file is downloaded from the TFTP server and gets
+ executed.
+ """
+
+ addr = fetch_tftp_file(u_boot_console, 'env__efi_loader_helloworld_file')
+
+ output = u_boot_console.run_command('bootefi %x' % addr)
+ expected_text = 'Hello, world'
+ assert expected_text in output
+ expected_text = '## Application terminated, r = 0'
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_bootefi_hello')
+def test_efi_helloworld_builtin(u_boot_console):
+ """Run the builtin helloworld.efi binary.
+
+ The helloworld.efi file is included in U-Boot, execute it using the
+ special "bootefi hello" command.
+ """
+
+ output = u_boot_console.run_command('bootefi hello')
+ expected_text = 'Hello, world'
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_bootefi')
+def test_efi_grub_net(u_boot_console):
+ """Run the grub.efi binary via TFTP.
+
+ The grub.efi file is downloaded from the TFTP server and gets
+ executed.
+ """
+
+ addr = fetch_tftp_file(u_boot_console, 'env__efi_loader_grub_file')
+
+ u_boot_console.run_command('bootefi %x' % addr, wait_for_prompt=False)
+
+ # Verify that we have an SMBIOS table
+ check_smbios = u_boot_console.config.env.get('env__efi_loader_check_smbios', False)
+ if check_smbios:
+ u_boot_console.wait_for('grub>')
+ output = u_boot_console.run_command('lsefisystab', wait_for_prompt=False, wait_for_echo=False)
+ u_boot_console.wait_for('SMBIOS')
+
+ # Then exit cleanly
+ u_boot_console.wait_for('grub>')
+ output = u_boot_console.run_command('exit', wait_for_prompt=False, wait_for_echo=False)
+ u_boot_console.wait_for('r = 0')
+
+ # And give us our U-Boot prompt back
+ u_boot_console.run_command('')
diff --git a/test/py/tests/test_efi_selftest.py b/test/py/tests/test_efi_selftest.py
new file mode 100644
index 00000000..ca015420
--- /dev/null
+++ b/test/py/tests/test_efi_selftest.py
@@ -0,0 +1,198 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2017, Heinrich Schuchardt <xypron.glpk@gmx.de>
+
+# Test efi API implementation
+
+import pytest
+import u_boot_utils
+
+@pytest.mark.buildconfigspec('cmd_bootefi_selftest')
+def test_efi_selftest(u_boot_console):
+ """Test the UEFI implementation
+
+ :param u_boot_console: U-Boot console
+
+ This function executes all selftests that are not marked as on request.
+ """
+ u_boot_console.run_command(cmd='setenv efi_selftest')
+ u_boot_console.run_command(cmd='bootefi selftest', wait_for_prompt=False)
+ m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key'])
+ if m != 0:
+ raise Exception('Failures occurred during the EFI selftest')
+ u_boot_console.restart_uboot();
+
+@pytest.mark.buildconfigspec('cmd_bootefi_selftest')
+@pytest.mark.buildconfigspec('of_control')
+@pytest.mark.notbuildconfigspec('generate_acpi_table')
+def test_efi_selftest_device_tree(u_boot_console):
+ u_boot_console.run_command(cmd='setenv efi_selftest list')
+ output = u_boot_console.run_command('bootefi selftest')
+ assert '\'device tree\'' in output
+ u_boot_console.run_command(cmd='setenv efi_selftest device tree')
+ u_boot_console.run_command(cmd='setenv -f serial# Testing DT')
+ u_boot_console.run_command(cmd='bootefi selftest ${fdtcontroladdr}', wait_for_prompt=False)
+ m = u_boot_console.p.expect(['serial-number: Testing DT', 'U-Boot'])
+ if m != 0:
+ raise Exception('serial-number missing in device tree')
+ u_boot_console.restart_uboot();
+
+@pytest.mark.buildconfigspec('cmd_bootefi_selftest')
+def test_efi_selftest_watchdog_reboot(u_boot_console):
+ u_boot_console.run_command(cmd='setenv efi_selftest list')
+ output = u_boot_console.run_command('bootefi selftest')
+ assert '\'watchdog reboot\'' in output
+ u_boot_console.run_command(cmd='setenv efi_selftest watchdog reboot')
+ u_boot_console.run_command(cmd='bootefi selftest', wait_for_prompt=False)
+ m = u_boot_console.p.expect(['resetting', 'U-Boot'])
+ if m != 0:
+ raise Exception('Reset failed in \'watchdog reboot\' test')
+ u_boot_console.restart_uboot();
+
+@pytest.mark.buildconfigspec('cmd_bootefi_selftest')
+def test_efi_selftest_text_input(u_boot_console):
+ """Test the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
+
+ :param u_boot_console: U-Boot console
+
+ This function calls the text input EFI selftest.
+ """
+ u_boot_console.run_command(cmd='setenv efi_selftest text input')
+ output = u_boot_console.run_command(cmd='bootefi selftest',
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect([r'To terminate type \'x\''])
+ if m != 0:
+ raise Exception('No prompt for \'text input\' test')
+ u_boot_console.drain_console()
+ u_boot_console.p.timeout = 500
+ # EOT
+ u_boot_console.run_command(cmd=chr(4), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 4 \(unknown\), scan code 0 \(Null\)'])
+ if m != 0:
+ raise Exception('EOT failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # BS
+ u_boot_console.run_command(cmd=chr(8), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 8 \(BS\), scan code 0 \(Null\)'])
+ if m != 0:
+ raise Exception('BS failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # TAB
+ u_boot_console.run_command(cmd=chr(9), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 9 \(TAB\), scan code 0 \(Null\)'])
+ if m != 0:
+ raise Exception('BS failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # a
+ u_boot_console.run_command(cmd='a', wait_for_echo=False, send_nl=False,
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 97 \(\'a\'\), scan code 0 \(Null\)'])
+ if m != 0:
+ raise Exception('\'a\' failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # UP escape sequence
+ u_boot_console.run_command(cmd=chr(27) + '[A', wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 0 \(Null\), scan code 1 \(Up\)'])
+ if m != 0:
+ raise Exception('UP failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # Euro sign
+ u_boot_console.run_command(cmd=b'\xe2\x82\xac'.decode(), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect([r'Unicode char 8364 \(\''])
+ if m != 0:
+ raise Exception('Euro sign failed in \'text input\' test')
+ u_boot_console.drain_console()
+ u_boot_console.run_command(cmd='x', wait_for_echo=False, send_nl=False,
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key'])
+ if m != 0:
+ raise Exception('Failures occurred during the EFI selftest')
+ u_boot_console.restart_uboot();
+
+@pytest.mark.buildconfigspec('cmd_bootefi_selftest')
+def test_efi_selftest_text_input_ex(u_boot_console):
+ """Test the EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL
+
+ :param u_boot_console: U-Boot console
+
+ This function calls the extended text input EFI selftest.
+ """
+ u_boot_console.run_command(cmd='setenv efi_selftest extended text input')
+ output = u_boot_console.run_command(cmd='bootefi selftest',
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect([r'To terminate type \'CTRL\+x\''])
+ if m != 0:
+ raise Exception('No prompt for \'text input\' test')
+ u_boot_console.drain_console()
+ u_boot_console.p.timeout = 500
+ # EOT
+ u_boot_console.run_command(cmd=chr(4), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 100 \(\'d\'\), scan code 0 \(CTRL\+Null\)'])
+ if m != 0:
+ raise Exception('EOT failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # BS
+ u_boot_console.run_command(cmd=chr(8), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 8 \(BS\), scan code 0 \(\+Null\)'])
+ if m != 0:
+ raise Exception('BS failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # TAB
+ u_boot_console.run_command(cmd=chr(9), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 9 \(TAB\), scan code 0 \(\+Null\)'])
+ if m != 0:
+ raise Exception('TAB failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # a
+ u_boot_console.run_command(cmd='a', wait_for_echo=False, send_nl=False,
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 97 \(\'a\'\), scan code 0 \(Null\)'])
+ if m != 0:
+ raise Exception('\'a\' failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # UP escape sequence
+ u_boot_console.run_command(cmd=chr(27) + '[A', wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 0 \(Null\), scan code 1 \(\+Up\)'])
+ if m != 0:
+ raise Exception('UP failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # Euro sign
+ u_boot_console.run_command(cmd=b'\xe2\x82\xac'.decode(), wait_for_echo=False,
+ send_nl=False, wait_for_prompt=False)
+ m = u_boot_console.p.expect([r'Unicode char 8364 \(\''])
+ if m != 0:
+ raise Exception('Euro sign failed in \'text input\' test')
+ u_boot_console.drain_console()
+ # SHIFT+ALT+FN 5
+ u_boot_console.run_command(cmd=b'\x1b\x5b\x31\x35\x3b\x34\x7e'.decode(),
+ wait_for_echo=False, send_nl=False,
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect(
+ [r'Unicode char 0 \(Null\), scan code 15 \(SHIFT\+ALT\+FN 5\)'])
+ if m != 0:
+ raise Exception('SHIFT+ALT+FN 5 failed in \'text input\' test')
+ u_boot_console.drain_console()
+ u_boot_console.run_command(cmd=chr(24), wait_for_echo=False, send_nl=False,
+ wait_for_prompt=False)
+ m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key'])
+ if m != 0:
+ raise Exception('Failures occurred during the EFI selftest')
+ u_boot_console.restart_uboot();
diff --git a/test/py/tests/test_env.py b/test/py/tests/test_env.py
new file mode 100644
index 00000000..6ff38f10
--- /dev/null
+++ b/test/py/tests/test_env.py
@@ -0,0 +1,338 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test operation of shell commands relating to environment variables.
+
+import pytest
+import u_boot_utils
+
+# FIXME: This might be useful for other tests;
+# perhaps refactor it into ConsoleBase or some other state object?
+class StateTestEnv(object):
+ """Container that represents the state of all U-Boot environment variables.
+ This enables quick determination of existant/non-existant variable
+ names.
+ """
+
+ def __init__(self, u_boot_console):
+ """Initialize a new StateTestEnv object.
+
+ Args:
+ u_boot_console: A U-Boot console.
+
+ Returns:
+ Nothing.
+ """
+
+ self.u_boot_console = u_boot_console
+ self.get_env()
+ self.set_var = self.get_non_existent_var()
+
+ def get_env(self):
+ """Read all current environment variables from U-Boot.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ if self.u_boot_console.config.buildconfig.get(
+ 'config_version_variable', 'n') == 'y':
+ with self.u_boot_console.disable_check('main_signon'):
+ response = self.u_boot_console.run_command('printenv')
+ else:
+ response = self.u_boot_console.run_command('printenv')
+ self.env = {}
+ for l in response.splitlines():
+ if not '=' in l:
+ continue
+ (var, value) = l.split('=', 1)
+ self.env[var] = value
+
+ def get_existent_var(self):
+ """Return the name of an environment variable that exists.
+
+ Args:
+ None.
+
+ Returns:
+ The name of an environment variable.
+ """
+
+ for var in self.env:
+ return var
+
+ def get_non_existent_var(self):
+ """Return the name of an environment variable that does not exist.
+
+ Args:
+ None.
+
+ Returns:
+ The name of an environment variable.
+ """
+
+ n = 0
+ while True:
+ var = 'test_env_' + str(n)
+ if var not in self.env:
+ return var
+ n += 1
+
+ste = None
+@pytest.fixture(scope='function')
+def state_test_env(u_boot_console):
+ """pytest fixture to provide a StateTestEnv object to tests."""
+
+ global ste
+ if not ste:
+ ste = StateTestEnv(u_boot_console)
+ return ste
+
+def unset_var(state_test_env, var):
+ """Unset an environment variable.
+
+ This both executes a U-Boot shell command and updates a StateTestEnv
+ object.
+
+ Args:
+ state_test_env: The StateTestEnv object to update.
+ var: The variable name to unset.
+
+ Returns:
+ Nothing.
+ """
+
+ state_test_env.u_boot_console.run_command('setenv %s' % var)
+ if var in state_test_env.env:
+ del state_test_env.env[var]
+
+def set_var(state_test_env, var, value):
+ """Set an environment variable.
+
+ This both executes a U-Boot shell command and updates a StateTestEnv
+ object.
+
+ Args:
+ state_test_env: The StateTestEnv object to update.
+ var: The variable name to set.
+ value: The value to set the variable to.
+
+ Returns:
+ Nothing.
+ """
+
+ bc = state_test_env.u_boot_console.config.buildconfig
+ if bc.get('config_hush_parser', None):
+ quote = '"'
+ else:
+ quote = ''
+ if ' ' in value:
+ pytest.skip('Space in variable value on non-Hush shell')
+
+ state_test_env.u_boot_console.run_command(
+ 'setenv %s %s%s%s' % (var, quote, value, quote))
+ state_test_env.env[var] = value
+
+def validate_empty(state_test_env, var):
+ """Validate that a variable is not set, using U-Boot shell commands.
+
+ Args:
+ var: The variable name to test.
+
+ Returns:
+ Nothing.
+ """
+
+ response = state_test_env.u_boot_console.run_command('echo $%s' % var)
+ assert response == ''
+
+def validate_set(state_test_env, var, value):
+ """Validate that a variable is set, using U-Boot shell commands.
+
+ Args:
+ var: The variable name to test.
+ value: The value the variable is expected to have.
+
+ Returns:
+ Nothing.
+ """
+
+ # echo does not preserve leading, internal, or trailing whitespace in the
+ # value. printenv does, and hence allows more complete testing.
+ response = state_test_env.u_boot_console.run_command('printenv %s' % var)
+ assert response == ('%s=%s' % (var, value))
+
+def test_env_echo_exists(state_test_env):
+ """Test echoing a variable that exists."""
+
+ var = state_test_env.get_existent_var()
+ value = state_test_env.env[var]
+ validate_set(state_test_env, var, value)
+
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_env_echo_non_existent(state_test_env):
+ """Test echoing a variable that doesn't exist."""
+
+ var = state_test_env.set_var
+ validate_empty(state_test_env, var)
+
+def test_env_printenv_non_existent(state_test_env):
+ """Test printenv error message for non-existant variables."""
+
+ var = state_test_env.set_var
+ c = state_test_env.u_boot_console
+ with c.disable_check('error_notification'):
+ response = c.run_command('printenv %s' % var)
+ assert(response == '## Error: "%s" not defined' % var)
+
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_env_unset_non_existent(state_test_env):
+ """Test unsetting a nonexistent variable."""
+
+ var = state_test_env.get_non_existent_var()
+ unset_var(state_test_env, var)
+ validate_empty(state_test_env, var)
+
+def test_env_set_non_existent(state_test_env):
+ """Test set a non-existant variable."""
+
+ var = state_test_env.set_var
+ value = 'foo'
+ set_var(state_test_env, var, value)
+ validate_set(state_test_env, var, value)
+
+def test_env_set_existing(state_test_env):
+ """Test setting an existant variable."""
+
+ var = state_test_env.set_var
+ value = 'bar'
+ set_var(state_test_env, var, value)
+ validate_set(state_test_env, var, value)
+
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_env_unset_existing(state_test_env):
+ """Test unsetting a variable."""
+
+ var = state_test_env.set_var
+ unset_var(state_test_env, var)
+ validate_empty(state_test_env, var)
+
+def test_env_expansion_spaces(state_test_env):
+ """Test expanding a variable that contains a space in its value."""
+
+ var_space = None
+ var_test = None
+ try:
+ var_space = state_test_env.get_non_existent_var()
+ set_var(state_test_env, var_space, ' ')
+
+ var_test = state_test_env.get_non_existent_var()
+ value = ' 1${%(var_space)s}${%(var_space)s} 2 ' % locals()
+ set_var(state_test_env, var_test, value)
+ value = ' 1 2 '
+ validate_set(state_test_env, var_test, value)
+ finally:
+ if var_space:
+ unset_var(state_test_env, var_space)
+ if var_test:
+ unset_var(state_test_env, var_test)
+
+@pytest.mark.buildconfigspec('cmd_importenv')
+def test_env_import_checksum_no_size(state_test_env):
+ """Test that omitted ('-') size parameter with checksum validation fails the
+ env import function.
+ """
+ c = state_test_env.u_boot_console
+ ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
+ addr = '%08x' % ram_base
+
+ with c.disable_check('error_notification'):
+ response = c.run_command('env import -c %s -' % addr)
+ assert(response == '## Error: external checksum format must pass size')
+
+@pytest.mark.buildconfigspec('cmd_importenv')
+def test_env_import_whitelist_checksum_no_size(state_test_env):
+ """Test that omitted ('-') size parameter with checksum validation fails the
+ env import function when variables are passed as parameters.
+ """
+ c = state_test_env.u_boot_console
+ ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
+ addr = '%08x' % ram_base
+
+ with c.disable_check('error_notification'):
+ response = c.run_command('env import -c %s - foo1 foo2 foo4' % addr)
+ assert(response == '## Error: external checksum format must pass size')
+
+@pytest.mark.buildconfigspec('cmd_exportenv')
+@pytest.mark.buildconfigspec('cmd_importenv')
+def test_env_import_whitelist(state_test_env):
+ """Test importing only a handful of env variables from an environment."""
+ c = state_test_env.u_boot_console
+ ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
+ addr = '%08x' % ram_base
+
+ set_var(state_test_env, 'foo1', 'bar1')
+ set_var(state_test_env, 'foo2', 'bar2')
+ set_var(state_test_env, 'foo3', 'bar3')
+
+ c.run_command('env export %s' % addr)
+
+ unset_var(state_test_env, 'foo1')
+ set_var(state_test_env, 'foo2', 'test2')
+ set_var(state_test_env, 'foo4', 'bar4')
+
+ # no foo1 in current env, foo2 overridden, foo3 should be of the value
+ # before exporting and foo4 should be of the value before importing.
+ c.run_command('env import %s - foo1 foo2 foo4' % addr)
+
+ validate_set(state_test_env, 'foo1', 'bar1')
+ validate_set(state_test_env, 'foo2', 'bar2')
+ validate_set(state_test_env, 'foo3', 'bar3')
+ validate_set(state_test_env, 'foo4', 'bar4')
+
+ # Cleanup test environment
+ unset_var(state_test_env, 'foo1')
+ unset_var(state_test_env, 'foo2')
+ unset_var(state_test_env, 'foo3')
+ unset_var(state_test_env, 'foo4')
+
+@pytest.mark.buildconfigspec('cmd_exportenv')
+@pytest.mark.buildconfigspec('cmd_importenv')
+def test_env_import_whitelist_delete(state_test_env):
+
+ """Test importing only a handful of env variables from an environment, with.
+ deletion if a var A that is passed to env import is not in the
+ environment to be imported.
+ """
+ c = state_test_env.u_boot_console
+ ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
+ addr = '%08x' % ram_base
+
+ set_var(state_test_env, 'foo1', 'bar1')
+ set_var(state_test_env, 'foo2', 'bar2')
+ set_var(state_test_env, 'foo3', 'bar3')
+
+ c.run_command('env export %s' % addr)
+
+ unset_var(state_test_env, 'foo1')
+ set_var(state_test_env, 'foo2', 'test2')
+ set_var(state_test_env, 'foo4', 'bar4')
+
+ # no foo1 in current env, foo2 overridden, foo3 should be of the value
+ # before exporting and foo4 should be empty.
+ c.run_command('env import -d %s - foo1 foo2 foo4' % addr)
+
+ validate_set(state_test_env, 'foo1', 'bar1')
+ validate_set(state_test_env, 'foo2', 'bar2')
+ validate_set(state_test_env, 'foo3', 'bar3')
+ validate_empty(state_test_env, 'foo4')
+
+ # Cleanup test environment
+ unset_var(state_test_env, 'foo1')
+ unset_var(state_test_env, 'foo2')
+ unset_var(state_test_env, 'foo3')
+ unset_var(state_test_env, 'foo4')
diff --git a/test/py/tests/test_fit.py b/test/py/tests/test_fit.py
new file mode 100755
index 00000000..356d9a20
--- /dev/null
+++ b/test/py/tests/test_fit.py
@@ -0,0 +1,457 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2013, Google Inc.
+#
+# Sanity check of the FIT handling in U-Boot
+
+import os
+import pytest
+import struct
+import u_boot_utils as util
+
+# Define a base ITS which we can adjust using % and a dictionary
+base_its = '''
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel@1 {
+ data = /incbin/("%(kernel)s");
+ type = "kernel";
+ arch = "sandbox";
+ os = "linux";
+ compression = "%(compression)s";
+ load = <0x40000>;
+ entry = <0x8>;
+ };
+ kernel@2 {
+ data = /incbin/("%(loadables1)s");
+ type = "kernel";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ %(loadables1_load)s
+ entry = <0x0>;
+ };
+ fdt@1 {
+ description = "snow";
+ data = /incbin/("%(fdt)s");
+ type = "flat_dt";
+ arch = "sandbox";
+ %(fdt_load)s
+ compression = "%(compression)s";
+ signature@1 {
+ algo = "sha1,rsa2048";
+ key-name-hint = "dev";
+ };
+ };
+ ramdisk@1 {
+ description = "snow";
+ data = /incbin/("%(ramdisk)s");
+ type = "ramdisk";
+ arch = "sandbox";
+ os = "linux";
+ %(ramdisk_load)s
+ compression = "%(compression)s";
+ };
+ ramdisk@2 {
+ description = "snow";
+ data = /incbin/("%(loadables2)s");
+ type = "ramdisk";
+ arch = "sandbox";
+ os = "linux";
+ %(loadables2_load)s
+ compression = "none";
+ };
+ };
+ configurations {
+ default = "conf@1";
+ conf@1 {
+ kernel = "kernel@1";
+ fdt = "fdt@1";
+ %(ramdisk_config)s
+ %(loadables_config)s
+ };
+ };
+};
+'''
+
+# Define a base FDT - currently we don't use anything in this
+base_fdt = '''
+/dts-v1/;
+
+/ {
+ model = "Sandbox Verified Boot Test";
+ compatible = "sandbox";
+
+ reset@0 {
+ compatible = "sandbox,reset";
+ };
+
+};
+'''
+
+# This is the U-Boot script that is run for each test. First load the FIT,
+# then run the 'bootm' command, then save out memory from the places where
+# we expect 'bootm' to write things. Then quit.
+base_script = '''
+host load hostfs 0 %(fit_addr)x %(fit)s
+fdt addr %(fit_addr)x
+bootm start %(fit_addr)x
+bootm loados
+host save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
+host save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
+host save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
+host save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
+host save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
+'''
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('fit_signature')
+@pytest.mark.requiredtool('dtc')
+def test_fit(u_boot_console):
+ def make_fname(leaf):
+ """Make a temporary filename
+
+ Args:
+ leaf: Leaf name of file to create (within temporary directory)
+ Return:
+ Temporary filename
+ """
+
+ return os.path.join(cons.config.build_dir, leaf)
+
+ def filesize(fname):
+ """Get the size of a file
+
+ Args:
+ fname: Filename to check
+ Return:
+ Size of file in bytes
+ """
+ return os.stat(fname).st_size
+
+ def read_file(fname):
+ """Read the contents of a file
+
+ Args:
+ fname: Filename to read
+ Returns:
+ Contents of file as a string
+ """
+ with open(fname, 'rb') as fd:
+ return fd.read()
+
+ def make_dtb():
+ """Make a sample .dts file and compile it to a .dtb
+
+ Returns:
+ Filename of .dtb file created
+ """
+ src = make_fname('u-boot.dts')
+ dtb = make_fname('u-boot.dtb')
+ with open(src, 'w') as fd:
+ fd.write(base_fdt)
+ util.run_and_log(cons, ['dtc', src, '-O', 'dtb', '-o', dtb])
+ return dtb
+
+ def make_its(params):
+ """Make a sample .its file with parameters embedded
+
+ Args:
+ params: Dictionary containing parameters to embed in the %() strings
+ Returns:
+ Filename of .its file created
+ """
+ its = make_fname('test.its')
+ with open(its, 'w') as fd:
+ print(base_its % params, file=fd)
+ return its
+
+ def make_fit(mkimage, params):
+ """Make a sample .fit file ready for loading
+
+ This creates a .its script with the selected parameters and uses mkimage to
+ turn this into a .fit image.
+
+ Args:
+ mkimage: Filename of 'mkimage' utility
+ params: Dictionary containing parameters to embed in the %() strings
+ Return:
+ Filename of .fit file created
+ """
+ fit = make_fname('test.fit')
+ its = make_its(params)
+ util.run_and_log(cons, [mkimage, '-f', its, fit])
+ with open(make_fname('u-boot.dts'), 'w') as fd:
+ fd.write(base_fdt)
+ return fit
+
+ def make_kernel(filename, text):
+ """Make a sample kernel with test data
+
+ Args:
+ filename: the name of the file you want to create
+ Returns:
+ Full path and filename of the kernel it created
+ """
+ fname = make_fname(filename)
+ data = ''
+ for i in range(100):
+ data += 'this %s %d is unlikely to boot\n' % (text, i)
+ with open(fname, 'w') as fd:
+ print(data, file=fd)
+ return fname
+
+ def make_ramdisk(filename, text):
+ """Make a sample ramdisk with test data
+
+ Returns:
+ Filename of ramdisk created
+ """
+ fname = make_fname(filename)
+ data = ''
+ for i in range(100):
+ data += '%s %d was seldom used in the middle ages\n' % (text, i)
+ with open(fname, 'w') as fd:
+ print(data, file=fd)
+ return fname
+
+ def make_compressed(filename):
+ util.run_and_log(cons, ['gzip', '-f', '-k', filename])
+ return filename + '.gz'
+
+ def find_matching(text, match):
+ """Find a match in a line of text, and return the unmatched line portion
+
+ This is used to extract a part of a line from some text. The match string
+ is used to locate the line - we use the first line that contains that
+ match text.
+
+ Once we find a match, we discard the match string itself from the line,
+ and return what remains.
+
+ TODO: If this function becomes more generally useful, we could change it
+ to use regex and return groups.
+
+ Args:
+ text: Text to check (list of strings, one for each command issued)
+ match: String to search for
+ Return:
+ String containing unmatched portion of line
+ Exceptions:
+ ValueError: If match is not found
+
+ >>> find_matching(['first line:10', 'second_line:20'], 'first line:')
+ '10'
+ >>> find_matching(['first line:10', 'second_line:20'], 'second line')
+ Traceback (most recent call last):
+ ...
+ ValueError: Test aborted
+ >>> find_matching('first line:10\', 'second_line:20'], 'second_line:')
+ '20'
+ >>> find_matching('first line:10\', 'second_line:20\nthird_line:30'],
+ 'third_line:')
+ '30'
+ """
+ __tracebackhide__ = True
+ for line in '\n'.join(text).splitlines():
+ pos = line.find(match)
+ if pos != -1:
+ return line[:pos] + line[pos + len(match):]
+
+ pytest.fail("Expected '%s' but not found in output")
+
+ def check_equal(expected_fname, actual_fname, failure_msg):
+ """Check that a file matches its expected contents
+
+ This is always used on out-buffers whose size is decided by the test
+ script anyway, which in some cases may be larger than what we're
+ actually looking for. So it's safe to truncate it to the size of the
+ expected data.
+
+ Args:
+ expected_fname: Filename containing expected contents
+ actual_fname: Filename containing actual contents
+ failure_msg: Message to print on failure
+ """
+ expected_data = read_file(expected_fname)
+ actual_data = read_file(actual_fname)
+ if len(expected_data) < len(actual_data):
+ actual_data = actual_data[:len(expected_data)]
+ assert expected_data == actual_data, failure_msg
+
+ def check_not_equal(expected_fname, actual_fname, failure_msg):
+ """Check that a file does not match its expected contents
+
+ Args:
+ expected_fname: Filename containing expected contents
+ actual_fname: Filename containing actual contents
+ failure_msg: Message to print on failure
+ """
+ expected_data = read_file(expected_fname)
+ actual_data = read_file(actual_fname)
+ assert expected_data != actual_data, failure_msg
+
+ def run_fit_test(mkimage):
+ """Basic sanity check of FIT loading in U-Boot
+
+ TODO: Almost everything:
+ - hash algorithms - invalid hash/contents should be detected
+ - signature algorithms - invalid sig/contents should be detected
+ - compression
+ - checking that errors are detected like:
+ - image overwriting
+ - missing images
+ - invalid configurations
+ - incorrect os/arch/type fields
+ - empty data
+ - images too large/small
+ - invalid FDT (e.g. putting a random binary in instead)
+ - default configuration selection
+ - bootm command line parameters should have desired effect
+ - run code coverage to make sure we are testing all the code
+ """
+ # Set up invariant files
+ control_dtb = make_dtb()
+ kernel = make_kernel('test-kernel.bin', 'kernel')
+ ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
+ loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
+ loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
+ kernel_out = make_fname('kernel-out.bin')
+ fdt = make_fname('u-boot.dtb')
+ fdt_out = make_fname('fdt-out.dtb')
+ ramdisk_out = make_fname('ramdisk-out.bin')
+ loadables1_out = make_fname('loadables1-out.bin')
+ loadables2_out = make_fname('loadables2-out.bin')
+
+ # Set up basic parameters with default values
+ params = {
+ 'fit_addr' : 0x1000,
+
+ 'kernel' : kernel,
+ 'kernel_out' : kernel_out,
+ 'kernel_addr' : 0x40000,
+ 'kernel_size' : filesize(kernel),
+
+ 'fdt' : fdt,
+ 'fdt_out' : fdt_out,
+ 'fdt_addr' : 0x80000,
+ 'fdt_size' : filesize(control_dtb),
+ 'fdt_load' : '',
+
+ 'ramdisk' : ramdisk,
+ 'ramdisk_out' : ramdisk_out,
+ 'ramdisk_addr' : 0xc0000,
+ 'ramdisk_size' : filesize(ramdisk),
+ 'ramdisk_load' : '',
+ 'ramdisk_config' : '',
+
+ 'loadables1' : loadables1,
+ 'loadables1_out' : loadables1_out,
+ 'loadables1_addr' : 0x100000,
+ 'loadables1_size' : filesize(loadables1),
+ 'loadables1_load' : '',
+
+ 'loadables2' : loadables2,
+ 'loadables2_out' : loadables2_out,
+ 'loadables2_addr' : 0x140000,
+ 'loadables2_size' : filesize(loadables2),
+ 'loadables2_load' : '',
+
+ 'loadables_config' : '',
+ 'compression' : 'none',
+ }
+
+ # Make a basic FIT and a script to load it
+ fit = make_fit(mkimage, params)
+ params['fit'] = fit
+ cmd = base_script % params
+
+ # First check that we can load a kernel
+ # We could perhaps reduce duplication with some loss of readability
+ cons.config.dtb = control_dtb
+ cons.restart_uboot()
+ with cons.log.section('Kernel load'):
+ output = cons.run_command_list(cmd.splitlines())
+ check_equal(kernel, kernel_out, 'Kernel not loaded')
+ check_not_equal(control_dtb, fdt_out,
+ 'FDT loaded but should be ignored')
+ check_not_equal(ramdisk, ramdisk_out,
+ 'Ramdisk loaded but should not be')
+
+ # Find out the offset in the FIT where U-Boot has found the FDT
+ line = find_matching(output, 'Booting using the fdt blob at ')
+ fit_offset = int(line, 16) - params['fit_addr']
+ fdt_magic = struct.pack('>L', 0xd00dfeed)
+ data = read_file(fit)
+
+ # Now find where it actually is in the FIT (skip the first word)
+ real_fit_offset = data.find(fdt_magic, 4)
+ assert fit_offset == real_fit_offset, (
+ 'U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
+ (fit_offset, real_fit_offset))
+
+ # Now a kernel and an FDT
+ with cons.log.section('Kernel + FDT load'):
+ params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
+ fit = make_fit(mkimage, params)
+ cons.restart_uboot()
+ output = cons.run_command_list(cmd.splitlines())
+ check_equal(kernel, kernel_out, 'Kernel not loaded')
+ check_equal(control_dtb, fdt_out, 'FDT not loaded')
+ check_not_equal(ramdisk, ramdisk_out,
+ 'Ramdisk loaded but should not be')
+
+ # Try a ramdisk
+ with cons.log.section('Kernel + FDT + Ramdisk load'):
+ params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
+ params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
+ fit = make_fit(mkimage, params)
+ cons.restart_uboot()
+ output = cons.run_command_list(cmd.splitlines())
+ check_equal(ramdisk, ramdisk_out, 'Ramdisk not loaded')
+
+ # Configuration with some Loadables
+ with cons.log.section('Kernel + FDT + Ramdisk load + Loadables'):
+ params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
+ params['loadables1_load'] = ('load = <%#x>;' %
+ params['loadables1_addr'])
+ params['loadables2_load'] = ('load = <%#x>;' %
+ params['loadables2_addr'])
+ fit = make_fit(mkimage, params)
+ cons.restart_uboot()
+ output = cons.run_command_list(cmd.splitlines())
+ check_equal(loadables1, loadables1_out,
+ 'Loadables1 (kernel) not loaded')
+ check_equal(loadables2, loadables2_out,
+ 'Loadables2 (ramdisk) not loaded')
+
+ # Kernel, FDT and Ramdisk all compressed
+ with cons.log.section('(Kernel + FDT + Ramdisk) compressed'):
+ params['compression'] = 'gzip'
+ params['kernel'] = make_compressed(kernel)
+ params['fdt'] = make_compressed(fdt)
+ params['ramdisk'] = make_compressed(ramdisk)
+ fit = make_fit(mkimage, params)
+ cons.restart_uboot()
+ output = cons.run_command_list(cmd.splitlines())
+ check_equal(kernel, kernel_out, 'Kernel not loaded')
+ check_equal(control_dtb, fdt_out, 'FDT not loaded')
+ check_not_equal(ramdisk, ramdisk_out, 'Ramdisk got decompressed?')
+ check_equal(ramdisk + '.gz', ramdisk_out, 'Ramdist not loaded')
+
+
+ cons = u_boot_console
+ try:
+ # We need to use our own device tree file. Remember to restore it
+ # afterwards.
+ old_dtb = cons.config.dtb
+ mkimage = cons.config.build_dir + '/tools/mkimage'
+ run_fit_test(mkimage)
+ finally:
+ # Go back to the original U-Boot with the correct dtb.
+ cons.config.dtb = old_dtb
+ cons.restart_uboot()
diff --git a/test/py/tests/test_fpga.py b/test/py/tests/test_fpga.py
new file mode 100644
index 00000000..ca7ef8ea
--- /dev/null
+++ b/test/py/tests/test_fpga.py
@@ -0,0 +1,565 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (c) 2018, Xilinx Inc.
+#
+# Michal Simek
+# Siva Durga Prasad Paladugu
+
+import pytest
+import re
+import random
+import u_boot_utils
+
+"""
+Note: This test relies on boardenv_* containing configuration values to define
+the network available and files to be used for testing. Without this, this test
+will be automatically skipped.
+
+For example:
+
+# True if a DHCP server is attached to the network, and should be tested.
+env__net_dhcp_server = True
+
+# A list of environment variables that should be set in order to configure a
+# static IP. In this test case we atleast need serverip for performing tftpb
+# to get required files.
+env__net_static_env_vars = [
+ ('ipaddr', '10.0.0.100'),
+ ('netmask', '255.255.255.0'),
+ ('serverip', '10.0.0.1'),
+]
+
+# Details regarding the files that may be read from a TFTP server. .
+env__fpga_secure_readable_file = {
+ 'fn': 'auth_bhdr_ppk1_bit.bin',
+ 'enckupfn': 'auth_bhdr_enc_kup_load_bit.bin',
+ 'addr': 0x1000000,
+ 'keyaddr': 0x100000,
+ 'keyfn': 'key.txt',
+}
+
+env__fpga_under_test = {
+ 'dev': 0,
+ 'addr' : 0x1000000,
+ 'bitstream_load': 'compress.bin',
+ 'bitstream_load_size': 1831960,
+ 'bitstream_loadp': 'compress_pr.bin',
+ 'bitstream_loadp_size': 423352,
+ 'bitstream_loadb': 'compress.bit',
+ 'bitstream_loadb_size': 1832086,
+ 'bitstream_loadbp': 'compress_pr.bit',
+ 'bitstream_loadbp_size': 423491,
+ 'mkimage_legacy': 'download.ub',
+ 'mkimage_legacy_size': 13321468,
+ 'mkimage_legacy_gz': 'download.gz.ub',
+ 'mkimage_legacy_gz_size': 53632,
+ 'mkimage_fit': 'download-fit.ub',
+ 'mkimage_fit_size': 13322784,
+ 'loadfs': 'mmc 0 compress.bin',
+ 'loadfs_size': 1831960,
+ 'loadfs_block_size': 0x10000,
+}
+"""
+
+import test_net
+
+def check_dev(u_boot_console):
+ f = u_boot_console.config.env.get('env__fpga_under_test', None)
+ if not f:
+ pytest.skip('No FPGA to test')
+
+ dev = f.get('dev', -1)
+ if dev < 0:
+ pytest.fail('No dev specified via env__fpga_under_test')
+
+ return dev, f
+
+def load_file_from_var(u_boot_console, name):
+ dev, f = check_dev(u_boot_console)
+
+ addr = f.get('addr', -1)
+ if addr < 0:
+ pytest.fail('No address specified via env__fpga_under_test')
+
+ test_net.test_net_dhcp(u_boot_console)
+ test_net.test_net_setup_static(u_boot_console)
+ bit = f['%s' % (name)]
+ bit_size = f['%s_size' % (name)]
+
+ expected_tftp = 'Bytes transferred = %d' % bit_size
+ output = u_boot_console.run_command('tftpboot %x %s' % (addr, bit))
+ assert expected_tftp in output
+
+ return f, dev, addr, bit, bit_size
+
+###### FPGA FAIL test ######
+expected_usage = 'fpga - loadable FPGA image support'
+
+@pytest.mark.xfail
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_fail(u_boot_console):
+ # Test non valid fpga subcommand
+ expected = 'fpga: non existing command'
+ output = u_boot_console.run_command('fpga broken 0')
+ #assert expected in output
+ assert expected_usage in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_help(u_boot_console):
+ # Just show help
+ output = u_boot_console.run_command('fpga')
+ assert expected_usage in output
+
+
+###### FPGA DUMP tests ######
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_dump(u_boot_console):
+ pytest.skip('Not implemented now')
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_dump_variable(u_boot_console):
+ # Same as above but via "fpga" variable
+ pytest.skip('Not implemented now')
+
+###### FPGA INFO tests ######
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_info_fail(u_boot_console):
+ # Maybe this can be skipped completely
+ dev, f = check_dev(u_boot_console)
+
+ # Multiple parameters to fpga info should fail
+ expected = 'fpga: more parameters passed'
+ output = u_boot_console.run_command('fpga info 0 0')
+ #assert expected in output
+ assert expected_usage in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_info_list(u_boot_console):
+ # Maybe this can be skipped completely
+ dev, f = check_dev(u_boot_console)
+
+ # Code is design in a way that if fpga dev is not passed it should
+ # return list of all fpga devices in the system
+ u_boot_console.run_command('setenv fpga')
+ output = u_boot_console.run_command('fpga info')
+ assert expected_usage not in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_info(u_boot_console):
+ dev, f = check_dev(u_boot_console)
+
+ output = u_boot_console.run_command('fpga info %x' % (dev))
+ assert expected_usage not in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_info_variable(u_boot_console):
+ dev, f = check_dev(u_boot_console)
+
+ #
+ # fpga variable is storing device number which doesn't need to be passed
+ #
+ u_boot_console.run_command('setenv fpga %x' % (dev))
+
+ output = u_boot_console.run_command('fpga info')
+ # Variable cleanup
+ u_boot_console.run_command('setenv fpga')
+ assert expected_usage not in output
+
+###### FPGA LOAD tests ######
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_load_fail(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_load')
+
+ for cmd in ['dump', 'load', 'loadb']:
+ # missing dev parameter
+ expected = 'fpga: incorrect parameters passed'
+ output = u_boot_console.run_command('fpga %s %x $filesize' % (cmd, addr))
+ #assert expected in output
+ assert expected_usage in output
+
+ # more parameters - 0 at the end
+ expected = 'fpga: more parameters passed'
+ output = u_boot_console.run_command('fpga %s %x %x $filesize 0' % (cmd, dev, addr))
+ #assert expected in output
+ assert expected_usage in output
+
+ # 0 address
+ expected = 'fpga: zero fpga_data address'
+ output = u_boot_console.run_command('fpga %s %x 0 $filesize' % (cmd, dev))
+ #assert expected in output
+ assert expected_usage in output
+
+ # 0 filesize
+ expected = 'fpga: zero size'
+ output = u_boot_console.run_command('fpga %s %x %x 0' % (cmd, dev, addr))
+ #assert expected in output
+ assert expected_usage in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_load(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_load')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga load %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadp')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadp(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_load')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga load %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+ # And load also partial bistream
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_loadp')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadp %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadb(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_loadb')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadb %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadbp')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadbp(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_loadb')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadb %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+ # And load also partial bistream in bit format
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'bitstream_loadbp')
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadbp %x %x $filesize && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+###### FPGA LOADMK tests ######
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+def test_fpga_loadmk_fail(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ # load image but pass incorrect address to show error message
+ expected = 'Unknown image type'
+ output = u_boot_console.run_command('fpga loadmk %x %x' % (dev, addr + 0x10))
+ assert expected in output
+
+ # Pass more parameters then command expects - 0 at the end
+ output = u_boot_console.run_command('fpga loadmk %x %x 0' % (dev, addr))
+ #assert expected in output
+ assert expected_usage in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+def test_fpga_loadmk_legacy(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x %x && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.xfail
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+def test_fpga_loadmk_legacy_variable_fpga(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ u_boot_console.run_command('setenv fpga %x' % (dev))
+
+ # this testcase should cover case which looks like it is supported but dev pointer is broken by loading mkimage address
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x && echo %s' % (addr, expected_text))
+ u_boot_console.run_command('setenv fpga')
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+def test_fpga_loadmk_legacy_variable_fpgadata(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ u_boot_console.run_command('setenv fpgadata %x' % (addr))
+
+ # this testcase should cover case which looks like it is supported but dev pointer is broken by loading mkimage address
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x && echo %s' % (dev, expected_text))
+ u_boot_console.run_command('setenv fpgadata')
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+def test_fpga_loadmk_legacy_variable(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ u_boot_console.run_command('setenv fpga %x' % (dev))
+ u_boot_console.run_command('setenv fpgadata %x' % (addr))
+
+ # this testcase should cover case which looks like it is supported but dev pointer is broken by loading mkimage address
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk && echo %s' % (expected_text))
+ u_boot_console.run_command('setenv fpga')
+ u_boot_console.run_command('setenv fpgadata')
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.buildconfigspec('image_format_legacy')
+@pytest.mark.buildconfigspec('gzip')
+def test_fpga_loadmk_legacy_gz(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_legacy_gz')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x %x && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('fit')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadmk_fit_external(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_fit_external')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x %x:fpga && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('fit')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadmk_fit(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_fit')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x %x:fpga && echo %s' % (dev, addr, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('fit')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadmk_fit_variable_fpga(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_fit')
+
+ u_boot_console.run_command('imi %x' % (addr))
+ # FIXME this should fail - broken support in past
+ u_boot_console.run_command('setenv fpga %x' % (dev))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x:fpga && echo %s' % (addr, expected_text))
+ u_boot_console.run_command('setenv fpga')
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('fit')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadmk_fit_variable_fpgadata(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_fit')
+
+ u_boot_console.run_command('imi %x' % (addr))
+ # FIXME this should fail - broken support in past
+ u_boot_console.run_command('setenv fpgadata %x:fpga' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk %x && echo %s' % (dev, expected_text))
+ u_boot_console.run_command('setenv fpgadata')
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_loadmk')
+@pytest.mark.buildconfigspec('fit')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadmk_fit_variable(u_boot_console):
+ f, dev, addr, bit, bit_size = load_file_from_var(u_boot_console, 'mkimage_fit')
+
+ u_boot_console.run_command('imi %x' % (addr))
+
+ u_boot_console.run_command('setenv fpga %x' % (dev))
+ u_boot_console.run_command('setenv fpgadata %x:fpga' % (addr))
+
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadmk && echo %s' % (expected_text))
+ u_boot_console.run_command('setenv fpga')
+ u_boot_console.run_command('setenv fpgadata')
+ assert expected_text in output
+
+###### FPGA LOAD tests ######
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+def test_fpga_loadfs_fail(u_boot_console):
+ dev, f = check_dev(u_boot_console)
+
+ addr = f.get('addr', -1)
+ if addr < 0:
+ pytest.fail('No address specified via env__fpga_under_test')
+
+ bit = f['loadfs']
+ bit_size = f['loadfs_size']
+ block_size = f['loadfs_block_size']
+
+ # less params - dev number removed
+ expected = 'fpga: incorrect parameters passed'
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %s' % (addr, bit_size, block_size, bit))
+ #assert expected in output
+ assert expected_usage in output
+
+ # one more param - 0 at the end
+ # This is the longest command that's why there is no message from cmd/fpga.c
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x %s 0' % (dev, addr, bit_size, block_size, bit))
+ assert expected_usage in output
+
+ # zero address 0
+ expected = 'fpga: zero fpga_data address'
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x %s' % (dev, 0, bit_size, block_size, bit))
+ #assert expected in output
+ assert expected_usage in output
+
+ # bit_size 0
+ expected = 'fpga: zero size'
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x %s' % (dev, addr, 0, block_size, bit))
+ #assert expected in output
+ assert expected_usage in output
+
+ # block size 0
+ # FIXME this should pass but it failing too
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x %s' % (dev, addr, bit_size, 0, bit))
+ assert expected_usage in output
+
+ # non existing bitstream name
+ expected = 'Unable to read file noname'
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x mmc 0 noname' % (dev, addr, bit_size, block_size))
+ assert expected in output
+ assert expected_usage in output
+
+ # -1 dev number
+ expected = 'fpga_fsload: Invalid device number -1'
+ output = u_boot_console.run_command('fpga loadfs %d %x %x %x mmc 0 noname' % (-1, addr, bit_size, block_size))
+ assert expected in output
+ assert expected_usage in output
+
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_echo')
+def test_fpga_loadfs(u_boot_console):
+ dev, f = check_dev(u_boot_console)
+
+ addr = f.get('addr', -1)
+ if addr < 0:
+ pytest.fail('No address specified via env__fpga_under_test')
+
+ bit = f['loadfs']
+ bit_size = f['loadfs_size']
+ block_size = f['loadfs_block_size']
+
+ # This should be done better
+ expected_text = 'FPGA loaded successfully'
+ output = u_boot_console.run_command('fpga loadfs %x %x %x %x %s && echo %s' % (dev, addr, bit_size, block_size, bit, expected_text))
+ assert expected_text in output
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_load_secure')
+@pytest.mark.buildconfigspec('cmd_net')
+@pytest.mark.buildconfigspec('cmd_dhcp')
+@pytest.mark.buildconfigspec('net')
+def test_fpga_secure_bit_auth(u_boot_console):
+
+ test_net.test_net_dhcp(u_boot_console)
+ test_net.test_net_setup_static(u_boot_console)
+
+ f = u_boot_console.config.env.get('env__fpga_secure_readable_file', None)
+ if not f:
+ pytest.skip('No TFTP readable file to read')
+
+ addr = f.get('addr', None)
+ if not addr:
+ addr = u_boot_utils.find_ram_base(u_boot_console)
+
+ expected_tftp = 'Bytes transferred = '
+ fn = f['fn']
+ output = u_boot_console.run_command('tftpboot %x %s' % (addr, fn))
+ assert expected_tftp in output
+
+ expected_zynqmpsecure = 'Bitstream successfully loaded'
+ output = u_boot_console.run_command('fpga loads 0 %x $filesize 0 2' % (addr))
+ assert expected_zynqmpsecure in output
+
+
+@pytest.mark.buildconfigspec('cmd_fpga')
+@pytest.mark.buildconfigspec('cmd_fpga_load_secure')
+@pytest.mark.buildconfigspec('cmd_net')
+@pytest.mark.buildconfigspec('cmd_dhcp')
+@pytest.mark.buildconfigspec('net')
+def test_fpga_secure_bit_img_auth_kup(u_boot_console):
+
+ test_net.test_net_dhcp(u_boot_console)
+ test_net.test_net_setup_static(u_boot_console)
+
+ f = u_boot_console.config.env.get('env__fpga_secure_readable_file', None)
+ if not f:
+ pytest.skip('No TFTP readable file to read')
+
+ keyaddr = f.get('keyaddr', None)
+ if not keyaddr:
+ addr = u_boot_utils.find_ram_base(u_boot_console)
+ expected_tftp = 'Bytes transferred = '
+ keyfn = f['keyfn']
+ output = u_boot_console.run_command('tftpboot %x %s' % (keyaddr, keyfn))
+ assert expected_tftp in output
+
+ addr = f.get('addr', None)
+ if not addr:
+ addr = u_boot_utils.find_ram_base(u_boot_console)
+ expected_tftp = 'Bytes transferred = '
+ fn = f['enckupfn']
+ output = u_boot_console.run_command('tftpboot %x %s' % (addr, fn))
+ assert expected_tftp in output
+
+ expected_zynqmpsecure = 'Bitstream successfully loaded'
+ output = u_boot_console.run_command('fpga loads 0 %x $filesize 0 1 %x' % (addr, keyaddr))
+ assert expected_zynqmpsecure in output
diff --git a/test/py/tests/test_fs/conftest.py b/test/py/tests/test_fs/conftest.py
new file mode 100644
index 00000000..1949f916
--- /dev/null
+++ b/test/py/tests/test_fs/conftest.py
@@ -0,0 +1,602 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Linaro Limited
+# Author: Takahiro Akashi <takahiro.akashi@linaro.org>
+
+import os
+import os.path
+import pytest
+import re
+from subprocess import call, check_call, check_output, CalledProcessError
+from fstest_defs import *
+
+supported_fs_basic = ['fat16', 'fat32', 'ext4']
+supported_fs_ext = ['fat16', 'fat32']
+supported_fs_mkdir = ['fat16', 'fat32']
+supported_fs_unlink = ['fat16', 'fat32']
+supported_fs_symlink = ['ext4']
+
+#
+# Filesystem test specific setup
+#
+def pytest_addoption(parser):
+ """Enable --fs-type option.
+
+ See pytest_configure() about how it works.
+
+ Args:
+ parser: Pytest command-line parser.
+
+ Returns:
+ Nothing.
+ """
+ parser.addoption('--fs-type', action='append', default=None,
+ help='Targeting Filesystem Types')
+
+def pytest_configure(config):
+ """Restrict a file system(s) to be tested.
+
+ A file system explicitly named with --fs-type option is selected
+ if it belongs to a default supported_fs_xxx list.
+ Multiple options can be specified.
+
+ Args:
+ config: Pytest configuration.
+
+ Returns:
+ Nothing.
+ """
+ global supported_fs_basic
+ global supported_fs_ext
+ global supported_fs_mkdir
+ global supported_fs_unlink
+ global supported_fs_symlink
+
+ def intersect(listA, listB):
+ return [x for x in listA if x in listB]
+
+ supported_fs = config.getoption('fs_type')
+ if supported_fs:
+ print('*** FS TYPE modified: %s' % supported_fs)
+ supported_fs_basic = intersect(supported_fs, supported_fs_basic)
+ supported_fs_ext = intersect(supported_fs, supported_fs_ext)
+ supported_fs_mkdir = intersect(supported_fs, supported_fs_mkdir)
+ supported_fs_unlink = intersect(supported_fs, supported_fs_unlink)
+ supported_fs_symlink = intersect(supported_fs, supported_fs_symlink)
+
+def pytest_generate_tests(metafunc):
+ """Parametrize fixtures, fs_obj_xxx
+
+ Each fixture will be parametrized with a corresponding support_fs_xxx
+ list.
+
+ Args:
+ metafunc: Pytest test function.
+
+ Returns:
+ Nothing.
+ """
+ if 'fs_obj_basic' in metafunc.fixturenames:
+ metafunc.parametrize('fs_obj_basic', supported_fs_basic,
+ indirect=True, scope='module')
+ if 'fs_obj_ext' in metafunc.fixturenames:
+ metafunc.parametrize('fs_obj_ext', supported_fs_ext,
+ indirect=True, scope='module')
+ if 'fs_obj_mkdir' in metafunc.fixturenames:
+ metafunc.parametrize('fs_obj_mkdir', supported_fs_mkdir,
+ indirect=True, scope='module')
+ if 'fs_obj_unlink' in metafunc.fixturenames:
+ metafunc.parametrize('fs_obj_unlink', supported_fs_unlink,
+ indirect=True, scope='module')
+ if 'fs_obj_symlink' in metafunc.fixturenames:
+ metafunc.parametrize('fs_obj_symlink', supported_fs_symlink,
+ indirect=True, scope='module')
+
+#
+# Helper functions
+#
+def fstype_to_ubname(fs_type):
+ """Convert a file system type to an U-boot specific string
+
+ A generated string can be used as part of file system related commands
+ or a config name in u-boot. Currently fat16 and fat32 are handled
+ specifically.
+
+ Args:
+ fs_type: File system type.
+
+ Return:
+ A corresponding string for file system type.
+ """
+ if re.match('fat', fs_type):
+ return 'fat'
+ else:
+ return fs_type
+
+def check_ubconfig(config, fs_type):
+ """Check whether a file system is enabled in u-boot configuration.
+
+ This function is assumed to be called in a fixture function so that
+ the whole test cases will be skipped if a given file system is not
+ enabled.
+
+ Args:
+ fs_type: File system type.
+
+ Return:
+ Nothing.
+ """
+ if not config.buildconfig.get('config_cmd_%s' % fs_type, None):
+ pytest.skip('.config feature "CMD_%s" not enabled' % fs_type.upper())
+ if not config.buildconfig.get('config_%s_write' % fs_type, None):
+ pytest.skip('.config feature "%s_WRITE" not enabled'
+ % fs_type.upper())
+
+def mk_fs(config, fs_type, size, id):
+ """Create a file system volume.
+
+ Args:
+ fs_type: File system type.
+ size: Size of file system in MiB.
+ id: Prefix string of volume's file name.
+
+ Return:
+ Nothing.
+ """
+ fs_img = '%s.%s.img' % (id, fs_type)
+ fs_img = config.persistent_data_dir + '/' + fs_img
+
+ if fs_type == 'fat16':
+ mkfs_opt = '-F 16'
+ elif fs_type == 'fat32':
+ mkfs_opt = '-F 32'
+ elif fs_type == 'ext4':
+ mkfs_opt = '-O ^metadata_csum'
+ else:
+ mkfs_opt = ''
+
+ if re.match('fat', fs_type):
+ fs_lnxtype = 'vfat'
+ else:
+ fs_lnxtype = fs_type
+
+ count = (size + 1048576 - 1) / 1048576
+
+ try:
+ check_call('rm -f %s' % fs_img, shell=True)
+ check_call('dd if=/dev/zero of=%s bs=1M count=%d'
+ % (fs_img, count), shell=True)
+ check_call('mkfs.%s %s %s'
+ % (fs_lnxtype, mkfs_opt, fs_img), shell=True)
+ return fs_img
+ except CalledProcessError:
+ call('rm -f %s' % fs_img, shell=True)
+ raise
+
+# from test/py/conftest.py
+def tool_is_in_path(tool):
+ """Check whether a given command is available on host.
+
+ Args:
+ tool: Command name.
+
+ Return:
+ True if available, False if not.
+ """
+ for path in os.environ['PATH'].split(os.pathsep):
+ fn = os.path.join(path, tool)
+ if os.path.isfile(fn) and os.access(fn, os.X_OK):
+ return True
+ return False
+
+fuse_mounted = False
+
+def mount_fs(fs_type, device, mount_point):
+ """Mount a volume.
+
+ Args:
+ fs_type: File system type.
+ device: Volume's file name.
+ mount_point: Mount point.
+
+ Return:
+ Nothing.
+ """
+ global fuse_mounted
+
+ fuse_mounted = False
+ try:
+ if tool_is_in_path('guestmount'):
+ fuse_mounted = True
+ check_call('guestmount -a %s -m /dev/sda %s'
+ % (device, mount_point), shell=True)
+ else:
+ mount_opt = 'loop,rw'
+ if re.match('fat', fs_type):
+ mount_opt += ',umask=0000'
+
+ check_call('sudo mount -o %s %s %s'
+ % (mount_opt, device, mount_point), shell=True)
+
+ # may not be effective for some file systems
+ check_call('sudo chmod a+rw %s' % mount_point, shell=True)
+ except CalledProcessError:
+ raise
+
+def umount_fs(mount_point):
+ """Unmount a volume.
+
+ Args:
+ mount_point: Mount point.
+
+ Return:
+ Nothing.
+ """
+ if fuse_mounted:
+ call('sync')
+ call('guestunmount %s' % mount_point, shell=True)
+ else:
+ call('sudo umount %s' % mount_point, shell=True)
+
+#
+# Fixture for basic fs test
+# derived from test/fs/fs-test.sh
+#
+# NOTE: yield_fixture was deprecated since pytest-3.0
+@pytest.yield_fixture()
+def fs_obj_basic(request, u_boot_config):
+ """Set up a file system to be used in basic fs test.
+
+ Args:
+ request: Pytest request object.
+ u_boot_config: U-boot configuration.
+
+ Return:
+ A fixture for basic fs test, i.e. a triplet of file system type,
+ volume file name and a list of MD5 hashes.
+ """
+ fs_type = request.param
+ fs_img = ''
+
+ fs_ubtype = fstype_to_ubname(fs_type)
+ check_ubconfig(u_boot_config, fs_ubtype)
+
+ mount_dir = u_boot_config.persistent_data_dir + '/mnt'
+
+ small_file = mount_dir + '/' + SMALL_FILE
+ big_file = mount_dir + '/' + BIG_FILE
+
+ try:
+
+ # 3GiB volume
+ fs_img = mk_fs(u_boot_config, fs_type, 0xc0000000, '3GB')
+
+ # Mount the image so we can populate it.
+ check_call('mkdir -p %s' % mount_dir, shell=True)
+ mount_fs(fs_type, fs_img, mount_dir)
+
+ # Create a subdirectory.
+ check_call('mkdir %s/SUBDIR' % mount_dir, shell=True)
+
+ # Create big file in this image.
+ # Note that we work only on the start 1MB, couple MBs in the 2GB range
+ # and the last 1 MB of the huge 2.5GB file.
+ # So, just put random values only in those areas.
+ check_call('dd if=/dev/urandom of=%s bs=1M count=1'
+ % big_file, shell=True)
+ check_call('dd if=/dev/urandom of=%s bs=1M count=2 seek=2047'
+ % big_file, shell=True)
+ check_call('dd if=/dev/urandom of=%s bs=1M count=1 seek=2499'
+ % big_file, shell=True)
+
+ # Create a small file in this image.
+ check_call('dd if=/dev/urandom of=%s bs=1M count=1'
+ % small_file, shell=True)
+
+ # Delete the small file copies which possibly are written as part of a
+ # previous test.
+ # check_call('rm -f "%s.w"' % MB1, shell=True)
+ # check_call('rm -f "%s.w2"' % MB1, shell=True)
+
+ # Generate the md5sums of reads that we will test against small file
+ out = check_output(
+ 'dd if=%s bs=1M skip=0 count=1 2> /dev/null | md5sum'
+ % small_file, shell=True).decode()
+ md5val = [ out.split()[0] ]
+
+ # Generate the md5sums of reads that we will test against big file
+ # One from beginning of file.
+ out = check_output(
+ 'dd if=%s bs=1M skip=0 count=1 2> /dev/null | md5sum'
+ % big_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # One from end of file.
+ out = check_output(
+ 'dd if=%s bs=1M skip=2499 count=1 2> /dev/null | md5sum'
+ % big_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # One from the last 1MB chunk of 2GB
+ out = check_output(
+ 'dd if=%s bs=1M skip=2047 count=1 2> /dev/null | md5sum'
+ % big_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # One from the start 1MB chunk from 2GB
+ out = check_output(
+ 'dd if=%s bs=1M skip=2048 count=1 2> /dev/null | md5sum'
+ % big_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # One 1MB chunk crossing the 2GB boundary
+ out = check_output(
+ 'dd if=%s bs=512K skip=4095 count=2 2> /dev/null | md5sum'
+ % big_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ umount_fs(mount_dir)
+ except CalledProcessError:
+ pytest.skip('Setup failed for filesystem: ' + fs_type)
+ return
+ else:
+ yield [fs_ubtype, fs_img, md5val]
+ finally:
+ umount_fs(mount_dir)
+ call('rmdir %s' % mount_dir, shell=True)
+ if fs_img:
+ call('rm -f %s' % fs_img, shell=True)
+
+#
+# Fixture for extended fs test
+#
+# NOTE: yield_fixture was deprecated since pytest-3.0
+@pytest.yield_fixture()
+def fs_obj_ext(request, u_boot_config):
+ """Set up a file system to be used in extended fs test.
+
+ Args:
+ request: Pytest request object.
+ u_boot_config: U-boot configuration.
+
+ Return:
+ A fixture for extended fs test, i.e. a triplet of file system type,
+ volume file name and a list of MD5 hashes.
+ """
+ fs_type = request.param
+ fs_img = ''
+
+ fs_ubtype = fstype_to_ubname(fs_type)
+ check_ubconfig(u_boot_config, fs_ubtype)
+
+ mount_dir = u_boot_config.persistent_data_dir + '/mnt'
+
+ min_file = mount_dir + '/' + MIN_FILE
+ tmp_file = mount_dir + '/tmpfile'
+
+ try:
+
+ # 128MiB volume
+ fs_img = mk_fs(u_boot_config, fs_type, 0x8000000, '128MB')
+
+ # Mount the image so we can populate it.
+ check_call('mkdir -p %s' % mount_dir, shell=True)
+ mount_fs(fs_type, fs_img, mount_dir)
+
+ # Create a test directory
+ check_call('mkdir %s/dir1' % mount_dir, shell=True)
+
+ # Create a small file and calculate md5
+ check_call('dd if=/dev/urandom of=%s bs=1K count=20'
+ % min_file, shell=True)
+ out = check_output(
+ 'dd if=%s bs=1K 2> /dev/null | md5sum'
+ % min_file, shell=True).decode()
+ md5val = [ out.split()[0] ]
+
+ # Calculate md5sum of Test Case 4
+ check_call('dd if=%s of=%s bs=1K count=20'
+ % (min_file, tmp_file), shell=True)
+ check_call('dd if=%s of=%s bs=1K seek=5 count=20'
+ % (min_file, tmp_file), shell=True)
+ out = check_output('dd if=%s bs=1K 2> /dev/null | md5sum'
+ % tmp_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # Calculate md5sum of Test Case 5
+ check_call('dd if=%s of=%s bs=1K count=20'
+ % (min_file, tmp_file), shell=True)
+ check_call('dd if=%s of=%s bs=1K seek=5 count=5'
+ % (min_file, tmp_file), shell=True)
+ out = check_output('dd if=%s bs=1K 2> /dev/null | md5sum'
+ % tmp_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ # Calculate md5sum of Test Case 7
+ check_call('dd if=%s of=%s bs=1K count=20'
+ % (min_file, tmp_file), shell=True)
+ check_call('dd if=%s of=%s bs=1K seek=20 count=20'
+ % (min_file, tmp_file), shell=True)
+ out = check_output('dd if=%s bs=1K 2> /dev/null | md5sum'
+ % tmp_file, shell=True).decode()
+ md5val.append(out.split()[0])
+
+ check_call('rm %s' % tmp_file, shell=True)
+ umount_fs(mount_dir)
+ except CalledProcessError:
+ pytest.skip('Setup failed for filesystem: ' + fs_type)
+ return
+ else:
+ yield [fs_ubtype, fs_img, md5val]
+ finally:
+ umount_fs(mount_dir)
+ call('rmdir %s' % mount_dir, shell=True)
+ if fs_img:
+ call('rm -f %s' % fs_img, shell=True)
+
+#
+# Fixture for mkdir test
+#
+# NOTE: yield_fixture was deprecated since pytest-3.0
+@pytest.yield_fixture()
+def fs_obj_mkdir(request, u_boot_config):
+ """Set up a file system to be used in mkdir test.
+
+ Args:
+ request: Pytest request object.
+ u_boot_config: U-boot configuration.
+
+ Return:
+ A fixture for mkdir test, i.e. a duplet of file system type and
+ volume file name.
+ """
+ fs_type = request.param
+ fs_img = ''
+
+ fs_ubtype = fstype_to_ubname(fs_type)
+ check_ubconfig(u_boot_config, fs_ubtype)
+
+ try:
+ # 128MiB volume
+ fs_img = mk_fs(u_boot_config, fs_type, 0x8000000, '128MB')
+ except:
+ pytest.skip('Setup failed for filesystem: ' + fs_type)
+ else:
+ yield [fs_ubtype, fs_img]
+ finally:
+ if fs_img:
+ call('rm -f %s' % fs_img, shell=True)
+
+#
+# Fixture for unlink test
+#
+# NOTE: yield_fixture was deprecated since pytest-3.0
+@pytest.yield_fixture()
+def fs_obj_unlink(request, u_boot_config):
+ """Set up a file system to be used in unlink test.
+
+ Args:
+ request: Pytest request object.
+ u_boot_config: U-boot configuration.
+
+ Return:
+ A fixture for unlink test, i.e. a duplet of file system type and
+ volume file name.
+ """
+ fs_type = request.param
+ fs_img = ''
+
+ fs_ubtype = fstype_to_ubname(fs_type)
+ check_ubconfig(u_boot_config, fs_ubtype)
+
+ mount_dir = u_boot_config.persistent_data_dir + '/mnt'
+
+ try:
+
+ # 128MiB volume
+ fs_img = mk_fs(u_boot_config, fs_type, 0x8000000, '128MB')
+
+ # Mount the image so we can populate it.
+ check_call('mkdir -p %s' % mount_dir, shell=True)
+ mount_fs(fs_type, fs_img, mount_dir)
+
+ # Test Case 1 & 3
+ check_call('mkdir %s/dir1' % mount_dir, shell=True)
+ check_call('dd if=/dev/urandom of=%s/dir1/file1 bs=1K count=1'
+ % mount_dir, shell=True)
+ check_call('dd if=/dev/urandom of=%s/dir1/file2 bs=1K count=1'
+ % mount_dir, shell=True)
+
+ # Test Case 2
+ check_call('mkdir %s/dir2' % mount_dir, shell=True)
+ for i in range(0, 20):
+ check_call('mkdir %s/dir2/0123456789abcdef%02x'
+ % (mount_dir, i), shell=True)
+
+ # Test Case 4
+ check_call('mkdir %s/dir4' % mount_dir, shell=True)
+
+ # Test Case 5, 6 & 7
+ check_call('mkdir %s/dir5' % mount_dir, shell=True)
+ check_call('dd if=/dev/urandom of=%s/dir5/file1 bs=1K count=1'
+ % mount_dir, shell=True)
+
+ umount_fs(mount_dir)
+ except CalledProcessError:
+ pytest.skip('Setup failed for filesystem: ' + fs_type)
+ return
+ else:
+ yield [fs_ubtype, fs_img]
+ finally:
+ umount_fs(mount_dir)
+ call('rmdir %s' % mount_dir, shell=True)
+ if fs_img:
+ call('rm -f %s' % fs_img, shell=True)
+
+#
+# Fixture for symlink fs test
+#
+# NOTE: yield_fixture was deprecated since pytest-3.0
+@pytest.yield_fixture()
+def fs_obj_symlink(request, u_boot_config):
+ """Set up a file system to be used in symlink fs test.
+
+ Args:
+ request: Pytest request object.
+ u_boot_config: U-boot configuration.
+
+ Return:
+ A fixture for basic fs test, i.e. a triplet of file system type,
+ volume file name and a list of MD5 hashes.
+ """
+ fs_type = request.param
+ fs_img = ''
+
+ fs_ubtype = fstype_to_ubname(fs_type)
+ check_ubconfig(u_boot_config, fs_ubtype)
+
+ mount_dir = u_boot_config.persistent_data_dir + '/mnt'
+
+ small_file = mount_dir + '/' + SMALL_FILE
+ medium_file = mount_dir + '/' + MEDIUM_FILE
+
+ try:
+
+ # 3GiB volume
+ fs_img = mk_fs(u_boot_config, fs_type, 0x40000000, '1GB')
+
+ # Mount the image so we can populate it.
+ check_call('mkdir -p %s' % mount_dir, shell=True)
+ mount_fs(fs_type, fs_img, mount_dir)
+
+ # Create a subdirectory.
+ check_call('mkdir %s/SUBDIR' % mount_dir, shell=True)
+
+ # Create a small file in this image.
+ check_call('dd if=/dev/urandom of=%s bs=1M count=1'
+ % small_file, shell=True)
+
+ # Create a medium file in this image.
+ check_call('dd if=/dev/urandom of=%s bs=10M count=1'
+ % medium_file, shell=True)
+
+ # Generate the md5sums of reads that we will test against small file
+ out = check_output(
+ 'dd if=%s bs=1M skip=0 count=1 2> /dev/null | md5sum'
+ % small_file, shell=True).decode()
+ md5val = [out.split()[0]]
+ out = check_output(
+ 'dd if=%s bs=10M skip=0 count=1 2> /dev/null | md5sum'
+ % medium_file, shell=True).decode()
+ md5val.extend([out.split()[0]])
+
+ umount_fs(mount_dir)
+ except CalledProcessError:
+ pytest.skip('Setup failed for filesystem: ' + fs_type)
+ return
+ else:
+ yield [fs_ubtype, fs_img, md5val]
+ finally:
+ umount_fs(mount_dir)
+ call('rmdir %s' % mount_dir, shell=True)
+ if fs_img:
+ call('rm -f %s' % fs_img, shell=True)
diff --git a/test/py/tests/test_fs/fstest_defs.py b/test/py/tests/test_fs/fstest_defs.py
new file mode 100644
index 00000000..35b2bb65
--- /dev/null
+++ b/test/py/tests/test_fs/fstest_defs.py
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0+
+
+# $MIN_FILE is the name of the 20KB file in the file system image
+MIN_FILE='testfile'
+
+# $SMALL_FILE is the name of the 1MB file in the file system image
+SMALL_FILE='1MB.file'
+
+# $MEDIUM_FILE is the name of the 10MB file in the file system image
+MEDIUM_FILE='10MB.file'
+
+# $BIG_FILE is the name of the 2.5GB file in the file system image
+BIG_FILE='2.5GB.file'
+
+ADDR=0x01000008
+LENGTH=0x00100000
diff --git a/test/py/tests/test_fs/fstest_helpers.py b/test/py/tests/test_fs/fstest_helpers.py
new file mode 100644
index 00000000..faec2982
--- /dev/null
+++ b/test/py/tests/test_fs/fstest_helpers.py
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2019, Texas Instrument
+# Author: JJ Hiblot <jjhiblot@ti.com>
+#
+
+from subprocess import check_call, CalledProcessError
+
+def assert_fs_integrity(fs_type, fs_img):
+ try:
+ if fs_type == 'ext4':
+ check_call('fsck.ext4 -n -f %s' % fs_img, shell=True)
+ except CalledProcessError:
+ raise
diff --git a/test/py/tests/test_fs/test_basic.py b/test/py/tests/test_fs/test_basic.py
new file mode 100644
index 00000000..71f3e86f
--- /dev/null
+++ b/test/py/tests/test_fs/test_basic.py
@@ -0,0 +1,292 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Linaro Limited
+# Author: Takahiro Akashi <takahiro.akashi@linaro.org>
+#
+# U-Boot File System:Basic Test
+
+"""
+This test verifies basic read/write operation on file system.
+"""
+
+import pytest
+import re
+from fstest_defs import *
+from fstest_helpers import assert_fs_integrity
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.slow
+class TestFsBasic(object):
+ def test_fs1(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 1 - ls command, listing a root directory and invalid directory
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 1a - ls'):
+ # Test Case 1 - ls
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sls host 0:0' % fs_type])
+ assert(re.search('2621440000 *%s' % BIG_FILE, ''.join(output)))
+ assert(re.search('1048576 *%s' % SMALL_FILE, ''.join(output)))
+
+ with u_boot_console.log.section('Test Case 1b - ls (invalid dir)'):
+ # In addition, test with a nonexistent directory to see if we crash.
+ output = u_boot_console.run_command(
+ '%sls host 0:0 invalid_d' % fs_type)
+ if fs_type == 'ext4':
+ assert('Can not find directory' in output)
+ else:
+ assert('' == output)
+
+ def test_fs2(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 2 - size command for a small file
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 2a - size (small)'):
+ # 1MB is 0x0010 0000
+ # Test Case 2a - size of small file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%ssize host 0:0 /%s' % (fs_type, SMALL_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ with u_boot_console.log.section('Test Case 2b - size (/../<file>)'):
+ # Test Case 2b - size of small file via a path using '..'
+ output = u_boot_console.run_command_list([
+ '%ssize host 0:0 /SUBDIR/../%s' % (fs_type, SMALL_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ def test_fs3(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 3 - size command for a large file
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 3 - size (large)'):
+ # 2.5GB (1024*1024*2500) is 0x9C40 0000
+ # Test Case 3 - size of big file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%ssize host 0:0 /%s' % (fs_type, BIG_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=9c400000' in ''.join(output))
+
+ def test_fs4(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 4 - load a small file, 1MB
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 4 - load (small)'):
+ # Test Case 4a - Read full 1MB of small file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, SMALL_FILE),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 4b - Read full 1MB of small file
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+
+ def test_fs5(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 5 - load, reading first 1MB of 3GB file
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 5 - load (first 1MB)'):
+ # Test Case 5a - First 1MB of big file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s %x 0x0' % (fs_type, ADDR, BIG_FILE, LENGTH),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 5b - First 1MB of big file
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[1] in ''.join(output))
+
+ def test_fs6(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 6 - load, reading last 1MB of 3GB file
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 6 - load (last 1MB)'):
+ # fails for ext as no offset support
+ # Test Case 6a - Last 1MB of big file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s %x 0x9c300000'
+ % (fs_type, ADDR, BIG_FILE, LENGTH),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 6b - Last 1MB of big file
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[2] in ''.join(output))
+
+ def test_fs7(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 7 - load, 1MB from the last 1MB in 2GB
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 7 - load (last 1MB in 2GB)'):
+ # fails for ext as no offset support
+ # Test Case 7a - One from the last 1MB chunk of 2GB
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s %x 0x7ff00000'
+ % (fs_type, ADDR, BIG_FILE, LENGTH),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 7b - One from the last 1MB chunk of 2GB
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[3] in ''.join(output))
+
+ def test_fs8(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 8 - load, reading first 1MB in 2GB
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 8 - load (first 1MB in 2GB)'):
+ # fails for ext as no offset support
+ # Test Case 8a - One from the start 1MB chunk from 2GB
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s %x 0x80000000'
+ % (fs_type, ADDR, BIG_FILE, LENGTH),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 8b - One from the start 1MB chunk from 2GB
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[4] in ''.join(output))
+
+ def test_fs9(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 9 - load, 1MB crossing 2GB boundary
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 9 - load (crossing 2GB boundary)'):
+ # fails for ext as no offset support
+ # Test Case 9a - One 1MB chunk crossing the 2GB boundary
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s %x 0x7ff80000'
+ % (fs_type, ADDR, BIG_FILE, LENGTH),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 9b - One 1MB chunk crossing the 2GB boundary
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[5] in ''.join(output))
+
+ def test_fs10(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 10 - load, reading beyond file end'):
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 10 - load (beyond file end)'):
+ # Generic failure case
+ # Test Case 10 - 2MB chunk from the last 1MB of big file
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s 0x00200000 0x9c300000'
+ % (fs_type, ADDR, BIG_FILE),
+ 'printenv filesize',
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ def test_fs11(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 11 - write'
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 11 - write'):
+ # Read 1MB from small file
+ # Write it back to test the writes
+ # Test Case 11a - Check that the write succeeded
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, SMALL_FILE),
+ '%swrite host 0:0 %x /%s.w $filesize'
+ % (fs_type, ADDR, SMALL_FILE)])
+ assert('1048576 bytes written' in ''.join(output))
+
+ # Test Case 11b - Check md5 of written to is same
+ # as the one read from
+ output = u_boot_console.run_command_list([
+ '%sload host 0:0 %x /%s.w' % (fs_type, ADDR, SMALL_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs12(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 12 - write to "." directory
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 12 - write (".")'):
+ # Next test case checks writing a file whose dirent
+ # is the first in the block, which is always true for "."
+ # The write should fail, but the lookup should work
+ # Test Case 12 - Check directory traversal
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%swrite host 0:0 %x /. 0x10' % (fs_type, ADDR)])
+ assert('Unable to write' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs13(self, u_boot_console, fs_obj_basic):
+ """
+ Test Case 13 - write to a file with "/./<filename>"
+ """
+ fs_type,fs_img,md5val = fs_obj_basic
+ with u_boot_console.log.section('Test Case 13 - write ("./<file>")'):
+ # Read 1MB from small file
+ # Write it via "same directory", i.e. "." dirent
+ # Test Case 13a - Check directory traversal
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, SMALL_FILE),
+ '%swrite host 0:0 %x /./%s2 $filesize'
+ % (fs_type, ADDR, SMALL_FILE)])
+ assert('1048576 bytes written' in ''.join(output))
+
+ # Test Case 13b - Check md5 of written to is same
+ # as the one read from
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /./%s2' % (fs_type, ADDR, SMALL_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+
+ # Test Case 13c - Check md5 of written to is same
+ # as the one read from
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /%s2' % (fs_type, ADDR, SMALL_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
diff --git a/test/py/tests/test_fs/test_ext.py b/test/py/tests/test_fs/test_ext.py
new file mode 100644
index 00000000..6b7fc487
--- /dev/null
+++ b/test/py/tests/test_fs/test_ext.py
@@ -0,0 +1,319 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Linaro Limited
+# Author: Takahiro Akashi <takahiro.akashi@linaro.org>
+#
+# U-Boot File System:Exntented Test
+
+"""
+This test verifies extended write operation on file system.
+"""
+
+import pytest
+import re
+from fstest_defs import *
+from fstest_helpers import assert_fs_integrity
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.slow
+class TestFsExt(object):
+ def test_fs_ext1(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 1 - write a file with absolute path
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 1 - write with abs path'):
+ # Test Case 1a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w1 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ assert('20480 bytes written' in ''.join(output))
+
+ # Test Case 1b - Check md5 of file content
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /dir1/%s.w1' % (fs_type, ADDR, MIN_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext2(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 2 - write to a file with relative path
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 2 - write with rel path'):
+ # Test Case 2a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x dir1/%s.w2 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ assert('20480 bytes written' in ''.join(output))
+
+ # Test Case 2b - Check md5 of file content
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x dir1/%s.w2' % (fs_type, ADDR, MIN_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext3(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 3 - write to a file with invalid path
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 3 - write with invalid path'):
+ # Test Case 3 - Check if command expectedly failed
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/none/%s.w3 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ assert('Unable to write "/dir1/none/' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext4(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 4 - write at non-zero offset, enlarging file size
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 4 - write at non-zero offset, enlarging file size'):
+ # Test Case 4a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w4 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/%s.w4 $filesize 0x1400'
+ % (fs_type, ADDR, MIN_FILE))
+ assert('20480 bytes written' in output)
+
+ # Test Case 4b - Check size of written file
+ output = u_boot_console.run_command_list([
+ '%ssize host 0:0 /dir1/%s.w4' % (fs_type, MIN_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=6400' in ''.join(output))
+
+ # Test Case 4c - Check md5 of file content
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /dir1/%s.w4' % (fs_type, ADDR, MIN_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[1] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext5(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 5 - write at non-zero offset, shrinking file size
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 5 - write at non-zero offset, shrinking file size'):
+ # Test Case 5a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w5 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/%s.w5 0x1400 0x1400'
+ % (fs_type, ADDR, MIN_FILE))
+ assert('5120 bytes written' in output)
+
+ # Test Case 5b - Check size of written file
+ output = u_boot_console.run_command_list([
+ '%ssize host 0:0 /dir1/%s.w5' % (fs_type, MIN_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=2800' in ''.join(output))
+
+ # Test Case 5c - Check md5 of file content
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /dir1/%s.w5' % (fs_type, ADDR, MIN_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[2] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext6(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 6 - write nothing at the start, truncating to zero
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 6 - write nothing at the start, truncating to zero'):
+ # Test Case 6a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w6 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/%s.w6 0 0'
+ % (fs_type, ADDR, MIN_FILE))
+ assert('0 bytes written' in output)
+
+ # Test Case 6b - Check size of written file
+ output = u_boot_console.run_command_list([
+ '%ssize host 0:0 /dir1/%s.w6' % (fs_type, MIN_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=0' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext7(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 7 - write at the end (append)
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 7 - write at the end (append)'):
+ # Test Case 7a - Check if command successfully returned
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w7 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/%s.w7 $filesize $filesize'
+ % (fs_type, ADDR, MIN_FILE))
+ assert('20480 bytes written' in output)
+
+ # Test Case 7b - Check size of written file
+ output = u_boot_console.run_command_list([
+ '%ssize host 0:0 /dir1/%s.w7' % (fs_type, MIN_FILE),
+ 'printenv filesize',
+ 'setenv filesize'])
+ assert('filesize=a000' in ''.join(output))
+
+ # Test Case 7c - Check md5 of file content
+ output = u_boot_console.run_command_list([
+ 'mw.b %x 00 100' % ADDR,
+ '%sload host 0:0 %x /dir1/%s.w7' % (fs_type, ADDR, MIN_FILE),
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[3] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext8(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 8 - write at offset beyond the end of file
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 8 - write beyond the end'):
+ # Test Case 8a - Check if command expectedly failed
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w8 $filesize'
+ % (fs_type, ADDR, MIN_FILE)])
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/%s.w8 0x1400 %x'
+ % (fs_type, ADDR, MIN_FILE, 0x100000 + 0x1400))
+ assert('Unable to write "/dir1' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext9(self, u_boot_console, fs_obj_ext):
+ """
+ Test Case 9 - write to a non-existing file at non-zero offset
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 9 - write to non-existing file with non-zero offset'):
+ # Test Case 9a - Check if command expectedly failed
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, MIN_FILE),
+ '%swrite host 0:0 %x /dir1/%s.w9 0x1400 0x1400'
+ % (fs_type, ADDR, MIN_FILE)])
+ assert('Unable to write "/dir1' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext10(self, u_boot_console, fs_obj_ext):
+ """
+ 'Test Case 10 - create/delete as many directories under root directory
+ as amount of directory entries goes beyond one cluster size)'
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 10 - create/delete (many)'):
+ # Test Case 10a - Create many files
+ # Please note that the size of directory entry is 32 bytes.
+ # So one typical cluster may holds 64 (2048/32) entries.
+ output = u_boot_console.run_command(
+ 'host bind 0 %s' % fs_img)
+
+ for i in range(0, 66):
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /FILE0123456789_%02x 100'
+ % (fs_type, ADDR, i))
+ output = u_boot_console.run_command('%sls host 0:0 /' % fs_type)
+ assert('FILE0123456789_00' in output)
+ assert('FILE0123456789_41' in output)
+
+ # Test Case 10b - Delete many files
+ for i in range(0, 66):
+ output = u_boot_console.run_command(
+ '%srm host 0:0 /FILE0123456789_%02x'
+ % (fs_type, i))
+ output = u_boot_console.run_command('%sls host 0:0 /' % fs_type)
+ assert(not 'FILE0123456789_00' in output)
+ assert(not 'FILE0123456789_41' in output)
+
+ # Test Case 10c - Create many files again
+ # Please note no.64 and 65 are intentionally re-created
+ for i in range(64, 128):
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /FILE0123456789_%02x 100'
+ % (fs_type, ADDR, i))
+ output = u_boot_console.run_command('%sls host 0:0 /' % fs_type)
+ assert('FILE0123456789_40' in output)
+ assert('FILE0123456789_79' in output)
+
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_fs_ext11(self, u_boot_console, fs_obj_ext):
+ """
+ 'Test Case 11 - create/delete as many directories under non-root
+ directory as amount of directory entries goes beyond one cluster size)'
+ """
+ fs_type,fs_img,md5val = fs_obj_ext
+ with u_boot_console.log.section('Test Case 11 - create/delete (many)'):
+ # Test Case 11a - Create many files
+ # Please note that the size of directory entry is 32 bytes.
+ # So one typical cluster may holds 64 (2048/32) entries.
+ output = u_boot_console.run_command(
+ 'host bind 0 %s' % fs_img)
+
+ for i in range(0, 66):
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/FILE0123456789_%02x 100'
+ % (fs_type, ADDR, i))
+ output = u_boot_console.run_command('%sls host 0:0 /dir1' % fs_type)
+ assert('FILE0123456789_00' in output)
+ assert('FILE0123456789_41' in output)
+
+ # Test Case 11b - Delete many files
+ for i in range(0, 66):
+ output = u_boot_console.run_command(
+ '%srm host 0:0 /dir1/FILE0123456789_%02x'
+ % (fs_type, i))
+ output = u_boot_console.run_command('%sls host 0:0 /dir1' % fs_type)
+ assert(not 'FILE0123456789_00' in output)
+ assert(not 'FILE0123456789_41' in output)
+
+ # Test Case 11c - Create many files again
+ # Please note no.64 and 65 are intentionally re-created
+ for i in range(64, 128):
+ output = u_boot_console.run_command(
+ '%swrite host 0:0 %x /dir1/FILE0123456789_%02x 100'
+ % (fs_type, ADDR, i))
+ output = u_boot_console.run_command('%sls host 0:0 /dir1' % fs_type)
+ assert('FILE0123456789_40' in output)
+ assert('FILE0123456789_79' in output)
+
+ assert_fs_integrity(fs_type, fs_img)
diff --git a/test/py/tests/test_fs/test_mkdir.py b/test/py/tests/test_fs/test_mkdir.py
new file mode 100644
index 00000000..fa9561ec
--- /dev/null
+++ b/test/py/tests/test_fs/test_mkdir.py
@@ -0,0 +1,121 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Linaro Limited
+# Author: Takahiro Akashi <takahiro.akashi@linaro.org>
+#
+# U-Boot File System:mkdir Test
+
+"""
+This test verifies mkdir operation on file system.
+"""
+
+import pytest
+from fstest_helpers import assert_fs_integrity
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.slow
+class TestMkdir(object):
+ def test_mkdir1(self, u_boot_console, fs_obj_mkdir):
+ """
+ Test Case 1 - create a directory under a root
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 1 - mkdir'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 dir1' % fs_type,
+ '%sls host 0:0 /' % fs_type])
+ assert('dir1/' in ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir1' % fs_type)
+ assert('./' in output)
+ assert('../' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+
+ def test_mkdir2(self, u_boot_console, fs_obj_mkdir):
+ """
+ Test Case 2 - create a directory under a sub-directory
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 2 - mkdir (sub-sub directory)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 dir1/dir2' % fs_type,
+ '%sls host 0:0 dir1' % fs_type])
+ assert('dir2/' in ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir1/dir2' % fs_type)
+ assert('./' in output)
+ assert('../' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_mkdir3(self, u_boot_console, fs_obj_mkdir):
+ """
+ Test Case 3 - trying to create a directory with a non-existing
+ path should fail
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 3 - mkdir (non-existing path)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 none/dir3' % fs_type])
+ assert('Unable to create a directory' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_mkdir4(self, u_boot_console, fs_obj_mkdir):
+ """
+ Test Case 4 - trying to create "." should fail
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 4 - mkdir (".")'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 .' % fs_type])
+ assert('Unable to create a directory' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_mkdir5(self, u_boot_console, fs_obj_mkdir):
+ """
+ Test Case 5 - trying to create ".." should fail
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 5 - mkdir ("..")'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 ..' % fs_type])
+ assert('Unable to create a directory' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_mkdir6(self, u_boot_console, fs_obj_mkdir):
+ """
+ 'Test Case 6 - create as many directories as amount of directory
+ entries goes beyond a cluster size)'
+ """
+ fs_type,fs_img = fs_obj_mkdir
+ with u_boot_console.log.section('Test Case 6 - mkdir (create many)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%smkdir host 0:0 dir6' % fs_type,
+ '%sls host 0:0 /' % fs_type])
+ assert('dir6/' in ''.join(output))
+
+ for i in range(0, 20):
+ output = u_boot_console.run_command(
+ '%smkdir host 0:0 dir6/0123456789abcdef%02x'
+ % (fs_type, i))
+ output = u_boot_console.run_command('%sls host 0:0 dir6' % fs_type)
+ assert('0123456789abcdef00/' in output)
+ assert('0123456789abcdef13/' in output)
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir6/0123456789abcdef13/.' % fs_type)
+ assert('./' in output)
+ assert('../' in output)
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir6/0123456789abcdef13/..' % fs_type)
+ assert('0123456789abcdef00/' in output)
+ assert('0123456789abcdef13/' in output)
+ assert_fs_integrity(fs_type, fs_img)
diff --git a/test/py/tests/test_fs/test_symlink.py b/test/py/tests/test_fs/test_symlink.py
new file mode 100644
index 00000000..9ced101a
--- /dev/null
+++ b/test/py/tests/test_fs/test_symlink.py
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2019, Texas Instrument
+# Author: Jean-Jacques Hiblot <jjhiblot@ti.com>
+#
+# U-Boot File System:symlink Test
+
+"""
+This test verifies unlink operation (deleting a file or a directory)
+on file system.
+"""
+
+import pytest
+import re
+from fstest_defs import *
+from fstest_helpers import assert_fs_integrity
+
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.slow
+class TestSymlink(object):
+ def test_symlink1(self, u_boot_console, fs_obj_symlink):
+ """
+ Test Case 1 - create a link. and follow it when reading
+ """
+ fs_type, fs_img, md5val = fs_obj_symlink
+ with u_boot_console.log.section('Test Case 1 - create link and read'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ 'setenv filesize',
+ 'ln host 0:0 %s /%s.link ' % (SMALL_FILE, SMALL_FILE),
+ ])
+ assert('' in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ '%sload host 0:0 %x /%s.link' % (fs_type, ADDR, SMALL_FILE),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 4b - Read full 1MB of small file
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_symlink2(self, u_boot_console, fs_obj_symlink):
+ """
+ Test Case 2 - create chained links
+ """
+ fs_type, fs_img, md5val = fs_obj_symlink
+ with u_boot_console.log.section('Test Case 2 - create chained links'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ 'setenv filesize',
+ 'ln host 0:0 %s /%s.link1 ' % (SMALL_FILE, SMALL_FILE),
+ 'ln host 0:0 /%s.link1 /SUBDIR/%s.link2' % (
+ SMALL_FILE, SMALL_FILE),
+ 'ln host 0:0 SUBDIR/%s.link2 /%s.link3' % (
+ SMALL_FILE, SMALL_FILE),
+ ])
+ assert('' in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ '%sload host 0:0 %x /%s.link3' % (fs_type, ADDR, SMALL_FILE),
+ 'printenv filesize'])
+ assert('filesize=100000' in ''.join(output))
+
+ # Test Case 4b - Read full 1MB of small file
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[0] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_symlink3(self, u_boot_console, fs_obj_symlink):
+ """
+ Test Case 3 - replace file/link with link
+ """
+ fs_type, fs_img, md5val = fs_obj_symlink
+ with u_boot_console.log.section('Test Case 1 - create link and read'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ 'setenv filesize',
+ 'ln host 0:0 %s /%s ' % (MEDIUM_FILE, SMALL_FILE),
+ 'ln host 0:0 %s /%s.link ' % (MEDIUM_FILE, MEDIUM_FILE),
+ ])
+ assert('' in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, SMALL_FILE),
+ 'printenv filesize'])
+ assert('filesize=a00000' in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[1] in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ 'ln host 0:0 %s.link /%s ' % (MEDIUM_FILE, SMALL_FILE),
+ '%sload host 0:0 %x /%s' % (fs_type, ADDR, SMALL_FILE),
+ 'printenv filesize'])
+ assert('filesize=a00000' in ''.join(output))
+
+ output = u_boot_console.run_command_list([
+ 'md5sum %x $filesize' % ADDR,
+ 'setenv filesize'])
+ assert(md5val[1] in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_symlink4(self, u_boot_console, fs_obj_symlink):
+ """
+ Test Case 4 - create a broken link
+ """
+ fs_type, fs_img, md5val = fs_obj_symlink
+ with u_boot_console.log.section('Test Case 1 - create link and read'):
+
+ output = u_boot_console.run_command_list([
+ 'setenv filesize',
+ 'ln host 0:0 nowhere /link ',
+ ])
+ assert('' in ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sload host 0:0 %x /link' %
+ (fs_type, ADDR))
+ with u_boot_console.disable_check('error_notification'):
+ output = u_boot_console.run_command('printenv filesize')
+ assert('"filesize" not defined' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
diff --git a/test/py/tests/test_fs/test_unlink.py b/test/py/tests/test_fs/test_unlink.py
new file mode 100644
index 00000000..97aafc63
--- /dev/null
+++ b/test/py/tests/test_fs/test_unlink.py
@@ -0,0 +1,118 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Linaro Limited
+# Author: Takahiro Akashi <takahiro.akashi@linaro.org>
+#
+# U-Boot File System:unlink Test
+
+"""
+This test verifies unlink operation (deleting a file or a directory)
+on file system.
+"""
+
+import pytest
+from fstest_helpers import assert_fs_integrity
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.slow
+class TestUnlink(object):
+ def test_unlink1(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 1 - delete a file
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 1 - unlink (file)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir1/file1' % fs_type,
+ '%sls host 0:0 dir1/file1' % fs_type])
+ assert('' == ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir1/' % fs_type)
+ assert(not 'file1' in output)
+ assert('file2' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink2(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 2 - delete many files
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 2 - unlink (many)'):
+ output = u_boot_console.run_command('host bind 0 %s' % fs_img)
+
+ for i in range(0, 20):
+ output = u_boot_console.run_command_list([
+ '%srm host 0:0 dir2/0123456789abcdef%02x' % (fs_type, i),
+ '%sls host 0:0 dir2/0123456789abcdef%02x' % (fs_type, i)])
+ assert('' == ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 dir2' % fs_type)
+ assert('0 file(s), 2 dir(s)' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink3(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 3 - trying to delete a non-existing file should fail
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 3 - unlink (non-existing)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir1/nofile' % fs_type])
+ assert('nofile: doesn\'t exist' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink4(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 4 - delete an empty directory
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 4 - unlink (directory)'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir4' % fs_type])
+ assert('' == ''.join(output))
+
+ output = u_boot_console.run_command(
+ '%sls host 0:0 /' % fs_type)
+ assert(not 'dir4' in output)
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink5(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 5 - trying to deleting a non-empty directory ".."
+ should fail
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 5 - unlink ("non-empty directory")'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir5' % fs_type])
+ assert('directory is not empty' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink6(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 6 - trying to deleting a "." should fail
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 6 - unlink (".")'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir5/.' % fs_type])
+ assert('directory is not empty' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
+
+ def test_unlink7(self, u_boot_console, fs_obj_unlink):
+ """
+ Test Case 7 - trying to deleting a ".." should fail
+ """
+ fs_type,fs_img = fs_obj_unlink
+ with u_boot_console.log.section('Test Case 7 - unlink ("..")'):
+ output = u_boot_console.run_command_list([
+ 'host bind 0 %s' % fs_img,
+ '%srm host 0:0 dir5/..' % fs_type])
+ assert('directory is not empty' in ''.join(output))
+ assert_fs_integrity(fs_type, fs_img)
diff --git a/test/py/tests/test_gpt.py b/test/py/tests/test_gpt.py
new file mode 100644
index 00000000..229d7eb2
--- /dev/null
+++ b/test/py/tests/test_gpt.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2017 Alison Chaiken
+# Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
+
+# Test GPT manipulation commands.
+
+import os
+import pytest
+import u_boot_utils
+
+"""
+These tests rely on a 4 MB disk image, which is automatically created by
+the test.
+"""
+
+class GptTestDiskImage(object):
+ """Disk Image used by the GPT tests."""
+
+ def __init__(self, u_boot_console):
+ """Initialize a new GptTestDiskImage object.
+
+ Args:
+ u_boot_console: A U-Boot console.
+
+ Returns:
+ Nothing.
+ """
+
+ filename = 'test_gpt_disk_image.bin'
+
+ persistent = u_boot_console.config.persistent_data_dir + '/' + filename
+ self.path = u_boot_console.config.result_dir + '/' + filename
+
+ with u_boot_utils.persistent_file_helper(u_boot_console.log, persistent):
+ if os.path.exists(persistent):
+ u_boot_console.log.action('Disk image file ' + persistent +
+ ' already exists')
+ else:
+ u_boot_console.log.action('Generating ' + persistent)
+ fd = os.open(persistent, os.O_RDWR | os.O_CREAT)
+ os.ftruncate(fd, 4194304)
+ os.close(fd)
+ cmd = ('sgdisk',
+ '--disk-guid=375a56f7-d6c9-4e81-b5f0-09d41ca89efe',
+ persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ # part1 offset 1MB size 1MB
+ cmd = ('sgdisk', '--new=1:2048:4095', '--change-name=1:part1',
+ persistent)
+ # part2 offset 2MB size 1.5MB
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ cmd = ('sgdisk', '--new=2:4096:7167', '--change-name=2:part2',
+ persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ cmd = ('sgdisk', '--load-backup=' + persistent)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+ cmd = ('cp', persistent, self.path)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+gtdi = None
+@pytest.fixture(scope='function')
+def state_disk_image(u_boot_console):
+ """pytest fixture to provide a GptTestDiskImage object to tests.
+ This is function-scoped because it uses u_boot_console, which is also
+ function-scoped. However, we don't need to actually do any function-scope
+ work, so this simply returns the same object over and over each time."""
+
+ global gtdi
+ if not gtdi:
+ gtdi = GptTestDiskImage(u_boot_console)
+ return gtdi
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.buildconfigspec('cmd_part')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_read(state_disk_image, u_boot_console):
+ """Test the gpt read command."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('gpt read host 0')
+ assert 'Start 1MiB, size 1MiB' in output
+ assert 'Block size 512, name part1' in output
+ assert 'Start 2MiB, size 1MiB' in output
+ assert 'Block size 512, name part2' in output
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000800 0x00000fff "part1"' in output
+ assert '0x00001000 0x00001bff "part2"' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_verify(state_disk_image, u_boot_console):
+ """Test the gpt verify command."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('gpt verify host 0')
+ assert 'Verify GPT: success!' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_guid(state_disk_image, u_boot_console):
+ """Test the gpt guid command."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('gpt guid host 0')
+ assert '375a56f7-d6c9-4e81-b5f0-09d41ca89efe' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_save_guid(state_disk_image, u_boot_console):
+ """Test the gpt guid command to save GUID into a string."""
+
+ if u_boot_console.config.buildconfig.get('config_cmd_gpt', 'n') != 'y':
+ pytest.skip('gpt command not supported')
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('gpt guid host 0 newguid')
+ output = u_boot_console.run_command('printenv newguid')
+ assert '375a56f7-d6c9-4e81-b5f0-09d41ca89efe' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.buildconfigspec('cmd_gpt_rename')
+@pytest.mark.buildconfigspec('cmd_part')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_rename_partition(state_disk_image, u_boot_console):
+ """Test the gpt rename command to write partition names."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ u_boot_console.run_command('gpt rename host 0 1 first')
+ output = u_boot_console.run_command('gpt read host 0')
+ assert 'name first' in output
+ u_boot_console.run_command('gpt rename host 0 2 second')
+ output = u_boot_console.run_command('gpt read host 0')
+ assert 'name second' in output
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000800 0x00000fff "first"' in output
+ assert '0x00001000 0x00001bff "second"' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.buildconfigspec('cmd_gpt_rename')
+@pytest.mark.buildconfigspec('cmd_part')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_swap_partitions(state_disk_image, u_boot_console):
+ """Test the gpt swap command to exchange two partition names."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000800 0x00000fff "first"' in output
+ assert '0x00001000 0x00001bff "second"' in output
+ u_boot_console.run_command('gpt swap host 0 first second')
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000800 0x00000fff "second"' in output
+ assert '0x00001000 0x00001bff "first"' in output
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('cmd_gpt')
+@pytest.mark.buildconfigspec('cmd_part')
+@pytest.mark.requiredtool('sgdisk')
+def test_gpt_write(state_disk_image, u_boot_console):
+ """Test the gpt write command."""
+
+ u_boot_console.run_command('host bind 0 ' + state_disk_image.path)
+ output = u_boot_console.run_command('gpt write host 0 "name=all,size=0"')
+ assert 'Writing GPT: success!' in output
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000022 0x00001fde "all"' in output
+ output = u_boot_console.run_command('gpt write host 0 "uuid_disk=375a56f7-d6c9-4e81-b5f0-09d41ca89efe;name=first,start=1M,size=1M;name=second,start=0x200000,size=0x180000;"')
+ assert 'Writing GPT: success!' in output
+ output = u_boot_console.run_command('part list host 0')
+ assert '0x00000800 0x00000fff "first"' in output
+ assert '0x00001000 0x00001bff "second"' in output
+ output = u_boot_console.run_command('gpt guid host 0')
+ assert '375a56f7-d6c9-4e81-b5f0-09d41ca89efe' in output
diff --git a/test/py/tests/test_handoff.py b/test/py/tests/test_handoff.py
new file mode 100644
index 00000000..038f0306
--- /dev/null
+++ b/test/py/tests/test_handoff.py
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2016 Google, Inc
+
+import pytest
+
+# Magic number to check that SPL handoff is working
+TEST_HANDOFF_MAGIC = 0x14f93c7b
+
+@pytest.mark.boardspec('sandbox_spl')
+@pytest.mark.buildconfigspec('spl')
+def test_handoff(u_boot_console):
+ """Test that of-platdata can be generated and used in sandbox"""
+ cons = u_boot_console
+ response = cons.run_command('sb handoff')
+ assert ('SPL handoff magic %x' % TEST_HANDOFF_MAGIC) in response
diff --git a/test/py/tests/test_help.py b/test/py/tests/test_help.py
new file mode 100644
index 00000000..d50295e5
--- /dev/null
+++ b/test/py/tests/test_help.py
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+def test_help(u_boot_console):
+ """Test that the "help" command can be executed."""
+
+ u_boot_console.run_command('help')
diff --git a/test/py/tests/test_hush_if_test.py b/test/py/tests/test_hush_if_test.py
new file mode 100644
index 00000000..bba8d41d
--- /dev/null
+++ b/test/py/tests/test_hush_if_test.py
@@ -0,0 +1,161 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test operation of the "if" shell command.
+
+import os
+import os.path
+import pytest
+
+pytestmark = pytest.mark.buildconfigspec('hush_parser')
+
+# The list of "if test" conditions to test.
+subtests = (
+ # Base if functionality.
+
+ ('true', True),
+ ('false', False),
+
+ # Basic operators.
+
+ ('test aaa = aaa', True),
+ ('test aaa = bbb', False),
+
+ ('test aaa != bbb', True),
+ ('test aaa != aaa', False),
+
+ ('test aaa < bbb', True),
+ ('test bbb < aaa', False),
+
+ ('test bbb > aaa', True),
+ ('test aaa > bbb', False),
+
+ ('test 123 -eq 123', True),
+ ('test 123 -eq 456', False),
+
+ ('test 123 -ne 456', True),
+ ('test 123 -ne 123', False),
+
+ ('test 123 -lt 456', True),
+ ('test 123 -lt 123', False),
+ ('test 456 -lt 123', False),
+
+ ('test 123 -le 456', True),
+ ('test 123 -le 123', True),
+ ('test 456 -le 123', False),
+
+ ('test 456 -gt 123', True),
+ ('test 123 -gt 123', False),
+ ('test 123 -gt 456', False),
+
+ ('test 456 -ge 123', True),
+ ('test 123 -ge 123', True),
+ ('test 123 -ge 456', False),
+
+ ('test -z ""', True),
+ ('test -z "aaa"', False),
+
+ ('test -n "aaa"', True),
+ ('test -n ""', False),
+
+ # Inversion of simple tests.
+
+ ('test ! aaa = aaa', False),
+ ('test ! aaa = bbb', True),
+ ('test ! ! aaa = aaa', True),
+ ('test ! ! aaa = bbb', False),
+
+ # Binary operators.
+
+ ('test aaa != aaa -o bbb != bbb', False),
+ ('test aaa != aaa -o bbb = bbb', True),
+ ('test aaa = aaa -o bbb != bbb', True),
+ ('test aaa = aaa -o bbb = bbb', True),
+
+ ('test aaa != aaa -a bbb != bbb', False),
+ ('test aaa != aaa -a bbb = bbb', False),
+ ('test aaa = aaa -a bbb != bbb', False),
+ ('test aaa = aaa -a bbb = bbb', True),
+
+ # Inversion within binary operators.
+
+ ('test ! aaa != aaa -o ! bbb != bbb', True),
+ ('test ! aaa != aaa -o ! bbb = bbb', True),
+ ('test ! aaa = aaa -o ! bbb != bbb', True),
+ ('test ! aaa = aaa -o ! bbb = bbb', False),
+
+ ('test ! ! aaa != aaa -o ! ! bbb != bbb', False),
+ ('test ! ! aaa != aaa -o ! ! bbb = bbb', True),
+ ('test ! ! aaa = aaa -o ! ! bbb != bbb', True),
+ ('test ! ! aaa = aaa -o ! ! bbb = bbb', True),
+
+ # -z operator.
+
+ ('test -z "$ut_var_nonexistent"', True),
+ ('test -z "$ut_var_exists"', False),
+)
+
+def exec_hush_if(u_boot_console, expr, result):
+ """Execute a shell "if" command, and validate its result."""
+
+ config = u_boot_console.config.buildconfig
+ maxargs = int(config.get('config_sys_maxargs', '0'))
+ args = len(expr.split(' ')) - 1
+ if args > maxargs:
+ u_boot_console.log.warning('CONFIG_SYS_MAXARGS too low; need ' +
+ str(args))
+ pytest.skip()
+
+ cmd = 'if ' + expr + '; then echo true; else echo false; fi'
+ response = u_boot_console.run_command(cmd)
+ assert response.strip() == str(result).lower()
+
+def test_hush_if_test_setup(u_boot_console):
+ """Set up environment variables used during the "if" tests."""
+
+ u_boot_console.run_command('setenv ut_var_nonexistent')
+ u_boot_console.run_command('setenv ut_var_exists 1')
+
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.parametrize('expr,result', subtests)
+def test_hush_if_test(u_boot_console, expr, result):
+ """Test a single "if test" condition."""
+
+ exec_hush_if(u_boot_console, expr, result)
+
+def test_hush_if_test_teardown(u_boot_console):
+ """Clean up environment variables used during the "if" tests."""
+
+ u_boot_console.run_command('setenv ut_var_exists')
+
+# We might test this on real filesystems via UMS, DFU, 'save', etc.
+# Of those, only UMS currently allows file removal though.
+@pytest.mark.buildconfigspec('cmd_echo')
+@pytest.mark.boardspec('sandbox')
+def test_hush_if_test_host_file_exists(u_boot_console):
+ """Test the "if test -e" shell command."""
+
+ test_file = u_boot_console.config.result_dir + \
+ '/creating_this_file_breaks_u_boot_tests'
+
+ try:
+ os.unlink(test_file)
+ except:
+ pass
+ assert not os.path.exists(test_file)
+
+ expr = 'test -e hostfs - ' + test_file
+ exec_hush_if(u_boot_console, expr, False)
+
+ try:
+ with open(test_file, 'wb'):
+ pass
+ assert os.path.exists(test_file)
+
+ expr = 'test -e hostfs - ' + test_file
+ exec_hush_if(u_boot_console, expr, True)
+ finally:
+ os.unlink(test_file)
+
+ expr = 'test -e hostfs - ' + test_file
+ exec_hush_if(u_boot_console, expr, False)
diff --git a/test/py/tests/test_log.py b/test/py/tests/test_log.py
new file mode 100644
index 00000000..75325fad
--- /dev/null
+++ b/test/py/tests/test_log.py
@@ -0,0 +1,132 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2016, Google Inc.
+#
+# U-Boot Verified Boot Test
+
+"""
+This tests U-Boot logging. It uses the 'log test' command with various options
+and checks that the output is correct.
+"""
+
+import pytest
+
+LOGL_FIRST, LOGL_WARNING, LOGL_INFO = (0, 4, 6)
+
+@pytest.mark.buildconfigspec('cmd_log')
+def test_log(u_boot_console):
+ """Test that U-Boot logging works correctly."""
+ def check_log_entries(lines, mask, max_level=LOGL_INFO):
+ """Check that the expected log records appear in the output
+
+ Args:
+ lines: iterator containing lines to check
+ mask: bit mask to select which lines to check for:
+ bit 0: standard log line
+ bit 1: _log line
+ max_level: maximum log level to expect in the output
+ """
+ for i in range(max_level):
+ if mask & 1:
+ assert 'log_run() log %d' % i == next(lines)
+ if mask & 3:
+ assert 'func() _log %d' % i == next(lines)
+
+ def run_test(testnum):
+ """Run a particular test number (the 'log test' command)
+
+ Args:
+ testnum: Test number to run
+ Returns:
+ iterator containing the lines output from the command
+ """
+ with cons.log.section('basic'):
+ output = u_boot_console.run_command('log test %d' % testnum)
+ split = output.replace('\r', '').splitlines()
+ lines = iter(split)
+ assert 'test %d' % testnum == next(lines)
+ return lines
+
+ def test0():
+ lines = run_test(0)
+ check_log_entries(lines, 3)
+
+ def test1():
+ lines = run_test(1)
+ check_log_entries(lines, 3)
+
+ def test2():
+ lines = run_test(2)
+
+ def test3():
+ lines = run_test(3)
+ check_log_entries(lines, 2)
+
+ def test4():
+ lines = run_test(4)
+ assert next(lines, None) == None
+
+ def test5():
+ lines = run_test(5)
+ check_log_entries(lines, 2)
+
+ def test6():
+ lines = run_test(6)
+ check_log_entries(lines, 3)
+
+ def test7():
+ lines = run_test(7)
+ check_log_entries(lines, 3, LOGL_WARNING)
+
+ def test8():
+ lines = run_test(8)
+ check_log_entries(lines, 3)
+
+ def test9():
+ lines = run_test(9)
+ check_log_entries(lines, 3)
+
+ def test10():
+ lines = run_test(10)
+ for i in range(7):
+ assert 'log_test() level %d' % i == next(lines)
+
+ # TODO(sjg@chromium.org): Consider structuring this as separate tests
+ cons = u_boot_console
+ test0()
+ test1()
+ test2()
+ test3()
+ test4()
+ test5()
+ test6()
+ test7()
+ test8()
+ test9()
+ test10()
+
+@pytest.mark.buildconfigspec('cmd_log')
+def test_log_format(u_boot_console):
+ """Test the 'log format' and 'log rec' commands"""
+ def run_with_format(fmt, expected_output):
+ """Set up the log format and then write a log record
+
+ Args:
+ fmt: Format to use for 'log format'
+ expected_output: Expected output from the 'log rec' command
+ """
+ output = cons.run_command('log format %s' % fmt)
+ assert output == ''
+ output = cons.run_command('log rec arch notice file.c 123 func msg')
+ assert output == expected_output
+
+ cons = u_boot_console
+ with cons.log.section('format'):
+ run_with_format('all', 'NOTICE.arch,file.c:123-func() msg')
+ output = cons.run_command('log format')
+ assert output == 'Log format: clFLfm'
+
+ run_with_format('fm', 'func() msg')
+ run_with_format('clfm', 'NOTICE.arch,func() msg')
+ run_with_format('FLfm', 'file.c:123-func() msg')
+ run_with_format('lm', 'NOTICE. msg')
+ run_with_format('m', 'msg')
diff --git a/test/py/tests/test_md.py b/test/py/tests/test_md.py
new file mode 100644
index 00000000..83e3c546
--- /dev/null
+++ b/test/py/tests/test_md.py
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+import pytest
+import u_boot_utils
+
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_md(u_boot_console):
+ """Test that md reads memory as expected, and that memory can be modified
+ using the mw command."""
+
+ ram_base = u_boot_utils.find_ram_base(u_boot_console)
+ addr = '%08x' % ram_base
+ val = 'a5f09876'
+ expected_response = addr + ': ' + val
+ u_boot_console.run_command('mw ' + addr + ' 0 10')
+ response = u_boot_console.run_command('md ' + addr + ' 10')
+ assert(not (expected_response in response))
+ u_boot_console.run_command('mw ' + addr + ' ' + val)
+ response = u_boot_console.run_command('md ' + addr + ' 10')
+ assert(expected_response in response)
+
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_md_repeat(u_boot_console):
+ """Test command repeat (via executing an empty command) operates correctly
+ for "md"; the command must repeat and dump an incrementing address."""
+
+ ram_base = u_boot_utils.find_ram_base(u_boot_console)
+ addr_base = '%08x' % ram_base
+ words = 0x10
+ addr_repeat = '%08x' % (ram_base + (words * 4))
+ u_boot_console.run_command('md %s %x' % (addr_base, words))
+ response = u_boot_console.run_command('')
+ expected_response = addr_repeat + ': '
+ assert(expected_response in response)
diff --git a/test/py/tests/test_mmc_rd.py b/test/py/tests/test_mmc_rd.py
new file mode 100644
index 00000000..a25aa5f6
--- /dev/null
+++ b/test/py/tests/test_mmc_rd.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+
+# Test U-Boot's "mmc read" command. The test reads data from the eMMC or SD
+# card, and validates the no errors occurred, and that the expected data was
+# read if the test configuration contains a CRC of the expected data.
+
+import pytest
+import time
+import u_boot_utils
+
+"""
+This test relies on boardenv_* to containing configuration values to define
+which MMC devices should be tested. For example:
+
+# Configuration data for test_mmc_dev, test_mmc_rescan, test_mmc_info; defines
+# whole MMC devices that mmc dev/rescan/info commands may operate upon.
+env__mmc_dev_configs = (
+ {
+ 'fixture_id': 'emmc-boot0',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 1,
+ 'info_device': ???,
+ 'info_speed': ???,
+ 'info_mode': ???,
+ 'info_buswidth': ???.
+ },
+ {
+ 'fixture_id': 'emmc-boot1',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 2,
+ 'info_device': ???,
+ 'info_speed': ???,
+ 'info_mode': ???,
+ 'info_buswidth': ???.
+ },
+ {
+ 'fixture_id': 'emmc-data',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 0,
+ 'info_device': ???,
+ 'info_speed': ???,
+ 'info_mode': ???,
+ 'info_buswidth': ???.
+ },
+ {
+ 'fixture_id': 'sd',
+ 'is_emmc': False,
+ 'devid': 1,
+ 'partid': None,
+ 'info_device': ???,
+ 'info_speed': ???,
+ 'info_mode': ???,
+ 'info_buswidth': ???.
+ },
+}
+
+# Configuration data for test_mmc_rd; defines regions of the MMC (entire
+# devices, or ranges of sectors) which can be read:
+env__mmc_rd_configs = (
+ {
+ 'fixture_id': 'emmc-boot0',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 1,
+ 'sector': 0x10,
+ 'count': 1,
+ },
+ {
+ 'fixture_id': 'emmc-boot1',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 2,
+ 'sector': 0x10,
+ 'count': 1,
+ },
+ {
+ 'fixture_id': 'emmc-data',
+ 'is_emmc': True,
+ 'devid': 0,
+ 'partid': 0,
+ 'sector': 0x10,
+ 'count': 0x1000,
+ },
+ {
+ 'fixture_id': 'sd-mbr',
+ 'is_emmc': False,
+ 'devid': 1,
+ 'partid': None,
+ 'sector': 0,
+ 'count': 1,
+ 'crc32': '8f6ecf0d',
+ },
+ {
+ 'fixture_id': 'sd-large',
+ 'is_emmc': False,
+ 'devid': 1,
+ 'partid': None,
+ 'sector': 0x10,
+ 'count': 0x1000,
+ },
+)
+"""
+
+def mmc_dev(u_boot_console, is_emmc, devid, partid):
+ """Run the "mmc dev" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ is_emmc: Whether the device is eMMC
+ devid: Device ID
+ partid: Partition ID
+
+ Returns:
+ Nothing.
+ """
+
+ # Select MMC device
+ cmd = 'mmc dev %d' % devid
+ if is_emmc:
+ cmd += ' %d' % partid
+ response = u_boot_console.run_command(cmd)
+ assert 'no card present' not in response
+ if is_emmc:
+ partid_response = '(part %d)' % partid
+ else:
+ partid_response = ''
+ good_response = 'mmc%d%s is current device' % (devid, partid_response)
+ assert good_response in response
+
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_mmc_dev(u_boot_console, env__mmc_dev_config):
+ """Test the "mmc dev" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__mmc_dev_config: The single MMC configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ is_emmc = env__mmc_dev_config['is_emmc']
+ devid = env__mmc_dev_config['devid']
+ partid = env__mmc_dev_config.get('partid', 0)
+
+ # Select MMC device
+ mmc_dev(u_boot_console, is_emmc, devid, partid)
+
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_mmc_rescan(u_boot_console, env__mmc_dev_config):
+ """Test the "mmc rescan" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__mmc_dev_config: The single MMC configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ is_emmc = env__mmc_dev_config['is_emmc']
+ devid = env__mmc_dev_config['devid']
+ partid = env__mmc_dev_config.get('partid', 0)
+
+ # Select MMC device
+ mmc_dev(u_boot_console, is_emmc, devid, partid)
+
+ # Rescan MMC device
+ cmd = 'mmc rescan'
+ response = u_boot_console.run_command(cmd)
+ assert 'no card present' not in response
+
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_mmc_info(u_boot_console, env__mmc_dev_config):
+ """Test the "mmc info" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__mmc_dev_config: The single MMC configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ is_emmc = env__mmc_dev_config['is_emmc']
+ devid = env__mmc_dev_config['devid']
+ partid = env__mmc_dev_config.get('partid', 0)
+ info_device = env__mmc_dev_config['info_device']
+ info_speed = env__mmc_dev_config['info_speed']
+ info_mode = env__mmc_dev_config['info_mode']
+ info_buswidth = env__mmc_dev_config['info_buswidth']
+
+ # Select MMC device
+ mmc_dev(u_boot_console, is_emmc, devid, partid)
+
+ # Read MMC device information
+ cmd = 'mmc info'
+ response = u_boot_console.run_command(cmd)
+ good_response = "Device: %s" % info_device
+ assert good_response in response
+ good_response = "Bus Speed: %s" % info_speed
+ assert good_response in response
+ good_response = "Mode : %s" % info_mode
+ assert good_response in response
+ good_response = "Bus Width: %s" % info_buswidth
+ assert good_response in response
+
+@pytest.mark.buildconfigspec('cmd_mmc')
+def test_mmc_rd(u_boot_console, env__mmc_rd_config):
+ """Test the "mmc read" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__mmc_rd_config: The single MMC configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ is_emmc = env__mmc_rd_config['is_emmc']
+ devid = env__mmc_rd_config['devid']
+ partid = env__mmc_rd_config.get('partid', 0)
+ sector = env__mmc_rd_config.get('sector', 0)
+ count_sectors = env__mmc_rd_config.get('count', 1)
+ expected_crc32 = env__mmc_rd_config.get('crc32', None)
+ read_duration_max = env__mmc_rd_config.get('read_duration_max', 0)
+
+ count_bytes = count_sectors * 512
+ bcfg = u_boot_console.config.buildconfig
+ has_cmd_memory = bcfg.get('config_cmd_memory', 'n') == 'y'
+ has_cmd_crc32 = bcfg.get('config_cmd_crc32', 'n') == 'y'
+ ram_base = u_boot_utils.find_ram_base(u_boot_console)
+ addr = '0x%08x' % ram_base
+
+ # Select MMC device
+ mmc_dev(u_boot_console, is_emmc, devid, partid)
+
+ # Clear target RAM
+ if expected_crc32:
+ if has_cmd_memory and has_cmd_crc32:
+ cmd = 'mw.b %s 0 0x%x' % (addr, count_bytes)
+ u_boot_console.run_command(cmd)
+
+ cmd = 'crc32 %s 0x%x' % (addr, count_bytes)
+ response = u_boot_console.run_command(cmd)
+ assert expected_crc32 not in response
+ else:
+ u_boot_console.log.warning(
+ 'CONFIG_CMD_MEMORY or CONFIG_CMD_CRC32 != y: Skipping RAM clear')
+
+ # Read data
+ cmd = 'mmc read %s %x %x' % (addr, sector, count_sectors)
+ tstart = time.time()
+ response = u_boot_console.run_command(cmd)
+ tend = time.time()
+ good_response = 'MMC read: dev # %d, block # %d, count %d ... %d blocks read: OK' % (
+ devid, sector, count_sectors, count_sectors)
+ assert good_response in response
+
+ # Check target RAM
+ if expected_crc32:
+ if has_cmd_crc32:
+ cmd = 'crc32 %s 0x%x' % (addr, count_bytes)
+ response = u_boot_console.run_command(cmd)
+ assert expected_crc32 in response
+ else:
+ u_boot_console.log.warning('CONFIG_CMD_CRC32 != y: Skipping check')
+
+ # Check if the command did not take too long
+ if read_duration_max:
+ elapsed = tend - tstart
+ u_boot_console.log.info('Reading %d bytes took %f seconds' %
+ (count_bytes, elapsed))
+ assert elapsed <= (read_duration_max - 0.01)
diff --git a/test/py/tests/test_mmc_wr.py b/test/py/tests/test_mmc_wr.py
new file mode 100644
index 00000000..05e5c1ee
--- /dev/null
+++ b/test/py/tests/test_mmc_wr.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2019, Texas Instrument
+# Author: Jean-Jacques Hiblot <jjhiblot@ti.com>
+
+# Test U-Boot's "mmc write" command. The test generates random data, writes it
+# to the eMMC or SD card, then reads it back and performs a comparison.
+
+import pytest
+import u_boot_utils
+
+"""
+This test relies on boardenv_* to containing configuration values to define
+which MMC devices should be tested. For example:
+
+env__mmc_wr_configs = (
+ {
+ "fixture_id": "emmc-boot0",
+ "is_emmc": True,
+ "devid": 1,
+ "partid": 1,
+ "sector": 0x10,
+ "count": 100,
+ "test_iterations": 50,
+ },
+ {
+ "fixture_id": "emmc-boot1",
+ "is_emmc": True,
+ "devid": 1,
+ "partid": 2,
+ "sector": 0x10,
+ "count": 100,
+ "test_iterations": 50,
+ },
+)
+
+"""
+
+@pytest.mark.buildconfigspec('cmd_mmc')
+@pytest.mark.buildconfigspec('cmd_memory')
+@pytest.mark.buildconfigspec('cmd_random')
+def test_mmc_wr(u_boot_console, env__mmc_wr_config):
+ """Test the "mmc write" command.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__mmc_wr_config: The single MMC configuration on which
+ to run the test. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ is_emmc = env__mmc_wr_config['is_emmc']
+ devid = env__mmc_wr_config['devid']
+ partid = env__mmc_wr_config.get('partid', 0)
+ sector = env__mmc_wr_config.get('sector', 0)
+ count_sectors = env__mmc_wr_config.get('count', 1)
+ test_iterations = env__mmc_wr_config.get('test_iterations', 1)
+
+
+ count_bytes = count_sectors * 512
+ bcfg = u_boot_console.config.buildconfig
+ ram_base = u_boot_utils.find_ram_base(u_boot_console)
+ src_addr = '0x%08x' % ram_base
+ dst_addr = '0x%08x' % (ram_base + count_bytes)
+
+
+ for i in range(test_iterations):
+ # Generate random data
+ cmd = 'random %s %x' % (src_addr, count_bytes)
+ response = u_boot_console.run_command(cmd)
+ good_response = '%d bytes filled with random data' % (count_bytes)
+ assert good_response in response
+
+ # Select MMC device
+ cmd = 'mmc dev %d' % devid
+ if is_emmc:
+ cmd += ' %d' % partid
+ response = u_boot_console.run_command(cmd)
+ assert 'no card present' not in response
+ if is_emmc:
+ partid_response = "(part %d)" % partid
+ else:
+ partid_response = ""
+ good_response = 'mmc%d%s is current device' % (devid, partid_response)
+ assert good_response in response
+
+ # Write data
+ cmd = 'mmc write %s %x %x' % (src_addr, sector, count_sectors)
+ response = u_boot_console.run_command(cmd)
+ good_response = 'MMC write: dev # %d, block # %d, count %d ... %d blocks written: OK' % (devid, sector, count_sectors, count_sectors)
+ assert good_response in response
+
+ # Read data
+ cmd = 'mmc read %s %x %x' % (dst_addr, sector, count_sectors)
+ response = u_boot_console.run_command(cmd)
+ good_response = 'MMC read: dev # %d, block # %d, count %d ... %d blocks read: OK' % (devid, sector, count_sectors, count_sectors)
+ assert good_response in response
+
+ # Compare src and dst data
+ cmd = 'cmp.b %s %s %x' % (src_addr, dst_addr, count_bytes)
+ response = u_boot_console.run_command(cmd)
+ good_response = 'Total of %d byte(s) were the same' % (count_bytes)
+ assert good_response in response
diff --git a/test/py/tests/test_net.py b/test/py/tests/test_net.py
new file mode 100644
index 00000000..9ca6743a
--- /dev/null
+++ b/test/py/tests/test_net.py
@@ -0,0 +1,208 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test various network-related functionality, such as the dhcp, ping, and
+# tftpboot commands.
+
+import pytest
+import u_boot_utils
+
+"""
+Note: This test relies on boardenv_* containing configuration values to define
+which the network environment available for testing. Without this, this test
+will be automatically skipped.
+
+For example:
+
+# Boolean indicating whether the Ethernet device is attached to USB, and hence
+# USB enumeration needs to be performed prior to network tests.
+# This variable may be omitted if its value is False.
+env__net_uses_usb = False
+
+# Boolean indicating whether the Ethernet device is attached to PCI, and hence
+# PCI enumeration needs to be performed prior to network tests.
+# This variable may be omitted if its value is False.
+env__net_uses_pci = True
+
+# True if a DHCP server is attached to the network, and should be tested.
+# If DHCP testing is not possible or desired, this variable may be omitted or
+# set to False.
+env__net_dhcp_server = True
+
+# A list of environment variables that should be set in order to configure a
+# static IP. If solely relying on DHCP, this variable may be omitted or set to
+# an empty list.
+env__net_static_env_vars = [
+ ('ipaddr', '10.0.0.100'),
+ ('netmask', '255.255.255.0'),
+ ('serverip', '10.0.0.1'),
+]
+
+# Details regarding a file that may be read from a TFTP server. This variable
+# may be omitted or set to None if TFTP testing is not possible or desired.
+env__net_tftp_readable_file = {
+ 'fn': 'ubtest-readable.bin',
+ 'addr': 0x10000000,
+ 'size': 5058624,
+ 'crc32': 'c2244b26',
+}
+
+# Details regarding a file that may be read from a NFS server. This variable
+# may be omitted or set to None if NFS testing is not possible or desired.
+env__net_nfs_readable_file = {
+ 'fn': 'ubtest-readable.bin',
+ 'addr': 0x10000000,
+ 'size': 5058624,
+ 'crc32': 'c2244b26',
+}
+"""
+
+net_set_up = False
+
+def test_net_pre_commands(u_boot_console):
+ """Execute any commands required to enable network hardware.
+
+ These commands are provided by the boardenv_* file; see the comment at the
+ beginning of this file.
+ """
+
+ init_usb = u_boot_console.config.env.get('env__net_uses_usb', False)
+ if init_usb:
+ u_boot_console.run_command('usb start')
+
+ init_pci = u_boot_console.config.env.get('env__net_uses_pci', False)
+ if init_pci:
+ u_boot_console.run_command('pci enum')
+
+@pytest.mark.buildconfigspec('cmd_dhcp')
+def test_net_dhcp(u_boot_console):
+ """Test the dhcp command.
+
+ The boardenv_* file may be used to enable/disable this test; see the
+ comment at the beginning of this file.
+ """
+
+ test_dhcp = u_boot_console.config.env.get('env__net_dhcp_server', False)
+ if not test_dhcp:
+ pytest.skip('No DHCP server available')
+
+ u_boot_console.run_command('setenv autoload no')
+ output = u_boot_console.run_command('dhcp')
+ assert 'DHCP client bound to address ' in output
+
+ global net_set_up
+ net_set_up = True
+
+@pytest.mark.buildconfigspec('net')
+def test_net_setup_static(u_boot_console):
+ """Set up a static IP configuration.
+
+ The configuration is provided by the boardenv_* file; see the comment at
+ the beginning of this file.
+ """
+
+ env_vars = u_boot_console.config.env.get('env__net_static_env_vars', None)
+ if not env_vars:
+ pytest.skip('No static network configuration is defined')
+
+ for (var, val) in env_vars:
+ u_boot_console.run_command('setenv %s %s' % (var, val))
+
+ global net_set_up
+ net_set_up = True
+
+@pytest.mark.buildconfigspec('cmd_ping')
+def test_net_ping(u_boot_console):
+ """Test the ping command.
+
+ The $serverip (as set up by either test_net_dhcp or test_net_setup_static)
+ is pinged. The test validates that the host is alive, as reported by the
+ ping command's output.
+ """
+
+ if not net_set_up:
+ pytest.skip('Network not initialized')
+
+ output = u_boot_console.run_command('ping $serverip')
+ assert 'is alive' in output
+
+@pytest.mark.buildconfigspec('cmd_net')
+def test_net_tftpboot(u_boot_console):
+ """Test the tftpboot command.
+
+ A file is downloaded from the TFTP server, its size and optionally its
+ CRC32 are validated.
+
+ The details of the file to download are provided by the boardenv_* file;
+ see the comment at the beginning of this file.
+ """
+
+ if not net_set_up:
+ pytest.skip('Network not initialized')
+
+ f = u_boot_console.config.env.get('env__net_tftp_readable_file', None)
+ if not f:
+ pytest.skip('No TFTP readable file to read')
+
+ addr = f.get('addr', None)
+
+ fn = f['fn']
+ if not addr:
+ output = u_boot_console.run_command('tftpboot %s' % (fn))
+ else:
+ output = u_boot_console.run_command('tftpboot %x %s' % (addr, fn))
+ expected_text = 'Bytes transferred = '
+ sz = f.get('size', None)
+ if sz:
+ expected_text += '%d' % sz
+ assert expected_text in output
+
+ expected_crc = f.get('crc32', None)
+ if not expected_crc:
+ return
+
+ if u_boot_console.config.buildconfig.get('config_cmd_crc32', 'n') != 'y':
+ return
+
+ output = u_boot_console.run_command('crc32 $fileaddr $filesize')
+ assert expected_crc in output
+
+@pytest.mark.buildconfigspec('cmd_nfs')
+def test_net_nfs(u_boot_console):
+ """Test the nfs command.
+
+ A file is downloaded from the NFS server, its size and optionally its
+ CRC32 are validated.
+
+ The details of the file to download are provided by the boardenv_* file;
+ see the comment at the beginning of this file.
+ """
+
+ if not net_set_up:
+ pytest.skip('Network not initialized')
+
+ f = u_boot_console.config.env.get('env__net_nfs_readable_file', None)
+ if not f:
+ pytest.skip('No NFS readable file to read')
+
+ addr = f.get('addr', None)
+ if not addr:
+ addr = u_boot_utils.find_ram_base(u_boot_console)
+
+ fn = f['fn']
+ output = u_boot_console.run_command('nfs %x %s' % (addr, fn))
+ expected_text = 'Bytes transferred = '
+ sz = f.get('size', None)
+ if sz:
+ expected_text += '%d' % sz
+ assert expected_text in output
+
+ expected_crc = f.get('crc32', None)
+ if not expected_crc:
+ return
+
+ if u_boot_console.config.buildconfig.get('config_cmd_crc32', 'n') != 'y':
+ return
+
+ output = u_boot_console.run_command('crc32 %x $filesize' % addr)
+ assert expected_crc in output
diff --git a/test/py/tests/test_ofplatdata.py b/test/py/tests/test_ofplatdata.py
new file mode 100644
index 00000000..263334b0
--- /dev/null
+++ b/test/py/tests/test_ofplatdata.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2016 Google, Inc
+
+import pytest
+import u_boot_utils as util
+
+OF_PLATDATA_OUTPUT = '''
+of-platdata probe:
+bool 1
+byte 05
+bytearray 06 00 00
+int 1
+intarray 2 3 4 0
+longbytearray 09 0a 0b 0c 0d 0e 0f 10 11
+string message
+stringarray "multi-word" "message" ""
+of-platdata probe:
+bool 0
+byte 08
+bytearray 01 23 34
+int 3
+intarray 5 0 0 0
+longbytearray 09 00 00 00 00 00 00 00 00
+string message2
+stringarray "another" "multi-word" "message"
+of-platdata probe:
+bool 0
+byte 00
+bytearray 00 00 00
+int 0
+intarray 0 0 0 0
+longbytearray 00 00 00 00 00 00 00 00 00
+string <NULL>
+stringarray "one" "" ""
+of-platdata probe:
+bool 0
+byte 00
+bytearray 00 00 00
+int 0
+intarray 0 0 0 0
+longbytearray 00 00 00 00 00 00 00 00 00
+string <NULL>
+stringarray "spl" "" ""
+'''
+
+@pytest.mark.buildconfigspec('spl_of_platdata')
+def test_ofplatdata(u_boot_console):
+ """Test that of-platdata can be generated and used in sandbox"""
+ cons = u_boot_console
+ cons.restart_uboot_with_flags(['--show_of_platdata'])
+ output = cons.get_spawn_output().replace('\r', '')
+ assert OF_PLATDATA_OUTPUT in output
+
+@pytest.mark.buildconfigspec('spl_of_platdata')
+def test_spl_devicetree(u_boot_console):
+ """Test content of spl device-tree"""
+ cons = u_boot_console
+ dtb = cons.config.build_dir + '/spl/u-boot-spl.dtb'
+ fdtgrep = cons.config.build_dir + '/tools/fdtgrep'
+ output = util.run_and_log(cons, [fdtgrep, '-l', dtb])
+
+ assert "u-boot,dm-pre-reloc" not in output
+ assert "u-boot,dm-pre-proper" not in output
+ assert "u-boot,dm-spl" not in output
+ assert "u-boot,dm-tpl" not in output
+
+ assert "spl-test4" in output
+ assert "spl-test5" not in output
+ assert "spl-test6" not in output
+ assert "spl-test7" in output
diff --git a/test/py/tests/test_pinmux.py b/test/py/tests/test_pinmux.py
new file mode 100644
index 00000000..25394f1f
--- /dev/null
+++ b/test/py/tests/test_pinmux.py
@@ -0,0 +1,66 @@
+# SPDX-License-Identifier: GPL-2.0
+
+import pytest
+import u_boot_utils
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+def test_pinmux_usage_1(u_boot_console):
+ """Test that 'pinmux' command without parameters displays
+ pinmux usage."""
+ output = u_boot_console.run_command('pinmux')
+ assert 'Usage:' in output
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+def test_pinmux_usage_2(u_boot_console):
+ """Test that 'pinmux status' executed without previous "pinmux dev"
+ command displays pinmux usage."""
+ output = u_boot_console.run_command('pinmux status')
+ assert 'Usage:' in output
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+@pytest.mark.boardspec('sandbox')
+def test_pinmux_status_all(u_boot_console):
+ """Test that 'pinmux status -a' displays pin's muxing."""
+ output = u_boot_console.run_command('pinmux status -a')
+ assert ('SCL : I2C SCL' in output)
+ assert ('SDA : I2C SDA' in output)
+ assert ('TX : Uart TX' in output)
+ assert ('RX : Uart RX' in output)
+ assert ('W1 : 1-wire gpio' in output)
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+@pytest.mark.boardspec('sandbox')
+def test_pinmux_list(u_boot_console):
+ """Test that 'pinmux list' returns the pin-controller list."""
+ output = u_boot_console.run_command('pinmux list')
+ assert 'sandbox_pinctrl' in output
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+def test_pinmux_dev_bad(u_boot_console):
+ """Test that 'pinmux dev' returns an error when trying to select a
+ wrong pin controller."""
+ pincontroller = 'bad_pin_controller_name'
+ output = u_boot_console.run_command('pinmux dev ' + pincontroller)
+ expected_output = 'Can\'t get the pin-controller: ' + pincontroller + '!'
+ assert (expected_output in output)
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+@pytest.mark.boardspec('sandbox')
+def test_pinmux_dev(u_boot_console):
+ """Test that 'pinmux dev' select the wanted pin controller."""
+ pincontroller = 'pinctrl'
+ output = u_boot_console.run_command('pinmux dev ' + pincontroller)
+ expected_output = 'dev: ' + pincontroller
+ assert (expected_output in output)
+
+@pytest.mark.buildconfigspec('cmd_pinmux')
+@pytest.mark.boardspec('sandbox')
+def test_pinmux_status(u_boot_console):
+ """Test that 'pinmux status' displays selected pincontroller's pin
+ muxing descriptions."""
+ output = u_boot_console.run_command('pinmux status')
+ assert ('SCL : I2C SCL' in output)
+ assert ('SDA : I2C SDA' in output)
+ assert ('TX : Uart TX' in output)
+ assert ('RX : Uart RX' in output)
+ assert ('W1 : 1-wire gpio' in output)
diff --git a/test/py/tests/test_sandbox_exit.py b/test/py/tests/test_sandbox_exit.py
new file mode 100644
index 00000000..a301f4b5
--- /dev/null
+++ b/test/py/tests/test_sandbox_exit.py
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+import pytest
+import signal
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('sysreset')
+def test_reset(u_boot_console):
+ """Test that the "reset" command exits sandbox process."""
+
+ u_boot_console.run_command('reset', wait_for_prompt=False)
+ assert(u_boot_console.validate_exited())
+
+@pytest.mark.boardspec('sandbox')
+def test_ctrl_c(u_boot_console):
+ """Test that sending SIGINT to sandbox causes it to exit."""
+
+ u_boot_console.kill(signal.SIGINT)
+ assert(u_boot_console.validate_exited())
diff --git a/test/py/tests/test_sf.py b/test/py/tests/test_sf.py
new file mode 100644
index 00000000..adf8b7dc
--- /dev/null
+++ b/test/py/tests/test_sf.py
@@ -0,0 +1,217 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, Xilinx Inc. Michal Simek
+# Copyright (c) 2017, Xiphos Systems Corp. All rights reserved.
+
+import re
+import pytest
+import random
+import u_boot_utils
+
+"""
+Note: This test relies on boardenv_* containing configuration values to define
+which SPI Flash areas are available for testing. Without this, this test will
+be automatically skipped.
+For example:
+
+# A list of sections of Flash memory to be tested.
+env__sf_configs = (
+ {
+ # Where in SPI Flash should the test operate.
+ 'offset': 0x00000000,
+ # This value is optional.
+ # If present, specifies the [[bus:]cs] argument used in `sf probe`
+ # If missing, defaults to 0.
+ 'id': '0:1',
+ # This value is optional.
+ # If set as a number, specifies the speed of the SPI Flash.
+ # If set as an array of 2, specifies a range for a random speed.
+ # If missing, defaults to 0.
+ 'speed': 1000000,
+ # This value is optional.
+ # If present, specifies the size to use for read/write operations.
+ # If missing, the SPI Flash page size is used as a default (based on
+ # the `sf probe` output).
+ 'len': 0x10000,
+ # This value is optional.
+ # If present, specifies if the test can write to Flash offset
+ # If missing, defaults to False.
+ 'writeable': False,
+ # This value is optional.
+ # If present, specifies the expected CRC32 value of the flash area.
+ # If missing, extra check is ignored.
+ 'crc32': 0xCAFECAFE,
+ },
+)
+"""
+
+def sf_prepare(u_boot_console, env__sf_config):
+ """Check global state of the SPI Flash before running any test.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__sf_config: The single SPI Flash device configuration on which to
+ run the tests.
+
+ Returns:
+ sf_params: a dictionary of SPI Flash parameters.
+ """
+
+ sf_params = {}
+ sf_params['ram_base'] = u_boot_utils.find_ram_base(u_boot_console)
+
+ probe_id = env__sf_config.get('id', 0)
+ speed = env__sf_config.get('speed', 0)
+ if isinstance(speed, int):
+ sf_params['speed'] = speed
+ else:
+ assert len(speed) == 2, "If speed is a list, it must have 2 entries"
+ sf_params['speed'] = random.randint(speed[0], speed[1])
+
+ cmd = 'sf probe %d %d' % (probe_id, sf_params['speed'])
+
+ output = u_boot_console.run_command(cmd)
+ assert 'SF: Detected' in output, 'No Flash device available'
+
+ m = re.search('page size (.+?) Bytes', output)
+ assert m, 'SPI Flash page size not recognized'
+ sf_params['page_size'] = int(m.group(1))
+
+ m = re.search('erase size (.+?) KiB', output)
+ assert m, 'SPI Flash erase size not recognized'
+ sf_params['erase_size'] = int(m.group(1))
+ sf_params['erase_size'] *= 1024
+
+ m = re.search('total (.+?) MiB', output)
+ assert m, 'SPI Flash total size not recognized'
+ sf_params['total_size'] = int(m.group(1))
+ sf_params['total_size'] *= 1024 * 1024
+
+ assert 'offset' in env__sf_config, \
+ '\'offset\' is required for this test.'
+ sf_params['len'] = env__sf_config.get('len', sf_params['erase_size'])
+
+ assert not env__sf_config['offset'] % sf_params['erase_size'], \
+ 'offset not multiple of erase size.'
+ assert not sf_params['len'] % sf_params['erase_size'], \
+ 'erase length not multiple of erase size.'
+
+ assert not (env__sf_config.get('writeable', False) and
+ 'crc32' in env__sf_config), \
+ 'Cannot check crc32 on writeable sections'
+
+ return sf_params
+
+def sf_read(u_boot_console, env__sf_config, sf_params):
+ """Helper function used to read and compute the CRC32 value of a section of
+ SPI Flash memory.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__sf_config: The single SPI Flash device configuration on which to
+ run the tests.
+ sf_params: SPI Flash parameters.
+
+ Returns:
+ CRC32 value of SPI Flash section
+ """
+
+ addr = sf_params['ram_base']
+ offset = env__sf_config['offset']
+ count = sf_params['len']
+ pattern = random.randint(0, 0xFF)
+ crc_expected = env__sf_config.get('crc32', None)
+
+ cmd = 'mw.b %08x %02x %x' % (addr, pattern, count)
+ u_boot_console.run_command(cmd)
+ crc_pattern = u_boot_utils.crc32(u_boot_console, addr, count)
+ if crc_expected:
+ assert crc_pattern != crc_expected
+
+ cmd = 'sf read %08x %08x %x' % (addr, offset, count)
+ response = u_boot_console.run_command(cmd)
+ assert 'Read: OK' in response, 'Read operation failed'
+ crc_readback = u_boot_utils.crc32(u_boot_console, addr, count)
+ assert crc_pattern != crc_readback, 'sf read did not update RAM content.'
+ if crc_expected:
+ assert crc_readback == crc_expected
+
+ return crc_readback
+
+def sf_update(u_boot_console, env__sf_config, sf_params):
+ """Helper function used to update a section of SPI Flash memory.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__sf_config: The single SPI Flash device configuration on which to
+ run the tests.
+
+ Returns:
+ CRC32 value of SPI Flash section
+ """
+
+ addr = sf_params['ram_base']
+ offset = env__sf_config['offset']
+ count = sf_params['len']
+ pattern = int(random.random() * 0xFF)
+
+ cmd = 'mw.b %08x %02x %x' % (addr, pattern, count)
+ u_boot_console.run_command(cmd)
+ crc_pattern = u_boot_utils.crc32(u_boot_console, addr, count)
+
+ cmd = 'sf update %08x %08x %x' % (addr, offset, count)
+ u_boot_console.run_command(cmd)
+ crc_readback = sf_read(u_boot_console, env__sf_config, sf_params)
+
+ assert crc_readback == crc_pattern
+
+@pytest.mark.buildconfigspec('cmd_sf')
+@pytest.mark.buildconfigspec('cmd_crc32')
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_sf_read(u_boot_console, env__sf_config):
+ sf_params = sf_prepare(u_boot_console, env__sf_config)
+ sf_read(u_boot_console, env__sf_config, sf_params)
+
+@pytest.mark.buildconfigspec('cmd_sf')
+@pytest.mark.buildconfigspec('cmd_crc32')
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_sf_read_twice(u_boot_console, env__sf_config):
+ sf_params = sf_prepare(u_boot_console, env__sf_config)
+
+ crc1 = sf_read(u_boot_console, env__sf_config, sf_params)
+ sf_params['ram_base'] += 0x100
+ crc2 = sf_read(u_boot_console, env__sf_config, sf_params)
+
+ assert crc1 == crc2, 'CRC32 of two successive read operation do not match'
+
+@pytest.mark.buildconfigspec('cmd_sf')
+@pytest.mark.buildconfigspec('cmd_crc32')
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_sf_erase(u_boot_console, env__sf_config):
+ if not env__sf_config.get('writeable', False):
+ pytest.skip('Flash config is tagged as not writeable')
+
+ sf_params = sf_prepare(u_boot_console, env__sf_config)
+ addr = sf_params['ram_base']
+ offset = env__sf_config['offset']
+ count = sf_params['len']
+
+ cmd = 'sf erase %08x %x' % (offset, count)
+ output = u_boot_console.run_command(cmd)
+ assert 'Erased: OK' in output, 'Erase operation failed'
+
+ cmd = 'mw.b %08x ff %x' % (addr, count)
+ u_boot_console.run_command(cmd)
+ crc_ffs = u_boot_utils.crc32(u_boot_console, addr, count)
+
+ crc_read = sf_read(u_boot_console, env__sf_config, sf_params)
+ assert crc_ffs == crc_read, 'Unexpected CRC32 after erase operation.'
+
+@pytest.mark.buildconfigspec('cmd_sf')
+@pytest.mark.buildconfigspec('cmd_crc32')
+@pytest.mark.buildconfigspec('cmd_memory')
+def test_sf_update(u_boot_console, env__sf_config):
+ if not env__sf_config.get('writeable', False):
+ pytest.skip('Flash config is tagged as not writeable')
+
+ sf_params = sf_prepare(u_boot_console, env__sf_config)
+ sf_update(u_boot_console, env__sf_config, sf_params)
diff --git a/test/py/tests/test_shell_basics.py b/test/py/tests/test_shell_basics.py
new file mode 100644
index 00000000..f54f7b74
--- /dev/null
+++ b/test/py/tests/test_shell_basics.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test basic shell functionality, such as commands separate by semi-colons.
+
+import pytest
+
+pytestmark = pytest.mark.buildconfigspec('cmd_echo')
+
+def test_shell_execute(u_boot_console):
+ """Test any shell command."""
+
+ response = u_boot_console.run_command('echo hello')
+ assert response.strip() == 'hello'
+
+def test_shell_semicolon_two(u_boot_console):
+ """Test two shell commands separate by a semi-colon."""
+
+ cmd = 'echo hello; echo world'
+ response = u_boot_console.run_command(cmd)
+ # This validation method ignores the exact whitespace between the strings
+ assert response.index('hello') < response.index('world')
+
+def test_shell_semicolon_three(u_boot_console):
+ """Test three shell commands separate by a semi-colon, with variable
+ expansion dependencies between them."""
+
+ cmd = 'setenv list 1; setenv list ${list}2; setenv list ${list}3; ' + \
+ 'echo ${list}'
+ response = u_boot_console.run_command(cmd)
+ assert response.strip() == '123'
+ u_boot_console.run_command('setenv list')
+
+def test_shell_run(u_boot_console):
+ """Test the "run" shell command."""
+
+ u_boot_console.run_command('setenv foo "setenv monty 1; setenv python 2"')
+ u_boot_console.run_command('run foo')
+ response = u_boot_console.run_command('echo $monty')
+ assert response.strip() == '1'
+ response = u_boot_console.run_command('echo $python')
+ assert response.strip() == '2'
+ u_boot_console.run_command('setenv foo')
+ u_boot_console.run_command('setenv monty')
+ u_boot_console.run_command('setenv python')
diff --git a/test/py/tests/test_sleep.py b/test/py/tests/test_sleep.py
new file mode 100644
index 00000000..b69edf26
--- /dev/null
+++ b/test/py/tests/test_sleep.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+import pytest
+import time
+
+"""
+Note: This test doesn't rely on boardenv_* configuration values but they can
+change test behavior.
+
+# Setup env__sleep_accurate to False if time is not accurate on your platform
+env__sleep_accurate = False
+
+"""
+
+def test_sleep(u_boot_console):
+ """Test the sleep command, and validate that it sleeps for approximately
+ the correct amount of time."""
+
+ sleep_skip = u_boot_console.config.env.get('env__sleep_accurate', True)
+ if not sleep_skip:
+ pytest.skip('sleep is not accurate')
+
+ if u_boot_console.config.buildconfig.get('config_cmd_misc', 'n') != 'y':
+ pytest.skip('sleep command not supported')
+ # 3s isn't too long, but is enough to cross a few second boundaries.
+ sleep_time = 3
+ tstart = time.time()
+ u_boot_console.run_command('sleep %d' % sleep_time)
+ tend = time.time()
+ elapsed = tend - tstart
+ assert elapsed >= (sleep_time - 0.01)
+ if not u_boot_console.config.gdbserver:
+ # 0.25s margin is hopefully enough to account for any system overhead.
+ assert elapsed < (sleep_time + 0.25)
diff --git a/test/py/tests/test_tpm2.py b/test/py/tests/test_tpm2.py
new file mode 100644
index 00000000..70f906da
--- /dev/null
+++ b/test/py/tests/test_tpm2.py
@@ -0,0 +1,233 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2018, Bootlin
+# Author: Miquel Raynal <miquel.raynal@bootlin.com>
+
+import os.path
+import pytest
+import u_boot_utils
+import re
+import time
+
+"""
+Test the TPMv2.x related commands. You must have a working hardware setup in
+order to do these tests.
+
+Notes:
+* These tests will prove the password mechanism. The TPM chip must be cleared of
+any password.
+* Commands like pcr_setauthpolicy and pcr_resetauthpolicy are not implemented
+here because they would fail the tests in most cases (TPMs do not implement them
+and return an error).
+"""
+
+updates = 0
+
+def force_init(u_boot_console, force=False):
+ """When a test fails, U-Boot is reset. Because TPM stack must be initialized
+ after each reboot, we must ensure these lines are always executed before
+ trying any command or they will fail with no reason. Executing 'tpm init'
+ twice will spawn an error used to detect that the TPM was not reset and no
+ initialization code should be run.
+ """
+ output = u_boot_console.run_command('tpm2 init')
+ if force or not 'Error' in output:
+ u_boot_console.run_command('echo --- start of init ---')
+ u_boot_console.run_command('tpm2 startup TPM2_SU_CLEAR')
+ u_boot_console.run_command('tpm2 self_test full')
+ u_boot_console.run_command('tpm2 clear TPM2_RH_LOCKOUT')
+ output = u_boot_console.run_command('echo $?')
+ if not output.endswith('0'):
+ u_boot_console.run_command('tpm2 clear TPM2_RH_PLATFORM')
+ u_boot_console.run_command('echo --- end of init ---')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_init(u_boot_console):
+ """Init the software stack to use TPMv2 commands."""
+
+ u_boot_console.run_command('tpm2 init')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_startup(u_boot_console):
+ """Execute a TPM2_Startup command.
+
+ Initiate the TPM internal state machine.
+ """
+
+ u_boot_console.run_command('tpm2 startup TPM2_SU_CLEAR')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_self_test_full(u_boot_console):
+ """Execute a TPM2_SelfTest (full) command.
+
+ Ask the TPM to perform all self tests to also enable full capabilities.
+ """
+
+ u_boot_console.run_command('tpm2 self_test full')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_continue_self_test(u_boot_console):
+ """Execute a TPM2_SelfTest (continued) command.
+
+ Ask the TPM to finish its self tests (alternative to the full test) in order
+ to enter a fully operational state.
+ """
+
+ u_boot_console.run_command('tpm2 self_test continue')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_clear(u_boot_console):
+ """Execute a TPM2_Clear command.
+
+ Ask the TPM to reset entirely its internal state (including internal
+ configuration, passwords, counters and DAM parameters). This is half of the
+ TAKE_OWNERSHIP command from TPMv1.
+
+ Use the LOCKOUT hierarchy for this. The LOCKOUT/PLATFORM hierarchies must
+ not have a password set, otherwise this test will fail. ENDORSEMENT and
+ PLATFORM hierarchies are also available.
+ """
+
+ u_boot_console.run_command('tpm2 clear TPM2_RH_LOCKOUT')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+ u_boot_console.run_command('tpm2 clear TPM2_RH_PLATFORM')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_change_auth(u_boot_console):
+ """Execute a TPM2_HierarchyChangeAuth command.
+
+ Ask the TPM to change the owner, ie. set a new password: 'unicorn'
+
+ Use the LOCKOUT hierarchy for this. ENDORSEMENT and PLATFORM hierarchies are
+ also available.
+ """
+
+ force_init(u_boot_console)
+
+ u_boot_console.run_command('tpm2 change_auth TPM2_RH_LOCKOUT unicorn')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+ u_boot_console.run_command('tpm2 clear TPM2_RH_LOCKOUT unicorn')
+ output = u_boot_console.run_command('echo $?')
+ u_boot_console.run_command('tpm2 clear TPM2_RH_PLATFORM')
+ assert output.endswith('0')
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_get_capability(u_boot_console):
+ """Execute a TPM_GetCapability command.
+
+ Display one capability. In our test case, let's display the default DAM
+ lockout counter that should be 0 since the CLEAR:
+ - TPM_CAP_TPM_PROPERTIES = 0x6
+ - TPM_PT_LOCKOUT_COUNTER (1st parameter) = PTR_VAR + 14
+
+ There is no expected default values because it would depend on the chip
+ used. We can still save them in order to check they have changed later.
+ """
+
+ force_init(u_boot_console)
+ ram = u_boot_utils.find_ram_base(u_boot_console)
+
+ read_cap = u_boot_console.run_command('tpm2 get_capability 0x6 0x20e 0x200 1') #0x%x 1' % ram)
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+ assert 'Property 0x0000020e: 0x00000000' in read_cap
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_dam_parameters(u_boot_console):
+ """Execute a TPM2_DictionaryAttackParameters command.
+
+ Change Dictionary Attack Mitigation (DAM) parameters. Ask the TPM to change:
+ - Max number of failed authentication before lockout: 3
+ - Time before the failure counter is automatically decremented: 10 sec
+ - Time after a lockout failure before it can be attempted again: 0 sec
+
+ For an unknown reason, the DAM parameters must be changed before changing
+ the authentication, otherwise the lockout will be engaged after the first
+ failed authentication attempt.
+ """
+
+ force_init(u_boot_console)
+ ram = u_boot_utils.find_ram_base(u_boot_console)
+
+ # Set the DAM parameters to known values
+ u_boot_console.run_command('tpm2 dam_parameters 3 10 0')
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+ # Check the values have been saved
+ read_cap = u_boot_console.run_command('tpm2 get_capability 0x6 0x20f 0x%x 3' % ram)
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+ assert 'Property 0x0000020f: 0x00000003' in read_cap
+ assert 'Property 0x00000210: 0x0000000a' in read_cap
+ assert 'Property 0x00000211: 0x00000000' in read_cap
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_pcr_read(u_boot_console):
+ """Execute a TPM2_PCR_Read command.
+
+ Perform a PCR read of the 0th PCR. Must be zero.
+ """
+
+ force_init(u_boot_console)
+ ram = u_boot_utils.find_ram_base(u_boot_console)
+
+ read_pcr = u_boot_console.run_command('tpm2 pcr_read 0 0x%x' % ram)
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+ # Save the number of PCR updates
+ str = re.findall(r'\d+ known updates', read_pcr)[0]
+ global updates
+ updates = int(re.findall(r'\d+', str)[0])
+
+ # Check the output value
+ assert 'PCR #0 content' in read_pcr
+ assert '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00' in read_pcr
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_pcr_extend(u_boot_console):
+ """Execute a TPM2_PCR_Extend command.
+
+ Perform a PCR extension with a known hash in memory (zeroed since the board
+ must have been rebooted).
+
+ No authentication mechanism is used here, not protecting against packet
+ replay, yet.
+ """
+
+ force_init(u_boot_console)
+ ram = u_boot_utils.find_ram_base(u_boot_console)
+
+ u_boot_console.run_command('tpm2 pcr_extend 0 0x%x' % ram)
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+
+ read_pcr = u_boot_console.run_command('tpm2 pcr_read 0 0x%x' % ram)
+ output = u_boot_console.run_command('echo $?')
+ assert output.endswith('0')
+ assert 'f5 a5 fd 42 d1 6a 20 30 27 98 ef 6e d3 09 97 9b' in read_pcr
+ assert '43 00 3d 23 20 d9 f0 e8 ea 98 31 a9 27 59 fb 4b' in read_pcr
+
+ str = re.findall(r'\d+ known updates', read_pcr)[0]
+ new_updates = int(re.findall(r'\d+', str)[0])
+ assert (updates + 1) == new_updates
+
+@pytest.mark.buildconfigspec('cmd_tpm_v2')
+def test_tpm2_cleanup(u_boot_console):
+ """Ensure the TPM is cleared from password or test related configuration."""
+
+ force_init(u_boot_console, True)
diff --git a/test/py/tests/test_ums.py b/test/py/tests/test_ums.py
new file mode 100644
index 00000000..749b1606
--- /dev/null
+++ b/test/py/tests/test_ums.py
@@ -0,0 +1,236 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Test U-Boot's "ums" command. The test starts UMS in U-Boot, waits for USB
+# device enumeration on the host, reads a small block of data from the UMS
+# block device, optionally mounts a partition and performs filesystem-based
+# read/write tests, and finally aborts the "ums" command in U-Boot.
+
+import os
+import os.path
+import pytest
+import re
+import time
+import u_boot_utils
+
+"""
+Note: This test relies on:
+
+a) boardenv_* to contain configuration values to define which USB ports are
+available for testing. Without this, this test will be automatically skipped.
+For example:
+
+# Leave this list empty if you have no block_devs below with writable
+# partitions defined.
+env__mount_points = (
+ '/mnt/ubtest-mnt-p2371-2180-na',
+)
+
+env__usb_dev_ports = (
+ {
+ 'fixture_id': 'micro_b',
+ 'tgt_usb_ctlr': '0',
+ 'host_ums_dev_node': '/dev/disk/by-path/pci-0000:00:14.0-usb-0:13:1.0-scsi-0:0:0:0',
+ },
+)
+
+env__block_devs = (
+ # eMMC; always present
+ {
+ 'fixture_id': 'emmc',
+ 'type': 'mmc',
+ 'id': '0',
+ # The following two properties are optional.
+ # If present, the partition will be mounted and a file written-to and
+ # read-from it. If missing, only a simple block read test will be
+ # performed.
+ 'writable_fs_partition': 1,
+ 'writable_fs_subdir': 'tmp/',
+ },
+ # SD card; present since I plugged one in
+ {
+ 'fixture_id': 'sd',
+ 'type': 'mmc',
+ 'id': '1'
+ },
+)
+
+b) udev rules to set permissions on devices nodes, so that sudo is not
+required. For example:
+
+ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", KERNELS=="3-13", MODE:="666"
+
+(You may wish to change the group ID instead of setting the permissions wide
+open. All that matters is that the user ID running the test can access the
+device.)
+
+c) /etc/fstab entries to allow the block device to be mounted without requiring
+root permissions. For example:
+
+/dev/disk/by-path/pci-0000:00:14.0-usb-0:13:1.0-scsi-0:0:0:0-part1 /mnt/ubtest-mnt-p2371-2180-na ext4 noauto,user,nosuid,nodev
+
+This entry is only needed if any block_devs above contain a
+writable_fs_partition value.
+"""
+
+@pytest.mark.buildconfigspec('cmd_usb_mass_storage')
+def test_ums(u_boot_console, env__usb_dev_port, env__block_devs):
+ """Test the "ums" command; the host system must be able to enumerate a UMS
+ device when "ums" is running, block and optionally file I/O are tested,
+ and this device must disappear when "ums" is aborted.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ env__usb_dev_port: The single USB device-mode port specification on
+ which to run the test. See the file-level comment above for
+ details of the format.
+ env__block_devs: The list of block devices that the target U-Boot
+ device has attached. See the file-level comment above for details
+ of the format.
+
+ Returns:
+ Nothing.
+ """
+
+ have_writable_fs_partition = 'writable_fs_partition' in env__block_devs[0]
+ if not have_writable_fs_partition:
+ # If 'writable_fs_subdir' is missing, we'll skip all parts of the
+ # testing which mount filesystems.
+ u_boot_console.log.warning(
+ 'boardenv missing "writable_fs_partition"; ' +
+ 'UMS testing will be limited.')
+
+ tgt_usb_ctlr = env__usb_dev_port['tgt_usb_ctlr']
+ host_ums_dev_node = env__usb_dev_port['host_ums_dev_node']
+
+ # We're interested in testing USB device mode on each port, not the cross-
+ # product of that with each device. So, just pick the first entry in the
+ # device list here. We'll test each block device somewhere else.
+ tgt_dev_type = env__block_devs[0]['type']
+ tgt_dev_id = env__block_devs[0]['id']
+ if have_writable_fs_partition:
+ mount_point = u_boot_console.config.env['env__mount_points'][0]
+ mount_subdir = env__block_devs[0]['writable_fs_subdir']
+ part_num = env__block_devs[0]['writable_fs_partition']
+ host_ums_part_node = '%s-part%d' % (host_ums_dev_node, part_num)
+ else:
+ host_ums_part_node = host_ums_dev_node
+
+ test_f = u_boot_utils.PersistentRandomFile(u_boot_console, 'ums.bin',
+ 1024 * 1024);
+ if have_writable_fs_partition:
+ mounted_test_fn = mount_point + '/' + mount_subdir + test_f.fn
+
+ def start_ums():
+ """Start U-Boot's ums shell command.
+
+ This also waits for the host-side USB enumeration process to complete.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ u_boot_console.log.action(
+ 'Starting long-running U-Boot ums shell command')
+ cmd = 'ums %s %s %s' % (tgt_usb_ctlr, tgt_dev_type, tgt_dev_id)
+ u_boot_console.run_command(cmd, wait_for_prompt=False)
+ u_boot_console.wait_for(re.compile('UMS: LUN.*[\r\n]'))
+ fh = u_boot_utils.wait_until_open_succeeds(host_ums_part_node)
+ u_boot_console.log.action('Reading raw data from UMS device')
+ fh.read(4096)
+ fh.close()
+
+ def mount():
+ """Mount the block device that U-Boot exports.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ u_boot_console.log.action('Mounting exported UMS device')
+ cmd = ('/bin/mount', host_ums_part_node)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+
+ def umount(ignore_errors):
+ """Unmount the block device that U-Boot exports.
+
+ Args:
+ ignore_errors: Ignore any errors. This is useful if an error has
+ already been detected, and the code is performing best-effort
+ cleanup. In this case, we do not want to mask the original
+ error by "honoring" any new errors.
+
+ Returns:
+ Nothing.
+ """
+
+ u_boot_console.log.action('Unmounting UMS device')
+ cmd = ('/bin/umount', host_ums_part_node)
+ u_boot_utils.run_and_log(u_boot_console, cmd, ignore_errors)
+
+ def stop_ums(ignore_errors):
+ """Stop U-Boot's ums shell command from executing.
+
+ This also waits for the host-side USB de-enumeration process to
+ complete.
+
+ Args:
+ ignore_errors: Ignore any errors. This is useful if an error has
+ already been detected, and the code is performing best-effort
+ cleanup. In this case, we do not want to mask the original
+ error by "honoring" any new errors.
+
+ Returns:
+ Nothing.
+ """
+
+ u_boot_console.log.action(
+ 'Stopping long-running U-Boot ums shell command')
+ u_boot_console.ctrlc()
+ u_boot_utils.wait_until_file_open_fails(host_ums_part_node,
+ ignore_errors)
+
+ ignore_cleanup_errors = True
+ try:
+ start_ums()
+ if not have_writable_fs_partition:
+ # Skip filesystem-based testing if not configured
+ return
+ try:
+ mount()
+ u_boot_console.log.action('Writing test file via UMS')
+ cmd = ('rm', '-f', mounted_test_fn)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ if os.path.exists(mounted_test_fn):
+ raise Exception('Could not rm target UMS test file')
+ cmd = ('cp', test_f.abs_fn, mounted_test_fn)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ ignore_cleanup_errors = False
+ finally:
+ umount(ignore_errors=ignore_cleanup_errors)
+ finally:
+ stop_ums(ignore_errors=ignore_cleanup_errors)
+
+ ignore_cleanup_errors = True
+ try:
+ start_ums()
+ try:
+ mount()
+ u_boot_console.log.action('Reading test file back via UMS')
+ read_back_hash = u_boot_utils.md5sum_file(mounted_test_fn)
+ cmd = ('rm', '-f', mounted_test_fn)
+ u_boot_utils.run_and_log(u_boot_console, cmd)
+ ignore_cleanup_errors = False
+ finally:
+ umount(ignore_errors=ignore_cleanup_errors)
+ finally:
+ stop_ums(ignore_errors=ignore_cleanup_errors)
+
+ written_hash = test_f.content_hash
+ assert(written_hash == read_back_hash)
diff --git a/test/py/tests/test_unknown_cmd.py b/test/py/tests/test_unknown_cmd.py
new file mode 100644
index 00000000..8fc284a9
--- /dev/null
+++ b/test/py/tests/test_unknown_cmd.py
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+def test_unknown_command(u_boot_console):
+ """Test that executing an unknown command causes U-Boot to print an
+ error."""
+
+ # The "unknown command" error is actively expected here,
+ # so error detection for it is disabled.
+ with u_boot_console.disable_check('unknown_command'):
+ response = u_boot_console.run_command('non_existent_cmd')
+ assert('Unknown command \'non_existent_cmd\' - try \'help\'' in response)
diff --git a/test/py/tests/test_ut.py b/test/py/tests/test_ut.py
new file mode 100644
index 00000000..6c7b8dd2
--- /dev/null
+++ b/test/py/tests/test_ut.py
@@ -0,0 +1,28 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+import os.path
+import pytest
+
+@pytest.mark.buildconfigspec('ut_dm')
+def test_ut_dm_init(u_boot_console):
+ """Initialize data for ut dm tests."""
+
+ fn = u_boot_console.config.source_dir + '/testflash.bin'
+ if not os.path.exists(fn):
+ data = b'this is a test'
+ data += b'\x00' * ((4 * 1024 * 1024) - len(data))
+ with open(fn, 'wb') as fh:
+ fh.write(data)
+
+ fn = u_boot_console.config.source_dir + '/spi.bin'
+ if not os.path.exists(fn):
+ data = b'\x00' * (2 * 1024 * 1024)
+ with open(fn, 'wb') as fh:
+ fh.write(data)
+
+def test_ut(u_boot_console, ut_subtest):
+ """Execute a "ut" subtest."""
+
+ output = u_boot_console.run_command('ut ' + ut_subtest)
+ assert output.endswith('Failures: 0')
diff --git a/test/py/tests/test_vboot.py b/test/py/tests/test_vboot.py
new file mode 100644
index 00000000..9c41ee56
--- /dev/null
+++ b/test/py/tests/test_vboot.py
@@ -0,0 +1,293 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2016, Google Inc.
+#
+# U-Boot Verified Boot Test
+
+"""
+This tests verified boot in the following ways:
+
+For image verification:
+- Create FIT (unsigned) with mkimage
+- Check that verification shows that no keys are verified
+- Sign image
+- Check that verification shows that a key is now verified
+
+For configuration verification:
+- Corrupt signature and check for failure
+- Create FIT (with unsigned configuration) with mkimage
+- Check that image verification works
+- Sign the FIT and mark the key as 'required' for verification
+- Check that image verification works
+- Corrupt the signature
+- Check that image verification no-longer works
+
+Tests run with both SHA1 and SHA256 hashing.
+"""
+
+import pytest
+import sys
+import struct
+import u_boot_utils as util
+
+@pytest.mark.boardspec('sandbox')
+@pytest.mark.buildconfigspec('fit_signature')
+@pytest.mark.requiredtool('dtc')
+@pytest.mark.requiredtool('fdtget')
+@pytest.mark.requiredtool('fdtput')
+@pytest.mark.requiredtool('openssl')
+def test_vboot(u_boot_console):
+ """Test verified boot signing with mkimage and verification with 'bootm'.
+
+ This works using sandbox only as it needs to update the device tree used
+ by U-Boot to hold public keys from the signing process.
+
+ The SHA1 and SHA256 tests are combined into a single test since the
+ key-generation process is quite slow and we want to avoid doing it twice.
+ """
+ def dtc(dts):
+ """Run the device tree compiler to compile a .dts file
+
+ The output file will be the same as the input file but with a .dtb
+ extension.
+
+ Args:
+ dts: Device tree file to compile.
+ """
+ dtb = dts.replace('.dts', '.dtb')
+ util.run_and_log(cons, 'dtc %s %s%s -O dtb '
+ '-o %s%s' % (dtc_args, datadir, dts, tmpdir, dtb))
+
+ def run_bootm(sha_algo, test_type, expect_string, boots):
+ """Run a 'bootm' command U-Boot.
+
+ This always starts a fresh U-Boot instance since the device tree may
+ contain a new public key.
+
+ Args:
+ test_type: A string identifying the test type.
+ expect_string: A string which is expected in the output.
+ sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
+ use.
+ boots: A boolean that is True if Linux should boot and False if
+ we are expected to not boot
+ """
+ cons.restart_uboot()
+ with cons.log.section('Verified boot %s %s' % (sha_algo, test_type)):
+ output = cons.run_command_list(
+ ['host load hostfs - 100 %stest.fit' % tmpdir,
+ 'fdt addr 100',
+ 'bootm 100'])
+ assert(expect_string in ''.join(output))
+ if boots:
+ assert('sandbox: continuing, as we cannot run' in ''.join(output))
+ else:
+ assert('sandbox: continuing, as we cannot run' not in ''.join(output))
+
+ def make_fit(its):
+ """Make a new FIT from the .its source file.
+
+ This runs 'mkimage -f' to create a new FIT.
+
+ Args:
+ its: Filename containing .its source.
+ """
+ util.run_and_log(cons, [mkimage, '-D', dtc_args, '-f',
+ '%s%s' % (datadir, its), fit])
+
+ def sign_fit(sha_algo):
+ """Sign the FIT
+
+ Signs the FIT and writes the signature into it. It also writes the
+ public key into the dtb.
+
+ Args:
+ sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
+ use.
+ """
+ cons.log.action('%s: Sign images' % sha_algo)
+ util.run_and_log(cons, [mkimage, '-F', '-k', tmpdir, '-K', dtb,
+ '-r', fit])
+
+ def sign_fit_norequire(sha_algo):
+ """Sign the FIT
+
+ Signs the FIT and writes the signature into it. It also writes the
+ public key into the dtb.
+
+ Args:
+ sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
+ use.
+ """
+ cons.log.action('%s: Sign images' % sha_algo)
+ util.run_and_log(cons, [mkimage, '-F', '-k', tmpdir, '-K', dtb,
+ fit])
+
+ def replace_fit_totalsize(size):
+ """Replace FIT header's totalsize with something greater.
+
+ The totalsize must be less than or equal to FIT_SIGNATURE_MAX_SIZE.
+ If the size is greater, the signature verification should return false.
+
+ Args:
+ size: The new totalsize of the header
+
+ Returns:
+ prev_size: The previous totalsize read from the header
+ """
+ total_size = 0
+ with open(fit, 'r+b') as handle:
+ handle.seek(4)
+ total_size = handle.read(4)
+ handle.seek(4)
+ handle.write(struct.pack(">I", size))
+ return struct.unpack(">I", total_size)[0]
+
+ def test_with_algo(sha_algo, padding):
+ """Test verified boot with the given hash algorithm.
+
+ This is the main part of the test code. The same procedure is followed
+ for both hashing algorithms.
+
+ Args:
+ sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
+ use.
+ """
+ # Compile our device tree files for kernel and U-Boot. These are
+ # regenerated here since mkimage will modify them (by adding a
+ # public key) below.
+ dtc('sandbox-kernel.dts')
+ dtc('sandbox-u-boot.dts')
+
+ # Build the FIT, but don't sign anything yet
+ cons.log.action('%s: Test FIT with signed images' % sha_algo)
+ make_fit('sign-images-%s%s.its' % (sha_algo , padding))
+ run_bootm(sha_algo, 'unsigned images', 'dev-', True)
+
+ # Sign images with our dev keys
+ sign_fit(sha_algo)
+ run_bootm(sha_algo, 'signed images', 'dev+', True)
+
+ # Create a fresh .dtb without the public keys
+ dtc('sandbox-u-boot.dts')
+
+ cons.log.action('%s: Test FIT with signed configuration' % sha_algo)
+ make_fit('sign-configs-%s%s.its' % (sha_algo , padding))
+ run_bootm(sha_algo, 'unsigned config', '%s+ OK' % sha_algo, True)
+
+ # Sign images with our dev keys
+ sign_fit(sha_algo)
+ run_bootm(sha_algo, 'signed config', 'dev+', True)
+
+ cons.log.action('%s: Check signed config on the host' % sha_algo)
+
+ util.run_and_log(cons, [fit_check_sign, '-f', fit, '-k', tmpdir,
+ '-k', dtb])
+
+ # Replace header bytes
+ bcfg = u_boot_console.config.buildconfig
+ max_size = int(bcfg.get('config_fit_signature_max_size', 0x10000000), 0)
+ existing_size = replace_fit_totalsize(max_size + 1)
+ run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash', False)
+ cons.log.action('%s: Check overflowed FIT header totalsize' % sha_algo)
+
+ # Replace with existing header bytes
+ replace_fit_totalsize(existing_size)
+ run_bootm(sha_algo, 'signed config', 'dev+', True)
+ cons.log.action('%s: Check default FIT header totalsize' % sha_algo)
+
+ # Increment the first byte of the signature, which should cause failure
+ sig = util.run_and_log(cons, 'fdtget -t bx %s %s value' %
+ (fit, sig_node))
+ byte_list = sig.split()
+ byte = int(byte_list[0], 16)
+ byte_list[0] = '%x' % (byte + 1)
+ sig = ' '.join(byte_list)
+ util.run_and_log(cons, 'fdtput -t bx %s %s value %s' %
+ (fit, sig_node, sig))
+
+ run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash', False)
+
+ cons.log.action('%s: Check bad config on the host' % sha_algo)
+ util.run_and_log_expect_exception(cons, [fit_check_sign, '-f', fit,
+ '-k', dtb], 1, 'Failed to verify required signature')
+
+ def test_required_key(sha_algo, padding):
+ """Test verified boot with the given hash algorithm.
+
+ This function test if u-boot reject an image when a required
+ key isn't used to sign a FIT.
+
+ Args:
+ sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
+ use.
+ """
+ # Compile our device tree files for kernel and U-Boot. These are
+ # regenerated here since mkimage will modify them (by adding a
+ # public key) below.
+ dtc('sandbox-kernel.dts')
+ dtc('sandbox-u-boot.dts')
+
+ # Build the FIT with prod key (keys required)
+ # Build the FIT with dev key (keys NOT required)
+ # The dtb contain the key prod and dev and the key prod are set as required.
+ # Then try to boot the FIT with dev key
+ # This FIT should not be accepted by u-boot because the key prod is required
+ cons.log.action('%s: Test FIT with configs images' % sha_algo)
+ make_fit('sign-configs-%s%s-prod.its' % (sha_algo , padding))
+ sign_fit(sha_algo)
+ make_fit('sign-configs-%s%s.its' % (sha_algo , padding))
+ sign_fit(sha_algo)
+
+ run_bootm(sha_algo, 'signed configs', '', False)
+
+ cons = u_boot_console
+ tmpdir = cons.config.result_dir + '/'
+ tmp = tmpdir + 'vboot.tmp'
+ datadir = cons.config.source_dir + '/test/py/tests/vboot/'
+ fit = '%stest.fit' % tmpdir
+ mkimage = cons.config.build_dir + '/tools/mkimage'
+ fit_check_sign = cons.config.build_dir + '/tools/fit_check_sign'
+ dtc_args = '-I dts -O dtb -i %s' % tmpdir
+ dtb = '%ssandbox-u-boot.dtb' % tmpdir
+ sig_node = '/configurations/conf-1/signature'
+
+ # Create an RSA key pair
+ public_exponent = 65537
+ util.run_and_log(cons, 'openssl genpkey -algorithm RSA -out %sdev.key '
+ '-pkeyopt rsa_keygen_bits:2048 '
+ '-pkeyopt rsa_keygen_pubexp:%d' %
+ (tmpdir, public_exponent))
+
+ # Create a certificate containing the public key
+ util.run_and_log(cons, 'openssl req -batch -new -x509 -key %sdev.key -out '
+ '%sdev.crt' % (tmpdir, tmpdir))
+
+ # Create an RSA key pair (prod)
+ public_exponent = 65537
+ util.run_and_log(cons, 'openssl genpkey -algorithm RSA -out %sprod.key '
+ '-pkeyopt rsa_keygen_bits:2048 '
+ '-pkeyopt rsa_keygen_pubexp:%d' %
+ (tmpdir, public_exponent))
+
+ # Create a certificate containing the public key (prod)
+ util.run_and_log(cons, 'openssl req -batch -new -x509 -key %sprod.key -out '
+ '%sprod.crt' % (tmpdir, tmpdir))
+
+ # Create a number kernel image with zeroes
+ with open('%stest-kernel.bin' % tmpdir, 'w') as fd:
+ fd.write(5000 * chr(0))
+
+ try:
+ # We need to use our own device tree file. Remember to restore it
+ # afterwards.
+ old_dtb = cons.config.dtb
+ cons.config.dtb = dtb
+ test_with_algo('sha1','')
+ test_with_algo('sha1','-pss')
+ test_with_algo('sha256','')
+ test_with_algo('sha256','-pss')
+ test_required_key('sha256','-pss')
+ finally:
+ # Go back to the original U-Boot with the correct dtb.
+ cons.config.dtb = old_dtb
+ cons.restart_uboot()
diff --git a/test/py/tests/vboot/sandbox-kernel.dts b/test/py/tests/vboot/sandbox-kernel.dts
new file mode 100644
index 00000000..a1e853c9
--- /dev/null
+++ b/test/py/tests/vboot/sandbox-kernel.dts
@@ -0,0 +1,7 @@
+/dts-v1/;
+
+/ {
+ model = "Sandbox Verified Boot Test";
+ compatible = "sandbox";
+
+};
diff --git a/test/py/tests/vboot/sandbox-u-boot.dts b/test/py/tests/vboot/sandbox-u-boot.dts
new file mode 100644
index 00000000..63f8f401
--- /dev/null
+++ b/test/py/tests/vboot/sandbox-u-boot.dts
@@ -0,0 +1,10 @@
+/dts-v1/;
+
+/ {
+ model = "Sandbox Verified Boot Test";
+ compatible = "sandbox";
+
+ reset@0 {
+ compatible = "sandbox,reset";
+ };
+};
diff --git a/test/py/tests/vboot/sign-configs-sha1-pss.its b/test/py/tests/vboot/sign-configs-sha1-pss.its
new file mode 100644
index 00000000..72a5637e
--- /dev/null
+++ b/test/py/tests/vboot/sign-configs-sha1-pss.its
@@ -0,0 +1,46 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ hash-1 {
+ algo = "sha1";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ hash-1 {
+ algo = "sha1";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ signature {
+ algo = "sha1,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ sign-images = "fdt", "kernel";
+ };
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-configs-sha1.its b/test/py/tests/vboot/sign-configs-sha1.its
new file mode 100644
index 00000000..d8bc1fa0
--- /dev/null
+++ b/test/py/tests/vboot/sign-configs-sha1.its
@@ -0,0 +1,45 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ hash-1 {
+ algo = "sha1";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ hash-1 {
+ algo = "sha1";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ signature {
+ algo = "sha1,rsa2048";
+ key-name-hint = "dev";
+ sign-images = "fdt", "kernel";
+ };
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-configs-sha256-pss-prod.its b/test/py/tests/vboot/sign-configs-sha256-pss-prod.its
new file mode 100644
index 00000000..aac732e3
--- /dev/null
+++ b/test/py/tests/vboot/sign-configs-sha256-pss-prod.its
@@ -0,0 +1,46 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ signature {
+ algo = "sha256,rsa2048";
+ padding = "pss";
+ key-name-hint = "prod";
+ sign-images = "fdt", "kernel";
+ };
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-configs-sha256-pss.its b/test/py/tests/vboot/sign-configs-sha256-pss.its
new file mode 100644
index 00000000..7bdcc7e2
--- /dev/null
+++ b/test/py/tests/vboot/sign-configs-sha256-pss.its
@@ -0,0 +1,46 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ signature {
+ algo = "sha256,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ sign-images = "fdt", "kernel";
+ };
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-configs-sha256.its b/test/py/tests/vboot/sign-configs-sha256.its
new file mode 100644
index 00000000..f5591aad
--- /dev/null
+++ b/test/py/tests/vboot/sign-configs-sha256.its
@@ -0,0 +1,45 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ hash-1 {
+ algo = "sha256";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ signature {
+ algo = "sha256,rsa2048";
+ key-name-hint = "dev";
+ sign-images = "fdt", "kernel";
+ };
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-images-sha1-pss.its b/test/py/tests/vboot/sign-images-sha1-pss.its
new file mode 100644
index 00000000..ded7ae4f
--- /dev/null
+++ b/test/py/tests/vboot/sign-images-sha1-pss.its
@@ -0,0 +1,44 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ signature {
+ algo = "sha1,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ signature {
+ algo = "sha1,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-images-sha1.its b/test/py/tests/vboot/sign-images-sha1.its
new file mode 100644
index 00000000..18c759e9
--- /dev/null
+++ b/test/py/tests/vboot/sign-images-sha1.its
@@ -0,0 +1,42 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ signature {
+ algo = "sha1,rsa2048";
+ key-name-hint = "dev";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ signature {
+ algo = "sha1,rsa2048";
+ key-name-hint = "dev";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-images-sha256-pss.its b/test/py/tests/vboot/sign-images-sha256-pss.its
new file mode 100644
index 00000000..34850cc6
--- /dev/null
+++ b/test/py/tests/vboot/sign-images-sha256-pss.its
@@ -0,0 +1,44 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ signature {
+ algo = "sha256,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ signature {
+ algo = "sha256,rsa2048";
+ padding = "pss";
+ key-name-hint = "dev";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ };
+ };
+};
diff --git a/test/py/tests/vboot/sign-images-sha256.its b/test/py/tests/vboot/sign-images-sha256.its
new file mode 100644
index 00000000..bb0f8ee8
--- /dev/null
+++ b/test/py/tests/vboot/sign-images-sha256.its
@@ -0,0 +1,42 @@
+/dts-v1/;
+
+/ {
+ description = "Chrome OS kernel image with one or more FDT blobs";
+ #address-cells = <1>;
+
+ images {
+ kernel {
+ data = /incbin/("test-kernel.bin");
+ type = "kernel_noload";
+ arch = "sandbox";
+ os = "linux";
+ compression = "none";
+ load = <0x4>;
+ entry = <0x8>;
+ kernel-version = <1>;
+ signature {
+ algo = "sha256,rsa2048";
+ key-name-hint = "dev";
+ };
+ };
+ fdt-1 {
+ description = "snow";
+ data = /incbin/("sandbox-kernel.dtb");
+ type = "flat_dt";
+ arch = "sandbox";
+ compression = "none";
+ fdt-version = <1>;
+ signature {
+ algo = "sha256,rsa2048";
+ key-name-hint = "dev";
+ };
+ };
+ };
+ configurations {
+ default = "conf-1";
+ conf-1 {
+ kernel = "kernel";
+ fdt = "fdt-1";
+ };
+ };
+};
diff --git a/test/py/u_boot_console_base.py b/test/py/u_boot_console_base.py
new file mode 100644
index 00000000..326b2ac5
--- /dev/null
+++ b/test/py/u_boot_console_base.py
@@ -0,0 +1,468 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Common logic to interact with U-Boot via the console. This class provides
+# the interface that tests use to execute U-Boot shell commands and wait for
+# their results. Sub-classes exist to perform board-type-specific setup
+# operations, such as spawning a sub-process for Sandbox, or attaching to the
+# serial console of real hardware.
+
+import multiplexed_log
+import os
+import pytest
+import re
+import sys
+import u_boot_spawn
+
+# Regexes for text we expect U-Boot to send to the console.
+pattern_u_boot_spl_signon = re.compile('(U-Boot SPL \\d{4}\\.\\d{2}[^\r\n]*\\))')
+pattern_u_boot_main_signon = re.compile('(U-Boot \\d{4}\\.\\d{2}[^\r\n]*\\))')
+pattern_stop_autoboot_prompt = re.compile('Hit any key to stop autoboot: ')
+pattern_unknown_command = re.compile('Unknown command \'.*\' - try \'help\'')
+pattern_error_notification = re.compile('## Error: ')
+pattern_error_please_reset = re.compile('### ERROR ### Please RESET the board ###')
+
+PAT_ID = 0
+PAT_RE = 1
+
+bad_pattern_defs = (
+ ('spl_signon', pattern_u_boot_spl_signon),
+ ('main_signon', pattern_u_boot_main_signon),
+ ('stop_autoboot_prompt', pattern_stop_autoboot_prompt),
+ ('unknown_command', pattern_unknown_command),
+ ('error_notification', pattern_error_notification),
+ ('error_please_reset', pattern_error_please_reset),
+)
+
+class ConsoleDisableCheck(object):
+ """Context manager (for Python's with statement) that temporarily disables
+ the specified console output error check. This is useful when deliberately
+ executing a command that is known to trigger one of the error checks, in
+ order to test that the error condition is actually raised. This class is
+ used internally by ConsoleBase::disable_check(); it is not intended for
+ direct usage."""
+
+ def __init__(self, console, check_type):
+ self.console = console
+ self.check_type = check_type
+
+ def __enter__(self):
+ self.console.disable_check_count[self.check_type] += 1
+ self.console.eval_bad_patterns()
+
+ def __exit__(self, extype, value, traceback):
+ self.console.disable_check_count[self.check_type] -= 1
+ self.console.eval_bad_patterns()
+
+class ConsoleSetupTimeout(object):
+ """Context manager (for Python's with statement) that temporarily sets up
+ timeout for specific command. This is useful when execution time is greater
+ then default 30s."""
+
+ def __init__(self, console, timeout):
+ self.p = console.p
+ self.orig_timeout = self.p.timeout
+ self.p.timeout = timeout
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, extype, value, traceback):
+ self.p.timeout = self.orig_timeout
+
+class ConsoleBase(object):
+ """The interface through which test functions interact with the U-Boot
+ console. This primarily involves executing shell commands, capturing their
+ results, and checking for common error conditions. Some common utilities
+ are also provided too."""
+
+ def __init__(self, log, config, max_fifo_fill):
+ """Initialize a U-Boot console connection.
+
+ Can only usefully be called by sub-classes.
+
+ Args:
+ log: A mulptiplex_log.Logfile object, to which the U-Boot output
+ will be logged.
+ config: A configuration data structure, as built by conftest.py.
+ max_fifo_fill: The maximum number of characters to send to U-Boot
+ command-line before waiting for U-Boot to echo the characters
+ back. For UART-based HW without HW flow control, this value
+ should be set less than the UART RX FIFO size to avoid
+ overflow, assuming that U-Boot can't keep up with full-rate
+ traffic at the baud rate.
+
+ Returns:
+ Nothing.
+ """
+
+ self.log = log
+ self.config = config
+ self.max_fifo_fill = max_fifo_fill
+
+ self.logstream = self.log.get_stream('console', sys.stdout)
+
+ # Array slice removes leading/trailing quotes
+ self.prompt = self.config.buildconfig['config_sys_prompt'][1:-1]
+ self.prompt_compiled = re.compile('^' + re.escape(self.prompt), re.MULTILINE)
+ self.p = None
+ self.disable_check_count = {pat[PAT_ID]: 0 for pat in bad_pattern_defs}
+ self.eval_bad_patterns()
+
+ self.at_prompt = False
+ self.at_prompt_logevt = None
+
+ def eval_bad_patterns(self):
+ self.bad_patterns = [pat[PAT_RE] for pat in bad_pattern_defs \
+ if self.disable_check_count[pat[PAT_ID]] == 0]
+ self.bad_pattern_ids = [pat[PAT_ID] for pat in bad_pattern_defs \
+ if self.disable_check_count[pat[PAT_ID]] == 0]
+
+ def close(self):
+ """Terminate the connection to the U-Boot console.
+
+ This function is only useful once all interaction with U-Boot is
+ complete. Once this function is called, data cannot be sent to or
+ received from U-Boot.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ if self.p:
+ self.p.close()
+ self.logstream.close()
+
+ def run_command(self, cmd, wait_for_echo=True, send_nl=True,
+ wait_for_prompt=True):
+ """Execute a command via the U-Boot console.
+
+ The command is always sent to U-Boot.
+
+ U-Boot echoes any command back to its output, and this function
+ typically waits for that to occur. The wait can be disabled by setting
+ wait_for_echo=False, which is useful e.g. when sending CTRL-C to
+ interrupt a long-running command such as "ums".
+
+ Command execution is typically triggered by sending a newline
+ character. This can be disabled by setting send_nl=False, which is
+ also useful when sending CTRL-C.
+
+ This function typically waits for the command to finish executing, and
+ returns the console output that it generated. This can be disabled by
+ setting wait_for_prompt=False, which is useful when invoking a long-
+ running command such as "ums".
+
+ Args:
+ cmd: The command to send.
+ wait_for_echo: Boolean indicating whether to wait for U-Boot to
+ echo the command text back to its output.
+ send_nl: Boolean indicating whether to send a newline character
+ after the command string.
+ wait_for_prompt: Boolean indicating whether to wait for the
+ command prompt to be sent by U-Boot. This typically occurs
+ immediately after the command has been executed.
+
+ Returns:
+ If wait_for_prompt == False:
+ Nothing.
+ Else:
+ The output from U-Boot during command execution. In other
+ words, the text U-Boot emitted between the point it echod the
+ command string and emitted the subsequent command prompts.
+ """
+
+ if self.at_prompt and \
+ self.at_prompt_logevt != self.logstream.logfile.cur_evt:
+ self.logstream.write(self.prompt, implicit=True)
+
+ try:
+ self.at_prompt = False
+ if send_nl:
+ cmd += '\n'
+ while cmd:
+ # Limit max outstanding data, so UART FIFOs don't overflow
+ chunk = cmd[:self.max_fifo_fill]
+ cmd = cmd[self.max_fifo_fill:]
+ self.p.send(chunk)
+ if not wait_for_echo:
+ continue
+ chunk = re.escape(chunk)
+ chunk = chunk.replace('\\\n', '[\r\n]')
+ m = self.p.expect([chunk] + self.bad_patterns)
+ if m != 0:
+ self.at_prompt = False
+ raise Exception('Bad pattern found on console: ' +
+ self.bad_pattern_ids[m - 1])
+ if not wait_for_prompt:
+ return
+ m = self.p.expect([self.prompt_compiled] + self.bad_patterns)
+ if m != 0:
+ self.at_prompt = False
+ raise Exception('Bad pattern found on console: ' +
+ self.bad_pattern_ids[m - 1])
+ self.at_prompt = True
+ self.at_prompt_logevt = self.logstream.logfile.cur_evt
+ # Only strip \r\n; space/TAB might be significant if testing
+ # indentation.
+ return self.p.before.strip('\r\n')
+ except Exception as ex:
+ self.log.error(str(ex))
+ self.cleanup_spawn()
+ raise
+ finally:
+ self.log.timestamp()
+
+ def run_command_list(self, cmds):
+ """Run a list of commands.
+
+ This is a helper function to call run_command() with default arguments
+ for each command in a list.
+
+ Args:
+ cmd: List of commands (each a string).
+ Returns:
+ A list of output strings from each command, one element for each
+ command.
+ """
+ output = []
+ for cmd in cmds:
+ output.append(self.run_command(cmd))
+ return output
+
+ def ctrlc(self):
+ """Send a CTRL-C character to U-Boot.
+
+ This is useful in order to stop execution of long-running synchronous
+ commands such as "ums".
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ self.log.action('Sending Ctrl-C')
+ self.run_command(chr(3), wait_for_echo=False, send_nl=False)
+
+ def wait_for(self, text):
+ """Wait for a pattern to be emitted by U-Boot.
+
+ This is useful when a long-running command such as "dfu" is executing,
+ and it periodically emits some text that should show up at a specific
+ location in the log file.
+
+ Args:
+ text: The text to wait for; either a string (containing raw text,
+ not a regular expression) or an re object.
+
+ Returns:
+ Nothing.
+ """
+
+ if type(text) == type(''):
+ text = re.escape(text)
+ m = self.p.expect([text] + self.bad_patterns)
+ if m != 0:
+ raise Exception('Bad pattern found on console: ' +
+ self.bad_pattern_ids[m - 1])
+
+ def drain_console(self):
+ """Read from and log the U-Boot console for a short time.
+
+ U-Boot's console output is only logged when the test code actively
+ waits for U-Boot to emit specific data. There are cases where tests
+ can fail without doing this. For example, if a test asks U-Boot to
+ enable USB device mode, then polls until a host-side device node
+ exists. In such a case, it is useful to log U-Boot's console output
+ in case U-Boot printed clues as to why the host-side even did not
+ occur. This function will do that.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ # If we are already not connected to U-Boot, there's nothing to drain.
+ # This should only happen when a previous call to run_command() or
+ # wait_for() failed (and hence the output has already been logged), or
+ # the system is shutting down.
+ if not self.p:
+ return
+
+ orig_timeout = self.p.timeout
+ try:
+ # Drain the log for a relatively short time.
+ self.p.timeout = 1000
+ # Wait for something U-Boot will likely never send. This will
+ # cause the console output to be read and logged.
+ self.p.expect(['This should never match U-Boot output'])
+ except:
+ # We expect a timeout, since U-Boot won't print what we waited
+ # for. Squash it when it happens.
+ #
+ # Squash any other exception too. This function is only used to
+ # drain (and log) the U-Boot console output after a failed test.
+ # The U-Boot process will be restarted, or target board reset, once
+ # this function returns. So, we don't care about detecting any
+ # additional errors, so they're squashed so that the rest of the
+ # post-test-failure cleanup code can continue operation, and
+ # correctly terminate any log sections, etc.
+ pass
+ finally:
+ self.p.timeout = orig_timeout
+
+ def ensure_spawned(self):
+ """Ensure a connection to a correctly running U-Boot instance.
+
+ This may require spawning a new Sandbox process or resetting target
+ hardware, as defined by the implementation sub-class.
+
+ This is an internal function and should not be called directly.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ if self.p:
+ return
+ try:
+ self.log.start_section('Starting U-Boot')
+ self.at_prompt = False
+ self.p = self.get_spawn()
+ # Real targets can take a long time to scroll large amounts of
+ # text if LCD is enabled. This value may need tweaking in the
+ # future, possibly per-test to be optimal. This works for 'help'
+ # on board 'seaboard'.
+ if not self.config.gdbserver:
+ self.p.timeout = 30000
+ self.p.logfile_read = self.logstream
+ bcfg = self.config.buildconfig
+ config_spl = bcfg.get('config_spl', 'n') == 'y'
+ config_spl_serial_support = bcfg.get('config_spl_serial_support',
+ 'n') == 'y'
+ env_spl_skipped = self.config.env.get('env__spl_skipped',
+ False)
+ if config_spl and config_spl_serial_support and not env_spl_skipped:
+ m = self.p.expect([pattern_u_boot_spl_signon] +
+ self.bad_patterns)
+ if m != 0:
+ raise Exception('Bad pattern found on SPL console: ' +
+ self.bad_pattern_ids[m - 1])
+ m = self.p.expect([pattern_u_boot_main_signon] + self.bad_patterns)
+ if m != 0:
+ raise Exception('Bad pattern found on console: ' +
+ self.bad_pattern_ids[m - 1])
+ self.u_boot_version_string = self.p.after
+ while True:
+ m = self.p.expect([self.prompt_compiled,
+ pattern_stop_autoboot_prompt] + self.bad_patterns)
+ if m == 0:
+ break
+ if m == 1:
+ self.p.send(' ')
+ continue
+ raise Exception('Bad pattern found on console: ' +
+ self.bad_pattern_ids[m - 2])
+ self.at_prompt = True
+ self.at_prompt_logevt = self.logstream.logfile.cur_evt
+ except Exception as ex:
+ self.log.error(str(ex))
+ self.cleanup_spawn()
+ raise
+ finally:
+ self.log.timestamp()
+ self.log.end_section('Starting U-Boot')
+
+ def cleanup_spawn(self):
+ """Shut down all interaction with the U-Boot instance.
+
+ This is used when an error is detected prior to re-establishing a
+ connection with a fresh U-Boot instance.
+
+ This is an internal function and should not be called directly.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ try:
+ if self.p:
+ self.p.close()
+ except:
+ pass
+ self.p = None
+
+ def restart_uboot(self):
+ """Shut down and restart U-Boot."""
+ self.cleanup_spawn()
+ self.ensure_spawned()
+
+ def get_spawn_output(self):
+ """Return the start-up output from U-Boot
+
+ Returns:
+ The output produced by ensure_spawed(), as a string.
+ """
+ if self.p:
+ return self.p.get_expect_output()
+ return None
+
+ def validate_version_string_in_text(self, text):
+ """Assert that a command's output includes the U-Boot signon message.
+
+ This is primarily useful for validating the "version" command without
+ duplicating the signon text regex in a test function.
+
+ Args:
+ text: The command output text to check.
+
+ Returns:
+ Nothing. An exception is raised if the validation fails.
+ """
+
+ assert(self.u_boot_version_string in text)
+
+ def disable_check(self, check_type):
+ """Temporarily disable an error check of U-Boot's output.
+
+ Create a new context manager (for use with the "with" statement) which
+ temporarily disables a particular console output error check.
+
+ Args:
+ check_type: The type of error-check to disable. Valid values may
+ be found in self.disable_check_count above.
+
+ Returns:
+ A context manager object.
+ """
+
+ return ConsoleDisableCheck(self, check_type)
+
+ def temporary_timeout(self, timeout):
+ """Temporarily set up different timeout for commands.
+
+ Create a new context manager (for use with the "with" statement) which
+ temporarily change timeout.
+
+ Args:
+ timeout: Time in milliseconds.
+
+ Returns:
+ A context manager object.
+ """
+
+ return ConsoleSetupTimeout(self, timeout)
diff --git a/test/py/u_boot_console_exec_attach.py b/test/py/u_boot_console_exec_attach.py
new file mode 100644
index 00000000..27834b55
--- /dev/null
+++ b/test/py/u_boot_console_exec_attach.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Logic to interact with U-Boot running on real hardware, typically via a
+# physical serial port.
+
+import sys
+from u_boot_spawn import Spawn
+from u_boot_console_base import ConsoleBase
+
+class ConsoleExecAttach(ConsoleBase):
+ """Represents a physical connection to a U-Boot console, typically via a
+ serial port. This implementation executes a sub-process to attach to the
+ console, expecting that the stdin/out of the sub-process will be forwarded
+ to/from the physical hardware. This approach isolates the test infra-
+ structure from the user-/installation-specific details of how to
+ communicate with, and the identity of, serial ports etc."""
+
+ def __init__(self, log, config):
+ """Initialize a U-Boot console connection.
+
+ Args:
+ log: A multiplexed_log.Logfile instance.
+ config: A "configuration" object as defined in conftest.py.
+
+ Returns:
+ Nothing.
+ """
+
+ # The max_fifo_fill value might need tweaking per-board/-SoC?
+ # 1 would be safe anywhere, but is very slow (a pexpect issue?).
+ # 16 is a common FIFO size.
+ # HW flow control would mean this could be infinite.
+ super(ConsoleExecAttach, self).__init__(log, config, max_fifo_fill=16)
+
+ with self.log.section('flash'):
+ self.log.action('Flashing U-Boot')
+ cmd = ['u-boot-test-flash', config.board_type, config.board_identity]
+ runner = self.log.get_runner(cmd[0], sys.stdout)
+ runner.run(cmd)
+ runner.close()
+ self.log.status_pass('OK')
+
+ def get_spawn(self):
+ """Connect to a fresh U-Boot instance.
+
+ The target board is reset, so that U-Boot begins running from scratch.
+
+ Args:
+ None.
+
+ Returns:
+ A u_boot_spawn.Spawn object that is attached to U-Boot.
+ """
+
+ args = [self.config.board_type, self.config.board_identity]
+ s = Spawn(['u-boot-test-console'] + args)
+
+ try:
+ self.log.action('Resetting board')
+ cmd = ['u-boot-test-reset'] + args
+ runner = self.log.get_runner(cmd[0], sys.stdout)
+ runner.run(cmd)
+ runner.close()
+ except:
+ s.close()
+ raise
+
+ return s
diff --git a/test/py/u_boot_console_sandbox.py b/test/py/u_boot_console_sandbox.py
new file mode 100644
index 00000000..836f5a9e
--- /dev/null
+++ b/test/py/u_boot_console_sandbox.py
@@ -0,0 +1,108 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015 Stephen Warren
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Logic to interact with the sandbox port of U-Boot, running as a sub-process.
+
+import time
+from u_boot_spawn import Spawn
+from u_boot_console_base import ConsoleBase
+
+class ConsoleSandbox(ConsoleBase):
+ """Represents a connection to a sandbox U-Boot console, executed as a sub-
+ process."""
+
+ def __init__(self, log, config):
+ """Initialize a U-Boot console connection.
+
+ Args:
+ log: A multiplexed_log.Logfile instance.
+ config: A "configuration" object as defined in conftest.py.
+
+ Returns:
+ Nothing.
+ """
+
+ super(ConsoleSandbox, self).__init__(log, config, max_fifo_fill=1024)
+ self.sandbox_flags = []
+
+ def get_spawn(self):
+ """Connect to a fresh U-Boot instance.
+
+ A new sandbox process is created, so that U-Boot begins running from
+ scratch.
+
+ Args:
+ None.
+
+ Returns:
+ A u_boot_spawn.Spawn object that is attached to U-Boot.
+ """
+
+ bcfg = self.config.buildconfig
+ config_spl = bcfg.get('config_spl', 'n') == 'y'
+ fname = '/spl/u-boot-spl' if config_spl else '/u-boot'
+ print(fname)
+ cmd = []
+ if self.config.gdbserver:
+ cmd += ['gdbserver', self.config.gdbserver]
+ cmd += [
+ self.config.build_dir + fname,
+ '-v',
+ '-d',
+ self.config.dtb
+ ]
+ cmd += self.sandbox_flags
+ return Spawn(cmd, cwd=self.config.source_dir)
+
+ def restart_uboot_with_flags(self, flags):
+ """Run U-Boot with the given command-line flags
+
+ Args:
+ flags: List of flags to pass, each a string
+
+ Returns:
+ A u_boot_spawn.Spawn object that is attached to U-Boot.
+ """
+
+ try:
+ self.sandbox_flags = flags
+ return self.restart_uboot()
+ finally:
+ self.sandbox_flags = []
+
+ def kill(self, sig):
+ """Send a specific Unix signal to the sandbox process.
+
+ Args:
+ sig: The Unix signal to send to the process.
+
+ Returns:
+ Nothing.
+ """
+
+ self.log.action('kill %d' % sig)
+ self.p.kill(sig)
+
+ def validate_exited(self):
+ """Determine whether the sandbox process has exited.
+
+ If required, this function waits a reasonable time for the process to
+ exit.
+
+ Args:
+ None.
+
+ Returns:
+ Boolean indicating whether the process has exited.
+ """
+
+ p = self.p
+ self.p = None
+ for i in range(100):
+ ret = not p.isalive()
+ if ret:
+ break
+ time.sleep(0.1)
+ p.close()
+ return ret
diff --git a/test/py/u_boot_spawn.py b/test/py/u_boot_spawn.py
new file mode 100644
index 00000000..6991b78c
--- /dev/null
+++ b/test/py/u_boot_spawn.py
@@ -0,0 +1,209 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
+
+# Logic to spawn a sub-process and interact with its stdio.
+
+import os
+import re
+import pty
+import signal
+import select
+import time
+
+class Timeout(Exception):
+ """An exception sub-class that indicates that a timeout occurred."""
+ pass
+
+class Spawn(object):
+ """Represents the stdio of a freshly created sub-process. Commands may be
+ sent to the process, and responses waited for.
+
+ Members:
+ output: accumulated output from expect()
+ """
+
+ def __init__(self, args, cwd=None):
+ """Spawn (fork/exec) the sub-process.
+
+ Args:
+ args: array of processs arguments. argv[0] is the command to
+ execute.
+ cwd: the directory to run the process in, or None for no change.
+
+ Returns:
+ Nothing.
+ """
+
+ self.waited = False
+ self.buf = ''
+ self.output = ''
+ self.logfile_read = None
+ self.before = ''
+ self.after = ''
+ self.timeout = None
+ # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
+ self.re_vt100 = re.compile(r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]', re.I)
+
+ (self.pid, self.fd) = pty.fork()
+ if self.pid == 0:
+ try:
+ # For some reason, SIGHUP is set to SIG_IGN at this point when
+ # run under "go" (www.go.cd). Perhaps this happens under any
+ # background (non-interactive) system?
+ signal.signal(signal.SIGHUP, signal.SIG_DFL)
+ if cwd:
+ os.chdir(cwd)
+ os.execvp(args[0], args)
+ except:
+ print('CHILD EXECEPTION:')
+ import traceback
+ traceback.print_exc()
+ finally:
+ os._exit(255)
+
+ try:
+ self.poll = select.poll()
+ self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
+ except:
+ self.close()
+ raise
+
+ def kill(self, sig):
+ """Send unix signal "sig" to the child process.
+
+ Args:
+ sig: The signal number to send.
+
+ Returns:
+ Nothing.
+ """
+
+ os.kill(self.pid, sig)
+
+ def isalive(self):
+ """Determine whether the child process is still running.
+
+ Args:
+ None.
+
+ Returns:
+ Boolean indicating whether process is alive.
+ """
+
+ if self.waited:
+ return False
+
+ w = os.waitpid(self.pid, os.WNOHANG)
+ if w[0] == 0:
+ return True
+
+ self.waited = True
+ return False
+
+ def send(self, data):
+ """Send data to the sub-process's stdin.
+
+ Args:
+ data: The data to send to the process.
+
+ Returns:
+ Nothing.
+ """
+
+ os.write(self.fd, data.encode(errors='replace'))
+
+ def expect(self, patterns):
+ """Wait for the sub-process to emit specific data.
+
+ This function waits for the process to emit one pattern from the
+ supplied list of patterns, or for a timeout to occur.
+
+ Args:
+ patterns: A list of strings or regex objects that we expect to
+ see in the sub-process' stdout.
+
+ Returns:
+ The index within the patterns array of the pattern the process
+ emitted.
+
+ Notable exceptions:
+ Timeout, if the process did not emit any of the patterns within
+ the expected time.
+ """
+
+ for pi in range(len(patterns)):
+ if type(patterns[pi]) == type(''):
+ patterns[pi] = re.compile(patterns[pi])
+
+ tstart_s = time.time()
+ try:
+ while True:
+ earliest_m = None
+ earliest_pi = None
+ for pi in range(len(patterns)):
+ pattern = patterns[pi]
+ m = pattern.search(self.buf)
+ if not m:
+ continue
+ if earliest_m and m.start() >= earliest_m.start():
+ continue
+ earliest_m = m
+ earliest_pi = pi
+ if earliest_m:
+ pos = earliest_m.start()
+ posafter = earliest_m.end()
+ self.before = self.buf[:pos]
+ self.after = self.buf[pos:posafter]
+ self.output += self.buf[:posafter]
+ self.buf = self.buf[posafter:]
+ return earliest_pi
+ tnow_s = time.time()
+ if self.timeout:
+ tdelta_ms = (tnow_s - tstart_s) * 1000
+ poll_maxwait = self.timeout - tdelta_ms
+ if tdelta_ms > self.timeout:
+ raise Timeout()
+ else:
+ poll_maxwait = None
+ events = self.poll.poll(poll_maxwait)
+ if not events:
+ raise Timeout()
+ c = os.read(self.fd, 1024).decode(errors='replace')
+ if not c:
+ raise EOFError()
+ if self.logfile_read:
+ self.logfile_read.write(c)
+ self.buf += c
+ # count=0 is supposed to be the default, which indicates
+ # unlimited substitutions, but in practice the version of
+ # Python in Ubuntu 14.04 appears to default to count=2!
+ self.buf = self.re_vt100.sub('', self.buf, count=1000000)
+ finally:
+ if self.logfile_read:
+ self.logfile_read.flush()
+
+ def close(self):
+ """Close the stdio connection to the sub-process.
+
+ This also waits a reasonable time for the sub-process to stop running.
+
+ Args:
+ None.
+
+ Returns:
+ Nothing.
+ """
+
+ os.close(self.fd)
+ for i in range(100):
+ if not self.isalive():
+ break
+ time.sleep(0.1)
+
+ def get_expect_output(self):
+ """Return the output read by expect()
+
+ Returns:
+ The output processed by expect(), as a string.
+ """
+ return self.output
diff --git a/test/py/u_boot_utils.py b/test/py/u_boot_utils.py
new file mode 100644
index 00000000..bf2a0fc0
--- /dev/null
+++ b/test/py/u_boot_utils.py
@@ -0,0 +1,340 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
+
+# Utility code shared across multiple tests.
+
+import hashlib
+import inspect
+import os
+import os.path
+import pytest
+import sys
+import time
+import re
+
+def md5sum_data(data):
+ """Calculate the MD5 hash of some data.
+
+ Args:
+ data: The data to hash.
+
+ Returns:
+ The hash of the data, as a binary string.
+ """
+
+ h = hashlib.md5()
+ h.update(data)
+ return h.digest()
+
+def md5sum_file(fn, max_length=None):
+ """Calculate the MD5 hash of the contents of a file.
+
+ Args:
+ fn: The filename of the file to hash.
+ max_length: The number of bytes to hash. If the file has more
+ bytes than this, they will be ignored. If None or omitted, the
+ entire file will be hashed.
+
+ Returns:
+ The hash of the file content, as a binary string.
+ """
+
+ with open(fn, 'rb') as fh:
+ if max_length:
+ params = [max_length]
+ else:
+ params = []
+ data = fh.read(*params)
+ return md5sum_data(data)
+
+class PersistentRandomFile(object):
+ """Generate and store information about a persistent file containing
+ random data."""
+
+ def __init__(self, u_boot_console, fn, size):
+ """Create or process the persistent file.
+
+ If the file does not exist, it is generated.
+
+ If the file does exist, its content is hashed for later comparison.
+
+ These files are always located in the "persistent data directory" of
+ the current test run.
+
+ Args:
+ u_boot_console: A console connection to U-Boot.
+ fn: The filename (without path) to create.
+ size: The desired size of the file in bytes.
+
+ Returns:
+ Nothing.
+ """
+
+ self.fn = fn
+
+ self.abs_fn = u_boot_console.config.persistent_data_dir + '/' + fn
+
+ if os.path.exists(self.abs_fn):
+ u_boot_console.log.action('Persistent data file ' + self.abs_fn +
+ ' already exists')
+ self.content_hash = md5sum_file(self.abs_fn)
+ else:
+ u_boot_console.log.action('Generating ' + self.abs_fn +
+ ' (random, persistent, %d bytes)' % size)
+ data = os.urandom(size)
+ with open(self.abs_fn, 'wb') as fh:
+ fh.write(data)
+ self.content_hash = md5sum_data(data)
+
+def attempt_to_open_file(fn):
+ """Attempt to open a file, without throwing exceptions.
+
+ Any errors (exceptions) that occur during the attempt to open the file
+ are ignored. This is useful in order to test whether a file (in
+ particular, a device node) exists and can be successfully opened, in order
+ to poll for e.g. USB enumeration completion.
+
+ Args:
+ fn: The filename to attempt to open.
+
+ Returns:
+ An open file handle to the file, or None if the file could not be
+ opened.
+ """
+
+ try:
+ return open(fn, 'rb')
+ except:
+ return None
+
+def wait_until_open_succeeds(fn):
+ """Poll until a file can be opened, or a timeout occurs.
+
+ Continually attempt to open a file, and return when this succeeds, or
+ raise an exception after a timeout.
+
+ Args:
+ fn: The filename to attempt to open.
+
+ Returns:
+ An open file handle to the file.
+ """
+
+ for i in range(100):
+ fh = attempt_to_open_file(fn)
+ if fh:
+ return fh
+ time.sleep(0.1)
+ raise Exception('File could not be opened')
+
+def wait_until_file_open_fails(fn, ignore_errors):
+ """Poll until a file cannot be opened, or a timeout occurs.
+
+ Continually attempt to open a file, and return when this fails, or
+ raise an exception after a timeout.
+
+ Args:
+ fn: The filename to attempt to open.
+ ignore_errors: Indicate whether to ignore timeout errors. If True, the
+ function will simply return if a timeout occurs, otherwise an
+ exception will be raised.
+
+ Returns:
+ Nothing.
+ """
+
+ for i in range(100):
+ fh = attempt_to_open_file(fn)
+ if not fh:
+ return
+ fh.close()
+ time.sleep(0.1)
+ if ignore_errors:
+ return
+ raise Exception('File can still be opened')
+
+def run_and_log(u_boot_console, cmd, ignore_errors=False):
+ """Run a command and log its output.
+
+ Args:
+ u_boot_console: A console connection to U-Boot.
+ cmd: The command to run, as an array of argv[], or a string.
+ If a string, note that it is split up so that quoted spaces
+ will not be preserved. E.g. "fred and" becomes ['"fred', 'and"']
+ ignore_errors: Indicate whether to ignore errors. If True, the function
+ will simply return if the command cannot be executed or exits with
+ an error code, otherwise an exception will be raised if such
+ problems occur.
+
+ Returns:
+ The output as a string.
+ """
+ if isinstance(cmd, str):
+ cmd = cmd.split()
+ runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
+ output = runner.run(cmd, ignore_errors=ignore_errors)
+ runner.close()
+ return output
+
+def run_and_log_expect_exception(u_boot_console, cmd, retcode, msg):
+ """Run a command that is expected to fail.
+
+ This runs a command and checks that it fails with the expected return code
+ and exception method. If not, an exception is raised.
+
+ Args:
+ u_boot_console: A console connection to U-Boot.
+ cmd: The command to run, as an array of argv[].
+ retcode: Expected non-zero return code from the command.
+ msg: String that should be contained within the command's output.
+ """
+ try:
+ runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
+ runner.run(cmd)
+ except Exception as e:
+ assert(retcode == runner.exit_status)
+ assert(msg in runner.output)
+ else:
+ raise Exception("Expected an exception with retcode %d message '%s',"
+ "but it was not raised" % (retcode, msg))
+ finally:
+ runner.close()
+
+ram_base = None
+def find_ram_base(u_boot_console):
+ """Find the running U-Boot's RAM location.
+
+ Probe the running U-Boot to determine the address of the first bank
+ of RAM. This is useful for tests that test reading/writing RAM, or
+ load/save files that aren't associated with some standard address
+ typically represented in an environment variable such as
+ ${kernel_addr_r}. The value is cached so that it only needs to be
+ actively read once.
+
+ Args:
+ u_boot_console: A console connection to U-Boot.
+
+ Returns:
+ The address of U-Boot's first RAM bank, as an integer.
+ """
+
+ global ram_base
+ if u_boot_console.config.buildconfig.get('config_cmd_bdi', 'n') != 'y':
+ pytest.skip('bdinfo command not supported')
+ if ram_base == -1:
+ pytest.skip('Previously failed to find RAM bank start')
+ if ram_base is not None:
+ return ram_base
+
+ with u_boot_console.log.section('find_ram_base'):
+ response = u_boot_console.run_command('bdinfo')
+ for l in response.split('\n'):
+ if '-> start' in l or 'memstart =' in l:
+ ram_base = int(l.split('=')[1].strip(), 16)
+ break
+ if ram_base is None:
+ ram_base = -1
+ raise Exception('Failed to find RAM bank start in `bdinfo`')
+
+ # We don't want ram_base to be zero as some functions test if the given
+ # address is NULL (0). Let's add 2MiB then (size of an ARM LPAE/v8 section).
+
+ if ram_base == 0:
+ ram_base += 1024 * 1024 * 2
+
+ return ram_base
+
+class PersistentFileHelperCtxMgr(object):
+ """A context manager for Python's "with" statement, which ensures that any
+ generated file is deleted (and hence regenerated) if its mtime is older
+ than the mtime of the Python module which generated it, and gets an mtime
+ newer than the mtime of the Python module which generated after it is
+ generated. Objects of this type should be created by factory function
+ persistent_file_helper rather than directly."""
+
+ def __init__(self, log, filename):
+ """Initialize a new object.
+
+ Args:
+ log: The Logfile object to log to.
+ filename: The filename of the generated file.
+
+ Returns:
+ Nothing.
+ """
+
+ self.log = log
+ self.filename = filename
+
+ def __enter__(self):
+ frame = inspect.stack()[1]
+ module = inspect.getmodule(frame[0])
+ self.module_filename = module.__file__
+ self.module_timestamp = os.path.getmtime(self.module_filename)
+
+ if os.path.exists(self.filename):
+ filename_timestamp = os.path.getmtime(self.filename)
+ if filename_timestamp < self.module_timestamp:
+ self.log.action('Removing stale generated file ' +
+ self.filename)
+ os.unlink(self.filename)
+
+ def __exit__(self, extype, value, traceback):
+ if extype:
+ try:
+ os.path.unlink(self.filename)
+ except:
+ pass
+ return
+ logged = False
+ for i in range(20):
+ filename_timestamp = os.path.getmtime(self.filename)
+ if filename_timestamp > self.module_timestamp:
+ break
+ if not logged:
+ self.log.action(
+ 'Waiting for generated file timestamp to increase')
+ logged = True
+ os.utime(self.filename)
+ time.sleep(0.1)
+
+def persistent_file_helper(u_boot_log, filename):
+ """Manage the timestamps and regeneration of a persistent generated
+ file. This function creates a context manager for Python's "with"
+ statement
+
+ Usage:
+ with persistent_file_helper(u_boot_console.log, filename):
+ code to generate the file, if it's missing.
+
+ Args:
+ u_boot_log: u_boot_console.log.
+ filename: The filename of the generated file.
+
+ Returns:
+ A context manager object.
+ """
+
+ return PersistentFileHelperCtxMgr(u_boot_log, filename)
+
+def crc32(u_boot_console, address, count):
+ """Helper function used to compute the CRC32 value of a section of RAM.
+
+ Args:
+ u_boot_console: A U-Boot console connection.
+ address: Address where data starts.
+ count: Amount of data to use for calculation.
+
+ Returns:
+ CRC32 value
+ """
+
+ bcfg = u_boot_console.config.buildconfig
+ has_cmd_crc32 = bcfg.get('config_cmd_crc32', 'n') == 'y'
+ assert has_cmd_crc32, 'Cannot compute crc32 without CONFIG_CMD_CRC32.'
+ output = u_boot_console.run_command('crc32 %08x %x' % (address, count))
+
+ m = re.search('==> ([0-9a-fA-F]{8})$', output)
+ assert m, 'CRC32 operation failed.'
+
+ return m.group(1)
diff --git a/test/run b/test/run
new file mode 100755
index 00000000..d635622c
--- /dev/null
+++ b/test/run
@@ -0,0 +1,64 @@
+#!/bin/bash
+
+# Script to run all U-Boot tests that use sandbox.
+# $1: tests to run (empty for all, 'quick' for quick ones only)
+
+# Runs a test and checks the exit code to decide if it passed
+# $1: Test name
+# $2 onwards: command line to run
+run_test() {
+ echo -n "$1: "
+ shift
+ "$@"
+ [ $? -ne 0 ] && failures=$((failures+1))
+}
+
+# SKip slow tests if requested
+[ "$1" == "quick" ] && mark_expr="not slow"
+
+failures=0
+
+# Run all tests that the standard sandbox build can support
+run_test "sandbox" ./test/py/test.py --bd sandbox --build -m "${mark_expr}"
+
+# Run tests which require sandbox_spl
+run_test "sandbox_spl" ./test/py/test.py --bd sandbox_spl --build \
+ -k 'test_ofplatdata or test_handoff'
+
+# Run tests for the flat-device-tree version of sandbox. This is a special
+# build which does not enable CONFIG_OF_LIVE for the live device tree, so we can
+# check that functionality is the same. The standard sandbox build (above) uses
+# CONFIG_OF_LIVE.
+run_test "sandbox_flattree" ./test/py/test.py --bd sandbox_flattree --build \
+ -k test_ut
+
+# Set up a path to dtc (device-tree compiler) and libfdt.py, a library it
+# provides and which is built by the sandbox_spl config. Also set up the path
+# to tools build by the build.
+DTC_DIR=build-sandbox_spl/scripts/dtc
+export PYTHONPATH=${DTC_DIR}/pylibfdt
+export DTC=${DTC_DIR}/dtc
+TOOLS_DIR=build-sandbox_spl/tools
+
+run_test "binman" ./tools/binman/binman --toolpath ${TOOLS_DIR} test
+run_test "patman" ./tools/patman/patman --test
+
+[ "$1" == "quick" ] && skip=--skip-net-tests
+run_test "buildman" ./tools/buildman/buildman -t ${skip}
+run_test "fdt" ./tools/dtoc/test_fdt -t
+run_test "dtoc" ./tools/dtoc/dtoc -t
+
+# This needs you to set up Python test coverage tools.
+# To enable Python test coverage on Debian-type distributions (e.g. Ubuntu):
+# $ sudo apt-get install python-pytest python-coverage
+export PATH=$PATH:${TOOLS_DIR}
+run_test "binman code coverage" ./tools/binman/binman test -T
+run_test "dtoc code coverage" ./tools/dtoc/dtoc -T
+run_test "fdt code coverage" ./tools/dtoc/test_fdt -T
+
+if [ $failures == 0 ]; then
+ echo "Tests passed!"
+else
+ echo "Tests FAILED"
+ exit 1
+fi
diff --git a/test/stdint/int-types.c b/test/stdint/int-types.c
new file mode 100644
index 00000000..f6d09e86
--- /dev/null
+++ b/test/stdint/int-types.c
@@ -0,0 +1,12 @@
+#include <common.h>
+
+int test_types(void)
+{
+ uintptr_t uintptr = 0;
+ uint64_t uint64 = 0;
+ u64 u64_val = 0;
+
+ printf("uintptr = %lu\n", uintptr);
+ printf("uint64 = %llu\n", uint64);
+ printf("u64 = %llu\n", u64_val);
+}
diff --git a/test/stdint/test-includes.sh b/test/stdint/test-includes.sh
new file mode 100755
index 00000000..1db8515e
--- /dev/null
+++ b/test/stdint/test-includes.sh
@@ -0,0 +1,56 @@
+#!/bin/bash
+
+# Test script to check uintptr_t and 64-bit types for warnings
+#
+# It builds a few boards with different toolchains. If there are no warnings
+# then all is well.
+#
+# Usage:
+#
+# Make sure that your toolchains are correct at the bottom of this file
+#
+# Then:
+# ./test/stdint/test-includes.sh
+
+out=/tmp/test-includes.tmp
+
+try_test() {
+ local board=$1
+ local arch=$2
+ local soc=$3
+ local gcc=$4
+ local flags="$5"
+
+ echo $@
+ if ! which ${gcc} >/dev/null 2>&1; then
+ echo "Not found: ${gcc}"
+ return
+ fi
+
+ rm -rf ${out}
+ mkdir -p ${out}
+ touch ${out}/config.h
+ mkdir -p ${out}/generated
+ touch ${out}/generated/generic-asm-offsets.h
+ mkdir -p ${out}/include/asm
+ ln -s $(pwd)/arch/${arch}/include/asm/arch-${soc} \
+ ${out}/include/asm/arch
+
+ cmd="${gcc} -c -D__KERNEL__ ${flags} \
+ -fno-builtin -ffreestanding \
+ -Iarch/${arch}/include \
+ -Iinclude \
+ -I${out} -I${out}/include \
+ -include configs/${board}.h test/stdint/int-types.c \
+ -o /dev/null"
+ $cmd
+}
+
+try_both() {
+ try_test $@
+}
+
+# board arch soc path-to-gcc
+try_both sandbox sandbox - gcc
+try_both coreboot x86 - x86_64-linux-gnu-gcc
+try_both seaboard arm tegra20 /opt/linaro/gcc-linaro-arm-linux-gnueabihf-4.8-2013.08_linux/bin/arm-linux-gnueabihf-gcc
diff --git a/test/time_ut.c b/test/time_ut.c
new file mode 100644
index 00000000..40a19a50
--- /dev/null
+++ b/test/time_ut.c
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2015 Google, Inc
+ * Written by Simon Glass <sjg@chromium.org>
+ */
+
+#include <common.h>
+#include <command.h>
+#include <errno.h>
+#include <time.h>
+
+static int test_get_timer(void)
+{
+ ulong base, start, next, diff;
+ int iter;
+
+ base = get_timer(0);
+ start = get_timer(0);
+ for (iter = 0; iter < 10; iter++) {
+ do {
+ next = get_timer(0);
+ } while (start == next);
+
+ if (start + 1 != next) {
+ printf("%s: iter=%d, start=%lu, next=%lu, expected a difference of 1\n",
+ __func__, iter, start, next);
+ return -EINVAL;
+ }
+ start++;
+ }
+
+ /*
+ * Check that get_timer(base) matches our elapsed time, allowing that
+ * an extra millisecond may have passed.
+ */
+ diff = get_timer(base);
+ if (diff != iter && diff != iter + 1) {
+ printf("%s: expected get_timer(base) to match elapsed time: diff=%lu, expected=%d\n",
+ __func__, diff, iter);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int test_timer_get_us(void)
+{
+ ulong prev, next, min = 1000000;
+ long delta;
+ int iter;
+
+ /* Find the minimum delta we can measure, in microseconds */
+ prev = timer_get_us();
+ for (iter = 0; iter < 100; ) {
+ next = timer_get_us();
+ if (next != prev) {
+ delta = next - prev;
+ if (delta < 0) {
+ printf("%s: timer_get_us() went backwards from %lu to %lu\n",
+ __func__, prev, next);
+ return -EINVAL;
+ } else if (delta != 0) {
+ if (delta < min)
+ min = delta;
+ prev = next;
+ iter++;
+ }
+ }
+ }
+
+ if (min != 1) {
+ printf("%s: Minimum microsecond delta should be 1 but is %lu\n",
+ __func__, min);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int test_time_comparison(void)
+{
+ ulong start_us, end_us, delta_us;
+ long error;
+ ulong start;
+
+ start = get_timer(0);
+ start_us = timer_get_us();
+ while (get_timer(start) < 1000)
+ ;
+ end_us = timer_get_us();
+ delta_us = end_us - start_us;
+ error = delta_us - 1000000;
+ printf("%s: Microsecond time for 1 second: %lu, error = %ld\n",
+ __func__, delta_us, error);
+ if (abs(error) > 1000)
+ return -EINVAL;
+
+ return 0;
+}
+
+static int test_udelay(void)
+{
+ long error;
+ ulong start, delta;
+ int iter;
+
+ start = get_timer(0);
+ for (iter = 0; iter < 1000; iter++)
+ udelay(1000);
+ delta = get_timer(start);
+ error = delta - 1000;
+ printf("%s: Delay time for 1000 udelay(1000): %lu ms, error = %ld\n",
+ __func__, delta, error);
+ if (abs(error) > 100)
+ return -EINVAL;
+
+ return 0;
+}
+
+int do_ut_time(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ int ret = 0;
+
+ ret |= test_get_timer();
+ ret |= test_timer_get_us();
+ ret |= test_time_comparison();
+ ret |= test_udelay();
+
+ printf("Test %s\n", ret ? "failed" : "passed");
+
+ return ret ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
+}
diff --git a/test/trace/test-trace.sh b/test/trace/test-trace.sh
new file mode 100755
index 00000000..5130b2bf
--- /dev/null
+++ b/test/trace/test-trace.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2013 The Chromium OS Authors.
+#
+
+# Simple test script for tracing with sandbox
+
+TRACE_OPT="FTRACE=1"
+
+BASE="$(dirname $0)/.."
+. $BASE/common.sh
+
+run_trace() {
+ echo "Run trace"
+ ./${OUTPUT_DIR}/u-boot <<END
+trace stats
+hash sha256 0 10000
+trace pause
+trace stats
+hash sha256 0 10000
+trace stats
+trace resume
+hash sha256 0 10000
+trace pause
+trace stats
+reset
+END
+}
+
+check_results() {
+ echo "Check results"
+
+ # Expect sha256 to run 3 times, so we see the string 6 times
+ if [ $(grep -c sha256 ${tmp}) -ne 6 ]; then
+ fail "sha256 error"
+ fi
+
+ # 4 sets of results (output of 'trace stats')
+ if [ $(grep -c "traced function calls" ${tmp}) -ne 4 ]; then
+ fail "trace output error"
+ fi
+
+ # Check trace counts. We expect to see an increase in the number of
+ # traced function calls between each 'trace stats' command, except
+ # between calls 2 and 3, where tracing is paused.
+ # This code gets the sign of the difference between each number and
+ # its predecessor.
+ counts="$(tr -d ',\r' <${tmp} | awk \
+ '/traced function calls/ { diff = $1 - upto; upto = $1; \
+ printf "%d ", diff < 0 ? -1 : (diff > 0 ? 1 : 0)}')"
+
+ if [ "${counts}" != "1 1 0 1 " ]; then
+ fail "trace collection error: ${counts}"
+ fi
+}
+
+echo "Simple trace test / sanity check using sandbox"
+echo
+tmp="$(tempfile)"
+build_uboot "${TRACE_OPT}"
+run_trace >${tmp}
+check_results ${tmp}
+rm ${tmp}
+echo "Test passed"
diff --git a/test/unicode_ut.c b/test/unicode_ut.c
new file mode 100644
index 00000000..8875cdc6
--- /dev/null
+++ b/test/unicode_ut.c
@@ -0,0 +1,589 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Unit tests for Unicode functions
+ *
+ * Copyright (c) 2018 Heinrich Schuchardt <xypron.glpk@gmx.de>
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <command.h>
+#include <errno.h>
+#include <test/test.h>
+#include <test/suites.h>
+#include <test/ut.h>
+
+/* Linker list entry for a Unicode test */
+#define UNICODE_TEST(_name) UNIT_TEST(_name, 0, unicode_test)
+
+/* Constants c1-c4 and d1-d4 encode the same letters */
+
+/* Six characters translating to one utf-8 byte each. */
+static const u16 c1[] = {0x55, 0x2d, 0x42, 0x6f, 0x6f, 0x74, 0x00};
+/* One character translating to two utf-8 bytes */
+static const u16 c2[] = {0x6b, 0x61, 0x66, 0x62, 0xe1, 0x74, 0x75, 0x72, 0x00};
+/* Three characters translating to three utf-8 bytes each */
+static const u16 c3[] = {0x6f5c, 0x6c34, 0x8266, 0x00};
+/* Three letters translating to four utf-8 bytes each */
+static const u16 c4[] = {0xd801, 0xdc8d, 0xd801, 0xdc96, 0xd801, 0xdc87,
+ 0x0000};
+
+/* Illegal utf-16 strings */
+static const u16 i1[] = {0x69, 0x31, 0xdc87, 0x6c, 0x00};
+static const u16 i2[] = {0x69, 0x32, 0xd801, 0xd801, 0x6c, 0x00};
+static const u16 i3[] = {0x69, 0x33, 0xd801, 0x00};
+
+/* Six characters translating to one utf-16 word each. */
+static const char d1[] = {0x55, 0x2d, 0x42, 0x6f, 0x6f, 0x74, 0x00};
+/* Eight characters translating to one utf-16 word each */
+static const char d2[] = {0x6b, 0x61, 0x66, 0x62, 0xc3, 0xa1, 0x74, 0x75,
+ 0x72, 0x00};
+/* Three characters translating to one utf-16 word each */
+static const char d3[] = {0xe6, 0xbd, 0x9c, 0xe6, 0xb0, 0xb4, 0xe8, 0x89,
+ 0xa6, 0x00};
+/* Three letters translating to two utf-16 word each */
+static const char d4[] = {0xf0, 0x90, 0x92, 0x8d, 0xf0, 0x90, 0x92, 0x96,
+ 0xf0, 0x90, 0x92, 0x87, 0x00};
+
+/* Illegal utf-8 strings */
+static const char j1[] = {0x6a, 0x31, 0xa1, 0x6c, 0x00};
+static const char j2[] = {0x6a, 0x32, 0xc3, 0xc3, 0x6c, 0x00};
+static const char j3[] = {0x6a, 0x33, 0xf0, 0x90, 0xf0, 0x00};
+
+static int unicode_test_u16_strlen(struct unit_test_state *uts)
+{
+ ut_asserteq(6, u16_strlen(c1));
+ ut_asserteq(8, u16_strlen(c2));
+ ut_asserteq(3, u16_strlen(c3));
+ ut_asserteq(6, u16_strlen(c4));
+ return 0;
+}
+UNICODE_TEST(unicode_test_u16_strlen);
+
+static int unicode_test_u16_strdup(struct unit_test_state *uts)
+{
+ u16 *copy = u16_strdup(c4);
+
+ ut_assert(copy != c4);
+ ut_assert(!memcmp(copy, c4, sizeof(c4)));
+ free(copy);
+ return 0;
+}
+UNICODE_TEST(unicode_test_u16_strdup);
+
+static int unicode_test_u16_strcpy(struct unit_test_state *uts)
+{
+ u16 *r;
+ u16 copy[10];
+
+ r = u16_strcpy(copy, c1);
+ ut_assert(r == copy);
+ ut_assert(!memcmp(copy, c1, sizeof(c1)));
+ return 0;
+}
+UNICODE_TEST(unicode_test_u16_strcpy);
+
+/* U-Boot uses UTF-16 strings in the EFI context only. */
+#if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD)
+static int unicode_test_string16(struct unit_test_state *uts)
+{
+ char buf[20];
+
+ /* Test length and precision */
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%8.6ls", c2);
+ ut_asserteq(' ', buf[1]);
+ ut_assert(!strncmp(&buf[2], d2, 7));
+ ut_assert(!buf[9]);
+
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%8.6ls", c4);
+ ut_asserteq(' ', buf[4]);
+ ut_assert(!strncmp(&buf[5], d4, 12));
+ ut_assert(!buf[17]);
+
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%-8.2ls", c4);
+ ut_asserteq(' ', buf[8]);
+ ut_assert(!strncmp(buf, d4, 8));
+ ut_assert(!buf[14]);
+
+ /* Test handling of illegal utf-16 sequences */
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%ls", i1);
+ ut_asserteq_str("i1?l", buf);
+
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%ls", i2);
+ ut_asserteq_str("i2?l", buf);
+
+ memset(buf, 0xff, sizeof(buf));
+ sprintf(buf, "%ls", i3);
+ ut_asserteq_str("i3?", buf);
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_string16);
+#endif
+
+static int unicode_test_utf8_get(struct unit_test_state *uts)
+{
+ const char *s;
+ s32 code;
+ int i;
+
+ /* Check characters less than 0x800 */
+ s = d2;
+ for (i = 0; i < 8; ++i) {
+ code = utf8_get((const char **)&s);
+ /* c2 is the utf-8 encoding of d2 */
+ ut_asserteq(c2[i], code);
+ if (!code)
+ break;
+ }
+ ut_asserteq_ptr(s, d2 + 9)
+
+ /* Check characters less than 0x10000 */
+ s = d3;
+ for (i = 0; i < 4; ++i) {
+ code = utf8_get((const char **)&s);
+ /* c3 is the utf-8 encoding of d3 */
+ ut_asserteq(c3[i], code);
+ if (!code)
+ break;
+ }
+ ut_asserteq_ptr(s, d3 + 9)
+
+ /* Check character greater 0xffff */
+ s = d4;
+ code = utf8_get((const char **)&s);
+ ut_asserteq(0x0001048d, code);
+ ut_asserteq_ptr(s, d4 + 4);
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_get);
+
+static int unicode_test_utf8_put(struct unit_test_state *uts)
+{
+ char buffer[8] = { 0, };
+ char *pos;
+
+ /* Commercial at, translates to one character */
+ pos = buffer;
+ ut_assert(!utf8_put('@', &pos))
+ ut_asserteq(1, pos - buffer);
+ ut_asserteq('@', buffer[0]);
+ ut_assert(!buffer[1]);
+
+ /* Latin letter G with acute, translates to two charactes */
+ pos = buffer;
+ ut_assert(!utf8_put(0x1f4, &pos));
+ ut_asserteq(2, pos - buffer);
+ ut_asserteq_str("\xc7\xb4", buffer);
+
+ /* Tagalog letter i, translates to three characters */
+ pos = buffer;
+ ut_assert(!utf8_put(0x1701, &pos));
+ ut_asserteq(3, pos - buffer);
+ ut_asserteq_str("\xe1\x9c\x81", buffer);
+
+ /* Hamster face, translates to four characters */
+ pos = buffer;
+ ut_assert(!utf8_put(0x1f439, &pos));
+ ut_asserteq(4, pos - buffer);
+ ut_asserteq_str("\xf0\x9f\x90\xb9", buffer);
+
+ /* Illegal code */
+ pos = buffer;
+ ut_asserteq(-1, utf8_put(0xd888, &pos));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_put);
+
+static int unicode_test_utf8_utf16_strlen(struct unit_test_state *uts)
+{
+ ut_asserteq(6, utf8_utf16_strlen(d1));
+ ut_asserteq(8, utf8_utf16_strlen(d2));
+ ut_asserteq(3, utf8_utf16_strlen(d3));
+ ut_asserteq(6, utf8_utf16_strlen(d4));
+
+ /* illegal utf-8 sequences */
+ ut_asserteq(4, utf8_utf16_strlen(j1));
+ ut_asserteq(4, utf8_utf16_strlen(j2));
+ ut_asserteq(3, utf8_utf16_strlen(j3));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_utf16_strlen);
+
+static int unicode_test_utf8_utf16_strnlen(struct unit_test_state *uts)
+{
+ ut_asserteq(3, utf8_utf16_strnlen(d1, 3));
+ ut_asserteq(6, utf8_utf16_strnlen(d1, 13));
+ ut_asserteq(6, utf8_utf16_strnlen(d2, 6));
+ ut_asserteq(2, utf8_utf16_strnlen(d3, 2));
+ ut_asserteq(4, utf8_utf16_strnlen(d4, 2));
+ ut_asserteq(6, utf8_utf16_strnlen(d4, 3));
+
+ /* illegal utf-8 sequences */
+ ut_asserteq(4, utf8_utf16_strnlen(j1, 16));
+ ut_asserteq(4, utf8_utf16_strnlen(j2, 16));
+ ut_asserteq(3, utf8_utf16_strnlen(j3, 16));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_utf16_strnlen);
+
+/**
+ * ut_u16_strcmp() - Compare to u16 strings.
+ *
+ * @a1: first string
+ * @a2: second string
+ * @count: number of u16 to compare
+ * Return: -1 if a1 < a2, 0 if a1 == a2, 1 if a1 > a2
+ */
+static int unicode_test_u16_strcmp(const u16 *a1, const u16 *a2, size_t count)
+{
+ for (; (*a1 || *a2) && count; ++a1, ++a2, --count) {
+ if (*a1 < *a2)
+ return -1;
+ if (*a1 > *a2)
+ return 1;
+ }
+ return 0;
+}
+
+static int unicode_test_utf8_utf16_strcpy(struct unit_test_state *uts)
+{
+ u16 buf[16];
+ u16 *pos;
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, d1);
+ ut_asserteq(6, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, c1, SIZE_MAX));
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, d2);
+ ut_asserteq(8, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, c2, SIZE_MAX));
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, d3);
+ ut_asserteq(3, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, c3, SIZE_MAX));
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, d4);
+ ut_asserteq(6, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, c4, SIZE_MAX));
+
+ /* Illegal utf-8 strings */
+ pos = buf;
+ utf8_utf16_strcpy(&pos, j1);
+ ut_asserteq(4, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, L"j1?l", SIZE_MAX));
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, j2);
+ ut_asserteq(4, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, L"j2?l", SIZE_MAX));
+
+ pos = buf;
+ utf8_utf16_strcpy(&pos, j3);
+ ut_asserteq(3, pos - buf);
+ ut_assert(!unicode_test_u16_strcmp(buf, L"j3?", SIZE_MAX));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_utf16_strcpy);
+
+static int unicode_test_utf8_utf16_strncpy(struct unit_test_state *uts)
+{
+ u16 buf[16];
+ u16 *pos;
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf8_utf16_strncpy(&pos, d1, 4);
+ ut_asserteq(4, pos - buf);
+ ut_assert(!buf[4]);
+ ut_assert(!unicode_test_u16_strcmp(buf, c1, 4));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf8_utf16_strncpy(&pos, d2, 10);
+ ut_asserteq(8, pos - buf);
+ ut_assert(buf[4]);
+ ut_assert(!unicode_test_u16_strcmp(buf, c2, SIZE_MAX));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf8_utf16_strncpy(&pos, d3, 2);
+ ut_asserteq(2, pos - buf);
+ ut_assert(!buf[2]);
+ ut_assert(!unicode_test_u16_strcmp(buf, c3, 2));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf8_utf16_strncpy(&pos, d4, 2);
+ ut_asserteq(4, pos - buf);
+ ut_assert(!buf[4]);
+ ut_assert(!unicode_test_u16_strcmp(buf, c4, 4));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf8_utf16_strncpy(&pos, d4, 10);
+ ut_asserteq(6, pos - buf);
+ ut_assert(buf[5]);
+ ut_assert(!unicode_test_u16_strcmp(buf, c4, SIZE_MAX));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf8_utf16_strncpy);
+
+static int unicode_test_utf16_get(struct unit_test_state *uts)
+{
+ const u16 *s;
+ s32 code;
+ int i;
+
+ /* Check characters less than 0x10000 */
+ s = c2;
+ for (i = 0; i < 9; ++i) {
+ code = utf16_get((const u16 **)&s);
+ ut_asserteq(c2[i], code);
+ if (!code)
+ break;
+ }
+ ut_asserteq_ptr(c2 + 8, s);
+
+ /* Check character greater 0xffff */
+ s = c4;
+ code = utf16_get((const u16 **)&s);
+ ut_asserteq(0x0001048d, code);
+ ut_asserteq_ptr(c4 + 2, s);
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_get);
+
+static int unicode_test_utf16_put(struct unit_test_state *uts)
+{
+ u16 buffer[4] = { 0, };
+ u16 *pos;
+
+ /* Commercial at, translates to one word */
+ pos = buffer;
+ ut_assert(!utf16_put('@', &pos));
+ ut_asserteq(1, pos - buffer);
+ ut_asserteq((u16)'@', buffer[0]);
+ ut_assert(!buffer[1]);
+
+ /* Hamster face, translates to two words */
+ pos = buffer;
+ ut_assert(!utf16_put(0x1f439, &pos));
+ ut_asserteq(2, pos - buffer);
+ ut_asserteq((u16)0xd83d, buffer[0]);
+ ut_asserteq((u16)0xdc39, buffer[1]);
+ ut_assert(!buffer[2]);
+
+ /* Illegal code */
+ pos = buffer;
+ ut_asserteq(-1, utf16_put(0xd888, &pos));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_put);
+
+static int unicode_test_utf16_strnlen(struct unit_test_state *uts)
+{
+ ut_asserteq(3, utf16_strnlen(c1, 3));
+ ut_asserteq(6, utf16_strnlen(c1, 13));
+ ut_asserteq(6, utf16_strnlen(c2, 6));
+ ut_asserteq(2, utf16_strnlen(c3, 2));
+ ut_asserteq(2, utf16_strnlen(c4, 2));
+ ut_asserteq(3, utf16_strnlen(c4, 3));
+
+ /* illegal utf-16 word sequences */
+ ut_asserteq(4, utf16_strnlen(i1, 16));
+ ut_asserteq(4, utf16_strnlen(i2, 16));
+ ut_asserteq(3, utf16_strnlen(i3, 16));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_strnlen);
+
+static int unicode_test_utf16_utf8_strlen(struct unit_test_state *uts)
+{
+ ut_asserteq(6, utf16_utf8_strlen(c1));
+ ut_asserteq(9, utf16_utf8_strlen(c2));
+ ut_asserteq(9, utf16_utf8_strlen(c3));
+ ut_asserteq(12, utf16_utf8_strlen(c4));
+
+ /* illegal utf-16 word sequences */
+ ut_asserteq(4, utf16_utf8_strlen(i1));
+ ut_asserteq(4, utf16_utf8_strlen(i2));
+ ut_asserteq(3, utf16_utf8_strlen(i3));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_utf8_strlen);
+
+static int unicode_test_utf16_utf8_strnlen(struct unit_test_state *uts)
+{
+ ut_asserteq(3, utf16_utf8_strnlen(c1, 3));
+ ut_asserteq(6, utf16_utf8_strnlen(c1, 13));
+ ut_asserteq(7, utf16_utf8_strnlen(c2, 6));
+ ut_asserteq(6, utf16_utf8_strnlen(c3, 2));
+ ut_asserteq(8, utf16_utf8_strnlen(c4, 2));
+ ut_asserteq(12, utf16_utf8_strnlen(c4, 3));
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_utf8_strnlen);
+
+static int unicode_test_utf16_utf8_strcpy(struct unit_test_state *uts)
+{
+ char buf[16];
+ char *pos;
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, c1);
+ ut_asserteq(6, pos - buf);
+ ut_asserteq_str(d1, buf);
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, c2);
+ ut_asserteq(9, pos - buf);
+ ut_asserteq_str(d2, buf);
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, c3);
+ ut_asserteq(9, pos - buf);
+ ut_asserteq_str(d3, buf);
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, c4);
+ ut_asserteq(12, pos - buf);
+ ut_asserteq_str(d4, buf);
+
+ /* Illegal utf-16 strings */
+ pos = buf;
+ utf16_utf8_strcpy(&pos, i1);
+ ut_asserteq(4, pos - buf);
+ ut_asserteq_str("i1?l", buf);
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, i2);
+ ut_asserteq(4, pos - buf);
+ ut_asserteq_str("i2?l", buf);
+
+ pos = buf;
+ utf16_utf8_strcpy(&pos, i3);
+ ut_asserteq(3, pos - buf);
+ ut_asserteq_str("i3?", buf);
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_utf8_strcpy);
+
+static int unicode_test_utf16_utf8_strncpy(struct unit_test_state *uts)
+{
+ char buf[16];
+ char *pos;
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf16_utf8_strncpy(&pos, c1, 4);
+ ut_asserteq(4, pos - buf);
+ ut_assert(!buf[4]);
+ ut_assert(!strncmp(buf, d1, 4));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf16_utf8_strncpy(&pos, c2, 10);
+ ut_asserteq(9, pos - buf);
+ ut_assert(buf[4]);
+ ut_assert(!strncmp(buf, d2, SIZE_MAX));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf16_utf8_strncpy(&pos, c3, 2);
+ ut_asserteq(6, pos - buf);
+ ut_assert(!buf[6]);
+ ut_assert(!strncmp(buf, d3, 6));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf16_utf8_strncpy(&pos, c4, 2);
+ ut_asserteq(8, pos - buf);
+ ut_assert(!buf[8]);
+ ut_assert(!strncmp(buf, d4, 8));
+
+ pos = buf;
+ memset(buf, 0, sizeof(buf));
+ utf16_utf8_strncpy(&pos, c4, 10);
+ ut_asserteq(12, pos - buf);
+ ut_assert(buf[5]);
+ ut_assert(!strncmp(buf, d4, SIZE_MAX));
+
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf16_utf8_strncpy);
+
+static int unicode_test_utf_to_lower(struct unit_test_state *uts)
+{
+ ut_asserteq('@', utf_to_lower('@'));
+ ut_asserteq('a', utf_to_lower('A'));
+ ut_asserteq('z', utf_to_lower('Z'));
+ ut_asserteq('[', utf_to_lower('['));
+ ut_asserteq('m', utf_to_lower('m'));
+ /* Latin letter O with diaresis (umlaut) */
+ ut_asserteq(0x00f6, utf_to_lower(0x00d6));
+#ifdef CONFIG_EFI_UNICODE_CAPITALIZATION
+ /* Cyrillic letter I*/
+ ut_asserteq(0x0438, utf_to_lower(0x0418));
+#endif
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf_to_lower);
+
+static int unicode_test_utf_to_upper(struct unit_test_state *uts)
+{
+ ut_asserteq('`', utf_to_upper('`'));
+ ut_asserteq('A', utf_to_upper('a'));
+ ut_asserteq('Z', utf_to_upper('z'));
+ ut_asserteq('{', utf_to_upper('{'));
+ ut_asserteq('M', utf_to_upper('M'));
+ /* Latin letter O with diaresis (umlaut) */
+ ut_asserteq(0x00d6, utf_to_upper(0x00f6));
+#ifdef CONFIG_EFI_UNICODE_CAPITALIZATION
+ /* Cyrillic letter I */
+ ut_asserteq(0x0418, utf_to_upper(0x0438));
+#endif
+ return 0;
+}
+UNICODE_TEST(unicode_test_utf_to_upper);
+
+static int unicode_test_u16_strncmp(struct unit_test_state *uts)
+{
+ ut_assert(u16_strncmp(L"abc", L"abc", 3) == 0);
+ ut_assert(u16_strncmp(L"abcdef", L"abcghi", 3) == 0);
+ ut_assert(u16_strncmp(L"abcdef", L"abcghi", 6) < 0);
+ ut_assert(u16_strncmp(L"abcghi", L"abcdef", 6) > 0);
+ ut_assert(u16_strcmp(L"abc", L"abc") == 0);
+ ut_assert(u16_strcmp(L"abcdef", L"deghi") < 0);
+ ut_assert(u16_strcmp(L"deghi", L"abcdef") > 0);
+ return 0;
+}
+UNICODE_TEST(unicode_test_u16_strncmp);
+
+int do_ut_unicode(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+{
+ struct unit_test *tests = ll_entry_start(struct unit_test, unicode_test);
+ const int n_ents = ll_entry_count(struct unit_test, unicode_test);
+
+ return cmd_ut_category("Unicode", tests, n_ents, argc, argv);
+}
diff --git a/test/ut.c b/test/ut.c
new file mode 100644
index 00000000..55798041
--- /dev/null
+++ b/test/ut.c
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Simple unit test library
+ *
+ * Copyright (c) 2013 Google, Inc
+ */
+
+#include <common.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+void ut_fail(struct unit_test_state *uts, const char *fname, int line,
+ const char *func, const char *cond)
+{
+ gd->flags &= ~(GD_FLG_SILENT | GD_FLG_RECORD);
+ printf("%s:%d, %s(): %s\n", fname, line, func, cond);
+ uts->fail_count++;
+}
+
+void ut_failf(struct unit_test_state *uts, const char *fname, int line,
+ const char *func, const char *cond, const char *fmt, ...)
+{
+ va_list args;
+
+ gd->flags &= ~(GD_FLG_SILENT | GD_FLG_RECORD);
+ printf("%s:%d, %s(): %s: ", fname, line, func, cond);
+ va_start(args, fmt);
+ vprintf(fmt, args);
+ va_end(args);
+ putc('\n');
+ uts->fail_count++;
+}