1 // SPDX-License-Identifier: GPL-2.0
2 /* Test triggering of loading of firmware from different mount
3 * namespaces. Expect firmware to be always loaded from the mount
4 * namespace of PID 1. */
14 #include <sys/mount.h>
16 #include <sys/types.h>
21 # define CLONE_NEWNS 0x00020000
24 static char *fw_path = NULL;
26 static void die(char *fmt, ...)
31 vfprintf(stderr, fmt, ap);
35 umount("/lib/firmware");
39 static void trigger_fw(const char *fw_name, const char *sys_path)
43 fd = open(sys_path, O_WRONLY);
45 die("open failed: %s\n",
47 if (write(fd, fw_name, strlen(fw_name)) != strlen(fw_name))
52 static void setup_fw(const char *fw_path)
55 const char fw[] = "ABCD0123";
57 fd = open(fw_path, O_WRONLY | O_CREAT, 0600);
59 die("open failed: %s\n",
61 if (write(fd, fw, sizeof(fw) -1) != sizeof(fw) -1)
62 die("write failed: %s\n",
67 static bool test_fw_in_ns(const char *fw_name, const char *sys_path, bool block_fw_in_parent_ns)
71 if (block_fw_in_parent_ns)
72 if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY, NULL) == -1)
73 die("blocking firmware in parent ns failed\n");
77 die("fork failed: %s\n",
80 if (child != 0) { /* parent */
84 pid = waitpid(child, &status, 0);
86 die("waitpid failed: %s\n",
90 die("waited for %d got %d\n",
93 if (!WIFEXITED(status)) {
94 die("child did not terminate cleanly\n");
96 if (block_fw_in_parent_ns)
97 umount("/lib/firmware");
98 return WEXITSTATUS(status) == EXIT_SUCCESS ? true : false;
101 if (unshare(CLONE_NEWNS) != 0) {
102 die("unshare(CLONE_NEWNS) failed: %s\n",
105 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) == -1)
106 die("remount root in child ns failed\n");
108 if (!block_fw_in_parent_ns) {
109 if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY, NULL) == -1)
110 die("blocking firmware in child ns failed\n");
112 umount("/lib/firmware");
114 trigger_fw(fw_name, sys_path);
119 int main(int argc, char **argv)
121 const char *fw_name = "test-firmware.bin";
124 die("usage: %s sys_path\n", argv[0]);
126 /* Mount tmpfs to /lib/firmware so we don't have to assume
127 that it is writable for us.*/
128 if (mount("test", "/lib/firmware", "tmpfs", 0, NULL) == -1)
129 die("mounting tmpfs to /lib/firmware failed\n");
132 asprintf(&fw_path, "/lib/firmware/%s", fw_name);
136 setvbuf(stdout, NULL, _IONBF, 0);
137 /* Positive case: firmware in PID1 mount namespace */
138 printf("Testing with firmware in parent namespace (assumed to be same file system as PID1)\n");
139 if (!test_fw_in_ns(fw_name, sys_path, false))
140 die("error: failed to access firmware\n");
142 /* Negative case: firmware in child mount namespace, expected to fail */
143 printf("Testing with firmware in child namespace\n");
144 if (test_fw_in_ns(fw_name, sys_path, true))
145 die("error: firmware access did not fail\n");
149 umount("/lib/firmware");