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