Get path size with stat or ioctl

If we're making a file system in a real device then we need to get
the device size with an ioctl.
This commit is contained in:
Zach Brown
2016-02-25 22:40:48 -08:00
parent e9baa4559b
commit 906c0186bc
3 changed files with 53 additions and 4 deletions

42
utils/src/dev.c Normal file
View File

@@ -0,0 +1,42 @@
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <errno.h>
#include "sparse.h"
#include "dev.h"
int device_size(char *path, int fd, u64 *size)
{
struct stat st;
int ret;
if (fstat(fd, &st)) {
ret = -errno;
fprintf(stderr, "failed to stat '%s': %s (%d)\n",
path, strerror(errno), errno);
return ret;
}
if (S_ISREG(st.st_mode)) {
*size = st.st_size;
} else if (S_ISBLK(st.st_mode)) {
if (ioctl(fd, BLKGETSIZE64, size)) {
ret = -errno;
fprintf(stderr, "BLKGETSIZE64 failed '%s': %s (%d)\n",
path, strerror(errno), errno);
return ret;
}
} else {
fprintf(stderr, "path isn't regular or device file '%s'\n",
path);
return -EINVAL;
}
return 0;
}

6
utils/src/dev.h Normal file
View File

@@ -0,0 +1,6 @@
#ifndef _DEV_H_
#define _DEV_H_
int device_size(char *path, int fd, u64 *size);
#endif

View File

@@ -16,6 +16,7 @@
#include "format.h"
#include "crc.h"
#include "rand.h"
#include "dev.h"
/*
* Update the block's header and write it out.
@@ -52,8 +53,8 @@ static int write_new_fs(char *path, int fd)
struct scoutfs_key root_key;
struct timeval tv;
char uuid_str[37];
struct stat st;
unsigned int i;
u64 size;
u64 total_chunks;
u64 blkno;
void *buf;
@@ -73,14 +74,14 @@ static int write_new_fs(char *path, int fd)
goto out;
}
if (fstat(fd, &st)) {
ret = -errno;
ret = device_size(path, fd, &size);
if (ret) {
fprintf(stderr, "failed to stat '%s': %s (%d)\n",
path, strerror(errno), errno);
goto out;
}
total_chunks = st.st_size >> SCOUTFS_CHUNK_SHIFT;
total_chunks = size >> SCOUTFS_CHUNK_SHIFT;
root_key.inode = cpu_to_le64(SCOUTFS_ROOT_INO);
root_key.type = SCOUTFS_INODE_KEY;