2 * loopback block device utilities
4 * Copyright (C) 2011, Red Hat, Inc. All rights reserved.
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * version 2 as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <sys/ioctl.h>
26 #include <linux/loop.h>
30 #define LOOP_DEV_MAJOR 7
32 char *crypt_loop_get_device(void)
37 struct loop_info64 lo64 = {0};
39 for(i = 0; i < 256; i++) {
40 sprintf(dev, "/dev/loop%d", i);
41 if (stat(dev, &st) || !S_ISBLK(st.st_mode))
44 loop_fd = open(dev, O_RDONLY);
48 if(ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) && errno == ENXIO) {
58 int crypt_loop_attach(const char *loop, const char *file,
59 int offset, int *readonly)
61 struct loop_info64 lo64 = {0};
62 int loop_fd = -1, file_fd = -1, r = 1;
64 file_fd = open(file, (*readonly ? O_RDONLY : O_RDWR) | O_EXCL);
65 if (file_fd < 0 && errno == EROFS && !*readonly) {
67 file_fd = open(file, O_RDONLY | O_EXCL);
72 loop_fd = open(loop, *readonly ? O_RDONLY : O_RDWR);
76 strncpy((char*)lo64.lo_file_name, file, LO_NAME_SIZE);
77 lo64.lo_offset = offset;
78 lo64.lo_flags |= LO_FLAGS_AUTOCLEAR;
80 if (ioctl(loop_fd, LOOP_SET_FD, file_fd) < 0)
83 if (ioctl(loop_fd, LOOP_SET_STATUS64, &lo64) < 0) {
84 (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
89 if (r && loop_fd >= 0)
93 return r ? -1 : loop_fd;
96 char *crypt_loop_backing_file(const char *loop)
98 struct loop_info64 lo64 = {0};
101 loop_fd = open(loop, O_RDONLY);
105 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) < 0) {
110 lo64.lo_file_name[LO_NAME_SIZE-2] = '*';
111 lo64.lo_file_name[LO_NAME_SIZE-1] = 0;
115 return strdup((char*)lo64.lo_file_name);
118 int crypt_loop_device(const char *loop)
122 if (stat(loop, &st) || !S_ISBLK(st.st_mode) ||
123 major(st.st_rdev) != LOOP_DEV_MAJOR)