btrfs-progs: catch memory allocation failure from alloc_tree_backref
[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 struct dev_extent_elem {
333         u64 start;
334         /* inclusive end */
335         u64 end;
336         struct list_head list;
337 };
338
339 static int add_dev_extent(struct list_head *list,
340                           const u64 start, const u64 end,
341                           const int append)
342 {
343         struct dev_extent_elem *e;
344
345         e = malloc(sizeof(*e));
346         if (!e)
347                 return -ENOMEM;
348
349         e->start = start;
350         e->end = end;
351
352         if (append)
353                 list_add_tail(&e->list, list);
354         else
355                 list_add(&e->list, list);
356
357         return 0;
358 }
359
360 static void free_dev_extent_list(struct list_head *list)
361 {
362         while (!list_empty(list)) {
363                 struct dev_extent_elem *e;
364
365                 e = list_first_entry(list, struct dev_extent_elem, list);
366                 list_del(&e->list);
367                 free(e);
368         }
369 }
370
371 static int hole_includes_sb_mirror(const u64 start, const u64 end)
372 {
373         int i;
374         int ret = 0;
375
376         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
377                 u64 bytenr = btrfs_sb_offset(i);
378
379                 if (bytenr >= start && bytenr <= end) {
380                         ret = 1;
381                         break;
382                 }
383         }
384
385         return ret;
386 }
387
388 static void adjust_dev_min_size(struct list_head *extents,
389                                 struct list_head *holes,
390                                 u64 *min_size)
391 {
392         /*
393          * If relocation of the block group of a device extent must happen (see
394          * below) scratch space is used for the relocation. So track here the
395          * size of the largest device extent that has to be relocated. We track
396          * only the largest and not the sum of the sizes of all relocated block
397          * groups because after each block group is relocated the running
398          * transaction is committed so that pinned space is released.
399          */
400         u64 scratch_space = 0;
401
402         /*
403          * List of device extents is sorted by descending order of the extent's
404          * end offset. If some extent goes beyond the computed minimum size,
405          * which initially matches the sum of the lenghts of all extents,
406          * we need to check if the extent can be relocated to an hole in the
407          * device between [0, *min_size[ (which is what the resize ioctl does).
408          */
409         while (!list_empty(extents)) {
410                 struct dev_extent_elem *e;
411                 struct dev_extent_elem *h;
412                 int found = 0;
413                 u64 extent_len;
414                 u64 hole_len = 0;
415
416                 e = list_first_entry(extents, struct dev_extent_elem, list);
417                 if (e->end <= *min_size)
418                         break;
419
420                 /*
421                  * Our extent goes beyond the computed *min_size. See if we can
422                  * find a hole large enough to relocate it to. If not we must stop
423                  * and set *min_size to the end of the extent.
424                  */
425                 extent_len = e->end - e->start + 1;
426                 list_for_each_entry(h, holes, list) {
427                         hole_len = h->end - h->start + 1;
428                         if (hole_len >= extent_len) {
429                                 found = 1;
430                                 break;
431                         }
432                 }
433
434                 if (!found) {
435                         *min_size = e->end + 1;
436                         break;
437                 }
438
439                 /*
440                  * If the hole found contains the location for a superblock
441                  * mirror, we are pessimistic and require allocating one
442                  * more extent of the same size. This is because the block
443                  * group could be in the worst case used by a single extent
444                  * with a size >= (block_group.length - superblock.size).
445                  */
446                 if (hole_includes_sb_mirror(h->start,
447                                             h->start + extent_len - 1))
448                         *min_size += extent_len;
449
450                 if (hole_len > extent_len) {
451                         h->start += extent_len;
452                 } else {
453                         list_del(&h->list);
454                         free(h);
455                 }
456
457                 list_del(&e->list);
458                 free(e);
459
460                 if (extent_len > scratch_space)
461                         scratch_space = extent_len;
462         }
463
464         if (scratch_space) {
465                 *min_size += scratch_space;
466                 /*
467                  * Chunk allocation requires inserting/updating items in the
468                  * chunk tree, so often this can lead to the need of allocating
469                  * a new system chunk too, which has a maximum size of 32Mb.
470                  */
471                 *min_size += 32 * 1024 * 1024;
472         }
473 }
474
475 static int print_min_dev_size(int fd, u64 devid)
476 {
477         int ret = 1;
478         /*
479          * Device allocations starts at 1Mb or at the value passed through the
480          * mount option alloc_start if it's bigger than 1Mb. The alloc_start
481          * option is used for debugging and testing only, and recently the
482          * possibility of deprecating/removing it has been discussed, so we
483          * ignore it here.
484          */
485         u64 min_size = 1 * 1024 * 1024ull;
486         struct btrfs_ioctl_search_args args;
487         struct btrfs_ioctl_search_key *sk = &args.key;
488         u64 last_pos = (u64)-1;
489         LIST_HEAD(extents);
490         LIST_HEAD(holes);
491
492         memset(&args, 0, sizeof(args));
493         sk->tree_id = BTRFS_DEV_TREE_OBJECTID;
494         sk->min_objectid = devid;
495         sk->max_objectid = devid;
496         sk->max_type = BTRFS_DEV_EXTENT_KEY;
497         sk->min_type = BTRFS_DEV_EXTENT_KEY;
498         sk->min_offset = 0;
499         sk->max_offset = (u64)-1;
500         sk->min_transid = 0;
501         sk->max_transid = (u64)-1;
502         sk->nr_items = 4096;
503
504         while (1) {
505                 int i;
506                 struct btrfs_ioctl_search_header *sh;
507                 unsigned long off = 0;
508
509                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
510                 if (ret < 0) {
511                         fprintf(stderr,
512                                 "Error invoking tree search ioctl: %s\n",
513                                 strerror(errno));
514                         ret = 1;
515                         goto out;
516                 }
517
518                 if (sk->nr_items == 0)
519                         break;
520
521                 for (i = 0; i < sk->nr_items; i++) {
522                         struct btrfs_dev_extent *extent;
523                         u64 len;
524
525                         sh = (struct btrfs_ioctl_search_header *)(args.buf +
526                                                                   off);
527                         off += sizeof(*sh);
528                         extent = (struct btrfs_dev_extent *)(args.buf + off);
529                         off += sh->len;
530
531                         sk->min_objectid = sh->objectid;
532                         sk->min_type = sh->type;
533                         sk->min_offset = sh->offset + 1;
534
535                         if (sh->objectid != devid ||
536                             sh->type != BTRFS_DEV_EXTENT_KEY)
537                                 continue;
538
539                         len = btrfs_stack_dev_extent_length(extent);
540                         min_size += len;
541                         ret = add_dev_extent(&extents, sh->offset,
542                                              sh->offset + len - 1, 0);
543
544                         if (!ret && last_pos != (u64)-1 &&
545                             last_pos != sh->offset)
546                                 ret = add_dev_extent(&holes, last_pos,
547                                                      sh->offset - 1, 1);
548                         if (ret) {
549                                 fprintf(stderr, "Error: %s\n", strerror(-ret));
550                                 ret = 1;
551                                 goto out;
552                         }
553
554                         last_pos = sh->offset + len;
555                 }
556
557                 if (sk->min_type != BTRFS_DEV_EXTENT_KEY ||
558                     sk->min_objectid != devid)
559                         break;
560         }
561
562         adjust_dev_min_size(&extents, &holes, &min_size);
563         printf("%llu bytes (%s)\n", min_size, pretty_size(min_size));
564         ret = 0;
565 out:
566         free_dev_extent_list(&extents);
567         free_dev_extent_list(&holes);
568
569         return ret;
570 }
571
572 static const char* const cmd_inspect_min_dev_size_usage[] = {
573         "btrfs inspect-internal min-dev-size [options] <path>",
574         "Get the minimum size the device can be shrunk to. The",
575         "device id 1 is used by default.",
576         "--id DEVID   specify the device id to query",
577         NULL
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 }