Skip to content

Commit

Permalink
lib: A sparse file can be created with atomic_create_and_write()
Browse files Browse the repository at this point in the history
Fixes #227.

Signed-off-by: Takashi Menjo <menjo.takashi@lab.ntt.co.jp>
  • Loading branch information
tmenjo committed May 27, 2016
1 parent 2e3e1ee commit 094d723
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
37 changes: 37 additions & 0 deletions lib/common.c
Expand Up @@ -17,6 +17,7 @@
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <inttypes.h>

#include "util.h"
#include "work.h"
Expand Down Expand Up @@ -65,6 +66,42 @@ int atomic_create_and_write(const char *path, const char *buf, size_t len,
goto close_fd;
}

if (sparse) {
uint64_t nonzero_head = 0;
uint32_t nonzero_len = len;

find_zero_blocks(buf, &nonzero_head, &nonzero_len);

if (nonzero_head > 0) {
/* discard head */
ret = xfallocate(
fd, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE,
0, (size_t)nonzero_head);
if (ret < 0) {
sd_err("failed to discard file %s, "
"head %" PRIu64 ", %m",
path, nonzero_head);
goto close_fd;
}
}

const size_t nonzero_tail = nonzero_head + nonzero_len;
if (nonzero_tail < len) {
/* discard tail */
const size_t block_end = roundup(len, BLOCK_SIZE);
const size_t tail_len = block_end - nonzero_tail;
ret = xfallocate(
fd, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE,
nonzero_tail, tail_len);
if (ret < 0) {
sd_err("failed to discard file %s, "
"tail %zu, len %zu, %m",
path, nonzero_tail, tail_len);
goto close_fd;
}
}
}

ret = rename(tmp_path, path);
if (unlikely(ret < 0)) {
sd_err("failed to rename %s, %m", path);
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/lib/test_atomic_create_and_write.c
Expand Up @@ -135,7 +135,7 @@ static void test_atomic_create_and_write_sparse(void)
struct stat s;
TEST_ASSERT_EQUAL_INT(0, stat(obj_path, &s));
TEST_ASSERT_EQUAL(BUF_LEN, s.st_size);
TEST_ASSERT_EQUAL(BLOCK_SIZE, s.st_blocks * 512); /* FAIL */
TEST_ASSERT_EQUAL(BLOCK_SIZE, s.st_blocks * 512);

subtest_object_content();
}
Expand Down

0 comments on commit 094d723

Please sign in to comment.