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