btrfs-progs: inspect: add command min-dev-size
[platform/upstream/btrfs-progs.git] / cmds-inspect.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <stdint.h>
21 #include <sys/ioctl.h>
22 #include <errno.h>
23 #include <getopt.h>
24
25 #include "kerncompat.h"
26 #include "ioctl.h"
27 #include "utils.h"
28 #include "ctree.h"
29 #include "send-utils.h"
30 #include "disk-io.h"
31 #include "commands.h"
32 #include "btrfs-list.h"
33
34 static const char * const inspect_cmd_group_usage[] = {
35         "btrfs inspect-internal <command> <args>",
36         NULL
37 };
38
39 static int __ino_to_path_fd(u64 inum, int fd, int verbose, const char *prepend)
40 {
41         int ret;
42         int i;
43         struct btrfs_ioctl_ino_path_args ipa;
44         struct btrfs_data_container *fspath;
45
46         fspath = malloc(4096);
47         if (!fspath)
48                 return -ENOMEM;
49
50         memset(fspath, 0, sizeof(*fspath));
51         ipa.inum = inum;
52         ipa.size = 4096;
53         ipa.fspath = ptr_to_u64(fspath);
54
55         ret = ioctl(fd, BTRFS_IOC_INO_PATHS, &ipa);
56         if (ret) {
57                 printf("ioctl ret=%d, error: %s\n", ret, strerror(errno));
58                 goto out;
59         }
60
61         if (verbose)
62                 printf("ioctl ret=%d, bytes_left=%lu, bytes_missing=%lu, "
63                         "cnt=%d, missed=%d\n", ret,
64                         (unsigned long)fspath->bytes_left,
65                         (unsigned long)fspath->bytes_missing,
66                         fspath->elem_cnt, fspath->elem_missed);
67
68         for (i = 0; i < fspath->elem_cnt; ++i) {
69                 u64 ptr;
70                 char *str;
71                 ptr = (u64)(unsigned long)fspath->val;
72                 ptr += fspath->val[i];
73                 str = (char *)(unsigned long)ptr;
74                 if (prepend)
75                         printf("%s/%s\n", prepend, str);
76                 else
77                         printf("%s\n", str);
78         }
79
80 out:
81         free(fspath);
82         return !!ret;
83 }
84
85 static const char * const cmd_inode_resolve_usage[] = {
86         "btrfs inspect-internal inode-resolve [-v] <inode> <path>",
87         "Get file system paths for the given inode",
88         "",
89         "-v   verbose mode",
90         NULL
91 };
92
93 static int cmd_inode_resolve(int argc, char **argv)
94 {
95         int fd;
96         int verbose = 0;
97         int ret;
98         DIR *dirstream = NULL;
99
100         optind = 1;
101         while (1) {
102                 int c = getopt(argc, argv, "v");
103                 if (c < 0)
104                         break;
105
106                 switch (c) {
107                 case 'v':
108                         verbose = 1;
109                         break;
110                 default:
111                         usage(cmd_inode_resolve_usage);
112                 }
113         }
114
115         if (check_argc_exact(argc - optind, 2))
116                 usage(cmd_inode_resolve_usage);
117
118         fd = open_file_or_dir(argv[optind+1], &dirstream);
119         if (fd < 0) {
120                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[optind+1]);
121                 return 1;
122         }
123
124         ret = __ino_to_path_fd(arg_strtou64(argv[optind]), fd, verbose,
125                                argv[optind+1]);
126         close_file_or_dir(fd, dirstream);
127         return !!ret;
128
129 }
130
131 static const char * const cmd_logical_resolve_usage[] = {
132         "btrfs inspect-internal logical-resolve [-Pv] [-s bufsize] <logical> <path>",
133         "Get file system paths for the given logical address",
134         "-P          skip the path resolving and print the inodes instead",
135         "-v          verbose mode",
136         "-s bufsize  set inode container's size. This is used to increase inode",
137         "            container's size in case it is not enough to read all the ",
138         "            resolved results. The max value one can set is 64k",
139         NULL
140 };
141
142 static int cmd_logical_resolve(int argc, char **argv)
143 {
144         int ret;
145         int fd;
146         int i;
147         int verbose = 0;
148         int getpath = 1;
149         int bytes_left;
150         struct btrfs_ioctl_logical_ino_args loi;
151         struct btrfs_data_container *inodes;
152         u64 size = 4096;
153         char full_path[4096];
154         char *path_ptr;
155         DIR *dirstream = NULL;
156
157         optind = 1;
158         while (1) {
159                 int c = getopt(argc, argv, "Pvs:");
160                 if (c < 0)
161                         break;
162
163                 switch (c) {
164                 case 'P':
165                         getpath = 0;
166                         break;
167                 case 'v':
168                         verbose = 1;
169                         break;
170                 case 's':
171                         size = arg_strtou64(optarg);
172                         break;
173                 default:
174                         usage(cmd_logical_resolve_usage);
175                 }
176         }
177
178         if (check_argc_exact(argc - optind, 2))
179                 usage(cmd_logical_resolve_usage);
180
181         size = min(size, (u64)64 * 1024);
182         inodes = malloc(size);
183         if (!inodes)
184                 return 1;
185
186         memset(inodes, 0, sizeof(*inodes));
187         loi.logical = arg_strtou64(argv[optind]);
188         loi.size = size;
189         loi.inodes = ptr_to_u64(inodes);
190
191         fd = open_file_or_dir(argv[optind+1], &dirstream);
192         if (fd < 0) {
193                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[optind+1]);
194                 ret = 12;
195                 goto out;
196         }
197
198         ret = ioctl(fd, BTRFS_IOC_LOGICAL_INO, &loi);
199         if (ret) {
200                 printf("ioctl ret=%d, error: %s\n", ret, strerror(errno));
201                 goto out;
202         }
203
204         if (verbose)
205                 printf("ioctl ret=%d, total_size=%llu, bytes_left=%lu, "
206                         "bytes_missing=%lu, cnt=%d, missed=%d\n",
207                         ret, size,
208                         (unsigned long)inodes->bytes_left,
209                         (unsigned long)inodes->bytes_missing,
210                         inodes->elem_cnt, inodes->elem_missed);
211
212         bytes_left = sizeof(full_path);
213         ret = snprintf(full_path, bytes_left, "%s/", argv[optind+1]);
214         path_ptr = full_path + ret;
215         bytes_left -= ret + 1;
216         BUG_ON(bytes_left < 0);
217
218         for (i = 0; i < inodes->elem_cnt; i += 3) {
219                 u64 inum = inodes->val[i];
220                 u64 offset = inodes->val[i+1];
221                 u64 root = inodes->val[i+2];
222                 int path_fd;
223                 char *name;
224                 DIR *dirs = NULL;
225
226                 if (getpath) {
227                         name = btrfs_list_path_for_root(fd, root);
228                         if (IS_ERR(name)) {
229                                 ret = PTR_ERR(name);
230                                 goto out;
231                         }
232                         if (!name) {
233                                 path_ptr[-1] = '\0';
234                                 path_fd = fd;
235                         } else {
236                                 path_ptr[-1] = '/';
237                                 ret = snprintf(path_ptr, bytes_left, "%s",
238                                                 name);
239                                 BUG_ON(ret >= bytes_left);
240                                 free(name);
241                                 path_fd = open_file_or_dir(full_path, &dirs);
242                                 if (path_fd < 0) {
243                                         fprintf(stderr, "ERROR: can't access "
244                                                 "'%s'\n", full_path);
245                                         goto out;
246                                 }
247                         }
248                         __ino_to_path_fd(inum, path_fd, verbose, full_path);
249                         if (path_fd != fd)
250                                 close_file_or_dir(path_fd, dirs);
251                 } else {
252                         printf("inode %llu offset %llu root %llu\n", inum,
253                                 offset, root);
254                 }
255         }
256
257 out:
258         close_file_or_dir(fd, dirstream);
259         free(inodes);
260         return !!ret;
261 }
262
263 static const char * const cmd_subvolid_resolve_usage[] = {
264         "btrfs inspect-internal subvolid-resolve <subvolid> <path>",
265         "Get file system paths for the given subvolume ID.",
266         NULL
267 };
268
269 static int cmd_subvolid_resolve(int argc, char **argv)
270 {
271         int ret;
272         int fd = -1;
273         u64 subvol_id;
274         char path[PATH_MAX];
275         DIR *dirstream = NULL;
276
277         if (check_argc_exact(argc, 3))
278                 usage(cmd_subvolid_resolve_usage);
279
280         fd = open_file_or_dir(argv[2], &dirstream);
281         if (fd < 0) {
282                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[2]);
283                 ret = -ENOENT;
284                 goto out;
285         }
286
287         subvol_id = arg_strtou64(argv[1]);
288         ret = btrfs_subvolid_resolve(fd, path, sizeof(path), subvol_id);
289
290         if (ret) {
291                 fprintf(stderr,
292                         "%s: btrfs_subvolid_resolve(subvol_id %llu) failed with ret=%d\n",
293                         argv[0], (unsigned long long)subvol_id, ret);
294                 goto out;
295         }
296
297         path[PATH_MAX - 1] = '\0';
298         printf("%s\n", path);
299
300 out:
301         close_file_or_dir(fd, dirstream);
302         return ret ? 1 : 0;
303 }
304
305 static const char* const cmd_rootid_usage[] = {
306         "btrfs inspect-internal rootid <path>",
307         "Get tree ID of the containing subvolume of path.",
308         NULL
309 };
310
311 static int cmd_rootid(int argc, char **argv)
312 {
313         int ret;
314         int fd = -1;
315         u64 rootid;
316         DIR *dirstream = NULL;
317
318         if (check_argc_exact(argc, 2))
319                 usage(cmd_rootid_usage);
320
321         fd = open_file_or_dir(argv[1], &dirstream);
322         if (fd < 0) {
323                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[1]);
324                 ret = -ENOENT;
325                 goto out;
326         }
327
328         ret = lookup_ino_rootid(fd, &rootid);
329         if (ret) {
330                 fprintf(stderr, "%s: rootid failed with ret=%d\n",
331                         argv[0], ret);
332                 goto out;
333         }
334
335         printf("%llu\n", (unsigned long long)rootid);
336 out:
337         close_file_or_dir(fd, dirstream);
338
339         return !!ret;
340 }
341
342 struct dev_extent_elem {
343         u64 start;
344         /* inclusive end */
345         u64 end;
346         struct list_head list;
347 };
348
349 static int add_dev_extent(struct list_head *list,
350                           const u64 start, const u64 end,
351                           const int append)
352 {
353         struct dev_extent_elem *e;
354
355         e = malloc(sizeof(*e));
356         if (!e)
357                 return -ENOMEM;
358
359         e->start = start;
360         e->end = end;
361
362         if (append)
363                 list_add_tail(&e->list, list);
364         else
365                 list_add(&e->list, list);
366
367         return 0;
368 }
369
370 static void free_dev_extent_list(struct list_head *list)
371 {
372         while (!list_empty(list)) {
373                 struct dev_extent_elem *e;
374
375                 e = list_first_entry(list, struct dev_extent_elem, list);
376                 list_del(&e->list);
377                 free(e);
378         }
379 }
380
381 static int hole_includes_sb_mirror(const u64 start, const u64 end)
382 {
383         int i;
384         int ret = 0;
385
386         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
387                 u64 bytenr = btrfs_sb_offset(i);
388
389                 if (bytenr >= start && bytenr <= end) {
390                         ret = 1;
391                         break;
392                 }
393         }
394
395         return ret;
396 }
397
398 static void adjust_dev_min_size(struct list_head *extents,
399                                 struct list_head *holes,
400                                 u64 *min_size)
401 {
402         /*
403          * If relocation of the block group of a device extent must happen (see
404          * below) scratch space is used for the relocation. So track here the
405          * size of the largest device extent that has to be relocated. We track
406          * only the largest and not the sum of the sizes of all relocated block
407          * groups because after each block group is relocated the running
408          * transaction is committed so that pinned space is released.
409          */
410         u64 scratch_space = 0;
411
412         /*
413          * List of device extents is sorted by descending order of the extent's
414          * end offset. If some extent goes beyond the computed minimum size,
415          * which initially matches the sum of the lenghts of all extents,
416          * we need to check if the extent can be relocated to an hole in the
417          * device between [0, *min_size[ (which is what the resize ioctl does).
418          */
419         while (!list_empty(extents)) {
420                 struct dev_extent_elem *e;
421                 struct dev_extent_elem *h;
422                 int found = 0;
423                 u64 extent_len;
424                 u64 hole_len = 0;
425
426                 e = list_first_entry(extents, struct dev_extent_elem, list);
427                 if (e->end <= *min_size)
428                         break;
429
430                 /*
431                  * Our extent goes beyond the computed *min_size. See if we can
432                  * find a hole large enough to relocate it to. If not we must stop
433                  * and set *min_size to the end of the extent.
434                  */
435                 extent_len = e->end - e->start + 1;
436                 list_for_each_entry(h, holes, list) {
437                         hole_len = h->end - h->start + 1;
438                         if (hole_len >= extent_len) {
439                                 found = 1;
440                                 break;
441                         }
442                 }
443
444                 if (!found) {
445                         *min_size = e->end + 1;
446                         break;
447                 }
448
449                 /*
450                  * If the hole found contains the location for a superblock
451                  * mirror, we are pessimistic and require allocating one
452                  * more extent of the same size. This is because the block
453                  * group could be in the worst case used by a single extent
454                  * with a size >= (block_group.length - superblock.size).
455                  */
456                 if (hole_includes_sb_mirror(h->start,
457                                             h->start + extent_len - 1))
458                         *min_size += extent_len;
459
460                 if (hole_len > extent_len) {
461                         h->start += extent_len;
462                 } else {
463                         list_del(&h->list);
464                         free(h);
465                 }
466
467                 list_del(&e->list);
468                 free(e);
469
470                 if (extent_len > scratch_space)
471                         scratch_space = extent_len;
472         }
473
474         if (scratch_space) {
475                 *min_size += scratch_space;
476                 /*
477                  * Chunk allocation requires inserting/updating items in the
478                  * chunk tree, so often this can lead to the need of allocating
479                  * a new system chunk too, which has a maximum size of 32Mb.
480                  */
481                 *min_size += 32 * 1024 * 1024;
482         }
483 }
484
485 static int print_min_dev_size(int fd, u64 devid)
486 {
487         int ret = 1;
488         /*
489          * Device allocations starts at 1Mb or at the value passed through the
490          * mount option alloc_start if it's bigger than 1Mb. The alloc_start
491          * option is used for debugging and testing only, and recently the
492          * possibility of deprecating/removing it has been discussed, so we
493          * ignore it here.
494          */
495         u64 min_size = 1 * 1024 * 1024ull;
496         struct btrfs_ioctl_search_args args;
497         struct btrfs_ioctl_search_key *sk = &args.key;
498         u64 last_pos = (u64)-1;
499         LIST_HEAD(extents);
500         LIST_HEAD(holes);
501
502         memset(&args, 0, sizeof(args));
503         sk->tree_id = BTRFS_DEV_TREE_OBJECTID;
504         sk->min_objectid = devid;
505         sk->max_objectid = devid;
506         sk->max_type = BTRFS_DEV_EXTENT_KEY;
507         sk->min_type = BTRFS_DEV_EXTENT_KEY;
508         sk->min_offset = 0;
509         sk->max_offset = (u64)-1;
510         sk->min_transid = 0;
511         sk->max_transid = (u64)-1;
512         sk->nr_items = 4096;
513
514         while (1) {
515                 int i;
516                 struct btrfs_ioctl_search_header *sh;
517                 unsigned long off = 0;
518
519                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
520                 if (ret < 0) {
521                         fprintf(stderr,
522                                 "Error invoking tree search ioctl: %s\n",
523                                 strerror(errno));
524                         ret = 1;
525                         goto out;
526                 }
527
528                 if (sk->nr_items == 0)
529                         break;
530
531                 for (i = 0; i < sk->nr_items; i++) {
532                         struct btrfs_dev_extent *extent;
533                         u64 len;
534
535                         sh = (struct btrfs_ioctl_search_header *)(args.buf +
536                                                                   off);
537                         off += sizeof(*sh);
538                         extent = (struct btrfs_dev_extent *)(args.buf + off);
539                         off += sh->len;
540
541                         sk->min_objectid = sh->objectid;
542                         sk->min_type = sh->type;
543                         sk->min_offset = sh->offset + 1;
544
545                         if (sh->objectid != devid ||
546                             sh->type != BTRFS_DEV_EXTENT_KEY)
547                                 continue;
548
549                         len = btrfs_stack_dev_extent_length(extent);
550                         min_size += len;
551                         ret = add_dev_extent(&extents, sh->offset,
552                                              sh->offset + len - 1, 0);
553
554                         if (!ret && last_pos != (u64)-1 &&
555                             last_pos != sh->offset)
556                                 ret = add_dev_extent(&holes, last_pos,
557                                                      sh->offset - 1, 1);
558                         if (ret) {
559                                 fprintf(stderr, "Error: %s\n", strerror(-ret));
560                                 ret = 1;
561                                 goto out;
562                         }
563
564                         last_pos = sh->offset + len;
565                 }
566
567                 if (sk->min_type != BTRFS_DEV_EXTENT_KEY ||
568                     sk->min_objectid != devid)
569                         break;
570         }
571
572         adjust_dev_min_size(&extents, &holes, &min_size);
573         printf("%llu bytes (%s)\n", min_size, pretty_size(min_size));
574         ret = 0;
575 out:
576         free_dev_extent_list(&extents);
577         free_dev_extent_list(&holes);
578
579         return ret;
580 }
581
582 static const char* const cmd_inspect_min_dev_size_usage[] = {
583         "btrfs inspect-internal min-dev-size [options] <path>",
584         "Get the minimum size the device can be shrunk to. The",
585         "device id 1 is used by default.",
586         "--id DEVID   specify the device id to query",
587         NULL
588 };
589
590 static int cmd_inspect_min_dev_size(int argc, char **argv)
591 {
592         int ret;
593         int fd = -1;
594         DIR *dirstream = NULL;
595         u64 devid = 1;
596
597         while (1) {
598                 int c;
599                 enum { GETOPT_VAL_DEVID = 256 };
600                 static const struct option long_options[] = {
601                         { "id", required_argument, NULL, GETOPT_VAL_DEVID },
602                         {NULL, 0, NULL, 0}
603                 };
604
605                 c = getopt_long(argc, argv, "", long_options, NULL);
606                 if (c < 0)
607                         break;
608
609                 switch (c) {
610                 case GETOPT_VAL_DEVID:
611                         devid = arg_strtou64(optarg);
612                         break;
613                 default:
614                         usage(cmd_inspect_min_dev_size_usage);
615                 }
616         }
617         if (check_argc_exact(argc - optind, 1))
618                 usage(cmd_inspect_min_dev_size_usage);
619
620         fd = open_file_or_dir(argv[optind], &dirstream);
621         if (fd < 0) {
622                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[optind]);
623                 ret = -ENOENT;
624                 goto out;
625         }
626
627         ret = print_min_dev_size(fd, devid);
628 out:
629         close_file_or_dir(fd, dirstream);
630
631         return !!ret;
632 }
633
634 static const char inspect_cmd_group_info[] =
635 "query various internal information";
636
637 const struct cmd_group inspect_cmd_group = {
638         inspect_cmd_group_usage, inspect_cmd_group_info, {
639                 { "inode-resolve", cmd_inode_resolve, cmd_inode_resolve_usage,
640                         NULL, 0 },
641                 { "logical-resolve", cmd_logical_resolve,
642                         cmd_logical_resolve_usage, NULL, 0 },
643                 { "subvolid-resolve", cmd_subvolid_resolve,
644                         cmd_subvolid_resolve_usage, NULL, 0 },
645                 { "rootid", cmd_rootid, cmd_rootid_usage, NULL, 0 },
646                 { "min-dev-size", cmd_inspect_min_dev_size,
647                         cmd_inspect_min_dev_size_usage, NULL, 0 },
648                 NULL_CMD_STRUCT
649         }
650 };
651
652 int cmd_inspect(int argc, char **argv)
653 {
654         return handle_command_group(&inspect_cmd_group, argc, argv);
655 }