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
25 #include <sys/ioctl.h>
27 #include <linux/loop.h>
29 #include "utils_loop.h"
31 char *crypt_loop_get_device(void)
36 struct loop_info64 lo64 = {0};
38 for (i = 0; i < 256; i++) {
39 sprintf(dev, "/dev/loop%d", i);
40 if (stat(dev, &st) || !S_ISBLK(st.st_mode))
43 loop_fd = open(dev, O_RDONLY);
47 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) &&
58 int crypt_loop_attach(const char *loop, const char *file, int offset,
59 int autoclear, 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;
79 lo64.lo_flags |= LO_FLAGS_AUTOCLEAR;
81 if (ioctl(loop_fd, LOOP_SET_FD, file_fd) < 0)
84 if (ioctl(loop_fd, LOOP_SET_STATUS64, &lo64) < 0) {
85 (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
89 /* Verify that autoclear is really set */
91 memset(&lo64, 0, sizeof(lo64));
92 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) < 0 ||
93 !(lo64.lo_flags & LO_FLAGS_AUTOCLEAR)) {
94 (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
101 if (r && loop_fd >= 0)
105 return r ? -1 : loop_fd;
108 int crypt_loop_detach(const char *loop)
110 int loop_fd = -1, r = 1;
112 loop_fd = open(loop, O_RDONLY);
116 if (!ioctl(loop_fd, LOOP_CLR_FD, 0))
123 char *crypt_loop_backing_file(const char *loop)
125 struct loop_info64 lo64 = {0};
128 loop_fd = open(loop, O_RDONLY);
132 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) < 0) {
137 lo64.lo_file_name[LO_NAME_SIZE-2] = '*';
138 lo64.lo_file_name[LO_NAME_SIZE-1] = 0;
142 return strdup((char*)lo64.lo_file_name);
145 int crypt_loop_device(const char *loop)
152 if (stat(loop, &st) || !S_ISBLK(st.st_mode) ||
153 major(st.st_rdev) != LOOP_DEV_MAJOR)