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