git: 11ba214629b1 - main - bhyve: add basic TPM passthrough emulation

From: Corvin Köhne <corvink_at_FreeBSD.org>
Date: Fri, 16 Jun 2023 06:23:04 UTC
The branch main has been updated by corvink:

URL: https://cgit.FreeBSD.org/src/commit/?id=11ba214629b1c1379a29451af8af7e399713aa5a

commit 11ba214629b1c1379a29451af8af7e399713aa5a
Author:     Corvin Köhne <corvink@FreeBSD.org>
AuthorDate: 2023-05-15 12:04:15 +0000
Commit:     Corvin Köhne <corvink@FreeBSD.org>
CommitDate: 2023-06-16 06:18:55 +0000

    bhyve: add basic TPM passthrough emulation
    
    At the moment, the emulation only opens a file descriptor to the TPM
    device. Some subsequent commits will read and write from it.
    
    Reviewed by:            markj
    MFC after:              1 week
    Sponsored by:           Beckhoff Automation GmbH & Co. KG
    Differential Revision:  https://reviews.freebsd.org/D40455
---
 usr.sbin/bhyve/Makefile            |  1 +
 usr.sbin/bhyve/tpm_emul_passthru.c | 69 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)

diff --git a/usr.sbin/bhyve/Makefile b/usr.sbin/bhyve/Makefile
index 08eb41c430d5..fc880566228b 100644
--- a/usr.sbin/bhyve/Makefile
+++ b/usr.sbin/bhyve/Makefile
@@ -76,6 +76,7 @@ SRCS=	\
 	spinup_ap.c		\
 	task_switch.c		\
 	tpm_device.c		\
+	tpm_emul_passthru.c	\
 	uart_emul.c		\
 	usb_emul.c		\
 	usb_mouse.c		\
diff --git a/usr.sbin/bhyve/tpm_emul_passthru.c b/usr.sbin/bhyve/tpm_emul_passthru.c
new file mode 100644
index 000000000000..9d706dee7120
--- /dev/null
+++ b/usr.sbin/bhyve/tpm_emul_passthru.c
@@ -0,0 +1,69 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2023 Beckhoff Automation GmbH & Co. KG
+ * Author: Corvin Köhne <corvink@FreeBSD.org>
+ */
+
+#include <sys/types.h>
+
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <malloc_np.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "config.h"
+#include "tpm_device.h"
+#include "tpm_emul.h"
+
+struct tpm_passthru {
+	int fd;
+};
+
+static int
+tpm_passthru_init(void **sc, nvlist_t *nvl)
+{
+	struct tpm_passthru *tpm;
+	const char *path;
+	
+	tpm = calloc(1, sizeof(struct tpm_passthru));
+	if (tpm == NULL) {
+		warnx("%s: failed to allocate tpm passthru", __func__);
+		return (ENOMEM);
+	}
+
+	path = get_config_value_node(nvl, "path");
+	tpm->fd = open(path, O_RDWR);
+	if (tpm->fd < 0) {
+		warnx("%s: unable to open tpm device \"%s\"", __func__, path);
+		return (ENOENT);
+	}
+
+	*sc = tpm;
+
+	return (0);
+}
+
+static void
+tpm_passthru_deinit(void *sc)
+{
+	struct tpm_passthru *tpm;
+
+	tpm = sc;
+	if (tpm == NULL)
+		return;
+
+	if (tpm->fd >= 0)
+		close(tpm->fd);
+
+	free(tpm);
+}
+
+static const struct tpm_emul tpm_emul_passthru = {
+	.name = "passthru",
+	.init = tpm_passthru_init,
+	.deinit = tpm_passthru_deinit,
+};
+TPM_EMUL_SET(tpm_emul_passthru);