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>
20 static char *fw_path
= NULL
;
22 static void die(char *fmt
, ...)
27 vfprintf(stderr
, fmt
, ap
);
31 umount("/lib/firmware");
35 static void trigger_fw(const char *fw_name
, const char *sys_path
)
39 fd
= open(sys_path
, O_WRONLY
);
41 die("open failed: %s\n",
43 if (write(fd
, fw_name
, strlen(fw_name
)) != strlen(fw_name
))
48 static void setup_fw(const char *fw_path
)
51 const char fw
[] = "ABCD0123";
53 fd
= open(fw_path
, O_WRONLY
| O_CREAT
, 0600);
55 die("open failed: %s\n",
57 if (write(fd
, fw
, sizeof(fw
) -1) != sizeof(fw
) -1)
58 die("write failed: %s\n",
63 static bool test_fw_in_ns(const char *fw_name
, const char *sys_path
, bool block_fw_in_parent_ns
)
67 if (block_fw_in_parent_ns
)
68 if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY
, NULL
) == -1)
69 die("blocking firmware in parent ns failed\n");
73 die("fork failed: %s\n",
76 if (child
!= 0) { /* parent */
80 pid
= waitpid(child
, &status
, 0);
82 die("waitpid failed: %s\n",
86 die("waited for %d got %d\n",
89 if (!WIFEXITED(status
)) {
90 die("child did not terminate cleanly\n");
92 if (block_fw_in_parent_ns
)
93 umount("/lib/firmware");
94 return WEXITSTATUS(status
) == EXIT_SUCCESS
;
97 if (unshare(CLONE_NEWNS
) != 0) {
98 die("unshare(CLONE_NEWNS) failed: %s\n",
101 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
) == -1)
102 die("remount root in child ns failed\n");
104 if (!block_fw_in_parent_ns
) {
105 if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY
, NULL
) == -1)
106 die("blocking firmware in child ns failed\n");
108 umount("/lib/firmware");
110 trigger_fw(fw_name
, sys_path
);
115 int main(int argc
, char **argv
)
117 const char *fw_name
= "test-firmware.bin";
120 die("usage: %s sys_path\n", argv
[0]);
122 /* Mount tmpfs to /lib/firmware so we don't have to assume
123 that it is writable for us.*/
124 if (mount("test", "/lib/firmware", "tmpfs", 0, NULL
) == -1)
125 die("mounting tmpfs to /lib/firmware failed\n");
128 if (asprintf(&fw_path
, "/lib/firmware/%s", fw_name
) < 0)
129 die("error: failed to build full fw_path\n");
133 setvbuf(stdout
, NULL
, _IONBF
, 0);
134 /* Positive case: firmware in PID1 mount namespace */
135 printf("Testing with firmware in parent namespace (assumed to be same file system as PID1)\n");
136 if (!test_fw_in_ns(fw_name
, sys_path
, false))
137 die("error: failed to access firmware\n");
139 /* Negative case: firmware in child mount namespace, expected to fail */
140 printf("Testing with firmware in child namespace\n");
141 if (test_fw_in_ns(fw_name
, sys_path
, true))
142 die("error: firmware access did not fail\n");
146 umount("/lib/firmware");