]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs.c
Update bcachefs sources to f9d2e809a8 bcachefs: Turn encoded_extent_max into a regula...
[bcachefs-tools-debian] / libbcachefs.c
1 #include <ctype.h>
2 #include <dirent.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdbool.h>
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/stat.h>
11 #include <sys/sysmacros.h>
12 #include <sys/types.h>
13 #include <time.h>
14 #include <unistd.h>
15
16 #include <uuid/uuid.h>
17
18 #include "libbcachefs.h"
19 #include "crypto.h"
20 #include "libbcachefs/bcachefs_format.h"
21 #include "libbcachefs/btree_cache.h"
22 #include "libbcachefs/checksum.h"
23 #include "libbcachefs/disk_groups.h"
24 #include "libbcachefs/journal_seq_blacklist.h"
25 #include "libbcachefs/opts.h"
26 #include "libbcachefs/replicas.h"
27 #include "libbcachefs/super-io.h"
28 #include "tools-util.h"
29
30 #define NSEC_PER_SEC    1000000000L
31
32 /* minimum size filesystem we can create, given a bucket size: */
33 static u64 min_size(unsigned bucket_size)
34 {
35         return BCH_MIN_NR_NBUCKETS * bucket_size;
36 }
37
38 static void init_layout(struct bch_sb_layout *l,
39                         unsigned block_size,
40                         unsigned sb_size,
41                         u64 sb_start, u64 sb_end)
42 {
43         u64 sb_pos = sb_start;
44         unsigned i;
45
46         memset(l, 0, sizeof(*l));
47
48         l->magic                = BCACHE_MAGIC;
49         l->layout_type          = 0;
50         l->nr_superblocks       = 2;
51         l->sb_max_size_bits     = ilog2(sb_size);
52
53         /* Create two superblocks in the allowed range: */
54         for (i = 0; i < l->nr_superblocks; i++) {
55                 if (sb_pos != BCH_SB_SECTOR)
56                         sb_pos = round_up(sb_pos, block_size);
57
58                 l->sb_offset[i] = cpu_to_le64(sb_pos);
59                 sb_pos += sb_size;
60         }
61
62         if (sb_pos > sb_end)
63                 die("insufficient space for superblocks: start %llu end %llu > %llu size %u",
64                     sb_start, sb_pos, sb_end, sb_size);
65 }
66
67 void bch2_pick_bucket_size(struct bch_opts opts, struct dev_opts *dev)
68 {
69         if (!dev->size)
70                 dev->size = get_size(dev->path, dev->fd) >> 9;
71
72         if (!dev->bucket_size) {
73                 if (dev->size < min_size(opts.block_size))
74                         die("cannot format %s, too small (%llu sectors, min %llu)",
75                             dev->path, dev->size, min_size(opts.block_size));
76
77                 /* Bucket size must be >= block size: */
78                 dev->bucket_size = opts.block_size;
79
80                 /* Bucket size must be >= btree node size: */
81                 if (opt_defined(opts, btree_node_size))
82                         dev->bucket_size = max_t(unsigned, dev->bucket_size,
83                                                  opts.btree_node_size);
84
85                 /* Want a bucket size of at least 128k, if possible: */
86                 dev->bucket_size = max(dev->bucket_size, 256U);
87
88                 if (dev->size >= min_size(dev->bucket_size)) {
89                         unsigned scale = max(1,
90                                              ilog2(dev->size / min_size(dev->bucket_size)) / 4);
91
92                         scale = rounddown_pow_of_two(scale);
93
94                         /* max bucket size 1 mb */
95                         dev->bucket_size = min(dev->bucket_size * scale, 1U << 11);
96                 } else {
97                         do {
98                                 dev->bucket_size /= 2;
99                         } while (dev->size < min_size(dev->bucket_size));
100                 }
101         }
102
103         dev->nbuckets   = dev->size / dev->bucket_size;
104
105         if (dev->bucket_size << 9 < opts.block_size)
106                 die("Bucket size (%u) cannot be smaller than block size (%u)",
107                     dev->bucket_size << 9, opts.block_size);
108
109         if (opt_defined(opts, btree_node_size) &&
110             dev->bucket_size << 9 < opts.btree_node_size)
111                 die("Bucket size (%u) cannot be smaller than btree node size (%u)",
112                     dev->bucket_size << 9, opts.btree_node_size);
113
114         if (dev->nbuckets < BCH_MIN_NR_NBUCKETS)
115                 die("Not enough buckets: %llu, need %u (bucket size %u)",
116                     dev->nbuckets, BCH_MIN_NR_NBUCKETS, dev->bucket_size);
117
118 }
119
120 static unsigned parse_target(struct bch_sb_handle *sb,
121                              struct dev_opts *devs, size_t nr_devs,
122                              const char *s)
123 {
124         struct dev_opts *i;
125         int idx;
126
127         if (!s)
128                 return 0;
129
130         for (i = devs; i < devs + nr_devs; i++)
131                 if (!strcmp(s, i->path))
132                         return dev_to_target(i - devs);
133
134         idx = bch2_disk_path_find(sb, s);
135         if (idx >= 0)
136                 return group_to_target(idx);
137
138         die("Invalid target %s", s);
139         return 0;
140 }
141
142 struct bch_sb *bch2_format(struct bch_opt_strs  fs_opt_strs,
143                            struct bch_opts      fs_opts,
144                            struct format_opts   opts,
145                            struct dev_opts      *devs,
146                            size_t               nr_devs)
147 {
148         struct bch_sb_handle sb = { NULL };
149         struct dev_opts *i;
150         struct bch_sb_field_members *mi;
151         unsigned max_dev_block_size = 0;
152         unsigned opt_id;
153
154         for (i = devs; i < devs + nr_devs; i++)
155                 max_dev_block_size = max(max_dev_block_size,
156                                          get_blocksize(i->path, i->fd));
157
158         /* calculate block size: */
159         if (!opt_defined(fs_opts, block_size)) {
160                 opt_set(fs_opts, block_size, max_dev_block_size);
161         } else if (fs_opts.block_size < max_dev_block_size)
162                 die("blocksize too small: %u, must be greater than device blocksize %u",
163                     fs_opts.block_size, max_dev_block_size);
164
165         /* calculate bucket sizes: */
166         for (i = devs; i < devs + nr_devs; i++)
167                 bch2_pick_bucket_size(fs_opts, i);
168
169         /* calculate btree node size: */
170         if (!opt_defined(fs_opts, btree_node_size)) {
171                 /* 256k default btree node size */
172                 opt_set(fs_opts, btree_node_size, 256 << 10);
173
174                 for (i = devs; i < devs + nr_devs; i++)
175                         fs_opts.btree_node_size =
176                                 min_t(unsigned, fs_opts.btree_node_size,
177                                       i->bucket_size << 9);
178         }
179
180         if (uuid_is_null(opts.uuid.b))
181                 uuid_generate(opts.uuid.b);
182
183         if (bch2_sb_realloc(&sb, 0))
184                 die("insufficient memory");
185
186         sb.sb->version          = le16_to_cpu(opts.version);
187         sb.sb->version_min      = le16_to_cpu(opts.version);
188         sb.sb->magic            = BCACHE_MAGIC;
189         sb.sb->user_uuid        = opts.uuid;
190         sb.sb->nr_devices       = nr_devs;
191
192         if (opts.version == bcachefs_metadata_version_current)
193                 sb.sb->features[0] |= BCH_SB_FEATURES_ALL;
194
195         uuid_generate(sb.sb->uuid.b);
196
197         if (opts.label)
198                 memcpy(sb.sb->label,
199                        opts.label,
200                        min(strlen(opts.label), sizeof(sb.sb->label)));
201
202         for (opt_id = 0;
203              opt_id < bch2_opts_nr;
204              opt_id++) {
205                 u64 v;
206
207                 v = bch2_opt_defined_by_id(&fs_opts, opt_id)
208                         ? bch2_opt_get_by_id(&fs_opts, opt_id)
209                         : bch2_opt_get_by_id(&bch2_opts_default, opt_id);
210
211                 __bch2_opt_set_sb(sb.sb, &bch2_opt_table[opt_id], v);
212         }
213
214         struct timespec now;
215         if (clock_gettime(CLOCK_REALTIME, &now))
216                 die("error getting current time: %m");
217
218         sb.sb->time_base_lo     = cpu_to_le64(now.tv_sec * NSEC_PER_SEC + now.tv_nsec);
219         sb.sb->time_precision   = cpu_to_le32(1);
220
221         /* Member info: */
222         mi = bch2_sb_resize_members(&sb,
223                         (sizeof(*mi) + sizeof(struct bch_member) *
224                         nr_devs) / sizeof(u64));
225
226         for (i = devs; i < devs + nr_devs; i++) {
227                 struct bch_member *m = mi->members + (i - devs);
228
229                 uuid_generate(m->uuid.b);
230                 m->nbuckets     = cpu_to_le64(i->nbuckets);
231                 m->first_bucket = 0;
232                 m->bucket_size  = cpu_to_le16(i->bucket_size);
233
234                 SET_BCH_MEMBER_REPLACEMENT(m,   BCH_CACHE_REPLACEMENT_lru);
235                 SET_BCH_MEMBER_DISCARD(m,       i->discard);
236                 SET_BCH_MEMBER_DATA_ALLOWED(m,  i->data_allowed);
237                 SET_BCH_MEMBER_DURABILITY(m,    i->durability + 1);
238         }
239
240         /* Disk labels*/
241         for (i = devs; i < devs + nr_devs; i++) {
242                 struct bch_member *m = mi->members + (i - devs);
243                 int idx;
244
245                 if (!i->label)
246                         continue;
247
248                 idx = bch2_disk_path_find_or_create(&sb, i->label);
249                 if (idx < 0)
250                         die("error creating disk path: %s", idx);
251
252                 SET_BCH_MEMBER_GROUP(m, idx + 1);
253         }
254
255         SET_BCH_SB_FOREGROUND_TARGET(sb.sb,
256                 parse_target(&sb, devs, nr_devs, fs_opt_strs.foreground_target));
257         SET_BCH_SB_BACKGROUND_TARGET(sb.sb,
258                 parse_target(&sb, devs, nr_devs, fs_opt_strs.background_target));
259         SET_BCH_SB_PROMOTE_TARGET(sb.sb,
260                 parse_target(&sb, devs, nr_devs, fs_opt_strs.promote_target));
261         SET_BCH_SB_METADATA_TARGET(sb.sb,
262                 parse_target(&sb, devs, nr_devs, fs_opt_strs.metadata_target));
263
264         /* Crypt: */
265         if (opts.encrypted) {
266                 struct bch_sb_field_crypt *crypt =
267                         bch2_sb_resize_crypt(&sb, sizeof(*crypt) / sizeof(u64));
268
269                 bch_sb_crypt_init(sb.sb, crypt, opts.passphrase);
270                 SET_BCH_SB_ENCRYPTION_TYPE(sb.sb, 1);
271         }
272
273         for (i = devs; i < devs + nr_devs; i++) {
274                 sb.sb->dev_idx = i - devs;
275
276                 if (!i->sb_offset) {
277                         i->sb_offset    = BCH_SB_SECTOR;
278                         i->sb_end       = i->size;
279                 }
280
281                 init_layout(&sb.sb->layout, fs_opts.block_size,
282                             opts.superblock_size,
283                             i->sb_offset, i->sb_end);
284
285                 /*
286                  * Also create a backup superblock at the end of the disk:
287                  *
288                  * If we're not creating a superblock at the default offset, it
289                  * means we're being run from the migrate tool and we could be
290                  * overwriting existing data if we write to the end of the disk:
291                  */
292                 if (i->sb_offset == BCH_SB_SECTOR) {
293                         struct bch_sb_layout *l = &sb.sb->layout;
294                         u64 backup_sb = i->size - (1 << l->sb_max_size_bits);
295
296                         backup_sb = rounddown(backup_sb, i->bucket_size);
297                         l->sb_offset[l->nr_superblocks++] = cpu_to_le64(backup_sb);
298                 }
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, "Label %u (%.*s)", t.group,
404                                 BCH_SB_LABEL_SIZE, g->label);
405                 } else {
406                         ret = scnprintf(buf, len, "Bad label %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 label [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                                 scnprintf(label, sizeof(label), "%.*s (%u)",
481                                         BCH_SB_LABEL_SIZE,
482                                         gi->entries[idx].label, idx);
483                         } else {
484                                 strcpy(label, "(bad disk labels section)");
485                         }
486                 } else {
487                         strcpy(label, "(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_member_states[BCH_MEMBER_STATE(m)]
536                        : "unknown",
537
538                        label,
539                        data_allowed_str,
540                        data_has_str,
541
542                        BCH_MEMBER_REPLACEMENT(m) < BCH_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         struct bch_sb_field_clean *clean = field_to_type(f, clean);
622
623
624         printf("  flags:       %x", le32_to_cpu(clean->flags));
625         printf("  journal seq: %llx", le64_to_cpu(clean->journal_seq));
626 }
627
628 static void bch2_sb_print_journal_seq_blacklist(struct bch_sb *sb, struct bch_sb_field *f,
629                                                 enum units units)
630 {
631         struct bch_sb_field_journal_seq_blacklist *bl = field_to_type(f, journal_seq_blacklist);
632         unsigned i, nr = blacklist_nr_entries(bl);
633
634         for (i = 0; i < nr; i++) {
635                 struct journal_seq_blacklist_entry *e =
636                         bl->start + i;
637
638                 printf("  %llu-%llu\n",
639                        le64_to_cpu(e->start),
640                        le64_to_cpu(e->end));
641         }
642 }
643
644 typedef void (*sb_field_print_fn)(struct bch_sb *, struct bch_sb_field *, enum units);
645
646 struct bch_sb_field_toolops {
647         sb_field_print_fn       print;
648 };
649
650 static const struct bch_sb_field_toolops bch2_sb_field_ops[] = {
651 #define x(f, nr)                                        \
652         [BCH_SB_FIELD_##f] = {                          \
653                 .print  = bch2_sb_print_##f,            \
654         },
655         BCH_SB_FIELDS()
656 #undef x
657 };
658
659 static inline void bch2_sb_field_print(struct bch_sb *sb,
660                                        struct bch_sb_field *f,
661                                        enum units units)
662 {
663         unsigned type = le32_to_cpu(f->type);
664
665         if (type < BCH_SB_FIELD_NR)
666                 bch2_sb_field_ops[type].print(sb, f, units);
667         else
668                 printf("(unknown field %u)\n", type);
669 }
670
671 void bch2_sb_print(struct bch_sb *sb, bool print_layout,
672                    unsigned fields, enum units units)
673 {
674         struct bch_sb_field_members *mi;
675         char user_uuid_str[40], internal_uuid_str[40];
676         char features_str[500];
677         char compat_features_str[500];
678         char fields_have_str[200];
679         char label[BCH_SB_LABEL_SIZE + 1];
680         char time_str[64];
681         char foreground_str[64];
682         char background_str[64];
683         char promote_str[64];
684         char metadata_str[64];
685         struct bch_sb_field *f;
686         u64 fields_have = 0;
687         unsigned nr_devices = 0;
688         time_t time_base = le64_to_cpu(sb->time_base_lo) / NSEC_PER_SEC;
689
690         memcpy(label, sb->label, BCH_SB_LABEL_SIZE);
691         label[BCH_SB_LABEL_SIZE] = '\0';
692
693         uuid_unparse(sb->user_uuid.b, user_uuid_str);
694         uuid_unparse(sb->uuid.b, internal_uuid_str);
695
696         if (time_base) {
697                 struct tm *tm = localtime(&time_base);
698                 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
699                 if (!err)
700                         strcpy(time_str, "(formatting error)");
701         } else {
702                 strcpy(time_str, "(not set)");
703         }
704
705         mi = bch2_sb_get_members(sb);
706         if (mi) {
707                 struct bch_member *m;
708
709                 for (m = mi->members;
710                      m < mi->members + sb->nr_devices;
711                      m++)
712                         nr_devices += bch2_member_exists(m);
713         }
714
715         bch2_sb_get_target(sb, foreground_str, sizeof(foreground_str),
716                 BCH_SB_FOREGROUND_TARGET(sb));
717
718         bch2_sb_get_target(sb, background_str, sizeof(background_str),
719                 BCH_SB_BACKGROUND_TARGET(sb));
720
721         bch2_sb_get_target(sb, promote_str, sizeof(promote_str),
722                 BCH_SB_PROMOTE_TARGET(sb));
723
724         bch2_sb_get_target(sb, metadata_str, sizeof(metadata_str),
725                 BCH_SB_METADATA_TARGET(sb));
726
727         bch2_flags_to_text(&PBUF(features_str),
728                            bch2_sb_features,
729                            le64_to_cpu(sb->features[0]));
730
731         bch2_flags_to_text(&PBUF(compat_features_str),
732                            bch2_sb_compat,
733                            le64_to_cpu(sb->compat[0]));
734
735         vstruct_for_each(sb, f)
736                 fields_have |= 1 << le32_to_cpu(f->type);
737         bch2_flags_to_text(&PBUF(fields_have_str),
738                            bch2_sb_fields, fields_have);
739
740         printf("External UUID:                  %s\n"
741                "Internal UUID:                  %s\n"
742                "Device index:                   %u\n"
743                "Label:                          %s\n"
744                "Version:                        %u\n"
745                "Oldest version on disk:         %u\n"
746                "Created:                        %s\n"
747                "Squence number:                 %llu\n"
748                "Block_size:                     %s\n"
749                "Btree node size:                %s\n"
750                "Error action:                   %s\n"
751                "Clean:                          %llu\n"
752                "Features:                       %s\n"
753                "Compat features:                %s\n"
754
755                "Metadata replicas:              %llu\n"
756                "Data replicas:                  %llu\n"
757
758                "Metadata checksum type:         %s (%llu)\n"
759                "Data checksum type:             %s (%llu)\n"
760                "Compression type:               %s (%llu)\n"
761
762                "Foreground write target:        %s\n"
763                "Background write target:        %s\n"
764                "Promote target:                 %s\n"
765                "Metadata target:                %s\n"
766
767                "String hash type:               %s (%llu)\n"
768                "32 bit inodes:                  %llu\n"
769                "GC reserve percentage:          %llu%%\n"
770                "Root reserve percentage:        %llu%%\n"
771
772                "Devices:                        %u live, %u total\n"
773                "Sections:                       %s\n"
774                "Superblock size:                %llu\n",
775                user_uuid_str,
776                internal_uuid_str,
777                sb->dev_idx,
778                label,
779                le16_to_cpu(sb->version),
780                le16_to_cpu(sb->version_min),
781                time_str,
782                le64_to_cpu(sb->seq),
783                pr_units(le16_to_cpu(sb->block_size), units),
784                pr_units(BCH_SB_BTREE_NODE_SIZE(sb), units),
785
786                BCH_SB_ERROR_ACTION(sb) < BCH_ON_ERROR_NR
787                ? bch2_error_actions[BCH_SB_ERROR_ACTION(sb)]
788                : "unknown",
789
790                BCH_SB_CLEAN(sb),
791                features_str,
792                compat_features_str,
793
794                BCH_SB_META_REPLICAS_WANT(sb),
795                BCH_SB_DATA_REPLICAS_WANT(sb),
796
797                BCH_SB_META_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
798                ? bch2_csum_opts[BCH_SB_META_CSUM_TYPE(sb)]
799                : "unknown",
800                BCH_SB_META_CSUM_TYPE(sb),
801
802                BCH_SB_DATA_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
803                ? bch2_csum_opts[BCH_SB_DATA_CSUM_TYPE(sb)]
804                : "unknown",
805                BCH_SB_DATA_CSUM_TYPE(sb),
806
807                BCH_SB_COMPRESSION_TYPE(sb) < BCH_COMPRESSION_OPT_NR
808                ? bch2_compression_opts[BCH_SB_COMPRESSION_TYPE(sb)]
809                : "unknown",
810                BCH_SB_COMPRESSION_TYPE(sb),
811
812                foreground_str,
813                background_str,
814                promote_str,
815                metadata_str,
816
817                BCH_SB_STR_HASH_TYPE(sb) < BCH_STR_HASH_NR
818                ? bch2_str_hash_types[BCH_SB_STR_HASH_TYPE(sb)]
819                : "unknown",
820                BCH_SB_STR_HASH_TYPE(sb),
821
822                BCH_SB_INODE_32BIT(sb),
823                BCH_SB_GC_RESERVE(sb),
824                BCH_SB_ROOT_RESERVE(sb),
825
826                nr_devices, sb->nr_devices,
827                fields_have_str,
828                vstruct_bytes(sb));
829
830         if (print_layout) {
831                 printf("\n"
832                        "Layout:\n");
833                 bch2_sb_print_layout(sb, units);
834         }
835
836         vstruct_for_each(sb, f) {
837                 unsigned type = le32_to_cpu(f->type);
838                 char name[60];
839
840                 if (!(fields & (1 << type)))
841                         continue;
842
843                 if (type < BCH_SB_FIELD_NR) {
844                         scnprintf(name, sizeof(name), "%s", bch2_sb_fields[type]);
845                         name[0] = toupper(name[0]);
846                 } else {
847                         scnprintf(name, sizeof(name), "(unknown field %u)", type);
848                 }
849
850                 printf("\n%s (size %llu):\n", name, vstruct_bytes(f));
851                 if (type < BCH_SB_FIELD_NR)
852                         bch2_sb_field_print(sb, f, units);
853         }
854 }
855
856 /* ioctl interface: */
857
858 /* Global control device: */
859 int bcachectl_open(void)
860 {
861         return xopen("/dev/bcachefs-ctl", O_RDWR);
862 }
863
864 /* Filesystem handles (ioctl, sysfs dir): */
865
866 #define SYSFS_BASE "/sys/fs/bcachefs/"
867
868 void bcache_fs_close(struct bchfs_handle fs)
869 {
870         close(fs.ioctl_fd);
871         close(fs.sysfs_fd);
872 }
873
874 struct bchfs_handle bcache_fs_open(const char *path)
875 {
876         struct bchfs_handle ret;
877
878         if (!uuid_parse(path, ret.uuid.b)) {
879                 /* It's a UUID, look it up in sysfs: */
880                 char *sysfs = mprintf(SYSFS_BASE "%s", path);
881                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
882
883                 char *minor = read_file_str(ret.sysfs_fd, "minor");
884                 char *ctl = mprintf("/dev/bcachefs%s-ctl", minor);
885                 ret.ioctl_fd = xopen(ctl, O_RDWR);
886
887                 free(sysfs);
888                 free(minor);
889                 free(ctl);
890         } else {
891                 /* It's a path: */
892                 ret.ioctl_fd = open(path, O_RDONLY);
893                 if (ret.ioctl_fd < 0)
894                         die("Error opening filesystem at %s: %m", path);
895
896                 struct bch_ioctl_query_uuid uuid;
897                 if (ioctl(ret.ioctl_fd, BCH_IOCTL_QUERY_UUID, &uuid) < 0)
898                         die("error opening %s: not a bcachefs filesystem", path);
899
900                 ret.uuid = uuid.uuid;
901
902                 char uuid_str[40];
903                 uuid_unparse(uuid.uuid.b, uuid_str);
904
905                 char *sysfs = mprintf(SYSFS_BASE "%s", uuid_str);
906                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
907                 free(sysfs);
908         }
909
910         return ret;
911 }
912
913 /*
914  * Given a path to a block device, open the filesystem it belongs to; also
915  * return the device's idx:
916  */
917 struct bchfs_handle bchu_fs_open_by_dev(const char *path, int *idx)
918 {
919         char buf[1024], *uuid_str;
920
921         struct stat stat = xstat(path);
922
923         if (!S_ISBLK(stat.st_mode))
924                 die("%s is not a block device", path);
925
926         char *sysfs = mprintf("/sys/dev/block/%u:%u/bcachefs",
927                               major(stat.st_dev),
928                               minor(stat.st_dev));
929         ssize_t len = readlink(sysfs, buf, sizeof(buf));
930         free(sysfs);
931
932         if (len > 0) {
933                 char *p = strrchr(buf, '/');
934                 if (!p || sscanf(p + 1, "dev-%u", idx) != 1)
935                         die("error parsing sysfs");
936
937                 *p = '\0';
938                 p = strrchr(buf, '/');
939                 uuid_str = p + 1;
940         } else {
941                 struct bch_opts opts = bch2_opts_empty();
942
943                 opt_set(opts, noexcl,   true);
944                 opt_set(opts, nochanges, true);
945
946                 struct bch_sb_handle sb;
947                 int ret = bch2_read_super(path, &opts, &sb);
948                 if (ret)
949                         die("Error opening %s: %s", path, strerror(-ret));
950
951                 *idx = sb.sb->dev_idx;
952                 uuid_str = buf;
953                 uuid_unparse(sb.sb->user_uuid.b, uuid_str);
954
955                 bch2_free_super(&sb);
956         }
957
958         return bcache_fs_open(uuid_str);
959 }
960
961 int bchu_dev_path_to_idx(struct bchfs_handle fs, const char *dev_path)
962 {
963         int idx;
964         struct bchfs_handle fs2 = bchu_fs_open_by_dev(dev_path, &idx);
965
966         if (memcmp(&fs.uuid, &fs2.uuid, sizeof(fs.uuid)))
967                 idx = -1;
968         bcache_fs_close(fs2);
969         return idx;
970 }
971
972 int bchu_data(struct bchfs_handle fs, struct bch_ioctl_data cmd)
973 {
974         int progress_fd = xioctl(fs.ioctl_fd, BCH_IOCTL_DATA, &cmd);
975
976         while (1) {
977                 struct bch_ioctl_data_event e;
978
979                 if (read(progress_fd, &e, sizeof(e)) != sizeof(e))
980                         die("error reading from progress fd %m");
981
982                 if (e.type)
983                         continue;
984
985                 if (e.p.data_type == U8_MAX)
986                         break;
987
988                 printf("\33[2K\r");
989
990                 printf("%llu%% complete: current position %s",
991                        e.p.sectors_total
992                        ? e.p.sectors_done * 100 / e.p.sectors_total
993                        : 0,
994                        bch2_data_types[e.p.data_type]);
995
996                 switch (e.p.data_type) {
997                 case BCH_DATA_btree:
998                 case BCH_DATA_user:
999                         printf(" %s:%llu:%llu",
1000                                bch2_btree_ids[e.p.btree_id],
1001                                e.p.pos.inode,
1002                                e.p.pos.offset);
1003                 }
1004
1005                 fflush(stdout);
1006                 sleep(1);
1007         }
1008         printf("\nDone\n");
1009
1010         close(progress_fd);
1011         return 0;
1012 }
1013
1014 /* option parsing */
1015
1016 void bch2_opt_strs_free(struct bch_opt_strs *opts)
1017 {
1018         unsigned i;
1019
1020         for (i = 0; i < bch2_opts_nr; i++) {
1021                 free(opts->by_id[i]);
1022                 opts->by_id[i] = NULL;
1023         }
1024 }
1025
1026 struct bch_opt_strs bch2_cmdline_opts_get(int *argc, char *argv[],
1027                                           unsigned opt_types)
1028 {
1029         struct bch_opt_strs opts;
1030         unsigned i = 1;
1031
1032         memset(&opts, 0, sizeof(opts));
1033
1034         while (i < *argc) {
1035                 char *optstr = strcmp_prefix(argv[i], "--");
1036                 char *valstr = NULL, *p;
1037                 int optid, nr_args = 1;
1038
1039                 if (!optstr) {
1040                         i++;
1041                         continue;
1042                 }
1043
1044                 optstr = strdup(optstr);
1045
1046                 p = optstr;
1047                 while (isalpha(*p) || *p == '_')
1048                         p++;
1049
1050                 if (*p == '=') {
1051                         *p = '\0';
1052                         valstr = p + 1;
1053                 }
1054
1055                 optid = bch2_opt_lookup(optstr);
1056                 if (optid < 0 ||
1057                     !(bch2_opt_table[optid].flags & opt_types)) {
1058                         i++;
1059                         goto next;
1060                 }
1061
1062                 if (!valstr &&
1063                     bch2_opt_table[optid].type != BCH_OPT_BOOL) {
1064                         nr_args = 2;
1065                         valstr = argv[i + 1];
1066                 }
1067
1068                 if (!valstr)
1069                         valstr = "1";
1070
1071                 opts.by_id[optid] = strdup(valstr);
1072
1073                 *argc -= nr_args;
1074                 memmove(&argv[i],
1075                         &argv[i + nr_args],
1076                         sizeof(char *) * (*argc - i));
1077                 argv[*argc] = NULL;
1078 next:
1079                 free(optstr);
1080         }
1081
1082         return opts;
1083 }
1084
1085 struct bch_opts bch2_parse_opts(struct bch_opt_strs strs)
1086 {
1087         struct bch_opts opts = bch2_opts_empty();
1088         unsigned i;
1089         int ret;
1090         u64 v;
1091
1092         for (i = 0; i < bch2_opts_nr; i++) {
1093                 if (!strs.by_id[i] ||
1094                     bch2_opt_table[i].type == BCH_OPT_FN)
1095                         continue;
1096
1097                 ret = bch2_opt_parse(NULL, "option",
1098                                      &bch2_opt_table[i],
1099                                      strs.by_id[i], &v);
1100                 if (ret < 0)
1101                         die("Invalid %s: %s",
1102                             bch2_opt_table[i].attr.name,
1103                             strerror(-ret));
1104
1105                 bch2_opt_set_by_id(&opts, i, v);
1106         }
1107
1108         return opts;
1109 }
1110
1111 #define newline(c)              \
1112         do {                    \
1113                 printf("\n");   \
1114                 c = 0;          \
1115         } while(0)
1116 void bch2_opts_usage(unsigned opt_types)
1117 {
1118         const struct bch_option *opt;
1119         unsigned i, c = 0, helpcol = 30;
1120
1121
1122
1123         for (opt = bch2_opt_table;
1124              opt < bch2_opt_table + bch2_opts_nr;
1125              opt++) {
1126                 if (!(opt->flags & opt_types))
1127                         continue;
1128
1129                 c += printf("      --%s", opt->attr.name);
1130
1131                 switch (opt->type) {
1132                 case BCH_OPT_BOOL:
1133                         break;
1134                 case BCH_OPT_STR:
1135                         c += printf("=(");
1136                         for (i = 0; opt->choices[i]; i++) {
1137                                 if (i)
1138                                         c += printf("|");
1139                                 c += printf("%s", opt->choices[i]);
1140                         }
1141                         c += printf(")");
1142                         break;
1143                 default:
1144                         c += printf("=%s", opt->hint);
1145                         break;
1146                 }
1147
1148                 if (opt->help) {
1149                         const char *l = opt->help;
1150
1151                         if (c >= helpcol)
1152                                 newline(c);
1153
1154                         while (1) {
1155                                 const char *n = strchrnul(l, '\n');
1156
1157                                 while (c < helpcol) {
1158                                         putchar(' ');
1159                                         c++;
1160                                 }
1161                                 printf("%.*s", (int) (n - l), l);
1162                                 newline(c);
1163
1164                                 if (!*n)
1165                                         break;
1166                                 l = n + 1;
1167                         }
1168                 } else {
1169                         newline(c);
1170                 }
1171         }
1172 }
1173
1174 dev_names bchu_fs_get_devices(struct bchfs_handle fs)
1175 {
1176         DIR *dir = fdopendir(fs.sysfs_fd);
1177         struct dirent *d;
1178         dev_names devs;
1179
1180         darray_init(devs);
1181
1182         while ((errno = 0), (d = readdir(dir))) {
1183                 struct dev_name n = { 0, NULL, NULL };
1184
1185                 if (sscanf(d->d_name, "dev-%u", &n.idx) != 1)
1186                         continue;
1187
1188                 char *block_attr = mprintf("dev-%u/block", n.idx);
1189
1190                 char sysfs_block_buf[4096];
1191                 ssize_t r = readlinkat(fs.sysfs_fd, block_attr,
1192                                        sysfs_block_buf, sizeof(sysfs_block_buf));
1193                 if (r > 0) {
1194                         sysfs_block_buf[r] = '\0';
1195                         n.dev = strdup(basename(sysfs_block_buf));
1196                 }
1197
1198                 free(block_attr);
1199
1200                 char *label_attr = mprintf("dev-%u/label", n.idx);
1201                 n.label = read_file_str(fs.sysfs_fd, label_attr);
1202                 free(label_attr);
1203
1204                 darray_append(devs, n);
1205         }
1206
1207         closedir(dir);
1208
1209         return devs;
1210 }