f2fs-tools: avoid mounting f2fs if tools already open the device
authorSheng Yong <shengyong1@huawei.com>
Wed, 4 Jul 2018 09:50:45 +0000 (17:50 +0800)
committerJaegeuk Kim <jaegeuk@kernel.org>
Tue, 28 Aug 2018 06:49:26 +0000 (23:49 -0700)
If the block device is opened by tools, F2FS should not be mounted.
Especially when fsck is running, errors unexpected may happen. So if
tools open a block device, we give it the O_EXCL flag to make sure
the block device is opened exclusivly.

Signed-off-by: Sheng Yong <shengyong1@huawei.com>
Reviewed-by: Chao Yu <yuchao0@huawei.com>
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
lib/libf2fs.c

index b25fbf2..5625cff 100644 (file)
@@ -783,21 +783,35 @@ int get_device_info(int i)
 #endif
        struct device_info *dev = c.devices + i;
 
+       stat_buf = malloc(sizeof(struct stat));
+       ASSERT(stat_buf);
+       if (stat(dev->path, stat_buf) < 0 ) {
+               MSG(0, "\tError: Failed to get the device stat!\n");
+               free(stat_buf);
+               return -1;
+       }
+
        if (c.sparse_mode) {
-               fd = open((char *)dev->path, O_RDWR | O_CREAT | O_BINARY, 0644);
+               fd = open(dev->path, O_RDWR | O_CREAT | O_BINARY, 0644);
        } else {
-               fd = open((char *)dev->path, O_RDWR);
+               if (S_ISBLK(stat_buf->st_mode))
+                       fd = open(dev->path, O_RDWR | O_EXCL);
+               else
+                       fd = open(dev->path, O_RDWR);
        }
        if (fd < 0) {
                MSG(0, "\tError: Failed to open the device!\n");
+               free(stat_buf);
                return -1;
        }
 
        dev->fd = fd;
 
        if (c.sparse_mode) {
-               if (f2fs_init_sparse_file())
+               if (f2fs_init_sparse_file()) {
+                       free(stat_buf);
                        return -1;
+               }
        }
 
        if (c.kd == -1) {
@@ -810,13 +824,6 @@ int get_device_info(int i)
                }
        }
 
-       stat_buf = malloc(sizeof(struct stat));
-       if (fstat(fd, stat_buf) < 0 ) {
-               MSG(0, "\tError: Failed to get the device stat!\n");
-               free(stat_buf);
-               return -1;
-       }
-
        if (c.sparse_mode) {
                dev->total_sectors = c.device_size / dev->sector_size;
        } else if (S_ISREG(stat_buf->st_mode)) {