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