]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs.c
Update bcachefs sources to 86a99a7b7f bcachefs: Convert some enums to x-macros
[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 fields_have_str[200];
661         char label[BCH_SB_LABEL_SIZE + 1];
662         char time_str[64];
663         char foreground_str[64];
664         char background_str[64];
665         char promote_str[64];
666         struct bch_sb_field *f;
667         u64 fields_have = 0;
668         unsigned nr_devices = 0;
669         time_t time_base = le64_to_cpu(sb->time_base_lo) / NSEC_PER_SEC;
670
671         memcpy(label, sb->label, BCH_SB_LABEL_SIZE);
672         label[BCH_SB_LABEL_SIZE] = '\0';
673
674         uuid_unparse(sb->user_uuid.b, user_uuid_str);
675         uuid_unparse(sb->uuid.b, internal_uuid_str);
676
677         if (time_base) {
678                 struct tm *tm = localtime(&time_base);
679                 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
680                 if (!err)
681                         strcpy(time_str, "(formatting error)");
682         } else {
683                 strcpy(time_str, "(not set)");
684         }
685
686         mi = bch2_sb_get_members(sb);
687         if (mi) {
688                 struct bch_member *m;
689
690                 for (m = mi->members;
691                      m < mi->members + sb->nr_devices;
692                      m++)
693                         nr_devices += bch2_member_exists(m);
694         }
695
696         bch2_sb_get_target(sb, foreground_str, sizeof(foreground_str),
697                 BCH_SB_FOREGROUND_TARGET(sb));
698
699         bch2_sb_get_target(sb, background_str, sizeof(background_str),
700                 BCH_SB_BACKGROUND_TARGET(sb));
701
702         bch2_sb_get_target(sb, promote_str, sizeof(promote_str),
703                 BCH_SB_PROMOTE_TARGET(sb));
704
705         vstruct_for_each(sb, f)
706                 fields_have |= 1 << le32_to_cpu(f->type);
707         bch2_flags_to_text(&PBUF(fields_have_str),
708                            bch2_sb_fields, fields_have);
709
710         printf("External UUID:                  %s\n"
711                "Internal UUID:                  %s\n"
712                "Label:                          %s\n"
713                "Version:                        %llu\n"
714                "Created:                        %s\n"
715                "Block_size:                     %s\n"
716                "Btree node size:                %s\n"
717                "Error action:                   %s\n"
718                "Clean:                          %llu\n"
719
720                "Metadata replicas:              %llu\n"
721                "Data replicas:                  %llu\n"
722
723                "Metadata checksum type:         %s (%llu)\n"
724                "Data checksum type:             %s (%llu)\n"
725                "Compression type:               %s (%llu)\n"
726
727                "Foreground write target:        %s\n"
728                "Background write target:        %s\n"
729                "Promote target:                 %s\n"
730
731                "String hash type:               %s (%llu)\n"
732                "32 bit inodes:                  %llu\n"
733                "GC reserve percentage:          %llu%%\n"
734                "Root reserve percentage:        %llu%%\n"
735
736                "Devices:                        %u live, %u total\n"
737                "Sections:                       %s\n"
738                "Superblock size:                %llu\n",
739                user_uuid_str,
740                internal_uuid_str,
741                label,
742                le64_to_cpu(sb->version),
743                time_str,
744                pr_units(le16_to_cpu(sb->block_size), units),
745                pr_units(BCH_SB_BTREE_NODE_SIZE(sb), units),
746
747                BCH_SB_ERROR_ACTION(sb) < BCH_NR_ERROR_ACTIONS
748                ? bch2_error_actions[BCH_SB_ERROR_ACTION(sb)]
749                : "unknown",
750
751                BCH_SB_CLEAN(sb),
752
753                BCH_SB_META_REPLICAS_WANT(sb),
754                BCH_SB_DATA_REPLICAS_WANT(sb),
755
756                BCH_SB_META_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
757                ? bch2_csum_opts[BCH_SB_META_CSUM_TYPE(sb)]
758                : "unknown",
759                BCH_SB_META_CSUM_TYPE(sb),
760
761                BCH_SB_DATA_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
762                ? bch2_csum_opts[BCH_SB_DATA_CSUM_TYPE(sb)]
763                : "unknown",
764                BCH_SB_DATA_CSUM_TYPE(sb),
765
766                BCH_SB_COMPRESSION_TYPE(sb) < BCH_COMPRESSION_OPT_NR
767                ? bch2_compression_opts[BCH_SB_COMPRESSION_TYPE(sb)]
768                : "unknown",
769                BCH_SB_COMPRESSION_TYPE(sb),
770
771                foreground_str,
772                background_str,
773                promote_str,
774
775                BCH_SB_STR_HASH_TYPE(sb) < BCH_STR_HASH_NR
776                ? bch2_str_hash_types[BCH_SB_STR_HASH_TYPE(sb)]
777                : "unknown",
778                BCH_SB_STR_HASH_TYPE(sb),
779
780                BCH_SB_INODE_32BIT(sb),
781                BCH_SB_GC_RESERVE(sb),
782                BCH_SB_ROOT_RESERVE(sb),
783
784                nr_devices, sb->nr_devices,
785                fields_have_str,
786                vstruct_bytes(sb));
787
788         if (print_layout) {
789                 printf("\n"
790                        "Layout:\n");
791                 bch2_sb_print_layout(sb, units);
792         }
793
794         vstruct_for_each(sb, f) {
795                 unsigned type = le32_to_cpu(f->type);
796                 char name[60];
797
798                 if (!(fields & (1 << type)))
799                         continue;
800
801                 if (type < BCH_SB_FIELD_NR) {
802                         scnprintf(name, sizeof(name), "%s", bch2_sb_fields[type]);
803                         name[0] = toupper(name[0]);
804                 } else {
805                         scnprintf(name, sizeof(name), "(unknown field %u)", type);
806                 }
807
808                 printf("\n%s (size %llu):\n", name, vstruct_bytes(f));
809                 if (type < BCH_SB_FIELD_NR)
810                         bch2_sb_field_print(sb, f, units);
811         }
812 }
813
814 /* ioctl interface: */
815
816 /* Global control device: */
817 int bcachectl_open(void)
818 {
819         return xopen("/dev/bcachefs-ctl", O_RDWR);
820 }
821
822 /* Filesystem handles (ioctl, sysfs dir): */
823
824 #define SYSFS_BASE "/sys/fs/bcachefs/"
825
826 void bcache_fs_close(struct bchfs_handle fs)
827 {
828         close(fs.ioctl_fd);
829         close(fs.sysfs_fd);
830 }
831
832 struct bchfs_handle bcache_fs_open(const char *path)
833 {
834         struct bchfs_handle ret;
835
836         if (!uuid_parse(path, ret.uuid.b)) {
837                 /* It's a UUID, look it up in sysfs: */
838                 char *sysfs = mprintf(SYSFS_BASE "%s", path);
839                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
840
841                 char *minor = read_file_str(ret.sysfs_fd, "minor");
842                 char *ctl = mprintf("/dev/bcachefs%s-ctl", minor);
843                 ret.ioctl_fd = xopen(ctl, O_RDWR);
844
845                 free(sysfs);
846                 free(minor);
847                 free(ctl);
848         } else {
849                 /* It's a path: */
850                 ret.ioctl_fd = xopen(path, O_RDONLY);
851
852                 struct bch_ioctl_query_uuid uuid;
853                 if (ioctl(ret.ioctl_fd, BCH_IOCTL_QUERY_UUID, &uuid) < 0)
854                         die("error opening %s: not a bcachefs filesystem", path);
855
856                 ret.uuid = uuid.uuid;
857
858                 char uuid_str[40];
859                 uuid_unparse(uuid.uuid.b, uuid_str);
860
861                 char *sysfs = mprintf(SYSFS_BASE "%s", uuid_str);
862                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
863                 free(sysfs);
864         }
865
866         return ret;
867 }
868
869 /*
870  * Given a path to a block device, open the filesystem it belongs to; also
871  * return the device's idx:
872  */
873 struct bchfs_handle bchu_fs_open_by_dev(const char *path, unsigned *idx)
874 {
875         char buf[1024], *uuid_str;
876
877         struct stat stat = xstat(path);
878
879         if (!S_ISBLK(stat.st_mode))
880                 die("%s is not a block device", path);
881
882         char *sysfs = mprintf("/sys/dev/block/%u:%u/bcachefs",
883                               major(stat.st_dev),
884                               minor(stat.st_dev));
885         ssize_t len = readlink(sysfs, buf, sizeof(buf));
886         free(sysfs);
887
888         if (len > 0) {
889                 char *p = strrchr(buf, '/');
890                 if (!p || sscanf(p + 1, "dev-%u", idx) != 1)
891                         die("error parsing sysfs");
892
893                 *p = '\0';
894                 p = strrchr(buf, '/');
895                 uuid_str = p + 1;
896         } else {
897                 struct bch_opts opts = bch2_opts_empty();
898
899                 opt_set(opts, noexcl,   true);
900                 opt_set(opts, nochanges, true);
901
902                 struct bch_sb_handle sb;
903                 int ret = bch2_read_super(path, &opts, &sb);
904                 if (ret)
905                         die("Error opening %s: %s", path, strerror(-ret));
906
907                 *idx = sb.sb->dev_idx;
908                 uuid_str = buf;
909                 uuid_unparse(sb.sb->user_uuid.b, uuid_str);
910
911                 bch2_free_super(&sb);
912         }
913
914         return bcache_fs_open(uuid_str);
915 }
916
917 int bchu_data(struct bchfs_handle fs, struct bch_ioctl_data cmd)
918 {
919         int progress_fd = xioctl(fs.ioctl_fd, BCH_IOCTL_DATA, &cmd);
920
921         while (1) {
922                 struct bch_ioctl_data_event e;
923
924                 if (read(progress_fd, &e, sizeof(e)) != sizeof(e))
925                         die("error reading from progress fd %m");
926
927                 if (e.type)
928                         continue;
929
930                 if (e.p.data_type == U8_MAX)
931                         break;
932
933                 printf("\33[2K\r");
934
935                 printf("%llu%% complete: current position %s",
936                        e.p.sectors_total
937                        ? e.p.sectors_done * 100 / e.p.sectors_total
938                        : 0,
939                        bch2_data_types[e.p.data_type]);
940
941                 switch (e.p.data_type) {
942                 case BCH_DATA_BTREE:
943                 case BCH_DATA_USER:
944                         printf(" %s:%llu:%llu",
945                                bch2_btree_ids[e.p.btree_id],
946                                e.p.pos.inode,
947                                e.p.pos.offset);
948                 }
949
950                 sleep(1);
951         }
952         printf("\nDone\n");
953
954         close(progress_fd);
955         return 0;
956 }
957
958 /* option parsing */
959
960 struct bch_opt_strs bch2_cmdline_opts_get(int *argc, char *argv[],
961                                           unsigned opt_types)
962 {
963         struct bch_opt_strs opts;
964         unsigned i = 1;
965
966         memset(&opts, 0, sizeof(opts));
967
968         while (i < *argc) {
969                 char *optstr = strcmp_prefix(argv[i], "--");
970                 char *valstr = NULL, *p;
971                 int optid, nr_args = 1;
972
973                 if (!optstr) {
974                         i++;
975                         continue;
976                 }
977
978                 optstr = strdup(optstr);
979
980                 p = optstr;
981                 while (isalpha(*p) || *p == '_')
982                         p++;
983
984                 if (*p == '=') {
985                         *p = '\0';
986                         valstr = p + 1;
987                 }
988
989                 optid = bch2_opt_lookup(optstr);
990                 if (optid < 0 ||
991                     !(bch2_opt_table[optid].mode & opt_types)) {
992                         free(optstr);
993                         i++;
994                         continue;
995                 }
996
997                 if (!valstr &&
998                     bch2_opt_table[optid].type != BCH_OPT_BOOL) {
999                         nr_args = 2;
1000                         valstr = argv[i + 1];
1001                 }
1002
1003                 if (!valstr)
1004                         valstr = "1";
1005
1006                 opts.by_id[optid] = valstr;
1007
1008                 *argc -= nr_args;
1009                 memmove(&argv[i],
1010                         &argv[i + nr_args],
1011                         sizeof(char *) * (*argc - i));
1012                 argv[*argc] = NULL;
1013         }
1014
1015         return opts;
1016 }
1017
1018 struct bch_opts bch2_parse_opts(struct bch_opt_strs strs)
1019 {
1020         struct bch_opts opts = bch2_opts_empty();
1021         unsigned i;
1022         int ret;
1023         u64 v;
1024
1025         for (i = 0; i < bch2_opts_nr; i++) {
1026                 if (!strs.by_id[i] ||
1027                     bch2_opt_table[i].type == BCH_OPT_FN)
1028                         continue;
1029
1030                 ret = bch2_opt_parse(NULL, &bch2_opt_table[i],
1031                                      strs.by_id[i], &v);
1032                 if (ret < 0)
1033                         die("Invalid %s: %s", strs.by_id[i], strerror(-ret));
1034
1035                 bch2_opt_set_by_id(&opts, i, v);
1036         }
1037
1038         return opts;
1039 }
1040
1041 void bch2_opts_usage(unsigned opt_types)
1042 {
1043         const struct bch_option *opt;
1044         unsigned i, c = 0, helpcol = 30;
1045
1046         void tabalign() {
1047                 while (c < helpcol) {
1048                         putchar(' ');
1049                         c++;
1050                 }
1051         }
1052
1053         void newline() {
1054                 printf("\n");
1055                 c = 0;
1056         }
1057
1058         for (opt = bch2_opt_table;
1059              opt < bch2_opt_table + bch2_opts_nr;
1060              opt++) {
1061                 if (!(opt->mode & opt_types))
1062                         continue;
1063
1064                 c += printf("      --%s", opt->attr.name);
1065
1066                 switch (opt->type) {
1067                 case BCH_OPT_BOOL:
1068                         break;
1069                 case BCH_OPT_STR:
1070                         c += printf("=(");
1071                         for (i = 0; opt->choices[i]; i++) {
1072                                 if (i)
1073                                         c += printf("|");
1074                                 c += printf("%s", opt->choices[i]);
1075                         }
1076                         c += printf(")");
1077                         break;
1078                 default:
1079                         c += printf("=%s", opt->hint);
1080                         break;
1081                 }
1082
1083                 if (opt->help) {
1084                         const char *l = opt->help;
1085
1086                         if (c >= helpcol)
1087                                 newline();
1088
1089                         while (1) {
1090                                 const char *n = strchrnul(l, '\n');
1091
1092                                 tabalign();
1093                                 printf("%.*s", (int) (n - l), l);
1094                                 newline();
1095
1096                                 if (!*n)
1097                                         break;
1098                                 l = n + 1;
1099                         }
1100                 } else {
1101                         newline();
1102                 }
1103         }
1104 }
1105
1106 dev_names bchu_fs_get_devices(struct bchfs_handle fs)
1107 {
1108         DIR *dir = fdopendir(fs.sysfs_fd);
1109         struct dirent *d;
1110         dev_names devs;
1111
1112         darray_init(devs);
1113
1114         while ((errno = 0), (d = readdir(dir))) {
1115                 struct dev_name n = { 0, NULL, NULL };
1116
1117                 if (sscanf(d->d_name, "dev-%u", &n.idx) != 1)
1118                         continue;
1119
1120                 char *block_attr = mprintf("dev-%u/block", n.idx);
1121
1122                 char sysfs_block_buf[4096];
1123                 ssize_t r = readlinkat(fs.sysfs_fd, block_attr,
1124                                        sysfs_block_buf, sizeof(sysfs_block_buf));
1125                 if (r > 0) {
1126                         sysfs_block_buf[r] = '\0';
1127                         n.dev = strdup(basename(sysfs_block_buf));
1128                 }
1129
1130                 free(block_attr);
1131
1132                 char *label_attr = mprintf("dev-%u/label", n.idx);
1133                 n.label = read_file_str(fs.sysfs_fd, label_attr);
1134                 free(label_attr);
1135
1136                 darray_append(devs, n);
1137         }
1138
1139         closedir(dir);
1140
1141         return devs;
1142 }