* [PATCH v3 4/4] selftests/proc: add tests for new pidns APIs
From: Aleksa Sarai @ 2025-07-24 8:32 UTC (permalink / raw)
To: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan
Cc: Andy Lutomirski, linux-kernel, linux-fsdevel, linux-api,
linux-doc, linux-kselftest, Aleksa Sarai
In-Reply-To: <20250724-procfs-pidns-api-v3-0-4c685c910923@cyphar.com>
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
---
tools/testing/selftests/proc/.gitignore | 1 +
tools/testing/selftests/proc/Makefile | 1 +
tools/testing/selftests/proc/proc-pidns.c | 252 ++++++++++++++++++++++++++++++
3 files changed, 254 insertions(+)
diff --git a/tools/testing/selftests/proc/.gitignore b/tools/testing/selftests/proc/.gitignore
index 973968f45bba..2dced03e9e0e 100644
--- a/tools/testing/selftests/proc/.gitignore
+++ b/tools/testing/selftests/proc/.gitignore
@@ -17,6 +17,7 @@
/proc-tid0
/proc-uptime-001
/proc-uptime-002
+/proc-pidns
/read
/self
/setns-dcache
diff --git a/tools/testing/selftests/proc/Makefile b/tools/testing/selftests/proc/Makefile
index b12921b9794b..c6f7046b9860 100644
--- a/tools/testing/selftests/proc/Makefile
+++ b/tools/testing/selftests/proc/Makefile
@@ -27,5 +27,6 @@ TEST_GEN_PROGS += setns-sysvipc
TEST_GEN_PROGS += thread-self
TEST_GEN_PROGS += proc-multiple-procfs
TEST_GEN_PROGS += proc-fsconfig-hidepid
+TEST_GEN_PROGS += proc-pidns
include ../lib.mk
diff --git a/tools/testing/selftests/proc/proc-pidns.c b/tools/testing/selftests/proc/proc-pidns.c
new file mode 100644
index 000000000000..5994375e2377
--- /dev/null
+++ b/tools/testing/selftests/proc/proc-pidns.c
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Author: Aleksa Sarai <cyphar@cyphar.com>
+ * Copyright (C) 2025 SUSE LLC.
+ */
+
+#include <assert.h>
+#include <errno.h>
+#include <sched.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/prctl.h>
+
+#include "../kselftest_harness.h"
+
+#define ASSERT_ERRNO(expected, _t, seen) \
+ __EXPECT(expected, #expected, \
+ ({__typeof__(seen) _tmp_seen = (seen); \
+ _tmp_seen >= 0 ? _tmp_seen : -errno; }), #seen, _t, 1)
+
+#define ASSERT_ERRNO_EQ(expected, seen) \
+ ASSERT_ERRNO(expected, ==, seen)
+
+#define ASSERT_SUCCESS(seen) \
+ ASSERT_ERRNO(0, <=, seen)
+
+static int touch(char *path)
+{
+ int fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC, 0644);
+ if (fd < 0)
+ return -1;
+ return close(fd);
+}
+
+FIXTURE(ns)
+{
+ int host_mntns, host_pidns;
+ int dummy_pidns;
+};
+
+FIXTURE_SETUP(ns)
+{
+ /* Stash the old mntns. */
+ self->host_mntns = open("/proc/self/ns/mnt", O_RDONLY|O_CLOEXEC);
+ ASSERT_SUCCESS(self->host_mntns);
+
+ /* Create a new mount namespace and make it private. */
+ ASSERT_SUCCESS(unshare(CLONE_NEWNS));
+ ASSERT_SUCCESS(mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL));
+
+ /*
+ * Create a proper tmpfs that we can use and will disappear once we
+ * leave this mntns.
+ */
+ ASSERT_SUCCESS(mount("tmpfs", "/tmp", "tmpfs", 0, NULL));
+
+ /*
+ * Create a pidns we can use for later tests. We need to fork off a
+ * child so that we get a usable nsfd that we can bind-mount and open.
+ */
+ ASSERT_SUCCESS(touch("/tmp/dummy-pidns"));
+
+ self->host_pidns = open("/proc/self/ns/pid", O_RDONLY|O_CLOEXEC);
+ ASSERT_SUCCESS(self->host_pidns);
+ ASSERT_SUCCESS(unshare(CLONE_NEWPID));
+
+ pid_t pid = fork();
+ ASSERT_SUCCESS(pid);
+ if (!pid) {
+ prctl(PR_SET_PDEATHSIG, SIGKILL);
+ ASSERT_SUCCESS(mount("/proc/self/ns/pid", "/tmp/dummy-pidns", NULL, MS_BIND, 0));
+ exit(0);
+ }
+
+ int wstatus;
+ ASSERT_EQ(waitpid(pid, &wstatus, 0), pid);
+ ASSERT_TRUE(WIFEXITED(wstatus));
+ ASSERT_EQ(WEXITSTATUS(wstatus), 0);
+
+ ASSERT_SUCCESS(setns(self->host_pidns, CLONE_NEWPID));
+
+ self->dummy_pidns = open("/tmp/dummy-pidns", O_RDONLY|O_CLOEXEC);
+ ASSERT_SUCCESS(self->dummy_pidns);
+}
+
+FIXTURE_TEARDOWN(ns)
+{
+ ASSERT_SUCCESS(setns(self->host_mntns, CLONE_NEWNS));
+ ASSERT_SUCCESS(close(self->host_mntns));
+
+ ASSERT_SUCCESS(close(self->host_pidns));
+ ASSERT_SUCCESS(close(self->dummy_pidns));
+}
+
+TEST_F(ns, pidns_mount_string_path)
+{
+ ASSERT_SUCCESS(mkdir("/tmp/proc-host", 0755));
+ ASSERT_SUCCESS(mount("proc", "/tmp/proc-host", "proc", 0, "pidns=/proc/self/ns/pid"));
+ ASSERT_SUCCESS(access("/tmp/proc-host/self/", X_OK));
+
+ ASSERT_SUCCESS(mkdir("/tmp/proc-dummy", 0755));
+ ASSERT_SUCCESS(mount("proc", "/tmp/proc-dummy", "proc", 0, "pidns=/tmp/dummy-pidns"));
+ ASSERT_ERRNO_EQ(-ENOENT, access("/tmp/proc-dummy/1/", X_OK));
+ ASSERT_ERRNO_EQ(-ENOENT, access("/tmp/proc-dummy/self/", X_OK));
+}
+
+TEST_F(ns, pidns_fsconfig_string_path)
+{
+ int fsfd = fsopen("proc", FSOPEN_CLOEXEC);
+ ASSERT_SUCCESS(fsfd);
+
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_SET_STRING, "pidns", "/tmp/dummy-pidns", 0));
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0));
+
+ int mountfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
+ ASSERT_SUCCESS(mountfd);
+
+ ASSERT_ERRNO_EQ(-ENOENT, faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_ERRNO_EQ(-ENOENT, faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_SUCCESS(close(fsfd));
+ ASSERT_SUCCESS(close(mountfd));
+}
+
+TEST_F(ns, pidns_fsconfig_fd)
+{
+ int fsfd = fsopen("proc", FSOPEN_CLOEXEC);
+ ASSERT_SUCCESS(fsfd);
+
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_SET_FD, "pidns", NULL, self->dummy_pidns));
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0));
+
+ int mountfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
+ ASSERT_SUCCESS(mountfd);
+
+ ASSERT_ERRNO_EQ(-ENOENT, faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_ERRNO_EQ(-ENOENT, faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_SUCCESS(close(fsfd));
+ ASSERT_SUCCESS(close(mountfd));
+}
+
+TEST_F(ns, pidns_reconfigure_remount)
+{
+ ASSERT_SUCCESS(mkdir("/tmp/proc", 0755));
+ ASSERT_SUCCESS(mount("proc", "/tmp/proc", "proc", 0, ""));
+
+ ASSERT_SUCCESS(access("/tmp/proc/1/", X_OK));
+ ASSERT_SUCCESS(access("/tmp/proc/self/", X_OK));
+
+ ASSERT_ERRNO_EQ(-EBUSY, mount(NULL, "/tmp/proc", NULL, MS_REMOUNT, "pidns=/tmp/dummy-pidns"));
+
+ ASSERT_SUCCESS(access("/tmp/proc/1/", X_OK));
+ ASSERT_SUCCESS(access("/tmp/proc/self/", X_OK));
+}
+
+TEST_F(ns, pidns_reconfigure_fsconfig_string_path)
+{
+ int fsfd = fsopen("proc", FSOPEN_CLOEXEC);
+ ASSERT_SUCCESS(fsfd);
+
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0));
+
+ int mountfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
+ ASSERT_SUCCESS(mountfd);
+
+ ASSERT_SUCCESS(faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_SUCCESS(faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_ERRNO_EQ(-EBUSY, fsconfig(fsfd, FSCONFIG_SET_STRING, "pidns", "/tmp/dummy-pidns", 0));
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_RECONFIGURE, NULL, NULL, 0)); /* noop */
+
+ ASSERT_SUCCESS(faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_SUCCESS(faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_SUCCESS(close(fsfd));
+ ASSERT_SUCCESS(close(mountfd));
+}
+
+TEST_F(ns, pidns_reconfigure_fsconfig_fd)
+{
+ int fsfd = fsopen("proc", FSOPEN_CLOEXEC);
+ ASSERT_SUCCESS(fsfd);
+
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0));
+
+ int mountfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
+ ASSERT_SUCCESS(mountfd);
+
+ ASSERT_SUCCESS(faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_SUCCESS(faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_ERRNO_EQ(-EBUSY, fsconfig(fsfd, FSCONFIG_SET_FD, "pidns", NULL, self->dummy_pidns));
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_RECONFIGURE, NULL, NULL, 0)); /* noop */
+
+ ASSERT_SUCCESS(faccessat(mountfd, "1/", X_OK, 0));
+ ASSERT_SUCCESS(faccessat(mountfd, "self/", X_OK, 0));
+
+ ASSERT_SUCCESS(close(fsfd));
+ ASSERT_SUCCESS(close(mountfd));
+}
+
+int is_same_inode(int fd1, int fd2)
+{
+ struct stat stat1, stat2;
+
+ assert(fstat(fd1, &stat1) == 0);
+ assert(fstat(fd2, &stat2) == 0);
+
+ return stat1.st_ino == stat2.st_ino && stat1.st_dev == stat2.st_dev;
+}
+
+#define PROCFS_IOCTL_MAGIC 'f'
+#define PROCFS_GET_PID_NAMESPACE _IO(PROCFS_IOCTL_MAGIC, 1)
+
+TEST_F(ns, get_pidns_ioctl)
+{
+ int fsfd = fsopen("proc", FSOPEN_CLOEXEC);
+ ASSERT_SUCCESS(fsfd);
+
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_SET_FD, "pidns", NULL, self->dummy_pidns));
+ ASSERT_SUCCESS(fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0));
+
+ int mountfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
+ ASSERT_SUCCESS(mountfd);
+
+ /* fsmount returns an O_PATH, which ioctl(2) doesn't accept. */
+ int new_mountfd = openat(mountfd, ".", O_RDONLY|O_DIRECTORY|O_CLOEXEC);
+ ASSERT_SUCCESS(new_mountfd);
+
+ ASSERT_SUCCESS(close(mountfd));
+ mountfd = -EBADF;
+
+ int procfs_pidns = ioctl(new_mountfd, PROCFS_GET_PID_NAMESPACE);
+ ASSERT_SUCCESS(procfs_pidns);
+
+ ASSERT_NE(self->dummy_pidns, procfs_pidns);
+ ASSERT_FALSE(is_same_inode(self->host_pidns, procfs_pidns));
+ ASSERT_TRUE(is_same_inode(self->dummy_pidns, procfs_pidns));
+
+ ASSERT_SUCCESS(close(fsfd));
+ ASSERT_SUCCESS(close(new_mountfd));
+ ASSERT_SUCCESS(close(procfs_pidns));
+}
+
+TEST_HARNESS_MAIN
--
2.50.0
^ permalink raw reply related
* [PATCH v3 3/4] procfs: add PROCFS_GET_PID_NAMESPACE ioctl
From: Aleksa Sarai @ 2025-07-24 8:32 UTC (permalink / raw)
To: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan
Cc: Andy Lutomirski, linux-kernel, linux-fsdevel, linux-api,
linux-doc, linux-kselftest, Aleksa Sarai
In-Reply-To: <20250724-procfs-pidns-api-v3-0-4c685c910923@cyphar.com>
/proc has historically had very opaque semantics about PID namespaces,
which is a little unfortunate for container runtimes and other programs
that deal with switching namespaces very often. One common issue is that
of converting between PIDs in the process's namespace and PIDs in the
namespace of /proc.
In principle, it is possible to do this today by opening a pidfd with
pidfd_open(2) and then looking at /proc/self/fdinfo/$n (which will
contain a PID value translated to the pid namespace associated with that
procfs superblock). However, allocating a new file for each PID to be
converted is less than ideal for programs that may need to scan procfs,
and it is generally useful for userspace to be able to finally get this
information from procfs.
So, add a new API for this in the form of an ioctl(2) you can call on
the root directory of procfs. The returned file descriptor will have
O_CLOEXEC set. This acts as a sister feature to the new "pidns" mount
option, finally allowing userspace full control of the pid namespaces
associated with procfs instances.
The permission model for this is a bit looser than that of the "pidns"
mount option, but this is mainly because /proc/1/ns/pid provides the
same information, so as long as you have access to that magic-link (or
something equivalently reasonable such as privileges with CAP_SYS_ADMIN
or being in an ancestor pid namespace) it makes sense to allow userspace
to grab a handle. setns(2) will still have their own permission checks,
so being able to open a pidns handle doesn't really provide too many
other capabilities.
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
---
Documentation/filesystems/proc.rst | 4 +++
fs/proc/root.c | 54 ++++++++++++++++++++++++++++++++++++--
include/uapi/linux/fs.h | 3 +++
3 files changed, 59 insertions(+), 2 deletions(-)
diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst
index 5a157dadea0b..840f820fb467 100644
--- a/Documentation/filesystems/proc.rst
+++ b/Documentation/filesystems/proc.rst
@@ -2400,6 +2400,10 @@ will use the calling process's active pid namespace. Note that the pid
namespace of an existing procfs instance cannot be modified (attempting to do
so will give an `-EBUSY` error).
+Processes can check which pid namespace is used by a procfs instance by using
+the `PROCFS_GET_PID_NAMESPACE` ioctl() on the root directory of the procfs
+instance.
+
Chapter 5: Filesystem behavior
==============================
diff --git a/fs/proc/root.c b/fs/proc/root.c
index 22f8b10f6265..c6110436e528 100644
--- a/fs/proc/root.c
+++ b/fs/proc/root.c
@@ -23,8 +23,10 @@
#include <linux/cred.h>
#include <linux/magic.h>
#include <linux/slab.h>
+#include <linux/ptrace.h>
#include "internal.h"
+#include "../internal.h"
struct proc_fs_context {
struct pid_namespace *pid_ns;
@@ -430,15 +432,63 @@ static int proc_root_readdir(struct file *file, struct dir_context *ctx)
return proc_pid_readdir(file, ctx);
}
+static long int proc_root_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
+{
+ switch (cmd) {
+#ifdef CONFIG_PID_NS
+ case PROCFS_GET_PID_NAMESPACE: {
+ struct pid_namespace *active = task_active_pid_ns(current);
+ struct pid_namespace *ns = proc_pid_ns(file_inode(filp)->i_sb);
+ bool can_access_pidns = false;
+
+ /*
+ * If we are in an ancestors of the pidns, or have join
+ * privileges (CAP_SYS_ADMIN), then it makes sense that we
+ * would be able to grab a handle to the pidns.
+ *
+ * Otherwise, if there is a root process, then being able to
+ * access /proc/$pid/ns/pid is equivalent to this ioctl and so
+ * we should probably match the permission model. For empty
+ * namespaces it seems unlikely for there to be a downside to
+ * allowing unprivileged users to open a handle to it (setns
+ * will fail for unprivileged users anyway).
+ */
+ can_access_pidns = pidns_is_ancestor(ns, active) ||
+ ns_capable(ns->user_ns, CAP_SYS_ADMIN);
+ if (!can_access_pidns) {
+ bool cannot_ptrace_pid1 = false;
+
+ read_lock(&tasklist_lock);
+ if (ns->child_reaper)
+ cannot_ptrace_pid1 = ptrace_may_access(ns->child_reaper,
+ PTRACE_MODE_READ_FSCREDS);
+ read_unlock(&tasklist_lock);
+ can_access_pidns = !cannot_ptrace_pid1;
+ }
+ if (!can_access_pidns)
+ return -EPERM;
+
+ /* open_namespace() unconditionally consumes the reference. */
+ get_pid_ns(ns);
+ return open_namespace(to_ns_common(ns));
+ }
+#endif /* CONFIG_PID_NS */
+ default:
+ return -ENOIOCTLCMD;
+ }
+}
+
/*
* The root /proc directory is special, as it has the
* <pid> directories. Thus we don't use the generic
* directory handling functions for that..
*/
static const struct file_operations proc_root_operations = {
- .read = generic_read_dir,
- .iterate_shared = proc_root_readdir,
+ .read = generic_read_dir,
+ .iterate_shared = proc_root_readdir,
.llseek = generic_file_llseek,
+ .unlocked_ioctl = proc_root_ioctl,
+ .compat_ioctl = compat_ptr_ioctl,
};
/*
diff --git a/include/uapi/linux/fs.h b/include/uapi/linux/fs.h
index 0bd678a4a10e..aa642cb48feb 100644
--- a/include/uapi/linux/fs.h
+++ b/include/uapi/linux/fs.h
@@ -437,6 +437,9 @@ typedef int __bitwise __kernel_rwf_t;
#define PROCFS_IOCTL_MAGIC 'f'
+/* procfs root ioctls */
+#define PROCFS_GET_PID_NAMESPACE _IO(PROCFS_IOCTL_MAGIC, 1)
+
/* Pagemap ioctl */
#define PAGEMAP_SCAN _IOWR(PROCFS_IOCTL_MAGIC, 16, struct pm_scan_arg)
--
2.50.0
^ permalink raw reply related
* [PATCH v3 2/4] procfs: add "pidns" mount option
From: Aleksa Sarai @ 2025-07-24 8:32 UTC (permalink / raw)
To: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan
Cc: Andy Lutomirski, linux-kernel, linux-fsdevel, linux-api,
linux-doc, linux-kselftest, Aleksa Sarai
In-Reply-To: <20250724-procfs-pidns-api-v3-0-4c685c910923@cyphar.com>
Since the introduction of pid namespaces, their interaction with procfs
has been entirely implicit in ways that require a lot of dancing around
by programs that need to construct sandboxes with different PID
namespaces.
Being able to explicitly specify the pid namespace to use when
constructing a procfs super block will allow programs to no longer need
to fork off a process which does then does unshare(2) / setns(2) and
forks again in order to construct a procfs in a pidns.
So, provide a "pidns" mount option which allows such users to just
explicitly state which pid namespace they want that procfs instance to
use. This interface can be used with fsconfig(2) either with a file
descriptor or a path:
fsconfig(procfd, FSCONFIG_SET_FD, "pidns", NULL, nsfd);
fsconfig(procfd, FSCONFIG_SET_STRING, "pidns", "/proc/self/ns/pid", 0);
or with classic mount(2) / mount(8):
// mount -t proc -o pidns=/proc/self/ns/pid proc /tmp/proc
mount("proc", "/tmp/proc", "proc", MS_..., "pidns=/proc/self/ns/pid");
As this new API is effectively shorthand for setns(2) followed by
mount(2), the permission model for this mirrors pidns_install() to avoid
opening up new attack surfaces by loosening the existing permission
model.
In order to avoid having to RCU-protect all users of proc_pid_ns() (to
avoid UAFs), attempting to reconfigure an existing procfs instance's pid
namespace will error out with -EBUSY. Creating new procfs instances is
quite cheap, so this should not be an impediment to most users, and lets
us avoid a lot of churn in fs/proc/* for a feature that it seems
unlikely userspace would use.
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
---
Documentation/filesystems/proc.rst | 8 +++
fs/proc/root.c | 102 ++++++++++++++++++++++++++++++++++---
2 files changed, 104 insertions(+), 6 deletions(-)
diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst
index 5236cb52e357..5a157dadea0b 100644
--- a/Documentation/filesystems/proc.rst
+++ b/Documentation/filesystems/proc.rst
@@ -2360,6 +2360,7 @@ The following mount options are supported:
hidepid= Set /proc/<pid>/ access mode.
gid= Set the group authorized to learn processes information.
subset= Show only the specified subset of procfs.
+ pidns= Specify a the namespace used by this procfs.
========= ========================================================
hidepid=off or hidepid=0 means classic mode - everybody may access all
@@ -2392,6 +2393,13 @@ information about processes information, just add identd to this group.
subset=pid hides all top level files and directories in the procfs that
are not related to tasks.
+pidns= specifies a pid namespace (either as a string path to something like
+`/proc/$pid/ns/pid`, or a file descriptor when using `FSCONFIG_SET_FD`) that
+will be used by the procfs instance when translating pids. By default, procfs
+will use the calling process's active pid namespace. Note that the pid
+namespace of an existing procfs instance cannot be modified (attempting to do
+so will give an `-EBUSY` error).
+
Chapter 5: Filesystem behavior
==============================
diff --git a/fs/proc/root.c b/fs/proc/root.c
index ed86ac710384..22f8b10f6265 100644
--- a/fs/proc/root.c
+++ b/fs/proc/root.c
@@ -38,12 +38,18 @@ enum proc_param {
Opt_gid,
Opt_hidepid,
Opt_subset,
+#ifdef CONFIG_PID_NS
+ Opt_pidns,
+#endif
};
static const struct fs_parameter_spec proc_fs_parameters[] = {
- fsparam_u32("gid", Opt_gid),
+ fsparam_u32("gid", Opt_gid),
fsparam_string("hidepid", Opt_hidepid),
fsparam_string("subset", Opt_subset),
+#ifdef CONFIG_PID_NS
+ fsparam_file_or_string("pidns", Opt_pidns),
+#endif
{}
};
@@ -109,11 +115,67 @@ static int proc_parse_subset_param(struct fs_context *fc, char *value)
return 0;
}
+#ifdef CONFIG_PID_NS
+static int proc_parse_pidns_param(struct fs_context *fc,
+ struct fs_parameter *param,
+ struct fs_parse_result *result)
+{
+ struct proc_fs_context *ctx = fc->fs_private;
+ struct pid_namespace *target, *active = task_active_pid_ns(current);
+ struct ns_common *ns;
+ struct file *ns_filp __free(fput) = NULL;
+
+ switch (param->type) {
+ case fs_value_is_file:
+ /* came throug fsconfig, steal the file reference */
+ ns_filp = param->file;
+ param->file = NULL;
+ break;
+ case fs_value_is_string:
+ ns_filp = filp_open(param->string, O_RDONLY, 0);
+ break;
+ default:
+ WARN_ON_ONCE(true);
+ break;
+ }
+ if (!ns_filp)
+ ns_filp = ERR_PTR(-EBADF);
+ if (IS_ERR(ns_filp)) {
+ errorfc(fc, "could not get file from pidns argument");
+ return PTR_ERR(ns_filp);
+ }
+
+ if (!proc_ns_file(ns_filp))
+ return invalfc(fc, "pidns argument is not an nsfs file");
+ ns = get_proc_ns(file_inode(ns_filp));
+ if (ns->ops->type != CLONE_NEWPID)
+ return invalfc(fc, "pidns argument is not a pidns file");
+ target = container_of(ns, struct pid_namespace, ns);
+
+ /*
+ * pidns= is shorthand for joining the pidns to get a fsopen fd, so the
+ * permission model should be the same as pidns_install().
+ */
+ if (!ns_capable(target->user_ns, CAP_SYS_ADMIN)) {
+ errorfc(fc, "insufficient permissions to set pidns");
+ return -EPERM;
+ }
+ if (!pidns_is_ancestor(target, active))
+ return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+ put_pid_ns(ctx->pid_ns);
+ ctx->pid_ns = get_pid_ns(target);
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+ return 0;
+}
+#endif /* CONFIG_PID_NS */
+
static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
struct proc_fs_context *ctx = fc->fs_private;
struct fs_parse_result result;
- int opt;
+ int opt, err;
opt = fs_parse(fc, proc_fs_parameters, param, &result);
if (opt < 0)
@@ -125,15 +187,36 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
break;
case Opt_hidepid:
- if (proc_parse_hidepid_param(fc, param))
- return -EINVAL;
+ err = proc_parse_hidepid_param(fc, param);
+ if (err)
+ return err;
break;
case Opt_subset:
- if (proc_parse_subset_param(fc, param->string) < 0)
- return -EINVAL;
+ err = proc_parse_subset_param(fc, param->string);
+ if (err)
+ return err;
break;
+#ifdef CONFIG_PID_NS
+ case Opt_pidns:
+ /*
+ * We would have to RCU-protect every proc_pid_ns() or
+ * proc_sb_info() access if we allowed this to be reconfigured
+ * for an existing procfs instance. Luckily, procfs instances
+ * are cheap to create, and mount-beneath would let you
+ * atomically replace an instance even with overmounts.
+ */
+ if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
+ errorfc(fc, "cannot reconfigure pidns for existing procfs");
+ return -EBUSY;
+ }
+ err = proc_parse_pidns_param(fc, param, &result);
+ if (err)
+ return err;
+ break;
+#endif
+
default:
return -EINVAL;
}
@@ -154,6 +237,13 @@ static void proc_apply_options(struct proc_fs_info *fs_info,
fs_info->hide_pid = ctx->hidepid;
if (ctx->mask & (1 << Opt_subset))
fs_info->pidonly = ctx->pidonly;
+#ifdef CONFIG_PID_NS
+ if (ctx->mask & (1 << Opt_pidns) &&
+ !WARN_ON_ONCE(fc->purpose == FS_CONTEXT_FOR_RECONFIGURE)) {
+ put_pid_ns(fs_info->pid_ns);
+ fs_info->pid_ns = get_pid_ns(ctx->pid_ns);
+ }
+#endif
}
static int proc_fill_super(struct super_block *s, struct fs_context *fc)
--
2.50.0
^ permalink raw reply related
* [PATCH v3 1/4] pidns: move is-ancestor logic to helper
From: Aleksa Sarai @ 2025-07-24 8:32 UTC (permalink / raw)
To: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan
Cc: Andy Lutomirski, linux-kernel, linux-fsdevel, linux-api,
linux-doc, linux-kselftest, Aleksa Sarai
In-Reply-To: <20250724-procfs-pidns-api-v3-0-4c685c910923@cyphar.com>
This check will be needed in later patches, and there's no point
open-coding it each time.
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
---
include/linux/pid_namespace.h | 9 +++++++++
kernel/pid_namespace.c | 23 +++++++++++++++--------
2 files changed, 24 insertions(+), 8 deletions(-)
diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
index 7c67a5811199..17fdc059f8da 100644
--- a/include/linux/pid_namespace.h
+++ b/include/linux/pid_namespace.h
@@ -84,6 +84,9 @@ extern void zap_pid_ns_processes(struct pid_namespace *pid_ns);
extern int reboot_pid_ns(struct pid_namespace *pid_ns, int cmd);
extern void put_pid_ns(struct pid_namespace *ns);
+extern bool pidns_is_ancestor(struct pid_namespace *child,
+ struct pid_namespace *ancestor);
+
#else /* !CONFIG_PID_NS */
#include <linux/err.h>
@@ -118,6 +121,12 @@ static inline int reboot_pid_ns(struct pid_namespace *pid_ns, int cmd)
{
return 0;
}
+
+static inline bool pidns_is_ancestor(struct pid_namespace *child,
+ struct pid_namespace *ancestor)
+{
+ return false;
+}
#endif /* CONFIG_PID_NS */
extern struct pid_namespace *task_active_pid_ns(struct task_struct *tsk);
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 7098ed44e717..c2783c5fa90b 100644
--- a/kernel/pid_namespace.c
+++ b/kernel/pid_namespace.c
@@ -390,11 +390,24 @@ static void pidns_put(struct ns_common *ns)
put_pid_ns(to_pid_ns(ns));
}
+bool pidns_is_ancestor(struct pid_namespace *child,
+ struct pid_namespace *ancestor)
+{
+ struct pid_namespace *ns;
+
+ if (child->level < ancestor->level)
+ return false;
+ for (ns = child; ns->level > ancestor->level; ns = ns->parent)
+ ;
+ return ns == ancestor;
+}
+EXPORT_SYMBOL_GPL(pidns_is_ancestor);
+
static int pidns_install(struct nsset *nsset, struct ns_common *ns)
{
struct nsproxy *nsproxy = nsset->nsproxy;
struct pid_namespace *active = task_active_pid_ns(current);
- struct pid_namespace *ancestor, *new = to_pid_ns(ns);
+ struct pid_namespace *new = to_pid_ns(ns);
if (!ns_capable(new->user_ns, CAP_SYS_ADMIN) ||
!ns_capable(nsset->cred->user_ns, CAP_SYS_ADMIN))
@@ -408,13 +421,7 @@ static int pidns_install(struct nsset *nsset, struct ns_common *ns)
* this maintains the property that processes and their
* children can not escape their current pid namespace.
*/
- if (new->level < active->level)
- return -EINVAL;
-
- ancestor = new;
- while (ancestor->level > active->level)
- ancestor = ancestor->parent;
- if (ancestor != active)
+ if (!pidns_is_ancestor(new, active))
return -EINVAL;
put_pid_ns(nsproxy->pid_ns_for_children);
--
2.50.0
^ permalink raw reply related
* [PATCH v3 0/4] procfs: make reference pidns more user-visible
From: Aleksa Sarai @ 2025-07-24 8:32 UTC (permalink / raw)
To: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan
Cc: Andy Lutomirski, linux-kernel, linux-fsdevel, linux-api,
linux-doc, linux-kselftest, Aleksa Sarai
Ever since the introduction of pid namespaces, procfs has had very
implicit behaviour surrounding them (the pidns used by a procfs mount is
auto-selected based on the mounting process's active pidns, and the
pidns itself is basically hidden once the mount has been constructed).
/* pidns mount option for procfs */
This implicit behaviour has historically meant that userspace was
required to do some special dances in order to configure the pidns of a
procfs mount as desired. Examples include:
* In order to bypass the mnt_too_revealing() check, Kubernetes creates
a procfs mount from an empty pidns so that user namespaced containers
can be nested (without this, the nested containers would fail to
mount procfs). But this requires forking off a helper process because
you cannot just one-shot this using mount(2).
* Container runtimes in general need to fork into a container before
configuring its mounts, which can lead to security issues in the case
of shared-pidns containers (a privileged process in the pidns can
interact with your container runtime process). While
SUID_DUMP_DISABLE and user namespaces make this less of an issue, the
strict need for this due to a minor uAPI wart is kind of unfortunate.
Things would be much easier if there was a way for userspace to just
specify the pidns they want. Patch 1 implements a new "pidns" argument
which can be set using fsconfig(2):
fsconfig(procfd, FSCONFIG_SET_FD, "pidns", NULL, nsfd);
fsconfig(procfd, FSCONFIG_SET_STRING, "pidns", "/proc/self/ns/pid", 0);
or classic mount(2) / mount(8):
// mount -t proc -o pidns=/proc/self/ns/pid proc /tmp/proc
mount("proc", "/tmp/proc", "proc", MS_..., "pidns=/proc/self/ns/pid");
The initial security model I have in this RFC is to be as conservative
as possible and just mirror the security model for setns(2) -- which
means that you can only set pidns=... to pid namespaces that your
current pid namespace is a direct ancestor of and you have CAP_SYS_ADMIN
privileges over the pid namespace. This fulfils the requirements of
container runtimes, but I suspect that this may be too strict for some
usecases.
The pidns argument is not displayed in mountinfo -- it's not clear to me
what value it would make sense to show (maybe we could just use ns_dname
to provide an identifier for the namespace, but this number would be
fairly useless to userspace). I'm open to suggestions. Note that
PROCFS_GET_PID_NAMESPACE (see below) does at least let userspace get
information about this outside of mountinfo.
Note that you cannot change the pidns of an already-created procfs
instance. The primary reason is that allowing this to be changed would
require RCU-protecting proc_pid_ns(sb) and thus auditing all of
fs/proc/* and some of the users in fs/* to make sure they wouldn't UAF
the pid namespace. Since creating procfs instances is very cheap, it
seems unnecessary to overcomplicate this upfront. Trying to reconfigure
procfs this way errors out with -EBUSY.
/* ioctl(PROCFS_GET_PID_NAMESPACE) */
In addition, being able to figure out what pid namespace is being used
by a procfs mount is quite useful when you have an administrative
process (such as a container runtime) which wants to figure out the
correct way of mapping PIDs between its own namespace and the namespace
for procfs (using NS_GET_{PID,TGID}_{IN,FROM}_PIDNS). There are
alternative ways to do this, but they all rely on ancillary information
that third-party libraries and tools do not necessarily have access to.
To make this easier, add a new ioctl (PROCFS_GET_PID_NAMESPACE) which
can be used to get a reference to the pidns that a procfs is using.
It's not quite clear what is the correct security model for this API,
but the current approach I've taken is to:
* Make the ioctl only valid on the root (meaning that a process without
access to the procfs root -- such as only having an fd to a procfs
file or some open_tree(2)-like subset -- cannot use this API).
* Require that the process requesting either has access to
/proc/1/ns/pid anyway (i.e. has ptrace-read access to the pidns
pid1), has CAP_SYS_ADMIN access to the pidns (i.e. has administrative
access to it and can join it if they had a handle), or is in a pidns
that is a direct ancestor of the target pidns (i.e. all of the pids
are already visible in the procfs for the current process's pidns).
The security model for this is a little loose, as it seems to me that
all of the cases mentioned are valid cases to allow access, but I'm open
to suggestions for whether we need to make this stricter or looser.
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
---
Changes in v3:
- Disallow changing pidns for existing procfs instances, as we'd
probably have to RCU-protect everything that touches the pinned pidns
reference.
- Improve tests with slightly nicer ASSERT_ERRNO* macros.
- v2: <https://lore.kernel.org/r/20250723-procfs-pidns-api-v2-0-621e7edd8e40@cyphar.com>
Changes in v2:
- #ifdef CONFIG_PID_NS
- Improve cover letter wording to make it clear we're talking about two
separate features with different permission models. [Andy Lutomirski]
- Fix build warnings in pidns_is_ancestor() patch. [kernel test robot]
- v1: <https://lore.kernel.org/r/20250721-procfs-pidns-api-v1-0-5cd9007e512d@cyphar.com>
---
Aleksa Sarai (4):
pidns: move is-ancestor logic to helper
procfs: add "pidns" mount option
procfs: add PROCFS_GET_PID_NAMESPACE ioctl
selftests/proc: add tests for new pidns APIs
Documentation/filesystems/proc.rst | 12 ++
fs/proc/root.c | 156 +++++++++++++++++-
include/linux/pid_namespace.h | 9 ++
include/uapi/linux/fs.h | 3 +
kernel/pid_namespace.c | 23 ++-
tools/testing/selftests/proc/.gitignore | 1 +
tools/testing/selftests/proc/Makefile | 1 +
tools/testing/selftests/proc/proc-pidns.c | 252 ++++++++++++++++++++++++++++++
8 files changed, 441 insertions(+), 16 deletions(-)
---
base-commit: 66639db858112bf6b0f76677f7517643d586e575
change-id: 20250717-procfs-pidns-api-8ed1583431f0
Best regards,
--
Aleksa Sarai <cyphar@cyphar.com>
^ permalink raw reply
* Re: [PATCH RFC v2 0/4] procfs: make reference pidns more user-visible
From: Christian Brauner @ 2025-07-24 7:36 UTC (permalink / raw)
To: Aleksa Sarai
Cc: Alexander Viro, Jan Kara, Jonathan Corbet, Shuah Khan,
linux-kernel, linux-fsdevel, linux-api, linux-doc,
linux-kselftest
In-Reply-To: <20250723-procfs-pidns-api-v2-0-621e7edd8e40@cyphar.com>
On Wed, Jul 23, 2025 at 09:18:50AM +1000, Aleksa Sarai wrote:
> Ever since the introduction of pid namespaces, procfs has had very
> implicit behaviour surrounding them (the pidns used by a procfs mount is
> auto-selected based on the mounting process's active pidns, and the
> pidns itself is basically hidden once the mount has been constructed).
>
> /* pidns mount option for procfs */
I like it. I think this will be very useful!
Fwiw, I think sysfs could probably use the same treatment.
It should probably gain a pidns & netns mount option and the ioctls to
get those out of sysfs so you know where that sysfs belongs. Thoughts?
^ permalink raw reply
* Re: [PATCH RFC v2 3/4] procfs: add PROCFS_GET_PID_NAMESPACE ioctl
From: Christian Brauner @ 2025-07-24 7:34 UTC (permalink / raw)
To: Aleksa Sarai
Cc: Alexander Viro, Jan Kara, Jonathan Corbet, Shuah Khan,
linux-kernel, linux-fsdevel, linux-api, linux-doc,
linux-kselftest
In-Reply-To: <20250723-procfs-pidns-api-v2-3-621e7edd8e40@cyphar.com>
On Wed, Jul 23, 2025 at 09:18:53AM +1000, Aleksa Sarai wrote:
> /proc has historically had very opaque semantics about PID namespaces,
> which is a little unfortunate for container runtimes and other programs
> that deal with switching namespaces very often. One common issue is that
> of converting between PIDs in the process's namespace and PIDs in the
> namespace of /proc.
>
> In principle, it is possible to do this today by opening a pidfd with
> pidfd_open(2) and then looking at /proc/self/fdinfo/$n (which will
> contain a PID value translated to the pid namespace associated with that
> procfs superblock). However, allocating a new file for each PID to be
> converted is less than ideal for programs that may need to scan procfs,
> and it is generally useful for userspace to be able to finally get this
> information from procfs.
>
> So, add a new API for this in the form of an ioctl(2) you can call on
> the root directory of procfs. The returned file descriptor will have
> O_CLOEXEC set. This acts as a sister feature to the new "pidns" mount
> option, finally allowing userspace full control of the pid namespaces
> associated with procfs instances.
>
> The permission model for this is a bit looser than that of the "pidns"
> mount option, but this is mainly because /proc/1/ns/pid provides the
> same information, so as long as you have access to that magic-link (or
> something equivalently reasonable such as privileges with CAP_SYS_ADMIN
> or being in an ancestor pid namespace) it makes sense to allow userspace
> to grab a handle. setns(2) will still have their own permission checks,
> so being able to open a pidns handle doesn't really provide too many
> other capabilities.
>
> Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
> ---
> Documentation/filesystems/proc.rst | 4 +++
> fs/proc/root.c | 54 ++++++++++++++++++++++++++++++++++++--
> include/uapi/linux/fs.h | 3 +++
> 3 files changed, 59 insertions(+), 2 deletions(-)
>
> diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst
> index c520b9f8a3fd..506383273c9d 100644
> --- a/Documentation/filesystems/proc.rst
> +++ b/Documentation/filesystems/proc.rst
> @@ -2398,6 +2398,10 @@ pidns= specifies a pid namespace (either as a string path to something like
> will be used by the procfs instance when translating pids. By default, procfs
> will use the calling process's active pid namespace.
>
> +Processes can check which pid namespace is used by a procfs instance by using
> +the `PROCFS_GET_PID_NAMESPACE` ioctl() on the root directory of the procfs
> +instance.
> +
> Chapter 5: Filesystem behavior
> ==============================
>
> diff --git a/fs/proc/root.c b/fs/proc/root.c
> index 057c8a125c6e..548a57ec2152 100644
> --- a/fs/proc/root.c
> +++ b/fs/proc/root.c
> @@ -23,8 +23,10 @@
> #include <linux/cred.h>
> #include <linux/magic.h>
> #include <linux/slab.h>
> +#include <linux/ptrace.h>
>
> #include "internal.h"
> +#include "../internal.h"
>
> struct proc_fs_context {
> struct pid_namespace *pid_ns;
> @@ -418,15 +420,63 @@ static int proc_root_readdir(struct file *file, struct dir_context *ctx)
> return proc_pid_readdir(file, ctx);
> }
>
> +static long int proc_root_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
> +{
> + switch (cmd) {
> +#ifdef CONFIG_PID_NS
> + case PROCFS_GET_PID_NAMESPACE: {
> + struct pid_namespace *active = task_active_pid_ns(current);
> + struct pid_namespace *ns = proc_pid_ns(file_inode(filp)->i_sb);
> + bool can_access_pidns = false;
> +
> + /*
> + * If we are in an ancestors of the pidns, or have join
> + * privileges (CAP_SYS_ADMIN), then it makes sense that we
> + * would be able to grab a handle to the pidns.
> + *
> + * Otherwise, if there is a root process, then being able to
> + * access /proc/$pid/ns/pid is equivalent to this ioctl and so
> + * we should probably match the permission model. For empty
> + * namespaces it seems unlikely for there to be a downside to
> + * allowing unprivileged users to open a handle to it (setns
> + * will fail for unprivileged users anyway).
> + */
> + can_access_pidns = pidns_is_ancestor(ns, active) ||
> + ns_capable(ns->user_ns, CAP_SYS_ADMIN);
This seems to imply that if @ns is a descendant of @active that the
caller holds privileges over it. Is that actually always true?
IOW, why is the check different from the previous pidns= mount option
check. I would've expected:
ns_capable(_no_audit)(ns->user_ns) && pidns_is_ancestor(ns, active)
and then the ptrace check as a fallback.
> + if (!can_access_pidns) {
> + bool cannot_ptrace_pid1 = false;
> +
> + read_lock(&tasklist_lock);
> + if (ns->child_reaper)
> + cannot_ptrace_pid1 = ptrace_may_access(ns->child_reaper,
> + PTRACE_MODE_READ_FSCREDS);
> + read_unlock(&tasklist_lock);
> + can_access_pidns = !cannot_ptrace_pid1;
> + }
> + if (!can_access_pidns)
> + return -EPERM;
> +
> + /* open_namespace() unconditionally consumes the reference. */
> + get_pid_ns(ns);
> + return open_namespace(to_ns_common(ns));
> + }
> +#endif /* CONFIG_PID_NS */
> + default:
> + return -ENOIOCTLCMD;
> + }
> +}
> +
> /*
> * The root /proc directory is special, as it has the
> * <pid> directories. Thus we don't use the generic
> * directory handling functions for that..
> */
> static const struct file_operations proc_root_operations = {
> - .read = generic_read_dir,
> - .iterate_shared = proc_root_readdir,
> + .read = generic_read_dir,
> + .iterate_shared = proc_root_readdir,
> .llseek = generic_file_llseek,
> + .unlocked_ioctl = proc_root_ioctl,
> + .compat_ioctl = compat_ptr_ioctl,
> };
>
> /*
> diff --git a/include/uapi/linux/fs.h b/include/uapi/linux/fs.h
> index 0bd678a4a10e..aa642cb48feb 100644
> --- a/include/uapi/linux/fs.h
> +++ b/include/uapi/linux/fs.h
> @@ -437,6 +437,9 @@ typedef int __bitwise __kernel_rwf_t;
>
> #define PROCFS_IOCTL_MAGIC 'f'
>
> +/* procfs root ioctls */
> +#define PROCFS_GET_PID_NAMESPACE _IO(PROCFS_IOCTL_MAGIC, 1)
> +
> /* Pagemap ioctl */
> #define PAGEMAP_SCAN _IOWR(PROCFS_IOCTL_MAGIC, 16, struct pm_scan_arg)
>
>
> --
> 2.50.0
>
^ permalink raw reply
* Re: [PATCH RFC v2 2/4] procfs: add "pidns" mount option
From: Christian Brauner @ 2025-07-24 7:25 UTC (permalink / raw)
To: Aleksa Sarai
Cc: Alexander Viro, Jan Kara, Jonathan Corbet, Shuah Khan,
linux-kernel, linux-fsdevel, linux-api, linux-doc,
linux-kselftest
In-Reply-To: <20250723-procfs-pidns-api-v2-2-621e7edd8e40@cyphar.com>
On Wed, Jul 23, 2025 at 09:18:52AM +1000, Aleksa Sarai wrote:
> Since the introduction of pid namespaces, their interaction with procfs
> has been entirely implicit in ways that require a lot of dancing around
> by programs that need to construct sandboxes with different PID
> namespaces.
>
> Being able to explicitly specify the pid namespace to use when
> constructing a procfs super block will allow programs to no longer need
> to fork off a process which does then does unshare(2) / setns(2) and
> forks again in order to construct a procfs in a pidns.
>
> So, provide a "pidns" mount option which allows such users to just
> explicitly state which pid namespace they want that procfs instance to
> use. This interface can be used with fsconfig(2) either with a file
> descriptor or a path:
>
> fsconfig(procfd, FSCONFIG_SET_FD, "pidns", NULL, nsfd);
> fsconfig(procfd, FSCONFIG_SET_STRING, "pidns", "/proc/self/ns/pid", 0);
Fwiw, namespace mount options could just be VFS generic mount options.
But it's not something that we need to solve right now.
>
> or with classic mount(2) / mount(8):
>
> // mount -t proc -o pidns=/proc/self/ns/pid proc /tmp/proc
> mount("proc", "/tmp/proc", "proc", MS_..., "pidns=/proc/self/ns/pid");
>
> As this new API is effectively shorthand for setns(2) followed by
> mount(2), the permission model for this mirrors pidns_install() to avoid
> opening up new attack surfaces by loosening the existing permission
> model.
>
> Note that the mount infrastructure also allows userspace to reconfigure
> the pidns of an existing procfs mount, which may or may not be useful to
> some users.
>
> Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
> ---
> Documentation/filesystems/proc.rst | 6 +++
> fs/proc/root.c | 90 +++++++++++++++++++++++++++++++++++---
> 2 files changed, 90 insertions(+), 6 deletions(-)
>
> diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst
> index 5236cb52e357..c520b9f8a3fd 100644
> --- a/Documentation/filesystems/proc.rst
> +++ b/Documentation/filesystems/proc.rst
> @@ -2360,6 +2360,7 @@ The following mount options are supported:
> hidepid= Set /proc/<pid>/ access mode.
> gid= Set the group authorized to learn processes information.
> subset= Show only the specified subset of procfs.
> + pidns= Specify a the namespace used by this procfs.
> ========= ========================================================
>
> hidepid=off or hidepid=0 means classic mode - everybody may access all
> @@ -2392,6 +2393,11 @@ information about processes information, just add identd to this group.
> subset=pid hides all top level files and directories in the procfs that
> are not related to tasks.
>
> +pidns= specifies a pid namespace (either as a string path to something like
> +`/proc/$pid/ns/pid`, or a file descriptor when using `FSCONFIG_SET_FD`) that
> +will be used by the procfs instance when translating pids. By default, procfs
> +will use the calling process's active pid namespace.
> +
> Chapter 5: Filesystem behavior
> ==============================
>
> diff --git a/fs/proc/root.c b/fs/proc/root.c
> index ed86ac710384..057c8a125c6e 100644
> --- a/fs/proc/root.c
> +++ b/fs/proc/root.c
> @@ -38,12 +38,18 @@ enum proc_param {
> Opt_gid,
> Opt_hidepid,
> Opt_subset,
> +#ifdef CONFIG_PID_NS
> + Opt_pidns,
> +#endif
> };
>
> static const struct fs_parameter_spec proc_fs_parameters[] = {
> - fsparam_u32("gid", Opt_gid),
> + fsparam_u32("gid", Opt_gid),
> fsparam_string("hidepid", Opt_hidepid),
> fsparam_string("subset", Opt_subset),
> +#ifdef CONFIG_PID_NS
> + fsparam_file_or_string("pidns", Opt_pidns),
> +#endif
> {}
> };
>
> @@ -109,11 +115,67 @@ static int proc_parse_subset_param(struct fs_context *fc, char *value)
> return 0;
> }
>
> +#ifdef CONFIG_PID_NS
> +static int proc_parse_pidns_param(struct fs_context *fc,
> + struct fs_parameter *param,
> + struct fs_parse_result *result)
> +{
> + struct proc_fs_context *ctx = fc->fs_private;
> + struct pid_namespace *target, *active = task_active_pid_ns(current);
> + struct ns_common *ns;
> + struct file *ns_filp __free(fput) = NULL;
> +
> + switch (param->type) {
> + case fs_value_is_file:
> + /* came throug fsconfig, steal the file reference */
> + ns_filp = param->file;
> + param->file = NULL;
This can be shortened to:
ns_filp = no_free_ptr(param->file);
> + break;
> + case fs_value_is_string:
> + ns_filp = filp_open(param->string, O_RDONLY, 0);
> + break;
> + default:
> + WARN_ON_ONCE(true);
> + break;
> + }
> + if (!ns_filp)
> + ns_filp = ERR_PTR(-EBADF);
> + if (IS_ERR(ns_filp)) {
> + errorfc(fc, "could not get file from pidns argument");
> + return PTR_ERR(ns_filp);
> + }
> +
> + if (!proc_ns_file(ns_filp))
> + return invalfc(fc, "pidns argument is not an nsfs file");
> + ns = get_proc_ns(file_inode(ns_filp));
> + if (ns->ops->type != CLONE_NEWPID)
> + return invalfc(fc, "pidns argument is not a pidns file");
> + target = container_of(ns, struct pid_namespace, ns);
> +
> + /*
> + * pidns= is shorthand for joining the pidns to get a fsopen fd, so the
> + * permission model should be the same as pidns_install().
> + */
> + if (!ns_capable(target->user_ns, CAP_SYS_ADMIN)) {
> + errorfc(fc, "insufficient permissions to set pidns");
> + return -EPERM;
> + }
> + if (!pidns_is_ancestor(target, active))
> + return invalfc(fc, "cannot set pidns to non-descendant pidns");
This made me think. If one rewrote this as:
if (!ns_capable(task_active_pidns(current)->user_ns, CAP_SYS_ADMIN))
if (!pidns_is_ancestor(target, active))
that would also work, right? IOW, you'd be checking whether you're
capable over your current pid namespace owning userns and if the target
pidns is an ancestor it's also implied by the first check that you're
capable over it.
The only way this would not be true is if a descendant pidns would be
owned by a userns over which you don't hold privileges and I wondered
whether that's even possible? I don't think it is but maybe you see a
way.
> +
> + put_pid_ns(ctx->pid_ns);
> + ctx->pid_ns = get_pid_ns(target);
> + put_user_ns(fc->user_ns);
> + fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
> + return 0;
> +}
> +#endif /* CONFIG_PID_NS */
> +
> static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
> {
> struct proc_fs_context *ctx = fc->fs_private;
> struct fs_parse_result result;
> - int opt;
> + int opt, err;
>
> opt = fs_parse(fc, proc_fs_parameters, param, &result);
> if (opt < 0)
> @@ -125,14 +187,24 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
> break;
>
> case Opt_hidepid:
> - if (proc_parse_hidepid_param(fc, param))
> - return -EINVAL;
> + err = proc_parse_hidepid_param(fc, param);
> + if (err)
> + return err;
> break;
>
> case Opt_subset:
> - if (proc_parse_subset_param(fc, param->string) < 0)
> - return -EINVAL;
> + err = proc_parse_subset_param(fc, param->string);
> + if (err)
> + return err;
> + break;
> +
> +#ifdef CONFIG_PID_NS
> + case Opt_pidns:
I think it would be easier if we returned EOPNOTSUPP when !CONFIG_PID_NS
instead of EINVALing this?
> + err = proc_parse_pidns_param(fc, param, &result);
> + if (err)
> + return err;
> break;
> +#endif
>
> default:
> return -EINVAL;
> @@ -154,6 +226,12 @@ static void proc_apply_options(struct proc_fs_info *fs_info,
> fs_info->hide_pid = ctx->hidepid;
> if (ctx->mask & (1 << Opt_subset))
> fs_info->pidonly = ctx->pidonly;
> +#ifdef CONFIG_PID_NS
> + if (ctx->mask & (1 << Opt_pidns)) {
> + put_pid_ns(fs_info->pid_ns);
> + fs_info->pid_ns = get_pid_ns(ctx->pid_ns);
> + }
> +#endif
> }
>
> static int proc_fill_super(struct super_block *s, struct fs_context *fc)
>
> --
> 2.50.0
>
^ permalink raw reply
* Re: [PATCH RFC v2 1/4] pidns: move is-ancestor logic to helper
From: Christian Brauner @ 2025-07-24 7:06 UTC (permalink / raw)
To: Aleksa Sarai
Cc: Alexander Viro, Jan Kara, Jonathan Corbet, Shuah Khan,
linux-kernel, linux-fsdevel, linux-api, linux-doc,
linux-kselftest
In-Reply-To: <20250723-procfs-pidns-api-v2-1-621e7edd8e40@cyphar.com>
On Wed, Jul 23, 2025 at 09:18:51AM +1000, Aleksa Sarai wrote:
> This check will be needed in later patches, and there's no point
> open-coding it each time.
>
> Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
> ---
> include/linux/pid_namespace.h | 9 +++++++++
> kernel/pid_namespace.c | 23 +++++++++++++++--------
> 2 files changed, 24 insertions(+), 8 deletions(-)
>
> diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
> index 7c67a5811199..17fdc059f8da 100644
> --- a/include/linux/pid_namespace.h
> +++ b/include/linux/pid_namespace.h
> @@ -84,6 +84,9 @@ extern void zap_pid_ns_processes(struct pid_namespace *pid_ns);
> extern int reboot_pid_ns(struct pid_namespace *pid_ns, int cmd);
> extern void put_pid_ns(struct pid_namespace *ns);
>
> +extern bool pidns_is_ancestor(struct pid_namespace *child,
> + struct pid_namespace *ancestor);
> +
> #else /* !CONFIG_PID_NS */
> #include <linux/err.h>
>
> @@ -118,6 +121,12 @@ static inline int reboot_pid_ns(struct pid_namespace *pid_ns, int cmd)
> {
> return 0;
> }
> +
> +static inline bool pidns_is_ancestor(struct pid_namespace *child,
> + struct pid_namespace *ancestor)
> +{
> + return false;
> +}
> #endif /* CONFIG_PID_NS */
>
> extern struct pid_namespace *task_active_pid_ns(struct task_struct *tsk);
> diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
> index 7098ed44e717..c2783c5fa90b 100644
> --- a/kernel/pid_namespace.c
> +++ b/kernel/pid_namespace.c
> @@ -390,11 +390,24 @@ static void pidns_put(struct ns_common *ns)
> put_pid_ns(to_pid_ns(ns));
> }
>
> +bool pidns_is_ancestor(struct pid_namespace *child,
> + struct pid_namespace *ancestor)
> +{
> + struct pid_namespace *ns;
> +
> + if (child->level < ancestor->level)
> + return false;
> + for (ns = child; ns->level > ancestor->level; ns = ns->parent)
> + ;
> + return ns == ancestor;
> +}
> +EXPORT_SYMBOL_GPL(pidns_is_ancestor);
Why do you need to export this? Afaict, this is only used from procfs
and iirc procfs cannot be a module. This could also be a static inline
completely in the header? Otherwise this looks good.
^ permalink raw reply
* Re: [PATCH RFC 0/4] procfs: make reference pidns more user-visible
From: Aleksa Sarai @ 2025-07-23 23:55 UTC (permalink / raw)
To: Andy Lutomirski
Cc: Alexander Viro, Christian Brauner, Jan Kara, Jonathan Corbet,
Shuah Khan, linux-kernel, linux-fsdevel, linux-api, linux-doc,
linux-kselftest
In-Reply-To: <20250721.150803-lavish.ninja.rigid.racism-OCjeOw80sO9@cyphar.com>
[-- Attachment #1: Type: text/plain, Size: 6534 bytes --]
On 2025-07-22, Aleksa Sarai <cyphar@cyphar.com> wrote:
> On 2025-07-21, Andy Lutomirski <luto@amacapital.net> wrote:
> > On Mon, Jul 21, 2025 at 1:44 AM Aleksa Sarai <cyphar@cyphar.com> wrote:
> > >
> > > Ever since the introduction of pid namespaces, procfs has had very
> > > implicit behaviour surrounding them (the pidns used by a procfs mount is
> > > auto-selected based on the mounting process's active pidns, and the
> > > pidns itself is basically hidden once the mount has been constructed).
> > > This has historically meant that userspace was required to do some
> > > special dances in order to configure the pidns of a procfs mount as
> > > desired. Examples include:
> > >
> > > * In order to bypass the mnt_too_revealing() check, Kubernetes creates
> > > a procfs mount from an empty pidns so that user namespaced containers
> > > can be nested (without this, the nested containers would fail to
> > > mount procfs). But this requires forking off a helper process because
> > > you cannot just one-shot this using mount(2).
> > >
> > > * Container runtimes in general need to fork into a container before
> > > configuring its mounts, which can lead to security issues in the case
> > > of shared-pidns containers (a privileged process in the pidns can
> > > interact with your container runtime process). While
> > > SUID_DUMP_DISABLE and user namespaces make this less of an issue, the
> > > strict need for this due to a minor uAPI wart is kind of unfortunate.
> > >
> > > Things would be much easier if there was a way for userspace to just
> > > specify the pidns they want. Patch 1 implements a new "pidns" argument
> > > which can be set using fsconfig(2):
> > >
> > > fsconfig(procfd, FSCONFIG_SET_FD, "pidns", NULL, nsfd);
> > > fsconfig(procfd, FSCONFIG_SET_STRING, "pidns", "/proc/self/ns/pid", 0);
> > >
> > > or classic mount(2) / mount(8):
> > >
> > > // mount -t proc -o pidns=/proc/self/ns/pid proc /tmp/proc
> > > mount("proc", "/tmp/proc", "proc", MS_..., "pidns=/proc/self/ns/pid");
> > >
> > > The initial security model I have in this RFC is to be as conservative
> > > as possible and just mirror the security model for setns(2) -- which
> > > means that you can only set pidns=... to pid namespaces that your
> > > current pid namespace is a direct ancestor of. This fulfils the
> > > requirements of container runtimes, but I suspect that this may be too
> > > strict for some usecases.
> > >
> > > The pidns argument is not displayed in mountinfo -- it's not clear to me
> > > what value it would make sense to show (maybe we could just use ns_dname
> > > to provide an identifier for the namespace, but this number would be
> > > fairly useless to userspace). I'm open to suggestions.
> > >
> > > In addition, being able to figure out what pid namespace is being used
> > > by a procfs mount is quite useful when you have an administrative
> > > process (such as a container runtime) which wants to figure out the
> > > correct way of mapping PIDs between its own namespace and the namespace
> > > for procfs (using NS_GET_{PID,TGID}_{IN,FROM}_PIDNS). There are
> > > alternative ways to do this, but they all rely on ancillary information
> > > that third-party libraries and tools do not necessarily have access to.
> > >
> > > To make this easier, add a new ioctl (PROCFS_GET_PID_NAMESPACE) which
> > > can be used to get a reference to the pidns that a procfs is using.
> > >
> > > It's not quite clear what is the correct security model for this API,
> > > but the current approach I've taken is to:
> > >
> > > * Make the ioctl only valid on the root (meaning that a process without
> > > access to the procfs root -- such as only having an fd to a procfs
> > > file or some open_tree(2)-like subset -- cannot use this API).
> > >
> > > * Require that the process requesting either has access to
> > > /proc/1/ns/pid anyway (i.e. has ptrace-read access to the pidns
> > > pid1), has CAP_SYS_ADMIN access to the pidns (i.e. has administrative
> > > access to it and can join it if they had a handle), or is in a pidns
> > > that is a direct ancestor of the target pidns (i.e. all of the pids
> > > are already visible in the procfs for the current process's pidns).
> >
> > What's the motivation for the ptrace-read option? While I don't see
> > an attack off the top of my head, it seems like creating a procfs
> > mount may give write-ish access to things in the pidns (because the
> > creator is likely to have CAP_DAC_OVERRIDE, etc) and possibly even
> > access to namespace-wide things that aren't inherently visible to
> > PID1.
>
> This latter section is about the privilege model for
> ioctl(PROCFS_GET_PID_NAMESPACE), not the pidns= mount flag. pidns=
> requires CAP_SYS_ADMIN for pidns->user_ns, in addition to the same
> restrictions as pidns_install() (must be a direct ancestor). Maybe I
> should add some headers in this cover letter for v2...
>
> For the ioctl -- if the user can ptrace-read pid1 in the pidns, they can
> open a handle to /proc/1/ns/pid which is exactly the same thing they'd
> get from PROCFS_GET_PID_NAMESPACE.
>
> > Even the ancestor check seems dicey. Imagine that uid 1000 makes an
> > unprivileged container complete with a userns. Then uid 1001 (outside
> > the container) makes its own userns and mountns but stays in the init
> > pidns and then mounts (and owns, with all filesystem-related
> > capabilities) that mount. Is this really safe?
>
> As for the ancestor check (for the ioctl), the logic I had was that
> being in an ancestor pidns means that you already can see all of the
> subprocesses in your own pidns, so it seems strange to not be able to
> get a handle to their pidns. Maybe this isn't quite right, idk.
>
> Ultimately there isn't too much you can do with a pidns fd if you don't
> have privileges to join it (the only thing I can think of is that you
> could bind-mount it, which could maybe be used to trick an
> administrative process if they trusted your mountns for some reason).
>
> > CAP_SYS_ADMIN seems about right.
>
> For pidns=, sure. For the ioctl, I think this is overkill.
My bad, I forgot to add you to Cc for v2 Andy. PTAL:
<https://lore.kernel.org/all/20250723-procfs-pidns-api-v2-0-621e7edd8e40@cyphar.com/>
--
Aleksa Sarai
Senior Software Engineer (Containers)
SUSE Linux GmbH
https://www.cyphar.com/
[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 228 bytes --]
^ permalink raw reply
* [PATCH] man/man2/mremap.2: describe multiple mapping move, shrink
From: Lorenzo Stoakes @ 2025-07-23 17:46 UTC (permalink / raw)
To: Alejandro Colomar
Cc: linux-man, Andrew Morton, Peter Xu, Alexander Viro,
Christian Brauner, Jan Kara, Liam R . Howlett, Vlastimil Babka,
Jann Horn, Pedro Falcato, Rik van Riel, linux-mm, linux-kernel,
linux-api
There is pre-existing logic that appears to be undocumented for an mremap()
shrink operation, where it turns out that the usual 'input range must span
a single mapping' requirement no longer applies.
In fact, it turns out that the input range specified by [old_address,
old_size) may span any number of mappings, as long old_address resides at
or within a mapping and [old_address, new_size) spans only a single
mapping.
Explicitly document this.
In addition, document the new behaviour introduced in Linux 6.17 whereby it
is now possible to move multiple mappings in a single operation, as long as
the operation is purely a move, that is old_size is equal to new_size and
MREMAP_FIXED is specified.
To make things clearer, also describe this 'pure move' operation, before
expanding upon it to describe the newly introduced behaviour.
This change also explains the limitations of of this method and the
possibility of partial failure.
Finally, we pluralise language where it makes sense to so the documentation
does not contradict either this new capability nor the pre-existing edge
case.
Signed-off-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
---
man/man2/mremap.2 | 93 +++++++++++++++++++++++++++++++++++++++++------
1 file changed, 82 insertions(+), 11 deletions(-)
diff --git a/man/man2/mremap.2 b/man/man2/mremap.2
index 2168ca728..c1a9e7397 100644
--- a/man/man2/mremap.2
+++ b/man/man2/mremap.2
@@ -25,18 +25,56 @@ moving it at the same time (controlled by the
argument and
the available virtual address space).
.P
+Mappings can simply be moved by specifying equal
+.I old_size
+and
+.I new_size
+and specifying
+.IR new_address ,
+see the description of
+.B MREMAP_FIXED
+below.
+Since Linux 6.17,
+while
.I old_address
-is the old address of the virtual memory block that you
-want to expand (or shrink).
+must reside within a mapping,
+.I old_size
+may span multiple mappings
+which do not have to be
+adjacent to one another.
+.P
+Equally, if the operation performs a shrink,
+that is if
+.I old_size
+is greater than
+.IR new_size ,
+then
+.I old_size
+may also span multiple mappings
+which do not have to be
+adjacent to one another.
+However in this case,
+.I new_size
+must span only a single mapping.
+.P
+If the operation is neither a simple move
+nor a shrink,
+then
+.I old_size
+must span only a single mapping.
+.P
+.I old_address
+is the old address of the first virtual memory block that you
+want to expand, shrink, and/or move.
Note that
.I old_address
has to be page aligned.
.I old_size
-is the old size of the
-virtual memory block.
+is the size of the range containing
+virtual memory blocks to be manipulated.
.I new_size
is the requested size of the
-virtual memory block after the resize.
+virtual memory blocks after the resize.
An optional fifth argument,
.IR new_address ,
may be provided; see the description of
@@ -105,13 +143,43 @@ If
is specified, then
.B MREMAP_MAYMOVE
must also be specified.
+.IP
+Since Linux 6.17,
+if
+.I old_size
+is equal to
+.I new_size
+and
+.B MREMAP_FIXED
+is specified, then
+.I old_size
+may span beyond the mapping in which
+.I old_address
+resides.
+In this case,
+gaps between mappings in the original range
+are maintained in the new range.
+The whole operation is performed atomically
+unless an error arises,
+in which case the operation may be partially
+completed,
+that is,
+some mappings may be moved and others not.
+.IP
+
+Moving multiple mappings is not permitted if
+any of those mappings have either
+been registered with
+.BR userfaultfd (2) ,
+or map drivers that
+specify their own custom address mapping logic.
.TP
.BR MREMAP_DONTUNMAP " (since Linux 5.7)"
.\" commit e346b3813067d4b17383f975f197a9aa28a3b077
This flag, which must be used in conjunction with
.BR MREMAP_MAYMOVE ,
-remaps a mapping to a new address but does not unmap the mapping at
-.IR old_address .
+remaps mappings to a new address but does not unmap them
+from their original address.
.IP
The
.B MREMAP_DONTUNMAP
@@ -149,13 +217,13 @@ mapped.
See NOTES for some possible applications of
.BR MREMAP_DONTUNMAP .
.P
-If the memory segment specified by
+If the memory segments specified by
.I old_address
and
.I old_size
-is locked (using
+are locked (using
.BR mlock (2)
-or similar), then this lock is maintained when the segment is
+or similar), then this lock is maintained when the segments are
resized and/or relocated.
As a consequence, the amount of memory locked by the process may change.
.SH RETURN VALUE
@@ -188,7 +256,10 @@ virtual memory address for this process.
You can also get
.B EFAULT
even if there exist mappings that cover the
-whole address space requested, but those mappings are of different types.
+whole address space requested, but those mappings are of different types,
+and the
+.BR mremap ()
+operation being performed does not support this.
.TP
.B EINVAL
An invalid argument was given.
--
2.50.1
^ permalink raw reply related
* [PATCH v2 32/32] libluo: add tests
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
Add a test suite for libluo itself, and for the kernel LUO interface.
The below tests are added:
1. init - Tests the initialization and cleanup functions of libluo.
2. state - Tests the luo_get_state() API, which in turn tests the
LIVEUPDATE_IOCTL_GET_STATE ioctl
3. preserve - Creates a memfd, preserves it, puts LUO in prepared state,
cancels liveupdate, and makes sure memfd is functional.
4. prepared - Puts a memfd in LUO enters prepared state. Then it
makes sure the memfd stays functional but remains in restricted mode. It
makes sure the memfd can't grow or shrink, but can be read from or
written to.
5. transitions - Tests transitions from normal to prepared to cancel
state work.
6. error - Tests error handling of the library on invalid inputs.
7. kexec - Tests the main functionality of LUO -- preserving a FD over
kexec. It creates a memfd with random data, saves the data to a file on
disk, and then preserves the FD and goes into prepared state. Now the
test runner must perform a kexec. Once rebooted, running the test again
resumes the test. It fetches the memfd back, nd compares its content
with the saved data on disk.
A specific test can be selected or excluded uring the -t or -e arguments.
Sample run:
$ ./test
LibLUO Test Suite
=================
Testing initialization and cleanup... PASSED
Testing get_state... PASSED (current state: normal)
Testing state transitions... PASSED
Testing fd_preserve with freeze and cancel... PASSED
Testing operations on prepared memfd... PASSED
Testing error handling... PASSED
Testing fd preserve for kexec... READY FOR KEXEC (token: 3)
Run kexec now and then run this test again to complete.
All requested tests completed.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
tools/lib/luo/Makefile | 4 +
tools/lib/luo/tests/.gitignore | 1 +
tools/lib/luo/tests/Makefile | 18 +
tools/lib/luo/tests/test.c | 848 +++++++++++++++++++++++++++++++++
4 files changed, 871 insertions(+)
create mode 100644 tools/lib/luo/tests/.gitignore
create mode 100644 tools/lib/luo/tests/Makefile
create mode 100644 tools/lib/luo/tests/test.c
diff --git a/tools/lib/luo/Makefile b/tools/lib/luo/Makefile
index e8f6bd3b9e85..ef4c489efcc5 100644
--- a/tools/lib/luo/Makefile
+++ b/tools/lib/luo/Makefile
@@ -29,9 +29,13 @@ $(SHARED_LIB): $(OBJS)
cli: $(STATIC_LIB)
$(MAKE) -C cli
+tests: $(STATIC_LIB)
+ $(MAKE) -C tests
+
clean:
rm -f $(OBJS) $(STATIC_LIB) $(SHARED_LIB)
$(MAKE) -C cli clean
+ $(MAKE) -C tests clean
install: all
install -d $(DESTDIR)/usr/local/lib
diff --git a/tools/lib/luo/tests/.gitignore b/tools/lib/luo/tests/.gitignore
new file mode 100644
index 000000000000..ee4c92682341
--- /dev/null
+++ b/tools/lib/luo/tests/.gitignore
@@ -0,0 +1 @@
+/test
diff --git a/tools/lib/luo/tests/Makefile b/tools/lib/luo/tests/Makefile
new file mode 100644
index 000000000000..7f4689722ff6
--- /dev/null
+++ b/tools/lib/luo/tests/Makefile
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: LGPL-3.0-or-later
+TESTS = test
+INCLUDE_DIR = ../include
+HEADERS = $(wildcard $(INCLUDE_DIR)/*.h)
+
+CC = gcc
+CFLAGS = -Wall -Wextra -O2 -g -I$(INCLUDE_DIR)
+LDFLAGS = -L.. -l:libluo.a
+
+.PHONY: all clean
+
+all: $(TESTS)
+
+test: test.c ../libluo.a $(HEADERS)
+ $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
+
+clean:
+ rm -f $(TESTS)
diff --git a/tools/lib/luo/tests/test.c b/tools/lib/luo/tests/test.c
new file mode 100644
index 000000000000..7963ae8ebadf
--- /dev/null
+++ b/tools/lib/luo/tests/test.c
@@ -0,0 +1,848 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+#define _GNU_SOURCE
+/**
+ * @file test.c
+ * @brief Test program for the LibLUO library
+ *
+ * This program tests the basic functionality of the LibLUO library.
+ *
+ * Copyright (C) 2025 Amazon.com Inc. or its affiliates.
+ * Author: Pratyush Yadav <ptyadav@amazon.de>
+ */
+
+#include <libluo.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/mman.h>
+#include <getopt.h>
+
+/* Path to store token for kexec test */
+#define TOKEN_FILE "libluo_test_token"
+#define TEST_DATA_FILE "libluo_test_data"
+#define MEMFD_NAME "libluo_test_memfd"
+
+/* Size of the random data buffer (1 MiB) */
+#define RANDOM_BUFFER_SIZE (1 << 20)
+static char random_buffer[RANDOM_BUFFER_SIZE];
+
+/* Test IDs */
+#define TEST_INIT_CLEANUP (1 << 0)
+#define TEST_GET_STATE (1 << 1)
+#define TEST_FD_PRESERVE (1 << 2)
+#define TEST_ERROR_HANDLING (1 << 3)
+#define TEST_FD_KEXEC (1 << 4)
+#define TEST_FD_PREPARED (1 << 5)
+#define TEST_STATE_TRANSITIONS (1 << 6)
+#define TEST_ALL (TEST_INIT_CLEANUP | TEST_GET_STATE | \
+ TEST_FD_PRESERVE | TEST_ERROR_HANDLING | \
+ TEST_FD_KEXEC | TEST_FD_PREPARED | \
+ TEST_STATE_TRANSITIONS)
+
+/*
+ * luo_fd_preserve() needs a unique token. Generate a monotonically increasing
+ * token.
+ */
+static uint64_t next_token()
+{
+ static uint64_t token = 0;
+
+ return token++;
+}
+
+/* Read exactly specified size from fd. Any less results in error. */
+static int read_size(int fd, char *buffer, size_t size)
+{
+ size_t remain = size;
+ ssize_t bytes_read;
+
+ while (remain) {
+ bytes_read = read(fd, buffer, remain);
+ if (bytes_read == 0)
+ return -ENODATA;
+ if (bytes_read < 0)
+ return -errno;
+
+ remain -= bytes_read;
+ }
+
+ return 0;
+}
+
+/* Write exactly specified size from fd. Any less results in error. */
+static int write_size(int fd, const char *buffer, size_t size)
+{
+ size_t remain = size;
+ ssize_t written;
+
+ while (remain) {
+ written = write(fd, buffer, remain);
+ if (written == 0)
+ return -EIO;
+ if (written < 0)
+ return -errno;
+
+ remain -= written;
+ }
+
+ return 0;
+}
+
+static int generate_random_data(char *buffer, size_t size)
+{
+ int fd, ret;
+
+ fd = open("/dev/urandom", O_RDONLY);
+ if (fd < 0)
+ return -errno;
+
+ ret = read_size(fd, buffer, size);
+ close(fd);
+ return ret;
+}
+
+static int save_test_data(const char *buffer, size_t size)
+{
+ int fd, ret;
+
+ fd = open(TEST_DATA_FILE, O_RDWR);
+ if (fd < 0)
+ return -errno;
+
+ ret = write_size(fd, buffer, size);
+ close(fd);
+ return ret;
+}
+
+static int load_test_data(char *buffer, size_t size)
+{
+ int fd, ret;
+
+ fd = open(TEST_DATA_FILE, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+
+ ret = read_size(fd, buffer, size);
+ close(fd);
+ return ret;
+}
+
+/* Create and initialize a memfd with random data. */
+static int create_test_fd(const char *memfd_name, char *buffer, size_t size)
+{
+ int fd;
+ int ret;
+
+ fd = memfd_create(memfd_name, 0);
+ if (fd < 0)
+ return -errno;
+
+ ret = generate_random_data(buffer, size);
+ if (ret < 0) {
+ close(fd);
+ return ret;
+ }
+
+ if (write_size(fd, buffer, size) < 0) {
+ close(fd);
+ return -errno;
+ }
+
+ /* Reset file position to beginning */
+ if (lseek(fd, 0, SEEK_SET) < 0) {
+ close(fd);
+ return -errno;
+ }
+
+ return fd;
+}
+
+/*
+ * Make sure fd contains expected data up to size. Returns 0 on success, 1 on
+ * data mismatch, -errno on error.
+ */
+static int verify_fd_content(int fd, const char *expected_data, size_t size)
+{
+ char buffer[size];
+ int ret;
+
+ /* Reset file position to beginning */
+ if (lseek(fd, 0, SEEK_SET) < 0)
+ return -errno;
+
+ ret = read_size(fd, buffer, size);
+ if (ret < 0)
+ return ret;
+
+ if (memcmp(buffer, expected_data, size) != 0)
+ return 1;
+
+ return 0;
+}
+
+/* Save token to file for kexec test. */
+static int save_token(uint64_t token)
+{
+ FILE *file = fopen(TOKEN_FILE, "w");
+
+ if (!file)
+ return -errno;
+
+ if (fprintf(file, "%lu", token) < 0) {
+ fclose(file);
+ return -errno;
+ }
+
+ fclose(file);
+ return 0;
+}
+
+/* Load token from file for kexec test. */
+static int load_token(uint64_t *token)
+{
+ FILE *file = fopen(TOKEN_FILE, "r");
+
+ if (!file)
+ return -errno;
+
+ if (fscanf(file, "%lu", token) != 1) {
+ fclose(file);
+ return -EINVAL;
+ }
+
+ fclose(file);
+ return 0;
+}
+
+/* Test initialization and cleanup */
+static void test_init_cleanup(void)
+{
+ int ret;
+
+ printf("Testing initialization and cleanup... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ luo_cleanup();
+ printf("PASSED\n");
+}
+
+/* Test getting LUO state */
+static void test_get_state(void)
+{
+ int ret;
+ enum liveupdate_state state;
+
+ printf("Testing get_state... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ printf("FAILED (get_state: %s)\n", strerror(-ret));
+ luo_cleanup();
+ return;
+ }
+
+ printf("PASSED (current state: %s)\n", luo_state_to_string(state));
+ luo_cleanup();
+}
+
+/* Test preserving and unpreserving a file descriptor with prepare and cancel */
+static void test_fd_preserve_unpreserve(void)
+{
+ uint64_t token = next_token();
+ int ret, fd = -1;
+
+ printf("Testing fd_preserve with freeze and cancel... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ fd = create_test_fd(MEMFD_NAME, random_buffer, sizeof(random_buffer));
+ if (fd < 0) {
+ ret = fd;
+ printf("FAILED (create_test_fd: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ ret = luo_fd_preserve(fd, token);
+ if (ret < 0) {
+ printf("FAILED (preserve: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ ret = luo_prepare();
+ if (ret < 0) {
+ printf("FAILED (prepare: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ ret = luo_cancel();
+ if (ret < 0) {
+ printf("FAILED (cancel: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ ret = luo_fd_unpreserve(token);
+ if (ret < 0) {
+ printf("FAILED (unpreserve: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ ret = verify_fd_content(fd, random_buffer, sizeof(random_buffer));
+ if (ret < 0) {
+ printf("FAILED (verify_fd_content: %s)\n",
+ ret == 1 ? "data mismatch" : strerror(-ret));
+ goto out_close_fd;
+ }
+
+ printf("PASSED\n");
+ goto out_close_fd;
+
+out_unpreserve:
+ luo_fd_unpreserve(token);
+out_close_fd:
+ close(fd);
+out_cleanup:
+ luo_cleanup();
+}
+
+/* Test error handling with invalid inputs. */
+static void test_error_handling(void)
+{
+ int ret;
+
+ printf("Testing error handling... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ /* Test with invalid file descriptor */
+ ret = luo_fd_preserve(-1, next_token());
+ if (ret != -EINVAL) {
+ printf("FAILED (expected EINVAL for invalid fd, got %d)\n", ret);
+ luo_cleanup();
+ return;
+ }
+
+ /* Test with NULL state pointer */
+ ret = luo_get_state(NULL);
+ if (ret != -EINVAL) {
+ printf("FAILED (expected EINVAL for NULL state, got %d)\n", ret);
+ luo_cleanup();
+ return;
+ }
+
+ luo_cleanup();
+ printf("PASSED\n");
+}
+
+/* Test preserving a file descriptor for kexec reboot */
+static void test_fd_preserve_for_kexec(void)
+{
+ enum liveupdate_state state;
+ int fd = -1, ret;
+ uint64_t token;
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ /* Check if we're in post-kexec state */
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ printf("FAILED (get_state: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ if (state == LIVEUPDATE_STATE_UPDATED) {
+ /* Post-kexec: restore the file descriptor */
+ printf("Testing memfd restore after kexec... ");
+
+ ret = load_token(&token);
+ if (ret < 0) {
+ printf("FAILED (load_token: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ ret = load_test_data(random_buffer, RANDOM_BUFFER_SIZE);
+ if (ret < 0) {
+ printf("FAILED (load_test_data: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ ret = luo_fd_restore(token, &fd);
+ if (ret < 0) {
+ printf("FAILED (restore: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ /* Verify the file descriptor content with stored data. */
+ ret = verify_fd_content(fd, random_buffer, RANDOM_BUFFER_SIZE);
+ if (ret) {
+ printf("FAILED (verify_fd_content: %s)\n",
+ ret == 1 ? "data mismatch" : strerror(-ret));
+ goto out_close_fd;
+ }
+
+ ret = luo_finish();
+ if (ret < 0) {
+ printf("FAILED (finish: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ printf("PASSED\n");
+ goto out_close_fd;
+ } else {
+ /* Pre-kexec: preserve the file descriptor */
+ printf("Testing fd preserve for kexec... ");
+
+ fd = create_test_fd(MEMFD_NAME, random_buffer, RANDOM_BUFFER_SIZE);
+ if (fd < 0) {
+ ret = fd;
+ printf("FAILED (create_test_fd: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ /* Save random data to file for post-kexec verification */
+ ret = save_test_data(random_buffer, RANDOM_BUFFER_SIZE);
+ if (ret < 0) {
+ printf("FAILED (save_test_data: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ token = next_token();
+ ret = luo_fd_preserve(fd, token);
+ if (ret < 0) {
+ printf("FAILED (preserve: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ /* Save token to file for post-kexec restoration */
+ ret = save_token(token);
+ if (ret < 0) {
+ printf("FAILED (save_token: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ ret = luo_prepare();
+ if (ret < 0) {
+ printf("FAILED (prepare: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ printf("READY FOR KEXEC (token: %lu)\n", token);
+ printf("Run kexec now and then run this test again to complete.\n");
+
+ /* Note: At this point, the system should perform kexec reboot.
+ * The test will continue in the new kernel with the
+ * LIVEUPDATE_STATE_UPDATED state.
+ *
+ * Since the FD is now preserved, we can close it.
+ */
+ goto out_close_fd;
+ }
+
+out_unpreserve:
+ luo_fd_unpreserve(token);
+out_close_fd:
+ close(fd);
+out_cleanup:
+ luo_cleanup();
+}
+
+/*
+ * Test that prepared memfd can't grow or shrink, but reads and writes still
+ * work.
+ */
+static void test_fd_prepared_operations(void)
+{
+ char write_buffer[128] = {'A'};
+ size_t initial_size, file_size;
+ int ret, fd = -1;
+ uint64_t token;
+
+ printf("Testing operations on prepared memfd... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init: %s)\n", strerror(-ret));
+ return;
+ }
+
+ /* Create and initialize test file descriptor */
+ fd = create_test_fd(MEMFD_NAME, random_buffer, sizeof(random_buffer));
+ if (fd < 0) {
+ ret = fd;
+ printf("FAILED (create_test_fd: %s)\n", strerror(-ret));
+ goto out_cleanup;
+ }
+
+ /* Get initial file size */
+ ret = lseek(fd, 0, SEEK_END);
+ if (ret < 0) {
+ printf("FAILED (lseek to end: %s)\n", strerror(errno));
+ goto out_close_fd;
+ }
+ initial_size = (size_t)ret;
+
+ token = next_token();
+ ret = luo_fd_preserve(fd, token);
+ if (ret < 0) {
+ printf("FAILED (preserve: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ ret = luo_prepare();
+ if (ret < 0) {
+ printf("FAILED (prepare: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ /* Test 1: Write to the prepared file descriptor (within existing size) */
+ if (lseek(fd, 0, SEEK_SET) < 0) {
+ printf("FAILED (lseek before write: %s)\n", strerror(errno));
+ goto out_cancel;
+ }
+
+ /* Write buffer is smaller than total file size. */
+ ret = write_size(fd, write_buffer, sizeof(write_buffer));
+ if (ret < 0) {
+ printf("FAILED (write to prepared fd: %s)\n", strerror(errno));
+ goto out_cancel;
+ }
+
+ ret = verify_fd_content(fd, write_buffer, sizeof(write_buffer));
+ if (ret) {
+ printf("FAILED (verify_fd_content after write: %s)\n",
+ ret == 1 ? "data mismatch" : strerror(-ret));
+ goto out_cancel;
+ }
+
+ /* Test 2: Try to grow the file using write(). */
+
+ /* First, seek to one byte behind initial size. */
+ ret = lseek(fd, initial_size - 1, SEEK_SET);
+ if (ret < 0) {
+ printf("FAILED: (lseek after write verification: %s)\n",
+ strerror(errno));
+ }
+
+ /*
+ * Then, write some data that should increase the file size. This should
+ * fail.
+ */
+ ret = write_size(fd, write_buffer, sizeof(write_buffer));
+ if (ret == 0) {
+ printf("FAILED: (write beyond initial size succeeded)\n");
+ goto out_cancel;
+ }
+
+ ret = lseek(fd, 0, SEEK_END);
+ if (ret < 0) {
+ printf("FAILED (lseek after larger write: %s)\n", strerror(errno));
+ goto out_cancel;
+ }
+ file_size = (size_t)ret;
+
+ if (file_size != initial_size) {
+ printf("FAILED (file grew beyond initial size: %zu != %zu)\n",
+ (size_t)file_size, initial_size);
+ goto out_cancel;
+ }
+
+ /* Test 3: Try to shrink the file using truncate */
+ ret = ftruncate(fd, initial_size / 2);
+ if (ret == 0) {
+ printf("FAILED (file was truncated)\n");
+ goto out_cancel;
+ }
+
+ ret = lseek(fd, 0, SEEK_END);
+ if (ret < 0) {
+ printf("FAILED (lseek after shrink attempt: %s)\n", strerror(errno));
+ goto out_cancel;
+ }
+ file_size = (size_t)ret;
+
+ if (file_size != initial_size) {
+ printf("FAILED (file shrunk from initial size: %zu != %zu)\n",
+ (size_t)file_size, initial_size);
+ goto out_cancel;
+ }
+
+ ret = luo_cancel();
+ if (ret < 0) {
+ printf("FAILED (cancel: %s)\n", strerror(-ret));
+ goto out_unpreserve;
+ }
+
+ ret = luo_fd_unpreserve(token);
+ if (ret < 0) {
+ printf("FAILED (unpreserve: %s)\n", strerror(-ret));
+ goto out_close_fd;
+ }
+
+ printf("PASSED\n");
+ goto out_close_fd;
+
+out_cancel:
+ luo_cancel();
+out_unpreserve:
+ luo_fd_unpreserve(token);
+out_close_fd:
+ close(fd);
+out_cleanup:
+ luo_cleanup();
+}
+
+static int test_prepare_cancel_sequence(const char *sequence_name)
+{
+ int ret;
+ enum liveupdate_state state;
+
+ /* Initial state should be NORMAL */
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ printf("FAILED (%s get initial state failed: %s)\n",
+ sequence_name, strerror(-ret));
+ return ret;
+ }
+
+ if (state != LIVEUPDATE_STATE_NORMAL) {
+ printf("FAILED (%s unexpected initial state: %s)\n",
+ sequence_name, luo_state_to_string(state));
+ return -EINVAL;
+ }
+
+ /* Test NORMAL -> PREPARED transition */
+ ret = luo_prepare();
+ if (ret < 0) {
+ printf("FAILED (%s prepare failed: %s)\n",
+ sequence_name, strerror(-ret));
+ return ret;
+ }
+
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ printf("FAILED (%s get state after prepare failed: %s)\n",
+ sequence_name, strerror(-ret));
+ goto out_cancel;
+ }
+
+ if (state != LIVEUPDATE_STATE_PREPARED) {
+ printf("FAILED (%s expected PREPARED state, got %s)\n",
+ sequence_name, luo_state_to_string(state));
+ ret = -EINVAL;
+ goto out_cancel;
+ }
+
+ /* Test PREPARED -> NORMAL transition via cancel */
+ ret = luo_cancel();
+ if (ret < 0) {
+ printf("FAILED (%s cancel failed: %s)\n",
+ sequence_name, strerror(-ret));
+ return ret;
+ }
+
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ printf("FAILED (%s get state after cancel failed: %s)\n",
+ sequence_name, strerror(-ret));
+ return ret;
+ }
+
+ if (state != LIVEUPDATE_STATE_NORMAL) {
+ printf("FAILED (%s expected NORMAL state after cancel, got %s)\n",
+ sequence_name, luo_state_to_string(state));
+ return -EINVAL;
+ }
+
+ return 0;
+
+out_cancel:
+ luo_cancel();
+ return ret;
+}
+
+/* Test all state transitions */
+static void test_state_transitions(void)
+{
+ int ret;
+
+ printf("Testing state transitions... ");
+
+ ret = luo_init();
+ if (ret < 0) {
+ printf("FAILED (init failed: %s)\n", strerror(-ret));
+ return;
+ }
+
+ /* Test first prepare -> cancel sequence */
+ ret = test_prepare_cancel_sequence("first");
+ if (ret < 0)
+ goto out;
+
+ /*
+ * Test second prepare -> freeze -> cancel sequence in case the
+ * previous cancellation left some side effects.
+ */
+ ret = test_prepare_cancel_sequence("second");
+ if (ret < 0)
+ goto out;
+
+ printf("PASSED\n");
+
+out:
+ luo_cleanup();
+}
+
+/* Test name to flag mapping */
+struct test {
+ const char *name;
+ void (*fn)(void);
+ unsigned int flag;
+};
+
+/* Array of test names and their corresponding flags */
+static struct test tests[] = {
+ {"init", test_init_cleanup, TEST_INIT_CLEANUP},
+ {"state", test_get_state, TEST_GET_STATE},
+ {"transitions", test_state_transitions, TEST_STATE_TRANSITIONS},
+ {"preserve", test_fd_preserve_unpreserve, TEST_FD_PRESERVE},
+ {"prepared", test_fd_prepared_operations, TEST_FD_PREPARED},
+ {"error", test_error_handling, TEST_ERROR_HANDLING},
+ {"kexec", test_fd_preserve_for_kexec, TEST_FD_KEXEC},
+ {NULL, NULL, 0}
+};
+
+static int parse_test_names(char *arg, unsigned int *flags)
+{
+ char *name;
+ struct test *test;
+
+ *flags = 0;
+ name = strtok(arg, ",");
+
+ while (name != NULL) {
+ test = tests;
+ while (test->name) {
+ if (strcmp(name, test->name) == 0) {
+ *flags |= test->flag;
+ break;
+ }
+ test++;
+ }
+
+ /* Check if we found a match */
+ if (!test->name) {
+ printf("Unknown test: %s\n", name);
+ return 1;
+ }
+
+ name = strtok(NULL, ",");
+ }
+
+ return 0;
+}
+
+static void usage(const char *program_name)
+{
+ printf("Usage: %s [options]\n", program_name);
+ printf("Options:\n");
+ printf(" -h, --help Show this help message\n");
+ printf(" -t, --test=TEST_ID Run specific test(s)\n");
+ printf(" -e, --exclude=TEST_ID Exclude specific test(s)\n");
+ printf("\n");
+ printf("Test IDs:\n");
+ printf(" init - Test initialization and cleanup\n");
+ printf(" state - Test getting LUO state\n");
+ printf(" preserve - Test memfd preserve/unpreserve with freeze/cancel\n");
+ printf(" prepared - Test memfd functions can read/write but not grow after prepare\n");
+ printf(" transitions - Test all state transitions (NORMAL->PREPARED->FROZEN->NORMAL)\n");
+ printf(" error - Test error handling\n");
+ printf(" kexec - Test memfd preserve for kexec\n");
+ printf("\n");
+ printf("Multiple tests can be specified with comma separation.\n");
+ printf("Example: %s --test=init,state --exclude=kexec\n", program_name);
+ printf("By default, all tests are run.\n");
+}
+
+int main(int argc, char *argv[])
+{
+ unsigned int tests_to_run = TEST_ALL;
+ unsigned int tests_to_exclude = 0;
+ struct option long_options[] = {
+ {"help", no_argument, 0, 'h'},
+ {"test", required_argument, 0, 't'},
+ {"exclude", required_argument, 0, 'e'},
+ {0, 0, 0, 0}
+ };
+ struct test *test;
+ int opt;
+
+ printf("LibLUO Test Suite\n");
+ printf("=================\n\n");
+
+ if (!luo_is_available()) {
+ printf("LUO is not available on this system. Skipping tests.\n");
+ return 0;
+ }
+
+ while ((opt = getopt_long(argc, argv, "ht:e:", long_options, NULL)) != -1) {
+ switch (opt) {
+ case 'h':
+ usage(argv[0]);
+ return 0;
+ case 't':
+ if (parse_test_names(optarg, &tests_to_run))
+ return 1;
+ break;
+ case 'e':
+ if (parse_test_names(optarg, &tests_to_exclude))
+ return 1;
+ break;
+ default:
+ printf("Try '%s --help' for more information.\n", argv[0]);
+ return 1;
+ }
+ }
+
+ /* Apply exclusions to the tests to run */
+ tests_to_run &= ~tests_to_exclude;
+ if (!tests_to_run) {
+ printf("ERROR: all tests excluded\n");
+ return 1;
+ }
+
+ /* Run selected tests */
+ test = tests;
+ while (test->name) {
+ if (tests_to_run & test->flag)
+ test->fn();
+ test++;
+ }
+
+ printf("\nAll requested tests completed.\n");
+ return 0;
+}
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 31/32] libluo: introduce luoctl
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
luoctl is a utility to interact with the LUO state machine. It currently
supports viewing and change the current state of LUO. This can be used
by scripts, tools, or developers to control LUO state during the live
update process.
Example usage:
$ luoctl state
normal
$ luoctl prepare
$ luoctl state
prepared
$ luoctl cancel
$ luoctl state
normal
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
tools/lib/luo/Makefile | 6 +-
tools/lib/luo/cli/.gitignore | 1 +
tools/lib/luo/cli/Makefile | 18 ++++
tools/lib/luo/cli/luoctl.c | 178 +++++++++++++++++++++++++++++++++++
4 files changed, 202 insertions(+), 1 deletion(-)
create mode 100644 tools/lib/luo/cli/.gitignore
create mode 100644 tools/lib/luo/cli/Makefile
create mode 100644 tools/lib/luo/cli/luoctl.c
diff --git a/tools/lib/luo/Makefile b/tools/lib/luo/Makefile
index e851c37d3d0a..e8f6bd3b9e85 100644
--- a/tools/lib/luo/Makefile
+++ b/tools/lib/luo/Makefile
@@ -13,7 +13,7 @@ LIB_NAME = libluo
STATIC_LIB = $(LIB_NAME).a
SHARED_LIB = $(LIB_NAME).so
-.PHONY: all clean install
+.PHONY: all clean install cli
all: $(STATIC_LIB) $(SHARED_LIB)
@@ -26,8 +26,12 @@ $(SHARED_LIB): $(OBJS)
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
+cli: $(STATIC_LIB)
+ $(MAKE) -C cli
+
clean:
rm -f $(OBJS) $(STATIC_LIB) $(SHARED_LIB)
+ $(MAKE) -C cli clean
install: all
install -d $(DESTDIR)/usr/local/lib
diff --git a/tools/lib/luo/cli/.gitignore b/tools/lib/luo/cli/.gitignore
new file mode 100644
index 000000000000..3a5e2d287f60
--- /dev/null
+++ b/tools/lib/luo/cli/.gitignore
@@ -0,0 +1 @@
+/luoctl
diff --git a/tools/lib/luo/cli/Makefile b/tools/lib/luo/cli/Makefile
new file mode 100644
index 000000000000..6c0cbf92a420
--- /dev/null
+++ b/tools/lib/luo/cli/Makefile
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: LGPL-3.0-or-later
+LUOCTL = luoctl
+INCLUDE_DIR = ../include
+HEADERS = $(wildcard $(INCLUDE_DIR)/*.h)
+
+CC = gcc
+CFLAGS = -Wall -Wextra -O2 -g -I$(INCLUDE_DIR)
+LDFLAGS = -L.. -l:libluo.a
+
+.PHONY: all clean
+
+all: $(LUOCTL)
+
+luoctl: luoctl.c ../libluo.a $(HEADERS)
+ $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
+
+clean:
+ rm -f $(LUOCTL)
diff --git a/tools/lib/luo/cli/luoctl.c b/tools/lib/luo/cli/luoctl.c
new file mode 100644
index 000000000000..39ba0bdd44f0
--- /dev/null
+++ b/tools/lib/luo/cli/luoctl.c
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+/**
+ * @file luoctl.c
+ * @brief Simple utility to interact with LUO
+ *
+ * This utility allows viewing and controlling LUO state.
+ *
+ * Copyright (C) 2025 Amazon.com Inc. or its affiliates.
+ * Author: Pratyush Yadav <ptyadav@amazon.de>
+ */
+
+#include <libluo.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <getopt.h>
+
+#define fatal(fmt, ...) \
+ do { \
+ fprintf(stderr, "Error: " fmt, ##__VA_ARGS__); \
+ exit(1); \
+ } while (0)
+
+struct command {
+ char *name;
+ int (*handler)(void);
+};
+
+static void usage(const char *prog_name)
+{
+ printf("Usage: %s [command]\n\n", prog_name);
+ printf("Commands:\n");
+ printf(" state - Show current LUO state\n");
+ printf(" prepare - Prepare for live update\n");
+ printf(" cancel - Cancel live update preparation\n");
+ printf(" finish - Signal completion of restoration\n");
+}
+
+static enum liveupdate_state get_state(void)
+{
+ enum liveupdate_state state;
+ int ret;
+
+ ret = luo_get_state(&state);
+ if (ret)
+ fatal("failed to get LUO state: %s\n", strerror(-ret));
+
+ return state;
+}
+
+static int show_state(void)
+{
+ enum liveupdate_state state;
+
+ state = get_state();
+ printf("%s\n", luo_state_to_string(state));
+ return 0;
+}
+
+static int do_prepare(void)
+{
+ enum liveupdate_state state;
+ int ret;
+
+ state = get_state();
+ if (state != LIVEUPDATE_STATE_NORMAL)
+ fatal("can only switch to prepared state from normal state. Current state: %s\n",
+ luo_state_to_string(state));
+
+ ret = luo_prepare();
+ if (ret)
+ fatal("failed to prepare for live update: %s\n", strerror(-ret));
+
+ return 0;
+}
+
+static int do_cancel(void)
+{
+ enum liveupdate_state state;
+ int ret;
+
+ state = get_state();
+ if (state != LIVEUPDATE_STATE_PREPARED)
+ fatal("can only cancel from normal state. Current state: %s\n",
+ luo_state_to_string(state));
+
+ ret = luo_cancel();
+ if (ret)
+ fatal("failed to cancel live update: %s\n", strerror(-ret));
+
+ return 0;
+}
+
+static int do_finish(void)
+{
+ enum liveupdate_state state;
+ int ret;
+
+ state = get_state();
+ if (state != LIVEUPDATE_STATE_UPDATED)
+ fatal("can only finish from updated state. Current state: %s\n",
+ luo_state_to_string(state));
+
+ ret = luo_finish();
+ if (ret)
+ fatal("failed to finish live update: %s\n", strerror(-ret));
+
+ return 0;
+}
+
+static struct command commands[] = {
+ {"state", show_state},
+ {"prepare", do_prepare},
+ {"cancel", do_cancel},
+ {"finish", do_finish},
+ {NULL, NULL},
+};
+
+int main(int argc, char *argv[])
+{
+ struct option long_options[] = {
+ {"help", no_argument, 0, 'h'},
+ {0, 0, 0, 0}
+ };
+ struct command *command;
+ int ret = -EINVAL, opt;
+ char *cmd;
+
+ if (!luo_is_available()) {
+ fprintf(stderr, "LUO is not available on this system\n");
+ return 1;
+ }
+
+ while ((opt = getopt_long(argc, argv, "ht:e:", long_options, NULL)) != -1) {
+ switch (opt) {
+ case 'h':
+ usage(argv[0]);
+ return 0;
+ default:
+ fprintf(stderr, "Try '%s --help' for more information.\n", argv[0]);
+ return 1;
+ }
+ }
+
+ if (argc - optind != 1) {
+ usage(argv[0]);
+ return 1;
+ }
+
+ cmd = argv[optind];
+
+ ret = luo_init();
+ if (ret < 0) {
+ fprintf(stderr, "Failed to initialize LibLUO: %s\n", strerror(-ret));
+ return 1;
+ }
+
+ command = &commands[0];
+ while (command->name) {
+ if (!strcmp(cmd, command->name)) {
+ ret = command->handler();
+ break;
+ }
+ command++;
+ }
+
+ if (!command->name) {
+ fprintf(stderr, "Unknown command %s. Try '%s --help' for more information\n",
+ cmd, argv[0]);
+ ret = -EINVAL;
+ }
+
+ luo_cleanup();
+ return (ret < 0) ? 1 : 0;
+}
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 30/32] tools: introduce libluo
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
LibLUO is a C library for interacting with the Live Update
Orchestrator (LUO) subsystem. It provides a set of APIs for applications
to interact with LUO, avoiding the need to directly calling the LUO
ioctls. It provides APIs for controlling the LUO state and preserve and
restore file descriptors across live updates.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
MAINTAINERS | 1 +
tools/lib/luo/LICENSE | 165 ++++++++++++++++++
tools/lib/luo/Makefile | 37 ++++
tools/lib/luo/README.md | 166 ++++++++++++++++++
tools/lib/luo/include/libluo.h | 128 ++++++++++++++
tools/lib/luo/include/liveupdate.h | 265 +++++++++++++++++++++++++++++
tools/lib/luo/libluo.c | 203 ++++++++++++++++++++++
7 files changed, 965 insertions(+)
create mode 100644 tools/lib/luo/LICENSE
create mode 100644 tools/lib/luo/Makefile
create mode 100644 tools/lib/luo/README.md
create mode 100644 tools/lib/luo/include/libluo.h
create mode 100644 tools/lib/luo/include/liveupdate.h
create mode 100644 tools/lib/luo/libluo.c
diff --git a/MAINTAINERS b/MAINTAINERS
index b4fde9f62e9b..f833b340fabd 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14026,6 +14026,7 @@ F: include/linux/liveupdate.h
F: include/uapi/linux/liveupdate.h
F: kernel/liveupdate/
F: mm/memfd_luo.c
+F: tools/lib/luo/
F: tools/testing/selftests/liveupdate/
LLC (802.2)
diff --git a/tools/lib/luo/LICENSE b/tools/lib/luo/LICENSE
new file mode 100644
index 000000000000..0a041280bd00
--- /dev/null
+++ b/tools/lib/luo/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/tools/lib/luo/Makefile b/tools/lib/luo/Makefile
new file mode 100644
index 000000000000..e851c37d3d0a
--- /dev/null
+++ b/tools/lib/luo/Makefile
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: LGPL-3.0-or-later
+SRCS = libluo.c
+OBJS = $(SRCS:.c=.o)
+INCLUDE_DIR = include
+HEADERS = $(wildcard $(INCLUDE_DIR)/*.h)
+
+CC = gcc
+AR = ar
+CFLAGS = -Wall -Wextra -fPIC -O2 -g -I$(INCLUDE_DIR)
+LDFLAGS = -shared
+
+LIB_NAME = libluo
+STATIC_LIB = $(LIB_NAME).a
+SHARED_LIB = $(LIB_NAME).so
+
+.PHONY: all clean install
+
+all: $(STATIC_LIB) $(SHARED_LIB)
+
+$(STATIC_LIB): $(OBJS)
+ $(AR) rcs $@ $^
+
+$(SHARED_LIB): $(OBJS)
+ $(CC) $(LDFLAGS) -o $@ $^
+
+%.o: %.c $(HEADERS)
+ $(CC) $(CFLAGS) -c $< -o $@
+
+clean:
+ rm -f $(OBJS) $(STATIC_LIB) $(SHARED_LIB)
+
+install: all
+ install -d $(DESTDIR)/usr/local/lib
+ install -d $(DESTDIR)/usr/local/include
+ install -m 644 $(STATIC_LIB) $(DESTDIR)/usr/local/lib
+ install -m 755 $(SHARED_LIB) $(DESTDIR)/usr/local/lib
+ install -m 644 $(HEADERS) $(DESTDIR)/usr/local/include
diff --git a/tools/lib/luo/README.md b/tools/lib/luo/README.md
new file mode 100644
index 000000000000..a716ccb2992c
--- /dev/null
+++ b/tools/lib/luo/README.md
@@ -0,0 +1,166 @@
+# LibLUO - Live Update Orchestrator Library
+
+A C library for interacting with the Linux Live Update Orchestrator (LUO) subsystem.
+
+## Overview
+
+LibLUO provides a set of APIs for applications to interact with LUO, avoiding
+the need to directly calling the LUO ioctls. It provides APIs for controlling
+the LUO state and preserve and restore file descriptors across live updates.
+
+## Features
+
+- Initialize and manage connection to the LUO device.
+- Preserve file descriptors before a live update.
+- Restore file descriptors after a live update.
+- Control the live update state machine (prepare, cancel, finish).
+- Query the current state of the LUO subsystem.
+- The library also includes a test suite for testing both LibLUO and the kernel
+ LUO interface.
+
+## Building
+
+```bash
+make
+```
+
+This will build both static (`libluo.a`) and shared (`libluo.so`) versions of the library.
+
+To build the tests, do
+
+``` bash
+make tests
+```
+
+This will build the `tests/test` binary.
+
+## Installation
+
+```bash
+sudo make install
+```
+
+This will install the library to `/usr/local/lib` and the header file to `/usr/local/include`.
+
+## Usage
+
+### Preserving a file descriptor
+
+```c
+#include <libluo.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+int main() {
+ int ret;
+ uint64_t token;
+ int fd, new_fd;
+ enum luo_state state;
+
+ // Initialize the library
+ ret = luo_init();
+ if (ret < 0) {
+ fprintf(stderr, "Failed to initialize LibLUO: %d\n", ret);
+ return 1;
+ }
+
+ // Check if LUO is available
+ if (!luo_is_available()) {
+ fprintf(stderr, "LUO is not available on this system\n");
+ return 1;
+ }
+
+ // Get the current LUO state
+ ret = luo_get_state(&state);
+ if (ret < 0) {
+ fprintf(stderr, "Failed to get LUO state: %d\n", ret);
+ luo_cleanup();
+ return 1;
+ }
+
+ printf("Current LUO state: %s\n", luo_state_to_string(state));
+
+ // Open a file descriptor to preserve
+ fd = memfd_create("luo_memfd", 0);
+ if (fd < 0) {
+ perror("Failed to open memfd");
+ luo_cleanup();
+ return 1;
+ }
+
+ // Preserve the file descriptor
+ ret = luo_fd_preserve(fd, &token);
+ if (ret < 0) {
+ fprintf(stderr, "Failed to preserve FD: %d\n", ret);
+ close(fd);
+ luo_cleanup();
+ return 1;
+ }
+
+ printf("FD %d preserved with token %lu\n", fd, token);
+
+ // After a live update, restore the file descriptor
+ if (state == LUO_STATE_UPDATED) {
+ ret = luo_fd_restore(token, &new_fd);
+ if (ret < 0) {
+ fprintf(stderr, "Failed to restore FD: %d\n", ret);
+ } else {
+ printf("FD restored: %d\n", new_fd);
+ close(new_fd);
+ }
+
+ // Signal completion of restoration
+ luo_finish();
+ }
+
+ close(fd);
+ luo_cleanup();
+ return 0;
+}
+```
+
+### Controlling the Live Update Process
+
+```c
+#include <libluo.h>
+#include <stdio.h>
+
+int main() {
+ int ret;
+
+ ret = luo_init();
+ if (ret < 0) {
+ return 1;
+ }
+
+ // Initiate the preparation phase
+ ret = luo_prepare();
+ if (ret < 0) {
+ fprintf(stderr, "Failed to prepare for live update: %d\n", ret);
+ luo_cleanup();
+ return 1;
+ }
+
+ // At this point, the system is ready for kexec reboot
+ // The freeze operation is handled internally by the kernel
+ // during kexec.
+
+ // After reboot, in the new kernel
+ // Signal completion of restoration
+ ret = luo_finish();
+ if (ret < 0) {
+ fprintf(stderr, "Failed to finish live update: %d\n", ret);
+ luo_cleanup();
+ return 1;
+ }
+
+ luo_cleanup();
+ return 0;
+}
+```
+
+## License
+
+This library is provided under the terms of the GNU Lesser General Public
+License version 3.0, or (at your option) any later version.
diff --git a/tools/lib/luo/include/libluo.h b/tools/lib/luo/include/libluo.h
new file mode 100644
index 000000000000..86b277e8e4f6
--- /dev/null
+++ b/tools/lib/luo/include/libluo.h
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+/**
+ * @file libluo.h
+ * @brief Library for interacting with the Linux Live Update Orchestrator (LUO)
+ *
+ * This library provides a simple interface for applications to interact with
+ * the Linux Live Update Orchestrator (LUO) subsystem, allowing them to preserve
+ * and restore file descriptors across live kernel updates.
+ *
+ * Copyright (C) 2025 Amazon.com Inc. or its affiliates.
+ * Author: Pratyush Yadav <ptyadav@amazon.de>
+ */
+
+#ifndef _LIBLUO_H
+#define _LIBLUO_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <liveupdate.h>
+
+/**
+ * @brief Initialize the LUO library
+ *
+ * Opens the LUO device file and prepares the library for use.
+ *
+ * @return 0 on success, negative error code on failure
+ */
+int luo_init(void);
+
+/**
+ * @brief Clean up and release resources used by the LUO library
+ *
+ * Closes the LUO device file and releases any resources allocated by the
+ * library.
+ */
+void luo_cleanup(void);
+
+/**
+ * @brief Get the current state of the LUO subsystem
+ *
+ * @param[out] state Pointer to store the current LUO state
+ * @return 0 on success, negative error code on failure
+ */
+int luo_get_state(enum liveupdate_state *state);
+
+/**
+ * @brief Preserve a file descriptor for restoration after a live update
+ *
+ * Marks the specified file descriptor for preservation across a live update.
+ * The kernel validates if the FD type is supported for preservation.
+ *
+ * @param[in] fd The file descriptor to preserve
+ * @param[in] token Token to associate fd with. Must be unique.
+ * @return 0 on success, negative error code on failure
+ */
+int luo_fd_preserve(int fd, uint64_t token);
+
+/**
+ * @brief Cancel preservation of a previously preserved file descriptor
+ *
+ * Removes a file descriptor from the preservation list using its token.
+ *
+ * @param[in] token The token used to preserve fd previously.
+ * @return 0 on success, negative error code on failure
+ */
+int luo_fd_unpreserve(uint64_t token);
+
+/**
+ * @brief Restore a previously preserved file descriptor
+ *
+ * Restores a file descriptor that was preserved before the live update.
+ * This must be called after the system has rebooted into the new kernel.
+ *
+ * @param[in] token The token returned by luo_fd_preserve before the update
+ * @param[out] fd Pointer to store the new file descriptor
+ * @return 0 on success, negative error code on failure
+ */
+int luo_fd_restore(uint64_t token, int *fd);
+
+/**
+ * @brief Initiate the preparation phase for a live update
+ *
+ * Triggers the PREPARE phase in the LUO subsystem, which begins the
+ * state saving process for items marked for preservation.
+ *
+ * @return 0 on success, negative error code on failure
+ */
+int luo_prepare(void);
+
+/**
+ * @brief Cancel the live update preparation phase
+ *
+ * Aborts the preparation sequence and returns the system to normal state.
+ *
+ * @return 0 on success, negative error code on failure
+ */
+int luo_cancel(void);
+
+/**
+ * @brief Signal completion of restoration after a live update
+ *
+ * Notifies the LUO subsystem that all necessary restoration actions
+ * have been completed in the new kernel.
+ *
+ * @return 0 on success, negative error code on failure
+ */
+int luo_finish(void);
+
+/**
+ * @brief Check if the LUO subsystem is available
+ *
+ * Tests if the LUO device file exists and can be opened.
+ *
+ * @return true if LUO is available, false otherwise
+ */
+bool luo_is_available(void);
+
+/**
+ * @brief Convert a liveupdate_state enum value to a string
+ *
+ * Returns a string representation of the given LUO state.
+ *
+ * @param[in] state The LUO state to convert
+ * @return A constant string representing the state
+ */
+const char *luo_state_to_string(enum liveupdate_state state);
+
+#endif /* _LIBLUO_H */
diff --git a/tools/lib/luo/include/liveupdate.h b/tools/lib/luo/include/liveupdate.h
new file mode 100644
index 000000000000..7b12a1073c3c
--- /dev/null
+++ b/tools/lib/luo/include/liveupdate.h
@@ -0,0 +1,265 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+
+/*
+ * Userspace interface for /dev/liveupdate
+ * Live Update Orchestrator
+ *
+ * Copyright (c) 2025, Google LLC.
+ * Pasha Tatashin <pasha.tatashin@soleen.com>
+ */
+
+#ifndef _UAPI_LIVEUPDATE_H
+#define _UAPI_LIVEUPDATE_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/**
+ * enum liveupdate_state - Defines the possible states of the live update
+ * orchestrator.
+ * @LIVEUPDATE_STATE_UNDEFINED: State has not yet been initialized.
+ * @LIVEUPDATE_STATE_NORMAL: Default state, no live update in progress.
+ * @LIVEUPDATE_STATE_PREPARED: Live update is prepared for reboot; the
+ * LIVEUPDATE_PREPARE callbacks have completed
+ * successfully.
+ * Devices might operate in a limited state
+ * for example the participating devices might
+ * not be allowed to unbind, and also the
+ * setting up of new DMA mappings might be
+ * disabled in this state.
+ * @LIVEUPDATE_STATE_FROZEN: The final reboot event
+ * (%LIVEUPDATE_FREEZE) has been sent, and the
+ * system is performing its final state saving
+ * within the "blackout window". User
+ * workloads must be suspended. The actual
+ * reboot (kexec) into the next kernel is
+ * imminent.
+ * @LIVEUPDATE_STATE_UPDATED: The system has rebooted into the next
+ * kernel via live update the system is now
+ * running the next kernel, awaiting the
+ * finish event.
+ *
+ * These states track the progress and outcome of a live update operation.
+ */
+enum liveupdate_state {
+ LIVEUPDATE_STATE_UNDEFINED = 0,
+ LIVEUPDATE_STATE_NORMAL = 1,
+ LIVEUPDATE_STATE_PREPARED = 2,
+ LIVEUPDATE_STATE_FROZEN = 3,
+ LIVEUPDATE_STATE_UPDATED = 4,
+};
+
+/**
+ * struct liveupdate_fd - Holds parameters for preserving and restoring file
+ * descriptors across live update.
+ * @fd: Input for %LIVEUPDATE_IOCTL_FD_PRESERVE: The user-space file
+ * descriptor to be preserved.
+ * Output for %LIVEUPDATE_IOCTL_FD_RESTORE: The new file descriptor
+ * representing the fully restored kernel resource.
+ * @flags: Unused, reserved for future expansion, must be set to 0.
+ * @token: Input for %LIVEUPDATE_IOCTL_FD_PRESERVE: An opaque, unique token
+ * preserved for preserved resource.
+ * Input for %LIVEUPDATE_IOCTL_FD_RESTORE: The token previously
+ * provided to the preserve ioctl for the resource to be restored.
+ *
+ * This structure is used as the argument for the %LIVEUPDATE_IOCTL_FD_PRESERVE
+ * and %LIVEUPDATE_IOCTL_FD_RESTORE ioctls. These ioctls allow specific types
+ * of file descriptors (for example memfd, kvm, iommufd, and VFIO) to have their
+ * underlying kernel state preserved across a live update cycle.
+ *
+ * To preserve an FD, user space passes this struct to
+ * %LIVEUPDATE_IOCTL_FD_PRESERVE with the @fd field set. On success, the
+ * kernel uses the @token field to uniquly associate the preserved FD.
+ *
+ * After the live update transition, user space passes the struct populated with
+ * the *same* @token to %LIVEUPDATE_IOCTL_FD_RESTORE. The kernel uses the @token
+ * to find the preserved state and, on success, populates the @fd field with a
+ * new file descriptor referring to the restored resource.
+ */
+struct liveupdate_fd {
+ int fd;
+ __u32 flags;
+ __aligned_u64 token;
+};
+
+/* The ioctl type, documented in ioctl-number.rst */
+#define LIVEUPDATE_IOCTL_TYPE 0xBA
+
+/**
+ * LIVEUPDATE_IOCTL_FD_PRESERVE - Validate and initiate preservation for a file
+ * descriptor.
+ *
+ * Argument: Pointer to &struct liveupdate_fd.
+ *
+ * User sets the @fd field identifying the file descriptor to preserve
+ * (e.g., memfd, kvm, iommufd, VFIO). The kernel validates if this FD type
+ * and its dependencies are supported for preservation. If validation passes,
+ * the kernel marks the FD internally and *initiates the process* of preparing
+ * its state for saving. The actual snapshotting of the state typically occurs
+ * during the subsequent %LIVEUPDATE_IOCTL_PREPARE execution phase, though
+ * some finalization might occur during freeze.
+ * On successful validation and initiation, the kernel uses the @token
+ * field with an opaque identifier representing the resource being preserved.
+ * This token confirms the FD is targeted for preservation and is required for
+ * the subsequent %LIVEUPDATE_IOCTL_FD_RESTORE call after the live update.
+ *
+ * Return: 0 on success (validation passed, preservation initiated), negative
+ * error code on failure (e.g., unsupported FD type, dependency issue,
+ * validation failed).
+ */
+#define LIVEUPDATE_IOCTL_FD_PRESERVE \
+ _IOW(LIVEUPDATE_IOCTL_TYPE, 0x00, struct liveupdate_fd)
+
+/**
+ * LIVEUPDATE_IOCTL_FD_UNPRESERVE - Remove a file descriptor from the
+ * preservation list.
+ *
+ * Argument: Pointer to __u64 token.
+ *
+ * Allows user space to explicitly remove a file descriptor from the set of
+ * items marked as potentially preservable. User space provides a pointer to the
+ * __u64 @token that was previously returned by a successful
+ * %LIVEUPDATE_IOCTL_FD_PRESERVE call (potentially from a prior, possibly
+ * cancelled, live update attempt). The kernel reads the token value from the
+ * provided user-space address.
+ *
+ * On success, the kernel removes the corresponding entry (identified by the
+ * token value read from the user pointer) from its internal preservation list.
+ * The provided @token (representing the now-removed entry) becomes invalid
+ * after this call.
+ *
+ * Return: 0 on success, negative error code on failure (e.g., -EBUSY or -EINVAL
+ * if not in %LIVEUPDATE_STATE_NORMAL, bad address provided, invalid token value
+ * read, token not found).
+ */
+#define LIVEUPDATE_IOCTL_FD_UNPRESERVE \
+ _IOW(LIVEUPDATE_IOCTL_TYPE, 0x01, __u64)
+
+/**
+ * LIVEUPDATE_IOCTL_FD_RESTORE - Restore a previously preserved file descriptor.
+ *
+ * Argument: Pointer to &struct liveupdate_fd.
+ *
+ * User sets the @token field to the value obtained from a successful
+ * %LIVEUPDATE_IOCTL_FD_PRESERVE call before the live update. On success,
+ * the kernel restores the state (saved during the PREPARE/FREEZE phases)
+ * associated with the token and populates the @fd field with a new file
+ * descriptor referencing the restored resource in the current (new) kernel.
+ * This operation must be performed *before* signaling completion via
+ * %LIVEUPDATE_IOCTL_FINISH.
+ *
+ * Return: 0 on success, negative error code on failure (e.g., invalid token).
+ */
+#define LIVEUPDATE_IOCTL_FD_RESTORE \
+ _IOWR(LIVEUPDATE_IOCTL_TYPE, 0x02, struct liveupdate_fd)
+
+/**
+ * LIVEUPDATE_IOCTL_GET_STATE - Query the current state of the live update
+ * orchestrator.
+ *
+ * Argument: Pointer to &enum liveupdate_state.
+ *
+ * The kernel fills the enum value pointed to by the argument with the current
+ * state of the live update subsystem. Possible states are:
+ *
+ * - %LIVEUPDATE_STATE_NORMAL: Default state; no live update operation is
+ * currently in progress.
+ * - %LIVEUPDATE_STATE_PREPARED: The preparation phase (triggered by
+ * %LIVEUPDATE_IOCTL_PREPARE) has completed
+ * successfully. The system is ready for the
+ * reboot transition. Note that some
+ * device operations (e.g., unbinding, new DMA
+ * mappings) might be restricted in this state.
+ * - %LIVEUPDATE_STATE_UPDATED: The system has successfully rebooted into the
+ * new kernel via live update. It is now running
+ * the new kernel code and is awaiting the
+ * completion signal from user space via
+ * %LIVEUPDATE_IOCTL_FINISH after
+ * restoration tasks are done.
+ *
+ * See the definition of &enum liveupdate_state for more details on each state.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+#define LIVEUPDATE_IOCTL_GET_STATE \
+ _IOR(LIVEUPDATE_IOCTL_TYPE, 0x03, enum liveupdate_state)
+
+/**
+ * LIVEUPDATE_IOCTL_PREPARE - Initiate preparation phase and trigger state
+ * saving.
+ *
+ * Argument: None.
+ *
+ * Initiates the live update preparation phase. This action corresponds to
+ * the internal %LIVEUPDATE_PREPARE. This typically triggers the saving process
+ * for items marked via the PRESERVE ioctls. This typically occurs *before*
+ * the "blackout window", while user applications (e.g., VMs) may still be
+ * running. Kernel subsystems receiving the %LIVEUPDATE_PREPARE event should
+ * serialize necessary state. This command does not transfer data.
+ *
+ * Return: 0 on success, negative error code on failure. Transitions state
+ * towards %LIVEUPDATE_STATE_PREPARED on success.
+ */
+#define LIVEUPDATE_IOCTL_PREPARE \
+ _IO(LIVEUPDATE_IOCTL_TYPE, 0x04)
+
+/**
+ * LIVEUPDATE_IOCTL_CANCEL - Cancel the live update preparation phase.
+ *
+ * Argument: None.
+ *
+ * Notifies the live update subsystem to abort the preparation sequence
+ * potentially initiated by %LIVEUPDATE_IOCTL_PREPARE. This action
+ * typically corresponds to the internal %LIVEUPDATE_CANCEL kernel event,
+ * which might also be triggered automatically if the PREPARE stage fails
+ * internally.
+ *
+ * When triggered, subsystems receiving the %LIVEUPDATE_CANCEL event should
+ * revert any state changes or actions taken specifically for the aborted
+ * prepare phase (e.g., discard partially serialized state). The kernel
+ * releases resources allocated specifically for this *aborted preparation
+ * attempt*.
+ *
+ * This operation cancels the current *attempt* to prepare for a live update
+ * but does **not** remove previously validated items from the internal list
+ * of potentially preservable resources. Consequently, preservation tokens
+ * previously generated by successful %LIVEUPDATE_IOCTL_FD_PRESERVE or calls
+ * generally **remain valid** as identifiers for those potentially preservable
+ * resources. However, since the system state returns towards
+ * %LIVEUPDATE_STATE_NORMAL, user space must initiate a new live update sequence
+ * (starting with %LIVEUPDATE_IOCTL_PREPARE) to proceed with an update
+ * using these (or other) tokens.
+ *
+ * This command does not transfer data. Kernel callbacks for the
+ * %LIVEUPDATE_CANCEL event must not fail.
+ *
+ * Return: 0 on success, negative error code on failure. Transitions state back
+ * towards %LIVEUPDATE_STATE_NORMAL on success.
+ */
+#define LIVEUPDATE_IOCTL_CANCEL \
+ _IO(LIVEUPDATE_IOCTL_TYPE, 0x06)
+
+/**
+ * LIVEUPDATE_IOCTL_EVENT_FINISH - Signal restoration completion and trigger
+ * cleanup.
+ *
+ * Argument: None.
+ *
+ * Signals that user space has completed all necessary restoration actions in
+ * the new kernel (after a live update reboot). This action corresponds to the
+ * internal %LIVEUPDATE_FINISH kernel event. Calling this ioctl triggers the
+ * cleanup phase: any resources that were successfully preserved but were *not*
+ * subsequently restored (reclaimed) via the RESTORE ioctls will have their
+ * preserved state discarded and associated kernel resources released. Involved
+ * devices may be reset. All desired restorations *must* be completed *before*
+ * this. Kernel callbacks for the %LIVEUPDATE_FINISH event must not fail.
+ * Successfully completing this phase transitions the system state from
+ * %LIVEUPDATE_STATE_UPDATED back to %LIVEUPDATE_STATE_NORMAL. This command does
+ * not transfer data.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+#define LIVEUPDATE_IOCTL_FINISH \
+ _IO(LIVEUPDATE_IOCTL_TYPE, 0x07)
+
+#endif /* _UAPI_LIVEUPDATE_H */
diff --git a/tools/lib/luo/libluo.c b/tools/lib/luo/libluo.c
new file mode 100644
index 000000000000..7de4bf01de16
--- /dev/null
+++ b/tools/lib/luo/libluo.c
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+/*
+ * Copyright (C) 2025 Amazon.com Inc. or its affiliates.
+ * Author: Pratyush Yadav <ptyadav@amazon.de>
+ */
+#include <libluo.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+/*
+ * The liveupdate header is not mainline right now, so it is not available on
+ * the system include path. It is copied from Linux tree and put in include/.
+ *
+ * This can be removed when liveupdate hits mainline.
+ */
+#include <liveupdate.h>
+
+#define LUO_DEVICE_PATH "/dev/liveupdate"
+
+/* File descriptor for the LUO device */
+static int luo_fd = -1;
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
+
+int luo_init(void)
+{
+ if (luo_fd >= 0)
+ /* Already initialized */
+ return 0;
+
+ luo_fd = open(LUO_DEVICE_PATH, O_RDWR);
+ if (luo_fd < 0) {
+ int err = -errno;
+
+ fprintf(stderr, "Failed to open %s: %s\n",
+ LUO_DEVICE_PATH, strerror(errno));
+ return err;
+ }
+
+ return 0;
+}
+
+void luo_cleanup(void)
+{
+ if (luo_fd >= 0) {
+ close(luo_fd);
+ luo_fd = -1;
+ }
+}
+
+bool luo_is_available(void)
+{
+ struct stat st;
+
+ /* Use stat() to check if the device file exists and is accessible */
+ if (stat(LUO_DEVICE_PATH, &st) < 0)
+ return false;
+
+ /* Verify it's a character device file. */
+ if (!S_ISCHR(st.st_mode))
+ return false;
+
+ return true;
+}
+
+int luo_get_state(enum liveupdate_state *state)
+{
+ int ret;
+
+ if (!state)
+ return -EINVAL;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_GET_STATE, state);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+int luo_fd_preserve(int fd, uint64_t token)
+{
+ struct liveupdate_fd fd_data;
+ int ret;
+
+ if (fd < 0)
+ return -EINVAL;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ fd_data.fd = fd;
+ fd_data.flags = 0; /* Must be set to 0 as per API documentation */
+ fd_data.token = token;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_FD_PRESERVE, &fd_data);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+int luo_fd_unpreserve(uint64_t token)
+{
+ int ret;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_FD_UNPRESERVE, &token);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+int luo_fd_restore(uint64_t token, int *fd)
+{
+ struct liveupdate_fd fd_data;
+ int ret;
+
+ if (!fd)
+ return -EINVAL;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ fd_data.fd = -1; /* Will be filled by the kernel */
+ fd_data.flags = 0; /* Must be set to 0 as per API documentation */
+ fd_data.token = token;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_FD_RESTORE, &fd_data);
+ if (ret < 0)
+ return -errno;
+
+ *fd = fd_data.fd;
+ return 0;
+}
+
+int luo_prepare(void)
+{
+ int ret;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_PREPARE);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+int luo_cancel(void)
+{
+ int ret;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_CANCEL);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+int luo_finish(void)
+{
+ int ret;
+
+ if (luo_fd < 0)
+ return -EBADF;
+
+ ret = ioctl(luo_fd, LIVEUPDATE_IOCTL_FINISH);
+ if (ret < 0)
+ return -errno;
+
+ return 0;
+}
+
+const char *luo_state_to_string(enum liveupdate_state state)
+{
+ static const char * const state_strings[] = {
+ [LIVEUPDATE_STATE_UNDEFINED] = "undefined",
+ [LIVEUPDATE_STATE_NORMAL] = "normal",
+ [LIVEUPDATE_STATE_PREPARED] = "prepared",
+ [LIVEUPDATE_STATE_FROZEN] = "frozen",
+ [LIVEUPDATE_STATE_UPDATED] = "updated"
+ };
+
+ if (state >= 0 && state < ARRAY_SIZE(state_strings) && state_strings[state])
+ return state_strings[state];
+
+ return "UNKNOWN";
+}
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 29/32] docs: add documentation for memfd preservation via LUO
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
Add the documentation under the "Preserving file descriptors" section of
LUO's documentation. The doc describes the properties preserved,
behaviour of the file under different LUO states, serialization format,
and current limitations.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
Documentation/core-api/liveupdate.rst | 7 ++
Documentation/mm/index.rst | 1 +
Documentation/mm/memfd_preservation.rst | 138 ++++++++++++++++++++++++
MAINTAINERS | 1 +
4 files changed, 147 insertions(+)
create mode 100644 Documentation/mm/memfd_preservation.rst
diff --git a/Documentation/core-api/liveupdate.rst b/Documentation/core-api/liveupdate.rst
index 41c4b76cd3ec..232d5f623992 100644
--- a/Documentation/core-api/liveupdate.rst
+++ b/Documentation/core-api/liveupdate.rst
@@ -18,6 +18,13 @@ LUO Preserving File Descriptors
.. kernel-doc:: kernel/liveupdate/luo_files.c
:doc: LUO file descriptors
+The following types of file descriptors can be preserved
+
+.. toctree::
+ :maxdepth: 1
+
+ ../mm/memfd_preservation
+
Public API
==========
.. kernel-doc:: include/linux/liveupdate.h
diff --git a/Documentation/mm/index.rst b/Documentation/mm/index.rst
index d3ada3e45e10..97267567ef80 100644
--- a/Documentation/mm/index.rst
+++ b/Documentation/mm/index.rst
@@ -47,6 +47,7 @@ documentation, or deleted if it has served its purpose.
hugetlbfs_reserv
ksm
memory-model
+ memfd_preservation
mmu_notifier
multigen_lru
numa
diff --git a/Documentation/mm/memfd_preservation.rst b/Documentation/mm/memfd_preservation.rst
new file mode 100644
index 000000000000..416cd1dafc97
--- /dev/null
+++ b/Documentation/mm/memfd_preservation.rst
@@ -0,0 +1,138 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+==========================
+Memfd Preservation via LUO
+==========================
+
+Overview
+========
+
+Memory file descriptors (memfd) can be preserved over a kexec using the Live
+Update Orchestrator (LUO) file preservation. This allows userspace to transfer
+its memory contents to the next kernel after a kexec.
+
+The preservation is not intended to be transparent. Only select properties of
+the file are preserved. All others are reset to default. The preserved
+properties are described below.
+
+.. note::
+ The LUO API is not stabilized yet, so the preserved properties of a memfd are
+ also not stable and are subject to backwards incompatible changes.
+
+.. note::
+ Currently a memfd backed by Hugetlb is not supported. Memfds created
+ with ``MFD_HUGETLB`` will be rejected.
+
+Preserved Properties
+====================
+
+The following properties of the memfd are preserved across kexec:
+
+File Contents
+ All data stored in the file is preserved.
+
+File Size
+ The size of the file is preserved. Holes in the file are filled by allocating
+ pages for them during preservation.
+
+File Position
+ The current file position is preserved, allowing applications to continue
+ reading/writing from their last position.
+
+File Status Flags
+ memfds are always opened with ``O_RDWR`` and ``O_LARGEFILE``. This property is
+ maintained.
+
+Non-Preserved Properties
+========================
+
+All properties which are not preserved must be assumed to be reset to default.
+This section describes some of those properties which may be more of note.
+
+``FD_CLOEXEC`` flag
+ A memfd can be created with the ``MFD_CLOEXEC`` flag that sets the
+ ``FD_CLOEXEC`` on the file. This flag is not preserved and must be set again
+ after restore via ``fcntl()``.
+
+Seals
+ File seals are not preserved. The file is unsealed on restore and if needed,
+ must be sealed again via ``fcntl()``.
+
+Behavior with LUO states
+========================
+
+This section described the behavior of the memfd in the different LUO states.
+
+Normal Phase
+ During the normal phase, the memfd can be marked for preservation using the
+ ``LIVEUPDATE_IOCTL_FD_PRESERVE`` ioctl. The memfd acts as a regular memfd
+ during this phase with no additional restrictions.
+
+Prepared Phase
+ After LUO enters ``LIVEUPDATE_STATE_PREPARED``, the memfd is serialized and
+ prepared for the next kernel. During this phase, the below things happen:
+
+ - All the folios are pinned. If some folios reside in ``ZONE_MIGRATE``, they
+ are migrated out. This ensures none of the preserved folios land in KHO
+ scratch area.
+ - Pages in swap are swapped in. Currently, there is no way to pass pages in
+ swap over KHO, so all swapped out pages are swapped back in and pinned.
+ - The memfd goes into "frozen mapping" mode. The file can no longer grow or
+ shrink, or punch holes. This ensures the serialized mappings stay in sync.
+ The file can still be read from or written to or mmap-ed.
+
+Freeze Phase
+ Updates the current file position in the serialized data to capture any
+ changes that occurred between prepare and freeze phases. After this, the FD is
+ not allowed to be accessed.
+
+Restoration Phase
+ After being restored, the memfd is functional as normal with the properties
+ listed above restored.
+
+Cancellation
+ If the liveupdate is canceled after going into prepared phase, the memfd
+ functions like in normal phase.
+
+Serialization format
+====================
+
+The state is serialized in an FDT with the following structure::
+
+ /dts-v1/;
+
+ / {
+ compatible = "memfd-v1";
+ pos = <current_file_position>;
+ size = <file_size_in_bytes>;
+ folios = <array_of_preserved_folio_descriptors>;
+ };
+
+Each folio descriptor contains:
+
+- PFN + flags (8 bytes)
+
+ - Physical frame number (PFN) of the preserved folio (bits 63:12).
+ - Folio flags (bits 11:0):
+
+ - ``PRESERVED_FLAG_DIRTY`` (bit 0)
+ - ``PRESERVED_FLAG_UPTODATE`` (bit 1)
+
+- Folio index within the file (8 bytes).
+
+Limitations
+===========
+
+The current implementation has the following limitations:
+
+Size
+ Currently the size of the file is limited by the size of the FDT. The FDT can
+ be at of most ``MAX_PAGE_ORDER`` order. By default this is 4 MiB with 4K
+ pages. Each page in the file is tracked using 16 bytes. This limits the
+ maximum size of the file to 1 GiB.
+
+See Also
+========
+
+- :doc:`Live Update Orchestrator </admin-guide/liveupdate>`
+- :doc:`/core-api/kho/concepts`
diff --git a/MAINTAINERS b/MAINTAINERS
index 361032f23876..b4fde9f62e9b 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14020,6 +14020,7 @@ S: Maintained
F: Documentation/ABI/testing/sysfs-kernel-liveupdate
F: Documentation/admin-guide/liveupdate.rst
F: Documentation/core-api/liveupdate.rst
+F: Documentation/mm/memfd_preservation.rst
F: Documentation/userspace-api/liveupdate.rst
F: include/linux/liveupdate.h
F: include/uapi/linux/liveupdate.h
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 28/32] luo: allow preserving memfd
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
The ability to preserve a memfd allows userspace to use KHO and LUO to
transfer its memory contents to the next kernel. This is useful in many
ways. For one, it can be used with IOMMUFD as the backing store for
IOMMU page tables. Preserving IOMMUFD is essential for performing a
hypervisor live update with passthrough devices. memfd support provides
the first building block for making that possible.
For another, applications with a large amount of memory that takes time
to reconstruct, reboots to consume kernel upgrades can be very
expensive. memfd with LUO gives those applications reboot-persistent
memory that they can use to quickly save and reconstruct that state.
While memfd is backed by either hugetlbfs or shmem, currently only
support on shmem is added. To be more precise, support for anonymous
shmem files is added.
The handover to the next kernel is not transparent. All the properties
of the file are not preserved; only its memory contents, position, and
size. The recreated file gets the UID and GID of the task doing the
restore, and the task's cgroup gets charged with the memory.
After LUO is in prepared state, the file cannot grow or shrink, and all
its pages are pinned to avoid migrations and swapping. The file can
still be read from or written to.
Co-developed-by: Changyuan Lyu <changyuanl@google.com>
Signed-off-by: Changyuan Lyu <changyuanl@google.com>
Co-developed-by: Pasha Tatashin <pasha.tatashin@soleen.com>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
---
MAINTAINERS | 2 +
mm/Makefile | 1 +
mm/memfd_luo.c | 501 +++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 504 insertions(+)
create mode 100644 mm/memfd_luo.c
diff --git a/MAINTAINERS b/MAINTAINERS
index 711cf25d283d..361032f23876 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14014,6 +14014,7 @@ F: tools/testing/selftests/livepatch/
LIVE UPDATE
M: Pasha Tatashin <pasha.tatashin@soleen.com>
+R: Pratyush Yadav <pratyush@kernel.org>
L: linux-kernel@vger.kernel.org
S: Maintained
F: Documentation/ABI/testing/sysfs-kernel-liveupdate
@@ -14023,6 +14024,7 @@ F: Documentation/userspace-api/liveupdate.rst
F: include/linux/liveupdate.h
F: include/uapi/linux/liveupdate.h
F: kernel/liveupdate/
+F: mm/memfd_luo.c
F: tools/testing/selftests/liveupdate/
LLC (802.2)
diff --git a/mm/Makefile b/mm/Makefile
index 1a7a11d4933d..63cca66c068a 100644
--- a/mm/Makefile
+++ b/mm/Makefile
@@ -100,6 +100,7 @@ obj-$(CONFIG_NUMA) += memory-tiers.o
obj-$(CONFIG_DEVICE_MIGRATION) += migrate_device.o
obj-$(CONFIG_TRANSPARENT_HUGEPAGE) += huge_memory.o khugepaged.o
obj-$(CONFIG_PAGE_COUNTER) += page_counter.o
+obj-$(CONFIG_LIVEUPDATE) += memfd_luo.o
obj-$(CONFIG_MEMCG_V1) += memcontrol-v1.o
obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o
ifdef CONFIG_SWAP
diff --git a/mm/memfd_luo.c b/mm/memfd_luo.c
new file mode 100644
index 000000000000..339824ab6729
--- /dev/null
+++ b/mm/memfd_luo.c
@@ -0,0 +1,501 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright (c) 2025, Google LLC.
+ * Pasha Tatashin <pasha.tatashin@soleen.com>
+ * Changyuan Lyu <changyuanl@google.com>
+ *
+ * Copyright (C) 2025 Amazon.com Inc. or its affiliates.
+ * Pratyush Yadav <ptyadav@amazon.de>
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/file.h>
+#include <linux/io.h>
+#include <linux/libfdt.h>
+#include <linux/liveupdate.h>
+#include <linux/kexec_handover.h>
+#include <linux/shmem_fs.h>
+#include <linux/bits.h>
+#include "internal.h"
+
+static const char memfd_luo_compatible[] = "memfd-v1";
+
+#define PRESERVED_PFN_MASK GENMASK(63, 12)
+#define PRESERVED_PFN_SHIFT 12
+#define PRESERVED_FLAG_DIRTY BIT(0)
+#define PRESERVED_FLAG_UPTODATE BIT(1)
+
+#define PRESERVED_FOLIO_PFN(desc) (((desc) & PRESERVED_PFN_MASK) >> PRESERVED_PFN_SHIFT)
+#define PRESERVED_FOLIO_FLAGS(desc) ((desc) & ~PRESERVED_PFN_MASK)
+#define PRESERVED_FOLIO_MKDESC(pfn, flags) (((pfn) << PRESERVED_PFN_SHIFT) | (flags))
+
+struct memfd_luo_preserved_folio {
+ /*
+ * The folio descriptor is made of 2 parts. The bottom 12 bits are used
+ * for storing flags, the others for storing the PFN.
+ */
+ u64 foliodesc;
+ u64 index;
+};
+
+static int memfd_luo_preserve_folios(struct memfd_luo_preserved_folio *pfolios,
+ struct folio **folios,
+ unsigned int nr_folios)
+{
+ unsigned int i;
+ int err;
+
+ for (i = 0; i < nr_folios; i++) {
+ struct memfd_luo_preserved_folio *pfolio = &pfolios[i];
+ struct folio *folio = folios[i];
+ unsigned int flags = 0;
+ unsigned long pfn;
+
+ err = kho_preserve_folio(folio);
+ if (err)
+ goto err_unpreserve;
+
+ pfn = folio_pfn(folio);
+ if (folio_test_dirty(folio))
+ flags |= PRESERVED_FLAG_DIRTY;
+ if (folio_test_uptodate(folio))
+ flags |= PRESERVED_FLAG_UPTODATE;
+
+ pfolio->foliodesc = PRESERVED_FOLIO_MKDESC(pfn, flags);
+ pfolio->index = folio->index;
+ }
+
+ return 0;
+
+err_unpreserve:
+ i--;
+ for (; i >= 0; i--)
+ WARN_ON_ONCE(kho_unpreserve_folio(folios[i]));
+ return err;
+}
+
+static void memfd_luo_unpreserve_folios(const struct memfd_luo_preserved_folio *pfolios,
+ unsigned int nr_folios)
+{
+ unsigned int i;
+
+ for (i = 0; i < nr_folios; i++) {
+ const struct memfd_luo_preserved_folio *pfolio = &pfolios[i];
+ struct folio *folio;
+
+ if (!pfolio->foliodesc)
+ continue;
+
+ folio = pfn_folio(PRESERVED_FOLIO_PFN(pfolio->foliodesc));
+
+ kho_unpreserve_folio(folio);
+ unpin_folio(folio);
+ }
+}
+
+static void *memfd_luo_create_fdt(unsigned long size)
+{
+ unsigned int order = get_order(size);
+ struct folio *fdt_folio;
+ int err = 0;
+ void *fdt;
+
+ if (order > MAX_PAGE_ORDER)
+ return NULL;
+
+ fdt_folio = folio_alloc(GFP_KERNEL, order);
+ if (!fdt_folio)
+ return NULL;
+
+ fdt = folio_address(fdt_folio);
+
+ err |= fdt_create(fdt, (1 << (order + PAGE_SHIFT)));
+ err |= fdt_finish_reservemap(fdt);
+ err |= fdt_begin_node(fdt, "");
+ if (err)
+ goto free;
+
+ return fdt;
+
+free:
+ folio_put(fdt_folio);
+ return NULL;
+}
+
+static int memfd_luo_finish_fdt(void *fdt)
+{
+ int err;
+
+ err = fdt_end_node(fdt);
+ if (err)
+ return err;
+
+ return fdt_finish(fdt);
+}
+
+static int memfd_luo_prepare(struct file *file, void *arg, u64 *data)
+{
+ struct memfd_luo_preserved_folio *preserved_folios;
+ struct inode *inode = file_inode(file);
+ unsigned int max_folios, nr_folios = 0;
+ int err = 0, preserved_size;
+ struct folio **folios;
+ long size, nr_pinned;
+ pgoff_t offset;
+ void *fdt;
+ u64 pos;
+
+ if (WARN_ON_ONCE(!shmem_file(file)))
+ return -EINVAL;
+
+ inode_lock(inode);
+ shmem_i_mapping_freeze(inode, true);
+
+ size = i_size_read(inode);
+ if ((PAGE_ALIGN(size) / PAGE_SIZE) > UINT_MAX) {
+ err = -E2BIG;
+ goto err_unlock;
+ }
+
+ /*
+ * Guess the number of folios based on inode size. Real number might end
+ * up being smaller if there are higher order folios.
+ */
+ max_folios = PAGE_ALIGN(size) / PAGE_SIZE;
+ folios = kvmalloc_array(max_folios, sizeof(*folios), GFP_KERNEL);
+ if (!folios) {
+ err = -ENOMEM;
+ goto err_unfreeze;
+ }
+
+ /*
+ * Pin the folios so they don't move around behind our back. This also
+ * ensures none of the folios are in CMA -- which ensures they don't
+ * fall in KHO scratch memory. It also moves swapped out folios back to
+ * memory.
+ *
+ * A side effect of doing this is that it allocates a folio for all
+ * indices in the file. This might waste memory on sparse memfds. If
+ * that is really a problem in the future, we can have a
+ * memfd_pin_folios() variant that does not allocate a page on empty
+ * slots.
+ */
+ nr_pinned = memfd_pin_folios(file, 0, size - 1, folios, max_folios,
+ &offset);
+ if (nr_pinned < 0) {
+ err = nr_pinned;
+ pr_err("failed to pin folios: %d\n", err);
+ goto err_free_folios;
+ }
+ /* nr_pinned won't be more than max_folios which is also unsigned int. */
+ nr_folios = (unsigned int)nr_pinned;
+
+ preserved_size = sizeof(struct memfd_luo_preserved_folio) * nr_folios;
+ if (check_mul_overflow(sizeof(struct memfd_luo_preserved_folio),
+ nr_folios, &preserved_size)) {
+ err = -E2BIG;
+ goto err_unpin;
+ }
+
+ /*
+ * Most of the space should be taken by preserved folios. So take its
+ * size, plus a page for other properties.
+ */
+ fdt = memfd_luo_create_fdt(PAGE_ALIGN(preserved_size) + PAGE_SIZE);
+ if (!fdt) {
+ err = -ENOMEM;
+ goto err_unpin;
+ }
+
+ pos = file->f_pos;
+ err = fdt_property(fdt, "pos", &pos, sizeof(pos));
+ if (err)
+ goto err_free_fdt;
+
+ err = fdt_property(fdt, "size", &size, sizeof(size));
+ if (err)
+ goto err_free_fdt;
+
+ err = fdt_property_placeholder(fdt, "folios", preserved_size,
+ (void **)&preserved_folios);
+ if (err) {
+ pr_err("Failed to reserve folios property in FDT: %s\n",
+ fdt_strerror(err));
+ err = -ENOMEM;
+ goto err_free_fdt;
+ }
+
+ err = memfd_luo_preserve_folios(preserved_folios, folios, nr_folios);
+ if (err)
+ goto err_free_fdt;
+
+ err = memfd_luo_finish_fdt(fdt);
+ if (err)
+ goto err_unpreserve;
+
+ err = kho_preserve_folio(virt_to_folio(fdt));
+ if (err)
+ goto err_unpreserve;
+
+ kvfree(folios);
+ inode_unlock(inode);
+
+ *data = virt_to_phys(fdt);
+ return 0;
+
+err_unpreserve:
+ memfd_luo_unpreserve_folios(preserved_folios, nr_folios);
+err_free_fdt:
+ folio_put(virt_to_folio(fdt));
+err_unpin:
+ unpin_folios(folios, nr_pinned);
+err_free_folios:
+ kvfree(folios);
+err_unfreeze:
+ shmem_i_mapping_freeze(inode, false);
+err_unlock:
+ inode_unlock(inode);
+ return err;
+}
+
+static int memfd_luo_freeze(struct file *file, void *arg, u64 *data)
+{
+ u64 pos = file->f_pos;
+ void *fdt;
+ int err;
+
+ if (WARN_ON_ONCE(!*data))
+ return -EINVAL;
+
+ fdt = phys_to_virt(*data);
+
+ /*
+ * The pos or size might have changed since prepare. Everything else
+ * stays the same.
+ */
+ err = fdt_setprop(fdt, 0, "pos", &pos, sizeof(pos));
+ if (err)
+ return err;
+
+ return 0;
+}
+
+static void memfd_luo_cancel(struct file *file, void *arg, u64 data)
+{
+ const struct memfd_luo_preserved_folio *pfolios;
+ struct inode *inode = file_inode(file);
+ struct folio *fdt_folio;
+ void *fdt;
+ int len;
+
+ if (WARN_ON_ONCE(!data))
+ return;
+
+ inode_lock(inode);
+ shmem_i_mapping_freeze(inode, false);
+
+ fdt = phys_to_virt(data);
+ fdt_folio = virt_to_folio(fdt);
+ pfolios = fdt_getprop(fdt, 0, "folios", &len);
+ if (pfolios)
+ memfd_luo_unpreserve_folios(pfolios, len / sizeof(*pfolios));
+
+ kho_unpreserve_folio(fdt_folio);
+ folio_put(fdt_folio);
+ inode_unlock(inode);
+}
+
+static struct folio *memfd_luo_get_fdt(u64 data)
+{
+ return kho_restore_folio((phys_addr_t)data);
+}
+
+static void memfd_luo_finish(struct file *file, void *arg, u64 data,
+ bool reclaimed)
+{
+ const struct memfd_luo_preserved_folio *pfolios;
+ struct folio *fdt_folio;
+ int len;
+
+ if (reclaimed)
+ return;
+
+ fdt_folio = memfd_luo_get_fdt(data);
+
+ pfolios = fdt_getprop(folio_address(fdt_folio), 0, "folios", &len);
+ if (pfolios)
+ memfd_luo_unpreserve_folios(pfolios, len / sizeof(*pfolios));
+
+ folio_put(fdt_folio);
+}
+
+static int memfd_luo_retrieve(void *arg, u64 data, struct file **file_p)
+{
+ const struct memfd_luo_preserved_folio *pfolios;
+ int nr_pfolios, len, ret = 0, i = 0;
+ struct address_space *mapping;
+ struct folio *folio, *fdt_folio;
+ const u64 *pos, *size;
+ struct inode *inode;
+ struct file *file;
+ const void *fdt;
+
+ fdt_folio = memfd_luo_get_fdt(data);
+ if (!fdt_folio)
+ return -ENOENT;
+
+ fdt = page_to_virt(folio_page(fdt_folio, 0));
+
+ pfolios = fdt_getprop(fdt, 0, "folios", &len);
+ if (!pfolios || len % sizeof(*pfolios)) {
+ pr_err("invalid 'folios' property\n");
+ ret = -EINVAL;
+ goto put_fdt;
+ }
+ nr_pfolios = len / sizeof(*pfolios);
+
+ size = fdt_getprop(fdt, 0, "size", &len);
+ if (!size || len != sizeof(u64)) {
+ pr_err("invalid 'size' property\n");
+ ret = -EINVAL;
+ goto put_folios;
+ }
+
+ pos = fdt_getprop(fdt, 0, "pos", &len);
+ if (!pos || len != sizeof(u64)) {
+ pr_err("invalid 'pos' property\n");
+ ret = -EINVAL;
+ goto put_folios;
+ }
+
+ file = shmem_file_setup("", 0, VM_NORESERVE);
+
+ if (IS_ERR(file)) {
+ ret = PTR_ERR(file);
+ pr_err("failed to setup file: %d\n", ret);
+ goto put_folios;
+ }
+
+ inode = file->f_inode;
+ mapping = inode->i_mapping;
+ vfs_setpos(file, *pos, MAX_LFS_FILESIZE);
+
+ for (; i < nr_pfolios; i++) {
+ const struct memfd_luo_preserved_folio *pfolio = &pfolios[i];
+ phys_addr_t phys;
+ u64 index;
+ int flags;
+
+ if (!pfolio->foliodesc)
+ continue;
+
+ phys = PFN_PHYS(PRESERVED_FOLIO_PFN(pfolio->foliodesc));
+ folio = kho_restore_folio(phys);
+ if (!folio) {
+ pr_err("Unable to restore folio at physical address: %llx\n",
+ phys);
+ goto put_file;
+ }
+ index = pfolio->index;
+ flags = PRESERVED_FOLIO_FLAGS(pfolio->foliodesc);
+
+ /* Set up the folio for insertion. */
+ /*
+ * TODO: Should find a way to unify this and
+ * shmem_alloc_and_add_folio().
+ */
+ __folio_set_locked(folio);
+ __folio_set_swapbacked(folio);
+
+ ret = mem_cgroup_charge(folio, NULL, mapping_gfp_mask(mapping));
+ if (ret) {
+ pr_err("shmem: failed to charge folio index %d: %d\n",
+ i, ret);
+ goto unlock_folio;
+ }
+
+ ret = shmem_add_to_page_cache(folio, mapping, index, NULL,
+ mapping_gfp_mask(mapping));
+ if (ret) {
+ pr_err("shmem: failed to add to page cache folio index %d: %d\n",
+ i, ret);
+ goto unlock_folio;
+ }
+
+ if (flags & PRESERVED_FLAG_UPTODATE)
+ folio_mark_uptodate(folio);
+ if (flags & PRESERVED_FLAG_DIRTY)
+ folio_mark_dirty(folio);
+
+ ret = shmem_inode_acct_blocks(inode, 1);
+ if (ret) {
+ pr_err("shmem: failed to account folio index %d: %d\n",
+ i, ret);
+ goto unlock_folio;
+ }
+
+ shmem_recalc_inode(inode, 1, 0);
+ folio_add_lru(folio);
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+
+ inode->i_size = *size;
+ *file_p = file;
+ folio_put(fdt_folio);
+ return 0;
+
+unlock_folio:
+ folio_unlock(folio);
+ folio_put(folio);
+put_file:
+ fput(file);
+ i++;
+put_folios:
+ for (; i < nr_pfolios; i++) {
+ const struct memfd_luo_preserved_folio *pfolio = &pfolios[i];
+
+ folio = kho_restore_folio(PRESERVED_FOLIO_PFN(pfolio->foliodesc));
+ if (folio)
+ folio_put(folio);
+ }
+
+put_fdt:
+ folio_put(fdt_folio);
+ return ret;
+}
+
+static bool memfd_luo_can_preserve(struct file *file, void *arg)
+{
+ struct inode *inode = file_inode(file);
+
+ return shmem_file(file) && !inode->i_nlink;
+}
+
+static const struct liveupdate_file_ops memfd_luo_file_ops = {
+ .prepare = memfd_luo_prepare,
+ .freeze = memfd_luo_freeze,
+ .cancel = memfd_luo_cancel,
+ .finish = memfd_luo_finish,
+ .retrieve = memfd_luo_retrieve,
+ .can_preserve = memfd_luo_can_preserve,
+};
+
+static struct liveupdate_file_handler memfd_luo_handler = {
+ .ops = &memfd_luo_file_ops,
+ .compatible = memfd_luo_compatible,
+};
+
+static int __init memfd_luo_init(void)
+{
+ int err;
+
+ err = liveupdate_register_file_handler(&memfd_luo_handler);
+ if (err)
+ pr_err("Could not register luo filesystem handler: %d\n", err);
+
+ return err;
+}
+late_initcall(memfd_luo_init);
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 27/32] mm: shmem: export some functions to internal.h
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
shmem_inode_acct_blocks(), shmem_recalc_inode(), and
shmem_add_to_page_cache() are used by shmem_alloc_and_add_folio(). This
functionality will also be used in the future by Live Update
Orchestrator (LUO) to recreate memfd files after a live update.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
mm/internal.h | 6 ++++++
mm/shmem.c | 10 +++++-----
2 files changed, 11 insertions(+), 5 deletions(-)
diff --git a/mm/internal.h b/mm/internal.h
index 6b8ed2017743..991917a8ae23 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -1535,6 +1535,12 @@ void __meminit __init_page_from_nid(unsigned long pfn, int nid);
unsigned long shrink_slab(gfp_t gfp_mask, int nid, struct mem_cgroup *memcg,
int priority);
+int shmem_add_to_page_cache(struct folio *folio,
+ struct address_space *mapping,
+ pgoff_t index, void *expected, gfp_t gfp);
+int shmem_inode_acct_blocks(struct inode *inode, long pages);
+void shmem_recalc_inode(struct inode *inode, long alloced, long swapped);
+
#ifdef CONFIG_SHRINKER_DEBUG
static inline __printf(2, 0) int shrinker_debugfs_name_alloc(
struct shrinker *shrinker, const char *fmt, va_list ap)
diff --git a/mm/shmem.c b/mm/shmem.c
index d1e74f59cdba..4a616fe595e2 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -219,7 +219,7 @@ static inline void shmem_unacct_blocks(unsigned long flags, long pages)
vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
}
-static int shmem_inode_acct_blocks(struct inode *inode, long pages)
+int shmem_inode_acct_blocks(struct inode *inode, long pages)
{
struct shmem_inode_info *info = SHMEM_I(inode);
struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
@@ -433,7 +433,7 @@ static void shmem_free_inode(struct super_block *sb, size_t freed_ispace)
* But normally info->alloced == inode->i_mapping->nrpages + info->swapped
* So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
*/
-static void shmem_recalc_inode(struct inode *inode, long alloced, long swapped)
+void shmem_recalc_inode(struct inode *inode, long alloced, long swapped)
{
struct shmem_inode_info *info = SHMEM_I(inode);
long freed;
@@ -879,9 +879,9 @@ static void shmem_update_stats(struct folio *folio, int nr_pages)
/*
* Somewhat like filemap_add_folio, but error if expected item has gone.
*/
-static int shmem_add_to_page_cache(struct folio *folio,
- struct address_space *mapping,
- pgoff_t index, void *expected, gfp_t gfp)
+int shmem_add_to_page_cache(struct folio *folio,
+ struct address_space *mapping,
+ pgoff_t index, void *expected, gfp_t gfp)
{
XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio));
long nr = folio_nr_pages(folio);
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 26/32] mm: shmem: allow freezing inode mapping
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
To prepare a shmem inode for live update via the Live Update
Orchestrator (LUO), its index -> folio mappings must be serialized. Once
the mappings are serialized, they cannot change since it would cause the
serialized data to become inconsistent. This can be done by pinning the
folios to avoid migration, and by making sure no folios can be added to
or removed from the inode.
While mechanisms to pin folios already exist, the only way to stop
folios being added or removed are the grow and shrink file seals. But
file seals come with their own semantics, one of which is that they
can't be removed. This doesn't work with liveupdate since it can be
cancelled or error out, which would need the seals to be removed and the
file's normal functionality to be restored.
Introduce SHMEM_F_MAPPING_FROZEN to indicate this instead. It is
internal to shmem and is not directly exposed to userspace. It functions
similar to F_SEAL_GROW | F_SEAL_SHRINK, but additionally disallows hole
punching, and can be removed.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pahsa.tatashin@soleen.com>
---
include/linux/shmem_fs.h | 17 +++++++++++++++++
mm/shmem.c | 12 +++++++++++-
2 files changed, 28 insertions(+), 1 deletion(-)
diff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h
index 578a5f3d1935..1dd2aad0986b 100644
--- a/include/linux/shmem_fs.h
+++ b/include/linux/shmem_fs.h
@@ -22,6 +22,14 @@
#define SHMEM_F_NORESERVE BIT(0)
/* Disallow swapping. */
#define SHMEM_F_LOCKED BIT(1)
+/*
+ * Disallow growing, shrinking, or hole punching in the inode. Combined with
+ * folio pinning, makes sure the inode's mapping stays fixed.
+ *
+ * In some ways similar to F_SEAL_GROW | F_SEAL_SHRINK, but can be removed and
+ * isn't directly visible to userspace.
+ */
+#define SHMEM_F_MAPPING_FROZEN BIT(2)
struct shmem_inode_info {
spinlock_t lock;
@@ -183,6 +191,15 @@ static inline bool shmem_file(struct file *file)
return shmem_mapping(file->f_mapping);
}
+/* Must be called with inode lock taken exclusive. */
+static inline void shmem_i_mapping_freeze(struct inode *inode, bool freeze)
+{
+ if (freeze)
+ SHMEM_I(inode)->flags |= SHMEM_F_MAPPING_FROZEN;
+ else
+ SHMEM_I(inode)->flags &= ~SHMEM_F_MAPPING_FROZEN;
+}
+
/*
* If fallocate(FALLOC_FL_KEEP_SIZE) has been used, there may be pages
* beyond i_size's notion of EOF, which fallocate has committed to reserving:
diff --git a/mm/shmem.c b/mm/shmem.c
index 6eded368d17a..d1e74f59cdba 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -1297,7 +1297,8 @@ static int shmem_setattr(struct mnt_idmap *idmap,
loff_t newsize = attr->ia_size;
/* protected by i_rwsem */
- if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
+ if ((info->flags & SHMEM_F_MAPPING_FROZEN) ||
+ (newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
(newsize > oldsize && (info->seals & F_SEAL_GROW)))
return -EPERM;
@@ -3291,6 +3292,10 @@ shmem_write_begin(struct file *file, struct address_space *mapping,
return -EPERM;
}
+ if (unlikely((info->flags & SHMEM_F_MAPPING_FROZEN) &&
+ pos + len > inode->i_size))
+ return -EPERM;
+
ret = shmem_get_folio(inode, index, pos + len, &folio, SGP_WRITE);
if (ret)
return ret;
@@ -3664,6 +3669,11 @@ static long shmem_fallocate(struct file *file, int mode, loff_t offset,
inode_lock(inode);
+ if (info->flags & SHMEM_F_MAPPING_FROZEN) {
+ error = -EPERM;
+ goto out;
+ }
+
if (mode & FALLOC_FL_PUNCH_HOLE) {
struct address_space *mapping = file->f_mapping;
loff_t unmap_start = round_up(offset, PAGE_SIZE);
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 25/32] mm: shmem: use SHMEM_F_* flags instead of VM_* flags
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
From: Pratyush Yadav <ptyadav@amazon.de>
shmem_inode_info::flags can have the VM flags VM_NORESERVE and
VM_LOCKED. These are used to suppress pre-accounting or to lock the
pages in the inode respectively. Using the VM flags directly makes it
difficult to add shmem-specific flags that are unrelated to VM behavior
since one would need to find a VM flag not used by shmem and re-purpose
it.
Introduce SHMEM_F_NORESERVE and SHMEM_F_LOCKED which represent the same
information, but their bits are independent of the VM flags. Callers can
still pass VM_NORESERVE to shmem_get_inode(), but it gets transformed to
the shmem-specific flag internally.
No functional changes intended.
Signed-off-by: Pratyush Yadav <ptyadav@amazon.de>
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
include/linux/shmem_fs.h | 6 ++++++
mm/shmem.c | 30 +++++++++++++++++-------------
2 files changed, 23 insertions(+), 13 deletions(-)
diff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h
index 5f03a39a26f7..578a5f3d1935 100644
--- a/include/linux/shmem_fs.h
+++ b/include/linux/shmem_fs.h
@@ -10,6 +10,7 @@
#include <linux/xattr.h>
#include <linux/fs_parser.h>
#include <linux/userfaultfd_k.h>
+#include <linux/bits.h>
/* inode in-kernel data */
@@ -17,6 +18,11 @@
#define SHMEM_MAXQUOTAS 2
#endif
+/* Suppress pre-accounting of the entire object size. */
+#define SHMEM_F_NORESERVE BIT(0)
+/* Disallow swapping. */
+#define SHMEM_F_LOCKED BIT(1)
+
struct shmem_inode_info {
spinlock_t lock;
unsigned int seals; /* shmem seals */
diff --git a/mm/shmem.c b/mm/shmem.c
index 3a5a65b1f41a..6eded368d17a 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -175,20 +175,20 @@ static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
*/
static inline int shmem_acct_size(unsigned long flags, loff_t size)
{
- return (flags & VM_NORESERVE) ?
+ return (flags & SHMEM_F_NORESERVE) ?
0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
}
static inline void shmem_unacct_size(unsigned long flags, loff_t size)
{
- if (!(flags & VM_NORESERVE))
+ if (!(flags & SHMEM_F_NORESERVE))
vm_unacct_memory(VM_ACCT(size));
}
static inline int shmem_reacct_size(unsigned long flags,
loff_t oldsize, loff_t newsize)
{
- if (!(flags & VM_NORESERVE)) {
+ if (!(flags & SHMEM_F_NORESERVE)) {
if (VM_ACCT(newsize) > VM_ACCT(oldsize))
return security_vm_enough_memory_mm(current->mm,
VM_ACCT(newsize) - VM_ACCT(oldsize));
@@ -206,7 +206,7 @@ static inline int shmem_reacct_size(unsigned long flags,
*/
static inline int shmem_acct_blocks(unsigned long flags, long pages)
{
- if (!(flags & VM_NORESERVE))
+ if (!(flags & SHMEM_F_NORESERVE))
return 0;
return security_vm_enough_memory_mm(current->mm,
@@ -215,7 +215,7 @@ static inline int shmem_acct_blocks(unsigned long flags, long pages)
static inline void shmem_unacct_blocks(unsigned long flags, long pages)
{
- if (flags & VM_NORESERVE)
+ if (flags & SHMEM_F_NORESERVE)
vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
}
@@ -1557,7 +1557,7 @@ int shmem_writeout(struct folio *folio, struct writeback_control *wbc)
if (WARN_ON_ONCE(!wbc->for_reclaim))
goto redirty;
- if ((info->flags & VM_LOCKED) || sbinfo->noswap)
+ if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap)
goto redirty;
if (!total_swap_pages)
@@ -2910,15 +2910,15 @@ int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
* ipc_lock_object() when called from shmctl_do_lock(),
* no serialization needed when called from shm_destroy().
*/
- if (lock && !(info->flags & VM_LOCKED)) {
+ if (lock && !(info->flags & SHMEM_F_LOCKED)) {
if (!user_shm_lock(inode->i_size, ucounts))
goto out_nomem;
- info->flags |= VM_LOCKED;
+ info->flags |= SHMEM_F_LOCKED;
mapping_set_unevictable(file->f_mapping);
}
- if (!lock && (info->flags & VM_LOCKED) && ucounts) {
+ if (!lock && (info->flags & SHMEM_F_LOCKED) && ucounts) {
user_shm_unlock(inode->i_size, ucounts);
- info->flags &= ~VM_LOCKED;
+ info->flags &= ~SHMEM_F_LOCKED;
mapping_clear_unevictable(file->f_mapping);
}
retval = 0;
@@ -3062,7 +3062,9 @@ static struct inode *__shmem_get_inode(struct mnt_idmap *idmap,
spin_lock_init(&info->lock);
atomic_set(&info->stop_eviction, 0);
info->seals = F_SEAL_SEAL;
- info->flags = flags & VM_NORESERVE;
+ info->flags = 0;
+ if (flags & VM_NORESERVE)
+ info->flags |= SHMEM_F_NORESERVE;
info->i_crtime = inode_get_mtime(inode);
info->fsflags = (dir == NULL) ? 0 :
SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED;
@@ -5801,8 +5803,10 @@ static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap,
/* common code */
static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name,
- loff_t size, unsigned long flags, unsigned int i_flags)
+ loff_t size, unsigned long vm_flags,
+ unsigned int i_flags)
{
+ unsigned long flags = (vm_flags & VM_NORESERVE) ? SHMEM_F_NORESERVE : 0;
struct inode *inode;
struct file *res;
@@ -5819,7 +5823,7 @@ static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name,
return ERR_PTR(-ENOMEM);
inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL,
- S_IFREG | S_IRWXUGO, 0, flags);
+ S_IFREG | S_IRWXUGO, 0, vm_flags);
if (IS_ERR(inode)) {
shmem_unacct_size(flags, size);
return ERR_CAST(inode);
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 24/32] MAINTAINERS: add liveupdate entry
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Add a MAINTAINERS file entry for the new Live Update Orchestrator
introduced in previous patches.
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
MAINTAINERS | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 3b276cfeb038..711cf25d283d 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14012,6 +14012,19 @@ F: kernel/module/livepatch.c
F: samples/livepatch/
F: tools/testing/selftests/livepatch/
+LIVE UPDATE
+M: Pasha Tatashin <pasha.tatashin@soleen.com>
+L: linux-kernel@vger.kernel.org
+S: Maintained
+F: Documentation/ABI/testing/sysfs-kernel-liveupdate
+F: Documentation/admin-guide/liveupdate.rst
+F: Documentation/core-api/liveupdate.rst
+F: Documentation/userspace-api/liveupdate.rst
+F: include/linux/liveupdate.h
+F: include/uapi/linux/liveupdate.h
+F: kernel/liveupdate/
+F: tools/testing/selftests/liveupdate/
+
LLC (802.2)
L: netdev@vger.kernel.org
S: Odd fixes
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 23/32] docs: add luo documentation
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Add the documentation files for the Live Update Orchestrator
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
Documentation/admin-guide/index.rst | 1 +
Documentation/admin-guide/liveupdate.rst | 16 +++++++
Documentation/core-api/index.rst | 1 +
Documentation/core-api/liveupdate.rst | 50 ++++++++++++++++++++++
Documentation/userspace-api/index.rst | 1 +
Documentation/userspace-api/liveupdate.rst | 25 +++++++++++
6 files changed, 94 insertions(+)
create mode 100644 Documentation/admin-guide/liveupdate.rst
create mode 100644 Documentation/core-api/liveupdate.rst
create mode 100644 Documentation/userspace-api/liveupdate.rst
diff --git a/Documentation/admin-guide/index.rst b/Documentation/admin-guide/index.rst
index 259d79fbeb94..3f59ccf32760 100644
--- a/Documentation/admin-guide/index.rst
+++ b/Documentation/admin-guide/index.rst
@@ -95,6 +95,7 @@ likely to be of interest on almost any system.
cgroup-v2
cgroup-v1/index
cpu-load
+ liveupdate
mm/index
module-signing
namespaces/index
diff --git a/Documentation/admin-guide/liveupdate.rst b/Documentation/admin-guide/liveupdate.rst
new file mode 100644
index 000000000000..ff05cc1dd784
--- /dev/null
+++ b/Documentation/admin-guide/liveupdate.rst
@@ -0,0 +1,16 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=================
+Live Update sysfs
+=================
+:Author: Pasha Tatashin <pasha.tatashin@soleen.com>
+
+LUO sysfs interface
+===================
+.. kernel-doc:: kernel/liveupdate/luo_sysfs.c
+ :doc: LUO sysfs interface
+
+See Also
+========
+
+- :doc:`Live Update Orchestrator </core-api/liveupdate>`
diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst
index 7a4ca18ca6e2..a79d806f2c8e 100644
--- a/Documentation/core-api/index.rst
+++ b/Documentation/core-api/index.rst
@@ -136,6 +136,7 @@ Documents that don't fit elsewhere or which have yet to be categorized.
:maxdepth: 1
librs
+ liveupdate
netlink
.. only:: subproject and html
diff --git a/Documentation/core-api/liveupdate.rst b/Documentation/core-api/liveupdate.rst
new file mode 100644
index 000000000000..41c4b76cd3ec
--- /dev/null
+++ b/Documentation/core-api/liveupdate.rst
@@ -0,0 +1,50 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+========================
+Live Update Orchestrator
+========================
+:Author: Pasha Tatashin <pasha.tatashin@soleen.com>
+
+.. kernel-doc:: kernel/liveupdate/luo_core.c
+ :doc: Live Update Orchestrator (LUO)
+
+LUO Subsystems Participation
+============================
+.. kernel-doc:: kernel/liveupdate/luo_subsystems.c
+ :doc: LUO Subsystems support
+
+LUO Preserving File Descriptors
+===============================
+.. kernel-doc:: kernel/liveupdate/luo_files.c
+ :doc: LUO file descriptors
+
+Public API
+==========
+.. kernel-doc:: include/linux/liveupdate.h
+
+.. kernel-doc:: kernel/liveupdate/luo_core.c
+ :export:
+
+.. kernel-doc:: kernel/liveupdate/luo_subsystems.c
+ :export:
+
+.. kernel-doc:: kernel/liveupdate/luo_files.c
+ :export:
+
+Internal API
+============
+.. kernel-doc:: kernel/liveupdate/luo_core.c
+ :internal:
+
+.. kernel-doc:: kernel/liveupdate/luo_subsystems.c
+ :internal:
+
+.. kernel-doc:: kernel/liveupdate/luo_files.c
+ :internal:
+
+See Also
+========
+
+- :doc:`Live Update uAPI </userspace-api/liveupdate>`
+- :doc:`Live Update SysFS </admin-guide/liveupdate>`
+- :doc:`/core-api/kho/concepts`
diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index b8c73be4fb11..ee8326932cb0 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -62,6 +62,7 @@ Everything else
ELF
netlink/index
+ liveupdate
sysfs-platform_profile
vduse
futex2
diff --git a/Documentation/userspace-api/liveupdate.rst b/Documentation/userspace-api/liveupdate.rst
new file mode 100644
index 000000000000..70b5017c0e3c
--- /dev/null
+++ b/Documentation/userspace-api/liveupdate.rst
@@ -0,0 +1,25 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================
+Live Update uAPI
+================
+:Author: Pasha Tatashin <pasha.tatashin@soleen.com>
+
+ioctl interface
+===============
+.. kernel-doc:: kernel/liveupdate/luo_ioctl.c
+ :doc: LUO ioctl Interface
+
+ioctl uAPI
+===========
+.. kernel-doc:: include/uapi/linux/liveupdate.h
+
+LUO selftests ioctl
+===================
+.. kernel-doc:: kernel/liveupdate/luo_selftests.c
+ :doc: LUO Selftests
+
+See Also
+========
+
+- :doc:`Live Update Orchestrator </core-api/liveupdate>`
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 22/32] selftests/liveupdate: add subsystem/state tests
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Introduces a new set of userspace selftests for the LUO. These tests
verify the functionality LUO by using the kernel-side selftest ioctls
provided by the LUO module, primarily focusing on subsystem management
and basic LUO state transitions.
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
tools/testing/selftests/Makefile | 1 +
tools/testing/selftests/liveupdate/.gitignore | 1 +
tools/testing/selftests/liveupdate/Makefile | 7 +
tools/testing/selftests/liveupdate/config | 6 +
.../testing/selftests/liveupdate/liveupdate.c | 356 ++++++++++++++++++
5 files changed, 371 insertions(+)
create mode 100644 tools/testing/selftests/liveupdate/.gitignore
create mode 100644 tools/testing/selftests/liveupdate/Makefile
create mode 100644 tools/testing/selftests/liveupdate/config
create mode 100644 tools/testing/selftests/liveupdate/liveupdate.c
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 339b31e6a6b5..d8fc84ccac32 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -53,6 +53,7 @@ TARGETS += kvm
TARGETS += landlock
TARGETS += lib
TARGETS += livepatch
+TARGETS += liveupdate
TARGETS += lkdtm
TARGETS += lsm
TARGETS += membarrier
diff --git a/tools/testing/selftests/liveupdate/.gitignore b/tools/testing/selftests/liveupdate/.gitignore
new file mode 100644
index 000000000000..af6e773cf98f
--- /dev/null
+++ b/tools/testing/selftests/liveupdate/.gitignore
@@ -0,0 +1 @@
+/liveupdate
diff --git a/tools/testing/selftests/liveupdate/Makefile b/tools/testing/selftests/liveupdate/Makefile
new file mode 100644
index 000000000000..2a573c36016e
--- /dev/null
+++ b/tools/testing/selftests/liveupdate/Makefile
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0-only
+CFLAGS += -Wall -O2 -Wno-unused-function
+CFLAGS += $(KHDR_INCLUDES)
+
+TEST_GEN_PROGS += liveupdate
+
+include ../lib.mk
diff --git a/tools/testing/selftests/liveupdate/config b/tools/testing/selftests/liveupdate/config
new file mode 100644
index 000000000000..382c85b89570
--- /dev/null
+++ b/tools/testing/selftests/liveupdate/config
@@ -0,0 +1,6 @@
+CONFIG_KEXEC_FILE=y
+CONFIG_KEXEC_HANDOVER=y
+CONFIG_KEXEC_HANDOVER_DEBUG=y
+CONFIG_LIVEUPDATE=y
+CONFIG_LIVEUPDATE_SYSFS_API=y
+CONFIG_LIVEUPDATE_SELFTESTS=y
diff --git a/tools/testing/selftests/liveupdate/liveupdate.c b/tools/testing/selftests/liveupdate/liveupdate.c
new file mode 100644
index 000000000000..989a9a67d4cf
--- /dev/null
+++ b/tools/testing/selftests/liveupdate/liveupdate.c
@@ -0,0 +1,356 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+/*
+ * Copyright (c) 2025, Google LLC.
+ * Pasha Tatashin <pasha.tatashin@soleen.com>
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+
+#include <linux/liveupdate.h>
+
+#include "../kselftest.h"
+#include "../kselftest_harness.h"
+#include "../../../../kernel/liveupdate/luo_selftests.h"
+
+struct subsystem_info {
+ void *data_page;
+ void *verify_page;
+ char test_name[LUO_NAME_LENGTH];
+ bool registered;
+};
+
+FIXTURE(subsystem) {
+ int fd;
+ int fd_dbg;
+ struct subsystem_info si[LUO_MAX_SUBSYSTEMS];
+};
+
+FIXTURE(state) {
+ int fd;
+ int fd_dbg;
+};
+
+#define LUO_DEVICE "/dev/liveupdate"
+#define LUO_DBG_DEVICE "/sys/kernel/debug/liveupdate/luo_selftest"
+#define LUO_SYSFS_STATE "/sys/kernel/liveupdate/state"
+static size_t page_size;
+
+const char *const luo_state_str[] = {
+ [LIVEUPDATE_STATE_UNDEFINED] = "undefined",
+ [LIVEUPDATE_STATE_NORMAL] = "normal",
+ [LIVEUPDATE_STATE_PREPARED] = "prepared",
+ [LIVEUPDATE_STATE_FROZEN] = "frozen",
+ [LIVEUPDATE_STATE_UPDATED] = "updated",
+};
+
+static int run_luo_selftest_cmd(int fd_dbg, __u64 cmd_code,
+ struct luo_arg_subsystem *subsys_arg)
+{
+ struct liveupdate_selftest k_arg;
+
+ k_arg.cmd = cmd_code;
+ k_arg.arg = (__u64)(unsigned long)subsys_arg;
+
+ return ioctl(fd_dbg, LIVEUPDATE_IOCTL_SELFTESTS, &k_arg);
+}
+
+static int register_subsystem(int fd_dbg, struct subsystem_info *si)
+{
+ struct luo_arg_subsystem subsys_arg;
+ int ret;
+
+ memset(&subsys_arg, 0, sizeof(subsys_arg));
+ snprintf(subsys_arg.name, LUO_NAME_LENGTH, "%s", si->test_name);
+ subsys_arg.data_page = si->data_page;
+
+ ret = run_luo_selftest_cmd(fd_dbg, LUO_CMD_SUBSYSTEM_REGISTER,
+ &subsys_arg);
+ if (!ret)
+ si->registered = true;
+
+ return ret;
+}
+
+static int unregister_subsystem(int fd_dbg, struct subsystem_info *si)
+{
+ struct luo_arg_subsystem subsys_arg;
+ int ret;
+
+ memset(&subsys_arg, 0, sizeof(subsys_arg));
+ snprintf(subsys_arg.name, LUO_NAME_LENGTH, "%s", si->test_name);
+
+ ret = run_luo_selftest_cmd(fd_dbg, LUO_CMD_SUBSYSTEM_UNREGISTER,
+ &subsys_arg);
+ if (!ret)
+ si->registered = false;
+
+ return ret;
+}
+
+static int get_sysfs_state(void)
+{
+ char buf[64];
+ ssize_t len;
+ int fd, i;
+
+ fd = open(LUO_SYSFS_STATE, O_RDONLY);
+ if (fd < 0) {
+ ksft_print_msg("Failed to open sysfs state file '%s': %s\n",
+ LUO_SYSFS_STATE, strerror(errno));
+ return -errno;
+ }
+
+ len = read(fd, buf, sizeof(buf) - 1);
+ close(fd);
+
+ if (len <= 0) {
+ ksft_print_msg("Failed to read sysfs state file '%s': %s\n",
+ LUO_SYSFS_STATE, strerror(errno));
+ return -errno;
+ }
+ if (buf[len - 1] == '\n')
+ buf[len - 1] = '\0';
+ else
+ buf[len] = '\0';
+
+ for (i = 0; i < ARRAY_SIZE(luo_state_str); i++) {
+ if (!strcmp(buf, luo_state_str[i]))
+ return i;
+ }
+
+ return -EIO;
+}
+
+FIXTURE_SETUP(state)
+{
+ int state;
+
+ page_size = sysconf(_SC_PAGE_SIZE);
+ self->fd = open(LUO_DEVICE, O_RDWR);
+ if (self->fd < 0)
+ SKIP(return, "open(%s) failed [%d]", LUO_DEVICE, errno);
+
+ self->fd_dbg = open(LUO_DBG_DEVICE, O_RDWR);
+ ASSERT_GE(self->fd_dbg, 0);
+
+ state = get_sysfs_state();
+ if (state < 0) {
+ if (state == -ENOENT || state == -EACCES)
+ SKIP(return, "sysfs state not accessible (%d)", state);
+ }
+}
+
+FIXTURE_TEARDOWN(state)
+{
+ enum liveupdate_state state = LIVEUPDATE_STATE_NORMAL;
+
+ ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state);
+ if (state != LIVEUPDATE_STATE_NORMAL)
+ ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL);
+ close(self->fd);
+}
+
+FIXTURE_SETUP(subsystem)
+{
+ int i;
+
+ page_size = sysconf(_SC_PAGE_SIZE);
+ memset(&self->si, 0, sizeof(self->si));
+ self->fd = open(LUO_DEVICE, O_RDWR);
+ if (self->fd < 0)
+ SKIP(return, "open(%s) failed [%d]", LUO_DEVICE, errno);
+
+ self->fd_dbg = open(LUO_DBG_DEVICE, O_RDWR);
+ ASSERT_GE(self->fd_dbg, 0);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++) {
+ snprintf(self->si[i].test_name, LUO_NAME_LENGTH,
+ NAME_NORMAL ".%d", i);
+
+ self->si[i].data_page = mmap(NULL, page_size,
+ PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS,
+ -1, 0);
+ ASSERT_NE(MAP_FAILED, self->si[i].data_page);
+ memset(self->si[i].data_page, 'A' + i, page_size);
+
+ self->si[i].verify_page = mmap(NULL, page_size,
+ PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS,
+ -1, 0);
+ ASSERT_NE(MAP_FAILED, self->si[i].verify_page);
+ memset(self->si[i].verify_page, 0, page_size);
+ }
+}
+
+FIXTURE_TEARDOWN(subsystem)
+{
+ enum liveupdate_state state = LIVEUPDATE_STATE_NORMAL;
+ int i;
+
+ ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state);
+ if (state != LIVEUPDATE_STATE_NORMAL)
+ ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++) {
+ if (self->si[i].registered)
+ unregister_subsystem(self->fd_dbg, &self->si[i]);
+ munmap(self->si[i].data_page, page_size);
+ munmap(self->si[i].verify_page, page_size);
+ }
+
+ close(self->fd);
+}
+
+TEST_F(state, normal)
+{
+ enum liveupdate_state state;
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state));
+ ASSERT_EQ(state, LIVEUPDATE_STATE_NORMAL);
+}
+
+TEST_F(state, prepared)
+{
+ enum liveupdate_state state;
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state));
+ ASSERT_EQ(state, LIVEUPDATE_STATE_PREPARED);
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL));
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state));
+ ASSERT_EQ(state, LIVEUPDATE_STATE_NORMAL);
+}
+
+TEST_F(state, sysfs_normal)
+{
+ ASSERT_EQ(LIVEUPDATE_STATE_NORMAL, get_sysfs_state());
+}
+
+TEST_F(state, sysfs_prepared)
+{
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+ ASSERT_EQ(LIVEUPDATE_STATE_PREPARED, get_sysfs_state());
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL));
+ ASSERT_EQ(LIVEUPDATE_STATE_NORMAL, get_sysfs_state());
+}
+
+TEST_F(state, sysfs_frozen)
+{
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+
+ ASSERT_EQ(LIVEUPDATE_STATE_PREPARED, get_sysfs_state());
+
+ ASSERT_EQ(0, ioctl(self->fd_dbg, LIVEUPDATE_IOCTL_FREEZE, NULL));
+ ASSERT_EQ(LIVEUPDATE_STATE_FROZEN, get_sysfs_state());
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL));
+ ASSERT_EQ(LIVEUPDATE_STATE_NORMAL, get_sysfs_state());
+}
+
+TEST_F(subsystem, register_unregister)
+{
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[0]));
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[0]));
+}
+
+TEST_F(subsystem, double_unregister)
+{
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[0]));
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[0]));
+ EXPECT_NE(0, unregister_subsystem(self->fd_dbg, &self->si[0]));
+ EXPECT_TRUE(errno == EINVAL || errno == ENOENT);
+}
+
+TEST_F(subsystem, register_unregister_many)
+{
+ int i;
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[i]));
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[i]));
+}
+
+TEST_F(subsystem, getdata_verify)
+{
+ enum liveupdate_state state;
+ int i;
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[i]));
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state));
+ ASSERT_EQ(state, LIVEUPDATE_STATE_PREPARED);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++) {
+ struct luo_arg_subsystem subsys_arg;
+
+ memset(&subsys_arg, 0, sizeof(subsys_arg));
+ snprintf(subsys_arg.name, LUO_NAME_LENGTH, "%s",
+ self->si[i].test_name);
+ subsys_arg.data_page = self->si[i].verify_page;
+
+ ASSERT_EQ(0, run_luo_selftest_cmd(self->fd_dbg,
+ LUO_CMD_SUBSYSTEM_GETDATA,
+ &subsys_arg));
+ ASSERT_EQ(0, memcmp(self->si[i].data_page,
+ self->si[i].verify_page,
+ page_size));
+ }
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL));
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_GET_STATE, &state));
+ ASSERT_EQ(state, LIVEUPDATE_STATE_NORMAL);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[i]));
+}
+
+TEST_F(subsystem, prepare_fail)
+{
+ int i;
+
+ snprintf(self->si[LUO_MAX_SUBSYSTEMS - 1].test_name, LUO_NAME_LENGTH,
+ NAME_PREPARE_FAIL ".%d", LUO_MAX_SUBSYSTEMS - 1);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[i]));
+
+ ASSERT_EQ(-1, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[i]));
+
+ snprintf(self->si[LUO_MAX_SUBSYSTEMS - 1].test_name, LUO_NAME_LENGTH,
+ NAME_NORMAL ".%d", LUO_MAX_SUBSYSTEMS - 1);
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, register_subsystem(self->fd_dbg, &self->si[i]));
+
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_PREPARE, NULL));
+ ASSERT_EQ(0, ioctl(self->fd_dbg, LIVEUPDATE_IOCTL_FREEZE, NULL));
+ ASSERT_EQ(0, ioctl(self->fd, LIVEUPDATE_IOCTL_CANCEL, NULL));
+ ASSERT_EQ(LIVEUPDATE_STATE_NORMAL, get_sysfs_state());
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++)
+ ASSERT_EQ(0, unregister_subsystem(self->fd_dbg, &self->si[i]));
+}
+
+TEST_HARNESS_MAIN
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 21/32] liveupdate: add selftests for subsystems un/registration
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Introduce a self-test mechanism for the LUO to allow verification of
core subsystem management functionality. This is primarily intended
for developers and system integrators validating the live update
feature.
The tests are enabled via the new Kconfig option
CONFIG_LIVEUPDATE_SELFTESTS (default 'n') and are triggered through
a new ioctl command, LIVEUPDATE_IOCTL_SELFTESTS, added to the
/dev/liveupdate device node.
This ioctl accepts commands defined in luo_selftests.h to:
- LUO_CMD_SUBSYSTEM_REGISTER: Creates and registers a dummy LUO
subsystem using the liveupdate_register_subsystem() function. It
allocates a data page and copies initial data from userspace.
- LUO_CMD_SUBSYSTEM_UNREGISTER: Unregisters the specified dummy
subsystem using the liveupdate_unregister_subsystem() function and
cleans up associated test resources.
- LUO_CMD_SUBSYSTEM_GETDATA: Copies the data page associated with a
registered test subsystem back to userspace, allowing verification of
data potentially modified or preserved by test callbacks.
This provides a way to test the fundamental registration and
unregistration flows within the LUO framework from userspace without
requiring a full live update sequence.
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
kernel/liveupdate/Kconfig | 15 ++
kernel/liveupdate/Makefile | 1 +
kernel/liveupdate/luo_selftests.c | 344 ++++++++++++++++++++++++++++++
kernel/liveupdate/luo_selftests.h | 84 ++++++++
4 files changed, 444 insertions(+)
create mode 100644 kernel/liveupdate/luo_selftests.c
create mode 100644 kernel/liveupdate/luo_selftests.h
diff --git a/kernel/liveupdate/Kconfig b/kernel/liveupdate/Kconfig
index 75a17ca8a592..5be04ede357d 100644
--- a/kernel/liveupdate/Kconfig
+++ b/kernel/liveupdate/Kconfig
@@ -47,6 +47,21 @@ config LIVEUPDATE_SYSFS_API
If unsure, say N.
+config LIVEUPDATE_SELFTESTS
+ bool "Live Update Orchestrator - self-tests"
+ depends on LIVEUPDATE
+ help
+ Say Y here to build self-tests for the LUO framework. When enabled,
+ these tests can be initiated via the ioctl interface to help verify
+ the core live update functionality.
+
+ This option is primarily intended for developers working on the
+ live update feature or for validation purposes during system
+ integration.
+
+ If you are unsure or are building a production kernel where size
+ or attack surface is a concern, say N.
+
config KEXEC_HANDOVER
bool "kexec handover"
depends on ARCH_SUPPORTS_KEXEC_HANDOVER && ARCH_SUPPORTS_KEXEC_FILE
diff --git a/kernel/liveupdate/Makefile b/kernel/liveupdate/Makefile
index e35ddc51ab2b..dfb63414cab2 100644
--- a/kernel/liveupdate/Makefile
+++ b/kernel/liveupdate/Makefile
@@ -7,6 +7,7 @@ obj-$(CONFIG_KEXEC_HANDOVER) += kexec_handover.o
obj-$(CONFIG_KEXEC_HANDOVER_DEBUG) += kexec_handover_debug.o
obj-$(CONFIG_LIVEUPDATE) += luo_core.o
obj-$(CONFIG_LIVEUPDATE) += luo_files.o
+obj-$(CONFIG_LIVEUPDATE_SELFTESTS) += luo_selftests.o
obj-$(CONFIG_LIVEUPDATE) += luo_ioctl.o
obj-$(CONFIG_LIVEUPDATE) += luo_subsystems.o
obj-$(CONFIG_LIVEUPDATE_SYSFS_API) += luo_sysfs.o
diff --git a/kernel/liveupdate/luo_selftests.c b/kernel/liveupdate/luo_selftests.c
new file mode 100644
index 000000000000..a198195fd1a5
--- /dev/null
+++ b/kernel/liveupdate/luo_selftests.c
@@ -0,0 +1,344 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright (c) 2025, Google LLC.
+ * Pasha Tatashin <pasha.tatashin@soleen.com>
+ */
+
+/**
+ * DOC: LUO Selftests
+ *
+ * We provide ioctl-based selftest interface for the LUO. It provides a
+ * mechanism to test core LUO functionality, particularly the registration,
+ * unregistration, and data handling aspects of LUO subsystems, without
+ * requiring a full live update event sequence.
+ *
+ * The tests are intended primarily for developers working on the LUO framework
+ * or for validation purposes during system integration. This functionality is
+ * conditionally compiled based on the `CONFIG_LIVEUPDATE_SELFTESTS` Kconfig
+ * option and should typically be disabled in production kernels.
+ *
+ * Interface:
+ * The selftests are accessed via the `/dev/liveupdate` character device using
+ * the `LIVEUPDATE_IOCTL_SELFTESTS` ioctl command. The argument to the ioctl
+ * is a pointer to a `struct liveupdate_selftest` structure (defined in
+ * `uapi/linux/liveupdate.h`), which contains:
+ * - `cmd`: The specific selftest command to execute (e.g.,
+ * `LUO_CMD_SUBSYSTEM_REGISTER`).
+ * - `arg`: A pointer to a command-specific argument structure. For subsystem
+ * tests, this points to a `struct luo_arg_subsystem` (defined in
+ * `luo_selftests.h`).
+ *
+ * Commands:
+ * - `LUO_CMD_SUBSYSTEM_REGISTER`:
+ * Registers a new dummy LUO subsystem. It allocates kernel memory for test
+ * data, copies initial data from the user-provided `data_page`, sets up
+ * simple logging callbacks, and calls the core
+ * `liveupdate_register_subsystem()`
+ * function. Requires `arg` pointing to `struct luo_arg_subsystem`.
+ * - `LUO_CMD_SUBSYSTEM_UNREGISTER`:
+ * Unregisters a previously registered dummy subsystem identified by `name`.
+ * It calls the core `liveupdate_unregister_subsystem()` function and then
+ * frees the associated kernel memory and internal tracking structures.
+ * Requires `arg` pointing to `struct luo_arg_subsystem` (only `name` used).
+ * - `LUO_CMD_SUBSYSTEM_GETDATA`:
+ * Copies the content of the kernel data page associated with the specified
+ * dummy subsystem (`name`) back to the user-provided `data_page`. This allows
+ * userspace to verify the state of the data after potential test operations.
+ * Requires `arg` pointing to `struct luo_arg_subsystem`.
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/debugfs.h>
+#include <linux/errno.h>
+#include <linux/gfp.h>
+#include <linux/kexec_handover.h>
+#include <linux/liveupdate.h>
+#include <linux/mutex.h>
+#include <linux/uaccess.h>
+#include <uapi/linux/liveupdate.h>
+#include "luo_internal.h"
+#include "luo_selftests.h"
+
+static struct luo_subsystems {
+ struct liveupdate_subsystem handle;
+ char name[LUO_NAME_LENGTH];
+ void *data;
+ bool in_use;
+ bool preserved;
+} luo_subsystems[LUO_MAX_SUBSYSTEMS];
+
+/* Only allow one selftest ioctl operation at a time */
+static DEFINE_MUTEX(luo_ioctl_mutex);
+
+static int luo_subsystem_prepare(void *arg, u64 *data)
+{
+ unsigned long i = (unsigned long)arg;
+ unsigned long phys_addr = __pa(luo_subsystems[i].data);
+ int ret;
+
+ ret = kho_preserve_phys(phys_addr, PAGE_SIZE);
+ if (ret)
+ return ret;
+
+ luo_subsystems[i].preserved = true;
+ *data = phys_addr;
+ pr_info("Subsystem '%s' prepare data[%lx]\n",
+ luo_subsystems[i].name, phys_addr);
+
+ if (strstr(luo_subsystems[i].name, NAME_PREPARE_FAIL))
+ return -EAGAIN;
+
+ return 0;
+}
+
+static int luo_subsystem_freeze(void *arg, u64 *data)
+{
+ unsigned long i = (unsigned long)arg;
+
+ pr_info("Subsystem '%s' freeze data[%llx]\n",
+ luo_subsystems[i].name, *data);
+
+ return 0;
+}
+
+static void luo_subsystem_cancel(void *arg, u64 data)
+{
+ unsigned long i = (unsigned long)arg;
+
+ pr_info("Subsystem '%s' canel data[%llx]\n",
+ luo_subsystems[i].name, data);
+ luo_subsystems[i].preserved = false;
+ WARN_ON(kho_unpreserve_phys(data, PAGE_SIZE));
+}
+
+static void luo_subsystem_finish(void *arg, u64 data)
+{
+ unsigned long i = (unsigned long)arg;
+
+ pr_info("Subsystem '%s' finish data[%llx]\n",
+ luo_subsystems[i].name, data);
+}
+
+static const struct liveupdate_subsystem_ops luo_selftest_subsys_ops = {
+ .prepare = luo_subsystem_prepare,
+ .freeze = luo_subsystem_freeze,
+ .cancel = luo_subsystem_cancel,
+ .finish = luo_subsystem_finish,
+};
+
+static int luo_subsystem_idx(char *name)
+{
+ int i;
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++) {
+ if (luo_subsystems[i].in_use &&
+ !strcmp(luo_subsystems[i].name, name))
+ break;
+ }
+
+ if (i == LUO_MAX_SUBSYSTEMS) {
+ pr_warn("Subsystem with name '%s' is not registred\n", name);
+
+ return -EINVAL;
+ }
+
+ return i;
+}
+
+static void luo_put_and_free_subsystem(char *name)
+{
+ int i = luo_subsystem_idx(name);
+
+ if (i < 0)
+ return;
+
+ if (luo_subsystems[i].preserved)
+ kho_unpreserve_phys(__pa(luo_subsystems[i].data), PAGE_SIZE);
+ free_page((unsigned long)luo_subsystems[i].data);
+ luo_subsystems[i].in_use = false;
+ luo_subsystems[i].preserved = false;
+}
+
+static int luo_get_and_alloc_subsystem(char *name, void __user *data,
+ struct liveupdate_subsystem **hp)
+{
+ unsigned long page_addr, i;
+
+ page_addr = get_zeroed_page(GFP_KERNEL);
+ if (!page_addr) {
+ pr_warn("Failed to allocate memory for subsystem data\n");
+ return -ENOMEM;
+ }
+
+ if (copy_from_user((void *)page_addr, data, PAGE_SIZE)) {
+ free_page(page_addr);
+ return -EFAULT;
+ }
+
+ for (i = 0; i < LUO_MAX_SUBSYSTEMS; i++) {
+ if (!luo_subsystems[i].in_use)
+ break;
+ }
+
+ if (i == LUO_MAX_SUBSYSTEMS) {
+ pr_warn("Maximum number of subsystems registered\n");
+ free_page(page_addr);
+ return -ENOMEM;
+ }
+
+ luo_subsystems[i].in_use = true;
+ luo_subsystems[i].handle.ops = &luo_selftest_subsys_ops;
+ luo_subsystems[i].handle.name = luo_subsystems[i].name;
+ luo_subsystems[i].handle.arg = (void *)i;
+ strscpy(luo_subsystems[i].name, name, LUO_NAME_LENGTH);
+ luo_subsystems[i].data = (void *)page_addr;
+
+ *hp = &luo_subsystems[i].handle;
+
+ return 0;
+}
+
+static int luo_cmd_subsystem_unregister(void __user *argp)
+{
+ struct luo_arg_subsystem arg;
+ int ret, i;
+
+ if (copy_from_user(&arg, argp, sizeof(arg)))
+ return -EFAULT;
+
+ i = luo_subsystem_idx(arg.name);
+ if (i < 0)
+ return i;
+
+ ret = liveupdate_unregister_subsystem(&luo_subsystems[i].handle);
+ if (ret)
+ return ret;
+
+ luo_put_and_free_subsystem(arg.name);
+
+ return 0;
+}
+
+static int luo_cmd_subsystem_register(void __user *argp)
+{
+ struct liveupdate_subsystem *h;
+ struct luo_arg_subsystem arg;
+ int ret;
+
+ if (copy_from_user(&arg, argp, sizeof(arg)))
+ return -EFAULT;
+
+ ret = luo_get_and_alloc_subsystem(arg.name,
+ (void __user *)arg.data_page, &h);
+ if (ret)
+ return ret;
+
+ ret = liveupdate_register_subsystem(h);
+ if (ret)
+ luo_put_and_free_subsystem(arg.name);
+
+ return ret;
+}
+
+static int luo_cmd_subsystem_getdata(void __user *argp)
+{
+ struct luo_arg_subsystem arg;
+ int i;
+
+ if (copy_from_user(&arg, argp, sizeof(arg)))
+ return -EFAULT;
+
+ i = luo_subsystem_idx(arg.name);
+ if (i < 0)
+ return i;
+
+ if (copy_to_user(arg.data_page, luo_subsystems[i].data,
+ PAGE_SIZE)) {
+ return -EFAULT;
+ }
+
+ return 0;
+}
+
+static int luo_ioctl_selftests(void __user *argp)
+{
+ struct liveupdate_selftest luo_st;
+ void __user *cmd_argp;
+ int ret = 0;
+
+ if (copy_from_user(&luo_st, argp, sizeof(luo_st)))
+ return -EFAULT;
+
+ cmd_argp = (void __user *)luo_st.arg;
+
+ mutex_lock(&luo_ioctl_mutex);
+ switch (luo_st.cmd) {
+ case LUO_CMD_SUBSYSTEM_REGISTER:
+ ret = luo_cmd_subsystem_register(cmd_argp);
+ break;
+
+ case LUO_CMD_SUBSYSTEM_UNREGISTER:
+ ret = luo_cmd_subsystem_unregister(cmd_argp);
+ break;
+
+ case LUO_CMD_SUBSYSTEM_GETDATA:
+ ret = luo_cmd_subsystem_getdata(cmd_argp);
+ break;
+
+ default:
+ pr_warn("ioctl: unknown self-test command nr: 0x%llx\n",
+ luo_st.cmd);
+ ret = -ENOTTY;
+ break;
+ }
+ mutex_unlock(&luo_ioctl_mutex);
+
+ return ret;
+}
+
+static long luo_selftest_ioctl(struct file *filep, unsigned int cmd,
+ unsigned long arg)
+{
+ int ret = 0;
+
+ if (_IOC_TYPE(cmd) != LIVEUPDATE_IOCTL_TYPE)
+ return -ENOTTY;
+
+ switch (cmd) {
+ case LIVEUPDATE_IOCTL_FREEZE:
+ ret = luo_freeze();
+ break;
+
+ case LIVEUPDATE_IOCTL_SELFTESTS:
+ ret = luo_ioctl_selftests((void __user *)arg);
+ break;
+
+ default:
+ pr_warn("ioctl: unknown command nr: 0x%x\n", _IOC_NR(cmd));
+ ret = -ENOTTY;
+ break;
+ }
+
+ return ret;
+}
+
+static const struct file_operations luo_selftest_fops = {
+ .open = nonseekable_open,
+ .unlocked_ioctl = luo_selftest_ioctl,
+};
+
+static int __init luo_seltesttest_init(void)
+{
+ if (!liveupdate_debugfs_root) {
+ pr_err("liveupdate root is not set\n");
+ return 0;
+ }
+ debugfs_create_file_unsafe("luo_selftest", 0600,
+ liveupdate_debugfs_root, NULL,
+ &luo_selftest_fops);
+ return 0;
+}
+
+late_initcall(luo_seltesttest_init);
diff --git a/kernel/liveupdate/luo_selftests.h b/kernel/liveupdate/luo_selftests.h
new file mode 100644
index 000000000000..098f2e9e6a78
--- /dev/null
+++ b/kernel/liveupdate/luo_selftests.h
@@ -0,0 +1,84 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (c) 2025, Google LLC.
+ * Pasha Tatashin <pasha.tatashin@soleen.com>
+ */
+
+#ifndef _LINUX_LUO_SELFTESTS_H
+#define _LINUX_LUO_SELFTESTS_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/* Maximum number of subsystem self-test can register */
+#define LUO_MAX_SUBSYSTEMS 16
+#define LUO_NAME_LENGTH 32
+
+#define LUO_CMD_SUBSYSTEM_REGISTER 0
+#define LUO_CMD_SUBSYSTEM_UNREGISTER 1
+#define LUO_CMD_SUBSYSTEM_GETDATA 2
+struct luo_arg_subsystem {
+ char name[LUO_NAME_LENGTH];
+ void *data_page;
+};
+
+/*
+ * Test name prefixes:
+ * normal: prepare and freeze callbacks do not fail
+ * prepare_fail: prepare callback fails for this test.
+ * freeze_fail: freeze callback fails for this test
+ */
+#define NAME_NORMAL "ksft_luo"
+#define NAME_PREPARE_FAIL "ksft_prepare_fail"
+#define NAME_FREEZE_FAIL "ksft_freeze_fail"
+
+/**
+ * struct liveupdate_selftest - Holds directions for the self-test operations.
+ * @cmd: Selftest comman defined in luo_selftests.h.
+ * @arg: Argument for the self test command.
+ *
+ * This structure is used only for the selftest purposes.
+ */
+struct liveupdate_selftest {
+ __u64 cmd;
+ __u64 arg;
+};
+
+/**
+ * LIVEUPDATE_IOCTL_FREEZE - Notify subsystems of imminent reboot
+ * transition.
+ *
+ * Argument: None.
+ *
+ * Notifies the live update subsystem and associated components that the kernel
+ * is about to execute the final reboot transition into the new kernel (e.g.,
+ * via kexec). This action triggers the internal %LIVEUPDATE_FREEZE kernel
+ * event. This event provides subsystems a final, brief opportunity (within the
+ * "blackout window") to save critical state or perform last-moment quiescing.
+ * Any remaining or deferred state saving for items marked via the PRESERVE
+ * ioctls typically occurs in response to the %LIVEUPDATE_FREEZE event.
+ *
+ * This ioctl should only be called when the system is in the
+ * %LIVEUPDATE_STATE_PREPARED state. This command does not transfer data.
+ *
+ * Return: 0 if the notification is successfully processed by the kernel (but
+ * reboot follows). Returns a negative error code if the notification fails
+ * or if the system is not in the %LIVEUPDATE_STATE_PREPARED state.
+ */
+#define LIVEUPDATE_IOCTL_FREEZE \
+ _IO(LIVEUPDATE_IOCTL_TYPE, 0x05)
+
+/**
+ * LIVEUPDATE_IOCTL_SELFTESTS - Interface for the LUO selftests
+ *
+ * Argument: Pointer to &struct liveupdate_selftest.
+ *
+ * Use by LUO selftests, commands are declared in luo_selftests.h
+ *
+ * Return: 0 on success, negative error code on failure (e.g., invalid token).
+ */
+#define LIVEUPDATE_IOCTL_SELFTESTS \
+ _IOWR(LIVEUPDATE_IOCTL_TYPE, 0x08, struct liveupdate_selftest)
+
+#endif /* _LINUX_LUO_SELFTESTS_H */
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 20/32] kho: move kho debugfs directory to liveupdate
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Now, that LUO and KHO both live under kernel/liveupdate, it makes
sense to also move the kho debugfs files to liveupdate/
The old names:
/sys/kernel/debug/kho/out/
/sys/kernel/debug/kho/in/
The new names:
/sys/kernel/debug/liveupdate/kho_out/
/sys/kernel/debug/liveupdate/kho_in/
Also, export the liveupdate_debufs_root, so LUO selftests could use
it as well.
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
kernel/liveupdate/kexec_handover_debug.c | 11 ++++++-----
kernel/liveupdate/luo_internal.h | 4 ++++
2 files changed, 10 insertions(+), 5 deletions(-)
diff --git a/kernel/liveupdate/kexec_handover_debug.c b/kernel/liveupdate/kexec_handover_debug.c
index af4bad225630..f06d6cdfeab3 100644
--- a/kernel/liveupdate/kexec_handover_debug.c
+++ b/kernel/liveupdate/kexec_handover_debug.c
@@ -14,8 +14,9 @@
#include <linux/libfdt.h>
#include <linux/mm.h>
#include "kexec_handover_internal.h"
+#include "luo_internal.h"
-static struct dentry *debugfs_root;
+struct dentry *liveupdate_debugfs_root;
struct fdt_debugfs {
struct list_head list;
@@ -120,7 +121,7 @@ __init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt)
INIT_LIST_HEAD(&dbg->fdt_list);
- dir = debugfs_create_dir("in", debugfs_root);
+ dir = debugfs_create_dir("in", liveupdate_debugfs_root);
if (IS_ERR(dir)) {
err = PTR_ERR(dir);
goto err_out;
@@ -180,7 +181,7 @@ __init int kho_out_debugfs_init(struct kho_debugfs *dbg)
INIT_LIST_HEAD(&dbg->fdt_list);
- dir = debugfs_create_dir("out", debugfs_root);
+ dir = debugfs_create_dir("out", liveupdate_debugfs_root);
if (IS_ERR(dir))
return -ENOMEM;
@@ -214,8 +215,8 @@ __init int kho_out_debugfs_init(struct kho_debugfs *dbg)
__init int kho_debugfs_init(void)
{
- debugfs_root = debugfs_create_dir("kho", NULL);
- if (IS_ERR(debugfs_root))
+ liveupdate_debugfs_root = debugfs_create_dir("liveupdate", NULL);
+ if (IS_ERR(liveupdate_debugfs_root))
return -ENOENT;
return 0;
}
diff --git a/kernel/liveupdate/luo_internal.h b/kernel/liveupdate/luo_internal.h
index 8fef414e7e3e..fbb9c6642d19 100644
--- a/kernel/liveupdate/luo_internal.h
+++ b/kernel/liveupdate/luo_internal.h
@@ -40,4 +40,8 @@ void luo_sysfs_notify(void);
static inline void luo_sysfs_notify(void) {}
#endif
+#ifdef CONFIG_KEXEC_HANDOVER_DEBUG
+extern struct dentry *liveupdate_debugfs_root;
+#endif
+
#endif /* _LINUX_LUO_INTERNAL_H */
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
* [PATCH v2 19/32] liveupdate: luo_files: luo_ioctl: session-based file descriptor tracking
From: Pasha Tatashin @ 2025-07-23 14:46 UTC (permalink / raw)
To: pratyush, jasonmiu, graf, changyuanl, pasha.tatashin, rppt,
dmatlack, rientjes, corbet, rdunlap, ilpo.jarvinen, kanie, ojeda,
aliceryhl, masahiroy, akpm, tj, yoann.congal, mmaurer,
roman.gushchin, chenridong, axboe, mark.rutland, jannh,
vincent.guittot, hannes, dan.j.williams, david, joel.granados,
rostedt, anna.schumaker, song, zhangguopeng, linux, linux-kernel,
linux-doc, linux-mm, gregkh, tglx, mingo, bp, dave.hansen, x86,
hpa, rafael, dakr, bartosz.golaszewski, cw00.choi, myungjoo.ham,
yesanishhere, Jonathan.Cameron, quic_zijuhu, aleksander.lobakin,
ira.weiny, andriy.shevchenko, leon, lukas, bhelgaas, wagi,
djeffery, stuart.w.hayes, ptyadav, lennart, brauner, linux-api,
linux-fsdevel, saeedm, ajayachandra, jgg, parav, leonro, witu
In-Reply-To: <20250723144649.1696299-1-pasha.tatashin@soleen.com>
Currently, file descriptors registered for preservation via
/dev/liveupdate remain globally registered with the LUO core until
explicitly unregistered. This behavior can lead to unintended
consequences: if a userspace process (e.g., a VMM or
an agent managing FDs) registers FDs for preservation and then crashes
or exits prematurely before LUO transitions to a PREPARED state (and
without explicitly unregistering them), these FDs would remain marked
for preservation. This could result in unnecessary resources being
carried over to the next kernel or stale state or leaks.
Introduce a session-based approach to FD preservation to address this
issue. Each open instance of /dev/liveupdate now corresponds to a "LUO
session," which tracks the FDs registered through it. If a LUO session
is closed (i.e., the file descriptor for /dev/liveupdate is closed by
userspace) while LUO is still in the NORMAL or UPDATED state, all FDs
registered during that specific session are automatically unregistered.
This ensures that FD preservations are tied to the lifetime of the
controlling userspace entity's session, preventing unintentional leakage
of preserved FD state into the next kernel if the live update process
is not fully initiated and completed for those FDs. FDs are only
globally committed for preservation if the LUO state machine progresses
beyond NORMAL (i.e., into PREPARED or FROZEN) before the managing
session is closed. In the future, we can relax this even further, and
preserve only when the session is still open while we are already in
reboot() system call.
Signed-off-by: Pasha Tatashin <pasha.tatashin@soleen.com>
---
kernel/liveupdate/luo_files.c | 225 ++++++++++++++++++++++++-------
kernel/liveupdate/luo_internal.h | 9 +-
kernel/liveupdate/luo_ioctl.c | 20 ++-
3 files changed, 197 insertions(+), 57 deletions(-)
diff --git a/kernel/liveupdate/luo_files.c b/kernel/liveupdate/luo_files.c
index cd956ea69f43..256b5261f81e 100644
--- a/kernel/liveupdate/luo_files.c
+++ b/kernel/liveupdate/luo_files.c
@@ -67,7 +67,6 @@
#define LUO_FILES_COMPATIBLE "file-descriptors-v1"
static DEFINE_XARRAY(luo_files_xa_in);
-static DEFINE_XARRAY(luo_files_xa_out);
static bool luo_files_xa_in_recreated;
/* Registered files. */
@@ -81,6 +80,15 @@ static size_t luo_file_fdt_out_size;
static atomic64_t luo_files_count;
+/* Opened sessions */
+static DECLARE_RWSEM(luo_sessions_list_rwsem);
+static LIST_HEAD(luo_sessions_list);
+
+struct luo_session {
+ struct xarray files_xa_out;
+ struct list_head list;
+};
+
/**
* struct luo_file - Represents a file descriptor instance preserved
* across live update.
@@ -262,6 +270,7 @@ static int luo_files_to_fdt(struct xarray *files_xa_out)
static int luo_files_fdt_setup(void)
{
+ struct luo_session *s;
int ret;
luo_file_fdt_out_size = luo_files_fdt_size();
@@ -300,9 +309,15 @@ static int luo_files_fdt_setup(void)
if (ret < 0)
goto exit_end_node;
- ret = luo_files_to_fdt(&luo_files_xa_out);
- if (ret < 0)
- goto exit_end_node;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ ret = luo_files_to_fdt(&s->files_xa_out);
+ if (ret < 0) {
+ up_read(&luo_sessions_list_rwsem);
+ goto exit_end_node;
+ }
+ }
+ up_read(&luo_sessions_list_rwsem);
ret = fdt_end_node(luo_file_fdt_out);
if (ret < 0)
@@ -405,44 +420,59 @@ static void luo_files_cancel_one(struct luo_file *h)
static void __luo_files_cancel(struct luo_file *boundary_file)
{
+ struct luo_session *s;
unsigned long token;
struct luo_file *h;
- xa_for_each(&luo_files_xa_out, token, h) {
- if (h == boundary_file)
- break;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ xa_for_each(&s->files_xa_out, token, h) {
+ if (h == boundary_file)
+ goto exit;
- luo_files_cancel_one(h);
+ luo_files_cancel_one(h);
+ }
}
+exit:
+ up_read(&luo_sessions_list_rwsem);
luo_files_fdt_cleanup();
}
static int luo_files_commit_data_to_fdt(void)
{
+ struct luo_session *s;
int node_offset, ret;
unsigned long token;
char token_str[19];
struct luo_file *h;
- xa_for_each(&luo_files_xa_out, token, h) {
- snprintf(token_str, sizeof(token_str), "%#0llx", (u64)token);
- node_offset = fdt_subnode_offset(luo_file_fdt_out,
- 0,
- token_str);
- ret = fdt_setprop(luo_file_fdt_out, node_offset, "data",
- &h->private_data, sizeof(h->private_data));
- if (ret < 0) {
- pr_err("Failed to set data property for token %s: %s\n",
- token_str, fdt_strerror(ret));
- return -ENOSPC;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ xa_for_each(&s->files_xa_out, token, h) {
+ snprintf(token_str, sizeof(token_str), "%#0llx",
+ (u64)token);
+ node_offset = fdt_subnode_offset(luo_file_fdt_out,
+ 0, token_str);
+ ret = fdt_setprop(luo_file_fdt_out, node_offset, "data",
+ &h->private_data,
+ sizeof(h->private_data));
+ if (ret < 0) {
+ up_read(&luo_sessions_list_rwsem);
+ pr_err("Failed to set data property for token %s: %s\n",
+ token_str, fdt_strerror(ret));
+ up_read(&luo_sessions_list_rwsem);
+ return -ENOSPC;
+ }
}
}
+ up_read(&luo_sessions_list_rwsem);
return 0;
}
static int luo_files_prepare(void *arg, u64 *data)
{
+ struct luo_session *s;
unsigned long token;
struct luo_file *h;
int ret;
@@ -451,16 +481,21 @@ static int luo_files_prepare(void *arg, u64 *data)
if (ret)
return ret;
- xa_for_each(&luo_files_xa_out, token, h) {
- ret = luo_files_prepare_one(h);
- if (ret < 0) {
- pr_err("Prepare failed for file token %#0llx handler '%s' [%d]\n",
- (u64)token, h->fh->compatible, ret);
- __luo_files_cancel(h);
-
- return ret;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ xa_for_each(&s->files_xa_out, token, h) {
+ ret = luo_files_prepare_one(h);
+ if (ret < 0) {
+ pr_err("Prepare failed for file token %#0llx handler '%s' [%d]\n",
+ (u64)token, h->fh->compatible, ret);
+ __luo_files_cancel(h);
+ up_read(&luo_sessions_list_rwsem);
+
+ return ret;
+ }
}
}
+ up_read(&luo_sessions_list_rwsem);
ret = luo_files_commit_data_to_fdt();
if (ret)
@@ -473,20 +508,26 @@ static int luo_files_prepare(void *arg, u64 *data)
static int luo_files_freeze(void *arg, u64 *data)
{
+ struct luo_session *s;
unsigned long token;
struct luo_file *h;
int ret;
- xa_for_each(&luo_files_xa_out, token, h) {
- ret = luo_files_freeze_one(h);
- if (ret < 0) {
- pr_err("Freeze callback failed for file token %#0llx handler '%s' [%d]\n",
- (u64)token, h->fh->compatible, ret);
- __luo_files_cancel(h);
-
- return ret;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ xa_for_each(&s->files_xa_out, token, h) {
+ ret = luo_files_freeze_one(h);
+ if (ret < 0) {
+ pr_err("Freeze callback failed for file token %#0llx handler '%s' [%d]\n",
+ (u64)token, h->fh->compatible, ret);
+ __luo_files_cancel(h);
+ up_read(&luo_sessions_list_rwsem);
+
+ return ret;
+ }
}
}
+ up_read(&luo_sessions_list_rwsem);
ret = luo_files_commit_data_to_fdt();
if (ret)
@@ -561,6 +602,7 @@ late_initcall(luo_files_startup);
/**
* luo_register_file - Register a file descriptor for live update management.
+ * @s: Session for the file that is being registered
* @token: Token value for this file descriptor.
* @fd: file descriptor to be preserved.
*
@@ -568,10 +610,11 @@ late_initcall(luo_files_startup);
*
* Return: 0 on success. Negative errno on failure.
*/
-int luo_register_file(u64 token, int fd)
+int luo_register_file(struct luo_session *s, u64 token, int fd)
{
struct liveupdate_file_handler *fh;
struct luo_file *luo_file;
+ struct luo_session *_s;
bool found = false;
int ret = -ENOENT;
struct file *file;
@@ -615,15 +658,20 @@ int luo_register_file(u64 token, int fd)
mutex_init(&luo_file->mutex);
luo_file->state = LIVEUPDATE_STATE_NORMAL;
- if (xa_load(&luo_files_xa_out, token)) {
- ret = -EEXIST;
- pr_warn("Token %llu is already taken\n", token);
- mutex_destroy(&luo_file->mutex);
- kfree(luo_file);
- goto exit_unlock;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(_s, &luo_sessions_list, list) {
+ if (xa_load(&_s->files_xa_out, token)) {
+ up_read(&luo_sessions_list_rwsem);
+ ret = -EEXIST;
+ pr_warn("Token %llu is already taken\n", token);
+ mutex_destroy(&luo_file->mutex);
+ kfree(luo_file);
+ goto exit_unlock;
+ }
}
+ up_read(&luo_sessions_list_rwsem);
- ret = xa_err(xa_store(&luo_files_xa_out, token, luo_file,
+ ret = xa_err(xa_store(&s->files_xa_out, token, luo_file,
GFP_KERNEL));
if (ret < 0) {
pr_warn("Failed to store file for token %llu in XArray: %d\n",
@@ -646,6 +694,7 @@ int luo_register_file(u64 token, int fd)
/**
* luo_unregister_file - Unregister a file instance using its token.
+ * @s: Session for the file that is being registered.
* @token: The unique token of the file instance to unregister.
*
* Finds the &struct luo_file associated with the @token in the
@@ -659,7 +708,7 @@ int luo_register_file(u64 token, int fd)
*
* Return: 0 on success. Negative errno on failure.
*/
-int luo_unregister_file(u64 token)
+int luo_unregister_file(struct luo_session *s, u64 token)
{
struct luo_file *luo_file;
int ret = 0;
@@ -671,7 +720,7 @@ int luo_unregister_file(u64 token)
return -EBUSY;
}
- luo_file = xa_erase(&luo_files_xa_out, token);
+ luo_file = xa_erase(&s->files_xa_out, token);
if (luo_file) {
fput(luo_file->file);
mutex_destroy(&luo_file->mutex);
@@ -736,6 +785,74 @@ int luo_retrieve_file(u64 token, struct file **filep)
return ret;
}
+/**
+ * luo_create_session - Create and register a new LUO file preservation session.
+ *
+ * This function is called when a userspace process opens the /dev/liveupdate
+ * character device.
+ *
+ * Each session allows a specific open instance of /dev/liveupdate to
+ * independently register file descriptors for preservation. These registrations
+ * are local to the session until LUO's prepare phase aggregates them.
+ * If the /dev/liveupdate file descriptor is closed while LUO is still in
+ * the NORMAL or UPDATES states, all file descriptors registered within that
+ * session will be automatically unregistered by luo_destroy_session().
+ *
+ * Return: Pointer to the newly allocated &struct luo_session on success,
+ * NULL on memory allocation failure.
+ */
+struct luo_session *luo_create_session(void)
+{
+ struct luo_session *s;
+
+ s = kmalloc(sizeof(struct luo_session), GFP_KERNEL);
+ if (s) {
+ xa_init(&s->files_xa_out);
+ INIT_LIST_HEAD(&s->list);
+
+ down_write(&luo_sessions_list_rwsem);
+ list_add_tail(&s->list, &luo_sessions_list);
+ up_write(&luo_sessions_list_rwsem);
+ }
+
+ return s;
+}
+
+/**
+ * luo_destroy_session - Release a LUO file preservation session.
+ * @s: Pointer to the &struct luo_session to be destroyed, previously obtained
+ * from luo_create_session().
+ *
+ * This function must be called when a userspace file descriptor for
+ * /dev/liveupdate is being closed (typically from the .release file
+ * operation). It is responsible for cleaning up all resources associated
+ * with the given LUO session @s.
+ */
+void luo_destroy_session(struct luo_session *s)
+{
+ unsigned long token;
+ struct luo_file *h;
+
+ down_write(&luo_sessions_list_rwsem);
+ list_del(&s->list);
+ up_write(&luo_sessions_list_rwsem);
+
+ luo_state_read_enter();
+ if (!liveupdate_state_normal() && !liveupdate_state_updated()) {
+ luo_state_read_exit();
+ goto skip_unregister;
+ }
+
+ xa_for_each(&s->files_xa_out, token, h)
+ luo_unregister_file(s, token);
+
+ luo_state_read_exit();
+
+skip_unregister:
+ xa_destroy(&s->files_xa_out);
+ kfree(s);
+}
+
/**
* liveupdate_register_file_handler - Register a file handler with LUO.
* @fh: Pointer to a caller-allocated &struct liveupdate_file_handler.
@@ -796,6 +913,7 @@ EXPORT_SYMBOL_GPL(liveupdate_register_file_handler);
*/
int liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)
{
+ struct luo_session *s;
unsigned long token;
struct luo_file *h;
int ret = 0;
@@ -807,15 +925,18 @@ int liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)
}
down_write(&luo_register_file_list_rwsem);
-
- xa_for_each(&luo_files_xa_out, token, h) {
- if (h->fh == fh) {
- up_write(&luo_register_file_list_rwsem);
- luo_state_read_exit();
- return -EBUSY;
+ down_read(&luo_sessions_list_rwsem);
+ list_for_each_entry(s, &luo_sessions_list, list) {
+ xa_for_each(&s->files_xa_out, token, h) {
+ if (h->fh == fh) {
+ up_read(&luo_sessions_list_rwsem);
+ up_write(&luo_register_file_list_rwsem);
+ luo_state_read_exit();
+ return -EBUSY;
+ }
}
}
-
+ up_read(&luo_sessions_list_rwsem);
list_del_init(&fh->list);
up_write(&luo_register_file_list_rwsem);
luo_state_read_exit();
diff --git a/kernel/liveupdate/luo_internal.h b/kernel/liveupdate/luo_internal.h
index 05cd861ed2a8..8fef414e7e3e 100644
--- a/kernel/liveupdate/luo_internal.h
+++ b/kernel/liveupdate/luo_internal.h
@@ -25,9 +25,14 @@ int luo_do_subsystems_freeze_calls(void);
void luo_do_subsystems_finish_calls(void);
void luo_do_subsystems_cancel_calls(void);
+struct luo_session;
+
int luo_retrieve_file(u64 token, struct file **filep);
-int luo_register_file(u64 token, int fd);
-int luo_unregister_file(u64 token);
+int luo_register_file(struct luo_session *s, u64 token, int fd);
+int luo_unregister_file(struct luo_session *s, u64 token);
+
+struct luo_session *luo_create_session(void);
+void luo_destroy_session(struct luo_session *s);
#ifdef CONFIG_LIVEUPDATE_SYSFS_API
void luo_sysfs_notify(void);
diff --git a/kernel/liveupdate/luo_ioctl.c b/kernel/liveupdate/luo_ioctl.c
index 3de1d243df5a..d2c49cf33dd3 100644
--- a/kernel/liveupdate/luo_ioctl.c
+++ b/kernel/liveupdate/luo_ioctl.c
@@ -62,6 +62,17 @@ static int luo_open(struct inode *inodep, struct file *filep)
if (filep->f_flags & O_EXCL)
return -EINVAL;
+ filep->private_data = luo_create_session();
+ if (!filep->private_data)
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int luo_release(struct inode *inodep, struct file *filep)
+{
+ luo_destroy_session(filep->private_data);
+
return 0;
}
@@ -101,9 +112,11 @@ static long luo_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
break;
}
- ret = luo_register_file(luo_fd.token, luo_fd.fd);
+ ret = luo_register_file(filep->private_data, luo_fd.token,
+ luo_fd.fd);
if (!ret && copy_to_user(argp, &luo_fd, sizeof(luo_fd))) {
- WARN_ON_ONCE(luo_unregister_file(luo_fd.token));
+ WARN_ON_ONCE(luo_unregister_file(filep->private_data,
+ luo_fd.token));
ret = -EFAULT;
}
break;
@@ -114,7 +127,7 @@ static long luo_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
break;
}
- ret = luo_unregister_file(token);
+ ret = luo_unregister_file(filep->private_data, token);
break;
case LIVEUPDATE_IOCTL_FD_RESTORE:
@@ -140,6 +153,7 @@ static long luo_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
static const struct file_operations fops = {
.owner = THIS_MODULE,
.open = luo_open,
+ .release = luo_release,
.unlocked_ioctl = luo_ioctl,
};
--
2.50.0.727.gbf7dc18ff4-goog
^ permalink raw reply related
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox