xref: /linux/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c (revision 2a31b5378c6db9c4a8d399e5d10d32cd4b732bef)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * A mount that another namespace's rmdir detached, or that went down with
4  * the detached tree it was in when the tree's last fd was closed, keeps
5  * its submounts connected, and a connected submount is put by its
6  * parent's final mntput(). A submount whose filesystem keeps a file open
7  * on the parent then holds the parent's count above zero for good:
8  * nothing in userspace refers to either mount any more and nothing can
9  * release them. A loop device is the simplest such filesystem, its
10  * backing file sits on the parent.
11  */
12 #define _GNU_SOURCE
13 #include <dirent.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <sched.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/ioctl.h>
21 #include <sys/mount.h>
22 #include <sys/stat.h>
23 #include <stdbool.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26 #include <linux/fuse.h>
27 #include <linux/keyctl.h>
28 #include <linux/major.h>
29 #include <linux/raid/md_u.h>
30 #include <linux/raid/md_p.h>
31 #include <linux/loop.h>
32 #include <linux/magic.h>
33 #include <sys/syscall.h>
34 #include <sys/sysmacros.h>
35 #include <sys/uio.h>
36 
37 #include "../wrappers.h"
38 #include "../../kselftest_harness.h"
39 
40 #define IMAGE_SIZE	(1440 * 1024)
41 #define SECTOR		512
42 
43 /*
44  * The tmpfs of the fixture. A directory of its own from mkdtemp(), so that
45  * the test needs no writable root directory and two instances don't take
46  * each other's mounts down.
47  */
48 static char base[64];
49 
50 /* The configfs directory of the gadget, named after the test process. */
51 static char gadget[96];
52 
53 /* A path below the base directory. Eight of them can be in use at a time. */
54 static const char *at(const char *rel)
55 {
56 	static char buf[8][PATH_MAX];
57 	static unsigned int next;
58 	char *p = buf[next++ % 8];
59 
60 	snprintf(p, PATH_MAX, "%s/%s", base, rel);
61 	return p;
62 }
63 
64 /* A path below the gadget's configfs directory. */
65 static const char *gat(const char *rel)
66 {
67 	static char buf[4][PATH_MAX];
68 	static unsigned int next;
69 	char *p = buf[next++ % 4];
70 
71 	snprintf(p, PATH_MAX, "%s%s", gadget, rel);
72 	return p;
73 }
74 
75 /* The loop devices this process has bound, to release them on every path. */
76 #define MAX_LOOPS	4
77 static int bound[MAX_LOOPS];
78 static int nr_bound;
79 
80 /* What a child tells its parent: the loop devices it has bound, -1 for none. */
81 struct report {
82 	int n[2];
83 };
84 
85 /* A blank FAT12 floppy image: boot sector, two FATs, an empty root directory. */
86 static int write_fat12(int fd)
87 {
88 	struct stat st;
89 	unsigned char sector[SECTOR] = {
90 		0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
91 		[11] = 0x00, 0x02,	/* bytes per sector: 512 */
92 		[13] = 1,		/* sectors per cluster */
93 		[14] = 1, 0,		/* reserved sectors */
94 		[16] = 2,		/* FATs */
95 		[17] = 0xe0, 0x00,	/* root directory entries: 224 */
96 		[19] = 0x40, 0x0b,	/* total sectors: 2880 */
97 		[21] = 0xf0,		/* media descriptor */
98 		[22] = 9, 0,		/* sectors per FAT */
99 		[24] = 18, 0,		/* sectors per track */
100 		[26] = 2, 0,		/* heads */
101 		[38] = 0x29,		/* extended boot signature */
102 		[39] = 0x12, 0x34, 0x56, 0x78,
103 		[43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
104 		[54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
105 		[510] = 0x55, 0xaa,
106 	};
107 	unsigned char fat[SECTOR] = { 0xf0, 0xff, 0xff };
108 
109 	if (pwrite(fd, sector, SECTOR, 0) != SECTOR)
110 		return -1;
111 	/* the first FAT and the second one, one sector each is enough */
112 	if (pwrite(fd, fat, SECTOR, 1 * SECTOR) != SECTOR ||
113 	    pwrite(fd, fat, SECTOR, 10 * SECTOR) != SECTOR)
114 		return -1;
115 	if (fstat(fd, &st) || S_ISBLK(st.st_mode))
116 		return 0;
117 	return ftruncate(fd, IMAGE_SIZE);
118 }
119 
120 /*
121  * A blank FAT12 image with 4 KiB sectors and @sectors of them, for a device
122  * with 4 KiB logical blocks (zram) or for a bigger image than a floppy.
123  */
124 static int write_fat12_4k(int fd, unsigned int sectors)
125 {
126 	unsigned int fat_sectors = (sectors * 3 / 2 + 4095) / 4096;
127 	unsigned char sector[4096] = {
128 		0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
129 		[11] = 0x00, 0x10,	/* bytes per sector: 4096 */
130 		[13] = 1,		/* sectors per cluster */
131 		[14] = 1, 0,		/* reserved sectors */
132 		[16] = 2,		/* FATs */
133 		[17] = 128, 0,		/* root directory entries: one sector */
134 		[19] = sectors & 0xff, sectors >> 8,
135 		[21] = 0xf8,		/* media descriptor */
136 		[22] = fat_sectors, 0,
137 		[24] = 63, 0,		/* sectors per track */
138 		[26] = 255, 0,		/* heads */
139 		[38] = 0x29,		/* extended boot signature */
140 		[39] = 0x12, 0x34, 0x56, 0x78,
141 		[43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
142 		[54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
143 		[510] = 0x55, 0xaa,
144 	};
145 	unsigned char fat[4096] = { 0xf8, 0xff, 0xff };
146 	struct stat st;
147 
148 	if (pwrite(fd, sector, sizeof(sector), 0) != sizeof(sector))
149 		return -1;
150 	if (pwrite(fd, fat, sizeof(fat), 1 * 4096) != sizeof(fat) ||
151 	    pwrite(fd, fat, sizeof(fat), (1 + fat_sectors) * 4096) != sizeof(fat))
152 		return -1;
153 	if (fstat(fd, &st) || S_ISBLK(st.st_mode))
154 		return 0;
155 	return ftruncate(fd, (off_t)sectors * 4096);
156 }
157 
158 #define MINIX_BLOCK	1024
159 #define MINIX_BLOCKS	4096			/* a 4 MiB image */
160 #define MINIX_INODES	512
161 #define MINIX_ITABLE	(MINIX_INODES * 32 / MINIX_BLOCK)
162 #define MINIX_FIRSTDATA	(2 + 1 + 1 + MINIX_ITABLE)	/* boot, super, imap, zmap, inodes */
163 
164 /*
165  * A blank minix v1 image, for the holders that need a FIFO or a device
166  * node on the dying mount, which vfat can't hold. Superblock in block 1,
167  * one block each for the inode and zone bitmaps, the inode table, and
168  * the root directory in the first data zone.
169  */
170 static int write_minix(int fd)
171 {
172 	struct {
173 		__u16 s_ninodes, s_nzones, s_imap_blocks, s_zmap_blocks;
174 		__u16 s_firstdatazone, s_log_zone_size;
175 		__u32 s_max_size;
176 		__u16 s_magic, s_state;
177 	} sb = {
178 		.s_ninodes = MINIX_INODES,
179 		.s_nzones = MINIX_BLOCKS,
180 		.s_imap_blocks = 1,
181 		.s_zmap_blocks = 1,
182 		.s_firstdatazone = MINIX_FIRSTDATA,
183 		.s_max_size = (7 + 512 + 512 * 512) * MINIX_BLOCK,
184 		.s_magic = MINIX_SUPER_MAGIC,
185 		.s_state = 1,		/* MINIX_VALID_FS */
186 	};
187 	struct {
188 		__u16 i_mode, i_uid;
189 		__u32 i_size, i_time;
190 		__u8 i_gid, i_nlinks;
191 		__u16 i_zone[9];
192 	} root = {
193 		.i_mode = S_IFDIR | 0755,
194 		.i_size = 2 * 16,
195 		.i_nlinks = 2,
196 		.i_zone = { MINIX_FIRSTDATA },
197 	};
198 	unsigned char imap[MINIX_BLOCK], zmap[MINIX_BLOCK], dir[MINIX_BLOCK] = {};
199 	int i;
200 
201 	/* bit 0 is reserved in both maps, the root inode and its zone are in use */
202 	memset(imap, 0xff, sizeof(imap));
203 	for (i = 2; i <= MINIX_INODES; i++)
204 		imap[i / 8] &= ~(1 << (i % 8));
205 	memset(zmap, 0xff, sizeof(zmap));
206 	for (i = 2; i <= MINIX_BLOCKS - MINIX_FIRSTDATA; i++)
207 		zmap[i / 8] &= ~(1 << (i % 8));
208 	dir[0] = 1;
209 	dir[2] = '.';
210 	dir[16] = 1;
211 	dir[18] = '.';
212 	dir[19] = '.';
213 
214 	if (pwrite(fd, &sb, sizeof(sb), 1 * MINIX_BLOCK) != sizeof(sb) ||
215 	    pwrite(fd, imap, sizeof(imap), 2 * MINIX_BLOCK) != sizeof(imap) ||
216 	    pwrite(fd, zmap, sizeof(zmap), 3 * MINIX_BLOCK) != sizeof(zmap) ||
217 	    pwrite(fd, &root, sizeof(root), 4 * MINIX_BLOCK) != sizeof(root) ||
218 	    pwrite(fd, dir, sizeof(dir), MINIX_FIRSTDATA * MINIX_BLOCK) != sizeof(dir))
219 		return -1;
220 	return ftruncate(fd, (off_t)MINIX_BLOCKS * MINIX_BLOCK);
221 }
222 
223 static int read_sysfs(const char *path, char *buf, size_t size)
224 {
225 	ssize_t n;
226 	int fd;
227 
228 	fd = open(path, O_RDONLY);
229 	if (fd < 0)
230 		return -1;
231 	n = read(fd, buf, size - 1);
232 	close(fd);
233 	if (n < 0)
234 		return -1;
235 	buf[n] = '\0';
236 	return 0;
237 }
238 
239 /* Is @dev the mount source of this line of mountinfo? loop1 is not loop10. */
240 static bool line_has_source(const char *line, const char *dev)
241 {
242 	const char *sep, *src, *end;
243 
244 	sep = strstr(line, " - ");
245 	if (!sep)
246 		return false;
247 	src = strchr(sep + 3, ' ');	/* skip the filesystem type */
248 	if (!src)
249 		return false;
250 	src++;
251 	end = strchr(src, ' ');
252 	if (!end)
253 		return false;
254 	return (size_t)(end - src) == strlen(dev) && !strncmp(src, dev, end - src);
255 }
256 
257 /*
258  * Does a mount namespace of a process that /proc shows have a mount of @dev?
259  * The mounts under test are in no namespace at this point on any kernel, so
260  * this only checks that the test got as far as it thinks.
261  */
262 static bool mounted_anywhere(const char *dev)
263 {
264 	char path[PATH_MAX], line[4096];
265 	struct dirent *de;
266 	bool found = false;
267 	DIR *proc;
268 	FILE *f;
269 
270 	proc = opendir("/proc");
271 	if (!proc)
272 		return false;
273 	while (!found && (de = readdir(proc))) {
274 		if (de->d_name[0] < '0' || de->d_name[0] > '9')
275 			continue;
276 		snprintf(path, sizeof(path), "/proc/%s/mountinfo", de->d_name);
277 		f = fopen(path, "re");
278 		if (!f)
279 			continue;
280 		while (fgets(line, sizeof(line), f)) {
281 			if (line_has_source(line, dev)) {
282 				found = true;
283 				break;
284 			}
285 		}
286 		fclose(f);
287 	}
288 	closedir(proc);
289 	return found;
290 }
291 
292 /* Wait up to @ms milliseconds for the loop device to give up its backing file. */
293 static bool loop_released(const char *sysfs, int ms)
294 {
295 	char buf[PATH_MAX];
296 
297 	for (; ms > 0; ms -= 100) {
298 		if (read_sysfs(sysfs, buf, sizeof(buf)) < 0)
299 			return errno == ENOENT;
300 		usleep(100000);
301 	}
302 	return read_sysfs(sysfs, buf, sizeof(buf)) < 0 && errno == ENOENT;
303 }
304 
305 /* Tell the loop device to give its file up, now or when its last user is gone. */
306 static void loop_clear(int n)
307 {
308 	char dev[32];
309 	int lfd;
310 
311 	if (n < 0)
312 		return;
313 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
314 	lfd = open(dev, O_RDWR);
315 	if (lfd < 0)
316 		return;
317 	ioctl(lfd, LOOP_CLR_FD);
318 	close(lfd);
319 }
320 
321 FIXTURE(loop_cycle) {
322 	char dev[32];		/* the loop device the child set up */
323 	char sysfs[64];		/* its backing_file attribute */
324 	int loops[MAX_LOOPS];	/* every loop device the case has bound */
325 	int nr_loops;
326 	bool gadget;		/* the gadget's configfs directory exists */
327 };
328 
329 static void remember_loop(FIXTURE_DATA(loop_cycle) *self, int n)
330 {
331 	if (n >= 0 && self->nr_loops < MAX_LOOPS)
332 		self->loops[self->nr_loops++] = n;
333 }
334 
335 FIXTURE_SETUP(loop_cycle)
336 {
337 	if (geteuid() != 0)
338 		SKIP(return, "test requires CAP_SYS_ADMIN");
339 	if (access("/dev/loop-control", R_OK | W_OK))
340 		SKIP(return, "test requires loop devices");
341 
342 	ASSERT_EQ(unshare(CLONE_NEWNS), 0);
343 	ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
344 
345 	snprintf(base, sizeof(base), "/tmp/loop_cycle.XXXXXX");
346 	ASSERT_NE(mkdtemp(base), NULL);
347 	/* a failed assertion in the setup does not run the teardown */
348 	ASSERT_EQ(mount("tmpfs", base, "tmpfs", 0, NULL), 0)
349 		rmdir(base);
350 	snprintf(gadget, sizeof(gadget),
351 		 "/sys/kernel/config/usb_gadget/kselftest_cycle_%d", getpid());
352 	self->dev[0] = '\0';
353 	self->nr_loops = 0;
354 	self->gadget = false;
355 }
356 
357 static int mount_configfs(void);
358 static void gadget_remove(void);
359 
360 FIXTURE_TEARDOWN(loop_cycle)
361 {
362 	if (self->gadget)
363 		gadget_remove();
364 	/* whatever a failed assertion has left bound */
365 	for (int i = 0; i < self->nr_loops; i++)
366 		loop_clear(self->loops[i]);
367 	umount2(base, MNT_DETACH);
368 	rmdir(base);
369 }
370 
371 /* Child exit codes. */
372 enum {
373 	CHILD_OK,
374 	CHILD_NS,		/* could not set up the namespace or the tmpfs */
375 	CHILD_IMAGE,		/* could not write the image */
376 	CHILD_LOOP,		/* could not set up the loop device */
377 	CHILD_MOUNT,		/* could not mount it (vfat and msdos both refused) */
378 	CHILD_PIPE,		/* the parent went away */
379 	CHILD_HOLDER,		/* could not set the holder up below the mount */
380 	CHILD_SKIP,		/* the kernel lacks what the holder needs */
381 	CHILD_NOFS,		/* the kernel lacks the filesystem of the image */
382 };
383 
384 /* Bind the loop device that LOOP_CTL_GET_FREE names to @ifd; the device number. */
385 static int loop_bind_free(int ifd)
386 {
387 	int cfd, lfd, n;
388 	char dev[32];
389 
390 	cfd = open("/dev/loop-control", O_RDWR);
391 	if (cfd < 0)
392 		return -1;
393 	n = ioctl(cfd, LOOP_CTL_GET_FREE);
394 	close(cfd);
395 	if (n < 0)
396 		return -1;
397 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
398 	lfd = open(dev, O_RDWR);
399 	if (lfd < 0)
400 		return -1;
401 	if (ioctl(lfd, LOOP_SET_FD, ifd))
402 		n = -1;
403 	close(lfd);
404 	return n;
405 }
406 
407 /*
408  * Bind a free loop device to the open image @ifd; the device number. The
409  * device is free when LOOP_CTL_GET_FREE names it and may be somebody else's
410  * a moment later, so try again when it is busy.
411  */
412 static int loop_bind(int ifd)
413 {
414 	int n = -1;
415 
416 	for (int i = 0; i < 64 && n < 0; i++) {
417 		n = loop_bind_free(ifd);
418 		if (n < 0 && errno != EBUSY)
419 			return -1;
420 	}
421 	if (n >= 0 && nr_bound < MAX_LOOPS)
422 		bound[nr_bound++] = n;
423 	return n;
424 }
425 
426 /* Mount a FAT image, as vfat or as msdos; -1 with ENODEV if the kernel has neither. */
427 static int mount_fat(const char *dev, const char *mp)
428 {
429 	int err;
430 
431 	if (!mount(dev, mp, "vfat", 0, NULL))
432 		return 0;
433 	err = errno;
434 	if (!mount(dev, mp, "msdos", 0, NULL))
435 		return 0;
436 	if (err != ENODEV)
437 		errno = err;
438 	return -1;
439 }
440 
441 /*
442  * A child that gives up has to take down what it has set up: nobody else
443  * knows about it. Unmount, then tell the loop devices to let go. The mounts
444  * are released after this process is gone and the devices follow them.
445  */
446 static int child_fails(int ret)
447 {
448 	umount2(at("vol"), MNT_DETACH);
449 	umount2(at("vol2"), MNT_DETACH);
450 	umount2(at("p"), MNT_DETACH);
451 	umount2(at("img"), MNT_DETACH);
452 	for (int i = 0; i < nr_bound; i++)
453 		loop_clear(bound[i]);
454 	return ret;
455 }
456 
457 /* Write an image to @img, bind a loop device to it and mount that at @mp; the device number. */
458 static int loop_mount(const char *img, const char *mp)
459 {
460 	char dev[32];
461 	int ifd, n;
462 
463 	ifd = open(img, O_RDWR | O_CREAT | O_EXCL, 0600);
464 	if (ifd < 0 || write_fat12(ifd))
465 		return -CHILD_IMAGE;
466 	n = loop_bind(ifd);
467 	close(ifd);	/* the loop device holds the file from now on */
468 	if (n < 0)
469 		return -CHILD_LOOP;
470 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
471 	if (mkdir(mp, 0755))
472 		return -CHILD_MOUNT;
473 	if (mount_fat(dev, mp))
474 		return errno == ENODEV ? -CHILD_NOFS : -CHILD_MOUNT;
475 	return n;
476 }
477 
478 /*
479  * Two tmpfs mounts, each carrying the image of the loop mount below the
480  * other: the loop mount below vol has its image on vol2 and the other way
481  * round.
482  */
483 static int crossed_child(int to_parent, int from_parent)
484 {
485 	struct report r;
486 	char c;
487 
488 	if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
489 		return CHILD_NS;
490 	if (mkdir(at("vol"), 0755) || mount("tmpfs", at("vol"), "tmpfs", 0, NULL) ||
491 	    mkdir(at("vol2"), 0755) || mount("tmpfs", at("vol2"), "tmpfs", 0, NULL))
492 		return child_fails(CHILD_NS);
493 	r.n[0] = loop_mount(at("vol2/img"), at("vol/mnt"));
494 	if (r.n[0] < 0)
495 		return child_fails(-r.n[0]);
496 	r.n[1] = loop_mount(at("vol/img"), at("vol2/mnt"));
497 	if (r.n[1] < 0)
498 		return child_fails(-r.n[1]);
499 	if (write(to_parent, &r, sizeof(r)) != sizeof(r))
500 		return child_fails(CHILD_PIPE);
501 	if (read(from_parent, &c, 1) != 1)
502 		return child_fails(CHILD_PIPE);
503 	return CHILD_OK;
504 }
505 
506 /*
507  * In its own mount namespace the child mounts a tmpfs on vol,
508  * puts a filesystem image on it, binds a loop device to the image and
509  * mounts that loop device below. The loop device's backing file is a
510  * reference on the mount the image is on, held by the loop device, held
511  * by the mounted filesystem, held by the mount below.
512  */
513 static int loop_child(int to_parent, int from_parent)
514 {
515 	struct report r = { { -1, -1 } };
516 	char c;
517 
518 	if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
519 		return CHILD_NS;
520 	if (mkdir(at("vol"), 0755) || mount("tmpfs", at("vol"), "tmpfs", 0, NULL))
521 		return child_fails(CHILD_NS);
522 	r.n[0] = loop_mount(at("vol/img"), at("vol/mnt"));
523 	if (r.n[0] < 0)
524 		return child_fails(-r.n[0]);
525 
526 	if (write(to_parent, &r, sizeof(r)) != sizeof(r))
527 		return child_fails(CHILD_PIPE);
528 	/* keep the namespace alive while the parent removes the directory */
529 	if (read(from_parent, &c, 1) != 1)
530 		return child_fails(CHILD_PIPE);
531 	return CHILD_OK;
532 }
533 
534 /*
535  * The child did not report. Skip if the kernel lacks something, fail with
536  * what the child said otherwise. A child that a signal killed has failed.
537  */
538 #define CHILD_GAVE_UP(pid) do {						\
539 	int __status;							\
540 									\
541 	ASSERT_EQ(waitpid(pid, &__status, 0), pid);			\
542 	if (WIFEXITED(__status) && WEXITSTATUS(__status) == CHILD_NOFS)	\
543 		SKIP(return, "test requires the filesystem of the image (FAT or minix)"); \
544 	if (WIFEXITED(__status) && WEXITSTATUS(__status) == CHILD_SKIP)	\
545 		SKIP(return, "the kernel lacks what this holder needs"); \
546 	ASSERT_TRUE(false)						\
547 		TH_LOG("child failed to set up: %s %d",			\
548 		       WIFEXITED(__status) ? "exit status" : "signal",	\
549 		       WIFEXITED(__status) ? WEXITSTATUS(__status) : WTERMSIG(__status)); \
550 } while (0)
551 
552 /* The child has to leave by itself and with nothing to complain about. */
553 #define CHILD_LEFT(pid) do {						\
554 	int __status;							\
555 									\
556 	ASSERT_EQ(waitpid(pid, &__status, 0), pid);			\
557 	ASSERT_TRUE(WIFEXITED(__status));				\
558 	ASSERT_EQ(WEXITSTATUS(__status), CHILD_OK);			\
559 } while (0)
560 
561 /*
562  * An exclusive open of the device fails while a filesystem holds it, and
563  * the only filesystem that ever did is the one mounted below the dead
564  * mount. Give a release in flight a moment. Then the device must clear
565  * right away rather than only be marked for autoclear.
566  */
567 static void assert_loop_released(struct __test_metadata *_metadata,
568 				 FIXTURE_DATA(loop_cycle) *self)
569 {
570 	int lfd;
571 
572 	for (int i = 0; i < 20; i++) {
573 		lfd = open(self->dev, O_RDONLY | O_EXCL);
574 		if (lfd >= 0)
575 			break;
576 		usleep(100000);
577 	}
578 	EXPECT_GE(lfd, 0)
579 		TH_LOG("%s is still held by the loop mount below the dead mount: nothing refers to either mount and nothing can release them",
580 		       self->dev);
581 	if (lfd >= 0)
582 		close(lfd);
583 
584 	lfd = open(self->dev, O_RDWR);
585 	ASSERT_GE(lfd, 0);
586 	ASSERT_EQ(ioctl(lfd, LOOP_CLR_FD), 0);
587 	close(lfd);
588 	ASSERT_TRUE(loop_released(self->sysfs, 5000))
589 		TH_LOG("%s kept its backing file after LOOP_CLR_FD: the filesystem on it is still mounted somewhere nobody can reach",
590 		       self->dev);
591 	/* somebody else may bind it from now on, so the teardown leaves it alone */
592 	for (int i = 0; i < self->nr_loops; i++) {
593 		char dev[32];
594 
595 		snprintf(dev, sizeof(dev), "/dev/loop%d", self->loops[i]);
596 		if (!strcmp(dev, self->dev))
597 			self->loops[i] = -1;
598 	}
599 }
600 
601 /*
602  * rmdir of vol from here, where it is not a mountpoint, detaches
603  * the child's tmpfs with the loop mount connected below it. Once the child
604  * is gone nothing refers to either mount. The loop device must then be
605  * free to give up its backing file, which only happens when the mounted
606  * filesystem below the detached tmpfs has been released.
607  */
608 TEST_F(loop_cycle, detached_loop_mount_released)
609 {
610 	int to_parent[2], to_child[2];
611 	struct report r = { { -1, -1 } };
612 	char buf[PATH_MAX];
613 	pid_t pid;
614 
615 	ASSERT_EQ(pipe(to_parent), 0);
616 	ASSERT_EQ(pipe(to_child), 0);
617 
618 	pid = fork();
619 	ASSERT_GE(pid, 0);
620 	if (pid == 0) {
621 		close(to_parent[0]);
622 		close(to_child[1]);
623 		_exit(loop_child(to_parent[1], to_child[0]));
624 	}
625 	close(to_parent[1]);
626 	close(to_child[0]);
627 
628 	if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
629 		CHILD_GAVE_UP(pid);
630 	remember_loop(self, r.n[0]);
631 	snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", r.n[0]);
632 	snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", r.n[0]);
633 	ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
634 	ASSERT_NE(strstr(buf, "/vol/img"), NULL);
635 
636 	/* not a mountpoint in this namespace, so the directory can go */
637 	ASSERT_EQ(rmdir(at("vol")), 0);
638 
639 	/* the child leaves: its namespace and every reference it held are gone */
640 	ASSERT_EQ(write(to_child[1], "", 1), 1);
641 	CHILD_LEFT(pid);
642 	close(to_parent[0]);
643 	close(to_child[1]);
644 
645 	/* nothing can reach the two mounts any more */
646 	ASSERT_EQ(access(at("vol"), F_OK), -1);
647 	ASSERT_FALSE(mounted_anywhere(self->dev));
648 
649 	assert_loop_released(_metadata, self);
650 }
651 
652 /*
653  * The same two mounts in a detached tree: a clone of vol from
654  * open_tree(), the image opened through the clone so that the loop device
655  * holds the clone, and the loop mount moved below the clone. The last
656  * close of the tree's fd dissolves the tree with the loop mount left
657  * connected below the dead clone, and nothing refers to either afterwards.
658  */
659 TEST_F(loop_cycle, dissolved_tree_loop_mount_released)
660 {
661 	int tfd, ifd, fsfd, mfd, n;
662 	char buf[PATH_MAX];
663 
664 	fsfd = sys_fsopen("vfat", 0);
665 	if (fsfd < 0)
666 		fsfd = sys_fsopen("msdos", 0);
667 	if (fsfd < 0)
668 		SKIP(return, "test requires a FAT filesystem");
669 
670 	ASSERT_EQ(mkdir(at("vol"), 0755), 0);
671 	ASSERT_EQ(mount("tmpfs", at("vol"), "tmpfs", 0, NULL), 0);
672 	tfd = sys_open_tree(AT_FDCWD, at("vol"), OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
673 	ASSERT_GE(tfd, 0);
674 
675 	/* the image, opened through the clone: the loop device holds the clone */
676 	ifd = openat(tfd, "img", O_RDWR | O_CREAT | O_EXCL, 0600);
677 	ASSERT_GE(ifd, 0);
678 	ASSERT_EQ(write_fat12(ifd), 0);
679 	n = loop_bind(ifd);
680 	close(ifd);
681 	ASSERT_GE(n, 0);
682 	remember_loop(self, n);
683 	snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
684 	snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
685 
686 	/* the loop mount, moved below the clone */
687 	ASSERT_EQ(mkdirat(tfd, "mnt", 0755), 0);
688 	ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, "source", self->dev, 0), 0);
689 	ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);
690 	mfd = sys_fsmount(fsfd, 0, 0);
691 	ASSERT_GE(mfd, 0);
692 	close(fsfd);
693 	ASSERT_EQ(sys_move_mount(mfd, "", tfd, "mnt", MOVE_MOUNT_F_EMPTY_PATH), 0);
694 	close(mfd);
695 
696 	ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
697 	ASSERT_NE(strstr(buf, "img"), NULL);
698 
699 	/* the last fd of the tree: both mounts die, the loop mount connected */
700 	close(tfd);
701 
702 	/* nothing can reach the two mounts any more */
703 	ASSERT_FALSE(mounted_anywhere(self->dev));
704 
705 	assert_loop_released(_metadata, self);
706 }
707 
708 /*
709  * The cycle in two steps: rmdir of vol leaves the loop mount below it
710  * connected while its image's mount, vol2, is alive; then rmdir of vol2
711  * takes that one with the loop mount whose image is on the dead vol. Each
712  * dead mount now owns a loop mount whose filesystem pins the other.
713  */
714 TEST_F(loop_cycle, crossed_images_released)
715 {
716 	int to_parent[2], to_child[2];
717 	struct report r = { { -1, -1 } };
718 	char sysfs[2][64], dev[2][32];
719 	pid_t pid;
720 
721 	ASSERT_EQ(pipe(to_parent), 0);
722 	ASSERT_EQ(pipe(to_child), 0);
723 
724 	pid = fork();
725 	ASSERT_GE(pid, 0);
726 	if (pid == 0) {
727 		close(to_parent[0]);
728 		close(to_child[1]);
729 		_exit(crossed_child(to_parent[1], to_child[0]));
730 	}
731 	close(to_parent[1]);
732 	close(to_child[0]);
733 
734 	if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
735 		CHILD_GAVE_UP(pid);
736 	for (int i = 0; i < 2; i++) {
737 		remember_loop(self, r.n[i]);
738 		snprintf(dev[i], sizeof(dev[i]), "/dev/loop%d", r.n[i]);
739 		snprintf(sysfs[i], sizeof(sysfs[i]), "/sys/block/loop%d/loop/backing_file", r.n[i]);
740 	}
741 
742 	/* step one: the mount with the first loop mount below it goes */
743 	ASSERT_EQ(rmdir(at("vol")), 0);
744 
745 	/* step two: the other one, with the loop mount whose image is on the first */
746 	ASSERT_EQ(rmdir(at("vol2")), 0);
747 
748 	/* the child leaves: its namespace and every reference it held are gone */
749 	ASSERT_EQ(write(to_child[1], "", 1), 1);
750 	CHILD_LEFT(pid);
751 	close(to_parent[0]);
752 	close(to_child[1]);
753 
754 	/* nothing can reach the four mounts any more */
755 	for (int i = 0; i < 2; i++) {
756 		ASSERT_FALSE(mounted_anywhere(dev[i]));
757 		strcpy(self->dev, dev[i]);
758 		strcpy(self->sysfs, sysfs[i]);
759 		assert_loop_released(_metadata, self);
760 	}
761 }
762 
763 /*
764  * The holders. Each keeps a file or a path on a mount P for as long as
765  * its own filesystem or device lives, and each has that filesystem or
766  * device mounted at C below P. Once another namespace's rmdir has
767  * detached P with C connected below it and the child is gone, P is owned
768  * by nobody, C by P, and P is kept by whatever the holder still holds.
769  *
770  * P is a loop mount so that its death can be observed: the loop device
771  * gives its backing file up when P's superblock goes. The image sits on
772  * a tmpfs next to P, not above it, so the loop device's own reference is
773  * not part of the picture.
774  */
775 enum holder {
776 	HOLDER_AUTOFS,		/* a FIFO on P as the daemon's pipe */
777 	HOLDER_ZRAM,		/* a device node on P as the writeback device */
778 	HOLDER_ECRYPTFS,	/* a directory on P as the lower directory */
779 	HOLDER_BINFMT_MISC,	/* an executable on P as an 'F' interpreter */
780 	HOLDER_FUSE,		/* a file on P as a passthrough backing file */
781 	HOLDER_ZLOOP,		/* a directory on P for the zone files */
782 	HOLDER_GADGET,		/* a file on P as a mass storage LUN, over dummy_hcd */
783 	HOLDER_MD,		/* a file on P as an array's bitmap file */
784 };
785 
786 #define HOLDER_IMG	at("img/p.img")
787 #define HOLDER_MNT	at("p")
788 #define HOLDER_BELOW	at("p/c")
789 
790 static int write_file(const char *path, const char *s)
791 {
792 	int fd = open(path, O_WRONLY);
793 	ssize_t n;
794 
795 	if (fd < 0)
796 		return -1;
797 	n = write(fd, s, strlen(s));
798 	close(fd);
799 	return n == (ssize_t)strlen(s) ? 0 : -1;
800 }
801 
802 /* Bind a free loop device to @img; the device number. */
803 static int loop_attach(const char *img)
804 {
805 	int ifd, n;
806 
807 	ifd = open(img, O_RDWR);
808 	if (ifd < 0)
809 		return -1;
810 	n = loop_bind(ifd);
811 	close(ifd);
812 	return n;
813 }
814 
815 static int holder_autofs(void)
816 {
817 	char opts[64];
818 	int pfd;
819 
820 	if (mkfifo(at("p/pipe"), 0600))
821 		return CHILD_HOLDER;
822 	pfd = open(at("p/pipe"), O_RDWR);
823 	if (pfd < 0)
824 		return CHILD_HOLDER;
825 	snprintf(opts, sizeof(opts), "fd=%d,minproto=5,maxproto=5", pfd);
826 	if (mount("autofs", HOLDER_BELOW, "autofs", 0, opts))
827 		return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
828 	close(pfd);	/* the mount keeps its own */
829 	return CHILD_OK;
830 }
831 
832 /*
833  * zram's writeback device has to be a block device node, and that node has
834  * to be on P. Point it at a second loop device.
835  */
836 static void zram_reset(void);
837 
838 static int holder_zram(void)
839 {
840 	char dev[32], buf[64];
841 	struct stat st;
842 	int fd, n;
843 
844 	if (access("/sys/block/zram0/backing_dev", W_OK))
845 		return CHILD_SKIP;
846 	/* somebody else's device, leave it alone */
847 	if (read_sysfs("/sys/block/zram0/initstate", buf, sizeof(buf)) || buf[0] != '0')
848 		return CHILD_SKIP;
849 	fd = open(at("img/wb.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
850 	if (fd < 0 || ftruncate(fd, IMAGE_SIZE))
851 		return CHILD_HOLDER;
852 	close(fd);
853 	n = loop_attach(at("img/wb.img"));
854 	if (n < 0)
855 		return CHILD_HOLDER;
856 	/* the minor is not the number of the device when loop has partitions */
857 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
858 	if (stat(dev, &st) || mknod(at("p/wbdev"), S_IFBLK | 0600, st.st_rdev))
859 		return CHILD_HOLDER;
860 	if (write_file("/sys/block/zram0/backing_dev", at("p/wbdev")))
861 		return CHILD_HOLDER;
862 	snprintf(buf, sizeof(buf), "%d", 4 * 1024 * 1024);
863 	if (write_file("/sys/block/zram0/disksize", buf))
864 		goto undo;
865 	fd = open("/dev/zram0", O_RDWR);
866 	if (fd < 0)
867 		goto undo;
868 	n = write_fat12_4k(fd, 1024);	/* zram has 4 KiB blocks */
869 	close(fd);	/* the reset in undo is refused while the device is open */
870 	if (n)
871 		goto undo;
872 	if (mount_fat("/dev/zram0", HOLDER_BELOW)) {
873 		n = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
874 		zram_reset();
875 		return n;
876 	}
877 	return CHILD_OK;
878 undo:
879 	zram_reset();
880 	return CHILD_HOLDER;
881 }
882 
883 /* Is @alg in /proc/crypto? A module is listed once a request has loaded it. */
884 static bool crypto_has(const char *alg)
885 {
886 	char line[256], name[64];
887 	bool found = false;
888 	FILE *f;
889 
890 	f = fopen("/proc/crypto", "r");
891 	if (!f)
892 		return true;	/* no way to tell, assume it is */
893 	while (!found && fgets(line, sizeof(line), f))
894 		found = sscanf(line, "name : %63s", name) == 1 && !strcmp(name, alg);
895 	fclose(f);
896 	return found;
897 }
898 
899 /* The kernel's auth token layout, which userspace has to match byte for byte. */
900 struct ecryptfs_auth_tok {
901 	__u16 version;
902 	__u16 token_type;
903 	__u32 flags;
904 	struct {
905 		__u32 flags, encrypted_key_size, decrypted_key_size;
906 		__u8 encrypted_key[512], decrypted_key[64];
907 	} session_key;
908 	__u8 reserved[32];
909 	struct {
910 		__u32 password_bytes;
911 		__s32 hash_algo;
912 		__u32 hash_iterations, session_key_encryption_key_bytes, flags;
913 		__u8 session_key_encryption_key[64];
914 		__u8 signature[17];
915 		__u8 salt[8];
916 	} password;
917 } __attribute__((packed));
918 
919 #define ECRYPTFS_SIG	"0123456789abcdef"
920 
921 static int holder_ecryptfs(void)
922 {
923 	struct ecryptfs_auth_tok tok = {
924 		.version = 0x0004,
925 		.token_type = 0,		/* ECRYPTFS_PASSWORD */
926 		.password.session_key_encryption_key_bytes = 16,
927 		.password.flags = 0x02,		/* ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET */
928 		.password.signature = ECRYPTFS_SIG,
929 	};
930 
931 	/* a session keyring of this child's own, so that the key goes with it */
932 	if (syscall(__NR_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) < 0)
933 		return errno == ENOSYS ? CHILD_SKIP : CHILD_HOLDER;
934 	if (syscall(__NR_add_key, "user", ECRYPTFS_SIG, &tok, sizeof(tok),
935 		    KEY_SPEC_SESSION_KEYRING) < 0)
936 		return CHILD_HOLDER;
937 	if (mkdir(at("p/lower"), 0755))
938 		return CHILD_HOLDER;
939 	if (mount(at("p/lower"), HOLDER_BELOW, "ecryptfs", 0,
940 		  "ecryptfs_sig=" ECRYPTFS_SIG ",ecryptfs_cipher=aes,ecryptfs_key_bytes=16")) {
941 		/* EINVAL without the cipher; a module is loaded by the attempt */
942 		if (errno == ENODEV || (errno == EINVAL && !crypto_has("aes")))
943 			return CHILD_SKIP;
944 		return CHILD_HOLDER;
945 	}
946 	return CHILD_OK;
947 }
948 
949 /*
950  * binfmt_misc instances are per user namespace, so the mount below P is
951  * made from a new one, which gets a copy of P.
952  */
953 static int holder_binfmt_misc(void)
954 {
955 	static const char interp[] = "#!/bin/true\n";
956 	char reg[PATH_MAX];
957 	int out;
958 
959 	/* 'F' opens the interpreter at registration, nothing runs it here */
960 	out = open(at("p/interp"), O_WRONLY | O_CREAT | O_EXCL, 0755);
961 	if (out < 0 || write(out, interp, sizeof(interp) - 1) != sizeof(interp) - 1)
962 		return CHILD_HOLDER;
963 	close(out);
964 
965 	/* ENOSPC: user.max_user_namespaces is 0, EPERM: an LSM says no */
966 	if (unshare(CLONE_NEWUSER | CLONE_NEWNS)) {
967 		if (errno == EINVAL || errno == ENOSPC || errno == EPERM)
968 			return CHILD_SKIP;
969 		return CHILD_HOLDER;
970 	}
971 	if (write_file("/proc/self/setgroups", "deny") ||
972 	    write_file("/proc/self/uid_map", "0 0 1") ||
973 	    write_file("/proc/self/gid_map", "0 0 1"))
974 		return CHILD_HOLDER;
975 	if (mount("binfmt_misc", HOLDER_BELOW, "binfmt_misc", 0, NULL))
976 		return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
977 	snprintf(reg, sizeof(reg), ":cycle:E::cyc::%s:F", at("p/interp"));
978 	if (write_file(at("p/c/register"), reg))
979 		return CHILD_HOLDER;
980 	return CHILD_OK;
981 }
982 
983 /*
984  * A fuse server that only ever answers FUSE_INIT, with passthrough on, and
985  * then registers a file on P as a backing file. The registration alone
986  * makes the fuse superblock hold the file.
987  */
988 static int holder_fuse(void)
989 {
990 	struct fuse_backing_map map = {};
991 	struct fuse_in_header *ih;
992 	struct fuse_init_out init = {
993 		.major = FUSE_KERNEL_VERSION,
994 		.minor = FUSE_KERNEL_MINOR_VERSION,
995 		.flags = FUSE_INIT_EXT,
996 		.flags2 = FUSE_PASSTHROUGH >> 32,
997 		.max_write = 4096,
998 		.max_stack_depth = 1,
999 	};
1000 	struct fuse_out_header oh = { .len = sizeof(oh) + sizeof(init) };
1001 	struct iovec iov[2] = { { &oh, sizeof(oh) }, { &init, sizeof(init) } };
1002 	char opts[64], buf[8192];
1003 	int ffd, bfd;
1004 	ssize_t n;
1005 
1006 	bfd = open(at("p/backing"), O_RDWR | O_CREAT | O_EXCL, 0600);
1007 	if (bfd < 0)
1008 		return CHILD_HOLDER;
1009 	ffd = open("/dev/fuse", O_RDWR);
1010 	if (ffd < 0)
1011 		return CHILD_SKIP;
1012 	snprintf(opts, sizeof(opts), "fd=%d,rootmode=40000,user_id=0,group_id=0", ffd);
1013 	if (mount("fuse", HOLDER_BELOW, "fuse", 0, opts))
1014 		return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
1015 
1016 	n = read(ffd, buf, sizeof(buf));
1017 	ih = (void *)buf;
1018 	if (n < (ssize_t)sizeof(*ih) || ih->opcode != FUSE_INIT)
1019 		return CHILD_HOLDER;
1020 	oh.unique = ih->unique;
1021 	if (writev(ffd, iov, 2) != (ssize_t)oh.len)
1022 		return CHILD_HOLDER;
1023 
1024 	map.fd = bfd;
1025 	if (ioctl(ffd, FUSE_DEV_IOC_BACKING_OPEN, &map) < 0) {
1026 		/* EOPNOTSUPP: no FUSE_PASSTHROUGH, ENOTTY: no such ioctl */
1027 		if (errno == EPERM || errno == EOPNOTSUPP || errno == ENOTTY)
1028 			return CHILD_SKIP;
1029 		return CHILD_HOLDER;
1030 	}
1031 	close(bfd);	/* the connection keeps its own */
1032 	return CHILD_OK;	/* ffd stays open until the child exits */
1033 }
1034 
1035 /* Wait for a device node the kernel is about to create. */
1036 static int open_when_there(const char *dev, int flags, int ms)
1037 {
1038 	int fd;
1039 
1040 	for (; ms > 0; ms -= 100) {
1041 		fd = open(dev, flags);
1042 		if (fd >= 0)
1043 			return fd;
1044 		usleep(100000);
1045 	}
1046 	return -1;
1047 }
1048 
1049 /*
1050  * zloop keeps every zone file open. One conventional zone is enough for a
1051  * FAT image, the sequential one stays empty.
1052  */
1053 static int holder_zloop(void)
1054 {
1055 	char cmd[PATH_MAX];
1056 	int fd, ret = CHILD_HOLDER;
1057 
1058 	if (access("/dev/zloop-control", W_OK))
1059 		return CHILD_SKIP;
1060 	/* somebody else's device, leave it alone */
1061 	if (!access("/sys/block/zloop0", F_OK))
1062 		return CHILD_SKIP;
1063 	if (mkdir(at("p/zl"), 0755) || mkdir(at("p/zl/0"), 0755))
1064 		return CHILD_HOLDER;
1065 	snprintf(cmd, sizeof(cmd),
1066 		 "add id=0,capacity_mb=8,zone_size_mb=4,conv_zones=1,base_dir=%s",
1067 		 at("p/zl"));
1068 	if (write_file("/dev/zloop-control", cmd))
1069 		return CHILD_HOLDER;
1070 	fd = open_when_there("/dev/zloop0", O_RDWR, 5000);
1071 	if (fd < 0 || write_fat12_4k(fd, 1024))	/* 4 KiB blocks, like P */
1072 		goto undo;
1073 	close(fd);
1074 	fd = -1;
1075 	if (mount_fat("/dev/zloop0", HOLDER_BELOW)) {
1076 		ret = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1077 		goto undo;
1078 	}
1079 	return CHILD_OK;
1080 undo:
1081 	if (fd >= 0)
1082 		close(fd);
1083 	write_file("/dev/zloop-control", "remove id=0");
1084 	return ret;
1085 }
1086 
1087 static int mount_configfs(void)
1088 {
1089 	if (access("/sys/kernel/config", F_OK))
1090 		return -1;
1091 	if (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY)
1092 		return -1;
1093 	return 0;
1094 }
1095 
1096 /* Take the gadget out of configfs again, in the reverse order of its creation. */
1097 static void gadget_remove(void)
1098 {
1099 	if (mount_configfs())
1100 		return;
1101 	write_file(gat("/functions/mass_storage.0/lun.0/file"), "\n");
1102 	write_file(gat("/UDC"), "\n");
1103 	unlink(gat("/configs/c.1/mass_storage.0"));
1104 	rmdir(gat("/configs/c.1/strings/0x409"));
1105 	rmdir(gat("/configs/c.1"));
1106 	rmdir(gat("/functions/mass_storage.0"));
1107 	rmdir(gat("/strings/0x409"));
1108 	rmdir(gat(""));
1109 }
1110 
1111 /* The disk usb-storage created for the gadget, by the LUN's inquiry string. */
1112 static int find_gadget_disk(char *dev, size_t len, int ms)
1113 {
1114 	char path[PATH_MAX], model[64];
1115 	struct dirent *de;
1116 	DIR *d;
1117 
1118 	for (; ms > 0; ms -= 100, usleep(100000)) {
1119 		d = opendir("/sys/block");
1120 		if (!d)
1121 			return -1;
1122 		while ((de = readdir(d))) {
1123 			if (strncmp(de->d_name, "sd", 2))
1124 				continue;
1125 			snprintf(path, sizeof(path), "/sys/block/%s/device/model", de->d_name);
1126 			if (read_sysfs(path, model, sizeof(model)) ||
1127 			    strncmp(model, "File-Stor Gadget", 16))
1128 				continue;
1129 			snprintf(dev, len, "/dev/%s", de->d_name);
1130 			closedir(d);
1131 			return 0;
1132 		}
1133 		closedir(d);
1134 	}
1135 	return -1;
1136 }
1137 
1138 /*
1139  * A mass storage gadget bound to the dummy UDC, so that this kernel is
1140  * also the USB host that sees the LUN as a SCSI disk. sd locks the
1141  * medium on open, which is what keeps the LUN's file from being ejected.
1142  */
1143 #define GADGET_STEP(x) do {						\
1144 	if (x) {							\
1145 		fprintf(stderr, "gadget: %s failed: %s\n", #x, strerror(errno)); \
1146 		gadget_remove();					\
1147 		return CHILD_HOLDER;					\
1148 	}								\
1149 } while (0)
1150 
1151 static int holder_gadget(void)
1152 {
1153 	char dev[PATH_MAX];
1154 	int fd;
1155 
1156 	if (mount_configfs())
1157 		return CHILD_SKIP;
1158 	if (access("/sys/kernel/config/usb_gadget", F_OK) ||
1159 	    access("/sys/class/udc/dummy_udc.0", F_OK))
1160 		return CHILD_SKIP;
1161 
1162 	fd = open(at("p/lun.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
1163 	if (fd < 0 || write_fat12(fd))
1164 		return CHILD_HOLDER;
1165 	close(fd);
1166 
1167 	GADGET_STEP(mkdir(gat(""), 0755));
1168 	GADGET_STEP(write_file(gat("/idVendor"), "0x1d6b"));
1169 	GADGET_STEP(write_file(gat("/idProduct"), "0x0104"));
1170 	GADGET_STEP(mkdir(gat("/strings/0x409"), 0755));
1171 	GADGET_STEP(write_file(gat("/strings/0x409/serialnumber"), "1"));
1172 	GADGET_STEP(write_file(gat("/strings/0x409/manufacturer"), "kselftest"));
1173 	GADGET_STEP(write_file(gat("/strings/0x409/product"), "cycle"));
1174 	GADGET_STEP(mkdir(gat("/configs/c.1"), 0755));
1175 	GADGET_STEP(mkdir(gat("/configs/c.1/strings/0x409"), 0755));
1176 	GADGET_STEP(write_file(gat("/configs/c.1/strings/0x409/configuration"), "c"));
1177 	GADGET_STEP(mkdir(gat("/functions/mass_storage.0"), 0755));
1178 	GADGET_STEP(write_file(gat("/functions/mass_storage.0/lun.0/removable"), "1"));
1179 	GADGET_STEP(write_file(gat("/functions/mass_storage.0/lun.0/file"), at("p/lun.img")));
1180 	GADGET_STEP(symlink(gat("/functions/mass_storage.0"), gat("/configs/c.1/mass_storage.0")));
1181 	/* EBUSY: the controller is somebody else's, leave it alone */
1182 	if (write_file(gat("/UDC"), "dummy_udc.0")) {
1183 		fd = errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
1184 		gadget_remove();
1185 		return fd;
1186 	}
1187 
1188 	/* usb-storage waits a second before it scans the device */
1189 	if (find_gadget_disk(dev, sizeof(dev), 15000)) {
1190 		/* without usb-storage and sd the LUN never shows up as a disk */
1191 		fd = (access("/sys/bus/usb/drivers/usb-storage", F_OK) ||
1192 		      access("/sys/bus/scsi/drivers/sd", F_OK)) ? CHILD_SKIP : CHILD_HOLDER;
1193 		gadget_remove();
1194 		return fd;
1195 	}
1196 	fd = open_when_there(dev, O_RDONLY, 5000);
1197 	GADGET_STEP(fd < 0);
1198 	close(fd);
1199 	if (mount_fat(dev, HOLDER_BELOW)) {
1200 		fd = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1201 		gadget_remove();
1202 		return fd;
1203 	}
1204 	return CHILD_OK;
1205 }
1206 
1207 #define BITMAP_MAGIC	0x6d746962
1208 
1209 /*
1210  * A RAID1 of one loop device, not persistent, with its bitmap in a file
1211  * on P. The bitmap file needs a superblock the kernel accepts; sync_size,
1212  * uuid and events are not looked at for a non-persistent array.
1213  */
1214 static int holder_md(void)
1215 {
1216 	struct {
1217 		__u32 magic, version;
1218 		__u8 uuid[16];
1219 		__u64 events, events_cleared, sync_size;
1220 		__u32 state, chunksize, daemon_sleep, write_behind;
1221 	} bsb = {
1222 		.magic = BITMAP_MAGIC,
1223 		.version = 4,
1224 		.chunksize = 64 * 1024,
1225 		.daemon_sleep = 5,
1226 	};
1227 	mdu_array_info_t info = {
1228 		.level = 1,
1229 		.raid_disks = 1,
1230 		.size = 8 * 1024,		/* KiB */
1231 		.not_persistent = 1,
1232 	};
1233 	mdu_disk_info_t disk = {
1234 		.major = 7,
1235 		.state = (1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC),
1236 	};
1237 	int fd, mdfd, bfd, n, ret = CHILD_HOLDER;
1238 	char dev[32], buf[4096];
1239 	struct stat st;
1240 
1241 	fd = open(at("img/md.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
1242 	if (fd < 0 || ftruncate(fd, 8 * 1024 * 1024))
1243 		return CHILD_HOLDER;
1244 	close(fd);
1245 	n = loop_attach(at("img/md.img"));
1246 	if (n < 0)
1247 		return CHILD_HOLDER;
1248 	/* the minor is not the number of the device when loop has partitions */
1249 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
1250 	if (stat(dev, &st))
1251 		return CHILD_HOLDER;
1252 	disk.major = major(st.st_rdev);
1253 	disk.minor = minor(st.st_rdev);
1254 
1255 	bfd = open(at("p/bitmap"), O_RDWR | O_CREAT | O_EXCL, 0600);
1256 	if (bfd < 0 || write(bfd, &bsb, sizeof(bsb)) != sizeof(bsb) || ftruncate(bfd, 4096))
1257 		return CHILD_HOLDER;
1258 
1259 	if (read_sysfs("/proc/mdstat", buf, sizeof(buf))) {
1260 		fprintf(stderr, "md: no /proc/mdstat\n");
1261 		return CHILD_SKIP;
1262 	}
1263 	if (!strstr(buf, "[raid1]")) {
1264 		fprintf(stderr, "md: no raid1 personality: %s\n", buf);
1265 		return CHILD_SKIP;
1266 	}
1267 	/* a node of our own: /dev may not have one and is not ours to change */
1268 	if (mknod(at("img/md0"), S_IFBLK | 0600, makedev(MD_MAJOR, 0)))
1269 		return CHILD_HOLDER;
1270 	mdfd = open(at("img/md0"), O_RDWR);
1271 	if (mdfd < 0)
1272 		return CHILD_SKIP;
1273 	/* somebody else's array: SET_ARRAY_INFO would say EINVAL, not EBUSY */
1274 	if (!read_sysfs("/sys/block/md0/md/array_state", buf, sizeof(buf)) &&
1275 	    strncmp(buf, "clear", 5)) {
1276 		fprintf(stderr, "md: md0 is in use: %s", buf);
1277 		close(mdfd);
1278 		return CHILD_SKIP;
1279 	}
1280 	/* the bitmap ops are only installed once a bitmap type is chosen */
1281 	write_file("/sys/block/md0/md/bitmap_type", "bitmap");
1282 	/* EBUSY: somebody else's array, leave it alone */
1283 	if (ioctl(mdfd, SET_ARRAY_INFO, &info))
1284 		return errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
1285 	/* the array is ours from here on and has to be stopped on every path */
1286 	if (ioctl(mdfd, ADD_NEW_DISK, &disk))
1287 		goto undo;
1288 	/* attach the bitmap file before the array runs, the way mdadm does */
1289 	if (ioctl(mdfd, SET_BITMAP_FILE, bfd)) {
1290 		fprintf(stderr, "md: SET_BITMAP_FILE: %s\n", strerror(errno));
1291 		if (errno == EINVAL)
1292 			ret = CHILD_SKIP;
1293 		goto undo;
1294 	}
1295 	close(bfd);	/* the array keeps its own */
1296 	if (ioctl(mdfd, RUN_ARRAY, NULL)) {
1297 		fprintf(stderr, "md: RUN_ARRAY: %s\n", strerror(errno));
1298 		goto undo;
1299 	}
1300 	if (write_fat12(mdfd))
1301 		goto undo;
1302 	close(mdfd);
1303 	if (mount_fat(at("img/md0"), HOLDER_BELOW)) {
1304 		ret = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1305 		mdfd = open(at("img/md0"), O_RDWR);
1306 		goto undo;
1307 	}
1308 	return CHILD_OK;
1309 undo:
1310 	if (mdfd >= 0) {
1311 		ioctl(mdfd, STOP_ARRAY);
1312 		close(mdfd);
1313 	}
1314 	return ret;
1315 }
1316 
1317 /*
1318  * A device keeps its file for as long as it is configured, so once nothing
1319  * below the dead mount is left the device has to be told to let go. With
1320  * the cycle unbroken C's filesystem still holds the device and every one
1321  * of these refuses.
1322  */
1323 static int holder_let_go_once(enum holder holder)
1324 {
1325 	int fd, ret;
1326 
1327 	switch (holder) {
1328 	case HOLDER_ZRAM:
1329 		return write_file("/sys/block/zram0/reset", "1");
1330 	case HOLDER_ZLOOP:
1331 		return write_file("/dev/zloop-control", "remove id=0");
1332 	case HOLDER_GADGET:
1333 		if (mount_configfs())
1334 			return -1;
1335 		/* a zero-length write is a no-op for configfs; a newline ejects */
1336 		return write_file(gat("/functions/mass_storage.0/lun.0/file"), "\n");
1337 	case HOLDER_MD:
1338 		fd = open(at("img/md0"), O_RDONLY);
1339 		if (fd < 0) {
1340 			/* the child's node went with its tmpfs */
1341 			mknod(at("md0"), S_IFBLK | 0600, makedev(MD_MAJOR, 0));
1342 			fd = open(at("md0"), O_RDONLY);
1343 		}
1344 		if (fd < 0)
1345 			return -1;
1346 		ret = ioctl(fd, STOP_ARRAY);
1347 		close(fd);
1348 		return ret;
1349 	default:
1350 		return 0;
1351 	}
1352 }
1353 
1354 static void zram_reset(void)
1355 {
1356 	holder_let_go_once(HOLDER_ZRAM);
1357 }
1358 
1359 /*
1360  * In its own mount namespace the child puts the image on a tmpfs next to
1361  * P, mounts P from a loop device, and sets the holder up with its own
1362  * filesystem or device mounted at C below P.
1363  */
1364 static int holder_child(int to_parent, int from_parent, enum holder holder)
1365 {
1366 	bool fifo = holder == HOLDER_AUTOFS || holder == HOLDER_ZRAM;
1367 	/* room for a 4 MiB zone file or a floppy image on P */
1368 	bool big = holder == HOLDER_ZLOOP || holder == HOLDER_GADGET;
1369 	struct report r = { { -1, -1 } };
1370 	char dev[32], c;
1371 	int ifd, n, ret;
1372 
1373 	if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
1374 		return CHILD_NS;
1375 	if (mkdir(at("img"), 0755) || mount("tmpfs", at("img"), "tmpfs", 0, NULL))
1376 		return child_fails(CHILD_NS);
1377 
1378 	ifd = open(HOLDER_IMG, O_RDWR | O_CREAT | O_EXCL, 0600);
1379 	if (ifd < 0 || (fifo ? write_minix(ifd) :
1380 			big ? write_fat12_4k(ifd, 3072) : write_fat12(ifd)))
1381 		return child_fails(CHILD_IMAGE);
1382 	close(ifd);
1383 	n = loop_attach(HOLDER_IMG);
1384 	if (n < 0)
1385 		return child_fails(CHILD_LOOP);
1386 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
1387 	if (mkdir(HOLDER_MNT, 0755))
1388 		return child_fails(CHILD_MOUNT);
1389 	if (fifo ? mount(dev, HOLDER_MNT, "minix", 0, NULL) : mount_fat(dev, HOLDER_MNT))
1390 		return child_fails(errno == ENODEV ? CHILD_NOFS : CHILD_MOUNT);
1391 	if (mkdir(HOLDER_BELOW, 0755))
1392 		return child_fails(CHILD_MOUNT);
1393 
1394 	switch (holder) {
1395 	case HOLDER_AUTOFS:
1396 		ret = holder_autofs();
1397 		break;
1398 	case HOLDER_ZRAM:
1399 		ret = holder_zram();
1400 		break;
1401 	case HOLDER_ECRYPTFS:
1402 		ret = holder_ecryptfs();
1403 		break;
1404 	case HOLDER_BINFMT_MISC:
1405 		ret = holder_binfmt_misc();
1406 		break;
1407 	case HOLDER_FUSE:
1408 		ret = holder_fuse();
1409 		break;
1410 	case HOLDER_ZLOOP:
1411 		ret = holder_zloop();
1412 		break;
1413 	case HOLDER_GADGET:
1414 		ret = holder_gadget();
1415 		break;
1416 	case HOLDER_MD:
1417 		ret = holder_md();
1418 		break;
1419 	default:
1420 		ret = CHILD_HOLDER;
1421 	}
1422 	if (ret != CHILD_OK)
1423 		return child_fails(ret);
1424 
1425 	/* P's device first, then the one the holder has bound for itself */
1426 	r.n[0] = n;
1427 	if (nr_bound > 1)
1428 		r.n[1] = bound[1];
1429 	if (write(to_parent, &r, sizeof(r)) != sizeof(r) ||
1430 	    read(from_parent, &c, 1) != 1) {
1431 		/* the parent went away and will not tell the devices to let go */
1432 		umount2(HOLDER_BELOW, MNT_DETACH);
1433 		for (int i = 0; i < 50 && holder_let_go_once(holder); i++)
1434 			usleep(100000);
1435 		if (holder == HOLDER_GADGET)
1436 			gadget_remove();
1437 		return child_fails(CHILD_PIPE);
1438 	}
1439 	return CHILD_OK;
1440 }
1441 
1442 /*
1443  * The release of C's filesystem may still be in flight when the child is
1444  * gone, and a device that is still held refuses to let go, so try for a
1445  * while. With the cycle unbroken it refuses for good.
1446  */
1447 static void holder_let_go(enum holder holder)
1448 {
1449 	for (int i = 0; i < 50; i++) {
1450 		if (!holder_let_go_once(holder))
1451 			return;
1452 		usleep(100000);
1453 	}
1454 }
1455 
1456 /*
1457  * rmdir of p from here, where it is a plain directory, detaches
1458  * P in the child's namespace with C connected below it. Once the child is
1459  * gone the holder's file on P is the only thing left that refers to P,
1460  * and it is dropped only when C's filesystem dies, which waits for P.
1461  * The loop device backing P tells whether that resolved.
1462  */
1463 static void holder_cycle(struct __test_metadata *_metadata,
1464 			 FIXTURE_DATA(loop_cycle) *self, enum holder holder)
1465 {
1466 	struct report r = { { -1, -1 } };
1467 	int to_parent[2], from_parent[2];
1468 	pid_t pid;
1469 
1470 	ASSERT_EQ(pipe(to_parent), 0);
1471 	ASSERT_EQ(pipe(from_parent), 0);
1472 	pid = fork();
1473 	ASSERT_GE(pid, 0);
1474 	if (pid == 0) {
1475 		close(to_parent[0]);
1476 		close(from_parent[1]);
1477 		_exit(holder_child(to_parent[1], from_parent[0], holder));
1478 	}
1479 	close(to_parent[1]);
1480 	close(from_parent[0]);
1481 
1482 	if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
1483 		CHILD_GAVE_UP(pid);
1484 	self->gadget = holder == HOLDER_GADGET;
1485 	remember_loop(self, r.n[0]);
1486 	remember_loop(self, r.n[1]);
1487 	snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", r.n[0]);
1488 	snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", r.n[0]);
1489 
1490 	ASSERT_EQ(rmdir(HOLDER_MNT), 0);
1491 	ASSERT_EQ(write(from_parent[1], "x", 1), 1);
1492 	CHILD_LEFT(pid);
1493 	close(to_parent[0]);
1494 	close(from_parent[1]);
1495 
1496 	holder_let_go(holder);
1497 	assert_loop_released(_metadata, self);
1498 	/* the teardown takes the gadget and the holder's own loop device away */
1499 }
1500 
1501 TEST_F(loop_cycle, autofs_pipe_on_dead_mount_released)
1502 {
1503 	holder_cycle(_metadata, self, HOLDER_AUTOFS);
1504 }
1505 
1506 TEST_F(loop_cycle, zram_writeback_node_on_dead_mount_released)
1507 {
1508 	holder_cycle(_metadata, self, HOLDER_ZRAM);
1509 }
1510 
1511 TEST_F(loop_cycle, ecryptfs_lower_on_dead_mount_released)
1512 {
1513 	holder_cycle(_metadata, self, HOLDER_ECRYPTFS);
1514 }
1515 
1516 TEST_F(loop_cycle, binfmt_misc_interpreter_on_dead_mount_released)
1517 {
1518 	holder_cycle(_metadata, self, HOLDER_BINFMT_MISC);
1519 }
1520 
1521 TEST_F(loop_cycle, fuse_backing_file_on_dead_mount_released)
1522 {
1523 	holder_cycle(_metadata, self, HOLDER_FUSE);
1524 }
1525 
1526 TEST_F(loop_cycle, zloop_zone_files_on_dead_mount_released)
1527 {
1528 	holder_cycle(_metadata, self, HOLDER_ZLOOP);
1529 }
1530 
1531 /* up to 15 s for the disk to show up and 12 s for a device that is held */
1532 TEST_F_TIMEOUT(loop_cycle, mass_storage_lun_on_dead_mount_released, 120)
1533 {
1534 	holder_cycle(_metadata, self, HOLDER_GADGET);
1535 }
1536 
1537 TEST_F(loop_cycle, md_bitmap_file_on_dead_mount_released)
1538 {
1539 	holder_cycle(_metadata, self, HOLDER_MD);
1540 }
1541 
1542 TEST_HARNESS_MAIN
1543