Skip to contentSkip to conversation

tpm: robust stack allocations

PATCH Superseded Jarkko Sakkinen 3 participants 12 messages Sep 21, 2025 – Sep 24, 2025

Subsystems (4)

v10 of 11 Superseded Latest is v11 →

lore
Share & tools
lore

Jarkko Sakkinen

author maintainer
#0 lore raw

v10 cover tpm: robust stack allocations

1. These are previous changes to tpm_buf, which make stack allocations much more feasible than previously.
2. Migrate low-hanging fruit to use stack allocations.

Jarkko Sakkinen (4):
tpm: Make TPM buffer allocations more robust tpm, tpm1-cmd: Use stack for trivial cases tpm, tpm2-cmd: Use stack for trivial cases
tpm_vpm_proxy: Use stack for TPM_CC_SET_LOCALITY

 drivers/char/tpm/tpm-buf.c                | 137 ++++++----
 drivers/char/tpm/tpm-dev-common.c         |   4 +-
 drivers/char/tpm/tpm-dev.h                |   2 +-
 drivers/char/tpm/tpm-interface.c          |   4 +-
 drivers/char/tpm/tpm-sysfs.c              |  20 +-
 drivers/char/tpm/tpm.h                    |   3 +-
 drivers/char/tpm/tpm1-cmd.c               | 151 +++++------
 drivers/char/tpm/tpm2-cmd.c               | 297 ++++++++++------------
 drivers/char/tpm/tpm2-sessions.c          | 121 +++++----
 drivers/char/tpm/tpm2-space.c             |  44 ++--
 drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
 drivers/char/tpm/tpm_vtpm_proxy.c         |  34 +--
 include/linux/tpm.h                       |  28 +-
 security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
 security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
 15 files changed, 493 insertions(+), 546 deletions(-)
Signature · 1 line
2.39.5
author maintainer
#1 lore raw

PATCH v10 1/4 tpm: Make TPM buffer allocations more robust

From: Jarkko Sakkinen <[email protected]>

Create more ergonomic primitives to work with TPM buffers, where 'tpm_buf_init*' initialize the memory and 'tpm_buf_reset*' (re)set a buffer for a particular use and purpose. The new primitives are ubiquitos when it comes to heap and stack usage.

Given that the kzalloc is decoupled, a managed allocation can be done trivially:

	struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUF_MAX_SIZE,
							GFP_KERNEL);

This effectively zeros out the odds having any memory leaks with TPM buffers. The new structures can be later used to widen the use of stack over heap in the subsystem in the critical code paths..

---
v10:
- No changes.
v9:
- Rename pre-existing TPM_BUFSIZE as TPM_BUF_MAX_SIZE and redeclare it in include/linux/tpm.h, and use this constant instead of PAGE_SIZE in tpm_buf_init*. Define TPM_BUF_MIN_SIZE to be a sane placeholder value for stack allocations.
- Fix and restructure invariant for the sake of clarity.
- memset buffers to zero in tpm_buf_init* in order to guarantee a legit initial state. This does not cause any regressions but once tpm_buf is allocaed from stack at some site, this will zero out chance of corrupted state.
v8:
- Decouple memory init i.e. bring tpm_init* back but with new fresh form.
- Cap buf_size to page size and also make checks in tpm_buf_append safe:
https://lore.kernel.org/linux-integrity/hwsx2t2tkbos3g7k2syemxbvc6sfrsbviwm64ubcdl6ms7ljvo@toetomkhheht/
- Fix trusted_tpm_send() and simplify the flow.
v7:
- Additional function comments and invariant was unfortunately left to my staging area so here's the addition (does not affect functionality).
v6:
- Removed two empty lines as requested by Stefan:
https://lore.kernel.org/linux-integrity/[email protected]/
- Add 'capacity' field as this makes easy to stretch tpm_buf into stack allocation.
v5:
- I tested this version also with TPM 1.2 by booting up and checking that sysfs attributes work.
- Fixed the length check against capacity (James) with TPM_BUF_CAPACITY.
- Fixed declaration style: do it at the site (Jason).
- Improved commit message (Stefan).
- Removed "out" label from tpm2_pcr_read() (Stefan).
- Removed spurious "return rc;" from tpm2_get_pcr_allocation() (Stefan). v4:
- Wrote a more a descriptive short summary and improved description.
- Fixed the error in documentation: there is 4090 bytes of space left for the payload - not 4088 bytes.
- Turned tpm_buf_alloc() into inline function.
v3:
- Removed the cleanup class and moved on using __free(kfree) instead.
- Removed buf_size (James).
- I'm open for the idea of splitting still (Jason) but I'll hold at least this revision just to check that my core idea here is correct.
v2:
- Implement also memory allocation using the cleanup class.
- Rewrote the commit message.
- Implemented CLASS_TPM_BUF() helper macro.

---
 drivers/char/tpm/tpm-buf.c                | 137 +++++++----
 drivers/char/tpm/tpm-dev-common.c         |   4 +-
 drivers/char/tpm/tpm-dev.h                |   2 +-
 drivers/char/tpm/tpm-interface.c          |   4 +-
 drivers/char/tpm/tpm-sysfs.c              |  20 +-
 drivers/char/tpm/tpm.h                    |   3 +-
 drivers/char/tpm/tpm1-cmd.c               | 149 ++++++------
 drivers/char/tpm/tpm2-cmd.c               | 282 ++++++++++------------
 drivers/char/tpm/tpm2-sessions.c          | 121 +++++-----
 drivers/char/tpm/tpm2-space.c             |  44 ++--
 drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
 drivers/char/tpm/tpm_vtpm_proxy.c         |  32 ++-
 include/linux/tpm.h                       |  28 ++-
 security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
 security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
 15 files changed, 493 insertions(+), 527 deletions(-)
drivers/char/tpm/tpm-buf.c +84 -53
index dc882fc9fa9e..82dce0350a41 100644
@@ -7,82 +7,107 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-/**
- * tpm_buf_init() - Allocate and initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- *
- * Return: 0 or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
+	if (!buf->capacity) {
+		if (buf_size > TPM_BUF_MAX_SIZE) {
+			WARN(1, "%s: size overflow: %u\n", __func__, buf_size);
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	} else {
+		if (buf_size != buf->capacity + sizeof(*buf)) {
+			WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
+			     buf->capacity + sizeof(*buf));
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	}
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-/**
- * tpm_buf_reset() - Initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- */
-void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_reset(struct tpm_buf *buf, u16 buf_size, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
 		tag != TPM2_ST_SESSIONS && tag != 0);
 
 	buf->flags = 0;
 	buf->length = sizeof(*head);
+	buf->capacity = buf_size - sizeof(*buf);
+	buf->handles = 0;
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+}
+
+static void __tpm_buf_reset_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->capacity = buf_size - sizeof(*buf);
 	buf->handles = 0;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
 /**
- * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
- * @buf:	A @tpm_buf
- *
- * Return: 0 or -ENOMEM
+ * tpm_buf_init() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
  */
-int tpm_buf_init_sized(struct tpm_buf *buf)
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset(buf, buf_size, TPM_TAG_RQU_COMMAND, 0);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-	tpm_buf_reset_sized(buf);
-	return 0;
+/**
+ * tpm_buf_init_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
+ */
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset_sized(buf, buf_size);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
 
 /**
- * tpm_buf_reset_sized() - Initialize a sized buffer
+ * tpm_buf_reset() - Re-initialize a TPM command
  * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
  */
-void tpm_buf_reset_sized(struct tpm_buf *buf)
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
-	buf->flags = TPM_BUF_TPM2B;
-	buf->length = 2;
-	buf->data[0] = 0;
-	buf->data[1] = 0;
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset(buf, buf_size, tag, ordinal);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
-void tpm_buf_destroy(struct tpm_buf *buf)
+/**
+ * tpm_buf_reset_sized() - Re-initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
 {
-	free_page((unsigned long)buf->data);
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset_sized(buf, buf_size);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
 
 /**
  * tpm_buf_length() - Return the number of bytes consumed by the data
@@ -92,6 +117,9 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
  */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return 0;
+
 	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,13 +132,14 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
  */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
