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