]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs.c
Update bcachefs sources to b12d1535f3 bcachefs: fix bounds checks in bch2_bio_map()
[bcachefs-tools-debian] / libbcachefs.c
1 #include <ctype.h>
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <stdbool.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/stat.h>
10 #include <sys/sysmacros.h>
11 #include <sys/types.h>
12 #include <time.h>
13 #include <unistd.h>
14
15 #include <uuid/uuid.h>
16
17 #include "libbcachefs.h"
18 #include "crypto.h"
19 #include "libbcachefs/bcachefs_format.h"
20 #include "libbcachefs/btree_cache.h"
21 #include "libbcachefs/checksum.h"
22 #include "libbcachefs/disk_groups.h"
23 #include "libbcachefs/opts.h"
24 #include "libbcachefs/replicas.h"
25 #include "libbcachefs/super-io.h"
26
27 #define NSEC_PER_SEC    1000000000L
28
29 #define BCH_MIN_NR_NBUCKETS     (1 << 10)
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 format_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                 dev->bucket_size = max(dev->bucket_size, opts.btree_node_size);
96
97                 /* Want a bucket size of at least 128k, if possible: */
98                 dev->bucket_size = max(dev->bucket_size, 256U);
99
100                 if (dev->size >= min_size(dev->bucket_size)) {
101                         unsigned scale = max(1,
102                                              ilog2(dev->size / min_size(dev->bucket_size)) / 4);
103
104                         scale = rounddown_pow_of_two(scale);
105
106                         /* max bucket size 1 mb */
107                         dev->bucket_size = min(dev->bucket_size * scale, 1U << 11);
108                 } else {
109                         do {
110                                 dev->bucket_size /= 2;
111                         } while (dev->size < min_size(dev->bucket_size));
112                 }
113         }
114
115         dev->nbuckets   = dev->size / dev->bucket_size;
116
117         if (dev->bucket_size < opts.block_size)
118                 die("Bucket size cannot be smaller than block size");
119
120         if (dev->bucket_size < opts.btree_node_size)
121                 die("Bucket size cannot be smaller than btree node size");
122
123         if (dev->nbuckets < BCH_MIN_NR_NBUCKETS)
124                 die("Not enough buckets: %llu, need %u (bucket size %u)",
125                     dev->nbuckets, BCH_MIN_NR_NBUCKETS, dev->bucket_size);
126
127 }
128
129 static unsigned parse_target(struct bch_sb_handle *sb,
130                              struct dev_opts *devs, size_t nr_devs,
131                              const char *s)
132 {
133         struct dev_opts *i;
134         int idx;
135
136         if (!s)
137                 return 0;
138
139         for (i = devs; i < devs + nr_devs; i++)
140                 if (!strcmp(s, i->path))
141                         return dev_to_target(i - devs);
142
143         idx = bch2_disk_path_find(sb, s);
144         if (idx >= 0)
145                 return group_to_target(idx);
146
147         die("Invalid target %s", s);
148         return 0;
149 }
150
151 struct bch_sb *bch2_format(struct format_opts opts,
152                            struct dev_opts *devs, size_t nr_devs)
153 {
154         struct bch_sb_handle sb = { NULL };
155         struct dev_opts *i;
156         struct bch_sb_field_members *mi;
157
158         /* calculate block size: */
159         if (!opts.block_size)
160                 for (i = devs; i < devs + nr_devs; i++)
161                         opts.block_size = max(opts.block_size,
162                                               get_blocksize(i->path, i->fd));
163
164         /* calculate bucket sizes: */
165         for (i = devs; i < devs + nr_devs; i++)
166                 bch2_pick_bucket_size(opts, i);
167
168         /* calculate btree node size: */
169         if (!opts.btree_node_size) {
170                 /* 256k default btree node size */
171                 opts.btree_node_size = 512;
172
173                 for (i = devs; i < devs + nr_devs; i++)
174                         opts.btree_node_size =
175                                 min(opts.btree_node_size, i->bucket_size);
176         }
177
178         if (!is_power_of_2(opts.block_size))
179                 die("block size must be power of 2");
180
181         if (!is_power_of_2(opts.btree_node_size))
182                 die("btree node size must be power of 2");
183
184         if (uuid_is_null(opts.uuid.b))
185                 uuid_generate(opts.uuid.b);
186
187         if (bch2_sb_realloc(&sb, 0))
188                 die("insufficient memory");
189
190         sb.sb->version          = cpu_to_le64(BCH_SB_VERSION_MAX);
191         sb.sb->magic            = BCACHE_MAGIC;
192         sb.sb->block_size       = cpu_to_le16(opts.block_size);
193         sb.sb->user_uuid        = opts.uuid;
194         sb.sb->nr_devices       = nr_devs;
195
196         uuid_generate(sb.sb->uuid.b);
197
198         if (opts.label)
199                 memcpy(sb.sb->label,
200                        opts.label,
201                        min(strlen(opts.label), sizeof(sb.sb->label)));
202
203         SET_BCH_SB_CSUM_TYPE(sb.sb,             opts.meta_csum_type);
204         SET_BCH_SB_META_CSUM_TYPE(sb.sb,        opts.meta_csum_type);
205         SET_BCH_SB_DATA_CSUM_TYPE(sb.sb,        opts.data_csum_type);
206         SET_BCH_SB_COMPRESSION_TYPE(sb.sb,      opts.compression_type);
207         SET_BCH_SB_BACKGROUND_COMPRESSION_TYPE(sb.sb,
208                                                 opts.background_compression_type);
209
210         SET_BCH_SB_BTREE_NODE_SIZE(sb.sb,       opts.btree_node_size);
211         SET_BCH_SB_GC_RESERVE(sb.sb,            8);
212         SET_BCH_SB_META_REPLICAS_WANT(sb.sb,    opts.meta_replicas);
213         SET_BCH_SB_META_REPLICAS_REQ(sb.sb,     opts.meta_replicas_required);
214         SET_BCH_SB_DATA_REPLICAS_WANT(sb.sb,    opts.data_replicas);
215         SET_BCH_SB_DATA_REPLICAS_REQ(sb.sb,     opts.data_replicas_required);
216         SET_BCH_SB_ERROR_ACTION(sb.sb,          opts.on_error_action);
217         SET_BCH_SB_STR_HASH_TYPE(sb.sb,         BCH_STR_HASH_SIPHASH);
218         SET_BCH_SB_ENCODED_EXTENT_MAX_BITS(sb.sb,ilog2(opts.encoded_extent_max));
219
220         SET_BCH_SB_POSIX_ACL(sb.sb,             1);
221
222         struct timespec now;
223         if (clock_gettime(CLOCK_REALTIME, &now))
224                 die("error getting current time: %m");
225
226         sb.sb->time_base_lo     = cpu_to_le64(now.tv_sec * NSEC_PER_SEC + now.tv_nsec);
227         sb.sb->time_precision   = cpu_to_le32(1);
228
229         /* Member info: */
230         mi = bch2_sb_resize_members(&sb,
231                         (sizeof(*mi) + sizeof(struct bch_member) *
232                          nr_devs) / sizeof(u64));
233
234         for (i = devs; i < devs + nr_devs; i++) {
235                 struct bch_member *m = mi->members + (i - devs);
236
237                 uuid_generate(m->uuid.b);
238                 m->nbuckets     = cpu_to_le64(i->nbuckets);
239                 m->first_bucket = 0;
240                 m->bucket_size  = cpu_to_le16(i->bucket_size);
241
242                 SET_BCH_MEMBER_REPLACEMENT(m,   CACHE_REPLACEMENT_LRU);
243                 SET_BCH_MEMBER_DISCARD(m,       i->discard);
244                 SET_BCH_MEMBER_DATA_ALLOWED(m,  i->data_allowed);
245                 SET_BCH_MEMBER_DURABILITY(m,    i->durability + 1);
246         }
247
248         /* Disk groups */
249         for (i = devs; i < devs + nr_devs; i++) {
250                 struct bch_member *m = mi->members + (i - devs);
251                 int idx;
252
253                 if (!i->group)
254                         continue;
255
256                 idx = bch2_disk_path_find_or_create(&sb, i->group);
257                 if (idx < 0)
258                         die("error creating disk path: %s", idx);
259
260                 SET_BCH_MEMBER_GROUP(m, idx + 1);
261         }
262
263         SET_BCH_SB_FOREGROUND_TARGET(sb.sb,
264                 parse_target(&sb, devs, nr_devs, opts.foreground_target));
265         SET_BCH_SB_BACKGROUND_TARGET(sb.sb,
266                 parse_target(&sb, devs, nr_devs, opts.background_target));
267         SET_BCH_SB_PROMOTE_TARGET(sb.sb,
268                 parse_target(&sb, devs, nr_devs, opts.promote_target));
269
270         /* Crypt: */
271         if (opts.encrypted) {
272                 struct bch_sb_field_crypt *crypt =
273                         bch2_sb_resize_crypt(&sb, sizeof(*crypt) / sizeof(u64));
274
275                 bch_sb_crypt_init(sb.sb, crypt, opts.passphrase);
276                 SET_BCH_SB_ENCRYPTION_TYPE(sb.sb, 1);
277         }
278
279         for (i = devs; i < devs + nr_devs; i++) {
280                 sb.sb->dev_idx = i - devs;
281
282                 init_layout(&sb.sb->layout, opts.block_size,
283                             i->sb_offset, i->sb_end);
284
285                 if (i->sb_offset == BCH_SB_SECTOR) {
286                         /* Zero start of disk */
287                         static const char zeroes[BCH_SB_SECTOR << 9];
288
289                         xpwrite(i->fd, zeroes, BCH_SB_SECTOR << 9, 0);
290                 }
291
292                 bch2_super_write(i->fd, sb.sb);
293                 close(i->fd);
294         }
295
296         return sb.sb;
297 }
298
299 void bch2_super_write(int fd, struct bch_sb *sb)
300 {
301         struct nonce nonce = { 0 };
302
303         unsigned i;
304         for (i = 0; i < sb->layout.nr_superblocks; i++) {
305                 sb->offset = sb->layout.sb_offset[i];
306
307                 if (sb->offset == BCH_SB_SECTOR) {
308                         /* Write backup layout */
309                         xpwrite(fd, &sb->layout, sizeof(sb->layout),
310                                 BCH_SB_LAYOUT_SECTOR << 9);
311                 }
312
313                 sb->csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb), nonce, sb);
314                 xpwrite(fd, sb, vstruct_bytes(sb),
315                         le64_to_cpu(sb->offset) << 9);
316         }
317
318         fsync(fd);
319 }
320
321 struct bch_sb *__bch2_super_read(int fd, u64 sector)
322 {
323         struct bch_sb sb, *ret;
324
325         xpread(fd, &sb, sizeof(sb), sector << 9);
326
327         if (memcmp(&sb.magic, &BCACHE_MAGIC, sizeof(sb.magic)))
328                 die("not a bcachefs superblock");
329
330         size_t bytes = vstruct_bytes(&sb);
331
332         ret = malloc(bytes);
333
334         xpread(fd, ret, bytes, sector << 9);
335
336         return ret;
337 }
338
339 static unsigned get_dev_has_data(struct bch_sb *sb, unsigned dev)
340 {
341         struct bch_sb_field_replicas *replicas;
342         struct bch_replicas_entry *r;
343         unsigned i, data_has = 0;
344
345         replicas = bch2_sb_get_replicas(sb);
346
347         if (replicas)
348                 for_each_replicas_entry(replicas, r)
349                         for (i = 0; i < r->nr_devs; i++)
350                                 if (r->devs[i] == dev)
351                                         data_has |= 1 << r->data_type;
352
353         return data_has;
354 }
355
356 /* superblock printing: */
357
358 static void bch2_sb_print_layout(struct bch_sb *sb, enum units units)
359 {
360         struct bch_sb_layout *l = &sb->layout;
361         unsigned i;
362
363         printf("  type:                         %u\n"
364                "  superblock max size:          %s\n"
365                "  nr superblocks:               %u\n"
366                "  Offsets:                      ",
367                l->layout_type,
368                pr_units(1 << l->sb_max_size_bits, units),
369                l->nr_superblocks);
370
371         for (i = 0; i < l->nr_superblocks; i++) {
372                 if (i)
373                         printf(", ");
374                 printf("%llu", le64_to_cpu(l->sb_offset[i]));
375         }
376         putchar('\n');
377 }
378
379 static void bch2_sb_print_journal(struct bch_sb *sb, struct bch_sb_field *f,
380                                   enum units units)
381 {
382         struct bch_sb_field_journal *journal = field_to_type(f, journal);
383         unsigned i, nr = bch2_nr_journal_buckets(journal);
384
385         printf("  Buckets:                      ");
386         for (i = 0; i < nr; i++) {
387                 if (i)
388                         putchar(' ');
389                 printf("%llu", le64_to_cpu(journal->buckets[i]));
390         }
391         putchar('\n');
392 }
393
394 static void bch2_sb_print_members(struct bch_sb *sb, struct bch_sb_field *f,
395                                   enum units units)
396 {
397         struct bch_sb_field_members *mi = field_to_type(f, members);
398         struct bch_sb_field_disk_groups *gi = bch2_sb_get_disk_groups(sb);
399         unsigned i;
400
401         for (i = 0; i < sb->nr_devices; i++) {
402                 struct bch_member *m = mi->members + i;
403                 time_t last_mount = le64_to_cpu(m->last_mount);
404                 char member_uuid_str[40];
405                 char data_allowed_str[100];
406                 char data_has_str[100];
407                 char group[64];
408
409                 if (!bch2_member_exists(m))
410                         continue;
411
412                 uuid_unparse(m->uuid.b, member_uuid_str);
413
414                 if (BCH_MEMBER_GROUP(m)) {
415                         unsigned idx = BCH_MEMBER_GROUP(m) - 1;
416
417                         if (idx < disk_groups_nr(gi)) {
418                                 memcpy(group, gi->entries[idx].label,
419                                        BCH_SB_LABEL_SIZE);
420                                 group[BCH_SB_LABEL_SIZE] = '\0';
421                         } else {
422                                 strcpy(group, "(bad disk groups section");
423                         }
424                 }
425
426                 bch2_scnprint_flag_list(data_allowed_str,
427                                         sizeof(data_allowed_str),
428                                         bch2_data_types,
429                                         BCH_MEMBER_DATA_ALLOWED(m));
430                 if (!data_allowed_str[0])
431                         strcpy(data_allowed_str, "(none)");
432
433                 bch2_scnprint_flag_list(data_has_str,
434                                         sizeof(data_has_str),
435                                         bch2_data_types,
436                                         get_dev_has_data(sb, i));
437                 if (!data_has_str[0])
438                         strcpy(data_has_str, "(none)");
439
440                 printf("  Device %u:\n"
441                        "    UUID:                       %s\n"
442                        "    Size:                       %s\n"
443                        "    Bucket size:                %s\n"
444                        "    First bucket:               %u\n"
445                        "    Buckets:                    %llu\n"
446                        "    Last mount:                 %s\n"
447                        "    State:                      %s\n"
448                        "    Group:                      %s\n"
449                        "    Data allowed:               %s\n"
450
451                        "    Has data:                   %s\n"
452
453                        "    Replacement policy:         %s\n"
454                        "    Discard:                    %llu\n",
455                        i, member_uuid_str,
456                        pr_units(le16_to_cpu(m->bucket_size) *
457                                 le64_to_cpu(m->nbuckets), units),
458                        pr_units(le16_to_cpu(m->bucket_size), units),
459                        le16_to_cpu(m->first_bucket),
460                        le64_to_cpu(m->nbuckets),
461                        last_mount ? ctime(&last_mount) : "(never)",
462
463                        BCH_MEMBER_STATE(m) < BCH_MEMBER_STATE_NR
464                        ? bch2_dev_state[BCH_MEMBER_STATE(m)]
465                        : "unknown",
466
467                        group,
468                        data_allowed_str,
469                        data_has_str,
470
471                        BCH_MEMBER_REPLACEMENT(m) < CACHE_REPLACEMENT_NR
472                        ? bch2_cache_replacement_policies[BCH_MEMBER_REPLACEMENT(m)]
473                        : "unknown",
474
475                        BCH_MEMBER_DISCARD(m));
476         }
477 }
478
479 static void bch2_sb_print_crypt(struct bch_sb *sb, struct bch_sb_field *f,
480                                 enum units units)
481 {
482         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
483
484         printf("  KFD:                  %llu\n"
485                "  scrypt n:             %llu\n"
486                "  scrypt r:             %llu\n"
487                "  scrypt p:             %llu\n",
488                BCH_CRYPT_KDF_TYPE(crypt),
489                BCH_KDF_SCRYPT_N(crypt),
490                BCH_KDF_SCRYPT_R(crypt),
491                BCH_KDF_SCRYPT_P(crypt));
492 }
493
494 static void bch2_sb_print_replicas(struct bch_sb *sb, struct bch_sb_field *f,
495                                    enum units units)
496 {
497         struct bch_sb_field_replicas *replicas = field_to_type(f, replicas);
498         struct bch_replicas_entry *e;
499         unsigned i;
500
501         for_each_replicas_entry(replicas, e) {
502                 printf_pad(32, "  %s:", bch2_data_types[e->data_type]);
503
504                 putchar('[');
505                 for (i = 0; i < e->nr_devs; i++) {
506                         if (i)
507                                 putchar(' ');
508                         printf("%u", e->devs[i]);
509                 }
510                 printf("]\n");
511         }
512 }
513
514 static void bch2_sb_print_quota(struct bch_sb *sb, struct bch_sb_field *f,
515                                 enum units units)
516 {
517 }
518
519 static void bch2_sb_print_disk_groups(struct bch_sb *sb, struct bch_sb_field *f,
520                                       enum units units)
521 {
522 }
523
524 static void bch2_sb_print_clean(struct bch_sb *sb, struct bch_sb_field *f,
525                                 enum units units)
526 {
527 }
528
529 typedef void (*sb_field_print_fn)(struct bch_sb *, struct bch_sb_field *, enum units);
530
531 struct bch_sb_field_toolops {
532         sb_field_print_fn       print;
533 };
534
535 static const struct bch_sb_field_toolops bch2_sb_field_ops[] = {
536 #define x(f, nr)                                        \
537         [BCH_SB_FIELD_##f] = {                          \
538                 .print  = bch2_sb_print_##f,            \
539         },
540         BCH_SB_FIELDS()
541 #undef x
542 };
543
544 static inline void bch2_sb_field_print(struct bch_sb *sb,
545                                        struct bch_sb_field *f,
546                                        enum units units)
547 {
548         unsigned type = le32_to_cpu(f->type);
549
550         if (type < BCH_SB_FIELD_NR)
551                 bch2_sb_field_ops[type].print(sb, f, units);
552         else
553                 printf("(unknown field %u)\n", type);
554 }
555
556 void bch2_sb_print(struct bch_sb *sb, bool print_layout,
557                    unsigned fields, enum units units)
558 {
559         struct bch_sb_field_members *mi;
560         char user_uuid_str[40], internal_uuid_str[40];
561         char fields_have_str[200];
562         char label[BCH_SB_LABEL_SIZE + 1];
563         struct bch_sb_field *f;
564         u64 fields_have = 0;
565         unsigned nr_devices = 0;
566
567         memset(label, 0, sizeof(label));
568         memcpy(label, sb->label, sizeof(sb->label));
569         uuid_unparse(sb->user_uuid.b, user_uuid_str);
570         uuid_unparse(sb->uuid.b, internal_uuid_str);
571
572         mi = bch2_sb_get_members(sb);
573         if (mi) {
574                 struct bch_member *m;
575
576                 for (m = mi->members;
577                      m < mi->members + sb->nr_devices;
578                      m++)
579                         nr_devices += bch2_member_exists(m);
580         }
581
582         vstruct_for_each(sb, f)
583                 fields_have |= 1 << le32_to_cpu(f->type);
584         bch2_scnprint_flag_list(fields_have_str, sizeof(fields_have_str),
585                                 bch2_sb_fields, fields_have);
586
587         printf("External UUID:                  %s\n"
588                "Internal UUID:                  %s\n"
589                "Label:                          %s\n"
590                "Version:                        %llu\n"
591                "Block_size:                     %s\n"
592                "Btree node size:                %s\n"
593                "Error action:                   %s\n"
594                "Clean:                          %llu\n"
595
596                "Metadata replicas:              %llu\n"
597                "Data replicas:                  %llu\n"
598
599                "Metadata checksum type:         %s (%llu)\n"
600                "Data checksum type:             %s (%llu)\n"
601                "Compression type:               %s (%llu)\n"
602
603                "Foreground write target:        %llu\n"
604                "Background write target:        %llu\n"
605                "Promote target:                 %llu\n"
606
607                "String hash type:               %s (%llu)\n"
608                "32 bit inodes:                  %llu\n"
609                "GC reserve percentage:          %llu%%\n"
610                "Root reserve percentage:        %llu%%\n"
611
612                "Devices:                        %u live, %u total\n"
613                "Sections:                       %s\n"
614                "Superblock size:                %llu\n",
615                user_uuid_str,
616                internal_uuid_str,
617                label,
618                le64_to_cpu(sb->version),
619                pr_units(le16_to_cpu(sb->block_size), units),
620                pr_units(BCH_SB_BTREE_NODE_SIZE(sb), units),
621
622                BCH_SB_ERROR_ACTION(sb) < BCH_NR_ERROR_ACTIONS
623                ? bch2_error_actions[BCH_SB_ERROR_ACTION(sb)]
624                : "unknown",
625
626                BCH_SB_CLEAN(sb),
627
628                BCH_SB_META_REPLICAS_WANT(sb),
629                BCH_SB_DATA_REPLICAS_WANT(sb),
630
631                BCH_SB_META_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
632                ? bch2_csum_types[BCH_SB_META_CSUM_TYPE(sb)]
633                : "unknown",
634                BCH_SB_META_CSUM_TYPE(sb),
635
636                BCH_SB_DATA_CSUM_TYPE(sb) < BCH_CSUM_OPT_NR
637                ? bch2_csum_types[BCH_SB_DATA_CSUM_TYPE(sb)]
638                : "unknown",
639                BCH_SB_DATA_CSUM_TYPE(sb),
640
641                BCH_SB_COMPRESSION_TYPE(sb) < BCH_COMPRESSION_OPT_NR
642                ? bch2_compression_types[BCH_SB_COMPRESSION_TYPE(sb)]
643                : "unknown",
644                BCH_SB_COMPRESSION_TYPE(sb),
645
646                BCH_SB_FOREGROUND_TARGET(sb),
647                BCH_SB_BACKGROUND_TARGET(sb),
648                BCH_SB_PROMOTE_TARGET(sb),
649
650                BCH_SB_STR_HASH_TYPE(sb) < BCH_STR_HASH_NR
651                ? bch2_str_hash_types[BCH_SB_STR_HASH_TYPE(sb)]
652                : "unknown",
653                BCH_SB_STR_HASH_TYPE(sb),
654
655                BCH_SB_INODE_32BIT(sb),
656                BCH_SB_GC_RESERVE(sb),
657                BCH_SB_ROOT_RESERVE(sb),
658
659                nr_devices, sb->nr_devices,
660                fields_have_str,
661                vstruct_bytes(sb));
662
663         if (print_layout) {
664                 printf("\n"
665                        "Layout:\n");
666                 bch2_sb_print_layout(sb, units);
667         }
668
669         vstruct_for_each(sb, f) {
670                 unsigned type = le32_to_cpu(f->type);
671                 char name[60];
672
673                 if (!(fields & (1 << type)))
674                         continue;
675
676                 if (type < BCH_SB_FIELD_NR) {
677                         scnprintf(name, sizeof(name), "%s", bch2_sb_fields[type]);
678                         name[0] = toupper(name[0]);
679                 } else {
680                         scnprintf(name, sizeof(name), "(unknown field %u)", type);
681                 }
682
683                 printf("\n%s (size %llu):\n", name, vstruct_bytes(f));
684                 if (type < BCH_SB_FIELD_NR)
685                         bch2_sb_field_print(sb, f, units);
686         }
687 }
688
689 /* ioctl interface: */
690
691 /* Global control device: */
692 int bcachectl_open(void)
693 {
694         return xopen("/dev/bcachefs-ctl", O_RDWR);
695 }
696
697 /* Filesystem handles (ioctl, sysfs dir): */
698
699 #define SYSFS_BASE "/sys/fs/bcachefs/"
700
701 void bcache_fs_close(struct bchfs_handle fs)
702 {
703         close(fs.ioctl_fd);
704         close(fs.sysfs_fd);
705 }
706
707 struct bchfs_handle bcache_fs_open(const char *path)
708 {
709         struct bchfs_handle ret;
710
711         if (!uuid_parse(path, ret.uuid.b)) {
712                 /* It's a UUID, look it up in sysfs: */
713                 char *sysfs = mprintf(SYSFS_BASE "%s", path);
714                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
715
716                 char *minor = read_file_str(ret.sysfs_fd, "minor");
717                 char *ctl = mprintf("/dev/bcachefs%s-ctl", minor);
718                 ret.ioctl_fd = xopen(ctl, O_RDWR);
719
720                 free(sysfs);
721                 free(minor);
722                 free(ctl);
723         } else {
724                 /* It's a path: */
725                 ret.ioctl_fd = xopen(path, O_RDONLY);
726
727                 struct bch_ioctl_query_uuid uuid;
728                 if (ioctl(ret.ioctl_fd, BCH_IOCTL_QUERY_UUID, &uuid) < 0)
729                         die("error opening %s: not a bcachefs filesystem", path);
730
731                 ret.uuid = uuid.uuid;
732
733                 char uuid_str[40];
734                 uuid_unparse(uuid.uuid.b, uuid_str);
735
736                 char *sysfs = mprintf(SYSFS_BASE "%s", uuid_str);
737                 ret.sysfs_fd = xopen(sysfs, O_RDONLY);
738                 free(sysfs);
739         }
740
741         return ret;
742 }
743
744 /*
745  * Given a path to a block device, open the filesystem it belongs to; also
746  * return the device's idx:
747  */
748 struct bchfs_handle bchu_fs_open_by_dev(const char *path, unsigned *idx)
749 {
750         char buf[1024], *uuid_str;
751
752         struct stat stat = xstat(path);
753
754         if (!S_ISBLK(stat.st_mode))
755                 die("%s is not a block device", path);
756
757         char *sysfs = mprintf("/sys/dev/block/%u:%u/bcachefs",
758                               major(stat.st_dev),
759                               minor(stat.st_dev));
760         ssize_t len = readlink(sysfs, buf, sizeof(buf));
761         free(sysfs);
762
763         if (len > 0) {
764                 char *p = strrchr(buf, '/');
765                 if (!p || sscanf(p + 1, "dev-%u", idx) != 1)
766                         die("error parsing sysfs");
767
768                 *p = '\0';
769                 p = strrchr(buf, '/');
770                 uuid_str = p + 1;
771         } else {
772                 struct bch_opts opts = bch2_opts_empty();
773
774                 opt_set(opts, noexcl,   true);
775                 opt_set(opts, nochanges, true);
776
777                 struct bch_sb_handle sb;
778                 int ret = bch2_read_super(path, &opts, &sb);
779                 if (ret)
780                         die("Error opening %s: %s", path, strerror(-ret));
781
782                 *idx = sb.sb->dev_idx;
783                 uuid_str = buf;
784                 uuid_unparse(sb.sb->user_uuid.b, uuid_str);
785
786                 bch2_free_super(&sb);
787         }
788
789         return bcache_fs_open(uuid_str);
790 }
791
792 int bchu_data(struct bchfs_handle fs, struct bch_ioctl_data cmd)
793 {
794         int progress_fd = xioctl(fs.ioctl_fd, BCH_IOCTL_DATA, &cmd);
795
796         while (1) {
797                 struct bch_ioctl_data_event e;
798
799                 if (read(progress_fd, &e, sizeof(e)) != sizeof(e))
800                         die("error reading from progress fd %m");
801
802                 if (e.type)
803                         continue;
804
805                 if (e.p.data_type == U8_MAX)
806                         break;
807
808                 printf("\33[2K\r");
809
810                 printf("%llu%% complete: current position %s",
811                        e.p.sectors_done * 100 / e.p.sectors_total,
812                        bch2_data_types[e.p.data_type]);
813
814                 switch (e.p.data_type) {
815                 case BCH_DATA_BTREE:
816                 case BCH_DATA_USER:
817                         printf(" %s:%llu:%llu",
818                                bch2_btree_ids[e.p.btree_id],
819                                e.p.pos.inode,
820                                e.p.pos.offset);
821                 }
822
823                 sleep(1);
824         }
825         printf("\nDone\n");
826
827         close(progress_fd);
828         return 0;
829 }