Resguardo inicial

This commit is contained in:
lastdragon
2026-09-06 12:53:21 -06:00
parent 662efe3c2a
commit ad2088d178
94853 changed files with 43200404 additions and 0 deletions
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (C) 2022 Red Hat, Inc.
# Author: Vladis Dronov <vdronoff@gmail.com>
obj-m += test_cipher.o
test_cipher-y := test-cipher.o
all:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) clean
@@ -0,0 +1,34 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (C) 2022 Red Hat, Inc.
# Author: Vladis Dronov <vdronoff@gmail.com>
#
# This script runs (via instmod) test-cipher.ko module which invokes
# generic and s390-native ChaCha20 encryprion algorithms with different
# size of data. Check 'dmesg' for results.
#
# The insmod error is expected:
# insmod: ERROR: could not insert module test_cipher.ko: Operation not permitted
lsmod | grep chacha | cut -f1 -d' ' | xargs rmmod
modprobe chacha_generic
modprobe chacha_s390
# run encryption for different data size, including whole block(s) +/- 1
insmod test_cipher.ko size=63
insmod test_cipher.ko size=64
insmod test_cipher.ko size=65
insmod test_cipher.ko size=127
insmod test_cipher.ko size=128
insmod test_cipher.ko size=129
insmod test_cipher.ko size=511
insmod test_cipher.ko size=512
insmod test_cipher.ko size=513
insmod test_cipher.ko size=4096
insmod test_cipher.ko size=65611
insmod test_cipher.ko size=6291456
insmod test_cipher.ko size=62914560
# print test logs
dmesg | tail -170
@@ -0,0 +1,368 @@
/* SPDX-License-Identifier: GPL-2.0
*
* Copyright (C) 2022 Red Hat, Inc.
* Author: Vladis Dronov <vdronoff@gmail.com>
*/
#include <asm/elf.h>
#include <asm/uaccess.h>
#include <asm/smp.h>
#include <crypto/skcipher.h>
#include <crypto/akcipher.h>
#include <crypto/acompress.h>
#include <crypto/rng.h>
#include <crypto/kpp.h>
#include <crypto/internal/simd.h>
#include <crypto/chacha.h>
#include <crypto/aead.h>
#include <crypto/hash.h>
#include <linux/crypto.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/fips.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/scatterlist.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/zlib.h>
#include <linux/once.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/string.h>
static unsigned int data_size __read_mostly = 256;
static unsigned int debug __read_mostly = 0;
/* tie all skcipher structures together */
struct skcipher_def {
struct scatterlist sginp, sgout;
struct crypto_skcipher *tfm;
struct skcipher_request *req;
struct crypto_wait wait;
};
/* Perform cipher operations with the chacha lib */
static int test_lib_chacha(u8 *revert, u8 *cipher, u8 *plain)
{
struct chacha_state chacha_state;
u8 iv[16], key[32];
u64 start, end;
memset(key, 'X', sizeof(key));
memset(iv, 'I', sizeof(iv));
if (debug) {
print_hex_dump(KERN_INFO, "key: ", DUMP_PREFIX_OFFSET,
16, 1, key, 32, 1);
print_hex_dump(KERN_INFO, "iv: ", DUMP_PREFIX_OFFSET,
16, 1, iv, 16, 1);
}
/* Encrypt */
chacha_init(&chacha_state, (u32 *)key, iv);
start = ktime_get_ns();
chacha_crypt_arch(&chacha_state, cipher, plain, data_size, 20);
end = ktime_get_ns();
if (debug)
print_hex_dump(KERN_INFO, "encr:", DUMP_PREFIX_OFFSET,
16, 1, cipher,
(data_size > 64 ? 64 : data_size), 1);
pr_info("lib encryption took: %lld nsec", end - start);
/* Decrypt */
chacha_init(&chacha_state, (u32 *)key, iv);
start = ktime_get_ns();
chacha_crypt_arch(&chacha_state, revert, cipher, data_size, 20);
end = ktime_get_ns();
if (debug)
print_hex_dump(KERN_INFO, "decr:", DUMP_PREFIX_OFFSET,
16, 1, revert,
(data_size > 64 ? 64 : data_size), 1);
pr_info("lib decryption took: %lld nsec", end - start);
return 0;
}
/* Perform cipher operations with skcipher */
static unsigned int test_skcipher_encdec(struct skcipher_def *sk,
int enc)
{
int rc;
if (enc) {
rc = crypto_wait_req(crypto_skcipher_encrypt(sk->req),
&sk->wait);
if (rc)
pr_info("skcipher encrypt returned with result"
"%d\n", rc);
}
else
{
rc = crypto_wait_req(crypto_skcipher_decrypt(sk->req),
&sk->wait);
if (rc)
pr_info("skcipher decrypt returned with result"
"%d\n", rc);
}
return rc;
}
/* Initialize and trigger cipher operations */
static int test_skcipher(char *name, u8 *revert, u8 *cipher, u8 *plain)
{
struct skcipher_def sk;
struct crypto_skcipher *skcipher = NULL;
struct skcipher_request *req = NULL;
u8 iv[16], key[32];
u64 start, end;
int ret = -EFAULT;
skcipher = crypto_alloc_skcipher(name, 0, 0);
if (IS_ERR(skcipher)) {
pr_info("could not allocate skcipher %s handle\n", name);
return PTR_ERR(skcipher);
}
req = skcipher_request_alloc(skcipher, GFP_KERNEL);
if (!req) {
pr_info("could not allocate skcipher request\n");
ret = -ENOMEM;
goto out;
}
skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
crypto_req_done,
&sk.wait);
memset(key, 'X', sizeof(key));
memset(iv, 'I', sizeof(iv));
if (crypto_skcipher_setkey(skcipher, key, 32)) {
pr_info("key could not be set\n");
ret = -EAGAIN;
goto out;
}
if (debug) {
print_hex_dump(KERN_INFO, "key: ", DUMP_PREFIX_OFFSET,
16, 1, key, 32, 1);
print_hex_dump(KERN_INFO, "iv: ", DUMP_PREFIX_OFFSET,
16, 1, iv, 16, 1);
}
sk.tfm = skcipher;
sk.req = req;
/* Encrypt in one pass */
sg_init_one(&sk.sginp, plain, data_size);
sg_init_one(&sk.sgout, cipher, data_size);
skcipher_request_set_crypt(req, &sk.sginp, &sk.sgout,
data_size, iv);
crypto_init_wait(&sk.wait);
/* Encrypt data */
start = ktime_get_ns();
ret = test_skcipher_encdec(&sk, 1);
end = ktime_get_ns();
if (ret)
goto out;
pr_info("%s tfm encryption successful, took %lld nsec\n", name, end - start);
if (debug)
print_hex_dump(KERN_INFO, "encr:", DUMP_PREFIX_OFFSET,
16, 1, cipher,
(data_size > 64 ? 64 : data_size), 1);
/* Prepare for decryption */
memset(iv, 'I', sizeof(iv));
sg_init_one(&sk.sginp, cipher, data_size);
sg_init_one(&sk.sgout, revert, data_size);
skcipher_request_set_crypt(req, &sk.sginp, &sk.sgout,
data_size, iv);
crypto_init_wait(&sk.wait);
/* Decrypt data */
start = ktime_get_ns();
ret = test_skcipher_encdec(&sk, 0);
end = ktime_get_ns();
if (ret)
goto out;
pr_info("%s tfm decryption successful, took %lld nsec\n", name, end - start);
if (debug)
print_hex_dump(KERN_INFO, "decr:", DUMP_PREFIX_OFFSET,
16, 1, revert,
(data_size > 64 ? 64 : data_size), 1);
/* Dump some internal skcipher data */
if (debug)
pr_info("skcipher %s: cryptlen %d blksize %d stride %d "
"ivsize %d alignmask 0x%x\n",
name, sk.req->cryptlen,
crypto_skcipher_blocksize(sk.tfm),
crypto_skcipher_alg(sk.tfm)->walksize,
crypto_skcipher_ivsize(sk.tfm),
crypto_skcipher_alignmask(sk.tfm));
out:
if (skcipher)
crypto_free_skcipher(skcipher);
if (req)
skcipher_request_free(req);
return ret;
}
static int __init chacha_s390_test_init(void)
{
u8 *plain = NULL, *revert = NULL;
u8 *cipher_generic = NULL, *cipher_s390 = NULL;
int ret = -1;
pr_info("s390 ChaCha20 test module: size=%d debug=%d\n",
data_size, debug);
/* Allocate and fill buffers */
plain = vmalloc(data_size);
if (!plain) {
pr_info("could not allocate plain buffer\n");
ret = -2;
goto out;
}
memset(plain, 'a', data_size);
get_random_bytes(plain, (data_size > 256 ? 256 : data_size));
cipher_generic = vzalloc(data_size);
if (!cipher_generic) {
pr_info("could not allocate cipher_generic buffer\n");
ret = -2;
goto out;
}
cipher_s390 = vzalloc(data_size);
if (!cipher_s390) {
pr_info("could not allocate cipher_s390 buffer\n");
ret = -2;
goto out;
}
revert = vzalloc(data_size);
if (!revert) {
pr_info("could not allocate revert buffer\n");
ret = -2;
goto out;
}
if (debug)
print_hex_dump(KERN_INFO, "src: ", DUMP_PREFIX_OFFSET,
16, 1, plain,
(data_size > 64 ? 64 : data_size), 1);
/* Use chacha20 generic */
ret = test_skcipher("chacha20-generic", revert, cipher_generic, plain);
if (ret)
goto out;
if (memcmp(plain, revert, data_size)) {
pr_info("generic en/decryption check FAILED\n");
ret = -2;
goto out;
}
else
pr_info("generic en/decryption check OK\n");
memset(revert, 0, data_size);
/* Use chacha20 s390 */
ret = test_skcipher("chacha20-s390", revert, cipher_s390, plain);
if (ret)
goto out;
if (memcmp(plain, revert, data_size)) {
pr_info("s390 en/decryption check FAILED\n");
ret = -2;
goto out;
}
else
pr_info("s390 en/decryption check OK\n");
if (memcmp(cipher_generic, cipher_s390, data_size)) {
pr_info("s390 vs generic check FAILED\n");
ret = -2;
goto out;
}
else
pr_info("s390 vs generic check OK\n");
memset(cipher_s390, 0, data_size);
memset(revert, 0, data_size);
/* Use chacha20 lib */
test_lib_chacha(revert, cipher_s390, plain);
if (memcmp(plain, revert, data_size)) {
pr_info("lib en/decryption check FAILED\n");
ret = -2;
goto out;
}
else
pr_info("lib en/decryption check OK\n");
if (memcmp(cipher_generic, cipher_s390, data_size)) {
pr_info("lib vs generic check FAILED\n");
ret = -2;
goto out;
}
else
pr_info("lib vs generic check OK\n");
pr_info("--- chacha20 s390 test end ---\n");
out:
if (plain)
vfree(plain);
if (cipher_generic)
vfree(cipher_generic);
if (cipher_s390)
vfree(cipher_s390);
if (revert)
vfree(revert);
return -1;
}
static void __exit chacha_s390_test_exit(void)
{
pr_info("s390 ChaCha20 test module exit\n");
}
module_param_named(size, data_size, uint, 0660);
module_param(debug, int, 0660);
MODULE_PARM_DESC(size, "Size of a plaintext");
MODULE_PARM_DESC(debug, "Debug level (0=off,1=on)");
module_init(chacha_s390_test_init);
module_exit(chacha_s390_test_exit);
MODULE_DESCRIPTION("s390 ChaCha20 self-test");
MODULE_AUTHOR("Vladis Dronov <vdronoff@gmail.com>");
MODULE_LICENSE("GPL v2");
+82
View File
@@ -0,0 +1,82 @@
# SPDX-License-Identifier: GPL-2.0
ldflags-y += --wrap=acpi_table_parse_cedt
ldflags-y += --wrap=is_acpi_device_node
ldflags-y += --wrap=acpi_evaluate_integer
ldflags-y += --wrap=acpi_pci_find_root
ldflags-y += --wrap=nvdimm_bus_register
ldflags-y += --wrap=cxl_await_media_ready
ldflags-y += --wrap=devm_cxl_add_rch_dport
ldflags-y += --wrap=cxl_endpoint_parse_cdat
ldflags-y += --wrap=devm_cxl_endpoint_decoders_setup
ldflags-y += --wrap=hmat_get_extended_linear_cache_size
ldflags-y += --wrap=devm_cxl_add_dport_by_dev
ldflags-y += --wrap=devm_cxl_switch_port_decoders_setup
ldflags-y += --wrap=walk_hmem_resources
ldflags-y += --wrap=region_intersects
ldflags-y += --wrap=region_intersects_soft_reserve
DRIVERS := ../../../drivers
DAX_HMEM_SRC := $(DRIVERS)/dax/hmem
CXL_SRC := $(DRIVERS)/cxl
CXL_CORE_SRC := $(DRIVERS)/cxl/core
ccflags-y := -I$(srctree)/drivers/cxl/
ccflags-y += -D__mock=__weak
ccflags-y += -DCXL_TEST_ENABLE=1
ccflags-y += -DTRACE_INCLUDE_PATH=$(CXL_CORE_SRC) -I$(srctree)/drivers/cxl/core/
obj-m += cxl_acpi.o
cxl_acpi-y := $(CXL_SRC)/acpi.o
cxl_acpi-y += mock_acpi.o
cxl_acpi-y += config_check.o
cxl_acpi-y += cxl_acpi_test.o
obj-m += cxl_pmem.o
cxl_pmem-y := $(CXL_SRC)/pmem.o
cxl_pmem-y += $(CXL_SRC)/security.o
cxl_pmem-y += config_check.o
cxl_pmem-y += cxl_pmem_test.o
obj-m += cxl_port.o
cxl_port-y := $(CXL_SRC)/port.o
cxl_port-y += config_check.o
cxl_port-y += cxl_port_test.o
obj-m += cxl_mem.o
cxl_mem-y := $(CXL_SRC)/mem.o
cxl_mem-y += config_check.o
cxl_mem-y += cxl_mem_test.o
obj-m += cxl_core.o
cxl_core-y := $(CXL_CORE_SRC)/port.o
cxl_core-y += $(CXL_CORE_SRC)/pmem.o
cxl_core-y += $(CXL_CORE_SRC)/regs.o
cxl_core-y += $(CXL_CORE_SRC)/memdev.o
cxl_core-y += $(CXL_CORE_SRC)/mbox.o
cxl_core-y += $(CXL_CORE_SRC)/pci.o
cxl_core-y += $(CXL_CORE_SRC)/hdm.o
cxl_core-y += $(CXL_CORE_SRC)/pmu.o
cxl_core-y += $(CXL_CORE_SRC)/cdat.o
cxl_core-$(CONFIG_TRACING) += $(CXL_CORE_SRC)/trace.o
cxl_core-$(CONFIG_CXL_REGION) += $(CXL_CORE_SRC)/region.o $(CXL_CORE_SRC)/region_pmem.o $(CXL_CORE_SRC)/region_dax.o
cxl_core-$(CONFIG_CXL_MCE) += $(CXL_CORE_SRC)/mce.o
cxl_core-$(CONFIG_CXL_FEATURES) += $(CXL_CORE_SRC)/features.o
cxl_core-$(CONFIG_CXL_EDAC_MEM_FEATURES) += $(CXL_CORE_SRC)/edac.o
cxl_core-$(CONFIG_CXL_RAS) += $(CXL_CORE_SRC)/ras.o
cxl_core-$(CONFIG_CXL_RAS) += $(CXL_CORE_SRC)/ras_rch.o
cxl_core-$(CONFIG_CXL_ATL) += $(CXL_CORE_SRC)/atl.o
cxl_core-y += config_check.o
cxl_core-y += cxl_core_test.o
cxl_core-y += cxl_core_exports.o
obj-m += dax_hmem.o
dax_hmem-y := $(DAX_HMEM_SRC)/hmem.o
KBUILD_CFLAGS := $(filter-out -Wmissing-prototypes -Wmissing-declarations, $(KBUILD_CFLAGS))
obj-m += test/
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/bug.h>
void check(void)
{
/*
* These kconfig symbols must be set to "m" for cxl_test to load
* and operate.
*/
BUILD_BUG_ON(!IS_ENABLED(CONFIG_64BIT));
BUILD_BUG_ON(!IS_MODULE(CONFIG_CXL_BUS));
BUILD_BUG_ON(!IS_MODULE(CONFIG_CXL_ACPI));
BUILD_BUG_ON(!IS_MODULE(CONFIG_CXL_PMEM));
BUILD_BUG_ON(!IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST));
BUILD_BUG_ON(!IS_ENABLED(CONFIG_NVDIMM_SECURITY_TEST));
BUILD_BUG_ON(!IS_ENABLED(CONFIG_DEBUG_FS));
BUILD_BUG_ON(!IS_ENABLED(CONFIG_MEMORY_HOTPLUG));
}
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "watermark.h"
cxl_test_watermark(cxl_acpi);
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "cxl.h"
/* Exporting of cxl_core symbols that are only used by cxl_test */
EXPORT_SYMBOL_NS_GPL(cxl_num_decoders_committed, "CXL");
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "watermark.h"
cxl_test_watermark(cxl_core);
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "watermark.h"
cxl_test_watermark(cxl_mem);
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "watermark.h"
cxl_test_watermark(cxl_pmem);
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#include "watermark.h"
cxl_test_watermark(cxl_port);
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright(c) 2021 Intel Corporation. All rights reserved. */
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/acpi.h>
#include <cxl.h>
#include "test/mock.h"
struct acpi_device *to_cxl_host_bridge(struct device *host, struct device *dev)
{
int index;
struct acpi_device *adev, *found = NULL;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_bridge(dev)) {
found = ACPI_COMPANION(dev);
goto out;
}
if (dev_is_platform(dev))
goto out;
adev = to_acpi_device(dev);
if (!acpi_pci_find_root(adev->handle))
goto out;
if (strcmp(acpi_device_hid(adev), "ACPI0016") == 0) {
found = adev;
dev_dbg(host, "found host bridge %s\n", dev_name(&adev->dev));
}
out:
put_cxl_mock_ops(index);
return found;
}
+14
View File
@@ -0,0 +1,14 @@
# SPDX-License-Identifier: GPL-2.0
ccflags-y := -I$(srctree)/drivers/cxl/ -I$(srctree)/drivers/cxl/core
obj-m += cxl_test.o
obj-m += cxl_mock.o
obj-m += cxl_mock_mem.o
obj-m += cxl_translate.o
cxl_test-y := cxl.o
cxl_test-y += hmem_test.o
cxl_mock-y := mock.o
cxl_mock_mem-y := mem.o
KBUILD_CFLAGS := $(filter-out -Wmissing-prototypes -Wmissing-declarations, $(KBUILD_CFLAGS))
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,451 @@
// SPDX-License-Identifier: GPL-2.0-only
// Copyright(c) 2025 Intel Corporation. All rights reserved.
/* Preface all log entries with "cxl_translate" */
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <cxlmem.h>
#include <cxl.h>
/* Maximum number of test vectors and entry length */
#define MAX_TABLE_ENTRIES 128
#define MAX_ENTRY_LEN 128
/* Expected number of parameters in each test vector */
#define EXPECTED_PARAMS 7
/* Module parameters for test vectors */
static char *table[MAX_TABLE_ENTRIES];
static int table_num;
/* Interleave Arithmetic */
#define MODULO_MATH 0
#define XOR_MATH 1
/*
* XOR mapping configuration
* The test data sets all use the same set of xormaps. When additional
* data sets arrive for validation, this static setup will need to
* be changed to accept xormaps as additional parameters.
*/
struct cxl_cxims_data *cximsd;
static u64 xormaps[] = {
0x2020900,
0x4041200,
0x1010400,
0x800,
};
static int nr_maps = ARRAY_SIZE(xormaps);
#define HBIW_TO_NR_MAPS_SIZE (CXL_DECODER_MAX_INTERLEAVE + 1)
static const int hbiw_to_nr_maps[HBIW_TO_NR_MAPS_SIZE] = {
[1] = 0, [2] = 1, [3] = 0, [4] = 2, [6] = 1, [8] = 3, [12] = 2, [16] = 4
};
/**
* to_hpa - calculate an HPA offset from a DPA offset and position
*
* dpa_offset: device physical address offset
* pos: devices position in interleave
* r_eiw: region encoded interleave ways
* r_eig: region encoded interleave granularity
* hb_ways: host bridge interleave ways
* math: interleave arithmetic (MODULO_MATH or XOR_MATH)
*
* Returns: host physical address offset
*/
static u64 to_hpa(u64 dpa_offset, int pos, u8 r_eiw, u16 r_eig, u8 hb_ways,
u8 math)
{
u64 hpa_offset;
/* Calculate base HPA offset from DPA and position */
hpa_offset = cxl_calculate_hpa_offset(dpa_offset, pos, r_eiw, r_eig);
if (hpa_offset == ULLONG_MAX)
return ULLONG_MAX;
if (math == XOR_MATH) {
cximsd->nr_maps = hbiw_to_nr_maps[hb_ways];
if (cximsd->nr_maps)
return cxl_do_xormap_calc(cximsd, hpa_offset, hb_ways);
}
return hpa_offset;
}
/**
* to_dpa - translate an HPA offset to DPA offset
*
* hpa_offset: host physical address offset
* r_eiw: region encoded interleave ways
* r_eig: region encoded interleave granularity
* hb_ways: host bridge interleave ways
* math: interleave arithmetic (MODULO_MATH or XOR_MATH)
*
* Returns: device physical address offset
*/
static u64 to_dpa(u64 hpa_offset, u8 r_eiw, u16 r_eig, u8 hb_ways, u8 math)
{
u64 offset = hpa_offset;
if (math == XOR_MATH) {
cximsd->nr_maps = hbiw_to_nr_maps[hb_ways];
if (cximsd->nr_maps)
offset =
cxl_do_xormap_calc(cximsd, hpa_offset, hb_ways);
}
return cxl_calculate_dpa_offset(offset, r_eiw, r_eig);
}
/**
* to_pos - extract an interleave position from an HPA offset
*
* hpa_offset: host physical address offset
* r_eiw: region encoded interleave ways
* r_eig: region encoded interleave granularity
* hb_ways: host bridge interleave ways
* math: interleave arithmetic (MODULO_MATH or XOR_MATH)
*
* Returns: devices position in region interleave
*/
static u64 to_pos(u64 hpa_offset, u8 r_eiw, u16 r_eig, u8 hb_ways, u8 math)
{
u64 offset = hpa_offset;
/* Reverse XOR mapping if specified */
if (math == XOR_MATH)
offset = cxl_do_xormap_calc(cximsd, hpa_offset, hb_ways);
return cxl_calculate_position(offset, r_eiw, r_eig);
}
/**
* run_translation_test - execute forward and reverse translations
*
* @dpa: device physical address
* @pos: expected position in region interleave
* @r_eiw: region encoded interleave ways
* @r_eig: region encoded interleave granularity
* @hb_ways: host bridge interleave ways
* @math: interleave arithmetic (MODULO_MATH or XOR_MATH)
* @expect_spa: expected system physical address
*
* Returns: 0 on success, -1 on failure
*/
static int run_translation_test(u64 dpa, int pos, u8 r_eiw, u16 r_eig,
u8 hb_ways, int math, u64 expect_hpa)
{
u64 translated_spa, reverse_dpa;
int reverse_pos;
/* Test Device to Host translation: DPA + POS -> SPA */
translated_spa = to_hpa(dpa, pos, r_eiw, r_eig, hb_ways, math);
if (translated_spa != expect_hpa) {
pr_err("Device to host failed: expected HPA %llu, got %llu\n",
expect_hpa, translated_spa);
return -1;
}
/* Test Host to Device DPA translation: SPA -> DPA */
reverse_dpa = to_dpa(translated_spa, r_eiw, r_eig, hb_ways, math);
if (reverse_dpa != dpa) {
pr_err("Host to Device DPA failed: expected %llu, got %llu\n",
dpa, reverse_dpa);
return -1;
}
/* Test Host to Device Position translation: SPA -> POS */
reverse_pos = to_pos(translated_spa, r_eiw, r_eig, hb_ways, math);
if (reverse_pos != pos) {
pr_err("Position lookup failed: expected %d, got %d\n", pos,
reverse_pos);
return -1;
}
return 0;
}
/**
* parse_test_vector - parse a single test vector string
*
* entry: test vector string to parse
* dpa: device physical address
* pos: expected position in region interleave
* r_eiw: region encoded interleave ways
* r_eig: region encoded interleave granularity
* hb_ways: host bridge interleave ways
* math: interleave arithmetic (MODULO_MATH or XOR_MATH)
* expect_spa: expected system physical address
*
* Returns: 0 on success, negative error code on failure
*/
static int parse_test_vector(const char *entry, u64 *dpa, int *pos, u8 *r_eiw,
u16 *r_eig, u8 *hb_ways, int *math,
u64 *expect_hpa)
{
unsigned int tmp_r_eiw, tmp_r_eig, tmp_hb_ways;
int parsed;
parsed = sscanf(entry, "%llu %d %u %u %u %d %llu", dpa, pos, &tmp_r_eiw,
&tmp_r_eig, &tmp_hb_ways, math, expect_hpa);
if (parsed != EXPECTED_PARAMS) {
pr_err("Parse error: expected %d parameters, got %d in '%s'\n",
EXPECTED_PARAMS, parsed, entry);
return -EINVAL;
}
if (tmp_r_eiw > U8_MAX || tmp_r_eig > U16_MAX || tmp_hb_ways > U8_MAX) {
pr_err("Parameter overflow in entry: '%s'\n", entry);
return -ERANGE;
}
if (*math != MODULO_MATH && *math != XOR_MATH) {
pr_err("Invalid math type %d in entry: '%s'\n", *math, entry);
return -EINVAL;
}
*r_eiw = tmp_r_eiw;
*r_eig = tmp_r_eig;
*hb_ways = tmp_hb_ways;
return 0;
}
/*
* setup_xor_mapping - Initialize XOR mapping data structure
*
* The test data sets all use the same HBIG so we can use one set
* of xormaps, and set the number to apply based on HBIW before
* calling cxl_do_xormap_calc().
*
* When additional data sets arrive for validation with different
* HBIG's this static setup will need to be updated.
*
* Returns: 0 on success, negative error code on failure
*/
static int setup_xor_mapping(void)
{
if (nr_maps <= 0)
return -EINVAL;
cximsd = kzalloc(struct_size(cximsd, xormaps, nr_maps), GFP_KERNEL);
if (!cximsd)
return -ENOMEM;
cximsd->nr_maps = nr_maps;
memcpy(cximsd->xormaps, xormaps, nr_maps * sizeof(*cximsd->xormaps));
return 0;
}
static int test_random_params(void)
{
u8 valid_eiws[] = { 0, 1, 2, 3, 4, 8, 9, 10 };
u16 valid_eigs[] = { 0, 1, 2, 3, 4, 5, 6 };
int i, ways, pos, reverse_pos;
u64 dpa, hpa, reverse_dpa;
int iterations = 10000;
int failures = 0;
for (i = 0; i < iterations; i++) {
/* Generate valid random parameters for eiw, eig, pos, dpa */
u8 eiw = valid_eiws[get_random_u32() % ARRAY_SIZE(valid_eiws)];
u16 eig = valid_eigs[get_random_u32() % ARRAY_SIZE(valid_eigs)];
eiw_to_ways(eiw, &ways);
pos = get_random_u32() % ways;
dpa = get_random_u64() >> 12;
reverse_dpa = ULLONG_MAX;
reverse_pos = -1;
hpa = cxl_calculate_hpa_offset(dpa, pos, eiw, eig);
if (hpa != ULLONG_MAX) {
reverse_dpa = cxl_calculate_dpa_offset(hpa, eiw, eig);
reverse_pos = cxl_calculate_position(hpa, eiw, eig);
if (reverse_dpa == dpa && reverse_pos == pos)
continue;
}
pr_err("test random iter %d FAIL hpa=%llu, dpa=%llu reverse_dpa=%llu, pos=%d reverse_pos=%d eiw=%u eig=%u\n",
i, hpa, dpa, reverse_dpa, pos, reverse_pos, eiw, eig);
if (failures++ > 10) {
pr_err("test random too many failures, stop\n");
break;
}
}
pr_info("..... test random: PASS %d FAIL %d\n", i - failures, failures);
if (failures)
return -EINVAL;
return 0;
}
struct param_test {
u8 eiw;
u16 eig;
int pos;
bool expect; /* true: expect pass, false: expect fail */
const char *desc;
};
static struct param_test param_tests[] = {
{ 0x0, 0, 0, true, "1-way, min eig=0, pos=0" },
{ 0x0, 3, 0, true, "1-way, mid eig=3, pos=0" },
{ 0x0, 6, 0, true, "1-way, max eig=6, pos=0" },
{ 0x1, 0, 0, true, "2-way, eig=0, pos=0" },
{ 0x1, 3, 1, true, "2-way, eig=3, max pos=1" },
{ 0x1, 6, 1, true, "2-way, eig=6, max pos=1" },
{ 0x2, 0, 0, true, "4-way, eig=0, pos=0" },
{ 0x2, 3, 3, true, "4-way, eig=3, max pos=3" },
{ 0x2, 6, 3, true, "4-way, eig=6, max pos=3" },
{ 0x3, 0, 0, true, "8-way, eig=0, pos=0" },
{ 0x3, 3, 7, true, "8-way, eig=3, max pos=7" },
{ 0x3, 6, 7, true, "8-way, eig=6, max pos=7" },
{ 0x4, 0, 0, true, "16-way, eig=0, pos=0" },
{ 0x4, 3, 15, true, "16-way, eig=3, max pos=15" },
{ 0x4, 6, 15, true, "16-way, eig=6, max pos=15" },
{ 0x8, 0, 0, true, "3-way, eig=0, pos=0" },
{ 0x8, 3, 2, true, "3-way, eig=3, max pos=2" },
{ 0x8, 6, 2, true, "3-way, eig=6, max pos=2" },
{ 0x9, 0, 0, true, "6-way, eig=0, pos=0" },
{ 0x9, 3, 5, true, "6-way, eig=3, max pos=5" },
{ 0x9, 6, 5, true, "6-way, eig=6, max pos=5" },
{ 0xA, 0, 0, true, "12-way, eig=0, pos=0" },
{ 0xA, 3, 11, true, "12-way, eig=3, max pos=11" },
{ 0xA, 6, 11, true, "12-way, eig=6, max pos=11" },
{ 0x5, 0, 0, false, "invalid eiw=5" },
{ 0x7, 0, 0, false, "invalid eiw=7" },
{ 0xB, 0, 0, false, "invalid eiw=0xB" },
{ 0xFF, 0, 0, false, "invalid eiw=0xFF" },
{ 0x1, 7, 0, false, "invalid eig=7 (out of range)" },
{ 0x2, 0x10, 0, false, "invalid eig=0x10" },
{ 0x3, 0xFFFF, 0, false, "invalid eig=0xFFFF" },
{ 0x1, 0, -1, false, "pos < 0" },
{ 0x1, 0, 2, false, "2-way, pos=2 (>= ways)" },
{ 0x2, 0, 4, false, "4-way, pos=4 (>= ways)" },
{ 0x3, 0, 8, false, "8-way, pos=8 (>= ways)" },
{ 0x4, 0, 16, false, "16-way, pos=16 (>= ways)" },
{ 0x8, 0, 3, false, "3-way, pos=3 (>= ways)" },
{ 0x9, 0, 6, false, "6-way, pos=6 (>= ways)" },
{ 0xA, 0, 12, false, "12-way, pos=12 (>= ways)" },
};
static int test_cxl_validate_translation_params(void)
{
int i, rc, failures = 0;
bool valid;
for (i = 0; i < ARRAY_SIZE(param_tests); i++) {
struct param_test *t = &param_tests[i];
rc = cxl_validate_translation_params(t->eiw, t->eig, t->pos);
valid = (rc == 0);
if (valid != t->expect) {
pr_err("test params failed: %s\n", t->desc);
failures++;
}
}
pr_info("..... test params: PASS %d FAIL %d\n", i - failures, failures);
if (failures)
return -EINVAL;
return 0;
}
/*
* cxl_translate_init
*
* Run the internal validation tests when no params are passed.
* Otherwise, parse the parameters (test vectors), and kick off
* the translation test.
*
* Returns: 0 on success, negative error code on failure
*/
static int __init cxl_translate_init(void)
{
int rc, i;
/* If no tables are passed, validate module params only */
if (table_num == 0) {
pr_info("Internal validation test start...\n");
rc = test_cxl_validate_translation_params();
if (rc)
return rc;
rc = test_random_params();
if (rc)
return rc;
pr_info("Internal validation test completed successfully\n");
return 0;
}
pr_info("CXL translate test module loaded with %d test vectors\n",
table_num);
rc = setup_xor_mapping();
if (rc)
return rc;
/* Process each test vector */
for (i = 0; i < table_num; i++) {
u64 dpa, expect_spa;
int pos, math;
u8 r_eiw, hb_ways;
u16 r_eig;
pr_debug("Processing test vector %d: '%s'\n", i, table[i]);
/* Parse the test vector */
rc = parse_test_vector(table[i], &dpa, &pos, &r_eiw, &r_eig,
&hb_ways, &math, &expect_spa);
if (rc) {
pr_err("CXL Translate Test %d: FAIL\n"
" Failed to parse test vector '%s'\n",
i, table[i]);
continue;
}
/* Run the translation test */
rc = run_translation_test(dpa, pos, r_eiw, r_eig, hb_ways, math,
expect_spa);
if (rc) {
pr_err("CXL Translate Test %d: FAIL\n"
" dpa=%llu pos=%d r_eiw=%u r_eig=%u hb_ways=%u math=%s expect_spa=%llu\n",
i, dpa, pos, r_eiw, r_eig, hb_ways,
(math == XOR_MATH) ? "XOR" : "MODULO",
expect_spa);
} else {
pr_info("CXL Translate Test %d: PASS\n", i);
}
}
kfree(cximsd);
pr_info("CXL translate test completed\n");
return 0;
}
static void __exit cxl_translate_exit(void)
{
pr_info("CXL translate test module unloaded\n");
}
module_param_array(table, charp, &table_num, 0444);
MODULE_PARM_DESC(table, "Test vectors as space-separated decimal strings");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("cxl_test: cxl address translation test module");
MODULE_IMPORT_NS("CXL");
module_init(cxl_translate_init);
module_exit(cxl_translate_exit);
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright (C) 2026 Intel Corporation */
#include <linux/moduleparam.h>
#include <linux/workqueue.h>
#include "../../../drivers/dax/bus.h"
static bool hmem_test;
static void hmem_test_work(struct work_struct *work)
{
}
static void hmem_test_release(struct device *dev)
{
struct hmem_platform_device *hpdev =
container_of(dev, typeof(*hpdev), pdev.dev);
memset(hpdev, 0, sizeof(*hpdev));
}
static struct hmem_platform_device hmem_test_device = {
.pdev = {
.name = "hmem_platform",
.id = 1,
.dev = {
.release = hmem_test_release,
},
},
.work = __WORK_INITIALIZER(hmem_test_device.work, hmem_test_work),
};
int hmem_test_init(void)
{
if (!hmem_test)
return 0;
return platform_device_register(&hmem_test_device.pdev);
}
void hmem_test_exit(void)
{
if (hmem_test)
platform_device_unregister(&hmem_test_device.pdev);
}
module_param(hmem_test, bool, 0444);
MODULE_PARM_DESC(hmem_test, "Enable/disable the dax_hmem test platform device");
File diff suppressed because it is too large Load Diff
+307
View File
@@ -0,0 +1,307 @@
// SPDX-License-Identifier: GPL-2.0-only
//Copyright(c) 2021 Intel Corporation. All rights reserved.
#include <linux/libnvdimm.h>
#include <linux/rculist.h>
#include <linux/device.h>
#include <linux/export.h>
#include <linux/acpi.h>
#include <linux/pci.h>
#include <cxlmem.h>
#include <cxlpci.h>
#include "mock.h"
static LIST_HEAD(mock);
void register_cxl_mock_ops(struct cxl_mock_ops *ops)
{
list_add_rcu(&ops->list, &mock);
}
EXPORT_SYMBOL_GPL(register_cxl_mock_ops);
DEFINE_STATIC_SRCU(cxl_mock_srcu);
void unregister_cxl_mock_ops(struct cxl_mock_ops *ops)
{
list_del_rcu(&ops->list);
synchronize_srcu(&cxl_mock_srcu);
}
EXPORT_SYMBOL_GPL(unregister_cxl_mock_ops);
struct cxl_mock_ops *get_cxl_mock_ops(int *index)
{
*index = srcu_read_lock(&cxl_mock_srcu);
return list_first_or_null_rcu(&mock, struct cxl_mock_ops, list);
}
EXPORT_SYMBOL_GPL(get_cxl_mock_ops);
void put_cxl_mock_ops(int index)
{
srcu_read_unlock(&cxl_mock_srcu, index);
}
EXPORT_SYMBOL_GPL(put_cxl_mock_ops);
bool __wrap_is_acpi_device_node(const struct fwnode_handle *fwnode)
{
struct acpi_device *adev =
container_of(fwnode, struct acpi_device, fwnode);
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
bool retval = false;
if (ops)
retval = ops->is_mock_adev(adev);
if (!retval)
retval = is_acpi_device_node(fwnode);
put_cxl_mock_ops(index);
return retval;
}
EXPORT_SYMBOL(__wrap_is_acpi_device_node);
int __wrap_acpi_table_parse_cedt(enum acpi_cedt_type id,
acpi_tbl_entry_handler_arg handler_arg,
void *arg)
{
int index, rc;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops)
rc = ops->acpi_table_parse_cedt(id, handler_arg, arg);
else
rc = acpi_table_parse_cedt(id, handler_arg, arg);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_NS_GPL(__wrap_acpi_table_parse_cedt, "ACPI");
acpi_status __wrap_acpi_evaluate_integer(acpi_handle handle,
acpi_string pathname,
struct acpi_object_list *arguments,
unsigned long long *data)
{
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
acpi_status status;
if (ops)
status = ops->acpi_evaluate_integer(handle, pathname, arguments,
data);
else
status = acpi_evaluate_integer(handle, pathname, arguments,
data);
put_cxl_mock_ops(index);
return status;
}
EXPORT_SYMBOL(__wrap_acpi_evaluate_integer);
int __wrap_hmat_get_extended_linear_cache_size(struct resource *backing_res,
int nid,
resource_size_t *cache_size)
{
int index, rc;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops)
rc = ops->hmat_get_extended_linear_cache_size(backing_res, nid,
cache_size);
else
rc = hmat_get_extended_linear_cache_size(backing_res, nid,
cache_size);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_GPL(__wrap_hmat_get_extended_linear_cache_size);
struct acpi_pci_root *__wrap_acpi_pci_find_root(acpi_handle handle)
{
int index;
struct acpi_pci_root *root;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops)
root = ops->acpi_pci_find_root(handle);
else
root = acpi_pci_find_root(handle);
put_cxl_mock_ops(index);
return root;
}
EXPORT_SYMBOL_GPL(__wrap_acpi_pci_find_root);
struct nvdimm_bus *
__wrap_nvdimm_bus_register(struct device *dev,
struct nvdimm_bus_descriptor *nd_desc)
{
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_dev(dev->parent->parent))
nd_desc->provider_name = "cxl_test";
put_cxl_mock_ops(index);
return nvdimm_bus_register(dev, nd_desc);
}
EXPORT_SYMBOL_GPL(__wrap_nvdimm_bus_register);
int __wrap_devm_cxl_switch_port_decoders_setup(struct cxl_port *port)
{
int rc, index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_port(port->uport_dev))
rc = ops->devm_cxl_switch_port_decoders_setup(port);
else
rc = devm_cxl_switch_port_decoders_setup(port);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_NS_GPL(__wrap_devm_cxl_switch_port_decoders_setup, "CXL");
int __wrap_devm_cxl_endpoint_decoders_setup(struct cxl_port *port)
{
int rc, index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_port(port->uport_dev))
rc = ops->devm_cxl_endpoint_decoders_setup(port);
else
rc = devm_cxl_endpoint_decoders_setup(port);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_NS_GPL(__wrap_devm_cxl_endpoint_decoders_setup, "CXL");
int __wrap_cxl_await_media_ready(struct cxl_dev_state *cxlds)
{
int rc, index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_dev(cxlds->dev))
rc = 0;
else
rc = cxl_await_media_ready(cxlds);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_NS_GPL(__wrap_cxl_await_media_ready, "CXL");
struct cxl_dport *__wrap_devm_cxl_add_rch_dport(struct cxl_port *port,
struct device *dport_dev,
int port_id,
resource_size_t rcrb)
{
int index;
struct cxl_dport *dport;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops && ops->is_mock_port(dport_dev)) {
dport = devm_cxl_add_dport(port, dport_dev, port_id,
CXL_RESOURCE_NONE);
if (!IS_ERR(dport)) {
dport->rcrb.base = rcrb;
dport->rch = true;
}
} else
dport = devm_cxl_add_rch_dport(port, dport_dev, port_id, rcrb);
put_cxl_mock_ops(index);
return dport;
}
EXPORT_SYMBOL_NS_GPL(__wrap_devm_cxl_add_rch_dport, "CXL");
void __wrap_cxl_endpoint_parse_cdat(struct cxl_port *port)
{
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
struct cxl_memdev *cxlmd = to_cxl_memdev(port->uport_dev);
if (ops && ops->is_mock_dev(cxlmd->dev.parent))
ops->cxl_endpoint_parse_cdat(port);
else
cxl_endpoint_parse_cdat(port);
put_cxl_mock_ops(index);
}
EXPORT_SYMBOL_NS_GPL(__wrap_cxl_endpoint_parse_cdat, "CXL");
struct cxl_dport *__wrap_devm_cxl_add_dport_by_dev(struct cxl_port *port,
struct device *dport_dev)
{
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
struct cxl_dport *dport;
if (ops && ops->is_mock_port(port->uport_dev))
dport = ops->devm_cxl_add_dport_by_dev(port, dport_dev);
else
dport = devm_cxl_add_dport_by_dev(port, dport_dev);
put_cxl_mock_ops(index);
return dport;
}
EXPORT_SYMBOL_NS_GPL(__wrap_devm_cxl_add_dport_by_dev, "CXL");
int __wrap_region_intersects(resource_size_t start, size_t size,
unsigned long flags, unsigned long desc)
{
int rc = -1;
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops)
rc = ops->region_intersects(start, size, flags, desc);
if (rc < 0)
rc = region_intersects(start, size, flags, desc);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_GPL(__wrap_region_intersects);
int __wrap_region_intersects_soft_reserve(resource_size_t start, size_t size)
{
int rc = -1;
int index;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (ops)
rc = ops->region_intersects_soft_reserve(start, size);
if (rc < 0)
rc = region_intersects_soft_reserve(start, size);
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_GPL(__wrap_region_intersects_soft_reserve);
int __wrap_walk_hmem_resources(struct device *host, walk_hmem_fn fn)
{
int index, rc = 0;
bool is_mock = strcmp(dev_name(host), "hmem_platform.1") == 0;
struct cxl_mock_ops *ops = get_cxl_mock_ops(&index);
if (is_mock) {
if (ops)
rc = ops->walk_hmem_resources(host, fn);
} else {
rc = walk_hmem_resources(host, fn);
}
put_cxl_mock_ops(index);
return rc;
}
EXPORT_SYMBOL_GPL(__wrap_walk_hmem_resources);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("cxl_test: emulation module");
MODULE_IMPORT_NS("ACPI");
MODULE_IMPORT_NS("CXL");
+43
View File
@@ -0,0 +1,43 @@
/* SPDX-License-Identifier: GPL-2.0 */
#include <linux/list.h>
#include <linux/acpi.h>
#include <linux/dax.h>
#include <cxl.h>
struct cxl_mock_ops {
struct list_head list;
bool (*is_mock_adev)(struct acpi_device *dev);
int (*acpi_table_parse_cedt)(enum acpi_cedt_type id,
acpi_tbl_entry_handler_arg handler_arg,
void *arg);
bool (*is_mock_bridge)(struct device *dev);
acpi_status (*acpi_evaluate_integer)(acpi_handle handle,
acpi_string pathname,
struct acpi_object_list *arguments,
unsigned long long *data);
struct acpi_pci_root *(*acpi_pci_find_root)(acpi_handle handle);
bool (*is_mock_bus)(struct pci_bus *bus);
bool (*is_mock_port)(struct device *dev);
bool (*is_mock_dev)(struct device *dev);
int (*devm_cxl_switch_port_decoders_setup)(struct cxl_port *port);
int (*devm_cxl_endpoint_decoders_setup)(struct cxl_port *port);
void (*cxl_endpoint_parse_cdat)(struct cxl_port *port);
struct cxl_dport *(*devm_cxl_add_dport_by_dev)(struct cxl_port *port,
struct device *dport_dev);
int (*hmat_get_extended_linear_cache_size)(struct resource *backing_res,
int nid,
resource_size_t *cache_size);
int (*walk_hmem_resources)(struct device *host, walk_hmem_fn fn);
int (*region_intersects)(resource_size_t start, size_t size,
unsigned long flags, unsigned long desc);
int (*region_intersects_soft_reserve)(resource_size_t start,
size_t size);
};
int hmem_test_init(void);
void hmem_test_exit(void);
void register_cxl_mock_ops(struct cxl_mock_ops *ops);
void unregister_cxl_mock_ops(struct cxl_mock_ops *ops);
struct cxl_mock_ops *get_cxl_mock_ops(int *index);
void put_cxl_mock_ops(int index);
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2022 Intel Corporation. All rights reserved. */
#ifndef _TEST_CXL_WATERMARK_H_
#define _TEST_CXL_WATERMARK_H_
#include <linux/module.h>
#include <linux/printk.h>
int cxl_acpi_test(void);
int cxl_core_test(void);
int cxl_mem_test(void);
int cxl_pmem_test(void);
int cxl_port_test(void);
/*
* dummy routine for cxl_test to validate it is linking to the properly
* mocked module and not the standard one from the base tree.
*/
#define cxl_test_watermark(x) \
int x##_test(void) \
{ \
pr_debug("%s for cxl_test\n", KBUILD_MODNAME); \
return 0; \
} \
EXPORT_SYMBOL(x##_test)
#endif /* _TEST_CXL_WATERMARK_H_ */
+232
View File
@@ -0,0 +1,232 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
#
# NAME
# failcmd.sh - run a command with injecting slab/page allocation failures
#
# SYNOPSIS
# failcmd.sh --help
# failcmd.sh [<options>] command [arguments]
#
# DESCRIPTION
# Run command with injecting slab/page allocation failures by fault
# injection.
#
# NOTE: you need to run this script as root.
#
usage()
{
cat >&2 <<EOF
Usage: $0 [options] command [arguments]
OPTIONS
-p percent
--probability=percent
likelihood of failure injection, in percent.
Default value is 1
-t value
--times=value
specifies how many times failures may happen at most.
Default value is 1
--oom-kill-allocating-task=value
set /proc/sys/vm/oom_kill_allocating_task to specified value
before running the command.
Default value is 1
-h, --help
Display a usage message and exit
--interval=value, --space=value, --verbose=value, --task-filter=value,
--stacktrace-depth=value, --require-start=value, --require-end=value,
--reject-start=value, --reject-end=value, --ignore-gfp-wait=value
See Documentation/fault-injection/fault-injection.rst for more
information
failslab options:
--cache-filter=value
fail_page_alloc options:
--ignore-gfp-highmem=value, --min-order=value
ENVIRONMENT
FAILCMD_TYPE
The following values for FAILCMD_TYPE are recognized:
failslab
inject slab allocation failures
fail_page_alloc
inject page allocation failures
If FAILCMD_TYPE is not defined, then failslab is used.
EOF
}
exit_if_not_hex() {
local value="$1"
if ! [[ $value =~ ^0x[0-9a-fA-F]+$ ]]; then
echo "Error: The provided value '$value' is not a valid hexadecimal number." >&2
exit 1
fi
}
if [ $UID != 0 ]; then
echo must be run as root >&2
exit 1
fi
DEBUGFS=`mount -t debugfs | head -1 | awk '{ print $3}'`
if [ ! -d "$DEBUGFS" ]; then
echo debugfs is not mounted >&2
exit 1
fi
FAILCMD_TYPE=${FAILCMD_TYPE:-failslab}
FAULTATTR=$DEBUGFS/$FAILCMD_TYPE
if [ ! -d $FAULTATTR ]; then
echo $FAILCMD_TYPE is not available >&2
exit 1
fi
LONGOPTS=probability:,interval:,times:,space:,verbose:,task-filter:
LONGOPTS=$LONGOPTS,stacktrace-depth:,require-start:,require-end:
LONGOPTS=$LONGOPTS,reject-start:,reject-end:,oom-kill-allocating-task:,help
if [ $FAILCMD_TYPE = failslab ]; then
LONGOPTS=$LONGOPTS,ignore-gfp-wait:,cache-filter:
elif [ $FAILCMD_TYPE = fail_page_alloc ]; then
LONGOPTS=$LONGOPTS,ignore-gfp-wait:,ignore-gfp-highmem:,min-order:
fi
TEMP=`getopt -o p:i:t:s:v:h --long $LONGOPTS -n 'failcmd.sh' -- "$@"`
if [ $? != 0 ]; then
usage
exit 1
fi
eval set -- "$TEMP"
fault_attr_default()
{
echo N > $FAULTATTR/task-filter
echo 0 > $FAULTATTR/probability
echo 1 > $FAULTATTR/times
}
fault_attr_default
oom_kill_allocating_task_saved=`cat /proc/sys/vm/oom_kill_allocating_task`
restore_values()
{
fault_attr_default
echo $oom_kill_allocating_task_saved \
> /proc/sys/vm/oom_kill_allocating_task
}
#
# Default options
#
declare -i oom_kill_allocating_task=1
declare task_filter=Y
declare -i probability=1
declare -i times=1
while true; do
case "$1" in
-p|--probability)
probability=$2
shift 2
;;
-i|--interval)
echo $2 > $FAULTATTR/interval
shift 2
;;
-t|--times)
times=$2
shift 2
;;
-s|--space)
echo $2 > $FAULTATTR/space
shift 2
;;
-v|--verbose)
echo $2 > $FAULTATTR/verbose
shift 2
;;
--task-filter)
task_filter=$2
shift 2
;;
--stacktrace-depth)
echo $2 > $FAULTATTR/stacktrace-depth
shift 2
;;
--require-start)
exit_if_not_hex "$2"
echo $2 > $FAULTATTR/require-start
shift 2
;;
--require-end)
exit_if_not_hex "$2"
echo $2 > $FAULTATTR/require-end
shift 2
;;
--reject-start)
exit_if_not_hex "$2"
echo $2 > $FAULTATTR/reject-start
shift 2
;;
--reject-end)
exit_if_not_hex "$2"
echo $2 > $FAULTATTR/reject-end
shift 2
;;
--oom-kill-allocating-task)
oom_kill_allocating_task=$2
shift 2
;;
--ignore-gfp-wait)
echo $2 > $FAULTATTR/ignore-gfp-wait
shift 2
;;
--cache-filter)
echo $2 > $FAULTATTR/cache_filter
shift 2
;;
--ignore-gfp-highmem)
echo $2 > $FAULTATTR/ignore-gfp-highmem
shift 2
;;
--min-order)
echo $2 > $FAULTATTR/min-order
shift 2
;;
-h|--help)
usage
exit 0
shift
;;
--)
shift
break
;;
esac
done
[ -z "$1" ] && exit 0
echo $oom_kill_allocating_task > /proc/sys/vm/oom_kill_allocating_task
echo $task_filter > $FAULTATTR/task-filter
echo $probability > $FAULTATTR/probability
echo $times > $FAULTATTR/times
trap "restore_values" SIGINT SIGTERM EXIT
cmd="echo 1 > /proc/self/make-it-fail && exec $@"
bash -c "$cmd"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env perl
# SPDX-License-Identifier: GPL-2.0
open (IN,"ktest.pl");
while (<IN>) {
# hashes are now used
if (/\$opt\{"?([A-Z].*?)(\[.*\])?"?\}/ ||
/^\s*"?([A-Z].*?)"?\s*=>\s*/ ||
/set_test_option\("(.*?)"/) {
$opt{$1} = 1;
}
}
close IN;
open (IN, "sample.conf");
while (<IN>) {
if (/^\s*#?\s*([A-Z]\S*)\s*=/) {
$samp{$1} = 1;
}
}
close IN;
foreach $opt (keys %opt) {
if (!defined($samp{$opt})) {
print "opt = $opt\n";
}
}
foreach $samp (keys %samp) {
if (!defined($opt{$samp})) {
print "samp = $samp\n";
}
}
+769
View File
@@ -0,0 +1,769 @@
#!/usr/bin/perl -w
# SPDX-License-Identifier: GPL-2.0-only
#
# Copyright 2015 - Steven Rostedt, Red Hat Inc.
# Copyright 2017 - Steven Rostedt, VMware, Inc.
#
# usage:
# config-bisect.pl [options] good-config bad-config [good|bad]
#
# Compares a good config to a bad config, then takes half of the diffs
# and produces a config that is somewhere between the good config and
# the bad config. That is, the resulting config will start with the
# good config and will try to make half of the differences of between
# the good and bad configs match the bad config. It tries because of
# dependencies between the two configs it may not be able to change
# exactly half of the configs that are different between the two config
# files.
# Here's a normal way to use it:
#
# $ cd /path/to/linux/kernel
# $ config-bisect.pl /path/to/good/config /path/to/bad/config
# This will now pull in good config (blowing away .config in that directory
# so do not make that be one of the good or bad configs), and then
# build the config with "make oldconfig" to make sure it matches the
# current kernel. It will then store the configs in that result for
# the good config. It does the same for the bad config as well.
# The algorithm will run, merging half of the differences between
# the two configs and building them with "make oldconfig" to make sure
# the result changes (dependencies may reset changes the tool had made).
# It then copies the result of its good config to /path/to/good/config.tmp
# and the bad config to /path/to/bad/config.tmp (just appends ".tmp" to the
# files passed in). And the ".config" that you should test will be in
# directory
# After the first run, determine if the result is good or bad then
# run the same command appending the result
# For good results:
# $ config-bisect.pl /path/to/good/config /path/to/bad/config good
# For bad results:
# $ config-bisect.pl /path/to/good/config /path/to/bad/config bad
# Do not change the good-config or bad-config, config-bisect.pl will
# copy the good-config to a temp file with the same name as good-config
# but with a ".tmp" after it. It will do the same with the bad-config.
# If "good" or "bad" is not stated at the end, it will copy the good and
# bad configs to the .tmp versions. If a .tmp version already exists, it will
# warn before writing over them (-r will not warn, and just write over them).
# If the last config is labeled "good", then it will copy it to the good .tmp
# version. If the last config is labeled "bad", it will copy it to the bad
# .tmp version. It will continue this until it can not merge the two any more
# without the result being equal to either the good or bad .tmp configs.
my $start = 0;
my $val = "";
my $pwd = `pwd`;
chomp $pwd;
my $tree = $pwd;
my $build;
my $output_config;
my $reset_bisect;
sub usage {
print << "EOF"
usage: config-bisect.pl [-l linux-tree][-b build-dir] good-config bad-config [good|bad]
-l [optional] define location of linux-tree (default is current directory)
-b [optional] define location to build (O=build-dir) (default is linux-tree)
good-config the config that is considered good
bad-config the config that does not work
"good" add this if the last run produced a good config
"bad" add this if the last run produced a bad config
If "good" or "bad" is not specified, then it is the start of a new bisect
Note, each run will create copy of good and bad configs with ".tmp" appended.
EOF
;
exit(-1);
}
sub doprint {
print @_;
}
sub dodie {
doprint "CRITICAL FAILURE... ", @_, "\n";
die @_, "\n";
}
sub expand_path {
my ($file) = @_;
if ($file =~ m,^/,) {
return $file;
}
return "$pwd/$file";
}
sub read_prompt {
my ($cancel, $prompt) = @_;
my $ans;
for (;;) {
if ($cancel) {
print "$prompt [y/n/C] ";
} else {
print "$prompt [y/N] ";
}
$ans = <STDIN>;
chomp $ans;
if ($ans =~ /^\s*$/) {
if ($cancel) {
$ans = "c";
} else {
$ans = "n";
}
}
last if ($ans =~ /^y$/i || $ans =~ /^n$/i);
if ($cancel) {
last if ($ans =~ /^c$/i);
print "Please answer either 'y', 'n' or 'c'.\n";
} else {
print "Please answer either 'y' or 'n'.\n";
}
}
if ($ans =~ /^c/i) {
exit;
}
if ($ans !~ /^y$/i) {
return 0;
}
return 1;
}
sub read_yn {
my ($prompt) = @_;
return read_prompt 0, $prompt;
}
sub read_ync {
my ($prompt) = @_;
return read_prompt 1, $prompt;
}
sub run_command {
my ($command, $redirect) = @_;
my $start_time;
my $end_time;
my $dord = 0;
my $pid;
$start_time = time;
doprint("$command ... ");
$pid = open(CMD, "$command 2>&1 |") or
dodie "unable to exec $command";
if (defined($redirect)) {
open (RD, ">$redirect") or
dodie "failed to write to redirect $redirect";
$dord = 1;
}
while (<CMD>) {
print RD if ($dord);
}
waitpid($pid, 0);
my $failed = $?;
close(CMD);
close(RD) if ($dord);
$end_time = time;
my $delta = $end_time - $start_time;
if ($delta == 1) {
doprint "[1 second] ";
} else {
doprint "[$delta seconds] ";
}
if ($failed) {
doprint "FAILED!\n";
} else {
doprint "SUCCESS\n";
}
return !$failed;
}
###### CONFIG BISECT ######
# config_ignore holds the configs that were set (or unset) for
# a good config and we will ignore these configs for the rest
# of a config bisect. These configs stay as they were.
my %config_ignore;
# config_set holds what all configs were set as.
my %config_set;
# config_off holds the set of configs that the bad config had disabled.
# We need to record them and set them in the .config when running
# olddefconfig, because olddefconfig keeps the defaults.
my %config_off;
# config_off_tmp holds a set of configs to turn off for now
my @config_off_tmp;
# config_list is the set of configs that are being tested
my %config_list;
my %null_config;
my %dependency;
my $make;
sub make_oldconfig {
if (!run_command "$make olddefconfig") {
# Perhaps olddefconfig doesn't exist in this version of the kernel
# try oldnoconfig
doprint "olddefconfig failed, trying make oldnoconfig\n";
if (!run_command "$make oldnoconfig") {
doprint "oldnoconfig failed, trying yes '' | make oldconfig\n";
# try a yes '' | oldconfig
run_command "yes '' | $make oldconfig" or
dodie "failed make config oldconfig";
}
}
}
sub assign_configs {
my ($hash, $config) = @_;
doprint "Reading configs from $config\n";
open (IN, $config)
or dodie "Failed to read $config";
while (<IN>) {
chomp;
if (/^((CONFIG\S*)=.*)/) {
${$hash}{$2} = $1;
} elsif (/^(# (CONFIG\S*) is not set)/) {
${$hash}{$2} = $1;
}
}
close(IN);
}
sub process_config_ignore {
my ($config) = @_;
assign_configs \%config_ignore, $config;
}
sub get_dependencies {
my ($config) = @_;
my $arr = $dependency{$config};
if (!defined($arr)) {
return ();
}
my @deps = @{$arr};
foreach my $dep (@{$arr}) {
print "ADD DEP $dep\n";
@deps = (@deps, get_dependencies $dep);
}
return @deps;
}
sub save_config {
my ($pc, $file) = @_;
my %configs = %{$pc};
doprint "Saving configs into $file\n";
open(OUT, ">$file") or dodie "Can not write to $file";
foreach my $config (keys %configs) {
print OUT "$configs{$config}\n";
}
close(OUT);
}
sub create_config {
my ($name, $pc) = @_;
doprint "Creating old config from $name configs\n";
save_config $pc, $output_config;
make_oldconfig;
}
# compare two config hashes, and return configs with different vals.
# It returns B's config values, but you can use A to see what A was.
sub diff_config_vals {
my ($pa, $pb) = @_;
# crappy Perl way to pass in hashes.
my %a = %{$pa};
my %b = %{$pb};
my %ret;
foreach my $item (keys %a) {
if (defined($b{$item}) && $b{$item} ne $a{$item}) {
$ret{$item} = $b{$item};
}
}
return %ret;
}
# compare two config hashes and return the configs in B but not A
sub diff_configs {
my ($pa, $pb) = @_;
my %ret;
# crappy Perl way to pass in hashes.
my %a = %{$pa};
my %b = %{$pb};
foreach my $item (keys %b) {
if (!defined($a{$item})) {
$ret{$item} = $b{$item};
}
}
return %ret;
}
# return if two configs are equal or not
# 0 is equal +1 b has something a does not
# +1 if a and b have a different item.
# -1 if a has something b does not
sub compare_configs {
my ($pa, $pb) = @_;
my %ret;
# crappy Perl way to pass in hashes.
my %a = %{$pa};
my %b = %{$pb};
foreach my $item (keys %b) {
if (!defined($a{$item})) {
return 1;
}
if ($a{$item} ne $b{$item}) {
return 1;
}
}
foreach my $item (keys %a) {
if (!defined($b{$item})) {
return -1;
}
}
return 0;
}
sub process_failed {
my ($config) = @_;
doprint "\n\n***************************************\n";
doprint "Found bad config: $config\n";
doprint "***************************************\n\n";
}
sub process_new_config {
my ($tc, $nc, $gc, $bc) = @_;
my %tmp_config = %{$tc};
my %good_configs = %{$gc};
my %bad_configs = %{$bc};
my %new_configs;
my $runtest = 1;
my $ret;
create_config "tmp_configs", \%tmp_config;
assign_configs \%new_configs, $output_config;
$ret = compare_configs \%new_configs, \%bad_configs;
if (!$ret) {
doprint "New config equals bad config, try next test\n";
$runtest = 0;
}
if ($runtest) {
$ret = compare_configs \%new_configs, \%good_configs;
if (!$ret) {
doprint "New config equals good config, try next test\n";
$runtest = 0;
}
}
%{$nc} = %new_configs;
return $runtest;
}
sub convert_config {
my ($config) = @_;
if ($config =~ /^# (.*) is not set/) {
$config = "$1=n";
}
$config =~ s/^CONFIG_//;
return $config;
}
sub print_config {
my ($sym, $config) = @_;
$config = convert_config $config;
doprint "$sym$config\n";
}
sub print_config_compare {
my ($good_config, $bad_config) = @_;
$good_config = convert_config $good_config;
$bad_config = convert_config $bad_config;
my $good_value = $good_config;
my $bad_value = $bad_config;
$good_value =~ s/(.*)=//;
my $config = $1;
$bad_value =~ s/.*=//;
doprint " $config $good_value -> $bad_value\n";
}
# Pass in:
# $phalf: half of the configs names you want to add
# $oconfigs: The orginial configs to start with
# $sconfigs: The source to update $oconfigs with (from $phalf)
# $which: The name of which half that is updating (top / bottom)
# $type: The name of the source type (good / bad)
sub make_half {
my ($phalf, $oconfigs, $sconfigs, $which, $type) = @_;
my @half = @{$phalf};
my %orig_configs = %{$oconfigs};
my %source_configs = %{$sconfigs};
my %tmp_config = %orig_configs;
doprint "Settings bisect with $which half of $type configs:\n";
foreach my $item (@half) {
doprint "Updating $item to $source_configs{$item}\n";
$tmp_config{$item} = $source_configs{$item};
}
return %tmp_config;
}
sub run_config_bisect {
my ($pgood, $pbad) = @_;
my %good_configs = %{$pgood};
my %bad_configs = %{$pbad};
my %diff_configs = diff_config_vals \%good_configs, \%bad_configs;
my %b_configs = diff_configs \%good_configs, \%bad_configs;
my %g_configs = diff_configs \%bad_configs, \%good_configs;
# diff_arr is what is in both good and bad but are different (y->n)
my @diff_arr = keys %diff_configs;
my $len_diff = $#diff_arr + 1;
# b_arr is what is in bad but not in good (has depends)
my @b_arr = keys %b_configs;
my $len_b = $#b_arr + 1;
# g_arr is what is in good but not in bad
my @g_arr = keys %g_configs;
my $len_g = $#g_arr + 1;
my $runtest = 0;
my %new_configs;
my $ret;
# Look at the configs that are different between good and bad.
# This does not include those that depend on other configs
# (configs depending on other configs that are not set would
# not show up even as a "# CONFIG_FOO is not set"
doprint "# of configs to check: $len_diff\n";
doprint "# of configs showing only in good: $len_g\n";
doprint "# of configs showing only in bad: $len_b\n";
if ($len_diff > 0) {
# Now test for different values
doprint "Configs left to check:\n";
doprint " Good Config\t\t\tBad Config\n";
doprint " -----------\t\t\t----------\n";
foreach my $item (@diff_arr) {
doprint " $good_configs{$item}\t$bad_configs{$item}\n";
}
my $half = int($#diff_arr / 2);
my @tophalf = @diff_arr[0 .. $half];
doprint "Set tmp config to be good config with some bad config values\n";
my %tmp_config = make_half \@tophalf, \%good_configs,
\%bad_configs, "top", "bad";
$runtest = process_new_config \%tmp_config, \%new_configs,
\%good_configs, \%bad_configs;
if (!$runtest) {
doprint "Set tmp config to be bad config with some good config values\n";
my %tmp_config = make_half \@tophalf, \%bad_configs,
\%good_configs, "top", "good";
$runtest = process_new_config \%tmp_config, \%new_configs,
\%good_configs, \%bad_configs;
}
}
if (!$runtest && $len_diff > 0) {
# do the same thing, but this time with bottom half
my $half = int($#diff_arr / 2);
my @bottomhalf = @diff_arr[$half+1 .. $#diff_arr];
doprint "Set tmp config to be good config with some bad config values\n";
my %tmp_config = make_half \@bottomhalf, \%good_configs,
\%bad_configs, "bottom", "bad";
$runtest = process_new_config \%tmp_config, \%new_configs,
\%good_configs, \%bad_configs;
if (!$runtest) {
doprint "Set tmp config to be bad config with some good config values\n";
my %tmp_config = make_half \@bottomhalf, \%bad_configs,
\%good_configs, "bottom", "good";
$runtest = process_new_config \%tmp_config, \%new_configs,
\%good_configs, \%bad_configs;
}
}
if ($runtest) {
make_oldconfig;
doprint "READY TO TEST .config IN $build\n";
return 0;
}
doprint "\n%%%%%%%% FAILED TO FIND SINGLE BAD CONFIG %%%%%%%%\n";
doprint "Hmm, can't make any more changes without making good == bad?\n";
doprint "Difference between good (+) and bad (-)\n";
foreach my $item (keys %bad_configs) {
if (!defined($good_configs{$item})) {
print_config "-", $bad_configs{$item};
}
}
foreach my $item (keys %good_configs) {
next if (!defined($bad_configs{$item}));
if ($good_configs{$item} ne $bad_configs{$item}) {
print_config_compare $good_configs{$item}, $bad_configs{$item};
}
}
foreach my $item (keys %good_configs) {
if (!defined($bad_configs{$item})) {
print_config "+", $good_configs{$item};
}
}
return -1;
}
sub config_bisect {
my ($good_config, $bad_config) = @_;
my $ret;
my %good_configs;
my %bad_configs;
my %tmp_configs;
doprint "Run good configs through make oldconfig\n";
assign_configs \%tmp_configs, $good_config;
create_config "$good_config", \%tmp_configs;
assign_configs \%good_configs, $output_config;
doprint "Run bad configs through make oldconfig\n";
assign_configs \%tmp_configs, $bad_config;
create_config "$bad_config", \%tmp_configs;
assign_configs \%bad_configs, $output_config;
save_config \%good_configs, $good_config;
save_config \%bad_configs, $bad_config;
return run_config_bisect \%good_configs, \%bad_configs;
}
while ($#ARGV >= 0) {
if ($ARGV[0] !~ m/^-/) {
last;
}
my $opt = shift @ARGV;
if ($opt eq "-b") {
$val = shift @ARGV;
if (!defined($val)) {
die "-b requires value\n";
}
$build = $val;
}
elsif ($opt eq "-l") {
$val = shift @ARGV;
if (!defined($val)) {
die "-l requires value\n";
}
$tree = $val;
}
elsif ($opt eq "-r") {
$reset_bisect = 1;
}
elsif ($opt eq "-h") {
usage;
}
else {
die "Unknown option $opt\n";
}
}
$build = $tree if (!defined($build));
$tree = expand_path $tree;
$build = expand_path $build;
if ( ! -d $tree ) {
die "$tree not a directory\n";
}
if ( ! -d $build ) {
die "$build not a directory\n";
}
usage if $#ARGV < 1;
if ($#ARGV == 1) {
$start = 1;
} elsif ($#ARGV == 2) {
$val = $ARGV[2];
if ($val ne "good" && $val ne "bad") {
die "Unknown command '$val', bust be either \"good\" or \"bad\"\n";
}
} else {
usage;
}
my $good_start = expand_path $ARGV[0];
my $bad_start = expand_path $ARGV[1];
my $good = "$good_start.tmp";
my $bad = "$bad_start.tmp";
$make = "make";
if ($build ne $tree) {
$make = "make O=$build"
}
$output_config = "$build/.config";
if ($start) {
if ( ! -f $good_start ) {
die "$good_start not found\n";
}
if ( ! -f $bad_start ) {
die "$bad_start not found\n";
}
if ( -f $good || -f $bad ) {
my $p = "";
if ( -f $good ) {
$p = "$good exists\n";
}
if ( -f $bad ) {
$p = "$p$bad exists\n";
}
if (!defined($reset_bisect)) {
if (!read_yn "${p}Overwrite and start new bisect anyway?") {
exit (-1);
}
}
}
run_command "cp $good_start $good" or die "failed to copy to $good\n";
run_command "cp $bad_start $bad" or die "failed to copy to $bad\n";
} else {
if ( ! -f $good ) {
die "Can not find file $good\n";
}
if ( ! -f $bad ) {
die "Can not find file $bad\n";
}
if ($val eq "good") {
run_command "cp $output_config $good" or die "failed to copy $output_config to $good\n";
} elsif ($val eq "bad") {
run_command "cp $output_config $bad" or die "failed to copy $output_config to $bad\n";
}
}
chdir $tree || die "can't change directory to $tree";
my $ret = config_bisect $good, $bad;
if (!$ret) {
exit(0);
}
if ($ret > 0) {
doprint "Cleaning temp files\n";
run_command "rm $good";
run_command "rm $bad";
exit(1);
} else {
doprint "See good and bad configs for details:\n";
doprint "good: $good\n";
doprint "bad: $bad\n";
doprint "%%%%%%%% FAILED TO FIND SINGLE BAD CONFIG %%%%%%%%\n";
}
exit(2);
@@ -0,0 +1,32 @@
This directory contains example configs to use ktest for various tasks.
The configs still need to be customized for your environment, but it
is broken up by task which makes it easier to understand how to set up
ktest.
The configs are based off of real working configs but have been modified
and commented to show more generic use cases that are more helpful for
developers.
crosstests.conf - this config shows an example of testing a git repo against
lots of different architectures. It only does build tests, but makes
it easy to compile test different archs. You can download the arch
cross compilers from:
https://kernel.org/pub/tools/crosstool/files/bin/x86_64/
test.conf - A generic example of a config. This is based on an actual config
used to perform real testing.
kvm.conf - A example of a config that is used to test a virtual guest running
on a host.
snowball.conf - An example config that was used to demo ktest.pl against
a snowball ARM board.
include/ - The include directory holds default configs that can be
included into other configs. This is a real use example that shows how
to reuse configs for various machines or set ups. The files here
are included by other config files, where the other config files define
options and variables that will make the included config work for the
given environment.
@@ -0,0 +1,59 @@
ftrace.event {
task.task_newtask {
filter = "pid < 128"
enable
}
kprobes.vfs_read {
probes = "vfs_read $arg1 $arg2"
filter = "common_pid < 200"
enable
}
synthetic.initcall_latency {
fields = "unsigned long func", "u64 lat"
hist {
keys = func.sym,lat
values = lat
sort = lat
}
}
initcall.initcall_start.hist {
keys = func;
var.ts0 = common_timestamp.usecs
}
initcall.initcall_finish.hist {
keys = func
var.lat = common_timestamp.usecs - $ts0
onmatch {
event = initcall.initcall_start
trace = initcall_latency, func, $lat
}
}
}
ftrace.instance {
foo {
tracer = "function"
ftrace.filters = "user_*"
cpumask = 1
options = nosym-addr
buffer_size = 512KB
trace_clock = mono
event.signal.signal_deliver.actions=snapshot
}
bar {
tracer = "function"
ftrace.filters = "kernel_*"
cpumask = 2
trace_clock = x86-tsc
}
}
ftrace.alloc_snapshot
kernel {
trace_options = sym-addr
trace_event = "initcall:*"
trace_buf_size = 1M
ftrace = function
ftrace_filter = "vfs*"
}
@@ -0,0 +1 @@
CONFIG_CMDLINE="bootconfig"
@@ -0,0 +1,15 @@
ftrace {
tracing_on = 0 # off by default
tracer = function_graph
event.kprobes {
start_event {
probes = "pci_proc_init"
actions = "traceon"
}
end_event {
probes = "pci_proc_init%return"
actions = "traceoff"
}
}
}
@@ -0,0 +1,33 @@
ftrace {
tracer = function_graph;
options = event-fork, sym-addr, stacktrace;
buffer_size = 1M;
alloc_snapshot;
trace_clock = global;
events = "task:task_newtask", "initcall:*";
event.sched.sched_process_exec {
filter = "pid < 128";
}
instance.bar {
event.kprobes {
myevent {
probes = "vfs_read $arg2 $arg3";
}
myevent2 {
probes = "vfs_write $arg2 +0($arg2):ustring $arg3";
}
myevent3 {
probes = "initrd_load";
}
enable
}
}
instance.foo {
tracer = function;
tracing_on = false;
};
}
kernel {
ftrace_dump_on_oops = "orig_cpu"
traceoff_on_warning
}
@@ -0,0 +1,84 @@
#!/bin/sh
cd /sys/kernel/tracing
compare_file() {
file="$1"
val="$2"
content=`cat $file`
if [ "$content" != "$val" ]; then
echo "FAILED: $file has '$content', expected '$val'"
exit 1
fi
}
compare_file_partial() {
file="$1"
val="$2"
content=`cat $file | sed -ne "/^$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not contain '$val'"
cat $file
exit 1
fi
}
file_contains() {
file=$1
val="$2"
if ! grep -q "$val" $file ; then
echo "FAILED: $file does not contain $val"
cat $file
exit 1
fi
}
compare_mask() {
file=$1
val="$2"
content=`cat $file | sed -ne "/^[0 ]*$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not have mask '$val'"
cat $file
exit 1
fi
}
compare_file "events/task/task_newtask/filter" "pid < 128"
compare_file "events/task/task_newtask/enable" "1"
compare_file "events/kprobes/vfs_read/filter" "common_pid < 200"
compare_file "events/kprobes/vfs_read/enable" "1"
compare_file_partial "events/synthetic/initcall_latency/trigger" "hist:keys=func.sym,lat:vals=hitcount,lat:sort=lat"
compare_file_partial "events/synthetic/initcall_latency/enable" "0"
compare_file_partial "events/initcall/initcall_start/trigger" "hist:keys=func:vals=hitcount:ts0=common_timestamp.usecs"
compare_file_partial "events/initcall/initcall_start/enable" "1"
compare_file_partial "events/initcall/initcall_finish/trigger" 'hist:keys=func:vals=hitcount:lat=common_timestamp.usecs-\$ts0:sort=hitcount:size=2048:clock=global:onmatch(initcall.initcall_start).trace(initcall_latency,func,\$lat)'
compare_file_partial "events/initcall/initcall_finish/enable" "1"
compare_file "instances/foo/current_tracer" "function"
file_contains "instances/foo/set_ftrace_filter" "^user"
compare_file "instances/foo/buffer_size_kb" "512"
compare_mask "instances/foo/tracing_cpumask" "1"
compare_file "instances/foo/options/sym-addr" "0"
file_contains "instances/foo/trace_clock" '\[mono\]'
compare_file_partial "instances/foo/events/signal/signal_deliver/trigger" "snapshot"
compare_file "instances/bar/current_tracer" "function"
file_contains "instances/bar/set_ftrace_filter" "^kernel"
compare_mask "instances/bar/tracing_cpumask" "2"
file_contains "instances/bar/trace_clock" '\[x86-tsc\]'
file_contains "snapshot" "Snapshot is allocated"
compare_file "options/sym-addr" "1"
compare_file "events/initcall/enable" "1"
compare_file "buffer_size_kb" "1027"
compare_file "current_tracer" "function"
file_contains "set_ftrace_filter" '^vfs'
exit 0
@@ -0,0 +1,61 @@
#!/bin/sh
cd /sys/kernel/tracing
compare_file() {
file="$1"
val="$2"
content=`cat $file`
if [ "$content" != "$val" ]; then
echo "FAILED: $file has '$content', expected '$val'"
exit 1
fi
}
compare_file_partial() {
file="$1"
val="$2"
content=`cat $file | sed -ne "/^$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not contain '$val'"
cat $file
exit 1
fi
}
file_contains() {
file=$1
val="$2"
if ! grep -q "$val" $file ; then
echo "FAILED: $file does not contain $val"
cat $file
exit 1
fi
}
compare_mask() {
file=$1
val="$2"
content=`cat $file | sed -ne "/^[0 ]*$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not have mask '$val'"
cat $file
exit 1
fi
}
compare_file "tracing_on" "0"
compare_file "current_tracer" "function_graph"
compare_file_partial "events/kprobes/start_event/enable" "1"
compare_file_partial "events/kprobes/start_event/trigger" "traceon"
file_contains "kprobe_events" 'start_event.*pci_proc_init'
compare_file_partial "events/kprobes/end_event/enable" "1"
compare_file_partial "events/kprobes/end_event/trigger" "traceoff"
file_contains "kprobe_events" '^r.*end_event.*pci_proc_init'
exit 0
@@ -0,0 +1,72 @@
#!/bin/sh
cd /sys/kernel/tracing
compare_file() {
file="$1"
val="$2"
content=`cat $file`
if [ "$content" != "$val" ]; then
echo "FAILED: $file has '$content', expected '$val'"
exit 1
fi
}
compare_file_partial() {
file="$1"
val="$2"
content=`cat $file | sed -ne "/^$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not contain '$val'"
cat $file
exit 1
fi
}
file_contains() {
file=$1
val="$2"
if ! grep -q "$val" $file ; then
echo "FAILED: $file does not contain $val"
cat $file
exit 1
fi
}
compare_mask() {
file=$1
val="$2"
content=`cat $file | sed -ne "/^[0 ]*$val/p"`
if [ -z "$content" ]; then
echo "FAILED: $file does not have mask '$val'"
cat $file
exit 1
fi
}
compare_file "current_tracer" "function_graph"
compare_file "options/event-fork" "1"
compare_file "options/sym-addr" "1"
compare_file "options/stacktrace" "1"
compare_file "buffer_size_kb" "1024"
file_contains "snapshot" "Snapshot is allocated"
file_contains "trace_clock" '\[global\]'
compare_file "events/initcall/enable" "1"
compare_file "events/task/task_newtask/enable" "1"
compare_file "events/sched/sched_process_exec/filter" "pid < 128"
compare_file "events/kprobes/enable" "1"
compare_file "instances/bar/events/kprobes/myevent/enable" "1"
compare_file "instances/bar/events/kprobes/myevent2/enable" "1"
compare_file "instances/bar/events/kprobes/myevent3/enable" "1"
compare_file "instances/foo/current_tracer" "function"
compare_file "instances/foo/tracing_on" "0"
compare_file "/proc/sys/kernel/ftrace_dump_on_oops" "2"
compare_file "/proc/sys/kernel/traceoff_on_warning" "1"
exit 0
@@ -0,0 +1,225 @@
#
# Example config for cross compiling
#
# In this config, it is expected that the tool chains from:
#
# https://kernel.org/pub/tools/crosstool/files/bin/x86_64/
#
# running on a x86_64 system have been downloaded and installed into:
#
# /usr/local/
#
# such that the compiler binaries are something like:
#
# /usr/local/gcc-4.5.2-nolibc/mips-linux/bin/mips-linux-gcc
#
# Some of the archs will use gcc-4.5.1 instead of gcc-4.5.2
# this config uses variables to differentiate them.
#
# Comments describe some of the options, but full descriptions of
# options are described in the samples.conf file.
# ${PWD} is defined by ktest.pl to be the directory that the user
# was in when they executed ktest.pl. It may be better to hardcode the
# path name here. THIS_DIR is the variable used through out the config file
# in case you want to change it.
THIS_DIR := ${PWD}
# Update the BUILD_DIR option to the location of your git repo you want to test.
BUILD_DIR = ${THIS_DIR}/linux.git
# The build will go into this directory. It will be created when you run the test.
OUTPUT_DIR = ${THIS_DIR}/cross-compile
# The build will be compiled with -j8
BUILD_OPTIONS = -j8
# The test will not stop when it hits a failure.
DIE_ON_FAILURE = 0
# If you want to have ktest.pl store the failure somewhere, uncomment this option
# and change the directory where ktest should store the failures.
#STORE_FAILURES = ${THIS_DIR}/failures
# The log file is stored in the OUTPUT_DIR called cross.log
# If you enable this, you need to create the OUTPUT_DIR. It wont be created for you.
LOG_FILE = ${OUTPUT_DIR}/cross.log
# The log file will be cleared each time you run ktest.
CLEAR_LOG = 1
# As some archs do not build with the defconfig, they have been marked
# to be ignored. If you want to test them anyway, change DO_FAILED to 1.
# If a test that has been marked as DO_FAILED passes, then you should change
# that test to be DO_DEFAULT
DO_FAILED := 0
DO_DEFAULT := 1
# By setting both DO_FAILED and DO_DEFAULT to zero, you can pick a single
# arch that you want to test. (uncomment RUN and chose your arch)
#RUN := arm
# At the bottom of the config file exists a bisect test. You can update that
# test and set DO_FAILED and DO_DEFAULT to zero, and uncomment this variable
# to run the bisect on the arch.
#RUN := bisect
# By default all tests will be running gcc 4.5.2. Some tests are using 4.5.1
# and they select that in the test.
# Note: GCC_VER is declared as on option and not a variable ('=' instead of ':=')
# This is important. A variable is used only in the config file and if it is set
# it stays that way for the rest of the config file until it is change again.
# Here we want GCC_VER to remain persistent and change for each test, as it is used in
# the MAKE_CMD. By using '=' instead of ':=' we achieve our goal.
GCC_VER = 4.5.2
MAKE_CMD = PATH=/usr/local/gcc-${GCC_VER}-nolibc/${CROSS}/bin:$PATH CROSS_COMPILE=${CROSS}- make ARCH=${ARCH}
# all tests are only doing builds.
TEST_TYPE = build
# If you want to add configs on top of the defconfig, you can add those configs into
# the add-config file and uncomment this option. This is useful if you want to test
# all cross compiles with PREEMPT set, or TRACING on, etc.
#ADD_CONFIG = ${THIS_DIR}/add-config
# All tests are using defconfig
BUILD_TYPE = defconfig
# The test names will have the arch and cross compiler used. This will be shown in
# the results.
TEST_NAME = ${ARCH} ${CROSS}
# alpha
TEST_START IF ${RUN} == alpha || ${DO_DEFAULT}
# Notice that CROSS and ARCH are also options and not variables (again '=' instead
# of ':='). This is because TEST_NAME and MAKE_CMD wil use them for each test.
# Only options are available during runs. Variables are only present in parsing the
# config file.
CROSS = alpha-linux
ARCH = alpha
# arm
TEST_START IF ${RUN} == arm || ${DO_DEFAULT}
CROSS = arm-unknown-linux-gnueabi
ARCH = arm
# ia64
TEST_START IF ${RUN} == ia64 || ${DO_DEFAULT}
CROSS = ia64-linux
ARCH = ia64
# m68k fails with error?
TEST_START IF ${RUN} == m68k || ${DO_DEFAULT}
CROSS = m68k-linux
ARCH = m68k
# mips64
TEST_START IF ${RUN} == mips || ${RUN} == mips64 || ${DO_DEFAULT}
CROSS = mips64-linux
ARCH = mips
# mips32
TEST_START IF ${RUN} == mips || ${RUN} == mips32 || ${DO_DEFAULT}
CROSS = mips-linux
ARCH = mips
# parisc64 failed?
TEST_START IF ${RUN} == hppa || ${RUN} == hppa64 || ${DO_FAILED}
CROSS = hppa64-linux
ARCH = parisc
# parisc
TEST_START IF ${RUN} == hppa || ${RUN} == hppa32 || ${DO_FAILED}
CROSS = hppa-linux
ARCH = parisc
# ppc
TEST_START IF ${RUN} == ppc || ${RUN} == ppc32 || ${DO_DEFAULT}
CROSS = powerpc-linux
ARCH = powerpc
# ppc64
TEST_START IF ${RUN} == ppc || ${RUN} == ppc64 || ${DO_DEFAULT}
CROSS = powerpc64-linux
ARCH = powerpc
# s390
TEST_START IF ${RUN} == s390 || ${DO_DEFAULT}
CROSS = s390x-linux
ARCH = s390
# sh
TEST_START IF ${RUN} == sh || ${DO_DEFAULT}
CROSS = sh4-linux
ARCH = sh
# sparc64
TEST_START IF ${RUN} == sparc || ${RUN} == sparc64 || ${DO_DEFAULT}
CROSS = sparc64-linux
ARCH = sparc64
# sparc
TEST_START IF ${RUN} == sparc || ${RUN} == sparc32 || ${DO_DEFAULT}
CROSS = sparc-linux
ARCH = sparc
# xtensa failed
TEST_START IF ${RUN} == xtensa || ${DO_FAILED}
CROSS = xtensa-linux
ARCH = xtensa
# UML
TEST_START IF ${RUN} == uml || ${DO_DEFAULT}
MAKE_CMD = make ARCH=um SUBARCH=x86_64
ARCH = uml
CROSS =
TEST_START IF ${RUN} == x86 || ${RUN} == i386 || ${DO_DEFAULT}
MAKE_CMD = make ARCH=i386
ARCH = i386
CROSS =
TEST_START IF ${RUN} == x86 || ${RUN} == x86_64 || ${DO_DEFAULT}
MAKE_CMD = make ARCH=x86_64
ARCH = x86_64
CROSS =
#################################
# This is a bisect if needed. You need to give it a MIN_CONFIG that
# will be the config file it uses. Basically, just copy the created defconfig
# for the arch someplace and point MIN_CONFIG to it.
TEST_START IF ${RUN} == bisect
MIN_CONFIG = ${THIS_DIR}/min-config
CROSS = s390x-linux
ARCH = s390
TEST_TYPE = bisect
BISECT_TYPE = build
BISECT_GOOD = v3.1
BISECT_BAD = v3.2
CHECKOUT = v3.2
#################################
# These defaults are needed to keep ktest.pl from complaining. They are
# ignored because the test does not go pass the build. No install or
# booting of the target images.
DEFAULTS
MACHINE = crosstest
SSH_USER = root
BUILD_TARGET = cross
TARGET_IMAGE = image
POWER_CYCLE = cycle
CONSOLE = console
LOCALVERSION = version
GRUB_MENU = grub
REBOOT_ON_ERROR = 0
POWEROFF_ON_ERROR = 0
POWEROFF_ON_SUCCESS = 0
REBOOT_ON_SUCCESS = 0
@@ -0,0 +1,90 @@
#
# This example shows the bisect tests (git bisect and config bisect)
#
# The config that includes this file may define a RUN_TEST
# variable that will tell this config what test to run.
# (what to set the TEST option to).
#
DEFAULTS IF NOT DEFINED RUN_TEST
# Requires that hackbench is in the PATH
RUN_TEST := ${SSH} hackbench 50
# Set TEST to 'bisect' to do a normal git bisect. You need
# to modify the options below to make it bisect the exact
# commits you are interested in.
#
TEST_START IF ${TEST} == bisect
TEST_TYPE = bisect
# You must set the commit that was considered good (git bisect good)
BISECT_GOOD = v3.3
# You must set the commit that was considered bad (git bisect bad)
BISECT_BAD = HEAD
# It's best to specify the branch to checkout before starting the bisect.
CHECKOUT = origin/master
# This can be build, boot, or test. Here we are doing a bisect
# that requires to run a test to know if the bisect was good or bad.
# The test should exit with 0 on good, non-zero for bad. But see
# the BISECT_RET_* options in samples.conf to override this.
BISECT_TYPE = test
TEST = ${RUN_TEST}
# It is usually a good idea to confirm that the GOOD and the BAD
# commits are truly good and bad respectively. Having BISECT_CHECK
# set to 1 will check both that the good commit works and the bad
# commit fails. If you only want to check one or the other,
# set BISECT_CHECK to 'good' or to 'bad'.
BISECT_CHECK = 1
#BISECT_CHECK = good
#BISECT_CHECK = bad
# Usually it's a good idea to specify the exact config you
# want to use throughout the entire bisect. Here we placed
# it in the directory we called ktest.pl from and named it
# 'config-bisect'.
MIN_CONFIG = ${THIS_DIR}/config-bisect
# By default, if we are doing a BISECT_TYPE = test run but the
# build or boot fails, ktest.pl will do a 'git bisect skip'.
# Uncomment the below option to make ktest stop testing on such
# an error.
#BISECT_SKIP = 0
# Now if you had BISECT_SKIP = 0 and the test fails, you can
# examine what happened and then do 'git bisect log > /tmp/replay'
# Set BISECT_REPLAY to /tmp/replay and ktest.pl will run the
# 'git bisect replay /tmp/replay' before continuing the bisect test.
#BISECT_REPLAY = /tmp/replay
# If you used BISECT_REPLAY after the bisect test failed, you may
# not want to continue the bisect on that commit that failed.
# By setting BISECT_START to a new commit. ktest.pl will checkout
# that commit after it has performed the 'git bisect replay' but
# before it continues running the bisect test.
#BISECT_START = 2545eb6198e7e1ec50daa0cfc64a4cdfecf24ec9
# Now if you don't trust ktest.pl to make the decisions for you, then
# set BISECT_MANUAL to 1. This will cause ktest.pl not to decide
# if the commit was good or bad. Instead, it will ask you to tell
# it if the current commit was good. In the mean time, you could
# take the result, load it on any machine you want. Run several tests,
# or whatever you feel like. Then, when you are happy, you can tell
# ktest if you think it was good or not and ktest.pl will continue
# the git bisect. You can even change what commit it is currently at.
#BISECT_MANUAL = 1
# One of the unique tests that ktest does is the config bisect.
# Currently (which hopefully will be fixed soon), the bad config
# must be a superset of the good config. This is because it only
# searches for a config that causes the target to fail. If the
# good config is not a subset of the bad config, or if the target
# fails because of a lack of a config, then it will not find
# the config for you.
TEST_START IF ${TEST} == config-bisect
TEST_TYPE = config_bisect
# set to build, boot, test
CONFIG_BISECT_TYPE = boot
# Set the config that is considered bad.
CONFIG_BISECT = ${THIS_DIR}/config-bad
# This config is optional. By default it uses the
# MIN_CONFIG as the good config.
CONFIG_BISECT_GOOD = ${THIS_DIR}/config-good
@@ -0,0 +1,69 @@
# bootconfig.conf
#
# Tests to test some bootconfig scripts
# List where on the target machine the initrd is used
INITRD := /boot/initramfs-test.img
# Install bootconfig on the target machine and define the path here.
BOOTCONFIG := /usr/bin/bootconfig
# Currenty we just build the .config in the BUILD_DIR
BUILD_TYPE := oldconfig
# Helper macro to run bootconfig on the target
# SSH is defined in include/defaults.conf
ADD_BOOTCONFIG := ${SSH} "${BOOTCONFIG} -d ${INITRD} && ${BOOTCONFIG} -a /tmp/${BOOTCONFIG_FILE} ${INITRD}"
# This copies a bootconfig script to the target and then will
# add it to the initrd. SSH_USER is defined in include/defaults.conf
# and MACHINE is defined in the example configs.
BOOTCONFIG_TEST_PREP = scp ${BOOTCONFIG_PATH}${BOOTCONFIG_FILE} ${SSH_USER}@${MACHINE}:/tmp && ${ADD_BOOTCONFIG}
# When a test is complete, remove the bootconfig from the initrd.
CLEAR_BOOTCONFIG := ${SSH} "${BOOTCONFIG} -d ${INITRD}"
# Run a verifier on the target after it had booted, to make sure that the
# bootconfig script did what it was expected to do
DO_TEST = scp ${BOOTCONFIG_PATH}${BOOTCONFIG_VERIFY} ${SSH_USER}@${MACHINE}:/tmp && ${SSH} /tmp/${BOOTCONFIG_VERIFY}
# Comment this out to not run the boot configs
RUN_BOOTCONFIG := 1
TEST_START IF DEFINED RUN_BOOTCONFIG
TEST_TYPE = test
TEST_NAME = bootconfig boottrace
# Just testing the bootconfig on initrd, no need to build the kernel
BUILD_TYPE = nobuild
BOOTCONFIG_FILE = boottrace.bconf
BOOTCONFIG_VERIFY = verify-boottrace.sh
ADD_CONFIG = ${ADD_CONFIG} ${BOOTCONFIG_PATH}/config-bootconfig
PRE_TEST = ${BOOTCONFIG_TEST_PREP}
PRE_TEST_DIE = 1
TEST = ${DO_TEST}
POST_TEST = ${CLEAR_BOOTCONFIG}
TEST_START IF DEFINED RUN_BOOTCONFIG
TEST_TYPE = test
TEST_NAME = bootconfig function graph
BUILD_TYPE = nobuild
BOOTCONFIG_FILE = functiongraph.bconf
BOOTCONFIG_VERIFY = verify-functiongraph.sh
ADD_CONFIG = ${ADD_CONFIG} ${BOOTCONFIG_PATH}/config-bootconfig
PRE_TEST = ${BOOTCONFIG_TEST_PREP}
PRE_TEST_DIE = 1
TEST = ${DO_TEST}
POST_TEST = ${CLEAR_BOOTCONFIG}
TEST_START IF DEFINED RUN_BOOTCONFIG
TEST_TYPE = test
TEST_NAME = bootconfig tracing
BUILD_TYPE = nobuild
BOOTCONFIG_FILE = tracing.bconf
BOOTCONFIG_VERIFY = verify-tracing.sh
ADD_CONFIG = ${ADD_CONFIG} ${BOOTCONFIG_PATH}/config-bootconfig
PRE_TEST = ${BOOTCONFIG_TEST_PREP}
PRE_TEST_DIE = 1
TEST = ${DO_TEST}
POST_TEST = ${CLEAR_BOOTCONFIG}
@@ -0,0 +1,157 @@
# This file holds defaults for most the tests. It defines the options that
# are most common to tests that are likely to be shared.
#
# Note, after including this file, a config file may override any option
# with a DEFAULTS OVERRIDE section.
#
# For those cases that use the same machine to boot a 64 bit
# and a 32 bit version. The MACHINE is the DNS name to get to the
# box (usually different if it was 64 bit or 32 bit) but the
# BOX here is defined as a variable that will be the name of the box
# itself. It is useful for calling scripts that will power cycle
# the box, as only one script needs to be created to power cycle
# even though the box itself has multiple operating systems on it.
# By default, BOX and MACHINE are the same.
DEFAULTS IF NOT DEFINED BOX
BOX := ${MACHINE}
# Consider each box as 64 bit box, unless the config including this file
# has defined BITS = 32
DEFAULTS IF NOT DEFINED BITS
BITS := 64
DEFAULTS
# THIS_DIR is used through out the configs and defaults to ${PWD} which
# is the directory that ktest.pl was called from.
THIS_DIR := ${PWD}
# to organize your configs, having each machine save their configs
# into a separate directly is useful.
CONFIG_DIR := ${THIS_DIR}/configs/${MACHINE}
# Reset the log before running each test.
CLEAR_LOG = 1
# As installing kernels usually requires root privilege, default the
# user on the target as root. It is also required that the target
# allows ssh to root from the host without asking for a password.
SSH_USER = root
# For accessing the machine, we will ssh to root@machine.
SSH := ssh ${SSH_USER}@${MACHINE}
# Update this. The default here is ktest will ssh to the target box
# and run a script called 'run-test' located on that box.
TEST = ${SSH} run-test
# Point build dir to the git repo you use
BUILD_DIR = ${THIS_DIR}/linux.git
# Each machine will have its own output build directory.
OUTPUT_DIR = ${THIS_DIR}/build/${MACHINE}
# Yes this config is focused on x86 (but ktest works for other archs too)
BUILD_TARGET = arch/x86/boot/bzImage
TARGET_IMAGE = /boot/vmlinuz-test
# have directory for the scripts to reboot and power cycle the boxes
SCRIPTS_DIR := ${THIS_DIR}/scripts
# You can have each box/machine have a script to power cycle it.
# Name your script <box>-cycle.
POWER_CYCLE = ${SCRIPTS_DIR}/${BOX}-cycle
# This script is used to power off the box.
POWER_OFF = ${SCRIPTS_DIR}/${BOX}-poweroff
# Keep your test kernels separate from your other kernels.
LOCALVERSION = -test
# The /boot/grub/menu.lst is searched for the line:
# title Test Kernel
# and ktest will use that kernel to reboot into.
# For grub2 or other boot loaders, you need to set BOOT_TYPE
# to 'script' and define other ways to load the kernel.
# See snowball.conf example.
#
GRUB_MENU = Test Kernel
# The kernel build will use this option.
BUILD_OPTIONS = -j8
# Keeping the log file with the output dir is convenient.
LOG_FILE = ${OUTPUT_DIR}/${MACHINE}.log
# Each box should have their own minum configuration
# See min-config.conf
MIN_CONFIG = ${CONFIG_DIR}/config-min
# For things like randconfigs, there may be configs you find that
# are already broken, or there may be some configs that you always
# want set. Uncomment ADD_CONFIG and point it to the make config files
# that set the configs you want to keep on (or off) in your build.
# ADD_CONFIG is usually something to add configs to all machines,
# where as, MIN_CONFIG is specific per machine.
#ADD_CONFIG = ${THIS_DIR}/config-broken ${THIS_DIR}/config-general
# To speed up reboots for bisects and patchcheck, instead of
# waiting 60 seconds for the console to be idle, if this line is
# seen in the console output, ktest will know the good kernel has
# finished rebooting and it will be able to continue the tests.
REBOOT_SUCCESS_LINE = ${MACHINE} login:
# The following is different ways to end the test.
# by setting the variable REBOOT to: none, error, fail or
# something else, ktest will power cycle or reboot the target box
# at the end of the tests.
#
# REBOOT := none
# Don't do anything at the end of the test.
#
# REBOOT := error
# Reboot the box if ktest detects an error
#
# REBOOT := fail
# Do not stop on failure, and after all tests are complete
# power off the box (for both success and error)
# This is good to run over a weekend and you don't want to waste
# electricity.
#
DEFAULTS IF ${REBOOT} == none
REBOOT_ON_SUCCESS = 0
REBOOT_ON_ERROR = 0
POWEROFF_ON_ERROR = 0
POWEROFF_ON_SUCCESS = 0
DEFAULTS ELSE IF ${REBOOT} == error
REBOOT_ON_SUCCESS = 0
REBOOT_ON_ERROR = 1
POWEROFF_ON_ERROR = 0
POWEROFF_ON_SUCCESS = 0
DEFAULTS ELSE IF ${REBOOT} == fail
REBOOT_ON_SUCCESS = 0
POWEROFF_ON_ERROR = 1
POWEROFF_ON_SUCCESS = 1
POWEROFF_AFTER_HALT = 120
DIE_ON_FAILURE = 0
# Store the failure information into this directory
# such as the .config, dmesg, and build log.
STORE_FAILURES = ${THIS_DIR}/failures
DEFAULTS ELSE
REBOOT_ON_SUCCESS = 1
REBOOT_ON_ERROR = 1
POWEROFF_ON_ERROR = 0
POWEROFF_ON_SUCCESS = 0
@@ -0,0 +1,60 @@
#
# This file has some examples for creating a MIN_CONFIG.
# (A .config file that is the minimum for a machine to boot, or
# to boot and make a network connection.)
#
# A MIN_CONFIG is very useful as it is the minimum configuration
# needed to boot a given machine. You can debug someone else's
# .config by only setting the configs in your MIN_CONFIG. The closer
# your MIN_CONFIG is to the true minimum set of configs needed to
# boot your machine, the closer the config you test with will be
# to the users config that had the failure.
#
# The make_min_config test allows you to create a MIN_CONFIG that
# is truly the minimum set of configs needed to boot a box.
#
# In this example, the final config will reside in
# ${CONFIG_DIR}/config-new-min and ${CONFIG_DIR}/config-new-min-net.
# Just move one to the location you have set for MIN_CONFIG.
#
# The first test creates a MIN_CONFIG that will be the minimum
# configuration to boot ${MACHINE} and be able to ssh to it.
#
# The second test creates a MIN_CONFIG that will only boot
# the target and most likely will not let you ssh to it. (Notice
# how the second test uses the first test's result to continue with.
# This is because the second test config is a subset of the first).
#
# The ${CONFIG_DIR}/config-skip (and -net) will hold the configs
# that ktest.pl found would not boot the target without them set.
# The config-new-min holds configs that ktest.pl could not test
# directly because another config that was needed to boot the box
# selected them. Sometimes it is possible that this file will hold
# the true minimum configuration. You can test to see if this is
# the case by running the boot test with BOOT_TYPE = allnoconfig and
# setting setting the MIN_CONFIG to ${CONFIG_DIR}/config-skip. If the
# machine still boots, then you can use the config-skip as your MIN_CONFIG.
#
# These tests can run for several hours (and perhaps days).
# It's OK to kill the test with a Ctrl^C. By restarting without
# modifying this config, ktest.pl will notice that the config-new-min(-net)
# exists, and will use that instead as the starting point.
# The USE_OUTPUT_MIN_CONFIG is set to 1 to keep ktest.pl from asking
# you if you want to use the OUTPUT_MIN_CONFIG as the starting point.
# By using the OUTPUT_MIN_CONFIG as the starting point will allow ktest.pl to
# start almost where it left off.
#
TEST_START IF ${TEST} == min-config
TEST_TYPE = make_min_config
OUTPUT_MIN_CONFIG = ${CONFIG_DIR}/config-new-min-net
IGNORE_CONFIG = ${CONFIG_DIR}/config-skip-net
MIN_CONFIG_TYPE = test
TEST = ${SSH} echo hi
USE_OUTPUT_MIN_CONFIG = 1
TEST_START IF ${TEST} == min-config && ${MULTI}
TEST_TYPE = make_min_config
OUTPUT_MIN_CONFIG = ${CONFIG_DIR}/config-new-min
IGNORE_CONFIG = ${CONFIG_DIR}/config-skip
MIN_CONFIG = ${CONFIG_DIR}/config-new-min-net
USE_OUTPUT_MIN_CONFIG = 1
@@ -0,0 +1,111 @@
# patchcheck.conf
#
# This contains a test that takes two git commits and will test each
# commit between the two. The build test will look at what files the
# commit has touched, and if any of those files produce a warning, then
# the build will fail.
# PATCH_START is the commit to begin with and PATCH_END is the commit
# to end with (inclusive). This is similar to doing a git rebase -i PATCH_START~1
# and then testing each commit and doing a git rebase --continue.
# You can use a SHA1, a git tag, or anything that git will accept for a checkout
PATCH_START := HEAD~3
PATCH_END := HEAD
# Use the oldconfig if build_type wasn't defined
DEFAULTS IF NOT DEFINED BUILD_TYPE
DO_BUILD_TYPE := oldconfig
DEFAULTS ELSE
DO_BUILD_TYPE := ${BUILD_TYPE}
DEFAULTS
# Change PATCH_CHECKOUT to be the branch you want to test. The test will
# do a git checkout of this branch before starting. Obviously both
# PATCH_START and PATCH_END must be in this branch (and PATCH_START must
# be contained by PATCH_END).
PATCH_CHECKOUT := test/branch
# Usually it's a good idea to have a set config to use for testing individual
# patches.
PATCH_CONFIG := ${CONFIG_DIR}/config-patchcheck
# Change PATCH_TEST to run some test for each patch. Each commit that is
# tested, after it is built and installed on the test machine, this command
# will be executed. Usually what is done is to ssh to the target box and
# run some test scripts. If you just want to boot test your patches
# comment PATCH_TEST out.
PATCH_TEST := ${SSH} "/usr/local/bin/ktest-test-script"
DEFAULTS IF DEFINED PATCH_TEST
PATCH_TEST_TYPE := test
DEFAULTS ELSE
PATCH_TEST_TYPE := boot
# If for some reason a file has a warning that one of your patches touch
# but you do not care about it, set IGNORE_WARNINGS to that commit(s)
# (space delimited)
#IGNORE_WARNINGS = 39eaf7ef884dcc44f7ff1bac803ca2a1dcf43544 6edb2a8a385f0cdef51dae37ff23e74d76d8a6ce
# Instead of just checking for warnings to files that are changed
# it can be advantageous to check for any new warnings. If a
# header file is changed, it could cause a warning in a file not
# touched by the commit. To detect these kinds of warnings, you
# can use the WARNINGS_FILE option.
#
# If the variable CREATE_WARNINGS_FILE is set, this config will
# enable the WARNINGS_FILE during the patchcheck test. Also,
# before running the patchcheck test, it will create the
# warnings file.
#
DEFAULTS IF DEFINED CREATE_WARNINGS_FILE
WARNINGS_FILE = ${OUTPUT_DIR}/warnings_file
TEST_START IF DEFINED CREATE_WARNINGS_FILE
# WARNINGS_FILE is already set by the DEFAULTS above
TEST_TYPE = make_warnings_file
# Checkout the commit before the patches to test,
# and record all the warnings that exist before the patches
# to test are added
CHECKOUT = ${PATCHCHECK_START}~1
# Force a full build
BUILD_NOCLEAN = 0
BUILD_TYPE = ${DO_BUILD_TYPE}
# If you are running a multi test, and the test failed on the first
# test but on, say the 5th patch. If you want to restart on the
# fifth patch, set PATCH_START1. This will make the first test start
# from this commit instead of the PATCH_START commit.
# Note, do not change this option. Just define PATCH_START1 in the
# top config (the one you pass to ktest.pl), and this will use it,
# otherwise it will just use PATCH_START if PATCH_START1 is not defined.
DEFAULTS IF NOT DEFINED PATCH_START1
PATCH_START1 := ${PATCH_START}
TEST_START IF ${TEST} == patchcheck
TEST_TYPE = patchcheck
MIN_CONFIG = ${PATCH_CONFIG}
TEST = ${PATCH_TEST}
PATCHCHECK_TYPE = ${PATCH_TEST_TYPE}
PATCHCHECK_START = ${PATCH_START1}
PATCHCHECK_END = ${PATCH_END}
CHECKOUT = ${PATCH_CHECKOUT}
BUILD_TYPE = ${DO_BUILD_TYPE}
TEST_START IF ${TEST} == patchcheck && ${MULTI}
TEST_TYPE = patchcheck
MIN_CONFIG = ${PATCH_CONFIG}
TEST = ${PATCH_TEST}
PATCHCHECK_TYPE = ${PATCH_TEST_TYPE}
PATCHCHECK_START = ${PATCH_START}
PATCHCHECK_END = ${PATCH_END}
CHECKOUT = ${PATCH_CHECKOUT}
# Use multi to test different compilers?
MAKE_CMD = CC=gcc-4.5.1 make
BUILD_TYPE = ${DO_BUILD_TYPE}
@@ -0,0 +1,74 @@
#
# This is an example of various tests that you can run
#
# The variable TEST can be of boot, build, randconfig, or test.
#
# Note that TEST is a variable created with ':=' and only exists
# throughout the config processing (not during the tests itself).
#
# The TEST option (defined with '=') is used to tell ktest.pl
# what test to run after a successful boot. The TEST option is
# persistent into the test runs.
#
# The config that includes this file may define a BOOT_TYPE
# variable that tells this config what type of boot test to run.
# If it's not defined, the below DEFAULTS will set the default
# to 'oldconfig'.
#
DEFAULTS IF NOT DEFINED BOOT_TYPE
BOOT_TYPE := oldconfig
# The config that includes this file may define a RUN_TEST
# variable that will tell this config what test to run.
# (what to set the TEST option to).
#
DEFAULTS IF NOT DEFINED RUN_TEST
# Requires that hackbench is in the PATH
RUN_TEST := ${SSH} hackbench 50
# If TEST is set to 'boot' then just build a kernel and boot
# the target.
TEST_START IF ${TEST} == boot
TEST_TYPE = boot
# Notice how we set the BUILD_TYPE option to the BOOT_TYPE variable.
BUILD_TYPE = ${BOOT_TYPE}
# Do not do a make mrproper.
BUILD_NOCLEAN = 1
# If you only want to build the kernel, and perhaps install
# and test it yourself, then just set TEST to build.
TEST_START IF ${TEST} == build
TEST_TYPE = build
BUILD_TYPE = ${BOOT_TYPE}
BUILD_NOCLEAN = 1
# Build, install, boot and test with a randconfg 10 times.
# It is important that you have set MIN_CONFIG in the config
# that includes this file otherwise it is likely that the
# randconfig will not have the necessary configs needed to
# boot your box. This version of the test requires a min
# config that has enough to make sure the target has network
# working.
TEST_START ITERATE 10 IF ${TEST} == randconfig
MIN_CONFIG = ${CONFIG_DIR}/config-min-net
TEST_TYPE = test
BUILD_TYPE = randconfig
TEST = ${RUN_TEST}
# This is the same as above, but only tests to a boot prompt.
# The MIN_CONFIG used here does not need to have networking
# working.
TEST_START ITERATE 10 IF ${TEST} == randconfig && ${MULTI}
TEST_TYPE = boot
BUILD_TYPE = randconfig
MIN_CONFIG = ${CONFIG_DIR}/config-min
MAKE_CMD = make
# This builds, installs, boots and tests the target.
TEST_START IF ${TEST} == test
TEST_TYPE = test
BUILD_TYPE = ${BOOT_TYPE}
TEST = ${RUN_TEST}
BUILD_NOCLEAN = 1
@@ -0,0 +1,93 @@
#
# This config is an example usage of ktest.pl with a kvm guest
#
# The guest is called 'Guest' and this would be something that
# could be run on the host to test a virtual machine target.
MACHINE = Guest
# Use virsh to read the serial console of the guest
CONSOLE = virsh console ${MACHINE}
# Use SIGKILL to terminate virsh console. We can't kill virsh console
# by the default signal, SIGINT.
CLOSE_CONSOLE_SIGNAL = KILL
#*************************************#
# This part is the same as test.conf #
#*************************************#
# The include files will set up the type of test to run. Just set TEST to
# which test you want to run.
#
# TESTS = patchcheck, randconfig, boot, test, config-bisect, bisect, min-config
#
# See the include/*.conf files that define these tests
#
TEST := patchcheck
# Some tests may have more than one test to run. Define MULTI := 1 to run
# the extra tests.
MULTI := 0
# In case you want to differentiate which type of system you are testing
BITS := 64
# REBOOT = none, error, fail, empty
# See include/defaults.conf
REBOOT := empty
# The defaults file will set up various settings that can be used by all
# machine configs.
INCLUDE include/defaults.conf
#*************************************#
# Now we are different from test.conf #
#*************************************#
# The example here assumes that Guest is running a Fedora release
# that uses dracut for its initfs. The POST_INSTALL will be executed
# after the install of the kernel and modules are complete.
#
POST_INSTALL = ${SSH} /sbin/dracut -f /boot/initramfs-test.img $KERNEL_VERSION
# Guests sometimes get stuck on reboot. We wait 3 seconds after running
# the reboot command and then do a full power-cycle of the guest.
# This forces the guest to restart.
#
POWERCYCLE_AFTER_REBOOT = 3
# We do the same after the halt command, but this time we wait 20 seconds.
POWEROFF_AFTER_HALT = 20
# As the defaults.conf file has a POWER_CYCLE option already defined,
# and options can not be defined in the same section more than once
# (all DEFAULTS sections are considered the same). We use the
# DEFAULTS OVERRIDE to tell ktest.pl to ignore the previous defined
# options, for the options set in the OVERRIDE section.
#
DEFAULTS OVERRIDE
# Instead of using the default POWER_CYCLE option defined in
# defaults.conf, we use virsh to cycle it. To do so, we destroy
# the guest, wait 5 seconds, and then start it up again.
# Crude, but effective.
#
POWER_CYCLE = virsh destroy ${MACHINE}; sleep 5; virsh start ${MACHINE}
DEFAULTS
# The following files each handle a different test case.
# Having them included allows you to set up more than one machine and share
# the same tests.
INCLUDE include/patchcheck.conf
INCLUDE include/tests.conf
INCLUDE include/bisect.conf
INCLUDE include/min-config.conf
INCLUDE include/bootconfig.conf
@@ -0,0 +1,53 @@
# This example was used to boot the snowball ARM board.
# See http://people.redhat.com/srostedt/ktest-embedded-2012/
# PWD is a ktest.pl variable that will result in the process working
# directory that ktest.pl is executed in.
# THIS_DIR is automatically assigned the PWD of the path that generated
# the config file. It is best to use this variable when assigning other
# directory paths within this directory. This allows you to easily
# move the test cases to other locations or to other machines.
#
THIS_DIR := /home/rostedt/work/demo/ktest-embed
LOG_FILE = ${OUTPUT_DIR}/snowball.log
CLEAR_LOG = 1
MAKE_CMD = PATH=/usr/local/gcc-4.5.2-nolibc/arm-unknown-linux-gnueabi/bin:$PATH CROSS_COMPILE=arm-unknown-linux-gnueabi- make ARCH=arm
ADD_CONFIG = ${THIS_DIR}/addconfig
SCP_TO_TARGET = echo "don't do scp"
TFTPBOOT := /var/lib/tftpboot
TFTPDEF := ${TFTPBOOT}/snowball-default
TFTPTEST := ${OUTPUT_DIR}/${BUILD_TARGET}
SWITCH_TO_GOOD = cp ${TFTPDEF} ${TARGET_IMAGE}
SWITCH_TO_TEST = cp ${TFTPTEST} ${TARGET_IMAGE}
# Define each test with TEST_START
# The config options below it will override the defaults
TEST_START SKIP
TEST_TYPE = boot
BUILD_TYPE = u8500_defconfig
BUILD_NOCLEAN = 1
TEST_START
TEST_TYPE = make_min_config
OUTPUT_MIN_CONFIG = ${THIS_DIR}/config.newmin
START_MIN_CONFIG = ${THIS_DIR}/config.orig
IGNORE_CONFIG = ${THIS_DIR}/config.ignore
BUILD_NOCLEAN = 1
DEFAULTS
LOCALVERSION = -test
POWER_CYCLE = echo use the thumb luke; read a
CONSOLE = cat ${THIS_DIR}/snowball-cat
REBOOT_TYPE = script
SSH_USER = root
BUILD_OPTIONS = -j8 uImage
BUILD_DIR = ${THIS_DIR}/linux.git
OUTPUT_DIR = ${THIS_DIR}/snowball-build
MACHINE = snowball
TARGET_IMAGE = /var/lib/tftpboot/snowball-image
BUILD_TARGET = arch/arm/boot/uImage
@@ -0,0 +1,62 @@
#
# Generic config for a machine
#
# Name your machine (the DNS name, what you ssh to)
MACHINE = foo
# BOX can be different than foo, if the machine BOX has
# multiple partitions with different systems installed. For example,
# you may have a i386 and x86_64 installation on a test box.
# If this is the case, MACHINE defines the way to connect to the
# machine, which may be different between which system the machine
# is booting into. BOX is used for the scripts to reboot and power cycle
# the machine, where it does not matter which system the machine boots into.
#
#BOX := bar
# Define a way to read the console
CONSOLE = stty -F /dev/ttyS0 115200 parodd; cat /dev/ttyS0
# The include files will set up the type of test to run. Just set TEST to
# which test you want to run.
#
# TESTS = patchcheck, randconfig, boot, test, config-bisect, bisect, min-config
#
# See the include/*.conf files that define these tests
#
TEST := patchcheck
# Some tests may have more than one test to run. Define MULTI := 1 to run
# the extra tests.
MULTI := 0
# In case you want to differentiate which type of system you are testing
BITS := 64
# REBOOT = none, error, fail, empty
# See include/defaults.conf
REBOOT := empty
# The defaults file will set up various settings that can be used by all
# machine configs.
INCLUDE include/defaults.conf
# In case you need to add a patch for a bisect or something
#PRE_BUILD = patch -p1 < ${THIS_DIR}/fix.patch
# Reset the repo after the build and remove all 'test' modules from the target
# Notice that DO_POST_BUILD is a variable (defined by ':=') and POST_BUILD
# is the option (defined by '=')
DO_POST_BUILD := git reset --hard
POST_BUILD = ${SSH} 'rm -rf /lib/modules/*-test*'; ${DO_POST_BUILD}
# The following files each handle a different test case.
# Having them included allows you to set up more than one machine and share
# the same tests.
INCLUDE include/patchcheck.conf
INCLUDE include/tests.conf
INCLUDE include/bisect.conf
INCLUDE include/min-config.conf
@@ -0,0 +1,137 @@
#
# This config is an example usage of ktest.pl with a vmware guest
#
# VMware Setup:
# -------------
# - Edit the Virtual Machine ("Edit virtual machine settings")
# - Add a Serial Port
# - You almost certainly want it set "Connect at power on"
# - Select "Use socket (named pipe)"
# - Select a name that you'll recognize, like 'ktestserialpipe'
# - From: Server
# - To: A Virtual Machine
# - Save
# - Make sure you note the name, it will be in the base directory of the
# virtual machine (where the "disks" are stored. The default
# is /var/lib/vmware/<virtual machine name>/<the name you entered above>
#
# - Make note of the path to the VM
# </End VMware setup>
#
# The guest is called 'Guest' and this would be something that
# could be run on the host to test a virtual machine target.
MACHINE = Guest
# Name of the serial pipe you set in the VMware settings
VMWARE_SERIAL_NAME = <the name you entered above>
# Define a variable of the name of the VM
# Noting this needs to be the name of the kmx file, and usually, the
# name of the directory that it's in. If the directory and name
# differ change the VMWARE_VM_DIR accordingly.
# Please ommit the .kmx extension
VMWARE_VM_NAME = <virtual machine name>
# VM dir name. This is usually the same as the virtual machine's name,
# but not always the case. Change if they differ
VMWARE_VM_DIR = ${VMWARE_VM_NAME}
# Base directory that the Virtual machine is contained in
# /var/lib/vmware is the default on Linux
VMWARE_VM_BASE_DIR = /var/lib/vmware/${VMWARE_VM_DIR}
# Use ncat to read the unix pipe. Anything that can read the Unix Pipe
# and output it's contents to stdout will work
CONSOLE = /usr/bin/ncat -U ${VMWARE_VM_BASE_DIR}/${VMWARE_SERIAL_NAME}
# Define what version of Workstation you are using
# This is used by vmrun to use the appropriate appripriate pieces to
# test this. In all likelihood you want 'ws' or 'player'
# Valid options:
# ws - Workstation (Windows or Linux host)
# fusion - Fusion (Mac host)
# player - Using VMware Player (Windows or Linux host)
# Note: vmrun has to run directly on the host machine
VMWARE_HOST_TYPE = ws
# VMware provides `vmrun` to allow you to do certain things to the virtual machine
# This should hard reset the VM and force a boot
VMWARE_POWER_CYCLE = /usr/bin/vmrun -T ${VMWARE_HOST_TYPE} reset ${VMWARE_VM_BASE_DIR}/${VMWARE_VM_NAME}.kmx nogui
#*************************************#
# This part is the same as test.conf #
#*************************************#
# The include files will set up the type of test to run. Just set TEST to
# which test you want to run.
#
# TESTS = patchcheck, randconfig, boot, test, config-bisect, bisect, min-config
#
# See the include/*.conf files that define these tests
#
TEST := patchcheck
# Some tests may have more than one test to run. Define MULTI := 1 to run
# the extra tests.
MULTI := 0
# In case you want to differentiate which type of system you are testing
BITS := 64
# REBOOT = none, error, fail, empty
# See include/defaults.conf
REBOOT := empty
# The defaults file will set up various settings that can be used by all
# machine configs.
INCLUDE include/defaults.conf
#*************************************#
# Now we are different from test.conf #
#*************************************#
# The example here assumes that Guest is running a Fedora release
# that uses dracut for its initfs. The POST_INSTALL will be executed
# after the install of the kernel and modules are complete.
#
POST_INSTALL = ${SSH} /sbin/dracut -f /boot/initramfs-test.img $KERNEL_VERSION
# Guests sometimes get stuck on reboot. We wait 3 seconds after running
# the reboot command and then do a full power-cycle of the guest.
# This forces the guest to restart.
#
POWERCYCLE_AFTER_REBOOT = 3
# We do the same after the halt command, but this time we wait 20 seconds.
POWEROFF_AFTER_HALT = 20
# As the defaults.conf file has a POWER_CYCLE option already defined,
# and options can not be defined in the same section more than once
# (all DEFAULTS sections are considered the same). We use the
# DEFAULTS OVERRIDE to tell ktest.pl to ignore the previous defined
# options, for the options set in the OVERRIDE section.
#
DEFAULTS OVERRIDE
# Instead of using the default POWER_CYCLE option defined in
# defaults.conf, we use virsh to cycle it. To do so, we destroy
# the guest, wait 5 seconds, and then start it up again.
# Crude, but effective.
#
POWER_CYCLE = ${VMWARE_POWER_CYCLE}
DEFAULTS
# The following files each handle a different test case.
# Having them included allows you to set up more than one machine and share
# the same tests.
INCLUDE include/patchcheck.conf
INCLUDE include/tests.conf
INCLUDE include/bisect.conf
INCLUDE include/min-config.conf
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,4 @@
# SPDX-License-Identifier: GPL-2.0-only
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
@@ -0,0 +1,61 @@
# This config enables as many tests as possible under UML.
# It is intended for use in continuous integration systems and similar for
# automated testing of as much as possible.
# The config is manually maintained, though it uses KUNIT_ALL_TESTS=y to enable
# any tests whose dependencies are already satisfied. Please feel free to add
# more options if they any new tests.
CONFIG_KUNIT=y
CONFIG_KUNIT_EXAMPLE_TEST=y
CONFIG_KUNIT_ALL_TESTS=y
CONFIG_FORTIFY_SOURCE=y
CONFIG_IIO=y
CONFIG_EXT4_FS=y
CONFIG_MSDOS_FS=y
CONFIG_VFAT_FS=y
CONFIG_PCI=y
CONFIG_USB4=y
CONFIG_I2C=y
CONFIG_NET=y
CONFIG_MCTP=y
CONFIG_MCTP_FLOWS=y
CONFIG_INET=y
CONFIG_MPTCP=y
CONFIG_NETDEVICES=y
CONFIG_WLAN=y
CONFIG_CFG80211=y
CONFIG_MAC80211=y
CONFIG_WLAN_VENDOR_INTEL=y
CONFIG_IWLWIFI=y
CONFIG_DAMON=y
CONFIG_DAMON_VADDR=y
CONFIG_DAMON_PADDR=y
CONFIG_REGMAP_BUILD=y
CONFIG_AUDIT=y
CONFIG_CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT=y
CONFIG_PRIME_NUMBERS=y
CONFIG_CRC_ENABLE_ALL_FOR_KUNIT=y
CONFIG_SECURITY=y
CONFIG_SECURITY_APPARMOR=y
CONFIG_SECURITY_LANDLOCK=y
CONFIG_SOUND=y
CONFIG_SND=y
CONFIG_SND_SOC=y
CONFIG_SND_SOC_TOPOLOGY_BUILD=y
CONFIG_SND_SOC_CS35L56_I2C=y
@@ -0,0 +1,7 @@
# Config options which are added to UML builds by default
# Enable pci, as a lot of tests require it.
CONFIG_KUNIT_UML_PCI=y
# Enable FORTIFY_SOURCE for wider checking.
CONFIG_FORTIFY_SOURCE=y
@@ -0,0 +1,11 @@
# This config fragment enables coverage on UML, which is different from the
# normal gcov used in other arches (no debugfs).
# Example usage:
# ./tools/testing/kunit/kunit.py run \
# --kunitconfig=tools/testing/kunit/configs/all_tests_uml.config \
# --kunitconfig=tools/testing/kunit/configs/coverage_uml.config
CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_INFO=y
CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
CONFIG_GCOV=y
@@ -0,0 +1,3 @@
CONFIG_KUNIT=y
CONFIG_KUNIT_EXAMPLE_TEST=y
CONFIG_KUNIT_ALL_TESTS=y
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-2.0
# bash completion support for KUnit
_kunit_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
_kunit()
{
local cur prev words cword
_init_completion || return
local script="${_kunit_dir}/kunit.py"
if [[ $cword -eq 1 && "$cur" != -* ]]; then
local cmds=$(${script} --list-cmds 2>/dev/null)
COMPREPLY=($(compgen -W "${cmds}" -- "$cur"))
return 0
fi
if [[ "$cur" == -* ]]; then
if [[ -n "${words[1]}" && "${words[1]}" != -* ]]; then
local opts=$(${script} ${words[1]} --list-opts 2>/dev/null)
COMPREPLY=($(compgen -W "${opts}" -- "$cur"))
return 0
else
local opts=$(${script} --list-opts 2>/dev/null)
COMPREPLY=($(compgen -W "${opts}" -- "$cur"))
return 0
fi
fi
}
complete -o default -F _kunit kunit.py
complete -o default -F _kunit kunit
complete -o default -F _kunit ./tools/testing/kunit/kunit.py
+688
View File
@@ -0,0 +1,688 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
#
# A thin wrapper on top of the KUnit Kernel
#
# Copyright (C) 2019, Google LLC.
# Author: Felix Guo <felixguoxiuping@gmail.com>
# Author: Brendan Higgins <brendanhiggins@google.com>
import argparse
import os
import re
import shlex
import sys
import time
assert sys.version_info >= (3, 7), "Python version is too old"
from dataclasses import dataclass
from enum import Enum, auto
from typing import Iterable, List, Optional, Sequence, Tuple
import kunit_json
import kunit_junit
import kunit_kernel
import kunit_parser
from kunit_printer import stdout, null_printer
class KunitStatus(Enum):
SUCCESS = auto()
CONFIG_FAILURE = auto()
BUILD_FAILURE = auto()
TEST_FAILURE = auto()
@dataclass
class KunitResult:
status: KunitStatus
elapsed_time: float
@dataclass
class KunitConfigRequest:
build_dir: str
make_options: Optional[List[str]]
@dataclass
class KunitBuildRequest(KunitConfigRequest):
jobs: int
@dataclass
class KunitParseRequest:
raw_output: Optional[str]
json: Optional[str]
junit: Optional[str]
summary: bool
failed: bool
@dataclass
class KunitExecRequest(KunitParseRequest):
build_dir: str
timeout: int
filter_glob: str
filter: str
filter_action: Optional[str]
kernel_args: Optional[List[str]]
run_isolated: Optional[str]
list_tests: bool
list_tests_attr: bool
list_suites: bool
@dataclass
class KunitRequest(KunitExecRequest, KunitBuildRequest):
pass
def get_kernel_root_path() -> str:
path = sys.argv[0] if not __file__ else __file__
parts = os.path.realpath(path).split('tools/testing/kunit')
if len(parts) != 2:
sys.exit(1)
return parts[0]
def config_tests(linux: kunit_kernel.LinuxSourceTree,
request: KunitConfigRequest) -> KunitResult:
stdout.print_with_timestamp('Configuring KUnit Kernel ...')
config_start = time.time()
success = linux.build_reconfig(request.build_dir, request.make_options)
config_end = time.time()
status = KunitStatus.SUCCESS if success else KunitStatus.CONFIG_FAILURE
return KunitResult(status, config_end - config_start)
def build_tests(linux: kunit_kernel.LinuxSourceTree,
request: KunitBuildRequest) -> KunitResult:
stdout.print_with_timestamp('Building KUnit Kernel ...')
build_start = time.time()
success = linux.build_kernel(request.jobs,
request.build_dir,
request.make_options)
build_end = time.time()
status = KunitStatus.SUCCESS if success else KunitStatus.BUILD_FAILURE
return KunitResult(status, build_end - build_start)
def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
request: KunitBuildRequest) -> KunitResult:
config_result = config_tests(linux, request)
if config_result.status != KunitStatus.SUCCESS:
return config_result
return build_tests(linux, request)
def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
args = ['kunit.action=list']
if request.kernel_args:
args.extend(request.kernel_args)
output = linux.run_kernel(args=args,
timeout=request.timeout,
filter_glob=request.filter_glob,
filter=request.filter,
filter_action=request.filter_action,
build_dir=request.build_dir)
lines = kunit_parser.extract_tap_lines(output)
# Hack! Drop the dummy TAP version header that the executor prints out.
lines.pop()
# Filter out any extraneous non-test output that might have gotten mixed in.
return [l for l in output if re.match(r'^[^\s.]+\.[^\s.]+$', l)]
def _list_tests_attr(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> Iterable[str]:
args = ['kunit.action=list_attr']
if request.kernel_args:
args.extend(request.kernel_args)
output = linux.run_kernel(args=args,
timeout=request.timeout,
filter_glob=request.filter_glob,
filter=request.filter,
filter_action=request.filter_action,
build_dir=request.build_dir)
lines = kunit_parser.extract_tap_lines(output)
# Hack! Drop the dummy TAP version header that the executor prints out.
lines.pop()
# Filter out any extraneous non-test output that might have gotten mixed in.
return lines
def _suites_from_test_list(tests: List[str]) -> List[str]:
"""Extracts all the suites from an ordered list of tests."""
suites = [] # type: List[str]
for t in tests:
parts = t.split('.', maxsplit=2)
if len(parts) != 2:
raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
suite, _ = parts
if not suites or suites[-1] != suite:
suites.append(suite)
return suites
def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
filter_globs = [request.filter_glob]
if request.list_tests:
output = _list_tests(linux, request)
for line in output:
print(line.rstrip())
return KunitResult(status=KunitStatus.SUCCESS, elapsed_time=0.0)
if request.list_tests_attr:
attr_output = _list_tests_attr(linux, request)
for line in attr_output:
print(line.rstrip())
return KunitResult(status=KunitStatus.SUCCESS, elapsed_time=0.0)
if request.list_suites:
tests = _list_tests(linux, request)
output = _suites_from_test_list(tests)
for line in output:
print(line.rstrip())
return KunitResult(status=KunitStatus.SUCCESS, elapsed_time=0.0)
if request.run_isolated:
tests = _list_tests(linux, request)
if request.run_isolated == 'test':
filter_globs = tests
elif request.run_isolated == 'suite':
filter_globs = _suites_from_test_list(tests)
# Apply the test-part of the user's glob, if present.
if '.' in request.filter_glob:
test_glob = request.filter_glob.split('.', maxsplit=2)[1]
filter_globs = [g + '.'+ test_glob for g in filter_globs]
metadata = kunit_json.Metadata(arch=linux.arch(), build_dir=request.build_dir, def_config='kunit_defconfig')
test_counts = kunit_parser.TestCounts()
exec_time = 0.0
for i, filter_glob in enumerate(filter_globs):
stdout.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
test_start = time.time()
run_result = linux.run_kernel(
args=request.kernel_args,
timeout=request.timeout,
filter_glob=filter_glob,
filter=request.filter,
filter_action=request.filter_action,
build_dir=request.build_dir)
_, test_result = parse_tests(request, metadata, run_result)
# run_kernel() doesn't block on the kernel exiting.
# That only happens after we get the last line of output from `run_result`.
# So exec_time here actually contains parsing + execution time, which is fine.
test_end = time.time()
exec_time += test_end - test_start
test_counts.add_subtest_counts(test_result.counts)
if len(filter_globs) == 1 and test_counts.crashed > 0:
bd = request.build_dir
print('The kernel seems to have crashed; you can decode the stack traces with:')
print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
kunit_status = _map_to_overall_status(test_counts.get_status())
return KunitResult(status=kunit_status, elapsed_time=exec_time)
def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
return KunitStatus.SUCCESS
return KunitStatus.TEST_FAILURE
def parse_tests(request: KunitParseRequest, metadata: kunit_json.Metadata, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
parse_start = time.time()
if request.raw_output:
# Treat unparsed results as one passing test.
fake_test = kunit_parser.Test()
fake_test.status = kunit_parser.TestStatus.SUCCESS
fake_test.counts.passed = 1
output: Iterable[str] = input_data
if request.raw_output == 'all' or request.raw_output == 'full':
pass
elif request.raw_output == 'kunit':
output = kunit_parser.extract_tap_lines(output)
for line in output:
print(line.rstrip())
parse_time = time.time() - parse_start
return KunitResult(KunitStatus.SUCCESS, parse_time), fake_test
default_printer = stdout
if request.summary or request.failed:
default_printer = null_printer
# Actually parse the test results.
test = kunit_parser.parse_run_tests(input_data, default_printer)
parse_time = time.time() - parse_start
if request.failed:
kunit_parser.print_test(test, request.failed, stdout)
kunit_parser.print_summary_line(test, stdout)
if request.json:
json_str = kunit_json.get_json_result(
test=test,
metadata=metadata)
if request.json == 'stdout':
print(json_str)
else:
with open(request.json, 'w') as f:
f.write(json_str)
stdout.print_with_timestamp("Test results stored in %s" %
os.path.abspath(request.json))
if request.junit:
if request.junit == 'stdout':
kunit_junit.print_junit_result(test=test)
else:
kunit_junit.write_junit_result(test=test,filename=request.junit)
stdout.print_with_timestamp(f"Test results stored in {os.path.abspath(request.junit)}")
if test.status != kunit_parser.TestStatus.SUCCESS:
return KunitResult(KunitStatus.TEST_FAILURE, parse_time), test
return KunitResult(KunitStatus.SUCCESS, parse_time), test
def run_tests(linux: kunit_kernel.LinuxSourceTree,
request: KunitRequest) -> KunitResult:
run_start = time.time()
config_result = config_tests(linux, request)
if config_result.status != KunitStatus.SUCCESS:
return config_result
build_result = build_tests(linux, request)
if build_result.status != KunitStatus.SUCCESS:
return build_result
exec_result = exec_tests(linux, request)
run_end = time.time()
stdout.print_with_timestamp((
'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
'building, %.3fs running\n') % (
run_end - run_start,
config_result.elapsed_time,
build_result.elapsed_time,
exec_result.elapsed_time))
return exec_result
# Problem:
# $ kunit.py run --json
# works as one would expect and prints the parsed test results as JSON.
# $ kunit.py run --json suite_name
# would *not* pass suite_name as the filter_glob and print as json.
# argparse will consider it to be another way of writing
# $ kunit.py run --json=suite_name
# i.e. it would run all tests, and dump the json to a `suite_name` file.
# So we hackily automatically rewrite --json => --json=stdout
pseudo_bool_flag_defaults = {
'--json': 'stdout',
'--junit': 'stdout',
'--raw_output': 'kunit',
}
def massage_argv(argv: Sequence[str]) -> Sequence[str]:
def massage_arg(arg: str) -> str:
if arg not in pseudo_bool_flag_defaults:
return arg
return f'{arg}={pseudo_bool_flag_defaults[arg]}'
return list(map(massage_arg, argv))
def get_default_jobs() -> int:
if sys.version_info >= (3, 13):
if (ncpu := os.process_cpu_count()) is not None:
return ncpu
raise RuntimeError("os.process_cpu_count() returned None")
# See https://github.com/python/cpython/blob/b61fece/Lib/os.py#L1175-L1186.
if sys.platform != "darwin":
return len(os.sched_getaffinity(0))
if (ncpu := os.cpu_count()) is not None:
return ncpu
raise RuntimeError("os.cpu_count() returned None")
def get_default_build_dir() -> str:
if 'KBUILD_OUTPUT' in os.environ:
return os.path.join(os.environ['KBUILD_OUTPUT'], '.kunit')
return '.kunit'
def add_completion_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--list-opts',
help=argparse.SUPPRESS,
action='store_true')
def add_root_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--list-cmds',
help=argparse.SUPPRESS,
action='store_true')
add_completion_opts(parser)
def add_common_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--build_dir',
help='As in the make command, it specifies the build '
'directory.',
type=str, default=get_default_build_dir(), metavar='DIR')
parser.add_argument('--make_options',
help='X=Y make option, can be repeated.',
action='append', metavar='X=Y')
parser.add_argument('--alltests',
help='Run all KUnit tests via tools/testing/kunit/configs/all_tests.config',
action='store_true')
parser.add_argument('--kunitconfig',
help='Path to Kconfig fragment that enables KUnit tests.'
' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
'will get automatically appended. If repeated, the files '
'blindly concatenated, which might not work in all cases.',
action='append', metavar='PATHS')
parser.add_argument('--kconfig_add',
help='Additional Kconfig options to append to the '
'.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
action='append', metavar='CONFIG_X=Y')
parser.add_argument('--arch',
help=('Specifies the architecture to run tests under. '
'The architecture specified here must match the '
'string passed to the ARCH make param, '
'e.g. i386, x86_64, arm, um, etc. Non-UML '
'architectures run on QEMU.'),
type=str, default='um', metavar='ARCH')
parser.add_argument('--cross_compile',
help=('Sets make\'s CROSS_COMPILE variable; it should '
'be set to a toolchain path prefix (the prefix '
'of gcc and other tools in your toolchain, for '
'example `sparc64-linux-gnu-` if you have the '
'sparc toolchain installed on your system, or '
'`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
'if you have downloaded the microblaze toolchain '
'from the 0-day website to a directory in your '
'home directory called `toolchains`).'),
metavar='PREFIX')
parser.add_argument('--qemu_config',
help=('Takes a path to a path to a file containing '
'a QemuArchParams object.'),
type=str, metavar='FILE')
parser.add_argument('--qemu_args',
help='Additional QEMU arguments, e.g. "-smp 8"',
action='append', metavar='')
add_completion_opts(parser)
def add_build_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--jobs',
help='As in the make command, "Specifies the number of '
'jobs (commands) to run simultaneously."',
type=int, default=get_default_jobs(), metavar='N')
def add_exec_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--timeout',
help='maximum number of seconds to allow for all tests '
'to run. This does not include time taken to build the '
'tests.',
type=int,
default=300,
metavar='SECONDS')
parser.add_argument('filter_glob',
help='Filter which KUnit test suites/tests run at '
'boot-time, e.g. list* or list*.*del_test',
type=str,
nargs='?',
default='',
metavar='filter_glob')
parser.add_argument('--filter',
help='Filter KUnit tests with attributes, '
'e.g. module=example or speed>slow',
type=str,
default='')
parser.add_argument('--filter_action',
help='If set to skip, filtered tests will be skipped, '
'e.g. --filter_action=skip. Otherwise they will not run.',
type=str,
choices=['skip'])
parser.add_argument('--kernel_args',
help='Kernel command-line parameters. Maybe be repeated',
action='append', metavar='')
parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
'individual suite/test. This is can be useful for debugging '
'a non-hermetic test, one that might pass/fail based on '
'what ran before it.',
type=str,
choices=['suite', 'test'])
parser.add_argument('--list_tests', help='If set, list all tests that will be '
'run.',
action='store_true')
parser.add_argument('--list_tests_attr', help='If set, list all tests and test '
'attributes.',
action='store_true')
parser.add_argument('--list_suites', help='If set, list all suites that will be '
'run.',
action='store_true')
def add_parse_opts(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--raw_output', help='If set don\'t parse output from kernel. '
'By default, filters to just KUnit output. Use '
'--raw_output=all to show everything',
type=str, nargs='?', const='all', default=None, choices=['all', 'full', 'kunit'])
parser.add_argument('--json',
nargs='?',
help='Prints parsed test results as JSON to stdout or a file if '
'a filename is specified. Does nothing if --raw_output is set.',
type=str, const='stdout', default=None, metavar='FILE')
parser.add_argument('--junit',
nargs='?',
help='Prints parsed test results as JUnit XML to stdout or a file if '
'a filename is specified. Does nothing if --raw_output is set.',
type=str, const='stdout', default=None, metavar='FILE')
parser.add_argument('--summary',
help='Prints only the summary line for parsed test results.'
'Does nothing if --raw_output is set.',
action='store_true')
parser.add_argument('--failed',
help='Prints only the failed parsed test results and summary line.'
'Does nothing if --raw_output is set.',
action='store_true')
def tree_from_args(cli_args: argparse.Namespace) -> kunit_kernel.LinuxSourceTree:
"""Returns a LinuxSourceTree based on the user's arguments."""
# Allow users to specify multiple arguments in one string, e.g. '-smp 8'
qemu_args: List[str] = []
if cli_args.qemu_args:
for arg in cli_args.qemu_args:
qemu_args.extend(shlex.split(arg))
kunitconfigs = cli_args.kunitconfig if cli_args.kunitconfig else []
if cli_args.alltests:
# Prepend so user-specified options take prio if we ever allow
# --kunitconfig options to have differing options.
kunitconfigs = [kunit_kernel.ALL_TESTS_CONFIG_PATH] + kunitconfigs
return kunit_kernel.LinuxSourceTree(cli_args.build_dir,
kunitconfig_paths=kunitconfigs,
kconfig_add=cli_args.kconfig_add,
arch=cli_args.arch,
cross_compile=cli_args.cross_compile,
qemu_config_path=cli_args.qemu_config,
extra_qemu_args=qemu_args)
def run_handler(cli_args: argparse.Namespace) -> None:
if not os.path.exists(cli_args.build_dir):
os.mkdir(cli_args.build_dir)
linux = tree_from_args(cli_args)
request = KunitRequest(build_dir=cli_args.build_dir,
make_options=cli_args.make_options,
jobs=cli_args.jobs,
raw_output=cli_args.raw_output,
json=cli_args.json,
junit=cli_args.junit,
summary=cli_args.summary,
failed=cli_args.failed,
timeout=cli_args.timeout,
filter_glob=cli_args.filter_glob,
filter=cli_args.filter,
filter_action=cli_args.filter_action,
kernel_args=cli_args.kernel_args,
run_isolated=cli_args.run_isolated,
list_tests=cli_args.list_tests,
list_tests_attr=cli_args.list_tests_attr,
list_suites=cli_args.list_suites)
result = run_tests(linux, request)
if result.status != KunitStatus.SUCCESS:
sys.exit(1)
def config_handler(cli_args: argparse.Namespace) -> None:
if cli_args.build_dir and (
not os.path.exists(cli_args.build_dir)):
os.mkdir(cli_args.build_dir)
linux = tree_from_args(cli_args)
request = KunitConfigRequest(build_dir=cli_args.build_dir,
make_options=cli_args.make_options)
result = config_tests(linux, request)
stdout.print_with_timestamp((
'Elapsed time: %.3fs\n') % (
result.elapsed_time))
if result.status != KunitStatus.SUCCESS:
sys.exit(1)
def build_handler(cli_args: argparse.Namespace) -> None:
linux = tree_from_args(cli_args)
request = KunitBuildRequest(build_dir=cli_args.build_dir,
make_options=cli_args.make_options,
jobs=cli_args.jobs)
result = config_and_build_tests(linux, request)
stdout.print_with_timestamp((
'Elapsed time: %.3fs\n') % (
result.elapsed_time))
if result.status != KunitStatus.SUCCESS:
sys.exit(1)
def exec_handler(cli_args: argparse.Namespace) -> None:
linux = tree_from_args(cli_args)
exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
build_dir=cli_args.build_dir,
json=cli_args.json,
junit=cli_args.junit,
summary=cli_args.summary,
failed=cli_args.failed,
timeout=cli_args.timeout,
filter_glob=cli_args.filter_glob,
filter=cli_args.filter,
filter_action=cli_args.filter_action,
kernel_args=cli_args.kernel_args,
run_isolated=cli_args.run_isolated,
list_tests=cli_args.list_tests,
list_tests_attr=cli_args.list_tests_attr,
list_suites=cli_args.list_suites)
result = exec_tests(linux, exec_request)
stdout.print_with_timestamp((
'Elapsed time: %.3fs\n') % (result.elapsed_time))
if result.status != KunitStatus.SUCCESS:
sys.exit(1)
def parse_handler(cli_args: argparse.Namespace) -> None:
if cli_args.file is None:
sys.stdin.reconfigure(errors='backslashreplace') # type: ignore
kunit_output = sys.stdin # type: Iterable[str]
else:
with open(cli_args.file, 'r', errors='backslashreplace') as f:
kunit_output = f.read().splitlines()
# We know nothing about how the result was created!
metadata = kunit_json.Metadata()
request = KunitParseRequest(raw_output=cli_args.raw_output,
json=cli_args.json,
junit=cli_args.junit,
summary=cli_args.summary,
failed=cli_args.failed)
result, _ = parse_tests(request, metadata, kunit_output)
if result.status != KunitStatus.SUCCESS:
sys.exit(1)
subcommand_handlers_map = {
'run': run_handler,
'config': config_handler,
'build': build_handler,
'exec': exec_handler,
'parse': parse_handler
}
def main(argv: Sequence[str]) -> None:
parser = argparse.ArgumentParser(
description='Helps writing and running KUnit tests.')
add_root_opts(parser)
subparser = parser.add_subparsers(dest='subcommand')
# The 'run' command will config, build, exec, and parse in one go.
run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
add_common_opts(run_parser)
add_build_opts(run_parser)
add_exec_opts(run_parser)
add_parse_opts(run_parser)
config_parser = subparser.add_parser('config',
help='Ensures that .config contains all of '
'the options in .kunitconfig')
add_common_opts(config_parser)
build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
add_common_opts(build_parser)
add_build_opts(build_parser)
exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
add_common_opts(exec_parser)
add_exec_opts(exec_parser)
add_parse_opts(exec_parser)
# The 'parse' option is special, as it doesn't need the kernel source
# (therefore there is no need for a build_dir, hence no add_common_opts)
# and the '--file' argument is not relevant to 'run', so isn't in
# add_parse_opts()
parse_parser = subparser.add_parser('parse',
help='Parses KUnit results from a file, '
'and parses formatted results.')
add_parse_opts(parse_parser)
parse_parser.add_argument('file',
help='Specifies the file to read results from.',
type=str, nargs='?', metavar='input_file')
add_completion_opts(parse_parser)
cli_args = parser.parse_args(massage_argv(argv))
if get_kernel_root_path():
os.chdir(get_kernel_root_path())
if cli_args.list_cmds:
print(" ".join(subparser.choices.keys()))
return
if cli_args.list_opts:
target_parser = subparser.choices.get(cli_args.subcommand)
if not target_parser:
target_parser = parser
# Accessing private attribute _option_string_actions to get
# the list of options. This is not a public API, but argparse
# does not provide a way to inspect options programmatically.
print(' '.join(target_parser._option_string_actions.keys()))
return
subcomand_handler = subcommand_handlers_map.get(cli_args.subcommand, None)
if subcomand_handler is None:
parser.print_help()
return
subcomand_handler(cli_args)
if __name__ == '__main__':
main(sys.argv[1:])
@@ -0,0 +1,108 @@
# SPDX-License-Identifier: GPL-2.0
#
# Builds a .config from a kunitconfig.
#
# Copyright (C) 2019, Google LLC.
# Author: Felix Guo <felixguoxiuping@gmail.com>
# Author: Brendan Higgins <brendanhiggins@google.com>
from dataclasses import dataclass
import re
from typing import Any, Dict, Iterable, List, Tuple
CONFIG_IS_NOT_SET_PATTERN = r'^# CONFIG_(\w+) is not set$'
CONFIG_PATTERN = r'^CONFIG_(\w+)=(\S+|".*")$'
@dataclass(frozen=True)
class KconfigEntry:
name: str
value: str
def __str__(self) -> str:
if self.value == 'n':
return f'# CONFIG_{self.name} is not set'
return f'CONFIG_{self.name}={self.value}'
class KconfigParseError(Exception):
"""Error parsing Kconfig defconfig or .config."""
class Kconfig:
"""Represents defconfig or .config specified using the Kconfig language."""
def __init__(self) -> None:
self._entries = {} # type: Dict[str, str]
def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return False
return self._entries == other._entries
def __repr__(self) -> str:
return ','.join(str(e) for e in self.as_entries())
def as_entries(self) -> Iterable[KconfigEntry]:
for name, value in self._entries.items():
yield KconfigEntry(name, value)
def add_entry(self, name: str, value: str) -> None:
self._entries[name] = value
def is_subset_of(self, other: 'Kconfig') -> bool:
for name, value in self._entries.items():
b = other._entries.get(name)
if b is None:
if value == 'n':
continue
return False
if value != b:
return False
return True
def conflicting_options(self, other: 'Kconfig') -> List[Tuple[KconfigEntry, KconfigEntry]]:
diff = [] # type: List[Tuple[KconfigEntry, KconfigEntry]]
for name, value in self._entries.items():
b = other._entries.get(name)
if b and value != b:
pair = (KconfigEntry(name, value), KconfigEntry(name, b))
diff.append(pair)
return diff
def merge_in_entries(self, other: 'Kconfig') -> None:
for name, value in other._entries.items():
self._entries[name] = value
def write_to_file(self, path: str) -> None:
with open(path, 'a+') as f:
for e in self.as_entries():
f.write(str(e) + '\n')
def parse_file(path: str) -> Kconfig:
with open(path, 'r') as f:
return parse_from_string(f.read())
def parse_from_string(blob: str) -> Kconfig:
"""Parses a string containing Kconfig entries."""
kconfig = Kconfig()
is_not_set_matcher = re.compile(CONFIG_IS_NOT_SET_PATTERN)
config_matcher = re.compile(CONFIG_PATTERN)
for line in blob.split('\n'):
line = line.strip()
if not line:
continue
match = config_matcher.match(line)
if match:
kconfig.add_entry(match.group(1), match.group(2))
continue
empty_match = is_not_set_matcher.match(line)
if empty_match:
kconfig.add_entry(empty_match.group(1), 'n')
continue
if line[0] == '#':
continue
raise KconfigParseError('Failed to parse: ' + line)
return kconfig
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: GPL-2.0
#
# Generates JSON from KUnit results according to
# KernelCI spec: https://github.com/kernelci/kernelci-doc/wiki/Test-API
#
# Copyright (C) 2020, Google LLC.
# Author: Heidi Fahim <heidifahim@google.com>
from dataclasses import dataclass
import json
from typing import Any, Dict
from kunit_parser import Test, TestStatus
@dataclass
class Metadata:
"""Stores metadata about this run to include in get_json_result()."""
arch: str = ''
def_config: str = ''
build_dir: str = ''
JsonObj = Dict[str, Any]
_status_map: Dict[TestStatus, str] = {
TestStatus.SUCCESS: "PASS",
TestStatus.SKIPPED: "SKIP",
TestStatus.TEST_CRASHED: "ERROR",
}
def _get_group_json(test: Test, common_fields: JsonObj) -> JsonObj:
sub_groups = [] # List[JsonObj]
test_cases = [] # List[JsonObj]
for subtest in test.subtests:
if subtest.subtests:
sub_group = _get_group_json(subtest, common_fields)
sub_groups.append(sub_group)
continue
status = _status_map.get(subtest.status, "FAIL")
test_cases.append({"name": subtest.name, "status": status})
test_counts = test.counts
counts_json = {
"tests": test_counts.total(),
"passed": test_counts.passed,
"failed": test_counts.failed,
"crashed": test_counts.crashed,
"skipped": test_counts.skipped,
"errors": test_counts.errors,
}
test_group = {
"name": test.name,
"sub_groups": sub_groups,
"test_cases": test_cases,
"misc": counts_json
}
test_group.update(common_fields)
return test_group
def get_json_result(test: Test, metadata: Metadata) -> str:
common_fields = {
"arch": metadata.arch,
"defconfig": metadata.def_config,
"build_environment": metadata.build_dir,
"lab_name": None,
"kernel": None,
"job": None,
"git_branch": "kselftest",
}
test_group = _get_group_json(test, common_fields)
test_group["name"] = "KUnit Test Group"
return json.dumps(test_group, indent=4)
@@ -0,0 +1,61 @@
# SPDX-License-Identifier: GPL-2.0
#
# Generates JUnit XML files from KUnit test results
#
# Copyright (C) 2026, Google LLC and David Gow.
from xml.sax.saxutils import quoteattr, XMLGenerator
import xml.etree.ElementTree as ET
from kunit_parser import Test, TestStatus
from typing import Optional
# Get a string representing a tes suite (including subtests) in JUnit XML
def get_test_suite(test: Test, parent: Optional[ET.Element]) -> ET.Element:
suite_attrs = {
'name': test.name,
'tests': str(test.counts.total()),
'failures': str(test.counts.failed),
'skipped': str(test.counts.skipped),
'errors': str(test.counts.crashed + test.counts.errors),
}
if parent is not None:
test_suite_element = ET.SubElement(parent, 'testsuite', suite_attrs)
else:
test_suite_element = ET.Element('testsuite', suite_attrs)
for subtest in test.subtests:
if subtest.subtests:
get_test_suite(subtest, test_suite_element)
continue
test_case_element = ET.SubElement(test_suite_element, 'testcase', {'name': subtest.name})
if subtest.status == TestStatus.FAILURE:
ET.SubElement(test_case_element, 'failure', {}).text = 'Test Failed'
elif subtest.status == TestStatus.SKIPPED:
ET.SubElement(test_case_element, 'skipped', {}).text = subtest.skip_reason
elif subtest.status == TestStatus.TEST_CRASHED:
ET.SubElement(test_case_element, 'error', {}).text = 'Test Crashed'
if subtest.log:
ET.SubElement(test_case_element, 'system-out', {}).text = "\n".join(subtest.log)
return test_suite_element
# Get a string for an entire XML file for the test structure starting at test
def get_junit_result(test: Test) -> str:
root_element = get_test_suite(test, None)
ET.indent(root_element)
return ET.tostring(root_element, encoding="unicode", xml_declaration=True)
# Print a JUnit result to stdout.
def print_junit_result(test: Test) -> None:
root_element = get_test_suite(test, None)
ET.indent(root_element)
ET.dump(root_element)
# Write an entire XML file for the test structure starting at test
def write_junit_result(test: Test, filename: str) -> None:
root_element = get_test_suite(test, None)
ET.indent(root_element)
root_et = ET.ElementTree(root_element)
root_et.write(filename, encoding='utf-8', xml_declaration=True)
@@ -0,0 +1,409 @@
# SPDX-License-Identifier: GPL-2.0
#
# Runs UML kernel, collects output, and handles errors.
#
# Copyright (C) 2019, Google LLC.
# Author: Felix Guo <felixguoxiuping@gmail.com>
# Author: Brendan Higgins <brendanhiggins@google.com>
import importlib.abc
import importlib.util
import logging
import subprocess
import os
import shlex
import shutil
import signal
import sys
import threading
from typing import Iterator, List, Optional, Tuple, Any
from types import FrameType
import kunit_config
import qemu_config
KCONFIG_PATH = '.config'
KUNITCONFIG_PATH = '.kunitconfig'
OLD_KUNITCONFIG_PATH = 'last_used_kunitconfig'
DEFAULT_KUNITCONFIG_PATH = 'tools/testing/kunit/configs/default.config'
ALL_TESTS_CONFIG_PATH = 'tools/testing/kunit/configs/all_tests.config'
UML_KCONFIG_PATH = 'tools/testing/kunit/configs/arch_uml.config'
OUTFILE_PATH = 'test.log'
ABS_TOOL_PATH = os.path.abspath(os.path.dirname(__file__))
QEMU_CONFIGS_DIR = os.path.join(ABS_TOOL_PATH, 'qemu_configs')
class ConfigError(Exception):
"""Represents an error trying to configure the Linux kernel."""
class BuildError(Exception):
"""Represents an error trying to build the Linux kernel."""
class LinuxSourceTreeOperations:
"""An abstraction over command line operations performed on a source tree."""
def __init__(self, linux_arch: str, cross_compile: Optional[str]):
self._linux_arch = linux_arch
self._cross_compile = cross_compile
def make_mrproper(self) -> None:
try:
subprocess.check_output(['make', 'mrproper'], stderr=subprocess.STDOUT)
except OSError as e:
raise ConfigError('Could not call make command: ' + str(e))
except subprocess.CalledProcessError as e:
raise ConfigError(e.output.decode())
def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
return base_kunitconfig
def make_olddefconfig(self, build_dir: str, make_options: Optional[List[str]]) -> None:
command = ['make', 'ARCH=' + self._linux_arch, 'O=' + build_dir, 'olddefconfig']
if self._cross_compile:
command += ['CROSS_COMPILE=' + self._cross_compile]
if make_options:
command.extend(make_options)
print('Populating config with:\n$', ' '.join(command))
try:
subprocess.check_output(command, stderr=subprocess.STDOUT)
except OSError as e:
raise ConfigError('Could not call make command: ' + str(e))
except subprocess.CalledProcessError as e:
raise ConfigError(e.output.decode())
def make(self, jobs: int, build_dir: str, make_options: Optional[List[str]]) -> None:
command = ['make', 'all', 'compile_commands.json', 'scripts_gdb',
'ARCH=' + self._linux_arch, 'O=' + build_dir, '--jobs=' + str(jobs)]
if make_options:
command.extend(make_options)
if self._cross_compile:
command += ['CROSS_COMPILE=' + self._cross_compile]
print('Building with:\n$', ' '.join(command))
try:
proc = subprocess.Popen(command,
stderr=subprocess.PIPE,
stdout=subprocess.DEVNULL)
except OSError as e:
raise BuildError('Could not call execute make: ' + str(e))
except subprocess.CalledProcessError as e:
raise BuildError(e.output)
_, stderr = proc.communicate()
if proc.returncode != 0:
raise BuildError(stderr.decode())
if stderr: # likely only due to build warnings
print(stderr.decode())
def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
raise RuntimeError('not implemented!')
class LinuxSourceTreeOperationsQemu(LinuxSourceTreeOperations):
def __init__(self, qemu_arch_params: qemu_config.QemuArchParams, cross_compile: Optional[str]):
super().__init__(linux_arch=qemu_arch_params.linux_arch,
cross_compile=cross_compile)
self._kconfig = qemu_arch_params.kconfig
self._qemu_arch = qemu_arch_params.qemu_arch
self._kernel_path = qemu_arch_params.kernel_path
self._kernel_command_line = qemu_arch_params.kernel_command_line
if 'kunit_shutdown=' not in self._kernel_command_line:
self._kernel_command_line += ' kunit_shutdown=reboot'
self._extra_qemu_params = qemu_arch_params.extra_qemu_params
self._serial = qemu_arch_params.serial
def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
kconfig = kunit_config.parse_from_string(self._kconfig)
kconfig.merge_in_entries(base_kunitconfig)
return kconfig
def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
kernel_path = os.path.join(build_dir, self._kernel_path)
qemu_command = ['qemu-system-' + self._qemu_arch,
'-nodefaults',
'-m', '1024',
'-kernel', kernel_path,
'-append', ' '.join(params + [self._kernel_command_line]),
'-no-reboot',
'-nographic',
'-accel', 'kvm',
'-accel', 'hvf',
'-accel', 'tcg',
'-serial', self._serial] + self._extra_qemu_params
# Note: shlex.join() does what we want, but requires python 3.8+.
print('Running tests with:\n$', ' '.join(shlex.quote(arg) for arg in qemu_command))
return subprocess.Popen(qemu_command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True, errors='backslashreplace')
class LinuxSourceTreeOperationsUml(LinuxSourceTreeOperations):
"""An abstraction over command line operations performed on a source tree."""
def __init__(self, cross_compile: Optional[str]=None):
super().__init__(linux_arch='um', cross_compile=cross_compile)
def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
kconfig = kunit_config.parse_file(UML_KCONFIG_PATH)
kconfig.merge_in_entries(base_kunitconfig)
return kconfig
def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
"""Runs the Linux UML binary. Must be named 'linux'."""
linux_bin = os.path.join(build_dir, 'linux')
params.extend(['mem=1G', 'console=tty', 'kunit_shutdown=halt'])
print('Running tests with:\n$', linux_bin, ' '.join(shlex.quote(arg) for arg in params))
return subprocess.Popen([linux_bin] + params,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True, errors='backslashreplace')
def get_kconfig_path(build_dir: str) -> str:
return os.path.join(build_dir, KCONFIG_PATH)
def get_kunitconfig_path(build_dir: str) -> str:
return os.path.join(build_dir, KUNITCONFIG_PATH)
def get_old_kunitconfig_path(build_dir: str) -> str:
return os.path.join(build_dir, OLD_KUNITCONFIG_PATH)
def get_parsed_kunitconfig(build_dir: str,
kunitconfig_paths: Optional[List[str]]=None) -> kunit_config.Kconfig:
if not kunitconfig_paths:
path = get_kunitconfig_path(build_dir)
if not os.path.exists(path):
shutil.copyfile(DEFAULT_KUNITCONFIG_PATH, path)
return kunit_config.parse_file(path)
merged = kunit_config.Kconfig()
for path in kunitconfig_paths:
if os.path.isdir(path):
path = os.path.join(path, KUNITCONFIG_PATH)
if not os.path.exists(path):
raise ConfigError(f'Specified kunitconfig ({path}) does not exist')
partial = kunit_config.parse_file(path)
diff = merged.conflicting_options(partial)
if diff:
diff_str = '\n\n'.join(f'{a}\n vs from {path}\n{b}' for a, b in diff)
raise ConfigError(f'Multiple values specified for {len(diff)} options in kunitconfig:\n{diff_str}')
merged.merge_in_entries(partial)
return merged
def get_outfile_path(build_dir: str) -> str:
return os.path.join(build_dir, OUTFILE_PATH)
def _default_qemu_config_path(arch: str) -> str:
config_path = os.path.join(QEMU_CONFIGS_DIR, arch + '.py')
if os.path.isfile(config_path):
return config_path
options = [f[:-3] for f in os.listdir(QEMU_CONFIGS_DIR) if f.endswith('.py')]
if arch == 'help':
print('um')
for option in options:
print(option)
sys.exit()
raise ConfigError(arch + ' is not a valid arch, options are ' + str(sorted(options)))
def _get_qemu_ops(config_path: str,
extra_qemu_args: Optional[List[str]],
cross_compile: Optional[str]) -> Tuple[str, LinuxSourceTreeOperations]:
# The module name/path has very little to do with where the actual file
# exists (I learned this through experimentation and could not find it
# anywhere in the Python documentation).
#
# Basically, we completely ignore the actual file location of the config
# we are loading and just tell Python that the module lives in the
# QEMU_CONFIGS_DIR for import purposes regardless of where it actually
# exists as a file.
module_path = '.' + os.path.join(os.path.basename(QEMU_CONFIGS_DIR), os.path.basename(config_path))
spec = importlib.util.spec_from_file_location(module_path, config_path)
assert spec is not None
config = importlib.util.module_from_spec(spec)
# See https://github.com/python/typeshed/pull/2626 for context.
assert isinstance(spec.loader, importlib.abc.Loader)
spec.loader.exec_module(config)
if not hasattr(config, 'QEMU_ARCH'):
raise ValueError('qemu_config module missing "QEMU_ARCH": ' + config_path)
params: qemu_config.QemuArchParams = config.QEMU_ARCH
if extra_qemu_args:
params.extra_qemu_params.extend(extra_qemu_args)
return params.linux_arch, LinuxSourceTreeOperationsQemu(
params, cross_compile=cross_compile)
class LinuxSourceTree:
"""Represents a Linux kernel source tree with KUnit tests."""
def __init__(
self,
build_dir: str,
kunitconfig_paths: Optional[List[str]]=None,
kconfig_add: Optional[List[str]]=None,
arch: Optional[str]=None,
cross_compile: Optional[str]=None,
qemu_config_path: Optional[str]=None,
extra_qemu_args: Optional[List[str]]=None) -> None:
signal.signal(signal.SIGINT, self.signal_handler)
if qemu_config_path:
self._arch, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
else:
self._arch = 'um' if arch is None else arch
if self._arch == 'um':
self._ops = LinuxSourceTreeOperationsUml(cross_compile=cross_compile)
else:
qemu_config_path = _default_qemu_config_path(self._arch)
_, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
self._kconfig = get_parsed_kunitconfig(build_dir, kunitconfig_paths)
if kconfig_add:
kconfig = kunit_config.parse_from_string('\n'.join(kconfig_add))
self._kconfig.merge_in_entries(kconfig)
self._process : Optional[subprocess.Popen[Any]] = None
def arch(self) -> str:
return self._arch
def clean(self) -> bool:
try:
self._ops.make_mrproper()
except ConfigError as e:
logging.error(e)
return False
return True
def validate_config(self, build_dir: str) -> bool:
kconfig_path = get_kconfig_path(build_dir)
validated_kconfig = kunit_config.parse_file(kconfig_path)
if self._kconfig.is_subset_of(validated_kconfig):
return True
missing = set(self._kconfig.as_entries()) - set(validated_kconfig.as_entries())
message = 'Not all Kconfig options selected in kunitconfig were in the generated .config.\n' \
'This is probably due to unsatisfied dependencies.\n' \
'Missing: ' + ', '.join(str(e) for e in missing)
if self._arch == 'um':
message += '\nNote: many Kconfig options aren\'t available on UML. You can try running ' \
'on a different architecture with something like "--arch=x86_64".'
logging.error(message)
return False
def build_config(self, build_dir: str, make_options: Optional[List[str]]) -> bool:
kconfig_path = get_kconfig_path(build_dir)
if build_dir and not os.path.exists(build_dir):
os.mkdir(build_dir)
try:
self._kconfig = self._ops.make_arch_config(self._kconfig)
self._kconfig.write_to_file(kconfig_path)
self._ops.make_olddefconfig(build_dir, make_options)
except ConfigError as e:
logging.error(e)
return False
if not self.validate_config(build_dir):
return False
old_path = get_old_kunitconfig_path(build_dir)
if os.path.exists(old_path):
os.remove(old_path) # write_to_file appends to the file
self._kconfig.write_to_file(old_path)
return True
def _kunitconfig_changed(self, build_dir: str) -> bool:
old_path = get_old_kunitconfig_path(build_dir)
if not os.path.exists(old_path):
return True
old_kconfig = kunit_config.parse_file(old_path)
return old_kconfig != self._kconfig
def build_reconfig(self, build_dir: str, make_options: Optional[List[str]]) -> bool:
"""Creates a new .config if it is not a subset of the .kunitconfig."""
kconfig_path = get_kconfig_path(build_dir)
if not os.path.exists(kconfig_path):
print('Generating .config ...')
return self.build_config(build_dir, make_options)
existing_kconfig = kunit_config.parse_file(kconfig_path)
self._kconfig = self._ops.make_arch_config(self._kconfig)
if self._kconfig.is_subset_of(existing_kconfig) and not self._kunitconfig_changed(build_dir):
return True
print('Regenerating .config ...')
os.remove(kconfig_path)
return self.build_config(build_dir, make_options)
def build_kernel(self, jobs: int, build_dir: str, make_options: Optional[List[str]]) -> bool:
try:
self._ops.make_olddefconfig(build_dir, make_options)
self._ops.make(jobs, build_dir, make_options)
except (ConfigError, BuildError) as e:
logging.error(e)
return False
return self.validate_config(build_dir)
def _restore_terminal_if_tty(self) -> None:
# stty requires a controlling terminal; skip headless runs.
if sys.stdin is None or not sys.stdin.isatty():
return
subprocess.call(['stty', 'sane'])
def run_kernel(self, args: Optional[List[str]]=None, build_dir: str='', filter_glob: str='', filter: str='', filter_action: Optional[str]=None, timeout: Optional[int]=None) -> Iterator[str]:
# Copy to avoid mutating the caller-supplied list. exec_tests() reuses
# the same args across repeated run_kernel() calls (e.g. --run_isolated),
# so appending to the original would accumulate stale flags on each call.
args = list(args) if args else []
if filter_glob:
args.append('kunit.filter_glob=' + filter_glob)
if filter:
args.append('kunit.filter="' + filter + '"')
if filter_action:
args.append('kunit.filter_action=' + filter_action)
args.append('kunit.enable=1')
self._process = self._ops.start(args, build_dir)
assert self._process is not None # tell mypy it's set
assert self._process.stdout is not None # tell mypy it's set
# Enforce the timeout in a background thread.
def _wait_proc() -> None:
try:
if self._process:
self._process.wait(timeout=timeout)
except Exception as e:
print(e)
if self._process:
self._process.terminate()
self._process.wait()
waiter = threading.Thread(target=_wait_proc)
waiter.start()
output = open(get_outfile_path(build_dir), 'w')
try:
# Tee the output to the file and to our caller in real time.
for line in self._process.stdout:
output.write(line)
yield line
# This runs even if our caller doesn't consume every line.
finally:
# Flush any leftover output to the file
if self._process:
if self._process.stdout:
output.write(self._process.stdout.read())
self._process.stdout.close()
self._process = None
output.close()
waiter.join()
self._restore_terminal_if_tty()
def signal_handler(self, unused_sig: int, unused_frame: Optional[FrameType]) -> None:
logging.error('Build interruption occurred. Cleaning console.')
if self._process:
self._process.terminate()
self._process.wait()
self._restore_terminal_if_tty()
@@ -0,0 +1,873 @@
# SPDX-License-Identifier: GPL-2.0
#
# Parses KTAP test results from a kernel dmesg log and incrementally prints
# results with reader-friendly format. Stores and returns test results in a
# Test object.
#
# Copyright (C) 2019, Google LLC.
# Author: Felix Guo <felixguoxiuping@gmail.com>
# Author: Brendan Higgins <brendanhiggins@google.com>
# Author: Rae Moar <rmoar@google.com>
from __future__ import annotations
from dataclasses import dataclass
import re
import textwrap
from enum import Enum, auto
from typing import Iterable, Iterator, List, Optional, Tuple
from kunit_printer import Printer
class Test:
"""
A class to represent a test parsed from KTAP results. All KTAP
results within a test log are stored in a main Test object as
subtests.
Attributes:
status : TestStatus - status of the test
name : str - name of the test
expected_count : int - expected number of subtests (0 if single
test case and None if unknown expected number of subtests)
subtests : List[Test] - list of subtests
log : List[str] - log of KTAP lines that correspond to the test
counts : TestCounts - counts of the test statuses and errors of
subtests or of the test itself if the test is a single
test case.
"""
def __init__(self) -> None:
"""Creates Test object with default attributes."""
self.status = TestStatus.TEST_CRASHED
self.name = ''
self.expected_count = 0 # type: Optional[int]
self.subtests = [] # type: List[Test]
self.log = [] # type: List[str]
self.counts = TestCounts()
self.skip_reason = ''
def __str__(self) -> str:
"""Returns string representation of a Test class object."""
return (f'Test({self.status}, {self.name}, {self.expected_count}, '
f'{self.subtests}, {self.log}, {self.counts}, {self.skip_reason})')
def __repr__(self) -> str:
"""Returns string representation of a Test class object."""
return str(self)
def add_error(self, printer: Printer, error_message: str) -> None:
"""Records an error that occurred while parsing this test."""
self.counts.errors += 1
printer.print_with_timestamp(printer.red('[ERROR]') + f' Test: {self.name}: {error_message}')
def ok_status(self) -> bool:
"""Returns true if the status was ok, i.e. passed or skipped."""
return self.status in (TestStatus.SUCCESS, TestStatus.SKIPPED)
class TestStatus(Enum):
"""An enumeration class to represent the status of a test."""
SUCCESS = auto()
FAILURE = auto()
SKIPPED = auto()
TEST_CRASHED = auto()
NO_TESTS = auto()
FAILURE_TO_PARSE_TESTS = auto()
@dataclass
class TestCounts:
"""
Tracks the counts of statuses of all test cases and any errors within
a Test.
"""
passed: int = 0
failed: int = 0
crashed: int = 0
skipped: int = 0
errors: int = 0
def __str__(self) -> str:
"""Returns the string representation of a TestCounts object."""
statuses = [('passed', self.passed), ('failed', self.failed),
('crashed', self.crashed), ('skipped', self.skipped),
('errors', self.errors)]
return f'Ran {self.total()} tests: ' + \
', '.join(f'{s}: {n}' for s, n in statuses if n > 0)
def total(self) -> int:
"""Returns the total number of test cases within a test
object, where a test case is a test with no subtests.
"""
return (self.passed + self.failed + self.crashed +
self.skipped)
def add_subtest_counts(self, counts: TestCounts) -> None:
"""
Adds the counts of another TestCounts object to the current
TestCounts object. Used to add the counts of a subtest to the
parent test.
Parameters:
counts - a different TestCounts object whose counts
will be added to the counts of the TestCounts object
"""
self.passed += counts.passed
self.failed += counts.failed
self.crashed += counts.crashed
self.skipped += counts.skipped
self.errors += counts.errors
def get_status(self) -> TestStatus:
"""Returns the aggregated status of a Test using test
counts.
"""
if self.total() == 0:
return TestStatus.NO_TESTS
if self.crashed:
# Crashes should take priority.
return TestStatus.TEST_CRASHED
if self.failed:
return TestStatus.FAILURE
if self.passed:
# No failures or crashes, looks good!
return TestStatus.SUCCESS
# We have only skipped tests.
return TestStatus.SKIPPED
def add_status(self, status: TestStatus) -> None:
"""Increments the count for `status`."""
if status == TestStatus.SUCCESS:
self.passed += 1
elif status == TestStatus.FAILURE:
self.failed += 1
elif status == TestStatus.SKIPPED:
self.skipped += 1
elif status != TestStatus.NO_TESTS:
self.crashed += 1
class LineStream:
"""
A class to represent the lines of kernel output.
Provides a lazy peek()/pop() interface over an iterator of
(line#, text).
"""
_lines: Iterator[Tuple[int, str]]
_next: Tuple[int, str]
_need_next: bool
_done: bool
def __init__(self, lines: Iterator[Tuple[int, str]]):
"""Creates a new LineStream that wraps the given iterator."""
self._lines = lines
self._done = False
self._need_next = True
self._next = (0, '')
def _get_next(self) -> None:
"""Advances the LineSteam to the next line, if necessary."""
if not self._need_next:
return
try:
self._next = next(self._lines)
except StopIteration:
self._done = True
finally:
self._need_next = False
def peek(self) -> str:
"""Returns the current line, without advancing the LineStream.
"""
self._get_next()
return self._next[1]
def pop(self) -> str:
"""Returns the current line and advances the LineStream to
the next line.
"""
s = self.peek()
if self._done:
raise ValueError(f'LineStream: going past EOF, last line was {s}')
self._need_next = True
return s
def __bool__(self) -> bool:
"""Returns True if stream has more lines."""
self._get_next()
return not self._done
# Only used by kunit_tool_test.py.
def __iter__(self) -> Iterator[str]:
"""Empties all lines stored in LineStream object into
Iterator object and returns the Iterator object.
"""
while bool(self):
yield self.pop()
def line_number(self) -> int:
"""Returns the line number of the current line."""
self._get_next()
return self._next[0]
# Parsing helper methods:
KTAP_START = re.compile(r'\s*KTAP version ([0-9]+)$')
TAP_START = re.compile(r'\s*TAP version ([0-9]+)$')
KTAP_END = re.compile(r'\s*(List of all partitions:|'
'Kernel panic - not syncing: VFS:|reboot: System halted)')
EXECUTOR_ERROR = re.compile(r'\s*kunit executor: (.*)$')
def extract_tap_lines(kernel_output: Iterable[str]) -> LineStream:
"""Extracts KTAP lines from the kernel output."""
def isolate_ktap_output(kernel_output: Iterable[str]) \
-> Iterator[Tuple[int, str]]:
line_num = 0
started = False
for line in kernel_output:
line_num += 1
line = line.rstrip() # remove trailing \n
if not started and KTAP_START.search(line):
# start extracting KTAP lines and set prefix
# to number of characters before version line
prefix_len = len(
line.split('KTAP version')[0])
started = True
yield line_num, line[prefix_len:]
elif not started and TAP_START.search(line):
# start extracting KTAP lines and set prefix
# to number of characters before version line
prefix_len = len(line.split('TAP version')[0])
started = True
yield line_num, line[prefix_len:]
elif started and KTAP_END.search(line):
# stop extracting KTAP lines
break
elif started:
# remove the prefix, if any.
line = line[prefix_len:]
yield line_num, line
elif EXECUTOR_ERROR.search(line):
yield line_num, line
return LineStream(lines=isolate_ktap_output(kernel_output))
KTAP_VERSIONS = [1]
TAP_VERSIONS = [13, 14]
def check_version(version_num: int, accepted_versions: List[int],
version_type: str, test: Test, printer: Printer) -> None:
"""
Adds error to test object if version number is too high or too
low.
Parameters:
version_num - The inputted version number from the parsed KTAP or TAP
header line
accepted_version - List of accepted KTAP or TAP versions
version_type - 'KTAP' or 'TAP' depending on the type of
version line.
test - Test object for current test being parsed
printer - Printer object to output error
"""
if version_num < min(accepted_versions):
test.add_error(printer, f'{version_type} version lower than expected!')
elif version_num > max(accepted_versions):
test.add_error(printer, f'{version_type} version higher than expected!')
def parse_ktap_header(lines: LineStream, test: Test, printer: Printer) -> bool:
"""
Parses KTAP/TAP header line and checks version number.
Returns False if fails to parse KTAP/TAP header line.
Accepted formats:
- 'KTAP version [version number]'
- 'TAP version [version number]'
Parameters:
lines - LineStream of KTAP output to parse
test - Test object for current test being parsed
printer - Printer object to output results
Return:
True if successfully parsed KTAP/TAP header line
"""
ktap_match = KTAP_START.match(lines.peek())
tap_match = TAP_START.match(lines.peek())
if ktap_match:
version_num = int(ktap_match.group(1))
check_version(version_num, KTAP_VERSIONS, 'KTAP', test, printer)
elif tap_match:
version_num = int(tap_match.group(1))
check_version(version_num, TAP_VERSIONS, 'TAP', test, printer)
else:
return False
lines.pop()
return True
TEST_HEADER = re.compile(r'^\s*# Subtest: (.*)$')
def parse_test_header(lines: LineStream, test: Test) -> bool:
"""
Parses test header and stores test name in test object.
Returns False if fails to parse test header line.
Accepted format:
- '# Subtest: [test name]'
Parameters:
lines - LineStream of KTAP output to parse
test - Test object for current test being parsed
Return:
True if successfully parsed test header line
"""
match = TEST_HEADER.match(lines.peek())
if not match:
return False
test.name = match.group(1)
lines.pop()
return True
TEST_PLAN = re.compile(r'^\s*1\.\.([0-9]+)')
def parse_test_plan(lines: LineStream, test: Test) -> bool:
"""
Parses test plan line and stores the expected number of subtests in
test object. Reports an error if expected count is 0.
Returns False and sets expected_count to None if there is no valid test
plan.
Accepted format:
- '1..[number of subtests]'
Parameters:
lines - LineStream of KTAP output to parse
test - Test object for current test being parsed
Return:
True if successfully parsed test plan line
"""
match = TEST_PLAN.match(lines.peek())
if not match:
test.expected_count = None
return False
expected_count = int(match.group(1))
test.expected_count = expected_count
lines.pop()
return True
TEST_RESULT = re.compile(r'^\s*(ok|not ok) ([0-9]+) ?(:?- )?([^#]*)( # .*)?$')
TEST_RESULT_SKIP = re.compile(r'^\s*(ok|not ok) ([0-9]+) ?(:?- )?(.*) # SKIP ?(.*)$')
def peek_test_name_match(lines: LineStream, test: Test) -> bool:
"""
Matches current line with the format of a test result line and checks
if the name matches the name of the current test.
Returns False if fails to match format or name.
Accepted format:
- '[ok|not ok] [test number] [-] [test name] [optional skip
directive]'
Parameters:
lines - LineStream of KTAP output to parse
test - Test object for current test being parsed
Return:
True if matched a test result line and the name matching the
expected test name
"""
line = lines.peek()
match = TEST_RESULT.match(line)
if not match:
return False
name = match.group(4)
if not name:
return False
return name == test.name
def parse_test_result(lines: LineStream, test: Test,
expected_num: int, printer: Printer) -> bool:
"""
Parses test result line and stores the status and name in the test
object. Reports an error if the test number does not match expected
test number.
Returns False if fails to parse test result line.
Note that the SKIP directive is the only direction that causes a
change in status.
Accepted format:
- '[ok|not ok] [test number] [-] [test name] [optional skip
directive]'
Parameters:
lines - LineStream of KTAP output to parse
test - Test object for current test being parsed
expected_num - expected test number for current test
printer - Printer object to output results
Return:
True if successfully parsed a test result line.
"""
line = lines.peek()
match = TEST_RESULT.match(line)
skip_match = TEST_RESULT_SKIP.match(line)
# Check if line matches test result line format
if not match:
return False
lines.pop()
# Set name of test object
if skip_match:
test.name = skip_match.group(4)
else:
test.name = match.group(4)
# Check test num
num = int(match.group(2))
if num != expected_num:
test.add_error(printer, f'Expected test number {expected_num} but found {num}')
# Set status of test object
status = match.group(1)
if skip_match:
test.status = TestStatus.SKIPPED
test.skip_reason = skip_match.group(5) or ''
elif status == 'ok':
test.status = TestStatus.SUCCESS
else:
test.status = TestStatus.FAILURE
return True
def parse_diagnostic(lines: LineStream) -> List[str]:
"""
Parse lines that do not match the format of a test result line or
test header line and returns them in list.
Line formats that are not parsed:
- '# Subtest: [test name]'
- '[ok|not ok] [test number] [-] [test name] [optional skip
directive]'
- 'KTAP version [version number]'
Parameters:
lines - LineStream of KTAP output to parse
Return:
Log of diagnostic lines
"""
log = [] # type: List[str]
non_diagnostic_lines = [TEST_RESULT, TEST_HEADER, KTAP_START, TAP_START, TEST_PLAN]
while lines and not any(re.match(lines.peek())
for re in non_diagnostic_lines):
log.append(lines.pop())
return log
# Printing helper methods:
DIVIDER = '=' * 60
def format_test_divider(message: str, len_message: int) -> str:
"""
Returns string with message centered in fixed width divider.
Example:
'===================== message example ====================='
Parameters:
message - message to be centered in divider line
len_message - length of the message to be printed such that
any characters of the color codes are not counted
Return:
String containing message centered in fixed width divider
"""
default_count = 3 # default number of dashes
len_1 = default_count
len_2 = default_count
difference = len(DIVIDER) - len_message - 2 # 2 spaces added
if difference > 0:
# calculate number of dashes for each side of the divider
len_1 = int(difference / 2)
len_2 = difference - len_1
return ('=' * len_1) + f' {message} ' + ('=' * len_2)
def print_test_header(test: Test, printer: Printer) -> None:
"""
Prints test header with test name and optionally the expected number
of subtests.
Example:
'=================== example (2 subtests) ==================='
Parameters:
test - Test object representing current test being printed
printer - Printer object to output results
"""
message = test.name
if message != "":
# Add a leading space before the subtest counts only if a test name
# is provided using a "# Subtest" header line.
message += " "
if test.expected_count:
if test.expected_count == 1:
message += '(1 subtest)'
else:
message += f'({test.expected_count} subtests)'
printer.print_with_timestamp(format_test_divider(message, len(message)))
def print_log(log: Iterable[str], printer: Printer) -> None:
"""Prints all strings in saved log for test in yellow."""
formatted = textwrap.dedent('\n'.join(log))
for line in formatted.splitlines():
printer.print_with_timestamp(printer.yellow(line))
def format_test_result(test: Test, printer: Printer) -> str:
"""
Returns string with formatted test result with colored status and test
name.
Example:
'[PASSED] example'
Parameters:
test - Test object representing current test being printed
printer - Printer object to output results
Return:
String containing formatted test result
"""
if test.status == TestStatus.SUCCESS:
return printer.green('[PASSED] ') + test.name
if test.status == TestStatus.SKIPPED:
skip_message = printer.yellow('[SKIPPED] ') + test.name
if test.skip_reason != '':
skip_message += printer.yellow(' (' + test.skip_reason + ')')
return skip_message
if test.status == TestStatus.NO_TESTS:
return printer.yellow('[NO TESTS RUN] ') + test.name
if test.status == TestStatus.TEST_CRASHED:
print_log(test.log, printer)
return printer.red('[CRASHED] ') + test.name
print_log(test.log, printer)
return printer.red('[FAILED] ') + test.name
def print_test_result(test: Test, printer: Printer) -> None:
"""
Prints result line with status of test.
Example:
'[PASSED] example'
Parameters:
test - Test object representing current test being printed
printer - Printer object
"""
printer.print_with_timestamp(format_test_result(test, printer))
def print_test_footer(test: Test, printer: Printer) -> None:
"""
Prints test footer with status of test.
Example:
'===================== [PASSED] example ====================='
Parameters:
test - Test object representing current test being printed
printer - Printer object to output results
"""
message = format_test_result(test, printer)
printer.print_with_timestamp(format_test_divider(message,
len(message) - printer.color_len()))
def print_test(test: Test, failed_only: bool, printer: Printer) -> None:
"""
Prints Test object to given printer. For a child test, the result line is
printed. For a parent test, the test header, all child test results, and
the test footer are all printed. If failed_only is true, only failed/crashed
tests will be printed.
Parameters:
test - Test object to print
failed_only - True if only failed/crashed tests should be printed.
printer - Printer object to output results
"""
if test.name == "main":
printer.print_with_timestamp(DIVIDER)
for subtest in test.subtests:
print_test(subtest, failed_only, printer)
printer.print_with_timestamp(DIVIDER)
elif test.subtests != []:
if not failed_only or not test.ok_status():
print_test_header(test, printer)
for subtest in test.subtests:
print_test(subtest, failed_only, printer)
print_test_footer(test, printer)
else:
if not failed_only or not test.ok_status():
print_test_result(test, printer)
def _summarize_failed_tests(test: Test) -> str:
"""Tries to summarize all the failing subtests in `test`."""
def failed_names(test: Test, parent_name: str) -> List[str]:
# Note: we use 'main' internally for the top-level test.
if not parent_name or parent_name == 'main':
full_name = test.name
else:
full_name = parent_name + '.' + test.name
if not test.subtests: # this is a leaf node
return [full_name]
# If all the children failed, just say this subtest failed.
# Don't summarize it down "the top-level test failed", though.
failed_subtests = [sub for sub in test.subtests if not sub.ok_status()]
if parent_name and len(failed_subtests) == len(test.subtests):
return [full_name]
all_failures = [] # type: List[str]
for t in failed_subtests:
all_failures.extend(failed_names(t, full_name))
return all_failures
failures = failed_names(test, '')
# If there are too many failures, printing them out will just be noisy.
if len(failures) > 10: # this is an arbitrary limit
return ''
return 'Failures: ' + ', '.join(failures)
def print_summary_line(test: Test, printer: Printer) -> None:
"""
Prints summary line of test object. Color of line is dependent on
status of test. Color is green if test passes, yellow if test is
skipped, and red if the test fails or crashes. Summary line contains
counts of the statuses of the tests subtests or the test itself if it
has no subtests.
Example:
"Testing complete. Passed: 2, Failed: 0, Crashed: 0, Skipped: 0,
Errors: 0"
test - Test object representing current test being printed
printer - Printer object to output results
"""
if test.status == TestStatus.SUCCESS:
color = printer.green
elif test.status in (TestStatus.SKIPPED, TestStatus.NO_TESTS):
color = printer.yellow
else:
color = printer.red
printer.print_with_timestamp(color(f'Testing complete. {test.counts}'))
# Summarize failures that might have gone off-screen since we had a lot
# of tests (arbitrarily defined as >=100 for now).
if test.ok_status() or test.counts.total() < 100:
return
summarized = _summarize_failed_tests(test)
if not summarized:
return
printer.print_with_timestamp(color(summarized))
# Other methods:
def bubble_up_test_results(test: Test) -> None:
"""
If the test has subtests, add the test counts of the subtests to the
test and check if any of the tests crashed and if so set the test
status to crashed. Otherwise if the test has no subtests add the
status of the test to the test counts.
Parameters:
test - Test object for current test being parsed
"""
subtests = test.subtests
counts = test.counts
status = test.status
for t in subtests:
counts.add_subtest_counts(t.counts)
if counts.total() == 0:
counts.add_status(status)
elif test.counts.get_status() == TestStatus.TEST_CRASHED:
test.status = TestStatus.TEST_CRASHED
if status == TestStatus.FAILURE and test.counts.get_status() == TestStatus.SUCCESS:
counts.add_status(status)
def parse_test(lines: LineStream, expected_num: int, log: List[str], is_subtest: bool, printer: Printer) -> Test:
"""
Finds next test to parse in LineStream, creates new Test object,
parses any subtests of the test, populates Test object with all
information (status, name) about the test and the Test objects for
any subtests, and then returns the Test object. The method accepts
three formats of tests:
Accepted test formats:
- Main KTAP/TAP header
Example:
KTAP version 1
1..4
[subtests]
- Subtest header (must include either the KTAP version line or
"# Subtest" header line)
Example (preferred format with both KTAP version line and
"# Subtest" line):
KTAP version 1
# Subtest: name
1..3
[subtests]
ok 1 name
Example (only "# Subtest" line):
# Subtest: name
1..3
[subtests]
ok 1 name
Example (only KTAP version line, compliant with KTAP v1 spec):
KTAP version 1
1..3
[subtests]
ok 1 name
- Test result line
Example:
ok 1 - test
Parameters:
lines - LineStream of KTAP output to parse
expected_num - expected test number for test to be parsed
log - list of strings containing any preceding diagnostic lines
corresponding to the current test
is_subtest - boolean indicating whether test is a subtest
printer - Printer object to output results
Return:
Test object populated with characteristics and any subtests
"""
test = Test()
test.log.extend(log)
# Parse any errors prior to parsing tests
err_log = parse_diagnostic(lines)
test.log.extend(err_log)
if not is_subtest:
# If parsing the main/top-level test, parse KTAP version line and
# test plan
test.name = "main"
parse_ktap_header(lines, test, printer)
test.log.extend(parse_diagnostic(lines))
parse_test_plan(lines, test)
parent_test = True
else:
# If not the main test, attempt to parse a test header containing
# the KTAP version line and/or subtest header line
ktap_line = parse_ktap_header(lines, test, printer)
subtest_line = parse_test_header(lines, test)
test.log.extend(parse_diagnostic(lines))
parse_test_plan(lines, test)
parent_test = (ktap_line or subtest_line)
if parent_test:
print_test_header(test, printer)
expected_count = test.expected_count
subtests = []
test_num = 1
while parent_test and (expected_count is None or test_num <= expected_count):
# Loop to parse any subtests.
# Break after parsing expected number of tests or
# if expected number of tests is unknown break when test
# result line with matching name to subtest header is found
# or no more lines in stream.
sub_log = parse_diagnostic(lines)
sub_test = Test()
if not lines or (peek_test_name_match(lines, test) and
is_subtest):
if expected_count and test_num <= expected_count:
# If parser reaches end of test before
# parsing expected number of subtests, print
# crashed subtest and record error
test.add_error(printer, 'missing expected subtest!')
sub_test.log.extend(sub_log)
test.counts.add_status(
TestStatus.TEST_CRASHED)
print_test_result(sub_test, printer)
else:
test.log.extend(sub_log)
break
else:
sub_test = parse_test(lines, test_num, sub_log, True, printer)
subtests.append(sub_test)
test_num += 1
test.subtests = subtests
if is_subtest:
# If not main test, look for test result line
test.log.extend(parse_diagnostic(lines))
if test.name != "" and not peek_test_name_match(lines, test):
test.add_error(printer, 'missing subtest result line!')
elif not lines:
print_log(test.log, printer)
test.status = TestStatus.NO_TESTS
test.add_error(printer, 'No more test results!')
else:
parse_test_result(lines, test, expected_num, printer)
# Check for there being no subtests within parent test
if parent_test and len(subtests) == 0:
# Don't override a bad status if this test had one reported.
# Assumption: no subtests means CRASHED is from Test.__init__()
if test.status in (TestStatus.TEST_CRASHED, TestStatus.SUCCESS):
print_log(test.log, printer)
test.status = TestStatus.NO_TESTS
test.add_error(printer, '0 tests run!')
# Add statuses to TestCounts attribute in Test object
bubble_up_test_results(test)
if parent_test and is_subtest:
# If test has subtests and is not the main test object, print
# footer.
print_test_footer(test, printer)
elif is_subtest:
print_test_result(test, printer)
return test
def parse_run_tests(kernel_output: Iterable[str], printer: Printer) -> Test:
"""
Using kernel output, extract KTAP lines, parse the lines for test
results and print condensed test results and summary line.
Parameters:
kernel_output - Iterable object contains lines of kernel output
printer - Printer object to output results
Return:
Test - the main test object with all subtests.
"""
printer.print_with_timestamp(DIVIDER)
lines = extract_tap_lines(kernel_output)
test = Test()
if not lines:
test.name = '<missing>'
test.add_error(printer, 'Could not find any KTAP output. Did any KUnit tests run?\n' +
'Try running with the --raw_output=all option to see any log messages.')
test.status = TestStatus.FAILURE_TO_PARSE_TESTS
else:
test = parse_test(lines, 0, [], False, printer)
if test.status != TestStatus.NO_TESTS:
test.status = test.counts.get_status()
printer.print_with_timestamp(DIVIDER)
return test
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
#
# Utilities for printing and coloring output.
#
# Copyright (C) 2022, Google LLC.
# Author: Daniel Latypov <dlatypov@google.com>
import datetime
import sys
import typing
_RESET = '\033[0;0m'
class Printer:
"""Wraps a file object, providing utilities for coloring output, etc."""
def __init__(self, print: bool=True, output: typing.IO[str]=sys.stdout):
self._output = output
self._print = print
if print:
self._use_color = output.isatty()
else:
self._use_color = False
def print(self, message: str) -> None:
if self._print:
print(message, file=self._output)
def print_with_timestamp(self, message: str) -> None:
ts = datetime.datetime.now().strftime('%H:%M:%S')
self.print(f'[{ts}] {message}')
def _color(self, code: str, text: str) -> str:
if not self._use_color:
return text
return code + text + _RESET
def red(self, text: str) -> str:
return self._color('\033[1;31m', text)
def yellow(self, text: str) -> str:
return self._color('\033[1;33m', text)
def green(self, text: str) -> str:
return self._color('\033[1;32m', text)
def color_len(self) -> int:
"""Returns the length of the color escape codes."""
return len(self.red(''))
# Provides a default instance that prints to stdout
stdout = Printer()
null_printer = Printer(print=False)
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
[mypy]
strict = True
# E.g. we can't write subprocess.Popen[str] until Python 3.9+.
# But kunit.py tries to support Python 3.7+, so let's disable it.
disable_error_code = type-arg
@@ -0,0 +1,20 @@
# SPDX-License-Identifier: GPL-2.0
#
# Collection of configs for building non-UML kernels and running them on QEMU.
#
# Copyright (C) 2021, Google LLC.
# Author: Brendan Higgins <brendanhiggins@google.com>
from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class QemuArchParams:
linux_arch: str
kconfig: str
qemu_arch: str
kernel_path: str
kernel_command_line: str
extra_qemu_params: List[str]
serial: str = 'stdio'
@@ -0,0 +1,10 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='alpha',
kconfig='''
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y''',
qemu_arch='alpha',
kernel_path='arch/alpha/boot/vmlinux',
kernel_command_line='console=ttyS0',
extra_qemu_params=[])
@@ -0,0 +1,13 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='arm',
kconfig='''
CONFIG_ARCH_VIRT=y
CONFIG_SERIAL_AMBA_PL010=y
CONFIG_SERIAL_AMBA_PL010_CONSOLE=y
CONFIG_SERIAL_AMBA_PL011=y
CONFIG_SERIAL_AMBA_PL011_CONSOLE=y''',
qemu_arch='arm',
kernel_path='arch/arm/boot/zImage',
kernel_command_line='console=ttyAMA0',
extra_qemu_params=['-machine', 'virt'])
@@ -0,0 +1,12 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='arm64',
kconfig='''
CONFIG_SERIAL_AMBA_PL010=y
CONFIG_SERIAL_AMBA_PL010_CONSOLE=y
CONFIG_SERIAL_AMBA_PL011=y
CONFIG_SERIAL_AMBA_PL011_CONSOLE=y''',
qemu_arch='aarch64',
kernel_path='arch/arm64/boot/Image.gz',
kernel_command_line='console=ttyAMA0',
extra_qemu_params=['-machine', 'virt', '-cpu', 'max'])
@@ -0,0 +1,16 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='arm',
kconfig='''
CONFIG_CPU_BIG_ENDIAN=y
CONFIG_ARCH_VIRT=y
CONFIG_SERIAL_AMBA_PL010=y
CONFIG_SERIAL_AMBA_PL010_CONSOLE=y
CONFIG_SERIAL_AMBA_PL011=y
CONFIG_SERIAL_AMBA_PL011_CONSOLE=y''',
qemu_arch='arm',
kernel_path='arch/arm/boot/zImage',
kernel_command_line='console=ttyAMA0',
extra_qemu_params=['-machine', 'virt'])
@@ -0,0 +1,10 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='i386',
kconfig='''
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y''',
qemu_arch='i386',
kernel_path='arch/x86/boot/bzImage',
kernel_command_line='console=ttyS0',
extra_qemu_params=[])
@@ -0,0 +1,21 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='loongarch',
kconfig='''
CONFIG_EFI_STUB=n
CONFIG_PCI_HOST_GENERIC=y
CONFIG_PVPANIC=y
CONFIG_PVPANIC_PCI=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_OF_PLATFORM=y
''',
qemu_arch='loongarch64',
kernel_path='arch/loongarch/boot/vmlinux.elf',
kernel_command_line='console=ttyS0 kunit_shutdown=poweroff',
extra_qemu_params=[
'-machine', 'virt',
'-device', 'pvpanic-pci',
'-cpu', 'max',])
@@ -0,0 +1,10 @@
# SPDX-License-Identifier: GPL-2.0-only
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='m68k',
kconfig='''
CONFIG_VIRT=y''',
qemu_arch='m68k',
kernel_path='vmlinux',
kernel_command_line='console=hvc0',
extra_qemu_params=['-machine', 'virt'])
@@ -0,0 +1,18 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='mips',
kconfig='''
CONFIG_32BIT=y
CONFIG_CPU_BIG_ENDIAN=y
CONFIG_MIPS_MALTA=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_POWER_RESET=y
CONFIG_POWER_RESET_SYSCON=y
''',
qemu_arch='mips',
kernel_path='vmlinuz',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'malta'])
@@ -0,0 +1,19 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='mips',
kconfig='''
CONFIG_CPU_MIPS64_R2=y
CONFIG_64BIT=y
CONFIG_CPU_BIG_ENDIAN=y
CONFIG_MIPS_MALTA=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_POWER_RESET=y
CONFIG_POWER_RESET_SYSCON=y
''',
qemu_arch='mips64',
kernel_path='vmlinuz',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'malta', '-cpu', '5KEc'])
@@ -0,0 +1,19 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='mips',
kconfig='''
CONFIG_CPU_MIPS64_R2=y
CONFIG_64BIT=y
CONFIG_CPU_LITTLE_ENDIAN=y
CONFIG_MIPS_MALTA=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_POWER_RESET=y
CONFIG_POWER_RESET_SYSCON=y
''',
qemu_arch='mips64el',
kernel_path='vmlinuz',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'malta', '-cpu', '5KEc'])
@@ -0,0 +1,18 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='mips',
kconfig='''
CONFIG_32BIT=y
CONFIG_CPU_LITTLE_ENDIAN=y
CONFIG_MIPS_MALTA=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_POWER_RESET=y
CONFIG_POWER_RESET_SYSCON=y
''',
qemu_arch='mipsel',
kernel_path='vmlinuz',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'malta'])
@@ -0,0 +1,18 @@
# SPDX-License-Identifier: GPL-2.0-only
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='openrisc',
kconfig='''
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_OF_PLATFORM=y
CONFIG_POWER_RESET=y
CONFIG_POWER_RESET_SYSCON=y
''',
qemu_arch='or1k',
kernel_path='vmlinux',
kernel_command_line='console=ttyS0',
extra_qemu_params=[
'-machine', 'virt',
'-m', '512',
])
@@ -0,0 +1,13 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='powerpc',
kconfig='''
CONFIG_PPC64=y
CONFIG_CPU_BIG_ENDIAN=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_HVC_CONSOLE=y''',
qemu_arch='ppc64',
kernel_path='vmlinux',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'pseries', '-cpu', 'power8'])
@@ -0,0 +1,17 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='powerpc',
kconfig='''
CONFIG_PPC32=y
CONFIG_CPU_BIG_ENDIAN=y
CONFIG_ADB_CUDA=y
CONFIG_SERIAL_PMACZILOG=y
CONFIG_SERIAL_PMACZILOG_TTYS=y
CONFIG_SERIAL_PMACZILOG_CONSOLE=y
''',
qemu_arch='ppc',
kernel_path='vmlinux',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'g3beige', '-cpu', 'max'])
@@ -0,0 +1,14 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='powerpc',
kconfig='''
CONFIG_PPC64=y
CONFIG_CPU_LITTLE_ENDIAN=y
CONFIG_HVC_CONSOLE=y
''',
qemu_arch='ppc64',
kernel_path='vmlinux',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-M', 'pseries', '-cpu', 'power8'])
@@ -0,0 +1,28 @@
from ..qemu_config import QemuArchParams
import os
import os.path
import sys
OPENSBI_FILE = 'opensbi-riscv64-generic-fw_dynamic.bin'
OPENSBI_PATH = '/usr/share/qemu/' + OPENSBI_FILE
if not os.path.isfile(OPENSBI_PATH):
print('\n\nOpenSBI bios was not found in "' + OPENSBI_PATH + '".\n'
'Please ensure that qemu-system-riscv is installed, or edit the path in "qemu_configs/riscv.py"\n')
sys.exit()
QEMU_ARCH = QemuArchParams(linux_arch='riscv',
kconfig='''
CONFIG_ARCH_VIRT=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_OF_PLATFORM=y
CONFIG_RISCV_SBI_V01=y
CONFIG_SERIAL_EARLYCON_RISCV_SBI=y''',
qemu_arch='riscv64',
kernel_path='arch/riscv/boot/Image',
kernel_command_line='console=ttyS0',
extra_qemu_params=[
'-machine', 'virt',
'-cpu', 'rv64',
'-bios', OPENSBI_PATH])
@@ -0,0 +1,17 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='riscv',
kconfig='''
CONFIG_NONPORTABLE=y
CONFIG_ARCH_RV32I=y
CONFIG_ARCH_VIRT=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_OF_PLATFORM=y
''',
qemu_arch='riscv32',
kernel_path='arch/riscv/boot/Image',
kernel_command_line='console=ttyS0',
extra_qemu_params=['-machine', 'virt'])
@@ -0,0 +1,14 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='s390',
kconfig='''
CONFIG_EXPERT=y
CONFIG_TUNE_ZEC12=y
CONFIG_NUMA=y
CONFIG_MODULES=y''',
qemu_arch='s390x',
kernel_path='arch/s390/boot/bzImage',
kernel_command_line='console=ttyS0',
extra_qemu_params=[
'-machine', 's390-ccw-virtio',
'-cpu', 'qemu',])
@@ -0,0 +1,19 @@
# SPDX-License-Identifier: GPL-2.0-only
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='sh',
kconfig='''
CONFIG_CPU_SUBTYPE_SH7751R=y
CONFIG_MEMORY_START=0x0c000000
CONFIG_SH_RTS7751R2D=y
CONFIG_RTS7751R2D_PLUS=y
CONFIG_SERIAL_SH_SCI=y
CONFIG_CMDLINE_EXTEND=y
''',
qemu_arch='sh4',
kernel_path='arch/sh/boot/zImage',
kernel_command_line='console=ttySC1',
serial='null',
extra_qemu_params=[
'-machine', 'r2d',
'-serial', 'mon:stdio'])
@@ -0,0 +1,13 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='sparc',
kconfig='''
CONFIG_KUNIT_FAULT_TEST=n
CONFIG_SPARC32=y
CONFIG_SERIAL_SUNZILOG=y
CONFIG_SERIAL_SUNZILOG_CONSOLE=y
''',
qemu_arch='sparc',
kernel_path='arch/sparc/boot/zImage',
kernel_command_line='console=ttyS0 mem=256M',
extra_qemu_params=['-m', '256'])
@@ -0,0 +1,16 @@
# SPDX-License-Identifier: GPL-2.0
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='sparc',
kconfig='''
CONFIG_64BIT=y
CONFIG_SPARC64=y
CONFIG_PCI=y
CONFIG_SERIAL_SUNSU=y
CONFIG_SERIAL_SUNSU_CONSOLE=y
''',
qemu_arch='sparc64',
kernel_path='arch/sparc/boot/image',
kernel_command_line='console=ttyS0 kunit_shutdown=poweroff',
extra_qemu_params=[])
@@ -0,0 +1,12 @@
from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='x86_64',
kconfig='''
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y''',
qemu_arch='x86_64',
kernel_path='arch/x86/boot/bzImage',
kernel_command_line='console=ttyS0',
# qboot is faster than SeaBIOS and doesn't mess up
# the terminal.
extra_qemu_params=['-bios', 'qboot.rom'])
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
#
# This file runs some basic checks to verify kunit works.
# It is only of interest if you're making changes to KUnit itself.
#
# Copyright (C) 2021, Google LLC.
# Author: Daniel Latypov <dlatypov@google.com.com>
from concurrent import futures
import datetime
import os
import shutil
import subprocess
import sys
import textwrap
from typing import Dict, List, Sequence
ABS_TOOL_PATH = os.path.abspath(os.path.dirname(__file__))
TIMEOUT = datetime.timedelta(minutes=5).total_seconds()
commands: Dict[str, Sequence[str]] = {
'kunit_tool_test.py': ['./kunit_tool_test.py'],
'kunit smoke test': ['./kunit.py', 'run', '--kunitconfig=lib/kunit', '--build_dir=kunit_run_checks'],
'pytype': ['/bin/sh', '-c', 'pytype *.py'],
'mypy': ['mypy', '--config-file', 'mypy.ini', '--exclude', '_test.py$', '--exclude', 'qemu_configs/', '.'],
}
# The user might not have mypy or pytype installed, skip them if so.
# Note: you can install both via `$ pip install mypy pytype`
necessary_deps : Dict[str, str] = {
'pytype': 'pytype',
'mypy': 'mypy',
}
def main(argv: Sequence[str]) -> None:
if argv:
raise RuntimeError('This script takes no arguments')
future_to_name: Dict[futures.Future[None], str] = {}
executor = futures.ThreadPoolExecutor(max_workers=len(commands))
for name, argv in commands.items():
if name in necessary_deps and shutil.which(necessary_deps[name]) is None:
print(f'{name}: SKIPPED, {necessary_deps[name]} not in $PATH')
continue
f = executor.submit(run_cmd, argv)
future_to_name[f] = name
has_failures = False
print(f'Waiting on {len(future_to_name)} checks ({", ".join(future_to_name.values())})...')
for f in futures.as_completed(future_to_name.keys()):
name = future_to_name[f]
ex = f.exception()
if not ex:
print(f'{name}: PASSED')
continue
has_failures = True
if isinstance(ex, subprocess.TimeoutExpired):
print(f'{name}: TIMED OUT')
elif isinstance(ex, subprocess.CalledProcessError):
print(f'{name}: FAILED')
else:
print(f'{name}: unexpected exception: {ex}')
continue
output = ex.output
if output:
print(textwrap.indent(output.decode(), '> '))
executor.shutdown()
if has_failures:
sys.exit(1)
def run_cmd(argv: Sequence[str]) -> None:
subprocess.check_output(argv, stderr=subprocess.STDOUT, cwd=ABS_TOOL_PATH, timeout=TIMEOUT)
if __name__ == '__main__':
main(sys.argv[1:])
@@ -0,0 +1,32 @@
[ 0.060000] printk: console [mc-1] enabled
[ 0.060000] random: get_random_bytes called from init_oops_id+0x35/0x40 with crng_init=0
[ 0.060000] TAP version 14
[ 0.060000] 1..3
[ 0.060000] # Subtest: kunit-resource-test
[ 0.060000] 1..5
[ 0.060000] ok 1 - kunit_resource_test_init_resources
[ 0.060000] ok 2 - kunit_resource_test_alloc_resource
[ 0.060000] ok 3 - kunit_resource_test_destroy_resource
[ 0.060000] ok 4 - kunit_resource_test_cleanup_resources
[ 0.060000] ok 5 - kunit_resource_test_proper_free_ordering
[ 0.060000] ok 1 - kunit-resource-test
[ 0.060000] # Subtest: kunit-try-catch-test
[ 0.060000] 1..2
[ 0.060000] ok 1 - kunit_test_try_catch_successful_try_no_catch
[ 0.060000] ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch
[ 0.060000] ok 2 - kunit-try-catch-test
[ 0.060000] # Subtest: string-stream-test
[ 0.060000] 1..3
[ 0.060000] ok 1 - string_stream_test_empty_on_creation
[ 0.060000] ok 2 - string_stream_test_not_empty_after_add
[ 0.060000] ok 3 - string_stream_test_get_string
[ 0.060000] ok 3 - string-stream-test
[ 0.060000] List of all partitions:
[ 0.060000] No filesystem could mount root, tried:
[ 0.060000]
[ 0.060000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
[ 0.060000] CPU: 0 PID: 1 Comm: swapper Not tainted 5.4.0-rc1-gea2dd7c0875e-dirty #2
[ 0.060000] Stack:
[ 0.060000] 602086f8 601bc260 705c0000 705c0000
[ 0.060000] 602086f8 6005fcec 705c0000 6002c6ab
[ 0.060000] 6005fcec 601bc260 705c0000 3000000010
@@ -0,0 +1,38 @@
[ 0.060000] printk: console [mc-1] enabled
[ 0.060000] random: get_random_bytes called from init_oops_id+0x35/0x40 with crng_init=0
[ 0.060000] TAP version 14
[ 0.060000] 1..3
[ 0.060000] # Subtest: kunit-resource-test
[ 0.060000] 1..5
[ 0.060000] ok 1 - kunit_resource_test_init_resources
[ 0.060000] ok 2 - kunit_resource_test_alloc_resource
[ 0.060000] ok 3 - kunit_resource_test_destroy_resource
[ 0.060000] kAFS: Red Hat AFS client v0.1 registering.
[ 0.060000] FS-Cache: Netfs 'afs' registered for caching
[ 0.060000] *** VALIDATE kAFS ***
[ 0.060000] Btrfs loaded, crc32c=crc32c-generic, debug=on, assert=on, integrity-checker=on, ref-verify=on
[ 0.060000] BTRFS: selftest: sectorsize: 4096 nodesize: 4096
[ 0.060000] BTRFS: selftest: running btrfs free space cache tests
[ 0.060000] ok 4 - kunit_resource_test_cleanup_resources
[ 0.060000] ok 5 - kunit_resource_test_proper_free_ordering
[ 0.060000] ok 1 - kunit-resource-test
[ 0.060000] # Subtest: kunit-try-catch-test
[ 0.060000] 1..2
[ 0.060000] ok 1 - kunit_test_try_catch_successful_try_no_catch
[ 0.060000] ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch
[ 0.060000] ok 2 - kunit-try-catch-test
[ 0.060000] # Subtest: string-stream-test
[ 0.060000] 1..3
[ 0.060000] ok 1 - string_stream_test_empty_on_creation
[ 0.060000] ok 2 - string_stream_test_not_empty_after_add
[ 0.060000] ok 3 - string_stream_test_get_string
[ 0.060000] ok 3 - string-stream-test
[ 0.060000] List of all partitions:
[ 0.060000] No filesystem could mount root, tried:
[ 0.060000]
[ 0.060000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
[ 0.060000] CPU: 0 PID: 1 Comm: swapper Not tainted 5.4.0-rc1-gea2dd7c0875e-dirty #2
[ 0.060000] Stack:
[ 0.060000] 602086f8 601bc260 705c0000 705c0000
[ 0.060000] 602086f8 6005fcec 705c0000 6002c6ab
[ 0.060000] 6005fcec 601bc260 705c0000 3000000010
@@ -0,0 +1,33 @@
TAP version 14
1..2
# Subtest: sysctl_test
1..8
# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
ok 1 - sysctl_test_dointvec_null_tbl_data
# sysctl_test_dointvec_table_maxlen_unset: sysctl_test_dointvec_table_maxlen_unset passed
ok 2 - sysctl_test_dointvec_table_maxlen_unset
# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
ok 3 - sysctl_test_dointvec_table_len_is_zero
# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
ok 4 - sysctl_test_dointvec_table_read_but_position_set
# sysctl_test_dointvec_happy_single_positive: sysctl_test_dointvec_happy_single_positive passed
ok 5 - sysctl_test_dointvec_happy_single_positive
# sysctl_test_dointvec_happy_single_negative: sysctl_test_dointvec_happy_single_negative passed
ok 6 - sysctl_test_dointvec_happy_single_negative
# sysctl_test_dointvec_single_less_int_min: sysctl_test_dointvec_single_less_int_min passed
ok 7 - sysctl_test_dointvec_single_less_int_min
# sysctl_test_dointvec_single_greater_int_max: sysctl_test_dointvec_single_greater_int_max passed
ok 8 - sysctl_test_dointvec_single_greater_int_max
kunit sysctl_test: all tests passed
ok 1 - sysctl_test
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: example_simple_test passed
ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: all tests passed
ok 2 - example
@@ -0,0 +1,34 @@
TAP version 14
1..2
# Subtest: sysctl_test
1..4
# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
ok 1 - sysctl_test_dointvec_null_tbl_data
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: example_simple_test passed
ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: all tests passed
ok 2 - example
# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
ok 3 - sysctl_test_dointvec_table_len_is_zero
# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
ok 4 - sysctl_test_dointvec_table_read_but_position_set
kunit sysctl_test: all tests passed
ok 1 - sysctl_test
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: example_simple_test passed
ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: all tests passed
ok 2 - example
@@ -0,0 +1,10 @@
KTAP version 1
1..2
KTAP version 1
1..1
ok 1 test 1
not ok 1 subtest 1
KTAP version 1
1..1
not ok 1 subsubtest 1
not ok 2 subtest 2
@@ -0,0 +1,37 @@
TAP version 14
1..2
# Subtest: sysctl_test
1..8
# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
ok 1 - sysctl_test_dointvec_null_tbl_data
# sysctl_test_dointvec_table_maxlen_unset: sysctl_test_dointvec_table_maxlen_unset passed
ok 2 - sysctl_test_dointvec_table_maxlen_unset
# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
ok 3 - sysctl_test_dointvec_table_len_is_zero
# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
ok 4 - sysctl_test_dointvec_table_read_but_position_set
# sysctl_test_dointvec_happy_single_positive: sysctl_test_dointvec_happy_single_positive passed
ok 5 - sysctl_test_dointvec_happy_single_positive
# sysctl_test_dointvec_happy_single_negative: sysctl_test_dointvec_happy_single_negative passed
ok 6 - sysctl_test_dointvec_happy_single_negative
# sysctl_test_dointvec_single_less_int_min: sysctl_test_dointvec_single_less_int_min passed
ok 7 - sysctl_test_dointvec_single_less_int_min
# sysctl_test_dointvec_single_greater_int_max: sysctl_test_dointvec_single_greater_int_max passed
ok 8 - sysctl_test_dointvec_single_greater_int_max
kunit sysctl_test: all tests passed
ok 1 - sysctl_test
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: EXPECTATION FAILED at lib/kunit/example-test.c:30
Expected 1 + 1 == 3, but
1 + 1 == 2
3 == 3
# example_simple_test: example_simple_test failed
not ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: one or more tests failed
not ok 2 - example
@@ -0,0 +1,15 @@
TAP version 13
1..3
# selftests: membarrier: membarrier_test_single_thread
# TAP version 13
# 1..2
# ok 1 sys_membarrier available
# ok 2 sys membarrier invalid command test: command = -1, flags = 0, errno = 22. Failed as expected
ok 1 selftests: membarrier: membarrier_test_single_thread
# selftests: membarrier: membarrier_test_multi_thread
# TAP version 13
# 1..2
# ok 1 sys_membarrier available
# ok 2 sys membarrier invalid command test: command = -1, flags = 0, errno = 22. Failed as expected
ok 2 selftests: membarrier: membarrier_test_multi_thread
ok 3 # SKIP selftests: membarrier: membarrier_test_multi_thread
@@ -0,0 +1,31 @@
KTAP version 1
# Subtest: sysctl_test
# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
ok 1 - sysctl_test_dointvec_null_tbl_data
# sysctl_test_dointvec_table_maxlen_unset: sysctl_test_dointvec_table_maxlen_unset passed
ok 2 - sysctl_test_dointvec_table_maxlen_unset
# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
ok 3 - sysctl_test_dointvec_table_len_is_zero
# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
ok 4 - sysctl_test_dointvec_table_read_but_position_set
# sysctl_test_dointvec_happy_single_positive: sysctl_test_dointvec_happy_single_positive passed
ok 5 - sysctl_test_dointvec_happy_single_positive
# sysctl_test_dointvec_happy_single_negative: sysctl_test_dointvec_happy_single_negative passed
ok 6 - sysctl_test_dointvec_happy_single_negative
# sysctl_test_dointvec_single_less_int_min: sysctl_test_dointvec_single_less_int_min passed
ok 7 - sysctl_test_dointvec_single_less_int_min
# sysctl_test_dointvec_single_greater_int_max: sysctl_test_dointvec_single_greater_int_max passed
ok 8 - sysctl_test_dointvec_single_greater_int_max
kunit sysctl_test: all tests passed
ok 1 - sysctl_test
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: example_simple_test passed
ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: all tests passed
ok 2 - example
@@ -0,0 +1,7 @@
TAP version 14
1..1
# Subtest: suite
1..1
# Subtest: case
ok 1 - case
ok 1 - suite
@@ -0,0 +1,75 @@
Core dump limits :
soft - 0
hard - NONE
Checking environment variables for a tempdir...none found
Checking if /dev/shm is on tmpfs...OK
Checking PROT_EXEC mmap in /dev/shm...OK
Adding 24743936 bytes to physical memory to account for exec-shield gap
Linux version 4.12.0-rc3-00010-g7319eb35f493-dirty (brendanhiggins@mactruck.svl.corp.google.com) (gcc version 7.3.0 (Debian 7.3.0-5) ) #29 Thu Mar 15 14:57:19 PDT 2018
Built 1 zonelists in Zone order, mobility grouping on. Total pages: 14038
Kernel command line: root=98:0
PID hash table entries: 256 (order: -1, 2048 bytes)
Dentry cache hash table entries: 8192 (order: 4, 65536 bytes)
Inode-cache hash table entries: 4096 (order: 3, 32768 bytes)
Memory: 27868K/56932K available (1681K kernel code, 480K rwdata, 400K rodata, 89K init, 205K bss, 29064K reserved, 0K cma-reserved)
SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
NR_IRQS:15
clocksource: timer: mask: 0xffffffffffffffff max_cycles: 0x1cd42e205, max_idle_ns: 881590404426 ns
Calibrating delay loop... 7384.26 BogoMIPS (lpj=36921344)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 512 (order: 0, 4096 bytes)
Mountpoint-cache hash table entries: 512 (order: 0, 4096 bytes)
Checking that host ptys support output SIGIO...Yes
Checking that host ptys support SIGIO on close...No, enabling workaround
Using 2.6 host AIO
clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns
futex hash table entries: 256 (order: 0, 6144 bytes)
clocksource: Switched to clocksource timer
console [stderr0] disabled
mconsole (version 2) initialized on /usr/local/google/home/brendanhiggins/.uml/6Ijecl/mconsole
Checking host MADV_REMOVE support...OK
workingset: timestamp_bits=62 max_order=13 bucket_order=0
Block layer SCSI generic (bsg) driver version 0.4 loaded (major 254)
io scheduler noop registered
io scheduler deadline registered
io scheduler cfq registered (default)
io scheduler mq-deadline registered
io scheduler kyber registered
Initialized stdio console driver
Using a channel type which is configured out of UML
setup_one_line failed for device 1 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 2 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 3 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 4 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 5 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 6 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 7 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 8 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 9 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 10 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 11 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 12 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 13 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 14 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 15 : Configuration failed
Console initialized on /dev/tty0
console [tty0] enabled
console [mc-1] enabled
List of all partitions:
No filesystem could mount root, tried:
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
@@ -0,0 +1,2 @@
TAP version 14
1..0
@@ -0,0 +1,26 @@
[ 0.060000] printk: console [mc-1] enabled
[ 0.060000] random: get_random_bytes called from init_oops_id+0x35/0x40 with crng_init=0
[ 0.060000] TAP version 14
[ 0.060000] 1..3
[ 0.060000] # Subtest: kunit-resource-test
[ 0.060000] 1..5
[ 0.060000] ok 1 - kunit_resource_test_init_resources
[ 0.060000] ok 2 - kunit_resource_test_alloc_resource
[ 0.060000] ok 3 - kunit_resource_test_destroy_resource
[ 0.060000] ok 4 - kunit_resource_test_cleanup_resources
[ 0.060000] ok 5 - kunit_resource_test_proper_free_ordering
[ 0.060000] ok 1 - kunit-resource-test
[ 0.060000] # Subtest: kunit-try-catch-test
[ 0.060000] 1..2
[ 0.060000] ok 1 - kunit_test_try_catch_successful_try_no_catch
[ 0.060000] ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch
[ 0.060000] ok 2 - kunit-try-catch-test
[ 0.060000] # Subtest: string-stream-test
[ 0.060000] 1..3
[ 0.060000] ok 1 - string_stream_test_empty_on_creation
[ 0.060000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
[ 0.060000] CPU: 0 PID: 1 Comm: swapper Not tainted 5.4.0-rc1-gea2dd7c0875e-dirty #2
[ 0.060000] Stack:
[ 0.060000] 602086f8 601bc260 705c0000 705c0000
[ 0.060000] 602086f8 6005fcec 705c0000 6002c6ab
[ 0.060000] 6005fcec 601bc260 705c0000 3000000010
@@ -0,0 +1,32 @@
[ 0.060000][ T1] printk: console [mc-1] enabled
[ 0.060000][ T1] random: get_random_bytes called from init_oops_id+0x35/0x40 with crng_init=0
[ 0.060000][ T1] TAP version 14
[ 0.060000][ T1] 1..3
[ 0.060000][ T1] # Subtest: kunit-resource-test
[ 0.060000][ T1] 1..5
[ 0.060000][ T1] ok 1 - kunit_resource_test_init_resources
[ 0.060000][ T1] ok 2 - kunit_resource_test_alloc_resource
[ 0.060000][ T1] ok 3 - kunit_resource_test_destroy_resource
[ 0.060000][ T1] ok 4 - kunit_resource_test_cleanup_resources
[ 0.060000][ T1] ok 5 - kunit_resource_test_proper_free_ordering
[ 0.060000][ T1] ok 1 - kunit-resource-test
[ 0.060000][ T1] # Subtest: kunit-try-catch-test
[ 0.060000][ T1] 1..2
[ 0.060000][ T1] ok 1 - kunit_test_try_catch_successful_try_no_catch
[ 0.060000][ T1] ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch
[ 0.060000][ T1] ok 2 - kunit-try-catch-test
[ 0.060000][ T1] # Subtest: string-stream-test
[ 0.060000][ T1] 1..3
[ 0.060000][ T1] ok 1 - string_stream_test_empty_on_creation
[ 0.060000][ T1] ok 2 - string_stream_test_not_empty_after_add
[ 0.060000][ T1] ok 3 - string_stream_test_get_string
[ 0.060000][ T1] ok 3 - string-stream-test
[ 0.060000][ T1] List of all partitions:
[ 0.060000][ T1] No filesystem could mount root, tried:
[ 0.060000][ T1]
[ 0.060000][ T1] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
[ 0.060000][ T1] CPU: 0 PID: 1 Comm: swapper Not tainted 5.4.0-rc1-gea2dd7c0875e-dirty #2
[ 0.060000][ T1] Stack:
[ 0.060000][ T1] 602086f8 601bc260 705c0000 705c0000
[ 0.060000][ T1] 602086f8 6005fcec 705c0000 6002c6ab
[ 0.060000][ T1] 6005fcec 601bc260 705c0000 3000000010
@@ -0,0 +1,106 @@
Linux version 5.1.0-rc7-00061-g04652f1cb4aa0 (brendanhiggins@mactruck.svl.corp.google.com) (gcc version 7.3.0 (Debian 7.3.0-18)) #163 Wed May 8 16:18:20 PDT 2019
Built 1 zonelists, mobility grouping on. Total pages: 69906
Kernel command line: mem=256M root=98:0
Dentry cache hash table entries: 65536 (order: 7, 524288 bytes)
Inode-cache hash table entries: 32768 (order: 6, 262144 bytes)
Memory: 254468K/283500K available (1734K kernel code, 489K rwdata, 396K rodata, 85K init, 216K bss, 29032K reserved, 0K cma-reserved)
SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
NR_IRQS: 15
clocksource: timer: mask: 0xffffffffffffffff max_cycles: 0x1cd42e205, max_idle_ns: 881590404426 ns
------------[ cut here ]------------
WARNING: CPU: 0 PID: 0 at kernel/time/clockevents.c:458 clockevents_register_device+0x143/0x160
posix-timer cpumask == cpu_all_mask, using cpu_possible_mask instead
CPU: 0 PID: 0 Comm: swapper Not tainted 5.1.0-rc7-00061-g04652f1cb4aa0 #163
Stack:
6005cc00 60233e18 60233e60 60233e18
60233e60 00000009 00000000 6002a1b4
1ca00000000 60071c23 60233e78 100000000000062
Call Trace:
[<600214c5>] ? os_is_signal_stack+0x15/0x30
[<6005c5ec>] ? printk+0x0/0x9b
[<6001597e>] ? show_stack+0xbe/0x1c0
[<6005cc00>] ? __printk_safe_exit+0x0/0x40
[<6002a1b4>] ? __warn+0x144/0x170
[<60071c23>] ? clockevents_register_device+0x143/0x160
[<60021440>] ? get_signals+0x0/0x10
[<6005c5ec>] ? printk+0x0/0x9b
[<6002a27b>] ? warn_slowpath_fmt+0x9b/0xb0
[<6005c5ec>] ? printk+0x0/0x9b
[<6002a1e0>] ? warn_slowpath_fmt+0x0/0xb0
[<6005c5ec>] ? printk+0x0/0x9b
[<60021440>] ? get_signals+0x0/0x10
[<600213f0>] ? block_signals+0x0/0x20
[<60071c23>] ? clockevents_register_device+0x143/0x160
[<60021440>] ? get_signals+0x0/0x10
[<600213f0>] ? block_signals+0x0/0x20
[<6005c5ec>] ? printk+0x0/0x9b
[<60001bc8>] ? start_kernel+0x477/0x56a
[<600036f1>] ? start_kernel_proc+0x46/0x4d
[<60014442>] ? new_thread_handler+0x82/0xc0
random: get_random_bytes called from print_oops_end_marker+0x4c/0x60 with crng_init=0
---[ end trace c83434852b3702d3 ]---
Calibrating delay loop... 6958.28 BogoMIPS (lpj=34791424)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 1024 (order: 1, 8192 bytes)
Mountpoint-cache hash table entries: 1024 (order: 1, 8192 bytes)
*** VALIDATE proc ***
Checking that host ptys support output SIGIO...Yes
Checking that host ptys support SIGIO on close...No, enabling workaround
clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns
futex hash table entries: 256 (order: 0, 6144 bytes)
clocksource: Switched to clocksource timer
printk: console [stderr0] disabled
mconsole (version 2) initialized on /usr/local/google/home/brendanhiggins/.uml/VZ2qMm/mconsole
Checking host MADV_REMOVE support...OK
workingset: timestamp_bits=62 max_order=16 bucket_order=0
Block layer SCSI generic (bsg) driver version 0.4 loaded (major 254)
io scheduler mq-deadline registered
io scheduler kyber registered
Initialized stdio console driver
Using a channel type which is configured out of UML
setup_one_line failed for device 1 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 2 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 3 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 4 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 5 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 6 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 7 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 8 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 9 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 10 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 11 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 12 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 13 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 14 : Configuration failed
Using a channel type which is configured out of UML
setup_one_line failed for device 15 : Configuration failed
Console initialized on /dev/tty0
printk: console [tty0] enabled
printk: console [mc-1] enabled
TAP version 14
# Subtest: example
1..2
init_suite
# example_simple_test: initializing
# example_simple_test: example_simple_test passed
ok 1 - example_simple_test
# example_mock_test: initializing
# example_mock_test: example_mock_test passed
ok 2 - example_mock_test
kunit example: all tests passed
ok 1 - example
List of all partitions:
@@ -0,0 +1,33 @@
[ 0.060000] printk: console [mc-1] enabled
[ 0.060000] random: get_random_bytes called from init_oops_id+0x35/0x40 with crng_init=0
[ 0.060000] TAP version 14
[ 0.060000] # Subtest: kunit-resource-test
[ 0.060000] 1..5
[ 0.060000] ok 1 - kunit_resource_test_init_resources
[ 0.060000] ok 2 - kunit_resource_test_alloc_resource
[ 0.060000] ok 3 - kunit_resource_test_destroy_resource
[ 0.060000] foo bar #
[ 0.060000] ok 4 - kunit_resource_test_cleanup_resources
[ 0.060000] ok 5 - kunit_resource_test_proper_free_ordering
[ 0.060000] ok 1 - kunit-resource-test
[ 0.060000] foo bar # non-kunit output
[ 0.060000] # Subtest: kunit-try-catch-test
[ 0.060000] 1..2
[ 0.060000] ok 1 - kunit_test_try_catch_successful_try_no_catch
[ 0.060000] ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch
[ 0.060000] ok 2 - kunit-try-catch-test
[ 0.060000] # Subtest: string-stream-test
[ 0.060000] 1..3
[ 0.060000] ok 1 - string_stream_test_empty_on_creation
[ 0.060000] ok 2 - string_stream_test_not_empty_after_add
[ 0.060000] ok 3 - string_stream_test_get_string
[ 0.060000] ok 3 - string-stream-test
[ 0.060000] List of all partitions:
[ 0.060000] No filesystem could mount root, tried:
[ 0.060000]
[ 0.060000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(98,0)
[ 0.060000] CPU: 0 PID: 1 Comm: swapper Not tainted 5.4.0-rc1-gea2dd7c0875e-dirty #2
[ 0.060000] Stack:
[ 0.060000] 602086f8 601bc260 705c0000 705c0000
[ 0.060000] 602086f8 6005fcec 705c0000 6002c6ab
[ 0.060000] 6005fcec 601bc260 705c0000 3000000010
@@ -0,0 +1,9 @@
KTAP version 1
1..1
KTAP version 1
# Subtest: suite
# module: example
1..1
# test.speed: slow
ok 1 test
ok 1 suite

Some files were not shown because too many files have changed in this diff Show More