Add in-kernel test runner

This adds a way to run tests inside the Smalltown kernel.

Improvements to the Bazel part of this are tracked in T726

Test Plan: Tested by intentionally failing the test.

X-Origin-Diff: phab/D485
GitOrigin-RevId: e4aad7f28d122d82a7fcb6699e678cbe022e2f73
diff --git a/core/pkg/fsquota/BUILD.bazel b/core/pkg/fsquota/BUILD.bazel
index 6971929..8feeede 100644
--- a/core/pkg/fsquota/BUILD.bazel
+++ b/core/pkg/fsquota/BUILD.bazel
@@ -1,4 +1,5 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+load("//core/tools/ktest:ktest.bzl", "ktest")
 
 go_library(
     name = "go_default_library",
@@ -14,3 +15,25 @@
         "@org_golang_x_sys//unix:go_default_library",
     ],
 )
+
+go_test(
+    name = "go_default_test",
+    srcs = ["fsquota_test.go"],
+    embed = [":go_default_library"],
+    pure = "on",
+    deps = [
+        "@com_github_stretchr_testify//require:go_default_library",
+        "@org_golang_x_sys//unix:go_default_library",
+    ],
+)
+
+ktest(
+    tester = ":go_default_test",
+    deps = [
+        "//third_party/xfsprogs:mkfs.xfs",
+    ],
+    initramfs_extra = """
+file /mkfs.xfs $(location //third_party/xfsprogs:mkfs.xfs) 0755 0 0
+    """,
+    cmdline = "ramdisk_size=51200",
+)
diff --git a/core/pkg/fsquota/fsquota.go b/core/pkg/fsquota/fsquota.go
index f4f4050..e2d871a 100644
--- a/core/pkg/fsquota/fsquota.go
+++ b/core/pkg/fsquota/fsquota.go
@@ -137,7 +137,7 @@
 		return nil, err
 	}
 	return &Quota{
-		Bytes:      quota.BHardLimit,
+		Bytes:      quota.BHardLimit * 1024,
 		BytesUsed:  quota.CurSpace,
 		Inodes:     quota.IHardLimit,
 		InodesUsed: quota.CurInodes,
diff --git a/core/pkg/fsquota/fsquota_test.go b/core/pkg/fsquota/fsquota_test.go
new file mode 100644
index 0000000..4729dac
--- /dev/null
+++ b/core/pkg/fsquota/fsquota_test.go
@@ -0,0 +1,152 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fsquota
+
+import (
+	"fmt"
+	"io/ioutil"
+	"math"
+	"os"
+	"os/exec"
+	"syscall"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+	"golang.org/x/sys/unix"
+)
+
+// withinTolerance is a helper for asserting that a value is within a certain percentage of the
+// expected value. The tolerance is specified as a float between 0 (exact match)
+// and 1 (between 0 and twice the expected value).
+func withinTolerance(t *testing.T, expected uint64, actual uint64, tolerance float64, name string) {
+	t.Helper()
+	delta := uint64(math.Round(float64(expected) * tolerance))
+	lowerBound := expected - delta
+	upperBound := expected + delta
+	if actual < lowerBound {
+		t.Errorf("Value %v (%v) is too low, expected between %v and %v", name, actual, lowerBound, upperBound)
+	}
+	if actual > upperBound {
+		t.Errorf("Value %v (%v) is too high, expected between %v and %v", name, actual, lowerBound, upperBound)
+	}
+}
+
+func TestBasic(t *testing.T) {
+	if os.Getenv("IN_KTEST") != "true" {
+		t.Skip("Not in ktest")
+	}
+	mkfsCmd := exec.Command("/mkfs.xfs", "-qf", "/dev/ram0")
+	if _, err := mkfsCmd.Output(); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.Mkdir("/test", 0755); err != nil {
+		t.Error(err)
+	}
+
+	if err := unix.Mount("/dev/ram0", "/test", "xfs", unix.MS_NOEXEC|unix.MS_NODEV, "prjquota"); err != nil {
+		t.Fatal(err)
+	}
+	defer unix.Unmount("/test", 0)
+	defer os.RemoveAll("/test")
+	t.Run("SetQuota", func(t *testing.T) {
+		defer func() {
+			os.RemoveAll("/test/set")
+		}()
+		if err := os.Mkdir("/test/set", 0755); err != nil {
+			t.Fatal(err)
+		}
+		if err := SetQuota("/test/set", 1024*1024, 100); err != nil {
+			t.Fatal(err)
+		}
+	})
+	t.Run("SetQuotaAndExhaust", func(t *testing.T) {
+		defer func() {
+			os.RemoveAll("/test/sizequota")
+		}()
+		if err := os.Mkdir("/test/sizequota", 0755); err != nil {
+			t.Fatal(err)
+		}
+		const bytesQuota = 1024 * 1024 // 1MiB
+		if err := SetQuota("/test/sizequota", bytesQuota, 0); err != nil {
+			t.Fatal(err)
+		}
+		testfile, err := os.Create("/test/sizequota/testfile")
+		if err != nil {
+			t.Fatal(err)
+		}
+		testdata := make([]byte, 1024)
+		var bytesWritten int
+		for {
+			n, err := testfile.Write([]byte(testdata))
+			if err != nil {
+				if pathErr, ok := err.(*os.PathError); ok {
+					if pathErr.Err == syscall.ENOSPC {
+						// Running out of space is the only acceptable error to continue execution
+						break
+					}
+				}
+				t.Fatal(err)
+			}
+			bytesWritten += n
+		}
+		if bytesWritten > bytesQuota {
+			t.Errorf("Wrote %v bytes, quota is only %v bytes", bytesWritten, bytesQuota)
+		}
+	})
+	t.Run("GetQuotaReadbackAndUtilization", func(t *testing.T) {
+		defer func() {
+			os.RemoveAll("/test/readback")
+		}()
+		if err := os.Mkdir("/test/readback", 0755); err != nil {
+			t.Fatal(err)
+		}
+		const bytesQuota = 1024 * 1024 // 1MiB
+		const inodesQuota = 100
+		if err := SetQuota("/test/readback", bytesQuota, inodesQuota); err != nil {
+			t.Fatal(err)
+		}
+		sizeFileData := make([]byte, 512*1024)
+		if err := ioutil.WriteFile("/test/readback/512kfile", sizeFileData, 0644); err != nil {
+			t.Fatal(err)
+		}
+
+		quotaUtil, err := GetQuota("/test/readback")
+		if err != nil {
+			t.Fatal(err)
+		}
+		require.Equal(t, uint64(bytesQuota), quotaUtil.Bytes, "bytes quota readback incorrect")
+		require.Equal(t, uint64(inodesQuota), quotaUtil.Inodes, "inodes quota readback incorrect")
+
+		// Give 10% tolerance for quota used values to account for metadata overhead and internal
+		// structures that are also in there. If it's out by more than that it's an issue anyways.
+		withinTolerance(t, uint64(len(sizeFileData)), quotaUtil.BytesUsed, 0.1, "BytesUsed")
+
+		// Write 50 inodes for a total of 51 (with the 512K file)
+		for i := 0; i < 50; i++ {
+			if err := ioutil.WriteFile(fmt.Sprintf("/test/readback/ifile%v", i), []byte("test"), 0644); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		quotaUtil, err = GetQuota("/test/readback")
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		withinTolerance(t, 51, quotaUtil.InodesUsed, 0.1, "InodesUsed")
+	})
+}
diff --git a/core/tools/kconfig-patcher/BUILD.bazel b/core/tools/kconfig-patcher/BUILD.bazel
new file mode 100644
index 0000000..7c61d4f
--- /dev/null
+++ b/core/tools/kconfig-patcher/BUILD.bazel
@@ -0,0 +1,20 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["main.go"],
+    importpath = "git.monogon.dev/source/nexantic.git/core/tools/kconfig-patcher",
+    visibility = ["//visibility:private"],
+)
+
+go_binary(
+    name = "kconfig-patcher",
+    embed = [":go_default_library"],
+    visibility = ["//visibility:public"],
+)
+
+go_test(
+    name = "go_default_test",
+    srcs = ["main_test.go"],
+    embed = [":go_default_library"],
+)
diff --git a/core/tools/kconfig-patcher/kconfig-patcher.bzl b/core/tools/kconfig-patcher/kconfig-patcher.bzl
new file mode 100644
index 0000000..a6af343
--- /dev/null
+++ b/core/tools/kconfig-patcher/kconfig-patcher.bzl
@@ -0,0 +1,33 @@
+#  Copyright 2020 The Monogon Project Authors.
+#
+#  SPDX-License-Identifier: Apache-2.0
+#
+#  Licensed under the Apache License, Version 2.0 (the "License");
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+"""Override configs in a Linux kernel Kconfig
+"""
+
+def kconfig_patch(name, src, out, override_configs, **kwargs):
+    native.genrule(
+        name = name,
+        srcs = [src],
+        outs = [out],
+        tools = [
+            "//core/tools/kconfig-patcher",
+        ],
+        cmd = """
+        $(location //core/tools/kconfig-patcher) \
+            -in $< -out $@ '%s'
+        """ % struct(overrides = override_configs).to_json(),
+        **kwargs
+    )
diff --git a/core/tools/kconfig-patcher/main.go b/core/tools/kconfig-patcher/main.go
new file mode 100644
index 0000000..27c33e9
--- /dev/null
+++ b/core/tools/kconfig-patcher/main.go
@@ -0,0 +1,95 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+	"bufio"
+	"encoding/json"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+)
+
+var (
+	inPath  = flag.String("in", "", "Path to input Kconfig")
+	outPath = flag.String("out", "", "Path to output Kconfig")
+)
+
+func main() {
+	flag.Parse()
+	if *inPath == "" || *outPath == "" {
+		flag.PrintDefaults()
+		os.Exit(2)
+	}
+	inFile, err := os.Open(*inPath)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to open input Kconfig: %v\n", err)
+		os.Exit(1)
+	}
+	outFile, err := os.Create(*outPath)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to create output Kconfig: %v\n", err)
+		os.Exit(1)
+	}
+	var config struct {
+		Overrides map[string]string `json:"overrides"`
+	}
+	if err := json.Unmarshal([]byte(flag.Arg(0)), &config); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to parse overrides: %v\n", err)
+		os.Exit(1)
+	}
+	err = patchKconfig(inFile, outFile, config.Overrides)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to patch: %v\n", err)
+		os.Exit(1)
+	}
+}
+
+func patchKconfig(inFile io.Reader, outFile io.Writer, overrides map[string]string) error {
+	scanner := bufio.NewScanner(inFile)
+	for scanner.Scan() {
+		line := scanner.Text()
+		cleanLine := strings.TrimSpace(line)
+		if strings.HasPrefix(cleanLine, "#") || cleanLine == "" {
+			// Pass through comments and empty lines
+			fmt.Fprintln(outFile, line)
+		} else {
+			// Line contains a configuration option
+			parts := strings.SplitN(line, "=", 2)
+			keyName := parts[0]
+			if overrideVal, ok := overrides[strings.TrimSpace(keyName)]; ok {
+				// Override it
+				if overrideVal == "" {
+					fmt.Fprintf(outFile, "# %v is not set\n", keyName)
+				} else {
+					fmt.Fprintf(outFile, "%v=%v\n", keyName, overrideVal)
+				}
+				delete(overrides, keyName)
+			} else {
+				// Pass through unchanged
+				fmt.Fprintln(outFile, line)
+			}
+		}
+	}
+	// Process left over overrides
+	for key, val := range overrides {
+		fmt.Fprintf(outFile, "%v=%v\n", key, val)
+	}
+	return nil
+}
diff --git a/core/tools/kconfig-patcher/main_test.go b/core/tools/kconfig-patcher/main_test.go
new file mode 100644
index 0000000..11c7d84
--- /dev/null
+++ b/core/tools/kconfig-patcher/main_test.go
@@ -0,0 +1,61 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+	"bytes"
+	"strings"
+	"testing"
+)
+
+func Test_patchKconfig(t *testing.T) {
+	type args struct {
+		inFile    string
+		overrides map[string]string
+	}
+	tests := []struct {
+		name        string
+		args        args
+		wantOutFile string
+		wantErr     bool
+	}{
+		{
+			"passthroughExtend",
+			args{inFile: "# TEST=y\n\n", overrides: map[string]string{"TEST": "n"}},
+			"# TEST=y\n\nTEST=n\n",
+			false,
+		},
+		{
+			"patch",
+			args{inFile: "TEST=y\nTEST_NO=n\n", overrides: map[string]string{"TEST": "n"}},
+			"TEST=n\nTEST_NO=n\n",
+			false,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			outFile := &bytes.Buffer{}
+			if err := patchKconfig(strings.NewReader(tt.args.inFile), outFile, tt.args.overrides); (err != nil) != tt.wantErr {
+				t.Errorf("patchKconfig() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if gotOutFile := outFile.String(); gotOutFile != tt.wantOutFile {
+				t.Errorf("patchKconfig() = %v, want %v", gotOutFile, tt.wantOutFile)
+			}
+		})
+	}
+}
diff --git a/core/tools/ktest/BUILD b/core/tools/ktest/BUILD
new file mode 100644
index 0000000..e139a18
--- /dev/null
+++ b/core/tools/ktest/BUILD
@@ -0,0 +1,62 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+load("//core/tools/kconfig-patcher:kconfig-patcher.bzl", "kconfig_patch")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["main.go"],
+    importpath = "git.monogon.dev/source/nexantic.git/core/tools/ktest",
+    visibility = ["//visibility:private"],
+)
+
+go_binary(
+    name = "ktest",
+    embed = [":go_default_library"],
+    pure = "on",
+    visibility = ["//visibility:public"],
+)
+
+kconfig_patch(
+    name = "testing-config",
+    src = "//third_party/linux:kernel-config",
+    out = "testing.config",
+    override_configs = {
+        # Unlock command line
+        "CONFIG_CMDLINE_OVERRIDE": "n",
+        "CONFIG_CMDLINE_BOOL": "n",
+        # Shave off 1 second from boot time
+        "CONFIG_SERIO_I8042": "",
+        "CONFIG_KEYBOARD_ATKBD": "",
+        "CONFIG_RTC_DRV_CMOS": "",
+        # Shave off an additional 18ms (half of the boot time)
+        "CONFIG_DEBUG_WX": "",
+    },
+)
+
+genrule(
+    name = "linux-testing",
+    srcs = [
+        "@linux//:all",
+        ":testing-config",
+    ],
+    outs = [
+        "linux-testing.elf",
+    ],
+    cmd = """
+    DIR=external/linux
+
+    mkdir $$DIR/.bin
+
+    cp $(location :testing-config) $$DIR/.config
+
+    (cd $$DIR && make -j $$(nproc) vmlinux >/dev/null)
+
+    cp $$DIR/vmlinux $@
+    """,
+    visibility = ["//visibility:public"],
+)
+
+filegroup(
+    name = "test-script",
+    srcs = ["run_ktest.sh"],
+    visibility = ["//visibility:public"],
+)
diff --git a/core/tools/ktest/ktest.bzl b/core/tools/ktest/ktest.bzl
new file mode 100644
index 0000000..03a7d5c
--- /dev/null
+++ b/core/tools/ktest/ktest.bzl
@@ -0,0 +1,61 @@
+#  Copyright 2020 The Monogon Project Authors.
+#
+#  SPDX-License-Identifier: Apache-2.0
+#
+#  Licensed under the Apache License, Version 2.0 (the "License");
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+"""
+Ktest provides a simple macro to run tests inside the normal Smalltown kernel
+"""
+
+def ktest(deps, tester, initramfs_extra, cmdline):
+    native.genrule(
+        name = "test_initramfs",
+        srcs = [
+            "//core/tools/ktestinit",
+        ] + deps + [tester],
+        outs = [
+            "initramfs.cpio.lz4",
+        ],
+        testonly = True,
+        cmd = """
+        $(location @linux//:gen_init_cpio) - <<- 'EOF' | lz4 -l > \"$@\" 
+dir /dev 0755 0 0
+nod /dev/console 0600 0 0 c 5 1
+nod /dev/null 0644 0 0 c 1 3
+file /init $(location //core/tools/ktestinit) 0755 0 0
+file /tester $(location """ + tester + """) 0755 0 0
+""" + initramfs_extra + """
+EOF
+        """,
+        tools = [
+            "@linux//:gen_init_cpio",
+        ],
+    )
+
+    native.sh_test(
+        name = "ktest",
+        args = [
+            "$(location //core/tools/ktest)",
+            "$(location :test_initramfs)",
+            "$(location //core/tools/ktest:linux-testing)",
+            cmdline,
+        ],
+        size = "small",
+        srcs = ["//core/tools/ktest:test-script"],
+        data = [
+            "//core/tools/ktest",
+            ":test_initramfs",
+            "//core/tools/ktest:linux-testing",
+        ],
+    )
\ No newline at end of file
diff --git a/core/tools/ktest/main.go b/core/tools/ktest/main.go
new file mode 100644
index 0000000..67ad21a
--- /dev/null
+++ b/core/tools/ktest/main.go
@@ -0,0 +1,101 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ktest is a test launcher for running tests inside a custom kernel and passes the results
+// back out.
+package main
+
+import (
+	"crypto/rand"
+	"flag"
+	"fmt"
+	"io"
+	"log"
+	"net"
+	"os"
+	"os/exec"
+	"path/filepath"
+)
+
+var (
+	kernelPath = flag.String("kernel-path", "", "Path of the Kernel ELF file")
+	initrdPath = flag.String("initrd-path", "", "Path of the initrd image")
+	cmdline    = flag.String("cmdline", "", "Additional kernel command line options")
+)
+
+func main() {
+	flag.Parse()
+
+	// Create a temporary socket for passing data (currently only exit code)
+	// TODO: Land https://patchwork.ozlabs.org/project/qemu-devel/patch/1357671226-11334-1-git-send-email-alexander_barabash@mentor.com/
+	tmpDir := os.TempDir()
+	token := make([]byte, 16)
+	if _, err := io.ReadFull(rand.Reader, token); err != nil {
+		log.Fatal(err)
+	}
+
+	socketPath := filepath.Join(tmpDir, fmt.Sprintf("qemu-io-%x", token))
+	l, err := net.Listen("unix", socketPath)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer l.Close()
+	defer os.Remove(socketPath)
+
+	// Start a QEMU microvm (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with only
+	// a RNG and two character devices (one for console, one for OOB communication) attached.
+	cmd := exec.Command("qemu-system-x86_64", "-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
+		"-accel", "kvm", "-cpu", "host",
+		"-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
+		"-kernel", *kernelPath,
+		"-append", "reboot=t console=hvc0 quiet "+*cmdline,
+		"-initrd", *initrdPath,
+		"-device", "virtio-rng-device,max-bytes=1024,period=1000",
+		"-device", "virtio-serial-device,max_ports=2",
+		"-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
+		"-chardev", "socket,id=io,path="+socketPath, "-device", "virtserialport,chardev=io",
+	)
+
+	cmd.Stdout = os.Stdout
+	cmd.Stderr = os.Stderr
+
+	exitCodeChan := make(chan uint8, 1)
+
+	go func() {
+		conn, err := l.Accept()
+		if err != nil {
+			log.Fatal(err)
+		}
+		defer conn.Close()
+
+		returnCode := make([]byte, 1)
+		if _, err := conn.Read(returnCode); err != nil && err != io.EOF {
+			log.Fatalf("Failed to read socket: %v", err)
+		}
+		exitCodeChan <- returnCode[0]
+	}()
+
+	if err := cmd.Run(); err != nil {
+		log.Fatalf("Failed to run QEMU: %v", err)
+	}
+	select {
+	case exitCode := <-exitCodeChan:
+		os.Exit(int(exitCode))
+	default:
+		log.Printf("Failed to get an error code back")
+		os.Exit(1)
+	}
+}
diff --git a/core/tools/ktest/run_ktest.sh b/core/tools/ktest/run_ktest.sh
new file mode 100755
index 0000000..02920a1
--- /dev/null
+++ b/core/tools/ktest/run_ktest.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+exec "$1" -initrd-path "$2" -kernel-path "$3" -cmdline "$4"
\ No newline at end of file
diff --git a/core/tools/ktestinit/BUILD.bazel b/core/tools/ktestinit/BUILD.bazel
new file mode 100644
index 0000000..74eb742
--- /dev/null
+++ b/core/tools/ktestinit/BUILD.bazel
@@ -0,0 +1,16 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["main.go"],
+    importpath = "git.monogon.dev/source/nexantic.git/core/tools/ktestinit",
+    visibility = ["//visibility:private"],
+    deps = ["@org_golang_x_sys//unix:go_default_library"],
+)
+
+go_binary(
+    name = "ktestinit",
+    embed = [":go_default_library"],
+    pure = "on",
+    visibility = ["//visibility:public"],
+)
diff --git a/core/tools/ktestinit/main.go b/core/tools/ktestinit/main.go
new file mode 100644
index 0000000..9eb2342
--- /dev/null
+++ b/core/tools/ktestinit/main.go
@@ -0,0 +1,80 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ktestinit is an init designed to run inside a lightweight VM for running tests in there.
+// It performs basic platform initialization like mounting kernel filesystems and launches the
+// test executable at /tester, passes the exit code back out over the control socket to ktest and
+// then terminates the VM kernel.
+package main
+
+import (
+	"errors"
+	"fmt"
+	"os"
+	"os/exec"
+
+	"golang.org/x/sys/unix"
+)
+
+func mountInit() error {
+	for _, el := range []struct {
+		dir   string
+		fs    string
+		flags uintptr
+	}{
+		{"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
+		{"/proc", "proc", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
+		{"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
+		{"/dev/pts", "devpts", unix.MS_NOEXEC | unix.MS_NOSUID},
+	} {
+		if err := os.Mkdir(el.dir, 0755); err != nil && !os.IsExist(err) {
+			return fmt.Errorf("could not make %s: %w", el.dir, err)
+		}
+		if err := unix.Mount(el.fs, el.dir, el.fs, el.flags, ""); err != nil {
+			return fmt.Errorf("could not mount %s on %s: %w", el.fs, el.dir, err)
+		}
+	}
+	return nil
+}
+
+func main() {
+	if err := mountInit(); err != nil {
+		panic(err)
+	}
+
+	// First virtual serial is always stdout, second is control
+	ioConn, err := os.OpenFile("/dev/vport1p1", os.O_RDWR, 0)
+	if err != nil {
+		fmt.Printf("Failed to open communication device: %v\n", err)
+		return
+	}
+	cmd := exec.Command("/tester", "-test.v")
+	cmd.Stderr = os.Stderr
+	cmd.Stdout = os.Stdout
+	cmd.Env = append(cmd.Env, "IN_KTEST=true")
+	if err := cmd.Run(); err != nil {
+		var exerr *exec.ExitError
+		if errors.As(err, &exerr) {
+			if _, err := ioConn.Write([]byte{uint8(exerr.ExitCode())}); err != nil {
+				panic(err)
+			}
+		} else if err != nil {
+			fmt.Printf("Failed to execute tests (tests didn't run): %v", err)
+		}
+	}
+
+	unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
+}
diff --git a/third_party/linux/BUILD.bazel b/third_party/linux/BUILD.bazel
index 3829f96..48f811b 100644
--- a/third_party/linux/BUILD.bazel
+++ b/third_party/linux/BUILD.bazel
@@ -20,3 +20,9 @@
     """,
     visibility = ["//visibility:public"],
 )
+
+filegroup(
+    name = "kernel-config",
+    srcs = ["linux-smalltown.config"],
+    visibility = ["//visibility:public"],
+)
diff --git a/third_party/linux/linux-smalltown.config b/third_party/linux/linux-smalltown.config
index 9c01456..21cc824 100644
--- a/third_party/linux/linux-smalltown.config
+++ b/third_party/linux/linux-smalltown.config
@@ -1606,30 +1606,7 @@
 # CONFIG_KEYBOARD_STOWAWAY is not set
 # CONFIG_KEYBOARD_SUNKBD is not set
 # CONFIG_KEYBOARD_XTKBD is not set
-CONFIG_INPUT_MOUSE=y
-CONFIG_MOUSE_PS2=y
-CONFIG_MOUSE_PS2_ALPS=y
-CONFIG_MOUSE_PS2_BYD=y
-CONFIG_MOUSE_PS2_LOGIPS2PP=y
-CONFIG_MOUSE_PS2_SYNAPTICS=y
-CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS=y
-CONFIG_MOUSE_PS2_CYPRESS=y
-CONFIG_MOUSE_PS2_LIFEBOOK=y
-CONFIG_MOUSE_PS2_TRACKPOINT=y
-# CONFIG_MOUSE_PS2_ELANTECH is not set
-# CONFIG_MOUSE_PS2_SENTELIC is not set
-# CONFIG_MOUSE_PS2_TOUCHKIT is not set
-CONFIG_MOUSE_PS2_FOCALTECH=y
-# CONFIG_MOUSE_PS2_VMMOUSE is not set
-CONFIG_MOUSE_PS2_SMBUS=y
-# CONFIG_MOUSE_SERIAL is not set
-# CONFIG_MOUSE_APPLETOUCH is not set
-# CONFIG_MOUSE_BCM5974 is not set
-# CONFIG_MOUSE_CYAPA is not set
-# CONFIG_MOUSE_ELAN_I2C is not set
-# CONFIG_MOUSE_VSXXXAA is not set
-# CONFIG_MOUSE_SYNAPTICS_I2C is not set
-# CONFIG_MOUSE_SYNAPTICS_USB is not set
+# CONFIG_INPUT_MOUSE is not set
 # CONFIG_INPUT_JOYSTICK is not set
 # CONFIG_INPUT_TABLET is not set
 # CONFIG_INPUT_TOUCHSCREEN is not set
@@ -2414,7 +2391,8 @@
 CONFIG_VIRTIO_PCI_LEGACY=y
 CONFIG_VIRTIO_BALLOON=y
 # CONFIG_VIRTIO_INPUT is not set
-# CONFIG_VIRTIO_MMIO is not set
+CONFIG_VIRTIO_MMIO=y
+CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y
 
 #
 # Microsoft Hyper-V guest support
@@ -2709,7 +2687,7 @@
 # CONFIG_FANOTIFY is not set
 CONFIG_QUOTA=y
 # CONFIG_QUOTA_NETLINK_INTERFACE is not set
-CONFIG_PRINT_QUOTA_WARNING=y
+# CONFIG_PRINT_QUOTA_WARNING is not set
 # CONFIG_QUOTA_DEBUG is not set
 # CONFIG_QFMT_V1 is not set
 # CONFIG_QFMT_V2 is not set