[PATCH 01/11] uptr: add a new "universal pointer" type

From: Christoph Hellwig
Date: Wed Jun 24 2020 - 12:29:30 EST


Add a uptr_t type that can hold a pointer to either a user or kernel
memory region, and simply helpers to copy to and from it. For
architectures like x86 that have non-overlapping user and kernel
address space it just is a union and uses a TASK_SIZE check to
select the proper copy routine. For architectures with overlapping
address spaces a flag to indicate the address space is used instead.

Signed-off-by: Christoph Hellwig <hch@xxxxxx>
---
include/linux/uptr.h | 72 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 72 insertions(+)
create mode 100644 include/linux/uptr.h

diff --git a/include/linux/uptr.h b/include/linux/uptr.h
new file mode 100644
index 00000000000000..1373511f9897b4
--- /dev/null
+++ b/include/linux/uptr.h
@@ -0,0 +1,72 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2020 Christoph Hellwig.
+ *
+ * Support for "universal" pointers that can point to either kernel or userspace
+ * memory.
+ */
+#ifndef _LINUX_UPTR_H
+#define _LINUX_UPTR_H
+
+#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
+typedef union {
+ void *kernel;
+ void __user *user;
+} uptr_t;
+
+static inline uptr_t USER_UPTR(void __user *p)
+{
+ return (uptr_t) { .user = p };
+}
+
+static inline uptr_t KERNEL_UPTR(void *p)
+{
+ return (uptr_t) { .kernel = p };
+}
+
+static inline bool uptr_is_kernel(uptr_t uptr)
+{
+ return (unsigned long)uptr.kernel >= TASK_SIZE;
+}
+#else /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
+typedef struct {
+ union {
+ void *kernel;
+ void __user *user;
+ };
+ bool is_kernel : 1;
+} uptr_t;
+
+static inline uptr_t USER_UPTR(void __user *p)
+{
+ return (uptr_t) { .user = p };
+}
+
+static inline uptr_t KERNEL_UPTR(void *p)
+{
+ return (uptr_t) { .kernel = p, .is_kernel = true };
+}
+
+static inline bool uptr_is_kernel(uptr_t uptr)
+{
+ return uptr.is_kernel;
+}
+#endif /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
+
+static inline int copy_from_uptr(void *dst, uptr_t src, size_t size)
+{
+ if (!uptr_is_kernel(src))
+ return copy_from_user(dst, src.user, size);
+ memcpy(dst, src.kernel, size);
+ return 0;
+}
+
+static inline int copy_to_uptr(uptr_t dst, const void *src, size_t size)
+{
+ if (!uptr_is_kernel(dst))
+ return copy_to_user(dst.user, src, size);
+ memcpy(dst.kernel, src, size);
+ return 0;
+}
+
+#endif /* _LINUX_UPTR_H */
--
2.26.2