git: 5377cd66852c - stable/15 - sys: add safe_read(9)

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Thu, 04 Jun 2026 00:36:25 UTC
The branch stable/15 has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=5377cd66852c13e3a5f29f2ccc0c0e14b7431c11

commit 5377cd66852c13e3a5f29f2ccc0c0e14b7431c11
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2025-03-29 17:17:01 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2026-06-04 00:34:43 +0000

    sys: add safe_read(9)
    
    (cherry picked from commit 7b2702ee25f5230011fa7f8f650b65b37248fcca)
---
 sys/amd64/amd64/machdep.c | 18 ++++++++++++++++++
 sys/sys/systm.h           |  8 ++++++++
 2 files changed, 26 insertions(+)

diff --git a/sys/amd64/amd64/machdep.c b/sys/amd64/amd64/machdep.c
index d51e5501aca9..e337337fd8e7 100644
--- a/sys/amd64/amd64/machdep.c
+++ b/sys/amd64/amd64/machdep.c
@@ -1866,6 +1866,24 @@ wrmsr_early_safe_end(void)
 		memset_early(&idt0[i], 0, sizeof(idt0[0]));
 }
 
+int
+safe_read(vm_offset_t addr, char *valp)
+{
+	struct uio uio;
+	struct iovec iov;
+
+	iov.iov_base = valp;
+	iov.iov_len = 1;
+	uio.uio_offset = addr;
+	uio.uio_iov = &iov;
+	uio.uio_iovcnt = 1;
+	uio.uio_resid = 1;
+	uio.uio_segflg = UIO_SYSSPACE;
+	uio.uio_rw = UIO_READ;
+	uio.uio_td = NULL;
+	return (uiomove_mem(UIO_MEM_KMEM, &uio));
+}
+
 #ifdef KDB
 
 /*
diff --git a/sys/sys/systm.h b/sys/sys/systm.h
index c4e0aafac452..d6488f45acae 100644
--- a/sys/sys/systm.h
+++ b/sys/sys/systm.h
@@ -563,6 +563,14 @@ void	intr_prof_stack_use(struct thread *td, struct trapframe *frame);
 
 void counted_warning(unsigned *counter, const char *msg);
 
+/*
+ * Safely read one byte of kernel memory at address addr, placing the
+ * value into *valp.  Returns 0 on success, EFAULT if read was
+ * impossible, e.g. due to the address not being mapped or not having
+ * necessary permissions.
+ */
+int safe_read(vm_offset_t addr, char *valp);
+
 /*
  * APIs to manage deprecation and obsolescence.
  */