xref: /linux/tools/testing/selftests/filesystems/freeze/loop_util.h (revision 486b257357c23743d9729ea715136d105fff461e)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __SELFTESTS_FILESYSTEMS_FREEZE_LOOP_UTIL_H
3 #define __SELFTESTS_FILESYSTEMS_FREEZE_LOOP_UTIL_H
4 
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <linux/loop.h>
8 #include <stdbool.h>
9 #include <stdio.h>
10 #include <sys/ioctl.h>
11 #include <unistd.h>
12 
13 /* How often to retry when somebody else binds the free device first. */
14 #define LOOP_BIND_TRIES 64
15 
16 /* Bind a free loop device to @fd; its number or -errno. */
17 static inline int loop_bind(int fd)
18 {
19 	for (int i = 0; i < LOOP_BIND_TRIES; i++) {
20 		char dev[32];
21 		int cfd, lfd, n, err;
22 
23 		cfd = open("/dev/loop-control", O_RDWR | O_CLOEXEC);
24 		if (cfd < 0)
25 			return -errno;
26 		n = ioctl(cfd, LOOP_CTL_GET_FREE);
27 		err = errno;
28 		close(cfd);
29 		if (n < 0)
30 			return -err;
31 		snprintf(dev, sizeof(dev), "/dev/loop%d", n);
32 		lfd = open(dev, O_RDWR | O_CLOEXEC);
33 		if (lfd < 0)
34 			return -errno;
35 		err = ioctl(lfd, LOOP_SET_FD, fd) ? errno : 0;
36 		close(lfd);
37 		if (!err)
38 			return n;
39 		if (err != EBUSY)
40 			return -err;
41 	}
42 	return -EBUSY;
43 }
44 
45 /* Did loop_bind() fail because there are no loop device nodes or no driver? */
46 static inline bool loop_missing(int ret)
47 {
48 	return ret == -ENOENT || ret == -ENODEV;
49 }
50 
51 static inline void loop_clear(int n)
52 {
53 	char dev[32];
54 	int fd;
55 
56 	snprintf(dev, sizeof(dev), "/dev/loop%d", n);
57 	fd = open(dev, O_RDWR | O_CLOEXEC);
58 	if (fd < 0)
59 		return;
60 	ioctl(fd, LOOP_CLR_FD, 0);
61 	close(fd);
62 }
63 
64 #endif /* __SELFTESTS_FILESYSTEMS_FREEZE_LOOP_UTIL_H */
65