]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs.c
Add upstream files
[bcachefs-tools-debian] / libbcachefs.c
1 #include <ctype.h>
2 #include <dirent.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdbool.h>
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/stat.h>
11 #include <sys/sysmacros.h>
12 #include <sys/types.h>
13 #include <time.h>
14 #include <unistd.h>
15
16 #include <uuid/uuid.h>
17
18 #include "libbcachefs.h"
19 #include "crypto.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"
29
30 #define NSEC_PER_SEC    1000000000L
31
32 /* minimum size filesystem we can create, given a bucket size: */
33 static u64 min_size(unsigned bucket_size)
34 {
35         return BCH_MIN_NR_NBUCKETS * bucket_size;
36 }
37
38 static void init_layout(struct bch_sb_layout *l, unsigned block_size,
39                         u64 start, u64 end)
40 {
41         unsigned sb_size;
42         u64 backup; /* offset of 2nd sb */
43
44         memset(l, 0, sizeof(*l));
45
46         if (start != BCH_SB_SECTOR)
47                 start = round_up(start, block_size);
48         end = round_down(end, block_size);
49
50         if (start >= end)
51                 die("insufficient space for superblocks");
52
53         /*
54          * Create two superblocks in the allowed range: reserve a maximum of 64k
55          */
56         sb_size = min_t(u64, 128, end - start / 2);
57
58         backup = start + sb_size;
59         backup = round_up(backup, block_size);
60
61         backup = min(backup, end);
62
63         sb_size = min(end - backup, backup- start);
64         sb_size = rounddown_pow_of_two(sb_size);
65
66         if (sb_size < 8)
67                 die("insufficient space for superblocks");
68
69         l->magic                = BCACHE_MAGIC;
70         l->layout_type          = 0;
71         l->nr_superblocks       = 2;
72         l->sb_max_size_bits     = ilog2(sb_size);
73         l->sb_offset[0]         = cpu_to_le64(start);
74         l->sb_offset[1]         = cpu_to_le64(backup);
75 }
76
77 void bch2_pick_bucket_size(struct bch_opts opts, struct dev_opts *dev)
78 {
79         if (!dev->sb_offset) {
80                 dev->sb_offset  = BCH_SB_SECTOR;
81                 dev->sb_end     = BCH_SB_SECTOR + 256;
82         }
83
84         if (!dev->size)
85                 dev->size = get_size(dev->path, dev->fd) >> 9;
86
87         if (!dev->bucket_size) {
88                 if (dev->size < min_size(opts.block_size))
89                         die("cannot format %s, too small (%llu sectors, min %llu)",
90                             dev->path, dev->size, min_size(opts.block_size));
91
92                 /* Bucket size must be >= block size: */
93                 dev->bucket_size = opts.block_size;
94
95                 /* Bucket size must be >= btree node size: */
96                 if (opt_defined(opts, btree_node_size))
97                         dev->bucket_size = max_t(unsigned, dev->bucket_size,
98                                                  opts.btree_node_size);
99
100                 /* Want a bucket size of at least 128k, if possible: */
101                 dev->bucket_size = max(dev->bucket_size, 256U);
102
103                 if (dev->size >= min_size(dev->bucket_size)) {
104                         unsigned scale = max(1,
105                                              ilog2(dev->size / min_size(dev->bucket_size)) / 4);
106
107                         scale = rounddown_pow_of_two(scale);
108
109                         /* max bucket size 1 mb */
110                         dev->bucket_size = min(dev->bucket_size * scale, 1U << 11);
111                 } else {
112                         do {
113                                 dev->bucket_size /= 2;
114                         } while (dev->size < min_size(dev->bucket_size));
115                 }
116         }
117
118         dev->nbuckets   = dev->size / dev->bucket_size;
119
120         if (dev->bucket_size < opts.block_size)
121                 die("Bucket size cannot be smaller than block size");
122
123         if (opt_defined(opts, btree_node_size) &&
124             dev->bucket_size < opts.btree_node_size)
125                 die("Bucket size cannot be smaller than btree node size");
126
127         if (dev->nbuckets < BCH_MIN_NR_NBUCKETS)
128                 die("Not enough buckets: %llu, need %u (bucket size %u)",
129                     dev->nbuckets, BCH_MIN_NR_NBUCKETS, dev->bucket_size);
130
131 }
132
133 static unsigned parse_target(struct bch_sb_handle *sb,
134                              struct dev_opts *devs, size_t nr_devs,
135                              const char *s)
136 {
137         struct dev_opts *i;
138         int idx;
139
140         if (!s)
141                 return 0;
142
143         for (i = devs; i < devs + nr_devs; i++)
144                 if (!strcmp(s, i->path))
145                         return dev_to_target(i - devs);
146
147         idx = bch2_disk_path_find(sb, s);
148         if (idx >= 0)
149                 return group_to_target(idx);
150
151         die("Invalid target %s", s);
152         return 0;
153 }
154
155 struct bch_sb *bch2_format(struct bch_opt_strs  fs_opt_strs,
156                            struct bch_opts      fs_opts,
157                            struct format_opts   opts,
158                            struct dev_opts      *devs,
159                            size_t               nr_devs)
160 {
161         struct bch_sb_handle sb = { NULL };
162         struct dev_opts *i;
163         struct bch_sb_field_members *mi;
164         unsigned max_dev_block_size = 0;
165         unsigned opt_id;
166
167         for (i = devs; i < devs + nr_devs; i++)
168                 max_dev_block_size = max(max_dev_block_size,
169                                          get_blocksize(i->path, i->fd));
170
171         /* calculate block size: */
172         if (!opt_defined(fs_opts, block_size)) {
173                 opt_set(fs_opts, block_size, max_dev_block_size);
174         } else if (fs_opts.block_size < max_dev_block_size)
175                 die("blocksize too small: %u, must be greater than device blocksize %u",
176                     fs_opts.block_size, max_dev_block_size);
177
178         /* calculate bucket sizes: */
179         for (i = devs; i < devs + nr_devs; i++)
180                 bch2_pick_bucket_size(fs_opts, i);
181
182         /* calculate btree node size: */
183         if (!opt_defined(fs_opts, btree_node_size)) {
184                 /* 256k default btree node size */
185                 opt_set(fs_opts, btree_node_size, 512);
186
187                 for (i = devs; i < devs + nr_devs; i++)
188                         fs_opts.btree_node_size =
189                                 min_t(unsigned, fs_opts.btree_node_size,
190                                       i->bucket_size);
191         }
192
193         if (!is_power_of_2(fs_opts.block_size))
194                 die("block size must be power of 2");
195
196         if (!is_power_of_2(fs_opts.btree_node_size))
197                 die("btree node size must be power of 2");
198
199         if (uuid_is_null(opts.uuid.b))
200                 uuid_generate(opts.uuid.b);
201
202         if (bch2_sb_realloc(&sb, 0))
203                 die("insufficient memory");
204
205         sb.sb->version          = le16_to_cpu(bcachefs_metadata_version_current);
206         sb.sb->version_min      = le16_to_cpu(bcachefs_metadata_version_current);
207         sb.sb->magic            = BCACHE_MAGIC;
208         sb.sb->block_size       = cpu_to_le16(fs_opts.block_size);
209         sb.sb->user_uuid        = opts.uuid;
210         sb.sb->nr_devices       = nr_devs;
211
212         uuid_generate(sb.sb->uuid.b);
213
214         if (opts.label)
215                 memcpy(sb.sb->label,
216                        opts.label,
217                        min(strlen(opts.label), sizeof(sb.sb->label)));
218
219         for (opt_id = 0;
220              opt_id < bch2_opts_nr;
221              opt_id++) {
222                 const struct bch_option *opt = &bch2_opt_table[opt_id];
223                 u64 v;
224
225                 if (opt->set_sb == SET_NO_SB_OPT)
226                         continue;
227
228                 v = bch2_opt_defined_by_id(&fs_opts, opt_id)
229                         ? bch2_opt_get_by_id(&fs_opts, opt_id)
230                         : bch2_opt_get_by_id(&bch2_opts_default, opt_id);
231
232                 opt->set_sb(sb.sb, v);
233         }
234
235         SET_BCH_SB_ENCODED_EXTENT_MAX_BITS(sb.sb,
236                                 ilog2(opts.encoded_extent_max));
237
238         struct timespec now;
239         if (clock_gettime(CLOCK_REALTIME, &now))
240                 die("error getting current time: %m");
241
242         sb.sb->time_base_lo     = cpu_to_le64(now.tv_sec * NSEC_PER_SEC + now.tv_nsec);
243         sb.sb->time_precision   = cpu_to_le32(1);
244
245         /* Member info: */
246         mi = bch2_sb_resize_members(&sb,
247                         (sizeof(*mi) + sizeof(struct bch_member) *
248                          nr_devs) / sizeof(u64));
249
250         for (i = devs; i < devs + nr_devs; i++) {
251                 struct bch_member *m = mi->members + (i - devs);
252
253                 uuid_generate(m->uuid.b);
254                 m->nbuckets     = cpu_to_le64(i->nbuckets);
255                 m->first_bucket = 0;
256                 m->bucket_size  = cpu_to_le16(i->bucket_size);
257
258                 SET_BCH_MEMBER_REPLACEMENT(m,   CACHE_REPLACEMENT_LRU);
259                 SET_BCH_MEMBER_DISCARD(m,       i->discard);
260                 SET_BCH_MEMBER_DATA_ALLOWED(m,  i->data_allowed);
261                 SET_BCH_MEMBER_DURABILITY(m,    i->durability + 1);
262         }
263
264         /* Disk groups */
265         for (i = devs; i < devs + nr_devs; i++) {
266                 struct bch_member *m = mi->members + (i - devs);
267                 int idx;
268
269                 if (!i->group)
270                         continue;
271
272                 idx = bch2_disk_path_find_or_create(&sb, i->group);
273                 if (idx < 0)
274                         die("error creating disk path: %s", idx);
275
276                 SET_BCH_MEMBER_GROUP(m, idx + 1);
277         }
278
279         SET_BCH_SB_FOREGROUND_TARGET(sb.sb,
280                 parse_target(&sb, devs, nr_devs, fs_opt_strs.foreground_target));
281         SET_BCH_SB_BACKGROUND_TARGET(sb.sb,
282                 parse_target(&sb, devs, nr_devs, fs_opt_strs.background_target));
283         SET_BCH_SB_PROMOTE_TARGET(sb.sb,
284                 parse_target(&sb, devs, nr_devs, fs_opt_strs.promote_target));
285
286         /* Crypt: */
287         if (opts.encrypted) {
288                 struct bch_sb_field_crypt *crypt =
289                         bch2_sb_resize_crypt(&sb, sizeof(*crypt) / sizeof(u64));
290
291                 bch_sb_crypt_init(sb.sb, crypt, opts.passphrase);
292                 SET_BCH_SB_ENCRYPTION_TYPE(sb.sb, 1);
293         }
294
295         for (i = devs; i < devs + nr_devs; i++) {
296                 sb.sb->dev_idx = i - devs;
297
298                 init_layout(&sb.sb->layout, fs_opts.block_size,
299                             i->sb_offset, i->sb_end);
300
301                 if (i->sb_offset == BCH_SB_SECTOR) {
302                         /* Zero start of disk */
303                         static const char zeroes[BCH_SB_SECTOR << 9];
304
305                         xpwrite(i->fd, zeroes, BCH_SB_SECTOR << 9, 0);
306                 }
307
308                 bch2_super_write(i->fd, sb.sb);
309                 close(i->fd);
310         }
311
312         return sb.sb;
313 }
314
315 void bch2_super_write(int fd, struct bch_sb *sb)
316 {
317         struct nonce nonce = { 0 };
318
319         unsigned i;
320         for (i = 0; i < sb->layout.nr_superblocks; i++) {
321                 sb->offset = sb->layout.sb_offset[i];
322
323                 if (sb->offset == BCH_SB_SECTOR) {
324                         /* Write backup layout */
325                         xpwrite(fd, &sb->layout, sizeof(sb->layout),
326                                 BCH_SB_LAYOUT_SECTOR << 9);
327                 }
328
329                 sb->csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb), nonce, sb);
330                 xpwrite(fd, sb, vstruct_bytes(sb),
331                         le64_to_cpu(sb->offset) << 9);
332         }
333
334         fsync(fd);
335 }
336
337 struct bch_sb *__bch2_super_read(int fd, u64 sector)
338 {
339         struct bch_sb sb, *ret;
340
341         xpread(fd, &sb, sizeof(sb), sector << 9);
342
343         if (memcmp(&sb.magic, &BCACHE_MAGIC, sizeof(sb.magic)))
344                 die("not a bcachefs superblock");
345
346         size_t bytes = vstruct_bytes(&sb);
347
348         ret = malloc(bytes);
349
350         xpread(fd, ret, bytes, sector << 9);
351
352         return ret;
353 }
354
355 static unsigned get_dev_has_data(struct bch_sb *sb, unsigned dev)
356 {
357         struct bch_sb_field_replicas *replicas;
358         struct bch_replicas_entry *r;
359         unsigned i, data_has = 0;
360
361         replicas = bch2_sb_get_replicas(sb);
362
363         if (replicas)
364                 for_each_replicas_entry(replicas, r)
365                         for (i = 0; i < r->nr_devs; i++)
366                                 if (r->devs[i] == dev)
367                                         data_has |= 1 << r->data_type;
368
369         return data_has;
370 }
371
372 static int bch2_sb_get_target(struct bch_sb *sb, char *buf, size_t len, u64 v)
373 {
374         struct target t = target_decode(v);
375         int ret;
376
377         switch (t.type) {
378         case TARGET_NULL:
379                 return scnprintf(buf, len, "none");
380         case TARGET_DEV: {
381                 struct bch_sb_field_members *mi = bch2_sb_get_members(sb);
382                 struct bch_member *m = mi->members + t.dev;
383
384                 if (bch2_dev_exists(sb, mi, t.dev)) {
385                         char uuid_str[40];
386
387                         uuid_unparse(m->uuid.b, uuid_str);
388
389                         ret = scnprintf(buf, len, "Device %u (%s)", t.dev,
390                                 uuid_str);
391                 } else {
392                         ret = scnprintf(buf, len, "Bad device %u", t.dev);
393                 }
394
395                 break;
396         }
397         case TARGET_GROUP: {
398                 struct bch_sb_field_disk_groups *gi;
399                 gi = bch2_sb_get_disk_groups(sb);
400
401                 struct bch_disk_group *g = gi->entries + t.group;
402
403                 if (t.group < disk_groups_nr(gi) && !BCH_GROUP_DELETED(g)) {
404                         ret = scnprintf(buf, len, "Group %u (%.*s)", t.group,
405                                 BCH_SB_LABEL_SIZE, g->label);
406                 } else {
407                         ret = scnprintf(buf, len, "Bad group %u", t.group);
408                 }
409                 break;
410         }
411         default:
412                 BUG();
413         }
414
415         return ret;
416 }
417
418 /* superblock printing: */
419
420 static void bch2_sb_print_layout(struct bch_sb *sb, enum units units)
421 {
422         struct bch_sb_layout *l = &sb->layout;
423         unsigned i;
424
425         printf("  type:                         %u\n"
426                "  superblock max size:          %s\n"
427                "  nr superblocks:               %u\n"
428                "  Offsets:                      ",
429                l->layout_type,
430                pr_units(1 << l->sb_max_size_bits, units),
431                l->nr_superblocks);
432
433         for (i = 0; i < l->nr_superblocks; i++) {
434                 if (i)
435                         printf(", ");
436                 printf("%llu", le64_to_cpu(l->sb_offset[i]));
437         }
438         putchar('\n');
439 }
440
441 static void bch2_sb_print_journal(struct bch_sb *sb, struct bch_sb_field *f,
442                                   enum units units)
443 {
444         struct bch_sb_field_journal *journal = field_to_type(f, journal);
445         unsigned i, nr = bch2_nr_journal_buckets(journal);
446
447         printf("  Buckets:                      ");
448         for (i = 0; i < nr; i++) {
449                 if (i)
450                         putchar(' ');
451                 printf("%llu", le64_to_cpu(journal->buckets[i]));
452         }
453         putchar('\n');
454 }
455
456 static void bch2_sb_print_members(struct bch_sb *sb, struct bch_sb_field *f,
457                                   enum units units)
458 {
459         struct bch_sb_field_members *mi = field_to_type(f, members);
460         struct bch_sb_field_disk_groups *gi = bch2_sb_get_disk_groups(sb);
461         unsigned i;
462
463         for (i = 0; i < sb->nr_devices; i++) {
464                 struct bch_member *m = mi->members + i;
465                 time_t last_mount = le64_to_cpu(m->last_mount);
466                 char member_uuid_str[40];
467                 char data_allowed_str[100];
468                 char data_has_str[100];
469                 char group[BCH_SB_LABEL_SIZE+10];
470                 char time_str[64];
471
472                 if (!bch2_member_exists(m))
473                         continue;
474
475                 uuid_unparse(m->uuid.b, member_uuid_str);
476
477                 if (BCH_MEMBER_GROUP(m)) {
478                         unsigned idx = BCH_MEMBER_GROUP(m) - 1;
479
480                         if (idx < disk_groups_nr(gi)) {
481                                 snprintf(group, sizeof(group), "%.*s (%u)",
482                                         BCH_SB_LABEL_SIZE,
483                                         gi->entries[idx].label, idx);
484                         } else {
485                                 strcpy(group, "(bad disk groups section)");
486                         }
487                 } else {
488                         strcpy(group, "(none)");
489                 }
490
491                 bch2_flags_to_text(&PBUF(data_allowed_str),
492                                    bch2_data_types,
493                                    BCH_MEMBER_DATA_ALLOWED(m));
494                 if (!data_allowed_str[0])
495                         strcpy(data_allowed_str, "(none)");
496
497                 bch2_flags_to_text(&PBUF(data_has_str),
498                                    bch2_data_types,
499                                    get_dev_has_data(sb, i));
500                 if (!data_has_str[0])
501                         strcpy(data_has_str, "(none)");
502
503                 if (last_mount) {
504                         struct tm *tm = localtime(&last_mount);
505                         size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
506                         if (!err)
507                                 strcpy(time_str, "(formatting error)");
508                 } else {
509                         strcpy(time_str, "(never)");
510                 }
511
512                 printf("  Device %u:\n"
513                        "    UUID:                       %s\n"
514                        "    Size:                       %s\n"
515                        "    Bucket size:                %s\n"
516                        "    First bucket:               %u\n"
517                        "    Buckets:                    %llu\n"
518                        "    Last mount:                 %s\n"
519                        "    State:                      %s\n"
520                        "    Group:                      %s\n"
521                        "    Data allowed:               %s\n"
522
523                        "    Has data:                   %s\n"
524
525                        "    Replacement policy:         %s\n"
526                        "    Discard:                    %llu\n",
527                        i, member_uuid_str,
528                        pr_units(le16_to_cpu(m->bucket_size) *
529                                 le64_to_cpu(m->nbuckets), units),
530                        pr_units(le16_to_cpu(m->bucket_size), units),
531                        le16_to_cpu(m->first_bucket),
532                        le64_to_cpu(m->nbuckets),
533                        time_str,
534
535                        BCH_MEMBER_STATE(m) < BCH_MEMBER_STATE_NR
536                        ? bch2_dev_state[BCH_MEMBER_STATE(m)]
537                        : "unknown",
538
539                        group,
540                        data_allowed_str,
541                        data_has_str,
542
543                        BCH_MEMBER_REPLACEMENT(m) < CACHE_REPLACEMENT_NR
544                        ? bch2_cache_replacement_policies[BCH_MEMBER_REPLACEMENT(m)]
545                        : "unknown",
546
547                        BCH_MEMBER_DISCARD(m));
548         }
549 }
550
551 static void bch2_sb_print_crypt(struct bch_sb *sb, struct bch_sb_field *f,
552                                 enum units units)
553 {
554         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
555
556         printf("  KFD:                  %llu\n"
557                "  scrypt n:             %llu\n"
558                "  scrypt r:             %llu\n"
559                "  scrypt p:             %llu\n",
560                BCH_CRYPT_KDF_TYPE(crypt),
561                BCH_KDF_SCRYPT_N(crypt),
562                BCH_KDF_SCRYPT_R(crypt),
563                BCH_KDF_SCRYPT_P(crypt));
564 }
565
566 static void bch2_sb_print_replicas_v0(struct bch_sb *sb, struct bch_sb_field *f,
567                                    enum units units)
568 {
569         struct bch_sb_field_replicas_v0 *replicas = field_to_type(f, replicas_v0);
570         struct bch_replicas_entry_v0 *e;
571         unsigned i;
572
573         for_each_replicas_entry(replicas, e) {
574                 printf_pad(32, "  %s:", bch2_data_types[e->data_type]);
575
576                 putchar('[');
577                 for (i = 0; i < e->nr_devs; i++) {
578                         if (i)
579                                 putchar(' ');
580                         printf("%u", e->devs[i]);
581                 }
582                 printf("]\n");
583         }
584 }
585
586 static void bch2_sb_print_replicas(struct bch_sb *sb, struct bch_sb_field *f,
587                                    enum units units)
588 {
589         struct bch_sb_field_replicas *replicas = field_to_type(f, replicas);
590         struct bch_replicas_entry *e;
591         unsigned i;
592
593         for_each_replicas_entry(replicas, e) {
594                 printf_pad(32, "  %s: %u/%u",
595                            bch2_data_types[e->data_type],
596                            e->nr_required,
597                            e->nr_devs);
598
599                 putchar('[');
600                 for (i = 0; i < e->nr_devs; i++) {
601                         if (i)
602                                 putchar(' ');
603                         printf("%u", e->devs[i]);
604                 }
605                 printf("]\n");
606         }
607 }
608
609 static void bch2_sb_print_quota(struct bch_sb *sb, struct bch_sb_field *f,
610                                 enum units units)
611 {
612 }
613
614 static void bch2_sb_print_disk_groups(struct bch_sb *sb, struct bch_sb_field *f,
615                                       enum units units)
616 {
617 }
618
619 static void bch2_sb_print_clean(struct bch_sb *sb, struct bch_sb_field *f,
620                                 enum units units)
621 {
622 }
623
624 static void bch2_sb_print_journal_seq_blacklist(struct bch_sb *sb, struct bch_sb_field *f,
625                                 enum units units)
626 {
627         struct bch_sb_field_journal_seq_blacklist *bl = field_to_type(f, journal_seq_blacklist);
628         unsigned i, nr = blacklist_nr_entries(bl);
629
630         for (i = 0; i < nr; i++) {
631                 struct journal_seq_blacklist_entry *e =
632                         bl->start + i;
633
634                 printf("  %llu-%llu\n",
635                        le64_to_cpu(e->start),
636                        le64_to_cpu(e->end));
637         }
638 }
639
640 typedef void (*sb_field_print_fn)(struct bch_sb *, struct bch_sb_field *, enum units);
641
642 struct bch_sb_field_toolops {
643         sb_field_print_fn       print;
644 };
645
646 static const struct bch_sb_field_toolops bch2_sb_field_ops[] = {
647 #define x(f, nr)                                        \
648         [BCH_SB_FIELD_##f] = {                          \
649                 .print  = bch2_sb_print_##f,            \
650         },
651         BCH_SB_FIELDS()
652 #undef x
653 };
654
655 static inline void bch2_sb_field_print(struct bch_sb *sb,
656                                        struct bch_sb_field *f,
657                                        enum units units)
658 {
659         unsigned type = le32_to_cpu(f->type);
660
661         if (type < BCH_SB_FIELD_NR)
662                 bch2_sb_field_ops[type].print(sb, f, units);
663         else
664                 printf("(unknown field %u)\n", type);
665 }
666
667 void bch2_sb_print(struct bch_sb *sb, bool print_layout,
668                    unsigned fields, enum units units)
669 {
670         struct bch_sb_field_members *mi;
671         char user_uuid_str[40], internal_uuid_str[40];
672         char features_str[200];
673         char fields_have_str[200];
674         char label[BCH_SB_LABEL_SIZE + 1];
675         char time_str[64];
676         char foreground_str[64];
677         char background_str[64];
678         char promote_str[64];
679         struct bch_sb_field *f;
680         u64 fields_have = 0;
681         unsigned nr_devices = 0;
682         time_t time_base = le64_to_cpu(sb->time_base_lo) / NSEC_PER_SEC;
683
684         memcpy(label, sb->label, BCH_SB_LABEL_SIZE);
685         label[BCH_SB_LABEL_SIZE] = '\0';
686
687         uuid_unparse(sb->user_uuid.b, user_uuid_str);
688         uuid_unparse(sb->uuid.b, internal_uuid_str);
689
690         if (time_base) {
691                 struct tm *tm = localtime(&time_base);
692                 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
693                 if (!err)
694                         strcpy(time_str, "(formatting error)");
695         } else {
696                 strcpy(time_str, "(not set)");
697         }
698
699         mi = bch2_sb_get_members(sb);
700         if (mi) {
701                 struct bch_member *m;
702
703                 for (m = mi->members;
704                      m < mi->members + sb->nr_devices;
705                      m++)
706                         nr_devices += bch2_member_exists(m);
707         }
708
709         bch2_sb_get_target(sb, foreground_str, sizeof(foreground_str),
710                 BCH_SB_FOREGROUND_TARGET(sb));
711
712         bch2_sb_get_target(sb, background_str, sizeof(background_str),
713                 BCH_SB_BACKGROUND_TARGET(sb));
714
715         bch2_sb_get_target(sb, promote_str, sizeof(promote_str),
716                 BCH_SB_PROMOTE_TARGET(sb));
717
718         bch2_flags_to_text(&PBUF(features_str),
719                            bch2_sb_features,
720                            le64_to_cpu(sb->features[0]));
721
722         vstruct_for_each(sb, f)
723                 fields_have |= 1 << le32_to_cpu(f->type);
724         bch2_flags_to_text(&PBUF(fields_have_str),
725                            bch2_sb_fields, fields_have);
726
727         printf("External UUID:                  %s\n"
728                "Internal UUID:                  %s\n"
729                "Label:                          %s\n"
730                "Version:                        %llu\n"
731                "Created:                        %s\n"
732                "Squence number:                 %llu\n"
733                "Block_size:                     %s\n"
734                "Btree node size:                %s\n"
735                "Error action:                   %s\n"
736                "Clean:                          %llu\n"
737                "Features:                       %s\n"
738
739                "Metadata replicas:              %llu\n"
740                "Data replicas:                  %llu\n"
741
742                "Metadata checksum type:         %s (%llu)\n"
743                "Data checksum type:             %s (%llu)\n"
744                "Compression type:               %s (%llu)\n"
745
746                "Foreground write target:        %s\n"
747                "Background write target:        %s\n"
748                "Promote target:                 %s\n"
749
750                "String hash type:               %s (%llu)\n"
751                "32 bit inodes:                  %llu\n"
752                "GC reserve percentage:          %llu%%\n"
753                "Root reserve percentage:        %llu%%\n"
754
755                "Devices:                        %u live, %u total\n"
756                "Sections:                       %s\n"
757                "Superblock size:                %llu\n",
758                user_uuid_str,
759                internal_uuid_str,
760                label,
761                le64_to_cpu(sb->version),
762                time_str,
763                le64_to_cpu(sb->seq),
764                pr_units(le16_to_cpu(sb->block_size), units),
765                pr_units(BCH_SB_BTREE_NODE_SIZE(sb), units),
766
767                BCH_SB_ERROR_ACTION(sb) < BCH_NR_ERROR_ACTIONS
768                ? bch2_error_actions[BCH_SB_ERROR_ACTION(sb)]
769                : "unknown",
770
771                BCH_SB_CLEAN(sb),
772                features_str,
773
774                BCH_SB_META_REPLICAS_WANT(sb),
775                BCH_SB_DATA_REPLICAS_WANT(sb),
776
777                BCH_SB_META_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
778                ? bch2_csum_opts[BCH_SB_META_CSUM_TYPE(sb)]
779                : "unknown",
780                BCH_SB_META_CSUM_TYPE(sb),
781
782                BCH_SB_DATA_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
783                ? bch2_csum_opts[BCH_SB_DATA_CSUM_TYPE(sb)]
784                : "unknown",
785                BCH_SB_DATA_CSUM_TYPE(sb),
786
787                BCH_SB_COMPRESSION_TYPE(sb) < BCH_COMPRESSION_OPT_NR
788                ? bch2_compression_opts[BCH_SB_COMPRESSION_TYPE(sb)]
789                : "unknown",
790                BCH_SB_COMPRESSION_TYPE(sb),
791
792                foreground_str,
793                background_str,
794                promote_str,
795
796                BCH_SB_STR_HASH_TYPE(sb) < BCH_STR_HASH_NR
797                ? bch2_str_hash_types[BCH_SB_STR_HASH_TYPE(sb)]
798                : "unknown",
799                BCH_SB_STR_HASH_TYPE(sb),
800
801                BCH_SB_INODE_32BIT(sb),
802                BCH_SB_GC_RESERVE(sb),
803                BCH_SB_ROOT_RESERVE(sb),
804
805                nr_devices, sb->nr_devices,
806                fields_have_str,
807                vstruct_bytes(sb));
808
809         if (print_layout) {
810                 printf("\n"
811                        "Layout:\n");
812                 bch2_sb_print_layout(sb, units);
813         }
814
815         vstruct_for_each(sb, f) {
816                 unsigned type = le32_to_cpu(f->type);
817                 char name[60];
818
819                 if (!(fields & (1 << type)))
820                         continue;
821
822                 if (type < BCH_SB_FIELD_NR) {
823                         scnprintf(name, sizeof(name), "%s", bch2_sb_fields[type]);
824                         name[0] = toupper(name[0]);
825                 } else {
826                         scnprintf(name, sizeof(name), "(unknown field %u)", type);
827                 }
828
829                 printf("\n%s (size %llu):\n", name, vstruct_bytes(f));
830                 if (type < BCH_SB_FIELD_NR)
831                         bch2_sb_field_print(sb, f, units);
832         }
833 }
834
835 /* ioctl interface: */
836
837 /* Global control device: */
838 int bcachectl_open(void)
839 {
840         return xopen("/dev/bcachefs-ctl", O_RDWR);
841 }
842
843 /* Filesystem handles (ioctl, sysfs dir): */
844
845 #define SYSFS_BASE "/sys/fs/bcachefs/"
846
847 void bcache_fs_close(struct bchfs_handle fs)
848 {
849         close(fs.ioctl_fd);
850         close(fs.sysfs_fd);
851 }
852
853 struct bchfs_handle bcache_fs_open(const char *path)
854 {
855         struct bchfs_handle ret;
856
857         if (!uuid_parse(path, ret.uuid.b)) {
858                 /* It's a UUID, look it up in sysfs: */
859                 char *sysfs = mprintf(SYSFS_BASE "%s", path);
860                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
861
862                 char *minor = read_file_str(ret.sysfs_fd, "minor");
863                 char *ctl = mprintf("/dev/bcachefs%s-ctl", minor);
864                 ret.ioctl_fd = xopen(ctl, O_RDWR);
865
866                 free(sysfs);
867                 free(minor);
868                 free(ctl);
869         } else {
870                 /* It's a path: */
871                 ret.ioctl_fd = xopen(path, O_RDONLY);
872
873                 struct bch_ioctl_query_uuid uuid;
874                 if (ioctl(ret.ioctl_fd, BCH_IOCTL_QUERY_UUID, &uuid) < 0)
875                         die("error opening %s: not a bcachefs filesystem", path);
876
877                 ret.uuid = uuid.uuid;
878
879                 char uuid_str[40];
880                 uuid_unparse(uuid.uuid.b, uuid_str);
881
882                 char *sysfs = mprintf(SYSFS_BASE "%s", uuid_str);
883                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
884                 free(sysfs);
885         }
886
887         return ret;
888 }
889
890 /*
891  * Given a path to a block device, open the filesystem it belongs to; also
892  * return the device's idx:
893  */
894 struct bchfs_handle bchu_fs_open_by_dev(const char *path, unsigned *idx)
895 {
896         char buf[1024], *uuid_str;
897
898         struct stat stat = xstat(path);
899
900         if (!S_ISBLK(stat.st_mode))
901                 die("%s is not a block device", path);
902
903         char *sysfs = mprintf("/sys/dev/block/%u:%u/bcachefs",
904                               major(stat.st_dev),
905                               minor(stat.st_dev));
906         ssize_t len = readlink(sysfs, buf, sizeof(buf));
907         free(sysfs);
908
909         if (len > 0) {
910                 char *p = strrchr(buf, '/');
911                 if (!p || sscanf(p + 1, "dev-%u", idx) != 1)
912                         die("error parsing sysfs");
913
914                 *p = '\0';
915                 p = strrchr(buf, '/');
916                 uuid_str = p + 1;
917         } else {
918                 struct bch_opts opts = bch2_opts_empty();
919
920                 opt_set(opts, noexcl,   true);
921                 opt_set(opts, nochanges, true);
922
923                 struct bch_sb_handle sb;
924                 int ret = bch2_read_super(path, &opts, &sb);
925                 if (ret)
926                         die("Error opening %s: %s", path, strerror(-ret));
927
928                 *idx = sb.sb->dev_idx;
929                 uuid_str = buf;
930                 uuid_unparse(sb.sb->user_uuid.b, uuid_str);
931
932                 bch2_free_super(&sb);
933         }
934
935         return bcache_fs_open(uuid_str);
936 }
937
938 int bchu_data(struct bchfs_handle fs, struct bch_ioctl_data cmd)
939 {
940         int progress_fd = xioctl(fs.ioctl_fd, BCH_IOCTL_DATA, &cmd);
941
942         while (1) {
943                 struct bch_ioctl_data_event e;
944
945                 if (read(progress_fd, &e, sizeof(e)) != sizeof(e))
946                         die("error reading from progress fd %m");
947
948                 if (e.type)
949                         continue;
950
951                 if (e.p.data_type == U8_MAX)
952                         break;
953
954                 printf("\33[2K\r");
955
956                 printf("%llu%% complete: current position %s",
957                        e.p.sectors_total
958                        ? e.p.sectors_done * 100 / e.p.sectors_total
959                        : 0,
960                        bch2_data_types[e.p.data_type]);
961
962                 switch (e.p.data_type) {
963                 case BCH_DATA_btree:
964                 case BCH_DATA_user:
965                         printf(" %s:%llu:%llu",
966                                bch2_btree_ids[e.p.btree_id],
967                                e.p.pos.inode,
968                                e.p.pos.offset);
969                 }
970
971                 fflush(stdout);
972                 sleep(1);
973         }
974         printf("\nDone\n");
975
976         close(progress_fd);
977         return 0;
978 }
979
980 /* option parsing */
981
982 struct bch_opt_strs bch2_cmdline_opts_get(int *argc, char *argv[],
983                                           unsigned opt_types)
984 {
985         struct bch_opt_strs opts;
986         unsigned i = 1;
987
988         memset(&opts, 0, sizeof(opts));
989
990         while (i < *argc) {
991                 char *optstr = strcmp_prefix(argv[i], "--");
992                 char *valstr = NULL, *p;
993                 int optid, nr_args = 1;
994
995                 if (!optstr) {
996                         i++;
997                         continue;
998                 }
999
1000                 optstr = strdup(optstr);
1001
1002                 p = optstr;
1003                 while (isalpha(*p) || *p == '_')
1004                         p++;
1005
1006                 if (*p == '=') {
1007                         *p = '\0';
1008                         valstr = p + 1;
1009                 }
1010
1011                 optid = bch2_opt_lookup(optstr);
1012                 if (optid < 0 ||
1013                     !(bch2_opt_table[optid].mode & opt_types)) {
1014                         free(optstr);
1015                         i++;
1016                         continue;
1017                 }
1018
1019                 if (!valstr &&
1020                     bch2_opt_table[optid].type != BCH_OPT_BOOL) {
1021                         nr_args = 2;
1022                         valstr = argv[i + 1];
1023                 }
1024
1025                 if (!valstr)
1026                         valstr = "1";
1027
1028                 opts.by_id[optid] = valstr;
1029
1030                 *argc -= nr_args;
1031                 memmove(&argv[i],
1032                         &argv[i + nr_args],
1033                         sizeof(char *) * (*argc - i));
1034                 argv[*argc] = NULL;
1035         }
1036
1037         return opts;
1038 }
1039
1040 struct bch_opts bch2_parse_opts(struct bch_opt_strs strs)
1041 {
1042         struct bch_opts opts = bch2_opts_empty();
1043         unsigned i;
1044         int ret;
1045         u64 v;
1046
1047         for (i = 0; i < bch2_opts_nr; i++) {
1048                 if (!strs.by_id[i] ||
1049                     bch2_opt_table[i].type == BCH_OPT_FN)
1050                         continue;
1051
1052                 ret = bch2_opt_parse(NULL, &bch2_opt_table[i],
1053                                      strs.by_id[i], &v);
1054                 if (ret < 0)
1055                         die("Invalid %s: %s",
1056                             bch2_opt_table[i].attr.name,
1057                             strerror(-ret));
1058
1059                 bch2_opt_set_by_id(&opts, i, v);
1060         }
1061
1062         return opts;
1063 }
1064
1065 void bch2_opts_usage(unsigned opt_types)
1066 {
1067         const struct bch_option *opt;
1068         unsigned i, c = 0, helpcol = 30;
1069
1070         void tabalign() {
1071                 while (c < helpcol) {
1072                         putchar(' ');
1073                         c++;
1074                 }
1075         }
1076
1077         void newline() {
1078                 printf("\n");
1079                 c = 0;
1080         }
1081
1082         for (opt = bch2_opt_table;
1083              opt < bch2_opt_table + bch2_opts_nr;
1084              opt++) {
1085                 if (!(opt->mode & opt_types))
1086                         continue;
1087
1088                 c += printf("      --%s", opt->attr.name);
1089
1090                 switch (opt->type) {
1091                 case BCH_OPT_BOOL:
1092                         break;
1093                 case BCH_OPT_STR:
1094                         c += printf("=(");
1095                         for (i = 0; opt->choices[i]; i++) {
1096                                 if (i)
1097                                         c += printf("|");
1098                                 c += printf("%s", opt->choices[i]);
1099                         }
1100                         c += printf(")");
1101                         break;
1102                 default:
1103                         c += printf("=%s", opt->hint);
1104                         break;
1105                 }
1106
1107                 if (opt->help) {
1108                         const char *l = opt->help;
1109
1110                         if (c >= helpcol)
1111                                 newline();
1112
1113                         while (1) {
1114                                 const char *n = strchrnul(l, '\n');
1115
1116                                 tabalign();
1117                                 printf("%.*s", (int) (n - l), l);
1118                                 newline();
1119
1120                                 if (!*n)
1121                                         break;
1122                                 l = n + 1;
1123                         }
1124                 } else {
1125                         newline();
1126                 }
1127         }
1128 }
1129
1130 dev_names bchu_fs_get_devices(struct bchfs_handle fs)
1131 {
1132         DIR *dir = fdopendir(fs.sysfs_fd);
1133         struct dirent *d;
1134         dev_names devs;
1135
1136         darray_init(devs);
1137
1138         while ((errno = 0), (d = readdir(dir))) {
1139                 struct dev_name n = { 0, NULL, NULL };
1140
1141                 if (sscanf(d->d_name, "dev-%u", &n.idx) != 1)
1142                         continue;
1143
1144                 char *block_attr = mprintf("dev-%u/block", n.idx);
1145
1146                 char sysfs_block_buf[4096];
1147                 ssize_t r = readlinkat(fs.sysfs_fd, block_attr,
1148                                        sysfs_block_buf, sizeof(sysfs_block_buf));
1149                 if (r > 0) {
1150                         sysfs_block_buf[r] = '\0';
1151                         n.dev = strdup(basename(sysfs_block_buf));
1152                 }
1153
1154                 free(block_attr);
1155
1156                 char *label_attr = mprintf("dev-%u/label", n.idx);
1157                 n.label = read_file_str(fs.sysfs_fd, label_attr);
1158                 free(label_attr);
1159
1160                 darray_append(devs, n);
1161         }
1162
1163         closedir(dir);
1164
1165         return devs;
1166 }