1// Copyright 2017 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <errno.h>
6#include <fcntl.h>
7#include <sys/stat.h>
8#include <unistd.h>
9#include <stdlib.h>
10#include "util.h"
11
12#include <minfs/fsck.h>
13
14void setup_fs_test(size_t disk_size) {
15    int r = open(MOUNT_PATH, O_RDWR | O_CREAT | O_EXCL, 0755);
16
17    if (r < 0) {
18        fprintf(stderr, "Unable to create disk for test filesystem\n");
19        exit(-1);
20    }
21
22    if (ftruncate(r, disk_size) < 0) {
23        fprintf(stderr, "Unable to truncate disk\n");
24        exit(-1);
25    }
26
27    if (close(r) < 0) {
28        fprintf(stderr, "Unable to close disk\n");
29        exit(-1);
30    }
31
32    if (emu_mkfs(MOUNT_PATH) < 0) {
33        fprintf(stderr, "Unable to run mkfs\n");
34        exit(-1);
35    }
36
37    if (emu_mount(MOUNT_PATH) < 0) {
38        fprintf(stderr, "Unable to run mount\n");
39        exit(-1);
40    }
41}
42
43void teardown_fs_test() {
44    if (unlink(MOUNT_PATH) < 0) {
45        exit(-1);
46    }
47}
48
49int run_fsck() {
50    fbl::unique_fd disk(open(MOUNT_PATH, O_RDONLY));
51
52    if (!disk) {
53        fprintf(stderr, "Unable to open disk for fsck\n");
54        return -1;
55    }
56
57    struct stat stats;
58    if (fstat(disk.get(), &stats) < 0) {
59        fprintf(stderr, "error: minfs could not find end of file/device\n");
60        return 0;
61    }
62
63    if (stats.st_size == 0) {
64        fprintf(stderr, "Invalid disk\n");
65        return -1;
66    }
67
68    size_t size = stats.st_size /= minfs::kMinfsBlockSize;
69
70    fbl::unique_ptr<minfs::Bcache> block_cache;
71    if (minfs::Bcache::Create(&block_cache, fbl::move(disk), size) < 0) {
72        fprintf(stderr, "error: cannot create block cache\n");
73        return -1;
74    }
75
76    return minfs_check(fbl::move(block_cache));
77}
78