11 #include <sys/sysmacros.h>
12 #include <sys/types.h>
16 #include <uuid/uuid.h>
18 #include "libbcachefs.h"
20 #include "libbcachefs/bcachefs_format.h"
21 #include "libbcachefs/btree_cache.h"
22 #include "libbcachefs/checksum.h"
23 #include "libbcachefs/disk_groups.h"
24 #include "libbcachefs/journal_seq_blacklist.h"
25 #include "libbcachefs/opts.h"
26 #include "libbcachefs/replicas.h"
27 #include "libbcachefs/super-io.h"
28 #include "tools-util.h"
30 #define NSEC_PER_SEC 1000000000L
32 static void init_layout(struct bch_sb_layout *l,
35 u64 sb_start, u64 sb_end)
37 u64 sb_pos = sb_start;
40 memset(l, 0, sizeof(*l));
42 l->magic = BCACHE_MAGIC;
44 l->nr_superblocks = 2;
45 l->sb_max_size_bits = ilog2(sb_size);
47 /* Create two superblocks in the allowed range: */
48 for (i = 0; i < l->nr_superblocks; i++) {
49 if (sb_pos != BCH_SB_SECTOR)
50 sb_pos = round_up(sb_pos, block_size);
52 l->sb_offset[i] = cpu_to_le64(sb_pos);
57 die("insufficient space for superblocks: start %llu end %llu > %llu size %u",
58 sb_start, sb_pos, sb_end, sb_size);
61 /* minimum size filesystem we can create, given a bucket size: */
62 static u64 min_size(unsigned bucket_size)
64 return BCH_MIN_NR_NBUCKETS * bucket_size;
67 void bch2_pick_bucket_size(struct bch_opts opts, struct dev_opts *dev)
70 dev->size = get_size(dev->path, dev->fd);
72 if (!dev->bucket_size) {
73 if (dev->size < min_size(opts.block_size))
74 die("cannot format %s, too small (%llu bytes, min %llu)",
75 dev->path, dev->size, min_size(opts.block_size));
77 /* Bucket size must be >= block size: */
78 dev->bucket_size = opts.block_size;
80 /* Bucket size must be >= btree node size: */
81 if (opt_defined(opts, btree_node_size))
82 dev->bucket_size = max_t(unsigned, dev->bucket_size,
83 opts.btree_node_size);
85 /* Want a bucket size of at least 128k, if possible: */
86 dev->bucket_size = max(dev->bucket_size, 128ULL << 10);
88 if (dev->size >= min_size(dev->bucket_size)) {
89 unsigned scale = max(1,
90 ilog2(dev->size / min_size(dev->bucket_size)) / 4);
92 scale = rounddown_pow_of_two(scale);
94 /* max bucket size 1 mb */
95 dev->bucket_size = min(dev->bucket_size * scale, 1ULL << 20);
98 dev->bucket_size /= 2;
99 } while (dev->size < min_size(dev->bucket_size));
103 dev->nbuckets = dev->size / dev->bucket_size;
105 if (dev->bucket_size < opts.block_size)
106 die("Bucket size (%llu) cannot be smaller than block size (%u)",
107 dev->bucket_size, opts.block_size);
109 if (opt_defined(opts, btree_node_size) &&
110 dev->bucket_size < opts.btree_node_size)
111 die("Bucket size (%llu) cannot be smaller than btree node size (%u)",
112 dev->bucket_size, opts.btree_node_size);
114 if (dev->nbuckets < BCH_MIN_NR_NBUCKETS)
115 die("Not enough buckets: %llu, need %u (bucket size %llu)",
116 dev->nbuckets, BCH_MIN_NR_NBUCKETS, dev->bucket_size);
118 if (dev->bucket_size > (u32) U16_MAX << 9)
119 die("Bucket size (%llu) too big (max %u)",
120 dev->bucket_size, (u32) U16_MAX << 9);
123 static unsigned parse_target(struct bch_sb_handle *sb,
124 struct dev_opts *devs, size_t nr_devs,
133 for (i = devs; i < devs + nr_devs; i++)
134 if (!strcmp(s, i->path))
135 return dev_to_target(i - devs);
137 idx = bch2_disk_path_find(sb, s);
139 return group_to_target(idx);
141 die("Invalid target %s", s);
145 struct bch_sb *bch2_format(struct bch_opt_strs fs_opt_strs,
146 struct bch_opts fs_opts,
147 struct format_opts opts,
148 struct dev_opts *devs,
151 struct bch_sb_handle sb = { NULL };
153 struct bch_sb_field_members *mi;
154 unsigned max_dev_block_size = 0;
157 for (i = devs; i < devs + nr_devs; i++)
158 max_dev_block_size = max(max_dev_block_size,
159 get_blocksize(i->path, i->fd));
161 /* calculate block size: */
162 if (!opt_defined(fs_opts, block_size)) {
163 opt_set(fs_opts, block_size, max_dev_block_size);
164 } else if (fs_opts.block_size < max_dev_block_size)
165 die("blocksize too small: %u, must be greater than device blocksize %u",
166 fs_opts.block_size, max_dev_block_size);
168 /* calculate bucket sizes: */
169 for (i = devs; i < devs + nr_devs; i++)
170 bch2_pick_bucket_size(fs_opts, i);
172 /* calculate btree node size: */
173 if (!opt_defined(fs_opts, btree_node_size)) {
174 /* 256k default btree node size */
175 opt_set(fs_opts, btree_node_size, 256 << 10);
177 for (i = devs; i < devs + nr_devs; i++)
178 fs_opts.btree_node_size =
179 min_t(unsigned, fs_opts.btree_node_size,
183 if (uuid_is_null(opts.uuid.b))
184 uuid_generate(opts.uuid.b);
186 if (bch2_sb_realloc(&sb, 0))
187 die("insufficient memory");
189 sb.sb->version = le16_to_cpu(opts.version);
190 sb.sb->version_min = le16_to_cpu(opts.version);
191 sb.sb->magic = BCACHE_MAGIC;
192 sb.sb->user_uuid = opts.uuid;
193 sb.sb->nr_devices = nr_devs;
195 if (opts.version == bcachefs_metadata_version_current)
196 sb.sb->features[0] |= BCH_SB_FEATURES_ALL;
198 uuid_generate(sb.sb->uuid.b);
203 min(strlen(opts.label), sizeof(sb.sb->label)));
206 opt_id < bch2_opts_nr;
210 v = bch2_opt_defined_by_id(&fs_opts, opt_id)
211 ? bch2_opt_get_by_id(&fs_opts, opt_id)
212 : bch2_opt_get_by_id(&bch2_opts_default, opt_id);
214 __bch2_opt_set_sb(sb.sb, &bch2_opt_table[opt_id], v);
218 if (clock_gettime(CLOCK_REALTIME, &now))
219 die("error getting current time: %m");
221 sb.sb->time_base_lo = cpu_to_le64(now.tv_sec * NSEC_PER_SEC + now.tv_nsec);
222 sb.sb->time_precision = cpu_to_le32(1);
225 mi = bch2_sb_resize_members(&sb,
226 (sizeof(*mi) + sizeof(struct bch_member) *
227 nr_devs) / sizeof(u64));
229 for (i = devs; i < devs + nr_devs; i++) {
230 struct bch_member *m = mi->members + (i - devs);
232 uuid_generate(m->uuid.b);
233 m->nbuckets = cpu_to_le64(i->nbuckets);
235 m->bucket_size = cpu_to_le16(i->bucket_size >> 9);
237 SET_BCH_MEMBER_DISCARD(m, i->discard);
238 SET_BCH_MEMBER_DATA_ALLOWED(m, i->data_allowed);
239 SET_BCH_MEMBER_DURABILITY(m, i->durability + 1);
243 for (i = devs; i < devs + nr_devs; i++) {
244 struct bch_member *m;
250 idx = bch2_disk_path_find_or_create(&sb, i->label);
252 die("error creating disk path: %s", strerror(-idx));
255 * Recompute mi and m after each sb modification: its location
256 * in memory may have changed due to reallocation.
258 mi = bch2_sb_get_members(sb.sb);
259 m = mi->members + (i - devs);
261 SET_BCH_MEMBER_GROUP(m, idx + 1);
264 SET_BCH_SB_FOREGROUND_TARGET(sb.sb,
265 parse_target(&sb, devs, nr_devs, fs_opt_strs.foreground_target));
266 SET_BCH_SB_BACKGROUND_TARGET(sb.sb,
267 parse_target(&sb, devs, nr_devs, fs_opt_strs.background_target));
268 SET_BCH_SB_PROMOTE_TARGET(sb.sb,
269 parse_target(&sb, devs, nr_devs, fs_opt_strs.promote_target));
270 SET_BCH_SB_METADATA_TARGET(sb.sb,
271 parse_target(&sb, devs, nr_devs, fs_opt_strs.metadata_target));
274 if (opts.encrypted) {
275 struct bch_sb_field_crypt *crypt =
276 bch2_sb_resize_crypt(&sb, sizeof(*crypt) / sizeof(u64));
278 bch_sb_crypt_init(sb.sb, crypt, opts.passphrase);
279 SET_BCH_SB_ENCRYPTION_TYPE(sb.sb, 1);
282 for (i = devs; i < devs + nr_devs; i++) {
283 u64 size_sectors = i->size >> 9;
285 sb.sb->dev_idx = i - devs;
288 i->sb_offset = BCH_SB_SECTOR;
289 i->sb_end = size_sectors;
292 init_layout(&sb.sb->layout, fs_opts.block_size,
293 opts.superblock_size,
294 i->sb_offset, i->sb_end);
297 * Also create a backup superblock at the end of the disk:
299 * If we're not creating a superblock at the default offset, it
300 * means we're being run from the migrate tool and we could be
301 * overwriting existing data if we write to the end of the disk:
303 if (i->sb_offset == BCH_SB_SECTOR) {
304 struct bch_sb_layout *l = &sb.sb->layout;
305 u64 backup_sb = size_sectors - (1 << l->sb_max_size_bits);
307 backup_sb = rounddown(backup_sb, i->bucket_size >> 9);
308 l->sb_offset[l->nr_superblocks++] = cpu_to_le64(backup_sb);
311 if (i->sb_offset == BCH_SB_SECTOR) {
312 /* Zero start of disk */
313 static const char zeroes[BCH_SB_SECTOR << 9];
315 xpwrite(i->fd, zeroes, BCH_SB_SECTOR << 9, 0,
316 "zeroing start of disk");
319 bch2_super_write(i->fd, sb.sb);
326 void bch2_super_write(int fd, struct bch_sb *sb)
328 struct nonce nonce = { 0 };
331 for (i = 0; i < sb->layout.nr_superblocks; i++) {
332 sb->offset = sb->layout.sb_offset[i];
334 if (sb->offset == BCH_SB_SECTOR) {
335 /* Write backup layout */
336 xpwrite(fd, &sb->layout, sizeof(sb->layout),
337 BCH_SB_LAYOUT_SECTOR << 9,
341 sb->csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb), nonce, sb);
342 xpwrite(fd, sb, vstruct_bytes(sb),
343 le64_to_cpu(sb->offset) << 9,
350 struct bch_sb *__bch2_super_read(int fd, u64 sector)
352 struct bch_sb sb, *ret;
354 xpread(fd, &sb, sizeof(sb), sector << 9);
356 if (memcmp(&sb.magic, &BCACHE_MAGIC, sizeof(sb.magic)))
357 die("not a bcachefs superblock");
359 size_t bytes = vstruct_bytes(&sb);
363 xpread(fd, ret, bytes, sector << 9);
368 /* ioctl interface: */
370 /* Global control device: */
371 int bcachectl_open(void)
373 return xopen("/dev/bcachefs-ctl", O_RDWR);
376 /* Filesystem handles (ioctl, sysfs dir): */
378 #define SYSFS_BASE "/sys/fs/bcachefs/"
380 void bcache_fs_close(struct bchfs_handle fs)
386 struct bchfs_handle bcache_fs_open(const char *path)
388 struct bchfs_handle ret;
390 if (!uuid_parse(path, ret.uuid.b)) {
391 /* It's a UUID, look it up in sysfs: */
392 char *sysfs = mprintf(SYSFS_BASE "%s", path);
393 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
395 char *minor = read_file_str(ret.sysfs_fd, "minor");
396 char *ctl = mprintf("/dev/bcachefs%s-ctl", minor);
397 ret.ioctl_fd = xopen(ctl, O_RDWR);
404 ret.ioctl_fd = open(path, O_RDONLY);
405 if (ret.ioctl_fd < 0)
406 die("Error opening filesystem at %s: %m", path);
408 struct bch_ioctl_query_uuid uuid;
409 if (ioctl(ret.ioctl_fd, BCH_IOCTL_QUERY_UUID, &uuid) < 0)
410 die("error opening %s: not a bcachefs filesystem", path);
412 ret.uuid = uuid.uuid;
415 uuid_unparse(uuid.uuid.b, uuid_str);
417 char *sysfs = mprintf(SYSFS_BASE "%s", uuid_str);
418 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
426 * Given a path to a block device, open the filesystem it belongs to; also
427 * return the device's idx:
429 struct bchfs_handle bchu_fs_open_by_dev(const char *path, int *idx)
431 char buf[1024], *uuid_str;
433 struct stat stat = xstat(path);
435 if (!S_ISBLK(stat.st_mode))
436 die("%s is not a block device", path);
438 char *sysfs = mprintf("/sys/dev/block/%u:%u/bcachefs",
441 ssize_t len = readlink(sysfs, buf, sizeof(buf));
445 char *p = strrchr(buf, '/');
446 if (!p || sscanf(p + 1, "dev-%u", idx) != 1)
447 die("error parsing sysfs");
450 p = strrchr(buf, '/');
453 struct bch_opts opts = bch2_opts_empty();
455 opt_set(opts, noexcl, true);
456 opt_set(opts, nochanges, true);
458 struct bch_sb_handle sb;
459 int ret = bch2_read_super(path, &opts, &sb);
461 die("Error opening %s: %s", path, strerror(-ret));
463 *idx = sb.sb->dev_idx;
465 uuid_unparse(sb.sb->user_uuid.b, uuid_str);
467 bch2_free_super(&sb);
470 return bcache_fs_open(uuid_str);
473 int bchu_dev_path_to_idx(struct bchfs_handle fs, const char *dev_path)
476 struct bchfs_handle fs2 = bchu_fs_open_by_dev(dev_path, &idx);
478 if (memcmp(&fs.uuid, &fs2.uuid, sizeof(fs.uuid)))
480 bcache_fs_close(fs2);
484 int bchu_data(struct bchfs_handle fs, struct bch_ioctl_data cmd)
486 int progress_fd = xioctl(fs.ioctl_fd, BCH_IOCTL_DATA, &cmd);
489 struct bch_ioctl_data_event e;
491 if (read(progress_fd, &e, sizeof(e)) != sizeof(e))
492 die("error reading from progress fd %m");
497 if (e.p.data_type == U8_MAX)
502 printf("%llu%% complete: current position %s",
504 ? e.p.sectors_done * 100 / e.p.sectors_total
506 bch2_data_types[e.p.data_type]);
508 switch (e.p.data_type) {
511 printf(" %s:%llu:%llu",
512 bch2_btree_ids[e.p.btree_id],
528 void bch2_opt_strs_free(struct bch_opt_strs *opts)
532 for (i = 0; i < bch2_opts_nr; i++) {
533 free(opts->by_id[i]);
534 opts->by_id[i] = NULL;
538 struct bch_opt_strs bch2_cmdline_opts_get(int *argc, char *argv[],
541 struct bch_opt_strs opts;
544 memset(&opts, 0, sizeof(opts));
547 char *optstr = strcmp_prefix(argv[i], "--");
548 char *valstr = NULL, *p;
549 int optid, nr_args = 1;
556 optstr = strdup(optstr);
559 while (isalpha(*p) || *p == '_')
567 optid = bch2_opt_lookup(optstr);
569 !(bch2_opt_table[optid].flags & opt_types)) {
575 bch2_opt_table[optid].type != BCH_OPT_BOOL) {
577 valstr = argv[i + 1];
583 opts.by_id[optid] = strdup(valstr);
588 sizeof(char *) * (*argc - i));
597 struct bch_opts bch2_parse_opts(struct bch_opt_strs strs)
599 struct bch_opts opts = bch2_opts_empty();
600 struct printbuf err = PRINTBUF;
605 for (i = 0; i < bch2_opts_nr; i++) {
606 if (!strs.by_id[i] ||
607 bch2_opt_table[i].type == BCH_OPT_FN)
610 ret = bch2_opt_parse(NULL,
612 strs.by_id[i], &v, &err);
614 die("Invalid option %s", err.buf);
616 bch2_opt_set_by_id(&opts, i, v);
628 void bch2_opts_usage(unsigned opt_types)
630 const struct bch_option *opt;
631 unsigned i, c = 0, helpcol = 30;
635 for (opt = bch2_opt_table;
636 opt < bch2_opt_table + bch2_opts_nr;
638 if (!(opt->flags & opt_types))
641 c += printf(" --%s", opt->attr.name);
648 for (i = 0; opt->choices[i]; i++) {
651 c += printf("%s", opt->choices[i]);
656 c += printf("=%s", opt->hint);
661 const char *l = opt->help;
667 const char *n = strchrnul(l, '\n');
669 while (c < helpcol) {
673 printf("%.*s", (int) (n - l), l);
686 dev_names bchu_fs_get_devices(struct bchfs_handle fs)
688 DIR *dir = fdopendir(fs.sysfs_fd);
694 while ((errno = 0), (d = readdir(dir))) {
695 struct dev_name n = { 0, NULL, NULL };
697 if (sscanf(d->d_name, "dev-%u", &n.idx) != 1)
700 char *block_attr = mprintf("dev-%u/block", n.idx);
702 char sysfs_block_buf[4096];
703 ssize_t r = readlinkat(fs.sysfs_fd, block_attr,
704 sysfs_block_buf, sizeof(sysfs_block_buf));
706 sysfs_block_buf[r] = '\0';
707 n.dev = strdup(basename(sysfs_block_buf));
712 char *label_attr = mprintf("dev-%u/label", n.idx);
713 n.label = read_file_str(fs.sysfs_fd, label_attr);
716 darray_push(devs, n);