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) && errno == ENXIO) {
57 int crypt_loop_attach(const char *loop, const char *file,
58 int offset, int *readonly)
60 struct loop_info64 lo64 = {0};
61 int loop_fd = -1, file_fd = -1, r = 1;
63 file_fd = open(file, (*readonly ? O_RDONLY : O_RDWR) | O_EXCL);
64 if (file_fd < 0 && errno == EROFS && !*readonly) {
66 file_fd = open(file, O_RDONLY | O_EXCL);
71 loop_fd = open(loop, *readonly ? O_RDONLY : O_RDWR);
75 strncpy((char*)lo64.lo_file_name, file, LO_NAME_SIZE);
76 lo64.lo_offset = offset;
77 lo64.lo_flags |= LO_FLAGS_AUTOCLEAR;
79 if (ioctl(loop_fd, LOOP_SET_FD, file_fd) < 0)
82 if (ioctl(loop_fd, LOOP_SET_STATUS64, &lo64) < 0) {
83 (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
87 /* Verify that autoclear is really set */
88 memset(&lo64, 0, sizeof(lo64));
89 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) < 0 ||
90 !(lo64.lo_flags & LO_FLAGS_AUTOCLEAR)) {
91 (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
97 if (r && loop_fd >= 0)
101 return r ? -1 : loop_fd;
104 char *crypt_loop_backing_file(const char *loop)
106 struct loop_info64 lo64 = {0};
109 loop_fd = open(loop, O_RDONLY);
113 if (ioctl(loop_fd, LOOP_GET_STATUS64, &lo64) < 0) {
118 lo64.lo_file_name[LO_NAME_SIZE-2] = '*';
119 lo64.lo_file_name[LO_NAME_SIZE-1] = 0;
123 return strdup((char*)lo64.lo_file_name);
126 int crypt_loop_device(const char *loop)
130 if (stat(loop, &st) || !S_ISBLK(st.st_mode) ||
131 major(st.st_rdev) != LOOP_DEV_MAJOR)