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