+	u32 total_length = (u32)buf->length + (u32)new_length;
+
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
-	if ((buf->length + new_length) > PAGE_SIZE) {
+	if (total_length > (u32)buf->capacity) {
 		WARN(1, "tpm_buf: write overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -157,8 +186,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
  */
 void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	if (buf->flags & TPM_BUF_TPM2B) {
-		dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+		dev_err(&chip->dev, "%s: invalid for buffer type: TPM2B\n", __func__);
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -178,13 +211,13 @@ static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void
 	off_t next_offset;
 
 	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
 	next_offset = *offset + count;
 	if (next_offset > buf->length) {
 		WARN(1, "tpm_buf: read out of boundary\n");
-		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -242,5 +275,3 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
-
-
drivers/char/tpm/tpm-dev-common.c +2 -2
index f2a5e09257dd..4f5893555fb7 100644
@@ -147,7 +147,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 
 		rc = copy_to_user(buf, priv->data_buffer + *off, ret_size);
 		if (rc) {
-			memset(priv->data_buffer, 0, TPM_BUFSIZE);
+			memset(priv->data_buffer, 0, TPM_BUF_MAX_SIZE);
 			priv->response_length = 0;
 			ret_size = -EFAULT;
 		} else {
@@ -173,7 +173,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,
 	struct file_priv *priv = file->private_data;
 	int ret = 0;
 
-	if (size > TPM_BUFSIZE)
+	if (size > TPM_BUF_MAX_SIZE)
 		return -E2BIG;
 
 	mutex_lock(&priv->buffer_mutex);
drivers/char/tpm/tpm-dev.h +1 -1
index f3742bcc73e3..700e3d9d8b64 100644
@@ -18,7 +18,7 @@ struct file_priv {
 	bool response_read;
 	bool command_enqueued;
 
-	u8 data_buffer[TPM_BUFSIZE];
+	u8 data_buffer[TPM_BUF_MAX_SIZE];
 };
 
 void tpm_common_open(struct file *file, struct tpm_chip *chip,
drivers/char/tpm/tpm-interface.c +2 -2
index c9f173001d0e..b0d5098fb92b 100644
@@ -100,8 +100,8 @@ static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
 	if (bufsiz < TPM_HEADER_SIZE)
 		return -EINVAL;
 
-	if (bufsiz > TPM_BUFSIZE)
-		bufsiz = TPM_BUFSIZE;
+	if (bufsiz > TPM_BUF_MAX_SIZE)
+		bufsiz = TPM_BUF_MAX_SIZE;
 
 	count = be32_to_cpu(header->length);
 	ordinal = be32_to_cpu(header->ordinal);
drivers/char/tpm/tpm-sysfs.c +10 -10
index 94231f052ea7..4213a8285ed0 100644
@@ -32,28 +32,30 @@ struct tpm_readpubek_out {
 static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,
 			  char *buf)
 {
-	struct tpm_buf tpm_buf;
 	struct tpm_readpubek_out *out;
 	int i;
 	char *str = buf;
 	struct tpm_chip *chip = to_tpm_chip(dev);
 	char anti_replay[20];
 
+	struct tpm_buf *tpm_buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tpm_buf)
+		return -ENOMEM;
+
 	memset(&anti_replay, 0, sizeof(anti_replay));
 
 	if (tpm_try_get_ops(chip))
 		return 0;
 
-	if (tpm_buf_init(&tpm_buf, TPM_TAG_RQU_COMMAND, TPM_ORD_READPUBEK))
-		goto out_ops;
-
-	tpm_buf_append(&tpm_buf, anti_replay, sizeof(anti_replay));
+	tpm_buf_init(tpm_buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_reset(tpm_buf, TPM_TAG_RQU_COMMAND, TPM_ORD_READPUBEK);
+	tpm_buf_append(tpm_buf, anti_replay, sizeof(anti_replay));
 
-	if (tpm_transmit_cmd(chip, &tpm_buf, READ_PUBEK_RESULT_MIN_BODY_SIZE,
+	if (tpm_transmit_cmd(chip, tpm_buf, READ_PUBEK_RESULT_MIN_BODY_SIZE,
 			     "attempting to read the PUBEK"))
-		goto out_buf;
+		goto out_ops;
 
-	out = (struct tpm_readpubek_out *)&tpm_buf.data[10];
+	out = (struct tpm_readpubek_out *)&tpm_buf->data[10];
 	str +=
 	    sprintf(str,
 		    "Algorithm: %4ph\n"
@@ -71,8 +73,6 @@ static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,
 	for (i = 0; i < 256; i += 16)
 		str += sprintf(str, "%16ph\n", &out->modulus[i]);
 
-out_buf:
-	tpm_buf_destroy(&tpm_buf);
 out_ops:
 	tpm_put_ops(chip);
 	return str - buf;
drivers/char/tpm/tpm.h +1 -2
index 2726bd38e5ac..1a4abe54db15 100644
@@ -32,7 +32,6 @@
 #endif
 
 #define TPM_MINOR		224	/* officially assigned */
-#define TPM_BUFSIZE		4096
 #define TPM_NUM_DEVICES		65536
 #define TPM_RETRY		50
 
@@ -224,7 +223,7 @@ enum tpm2_pt_props {
 	TPM2_PT_AUDIT_COUNTER_1 = TPM2_PT_VAR + 20,
 };
 
-/* 128 bytes is an arbitrary cap. This could be as large as TPM_BUFSIZE - 18
+/* 128 bytes is an arbitrary cap. This could be as large as TPM_BUF_MAX_SIZE - 18
  * bytes, but 128 is still a relatively large number of random bytes and
  * anything much bigger causes users of struct tpm_cmd_t to start getting
  * compiler warnings about stack frame size. */
drivers/char/tpm/tpm1-cmd.c +70 -79

271 lines not on this page · raw message

drivers/char/tpm/tpm2-cmd.c +130 -152

522 lines not on this page · raw message

drivers/char/tpm/tpm2-sessions.c +58 -63

224 lines not on this page · raw message

drivers/char/tpm/tpm2-space.c +18 -26

106 lines not on this page · raw message

drivers/char/tpm/tpm_tis_i2c.c +2 -2
index 6cd07dd34507..5832713b1a2c 100644
@@ -232,7 +232,7 @@ static int tpm_tis_i2c_write_bytes(struct tpm_tis_data *data, u32 addr, u16 len,
 	int ret;
 	u16 wrote = 0;
 
-	if (len > TPM_BUFSIZE - 1)
+	if (len > TPM_BUF_MAX_SIZE - 1)
 		return -EIO;
 
 	phy->io_buf[0] = reg;
@@ -339,7 +339,7 @@ static int tpm_tis_i2c_probe(struct i2c_client *dev)
 	if (!phy)
 		return -ENOMEM;
 
-	phy->io_buf = devm_kzalloc(&dev->dev, TPM_BUFSIZE, GFP_KERNEL);
+	phy->io_buf = devm_kzalloc(&dev->dev, TPM_BUF_MAX_SIZE, GFP_KERNEL);
 	if (!phy->io_buf)
 		return -ENOMEM;
 
drivers/char/tpm/tpm_vtpm_proxy.c +14 -18
index 0818bb517805..e5de14379eb2 100644
@@ -42,7 +42,7 @@ struct proxy_dev {
 
 	size_t req_len;              /* length of queued TPM request */
 	size_t resp_len;             /* length of queued TPM response */
-	u8 buffer[TPM_BUFSIZE];      /* request/response buffer */
+	u8 buffer[TPM_BUF_MAX_SIZE];      /* request/response buffer */
 
 	struct work_struct work;     /* task that retrieves TPM timeouts */
 };
@@ -395,40 +395,36 @@ static bool vtpm_proxy_tpm_req_canceled(struct tpm_chip  *chip, u8 status)
 
 static int vtpm_proxy_request_locality(struct tpm_chip *chip, int locality)
 {
-	struct tpm_buf buf;
 	int rc;
 	const struct tpm_header *header;
 	struct proxy_dev *proxy_dev = dev_get_drvdata(&chip->dev);
 
+	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!buf)
+		return -ENOMEM;
+
+	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
-		rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS,
-				  TPM2_CC_SET_LOCALITY);
+		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_SET_LOCALITY);
 	else
-		rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND,
-				  TPM_ORD_SET_LOCALITY);
-	if (rc)
-		return rc;
-	tpm_buf_append_u8(&buf, locality);
+		tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SET_LOCALITY);
+
+	tpm_buf_append_u8(buf, locality);
 
 	proxy_dev->state |= STATE_DRIVER_COMMAND;
 
-	rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to set locality");
+	rc = tpm_transmit_cmd(chip, buf, 0, "attempting to set locality");
 
 	proxy_dev->state &= ~STATE_DRIVER_COMMAND;
 
-	if (rc < 0) {
-		locality = rc;
-		goto out;
-	}
+	if (rc < 0)
+		return rc;
 
-	header = (const struct tpm_header *)buf.data;
+	header = (const struct tpm_header *)buf->data;
 	rc = be32_to_cpu(header->return_code);
 	if (rc)
 		locality = -1;
 
-out:
-	tpm_buf_destroy(&buf);
-
 	return locality;
 }
 
include/linux/tpm.h +15 -13
index dc0338a783f3..a0ce1b565769 100644
@@ -367,22 +367,25 @@ struct tpm_header {
 } __packed;
 
 enum tpm_buf_flags {
-	/* the capacity exceeded: */
-	TPM_BUF_OVERFLOW	= BIT(0),
-	/* TPM2B format: */
-	TPM_BUF_TPM2B		= BIT(1),
-	/* read out of boundary: */
-	TPM_BUF_BOUNDARY_ERROR	= BIT(2),
+	/* TPM2B format */
+	TPM_BUF_TPM2B	= BIT(1),
+	/* overflow or underrun error */
+	TPM_BUF_ERROR	= BIT(2),
 };
 
+#define TPM_BUF_MIN_SIZE	256	/* size for stack allocations */
+#define TPM_BUF_MAX_SIZE	4096	/* size for heap allocations */
+
 /*
- * A string buffer type for constructing TPM commands.
+ * A buffer for constructing and parsing TPM commands, responses and sized
+ * (TPM2B) buffers.
  */
 struct tpm_buf {
-	u32 flags;
-	u32 length;
-	u8 *data;
+	u8 flags;
 	u8 handles;
+	u16 length;
+	u16 capacity;
+	u8 data[];
 };
 
 enum tpm2_object_attributes {
@@ -413,11 +416,10 @@ struct tpm2_hash {
 	unsigned int tpm_id;
 };
 
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size);
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size);
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
-int tpm_buf_init_sized(struct tpm_buf *buf);
 void tpm_buf_reset_sized(struct tpm_buf *buf);
-void tpm_buf_destroy(struct tpm_buf *buf);
 u32 tpm_buf_length(struct tpm_buf *buf);
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length);
 void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
security/keys/trusted-keys/trusted_tpm1.c +15 -19
index 636acb66a4f6..fec7b6de7887 100644
@@ -310,9 +310,8 @@ static int TSS_checkhmac2(unsigned char *buffer,
  * For key specific tpm requests, we will generate and send our
  * own TPM command packets using the drivers send function.
  */
-static int trusted_tpm_send(unsigned char *cmd, size_t buflen)
+static int trusted_tpm_send(void *cmd, size_t buflen)
 {
-	struct tpm_buf buf;
 	int rc;
 
 	if (!chip)
@@ -322,15 +321,12 @@ static int trusted_tpm_send(unsigned char *cmd, size_t buflen)
 	if (rc)
 		return rc;
 
-	buf.flags = 0;
-	buf.length = buflen;
-	buf.data = cmd;
 	dump_tpm_buf(cmd);
-	rc = tpm_transmit_cmd(chip, &buf, 4, "sending data");
+	rc = tpm_transmit_cmd(chip, cmd, 4, "sending data");
 	dump_tpm_buf(cmd);
 
+	/* Convert TPM error to -EPERM. */
 	if (rc > 0)
-		/* TPM error */
 		rc = -EPERM;
 
 	tpm_put_ops(chip);
@@ -624,23 +620,23 @@ static int tpm_unseal(struct tpm_buf *tb,
 static int key_seal(struct trusted_key_payload *p,
 		    struct trusted_key_options *o)
 {
-	struct tpm_buf tb;
 	int ret;
 
-	ret = tpm_buf_init(&tb, 0, 0);
-	if (ret)
-		return ret;
+	struct tpm_buf *tb __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tb)
+		return -ENOMEM;
+
+	tpm_buf_init(tb, TPM_BUF_MAX_SIZE);
 
 	/* include migratable flag at end of sealed key */
 	p->key[p->key_len] = p->migratable;
 
-	ret = tpm_seal(&tb, o->keytype, o->keyhandle, o->keyauth,
+	ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
 		       p->key, p->key_len + 1, p->blob, &p->blob_len,
 		       o->blobauth, o->pcrinfo, o->pcrinfo_len);
 	if (ret < 0)
 		pr_info("srkseal failed (%d)\n", ret);
 
-	tpm_buf_destroy(&tb);
 	return ret;
 }
 
@@ -650,14 +646,15 @@ static int key_seal(struct trusted_key_payload *p,
 static int key_unseal(struct trusted_key_payload *p,
 		      struct trusted_key_options *o)
 {
-	struct tpm_buf tb;
 	int ret;
 
-	ret = tpm_buf_init(&tb, 0, 0);
-	if (ret)
-		return ret;
+	struct tpm_buf *tb __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tb)
+		return -ENOMEM;
+
+	tpm_buf_init(tb, TPM_BUF_MAX_SIZE);
 
-	ret = tpm_unseal(&tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
+	ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
 			 o->blobauth, p->key, &p->key_len);
 	if (ret < 0)
 		pr_info("srkunseal failed (%d)\n", ret);
@@ -665,7 +662,6 @@ static int key_unseal(struct trusted_key_payload *p,
 		/* pull migratable flag out of sealed key */
 		p->migratable = p->key[--p->key_len];
 
-	tpm_buf_destroy(&tb);
 	return ret;
 }
 
security/keys/trusted-keys/trusted_tpm2.c +71 -85

286 lines not on this page · raw message

Signature · 1 line
2.39.5
#2 lore raw

Re: [PATCH v10 1/4] tpm: Make TPM buffer allocations more robust

kernel test robot noticed the following build warnings:

Hi Jarkko,

kernel test robot noticed the following build warnings:

[auto build test WARNING on next-20250919]
[cannot apply to char-misc/char-misc-testing char-misc/char-misc-next char-misc/char-misc-linus linus/master v6.17-rc6 v6.17-rc5 v6.17-rc4 v6.17-rc6] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Jarkko-Sakkinen/tpm-Make-TPM-buffer-allocations-more-robust/20250921-102024
base:   next-20250919
patch link:    https://lore.kernel.org/r/20250921020804.1088824-2-jarkko%40kernel.org
patch subject: [PATCH v10 1/4] tpm: Make TPM buffer allocations more robust
config: x86_64-buildonly-randconfig-001-20250921 (https://download.01.org/0day-ci/archive/20250921/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250921/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> drivers/char/tpm/tpm-buf.c:20:9: warning: format specifies type 'unsigned int' but the argument has type 'unsigned long' [-Wformat]
      19 |                         WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
         |                                                           ~~
         |                                                           %lu
      20 |                              buf->capacity + sizeof(*buf));
         |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
   include/asm-generic/bug.h:141:29: note: expanded from macro 'WARN'
     141 |                 __WARN_printf(TAINT_WARN, format);                      \
         |                                           ^~~~~~
   include/asm-generic/bug.h:112:17: note: expanded from macro '__WARN_printf'
     112 |                 __warn_printk(arg);                                     \
         |                               ^~~

1 warning generated.

vim +20 drivers/char/tpm/tpm-buf.c

     9	
    10	static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)
    11	{
    12		if (!buf->capacity) {
    13			if (buf_size > TPM_BUF_MAX_SIZE) {
    14				WARN(1, "%s: size overflow: %u\n", __func__, buf_size);
    15				buf->flags |= TPM_BUF_ERROR;
    16			}
    17		} else {
    18			if (buf_size != buf->capacity + sizeof(*buf)) {
    19				WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
  > 20				     buf->capacity + sizeof(*buf));
    21				buf->flags |= TPM_BUF_ERROR;
    22			}
    23		}
    24	}
    25	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#3 lore raw

Re: [PATCH v10 1/4] tpm: Make TPM buffer allocations more robust

In reply to Jarkko Sakkinen
Quoted 106 lines · Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Create more ergonomic primitives to work with TPM buffers, where 'tpm_buf_init*' initialize the memory and 'tpm_buf_reset*' (re)set a buffer for a particular use and purpose. The new primitives are ubiquitos when it comes to heap and stack usage.

Given that the kzalloc is decoupled, a managed allocation can be done trivially:

	struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUF_MAX_SIZE,
							GFP_KERNEL);

This effectively zeros out the odds having any memory leaks with TPM buffers. The new structures can be later used to widen the use of stack over heap in the subsystem in the critical code paths..

---
v10:
- No changes.
v9:
- Rename pre-existing TPM_BUFSIZE as TPM_BUF_MAX_SIZE and redeclare it in include/linux/tpm.h, and use this constant instead of PAGE_SIZE in tpm_buf_init*. Define TPM_BUF_MIN_SIZE to be a sane placeholder value for stack allocations.
- Fix and restructure invariant for the sake of clarity.
- memset buffers to zero in tpm_buf_init* in order to guarantee a legit initial state. This does not cause any regressions but once tpm_buf is allocaed from stack at some site, this will zero out chance of corrupted state.
v8:
- Decouple memory init i.e. bring tpm_init* back but with new fresh form.
- Cap buf_size to page size and also make checks in tpm_buf_append safe:
https://lore.kernel.org/linux-integrity/hwsx2t2tkbos3g7k2syemxbvc6sfrsbviwm64ubcdl6ms7ljvo@toetomkhheht/
- Fix trusted_tpm_send() and simplify the flow.
v7:
- Additional function comments and invariant was unfortunately left to my staging area so here's the addition (does not affect functionality).
v6:
- Removed two empty lines as requested by Stefan:
https://lore.kernel.org/linux-integrity/[email protected]/
- Add 'capacity' field as this makes easy to stretch tpm_buf into stack allocation.
v5:
- I tested this version also with TPM 1.2 by booting up and checking that sysfs attributes work.
- Fixed the length check against capacity (James) with TPM_BUF_CAPACITY.
- Fixed declaration style: do it at the site (Jason).
- Improved commit message (Stefan).
- Removed "out" label from tpm2_pcr_read() (Stefan).
- Removed spurious "return rc;" from tpm2_get_pcr_allocation() (Stefan). v4:
- Wrote a more a descriptive short summary and improved description.
- Fixed the error in documentation: there is 4090 bytes of space left for the payload - not 4088 bytes.
- Turned tpm_buf_alloc() into inline function.
v3:
- Removed the cleanup class and moved on using __free(kfree) instead.
- Removed buf_size (James).
- I'm open for the idea of splitting still (Jason) but I'll hold at least this revision just to check that my core idea here is correct.
v2:
- Implement also memory allocation using the cleanup class.
- Rewrote the commit message.
- Implemented CLASS_TPM_BUF() helper macro.
---

drivers/char/tpm/tpm-buf.c                | 137 +++++++----
drivers/char/tpm/tpm-dev-common.c         |   4 +-
drivers/char/tpm/tpm-dev.h                |   2 +-
drivers/char/tpm/tpm-interface.c          |   4 +-
drivers/char/tpm/tpm-sysfs.c              |  20 +-
drivers/char/tpm/tpm.h                    |   3 +-
drivers/char/tpm/tpm1-cmd.c               | 149 ++++++------
drivers/char/tpm/tpm2-cmd.c               | 282 ++++++++++------------
drivers/char/tpm/tpm2-sessions.c          | 121 +++++-----
drivers/char/tpm/tpm2-space.c             |  44 ++--
drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
drivers/char/tpm/tpm_vtpm_proxy.c         |  32 ++-
include/linux/tpm.h                       |  28 ++-
security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
15 files changed, 493 insertions(+), 527 deletions(-)
drivers/char/tpm/tpm-buf.c +1 -9
index dc882fc9fa9e..82dce0350a41 100644
@@ -7,82 +7,107 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-/**
- * tpm_buf_init() - Allocate and initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- *
- * Return: 0 or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)

drivers/char/tpm/tpm-buf.c line 14

Quoted 10 lines
drivers/char/tpm/tpm-buf.c +3 -6
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
+	if (!buf->capacity) {
+		if (buf_size > TPM_BUF_MAX_SIZE) {
+			WARN(1, "%s: size overflow: %u\n", __func__, buf_size);

IIUC here we will always print something like:
"__tpm_buf_size_invariant: size overflow: XXX"

So, should we just remove __func__ or maybe use a macro to print the name of the caller?

Quoted 250 lines
drivers/char/tpm/tpm-buf.c +80 -38
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	} else {
+		if (buf_size != buf->capacity + sizeof(*buf)) {
+			WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
+			     buf->capacity + sizeof(*buf));
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	}
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-/**
- * tpm_buf_reset() - Initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- */
-void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_reset(struct tpm_buf *buf, u16 buf_size, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
 		tag != TPM2_ST_SESSIONS && tag != 0);
 
 	buf->flags = 0;
 	buf->length = sizeof(*head);
+	buf->capacity = buf_size - sizeof(*buf);
+	buf->handles = 0;
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+}
+
+static void __tpm_buf_reset_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->capacity = buf_size - sizeof(*buf);
 	buf->handles = 0;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
 /**
- * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
- * @buf:	A @tpm_buf
- *
- * Return: 0 or -ENOMEM
+ * tpm_buf_init() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
 */
-int tpm_buf_init_sized(struct tpm_buf *buf)
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset(buf, buf_size, TPM_TAG_RQU_COMMAND, 0);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-	tpm_buf_reset_sized(buf);
-	return 0;
+/**
+ * tpm_buf_init_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
+ */
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset_sized(buf, buf_size);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
 
 /**
- * tpm_buf_reset_sized() - Initialize a sized buffer
+ * tpm_buf_reset() - Re-initialize a TPM command
 * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
 */
-void tpm_buf_reset_sized(struct tpm_buf *buf)
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
-	buf->flags = TPM_BUF_TPM2B;
-	buf->length = 2;
-	buf->data[0] = 0;
-	buf->data[1] = 0;
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset(buf, buf_size, tag, ordinal);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
-void tpm_buf_destroy(struct tpm_buf *buf)
+/**
+ * tpm_buf_reset_sized() - Re-initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
 {
-	free_page((unsigned long)buf->data);
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset_sized(buf, buf_size);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
 
 /**
 * tpm_buf_length() - Return the number of bytes consumed by the data
@@ -92,6 +117,9 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
 */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return 0;
+
 	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,13 +132,14 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
 */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
+	u32 total_length = (u32)buf->length + (u32)new_length;
+
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
-	if ((buf->length + new_length) > PAGE_SIZE) {
+	if (total_length > (u32)buf->capacity) {
 		WARN(1, "tpm_buf: write overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -157,8 +186,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
 */
 void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	if (buf->flags & TPM_BUF_TPM2B) {
-		dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+		dev_err(&chip->dev, "%s: invalid for buffer type: TPM2B\n", __func__);
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -178,13 +211,13 @@ static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void
 	off_t next_offset;
 
 	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
 	next_offset = *offset + count;
 	if (next_offset > buf->length) {
 		WARN(1, "tpm_buf: read out of boundary\n");
-		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -242,5 +275,3 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
-
-
drivers/char/tpm/tpm-dev-common.c +1 -1
index f2a5e09257dd..4f5893555fb7 100644
@@ -147,7 +147,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 
 		rc = copy_to_user(buf, priv->data_buffer + *off, 
 		ret_size);
 		if (rc) {
-			memset(priv->data_buffer, 0, TPM_BUFSIZE);
+			memset(priv->data_buffer, 0, TPM_BUF_MAX_SIZE);
 			priv->response_length = 0;
 			ret_size = -EFAULT;
		} else {
drivers/char/tpm/tpm-dev-common.c +1 -1
@@ -173,7 +173,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,
 	struct file_priv *priv = file->private_data;
 	int ret = 0;
 
-	if (size > TPM_BUFSIZE)
+	if (size > TPM_BUF_MAX_SIZE)
 		return -E2BIG;
 
 	mutex_lock(&priv->buffer_mutex);
drivers/char/tpm/tpm-dev.h +1 -1
index f3742bcc73e3..700e3d9d8b64 100644
@@ -18,7 +18,7 @@ struct file_priv {
 	bool response_read;
 	bool command_enqueued;
 
-	u8 data_buffer[TPM_BUFSIZE];
+	u8 data_buffer[TPM_BUF_MAX_SIZE];
 };
 
 void tpm_common_open(struct file *file, struct tpm_chip *chip,
drivers/char/tpm/tpm-interface.c +2 -2
index c9f173001d0e..b0d5098fb92b 100644
@@ -100,8 +100,8 @@ static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
 	if (bufsiz < TPM_HEADER_SIZE)
 		return -EINVAL;
 
-	if (bufsiz > TPM_BUFSIZE)
-		bufsiz = TPM_BUFSIZE;
+	if (bufsiz > TPM_BUF_MAX_SIZE)
+		bufsiz = TPM_BUF_MAX_SIZE;
 
 	count = be32_to_cpu(header->length);
 	ordinal = be32_to_cpu(header->ordinal);
drivers/char/tpm/tpm-sysfs.c +0 -0
index 94231f052ea7..4213a8285ed0 100644
@@ -32,28 +32,30 @@ struct tpm_readpubek_out {
 static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,

drivers/char/tpm/tpm-sysfs.c struct tpm_readpubek_out { · line 41

Quoted 10 lines
drivers/char/tpm/tpm-sysfs.c +1 -1
 			  char *buf)
 {
-	struct tpm_buf tpm_buf;
 	struct tpm_readpubek_out *out;
 	int i;
 	char *str = buf;
 	struct tpm_chip *chip = to_tpm_chip(dev);
 	char anti_replay[20];
 
+	struct tpm_buf *tpm_buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);

We're using PAGE_SIZE instead of TPM_BUF_MAX_SIZE to reduce the pressure on the allocator, right?

I was wondering if we could create an inline function or a macro that calls kzalloc() and tpm_buf_init(). Just because we do it often, it's not a strong opinion, just something that came to mind while doing the review. I mean something like this (untested):

struct tpm_buf *tpm_buf_alloc_max(void) {
	struct tpm_buf *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
	if (!buf)
		return NULL;

	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
	return buf;
}

Thanks,
Stefano

author maintainer
#4 lore raw

Re: [PATCH v10 1/4] tpm: Make TPM buffer allocations more robust

Quoted 121 lines · Stefano Garzarella
Quoted 106 lines · Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Create more ergonomic primitives to work with TPM buffers, where 'tpm_buf_init*' initialize the memory and 'tpm_buf_reset*' (re)set a buffer for a particular use and purpose. The new primitives are ubiquitos when it comes to heap and stack usage.

Given that the kzalloc is decoupled, a managed allocation can be done trivially:

	struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUF_MAX_SIZE,
							GFP_KERNEL);

This effectively zeros out the odds having any memory leaks with TPM buffers. The new structures can be later used to widen the use of stack over heap in the subsystem in the critical code paths..

---
v10:
- No changes.
v9:
- Rename pre-existing TPM_BUFSIZE as TPM_BUF_MAX_SIZE and redeclare it in include/linux/tpm.h, and use this constant instead of PAGE_SIZE in tpm_buf_init*. Define TPM_BUF_MIN_SIZE to be a sane placeholder value for stack allocations.
- Fix and restructure invariant for the sake of clarity.
- memset buffers to zero in tpm_buf_init* in order to guarantee a legit initial state. This does not cause any regressions but once tpm_buf is allocaed from stack at some site, this will zero out chance of corrupted state.
v8:
- Decouple memory init i.e. bring tpm_init* back but with new fresh form.
- Cap buf_size to page size and also make checks in tpm_buf_append safe:
https://lore.kernel.org/linux-integrity/hwsx2t2tkbos3g7k2syemxbvc6sfrsbviwm64ubcdl6ms7ljvo@toetomkhheht/
- Fix trusted_tpm_send() and simplify the flow.
v7:
- Additional function comments and invariant was unfortunately left to my staging area so here's the addition (does not affect functionality).
v6:
- Removed two empty lines as requested by Stefan:
https://lore.kernel.org/linux-integrity/[email protected]/
- Add 'capacity' field as this makes easy to stretch tpm_buf into stack allocation.
v5:
- I tested this version also with TPM 1.2 by booting up and checking that sysfs attributes work.
- Fixed the length check against capacity (James) with TPM_BUF_CAPACITY.
- Fixed declaration style: do it at the site (Jason).
- Improved commit message (Stefan).
- Removed "out" label from tpm2_pcr_read() (Stefan).
- Removed spurious "return rc;" from tpm2_get_pcr_allocation() (Stefan). v4:
- Wrote a more a descriptive short summary and improved description.
- Fixed the error in documentation: there is 4090 bytes of space left for the payload - not 4088 bytes.
- Turned tpm_buf_alloc() into inline function.
v3:
- Removed the cleanup class and moved on using __free(kfree) instead.
- Removed buf_size (James).
- I'm open for the idea of splitting still (Jason) but I'll hold at least this revision just to check that my core idea here is correct.
v2:
- Implement also memory allocation using the cleanup class.
- Rewrote the commit message.
- Implemented CLASS_TPM_BUF() helper macro.
---

drivers/char/tpm/tpm-buf.c                | 137 +++++++----
drivers/char/tpm/tpm-dev-common.c         |   4 +-
drivers/char/tpm/tpm-dev.h                |   2 +-
drivers/char/tpm/tpm-interface.c          |   4 +-
drivers/char/tpm/tpm-sysfs.c              |  20 +-
drivers/char/tpm/tpm.h                    |   3 +-
drivers/char/tpm/tpm1-cmd.c               | 149 ++++++------
drivers/char/tpm/tpm2-cmd.c               | 282 ++++++++++------------
drivers/char/tpm/tpm2-sessions.c          | 121 +++++-----
drivers/char/tpm/tpm2-space.c             |  44 ++--
drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
drivers/char/tpm/tpm_vtpm_proxy.c         |  32 ++-
include/linux/tpm.h                       |  28 ++-
security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
15 files changed, 493 insertions(+), 527 deletions(-)
drivers/char/tpm/tpm-buf.c +1 -9
index dc882fc9fa9e..82dce0350a41 100644
@@ -7,82 +7,107 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-/**
- * tpm_buf_init() - Allocate and initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- *
- * Return: 0 or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)

drivers/char/tpm/tpm-buf.c line 14

Quoted 10 lines
drivers/char/tpm/tpm-buf.c +3 -6
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
+	if (!buf->capacity) {
+		if (buf_size > TPM_BUF_MAX_SIZE) {
+			WARN(1, "%s: size overflow: %u\n", __func__, buf_size);

IIUC here we will always print something like:
"__tpm_buf_size_invariant: size overflow: XXX"

Quoted 2 lines

So, should we just remove __func__ or maybe use a macro to print the name of the caller?

It also prints a stack trace.

Quoted 270 lines
Quoted 250 lines
drivers/char/tpm/tpm-buf.c +80 -38
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	} else {
+		if (buf_size != buf->capacity + sizeof(*buf)) {
+			WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
+			     buf->capacity + sizeof(*buf));
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	}
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-/**
- * tpm_buf_reset() - Initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- */
-void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_reset(struct tpm_buf *buf, u16 buf_size, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
 		tag != TPM2_ST_SESSIONS && tag != 0);
 
 	buf->flags = 0;
 	buf->length = sizeof(*head);
+	buf->capacity = buf_size - sizeof(*buf);
+	buf->handles = 0;
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+}
+
+static void __tpm_buf_reset_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->capacity = buf_size - sizeof(*buf);
 	buf->handles = 0;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
 /**
- * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
- * @buf:	A @tpm_buf
- *
- * Return: 0 or -ENOMEM
+ * tpm_buf_init() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
 */
-int tpm_buf_init_sized(struct tpm_buf *buf)
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset(buf, buf_size, TPM_TAG_RQU_COMMAND, 0);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-	tpm_buf_reset_sized(buf);
-	return 0;
+/**
+ * tpm_buf_init_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
+ */
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset_sized(buf, buf_size);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
 
 /**
- * tpm_buf_reset_sized() - Initialize a sized buffer
+ * tpm_buf_reset() - Re-initialize a TPM command
 * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
 */
-void tpm_buf_reset_sized(struct tpm_buf *buf)
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
-	buf->flags = TPM_BUF_TPM2B;
-	buf->length = 2;
-	buf->data[0] = 0;
-	buf->data[1] = 0;
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset(buf, buf_size, tag, ordinal);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
-void tpm_buf_destroy(struct tpm_buf *buf)
+/**
+ * tpm_buf_reset_sized() - Re-initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
 {
-	free_page((unsigned long)buf->data);
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset_sized(buf, buf_size);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
 
 /**
 * tpm_buf_length() - Return the number of bytes consumed by the data
@@ -92,6 +117,9 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
 */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return 0;
+
 	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,13 +132,14 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
 */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
+	u32 total_length = (u32)buf->length + (u32)new_length;
+
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
-	if ((buf->length + new_length) > PAGE_SIZE) {
+	if (total_length > (u32)buf->capacity) {
 		WARN(1, "tpm_buf: write overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -157,8 +186,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
 */
 void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	if (buf->flags & TPM_BUF_TPM2B) {
-		dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+		dev_err(&chip->dev, "%s: invalid for buffer type: TPM2B\n", __func__);
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -178,13 +211,13 @@ static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void
 	off_t next_offset;
 
 	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
 	next_offset = *offset + count;
 	if (next_offset > buf->length) {
 		WARN(1, "tpm_buf: read out of boundary\n");
-		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -242,5 +275,3 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
-
-
drivers/char/tpm/tpm-dev-common.c +2 -2
index f2a5e09257dd..4f5893555fb7 100644
@@ -147,7 +147,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 
 		rc = copy_to_user(buf, priv->data_buffer + *off, 		ret_size);
 		if (rc) {
-			memset(priv->data_buffer, 0, TPM_BUFSIZE);
+			memset(priv->data_buffer, 0, TPM_BUF_MAX_SIZE);
 			priv->response_length = 0;
 			ret_size = -EFAULT;
 		} else {
@@ -173,7 +173,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,
 	struct file_priv *priv = file->private_data;
 	int ret = 0;
 
-	if (size > TPM_BUFSIZE)
+	if (size > TPM_BUF_MAX_SIZE)
 		return -E2BIG;
 
 	mutex_lock(&priv->buffer_mutex);
drivers/char/tpm/tpm-dev.h +1 -1
index f3742bcc73e3..700e3d9d8b64 100644
@@ -18,7 +18,7 @@ struct file_priv {
 	bool response_read;
 	bool command_enqueued;
 
-	u8 data_buffer[TPM_BUFSIZE];
+	u8 data_buffer[TPM_BUF_MAX_SIZE];
 };
 
 void tpm_common_open(struct file *file, struct tpm_chip *chip,
drivers/char/tpm/tpm-interface.c +2 -2
index c9f173001d0e..b0d5098fb92b 100644
@@ -100,8 +100,8 @@ static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
 	if (bufsiz < TPM_HEADER_SIZE)
 		return -EINVAL;
 
-	if (bufsiz > TPM_BUFSIZE)
-		bufsiz = TPM_BUFSIZE;
+	if (bufsiz > TPM_BUF_MAX_SIZE)
+		bufsiz = TPM_BUF_MAX_SIZE;
 
 	count = be32_to_cpu(header->length);
 	ordinal = be32_to_cpu(header->ordinal);
drivers/char/tpm/tpm-sysfs.c +0 -0
index 94231f052ea7..4213a8285ed0 100644
@@ -32,28 +32,30 @@ struct tpm_readpubek_out {
 static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,

drivers/char/tpm/tpm-sysfs.c struct tpm_readpubek_out { · line 41

Quoted 10 lines
drivers/char/tpm/tpm-sysfs.c +1 -1
 			  char *buf)
 {
-	struct tpm_buf tpm_buf;
 	struct tpm_readpubek_out *out;
 	int i;
 	char *str = buf;
 	struct tpm_chip *chip = to_tpm_chip(dev);
 	char anti_replay[20];
 
+	struct tpm_buf *tpm_buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);

We're using PAGE_SIZE instead of TPM_BUF_MAX_SIZE to reduce the pressure on the allocator, right?

I was wondering if we could create an inline function or a macro that calls kzalloc() and tpm_buf_init().
Just because we do it often, it's not a strong opinion, just something that came to mind while doing the review.
I mean something like this (untested):

Quoted 8 lines
struct tpm_buf *tpm_buf_alloc_max(void) {
	struct tpm_buf *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
	if (!buf)
		return NULL;

	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
	return buf;
}

With or without this, about same about of boiler plate is introduced to the call site. It's easier to understand the code later on when kzalloc alloc is clearly at site. Finally I think for most uses the driver could favor stack over heap (but that requires prepare the tpm_buf like this).

Quoted 4 lines

Thanks,
Stefano

BR, Jarkko

#5 lore raw

Re: [PATCH v10 1/4] tpm: Make TPM buffer allocations more robust

Quoted 122 lines · Jarkko Sakkinen
Quoted 121 lines · Stefano Garzarella
Quoted 106 lines · Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Create more ergonomic primitives to work with TPM buffers, where 'tpm_buf_init*' initialize the memory and 'tpm_buf_reset*' (re)set a buffer for a particular use and purpose. The new primitives are ubiquitos when it comes to heap and stack usage.

Given that the kzalloc is decoupled, a managed allocation can be done trivially:

	struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUF_MAX_SIZE,
							GFP_KERNEL);

This effectively zeros out the odds having any memory leaks with TPM buffers. The new structures can be later used to widen the use of stack over heap in the subsystem in the critical code paths..

---
v10:
- No changes.
v9:
- Rename pre-existing TPM_BUFSIZE as TPM_BUF_MAX_SIZE and redeclare it in include/linux/tpm.h, and use this constant instead of PAGE_SIZE in tpm_buf_init*. Define TPM_BUF_MIN_SIZE to be a sane placeholder value for stack allocations.
- Fix and restructure invariant for the sake of clarity.
- memset buffers to zero in tpm_buf_init* in order to guarantee a legit initial state. This does not cause any regressions but once tpm_buf is allocaed from stack at some site, this will zero out chance of corrupted state.
v8:
- Decouple memory init i.e. bring tpm_init* back but with new fresh form.
- Cap buf_size to page size and also make checks in tpm_buf_append safe:
https://lore.kernel.org/linux-integrity/hwsx2t2tkbos3g7k2syemxbvc6sfrsbviwm64ubcdl6ms7ljvo@toetomkhheht/
- Fix trusted_tpm_send() and simplify the flow.
v7:
- Additional function comments and invariant was unfortunately left to my staging area so here's the addition (does not affect functionality).
v6:
- Removed two empty lines as requested by Stefan:
https://lore.kernel.org/linux-integrity/[email protected]/
- Add 'capacity' field as this makes easy to stretch tpm_buf into stack allocation.
v5:
- I tested this version also with TPM 1.2 by booting up and checking that sysfs attributes work.
- Fixed the length check against capacity (James) with TPM_BUF_CAPACITY.
- Fixed declaration style: do it at the site (Jason).
- Improved commit message (Stefan).
- Removed "out" label from tpm2_pcr_read() (Stefan).
- Removed spurious "return rc;" from tpm2_get_pcr_allocation() (Stefan). v4:
- Wrote a more a descriptive short summary and improved description.
- Fixed the error in documentation: there is 4090 bytes of space left for the payload - not 4088 bytes.
- Turned tpm_buf_alloc() into inline function.
v3:
- Removed the cleanup class and moved on using __free(kfree) instead.
- Removed buf_size (James).
- I'm open for the idea of splitting still (Jason) but I'll hold at least this revision just to check that my core idea here is correct.
v2:
- Implement also memory allocation using the cleanup class.
- Rewrote the commit message.
- Implemented CLASS_TPM_BUF() helper macro.
---

drivers/char/tpm/tpm-buf.c                | 137 +++++++----
drivers/char/tpm/tpm-dev-common.c         |   4 +-
drivers/char/tpm/tpm-dev.h                |   2 +-
drivers/char/tpm/tpm-interface.c          |   4 +-
drivers/char/tpm/tpm-sysfs.c              |  20 +-
drivers/char/tpm/tpm.h                    |   3 +-
drivers/char/tpm/tpm1-cmd.c               | 149 ++++++------
drivers/char/tpm/tpm2-cmd.c               | 282 ++++++++++------------
drivers/char/tpm/tpm2-sessions.c          | 121 +++++-----
drivers/char/tpm/tpm2-space.c             |  44 ++--
drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
drivers/char/tpm/tpm_vtpm_proxy.c         |  32 ++-
include/linux/tpm.h                       |  28 ++-
security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
15 files changed, 493 insertions(+), 527 deletions(-)
drivers/char/tpm/tpm-buf.c +1 -9
index dc882fc9fa9e..82dce0350a41 100644
@@ -7,82 +7,107 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-/**
- * tpm_buf_init() - Allocate and initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- *
- * Return: 0 or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)

drivers/char/tpm/tpm-buf.c line 14

Quoted 10 lines
drivers/char/tpm/tpm-buf.c +3 -6
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
+	if (!buf->capacity) {
+		if (buf_size > TPM_BUF_MAX_SIZE) {
+			WARN(1, "%s: size overflow: %u\n", __func__, buf_size);

IIUC here we will always print something like:
"__tpm_buf_size_invariant: size overflow: XXX"

Quoted 4 lines
Quoted 2 lines

So, should we just remove __func__ or maybe use a macro to print the name of the caller?

It also prints a stack trace.

Oh, I see, thanks!

Quoted 276 lines
Quoted 276 lines
Quoted 251 lines
drivers/char/tpm/tpm-buf.c +80 -38
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	} else {
+		if (buf_size != buf->capacity + sizeof(*buf)) {
+			WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
+			     buf->capacity + sizeof(*buf));
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	}
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-/**
- * tpm_buf_reset() - Initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- */
-void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_reset(struct tpm_buf *buf, u16 buf_size, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
 		tag != TPM2_ST_SESSIONS && tag != 0);
 
 	buf->flags = 0;
 	buf->length = sizeof(*head);
+	buf->capacity = buf_size - sizeof(*buf);
+	buf->handles = 0;
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+}
+
+static void __tpm_buf_reset_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->capacity = buf_size - sizeof(*buf);
 	buf->handles = 0;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
 /**
- * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
- * @buf:	A @tpm_buf
- *
- * Return: 0 or -ENOMEM
+ * tpm_buf_init() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
 */
-int tpm_buf_init_sized(struct tpm_buf *buf)
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset(buf, buf_size, TPM_TAG_RQU_COMMAND, 0);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-	tpm_buf_reset_sized(buf);
-	return 0;
+/**
+ * tpm_buf_init_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
+ */
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset_sized(buf, buf_size);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
 
 /**
- * tpm_buf_reset_sized() - Initialize a sized buffer
+ * tpm_buf_reset() - Re-initialize a TPM command
 * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
 */
-void tpm_buf_reset_sized(struct tpm_buf *buf)
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
-	buf->flags = TPM_BUF_TPM2B;
-	buf->length = 2;
-	buf->data[0] = 0;
-	buf->data[1] = 0;
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset(buf, buf_size, tag, ordinal);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
-void tpm_buf_destroy(struct tpm_buf *buf)
+/**
+ * tpm_buf_reset_sized() - Re-initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
 {
-	free_page((unsigned long)buf->data);
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset_sized(buf, buf_size);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
 
 /**
 * tpm_buf_length() - Return the number of bytes consumed by the data
@@ -92,6 +117,9 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
 */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return 0;
+
 	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,13 +132,14 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
 */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
+	u32 total_length = (u32)buf->length + (u32)new_length;
+
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
-	if ((buf->length + new_length) > PAGE_SIZE) {
+	if (total_length > (u32)buf->capacity) {
 		WARN(1, "tpm_buf: write overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -157,8 +186,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
 */
 void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	if (buf->flags & TPM_BUF_TPM2B) {
-		dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+		dev_err(&chip->dev, "%s: invalid for buffer type: TPM2B\n", __func__);
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -178,13 +211,13 @@ static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void
 	off_t next_offset;
 
 	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
 	next_offset = *offset + count;
 	if (next_offset > buf->length) {
 		WARN(1, "tpm_buf: read out of boundary\n");
-		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -242,5 +275,3 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
-
-
drivers/char/tpm/tpm-dev-common.c +2 -2
index f2a5e09257dd..4f5893555fb7 100644
@@ -147,7 +147,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 
 		rc = copy_to_user(buf, priv->data_buffer + *off, 		ret_size);
 		if (rc) {
-			memset(priv->data_buffer, 0, TPM_BUFSIZE);
+			memset(priv->data_buffer, 0, TPM_BUF_MAX_SIZE);
 			priv->response_length = 0;
 			ret_size = -EFAULT;
 		} else {
@@ -173,7 +173,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,
 	struct file_priv *priv = file->private_data;
 	int ret = 0;
 
-	if (size > TPM_BUFSIZE)
+	if (size > TPM_BUF_MAX_SIZE)
 		return -E2BIG;
 
 	mutex_lock(&priv->buffer_mutex);
drivers/char/tpm/tpm-dev.h +1 -1
index f3742bcc73e3..700e3d9d8b64 100644
@@ -18,7 +18,7 @@ struct file_priv {
 	bool response_read;
 	bool command_enqueued;
 
-	u8 data_buffer[TPM_BUFSIZE];
+	u8 data_buffer[TPM_BUF_MAX_SIZE];
 };
 
 void tpm_common_open(struct file *file, struct tpm_chip *chip,
drivers/char/tpm/tpm-interface.c +2 -2
index c9f173001d0e..b0d5098fb92b 100644
@@ -100,8 +100,8 @@ static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
 	if (bufsiz < TPM_HEADER_SIZE)
 		return -EINVAL;
 
-	if (bufsiz > TPM_BUFSIZE)
-		bufsiz = TPM_BUFSIZE;
+	if (bufsiz > TPM_BUF_MAX_SIZE)
+		bufsiz = TPM_BUF_MAX_SIZE;
 
 	count = be32_to_cpu(header->length);
 	ordinal = be32_to_cpu(header->ordinal);
drivers/char/tpm/tpm-sysfs.c +0 -0
index 94231f052ea7..4213a8285ed0 100644
@@ -32,28 +32,30 @@ struct tpm_readpubek_out {
 static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,

drivers/char/tpm/tpm-sysfs.c struct tpm_readpubek_out { · line 41

Quoted 10 lines
drivers/char/tpm/tpm-sysfs.c +1 -1
 			  char *buf)
 {
-	struct tpm_buf tpm_buf;
 	struct tpm_readpubek_out *out;
 	int i;
 	char *str = buf;
 	struct tpm_chip *chip = to_tpm_chip(dev);
 	char anti_replay[20];
 
+	struct tpm_buf *tpm_buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);

We're using PAGE_SIZE instead of TPM_BUF_MAX_SIZE to reduce the pressure on the allocator, right?

I was wondering if we could create an inline function or a macro that calls kzalloc() and tpm_buf_init().
Just because we do it often, it's not a strong opinion, just something that came to mind while doing the review.
I mean something like this (untested):

struct tpm_buf *tpm_buf_alloc_max(void) {
	struct tpm_buf *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
	if (!buf)
		return NULL;
Quoted 8 lines
Quoted 3 lines
	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
	return buf;
}

With or without this, about same about of boiler plate is introduced to the call site. It's easier to understand the code later on when kzalloc alloc is clearly at site. Finally I think for most uses the driver could favor stack over heap (but that requires prepare the tpm_buf like this).

Yep, I see.

Stefano

author maintainer
#6 lore raw

PATCH v10 2/4 tpm, tpm1-cmd: Use stack for trivial cases

In reply to Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use stack allocation for trivial "low-hanging fruit" sites, which are often also critical code paths associated with probing and power management.

---
 drivers/char/tpm/tpm1-cmd.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
drivers/char/tpm/tpm1-cmd.c +5 -9
index ca3e7f9a105d..11c16ad9b2a7 100644
@@ -323,19 +323,15 @@ unsigned long tpm1_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
  */
 static int tpm1_startup(struct tpm_chip *chip)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	dev_info(&chip->dev, "starting up the TPM manually\n");
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	dev_info(&chip->dev, "TPM_Startup\n");
+	tpm_buf_init(buf, TPM_BUF_INT_SIZE);
 	tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
 	tpm_buf_append_u16(buf, TPM_ST_CLEAR);
-
-	rc = tpm_transmit_cmd(chip, buf, 0, "attempting to start the TPM");
+	rc = tpm_transmit_cmd(chip, buf, 0, "TPM_Startup");
 	return rc;
 }
 
Signature · 1 line
2.39.5
author maintainer
#7 lore raw

PATCH v10 3/4 tpm, tpm2-cmd: Use stack for trivial cases

In reply to Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use stack allocation for trivial "low-hanging fruit" sites, which are often also critical code paths associated with probing and power management.

---
 drivers/char/tpm/tpm2-cmd.c | 57 ++++++++++++++-----------------------
 1 file changed, 22 insertions(+), 35 deletions(-)
drivers/char/tpm/tpm2-cmd.c +22 -35
index 245c7c952e82..3c55f60ae4c2 100644
@@ -382,14 +382,13 @@ EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
  */
 void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
 {
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return;
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN);
 	tpm_buf_append_u16(buf, shutdown_type);
-	tpm_transmit_cmd(chip, buf, 0, "stopping the TPM");
+	tpm_transmit_cmd(chip, buf, 0, "TPM2_Shutdown");
 }
 
 /**
@@ -407,58 +406,49 @@ void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
  */
 static int tpm2_do_selftest(struct tpm_chip *chip)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 	int full;
 	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
-	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	for (full = 0; full < 2; full++) {
 		tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
 		tpm_buf_append_u8(buf, full);
-		rc = tpm_transmit_cmd(chip, buf, 0,
-				      "attempting the self test");
-
+		rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_SelfTest");
 		if (rc == TPM2_RC_TESTING)
 			rc = TPM2_RC_SUCCESS;
 		if (rc == TPM2_RC_INITIALIZE || rc == TPM2_RC_SUCCESS)
 			return rc;
 	}
-
 	return rc;
 }
 
 /**
- * tpm2_probe() - probe for the TPM 2.0 protocol
+ * tpm2_probe() - Probe for the TPM 2.0 protocol
  * @chip:	a &tpm_chip instance
  *
- * Send an idempotent TPM 2.0 command and see whether there is TPM2 chip in the
- * other end based on the response tag. The flag TPM_CHIP_FLAG_TPM2 is set by
- * this function if this is the case.
+ * Sends an idempotent TPM 2.0 command, and based on the response tag deduces
+ * whether a functional TPM2 chip is on the other side. When the result is
+ * positive, TPM_CHIP_FLAG_TPM2 is append to the chip's flags.
  *
  * Return:
- *   0 on success,
- *   -errno otherwise
+ * * 0 on success,
+ * * -errno otherwise
  */
 int tpm2_probe(struct tpm_chip *chip)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 	struct tpm_header *out;
 	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
 	tpm_buf_append_u32(buf, TPM2_CAP_TPM_PROPERTIES);
 	tpm_buf_append_u32(buf, TPM_PT_TOTAL_COMMANDS);
 	tpm_buf_append_u32(buf, 1);
 	rc = tpm_transmit_cmd(chip, buf, 0, NULL);
-	/* We ignore TPM return codes on purpose. */
 	if (rc >=  0) {
 		out = (struct tpm_header *)buf->data;
 		if (be16_to_cpu(out->tag) == TPM2_ST_NO_SESSIONS)
@@ -651,17 +641,14 @@ EXPORT_SYMBOL_GPL(tpm2_get_cc_attrs_tbl);
 
 static int tpm2_startup(struct tpm_chip *chip)
 {
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	dev_info(&chip->dev, "starting up the TPM manually\n");
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	dev_info(&chip->dev, "TPM2_Startup\n");
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
 	tpm_buf_append_u16(buf, TPM2_SU_CLEAR);
-
-	return tpm_transmit_cmd(chip, buf, 0, "attempting to start the TPM");
+	return tpm_transmit_cmd(chip, buf, 0, "TPM2_Startup");
 }
 
 /**
Signature · 1 line
2.39.5
author maintainer
#8 lore raw

PATCH v10 4/4 tpm_vpm_proxy: Use stack for TPM_CC_SET_LOCALITY

In reply to Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use stack allocation for TPM_CC_SET_LOCALITY, as it has known fixed size.

---
 drivers/char/tpm/tpm1-cmd.c       |  2 +-
 drivers/char/tpm/tpm_vtpm_proxy.c | 12 +++++-------
 2 files changed, 6 insertions(+), 8 deletions(-)
drivers/char/tpm/tpm1-cmd.c +1 -1
index 11c16ad9b2a7..433908cfb4a9 100644
@@ -328,7 +328,7 @@ static int tpm1_startup(struct tpm_chip *chip)
 	int rc;
 
 	dev_info(&chip->dev, "TPM_Startup\n");
-	tpm_buf_init(buf, TPM_BUF_INT_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
 	tpm_buf_append_u16(buf, TPM_ST_CLEAR);
 	rc = tpm_transmit_cmd(chip, buf, 0, "TPM_Startup");
drivers/char/tpm/tpm_vtpm_proxy.c +5 -7
index e5de14379eb2..0f1b1b67ed4e 100644
@@ -395,15 +395,13 @@ static bool vtpm_proxy_tpm_req_canceled(struct tpm_chip  *chip, u8 status)
 
 static int vtpm_proxy_request_locality(struct tpm_chip *chip, int locality)
 {
-	int rc;
-	const struct tpm_header *header;
 	struct proxy_dev *proxy_dev = dev_get_drvdata(&chip->dev);
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
+	const struct tpm_header *header;
+	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
 		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_SET_LOCALITY);
 	else
Signature · 1 line
2.39.5
#9 lore raw

Re: [PATCH v10 4/4] tpm_vpm_proxy: Use stack for TPM_CC_SET_LOCALITY

Quoted 15 lines · Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use stack allocation for TPM_CC_SET_LOCALITY, as it has known fixed size.

---
drivers/char/tpm/tpm1-cmd.c | 2 +-
drivers/char/tpm/tpm_vtpm_proxy.c | 12 +++++-------

2 files changed, 6 insertions(+), 8 deletions(-)
drivers/char/tpm/tpm1-cmd.c +0 -0
index 11c16ad9b2a7..433908cfb4a9 100644

drivers/char/tpm/tpm1-cmd.c static int tpm1_startup(struct tpm_chip *chip) · line 331

Quoted 5 lines
drivers/char/tpm/tpm1-cmd.c +1 -1
@@ -328,7 +328,7 @@ static int tpm1_startup(struct tpm_chip *chip)
 	int rc;
 
 	dev_info(&chip->dev, "TPM_Startup\n");
-	tpm_buf_init(buf, TPM_BUF_INT_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);

This change should be squashed in patch 2, right?

Thanks,
Stefano

Quoted 31 lines
drivers/char/tpm/tpm1-cmd.c +0 -0
 	tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
 	tpm_buf_append_u16(buf, TPM_ST_CLEAR);
 	rc = tpm_transmit_cmd(chip, buf, 0, "TPM_Startup");
drivers/char/tpm/tpm_vtpm_proxy.c +5 -7
index e5de14379eb2..0f1b1b67ed4e 100644
@@ -395,15 +395,13 @@ static bool vtpm_proxy_tpm_req_canceled(struct tpm_chip  *chip, u8 status)
 
 static int vtpm_proxy_request_locality(struct tpm_chip *chip, int locality)
 {
-	int rc;
-	const struct tpm_header *header;
 	struct proxy_dev *proxy_dev = dev_get_drvdata(&chip->dev);
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
+	const struct tpm_header *header;
+	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
 		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_SET_LOCALITY);
 	else
Signature · 1 line
2.39.5
author maintainer
#10 lore raw

Re: [PATCH v10 4/4] tpm_vpm_proxy: Use stack for TPM_CC_SET_LOCALITY

Quoted 18 lines · Stefano Garzarella
Quoted 17 lines · Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use stack allocation for TPM_CC_SET_LOCALITY, as it has known fixed size.

---
drivers/char/tpm/tpm1-cmd.c | 2 +-
drivers/char/tpm/tpm_vtpm_proxy.c | 12 +++++-------

2 files changed, 6 insertions(+), 8 deletions(-)
drivers/char/tpm/tpm1-cmd.c +0 -0
index 11c16ad9b2a7..433908cfb4a9 100644
@@ -328,7 +328,7 @@ static int tpm1_startup(struct tpm_chip *chip)
 	int rc;
 
Quoted 5 lines

drivers/char/tpm/tpm1-cmd.c static int tpm1_startup(struct tpm_chip *chip) · line 331

Quoted 3 lines
drivers/char/tpm/tpm1-cmd.c +1 -1
 	dev_info(&chip->dev, "TPM_Startup\n");
-	tpm_buf_init(buf, TPM_BUF_INT_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);

This change should be squashed in patch 2, right?

Yep, sure thanks :-)

BR, Jarkko

author maintainer
#11 lore raw
In reply to Jarkko Sakkinen
Quoted 3 lines · Jarkko Sakkinen

1. These are previous changes to tpm_buf, which make stack allocations much more feasible than previously.
2. Migrate low-hanging fruit to use stack allocations.

I highly unlikely would put this to 6.18 PR. The first patch huge but at the same time it is still a "logical change". Splitting it would make it less understandable. It's also quite stable and the despite many changes, most of them are mechanical changes (some of them I've even done originally with an LLM called 'sed').

IMHO reason to split should not be based no size but exactly on logical steps.

After these few quick rounds I take some time and work on tpm1/tpm2-cmd to make them follow a builder pattern. This helps e.g., TrenchBoot to accomplish their goals more easily as builders translate easily to early boot situations. In addition, making memory management more stack oriented usually tends to help with such situations.

So the next thing for this patch set is to make things work with parse, build and transmission decoupled from each other, and it will be as substantial change as the first patch but can be split into smaller patches as it does not change the global economy.

An example with tpm2_pcr_read:

1. tpm2_build_pcr_read(), which takes pre-initialized tpm_buf() and same parameter as today.
2. tpm_transmit()
3. tpm2_parse_pcr_read(), which takes resulting tpm_buf and parses it to a struct, let's say tpm2_pcr_read_result.

And similar decoupling is done for TPM 1 commands as they also need to translate between environments.

Obviously outer facing tpm-interface.c API can still respond to old API calls for the time being.

Other stuff:

1. tpm_buf_* from include/linux/tpm.j migrate to include/linux/tpm_buf.h
2. builders: tpm1_build.c, tpm2_build.c
3. parsers: tpm1_parse.c, tpm2_parse.c

Most likely at least at first landing some redundancy is required for Trenchboto and physical transmission path. By doing what I have described we can set a limit to the amount redunancy :-)

Quoted 7 lines

Jarkko Sakkinen (4):
tpm: Make TPM buffer allocations more robust tpm, tpm1-cmd: Use stack for trivial cases tpm, tpm2-cmd: Use stack for trivial cases
tpm_vpm_proxy: Use stack for TPM_CC_SET_LOCALITY

Quoted 20 lines
 drivers/char/tpm/tpm-buf.c                | 137 ++++++----
 drivers/char/tpm/tpm-dev-common.c         |   4 +-
 drivers/char/tpm/tpm-dev.h                |   2 +-
 drivers/char/tpm/tpm-interface.c          |   4 +-
 drivers/char/tpm/tpm-sysfs.c              |  20 +-
 drivers/char/tpm/tpm.h                    |   3 +-
 drivers/char/tpm/tpm1-cmd.c               | 151 +++++------
 drivers/char/tpm/tpm2-cmd.c               | 297 ++++++++++------------
 drivers/char/tpm/tpm2-sessions.c          | 121 +++++----
 drivers/char/tpm/tpm2-space.c             |  44 ++--
 drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
 drivers/char/tpm/tpm_vtpm_proxy.c         |  34 +--
 include/linux/tpm.h                       |  28 +-
 security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
 security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
 15 files changed, 493 insertions(+), 546 deletions(-)
Signature · 1 line
2.39.5

BR, Jarkko