- if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
- if ((fd = open(dev, O_RDONLY)) >= 0) {
- if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) != 0) {
- if (errno == ENXIO) { /* probably free */
- close(fd);
- return strdup(dev);
- }
- }
- close(fd);
+
+ /* Ran out of block devices, return failure. */
+ if (stat(try, &statbuf) || !S_ISBLK(statbuf.st_mode)) {
+ rc = -ENOENT;
+ break;
+ }
+ /* Open the sucker and check its loopiness. */
+ dfd = open(try, mode);
+ if (dfd < 0 && errno == EROFS) {
+ mode = O_RDONLY;
+ dfd = open(try, mode);
+ }
+ if (dfd < 0)
+ goto try_again;
+
+ rc = ioctl(dfd, BB_LOOP_GET_STATUS, &loopinfo);
+
+ /* If device is free, claim it. */
+ if (rc && errno == ENXIO) {
+ memset(&loopinfo, 0, sizeof(loopinfo));
+ safe_strncpy((char *)loopinfo.lo_file_name, file, LO_NAME_SIZE);
+ loopinfo.lo_offset = offset;
+ /* Associate free loop device with file. */
+ if (!ioctl(dfd, LOOP_SET_FD, ffd)) {
+ if (!ioctl(dfd, BB_LOOP_SET_STATUS, &loopinfo))
+ rc = 0;
+ else
+ ioctl(dfd, LOOP_CLR_FD, 0);