btrfs-progs: move min-resize implementation to inspect-internal
[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
24 #include "kerncompat.h"
25 #include "ioctl.h"
26 #include "utils.h"
27 #include "ctree.h"
28 #include "send-utils.h"
29
30 #include "commands.h"
31 #include "btrfs-list.h"
32
33 static const char * const inspect_cmd_group_usage[] = {
34         "btrfs inspect-internal <command> <args>",
35         NULL
36 };
37
38 static int __ino_to_path_fd(u64 inum, int fd, int verbose, const char *prepend)
39 {
40         int ret;
41         int i;
42         struct btrfs_ioctl_ino_path_args ipa;
43         struct btrfs_data_container *fspath;
44
45         fspath = malloc(4096);
46         if (!fspath)
47                 return -ENOMEM;
48
49         memset(fspath, 0, sizeof(*fspath));
50         ipa.inum = inum;
51         ipa.size = 4096;
52         ipa.fspath = ptr_to_u64(fspath);
53
54         ret = ioctl(fd, BTRFS_IOC_INO_PATHS, &ipa);
55         if (ret) {
56                 printf("ioctl ret=%d, error: %s\n", ret, strerror(errno));
57                 goto out;
58         }
59
60         if (verbose)
61                 printf("ioctl ret=%d, bytes_left=%lu, bytes_missing=%lu, "
62                         "cnt=%d, missed=%d\n", ret,
63                         (unsigned long)fspath->bytes_left,
64                         (unsigned long)fspath->bytes_missing,
65                         fspath->elem_cnt, fspath->elem_missed);
66
67         for (i = 0; i < fspath->elem_cnt; ++i) {
68                 u64 ptr;
69                 char *str;
70                 ptr = (u64)(unsigned long)fspath->val;
71                 ptr += fspath->val[i];
72                 str = (char *)(unsigned long)ptr;
73                 if (prepend)
74                         printf("%s/%s\n", prepend, str);
75                 else
76                         printf("%s\n", str);
77         }
78
79 out:
80         free(fspath);
81         return !!ret;
82 }
83
84 static const char * const cmd_inode_resolve_usage[] = {
85         "btrfs inspect-internal inode-resolve [-v] <inode> <path>",
86         "Get file system paths for the given inode",
87         "",
88         "-v   verbose mode",
89         NULL
90 };
91
92 static int cmd_inode_resolve(int argc, char **argv)
93 {
94         int fd;
95         int verbose = 0;
96         int ret;
97         DIR *dirstream = NULL;
98
99         optind = 1;
100         while (1) {
101                 int c = getopt(argc, argv, "v");
102                 if (c < 0)
103                         break;
104
105                 switch (c) {
106                 case 'v':
107                         verbose = 1;
108                         break;
109                 default:
110                         usage(cmd_inode_resolve_usage);
111                 }
112         }
113
114         if (check_argc_exact(argc - optind, 2))
115                 usage(cmd_inode_resolve_usage);
116
117         fd = open_file_or_dir(argv[optind+1], &dirstream);
118         if (fd < 0) {
119                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[optind+1]);
120                 return 1;
121         }
122
123         ret = __ino_to_path_fd(arg_strtou64(argv[optind]), fd, verbose,
124                                argv[optind+1]);
125         close_file_or_dir(fd, dirstream);
126         return !!ret;
127
128 }
129
130 static const char * const cmd_logical_resolve_usage[] = {
131         "btrfs inspect-internal logical-resolve [-Pv] [-s bufsize] <logical> <path>",
132         "Get file system paths for the given logical address",
133         "-P          skip the path resolving and print the inodes instead",
134         "-v          verbose mode",
135         "-s bufsize  set inode container's size. This is used to increase inode",
136         "            container's size in case it is not enough to read all the ",
137         "            resolved results. The max value one can set is 64k",
138         NULL
139 };
140
141 static int cmd_logical_resolve(int argc, char **argv)
142 {
143         int ret;
144         int fd;
145         int i;
146         int verbose = 0;
147         int getpath = 1;
148         int bytes_left;
149         struct btrfs_ioctl_logical_ino_args loi;
150         struct btrfs_data_container *inodes;
151         u64 size = 4096;
152         char full_path[4096];
153         char *path_ptr;
154         DIR *dirstream = NULL;
155
156         optind = 1;
157         while (1) {
158                 int c = getopt(argc, argv, "Pvs:");
159                 if (c < 0)
160                         break;
161
162                 switch (c) {
163                 case 'P':
164                         getpath = 0;
165                         break;
166                 case 'v':
167                         verbose = 1;
168                         break;
169                 case 's':
170                         size = arg_strtou64(optarg);
171                         break;
172                 default:
173                         usage(cmd_logical_resolve_usage);
174                 }
175         }
176
177         if (check_argc_exact(argc - optind, 2))
178                 usage(cmd_logical_resolve_usage);
179
180         size = min(size, (u64)64 * 1024);
181         inodes = malloc(size);
182         if (!inodes)
183                 return 1;
184
185         memset(inodes, 0, sizeof(*inodes));
186         loi.logical = arg_strtou64(argv[optind]);
187         loi.size = size;
188         loi.inodes = ptr_to_u64(inodes);
189
190         fd = open_file_or_dir(argv[optind+1], &dirstream);
191         if (fd < 0) {
192                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[optind+1]);
193                 ret = 12;
194                 goto out;
195         }
196
197         ret = ioctl(fd, BTRFS_IOC_LOGICAL_INO, &loi);
198         if (ret) {
199                 printf("ioctl ret=%d, error: %s\n", ret, strerror(errno));
200                 goto out;
201         }
202
203         if (verbose)
204                 printf("ioctl ret=%d, total_size=%llu, bytes_left=%lu, "
205                         "bytes_missing=%lu, cnt=%d, missed=%d\n",
206                         ret, size,
207                         (unsigned long)inodes->bytes_left,
208                         (unsigned long)inodes->bytes_missing,
209                         inodes->elem_cnt, inodes->elem_missed);
210
211         bytes_left = sizeof(full_path);
212         ret = snprintf(full_path, bytes_left, "%s/", argv[optind+1]);
213         path_ptr = full_path + ret;
214         bytes_left -= ret + 1;
215         BUG_ON(bytes_left < 0);
216
217         for (i = 0; i < inodes->elem_cnt; i += 3) {
218                 u64 inum = inodes->val[i];
219                 u64 offset = inodes->val[i+1];
220                 u64 root = inodes->val[i+2];
221                 int path_fd;
222                 char *name;
223                 DIR *dirs = NULL;
224
225                 if (getpath) {
226                         name = btrfs_list_path_for_root(fd, root);
227                         if (IS_ERR(name)) {
228                                 ret = PTR_ERR(name);
229                                 goto out;
230                         }
231                         if (!name) {
232                                 path_ptr[-1] = '\0';
233                                 path_fd = fd;
234                         } else {
235                                 path_ptr[-1] = '/';
236                                 ret = snprintf(path_ptr, bytes_left, "%s",
237                                                 name);
238                                 BUG_ON(ret >= bytes_left);
239                                 free(name);
240                                 path_fd = open_file_or_dir(full_path, &dirs);
241                                 if (path_fd < 0) {
242                                         fprintf(stderr, "ERROR: can't access "
243                                                 "'%s'\n", full_path);
244                                         goto out;
245                                 }
246                         }
247                         __ino_to_path_fd(inum, path_fd, verbose, full_path);
248                         if (path_fd != fd)
249                                 close_file_or_dir(path_fd, dirs);
250                 } else {
251                         printf("inode %llu offset %llu root %llu\n", inum,
252                                 offset, root);
253                 }
254         }
255
256 out:
257         close_file_or_dir(fd, dirstream);
258         free(inodes);
259         return !!ret;
260 }
261
262 static const char * const cmd_subvolid_resolve_usage[] = {
263         "btrfs inspect-internal subvolid-resolve <subvolid> <path>",
264         "Get file system paths for the given subvolume ID.",
265         NULL
266 };
267
268 static int cmd_subvolid_resolve(int argc, char **argv)
269 {
270         int ret;
271         int fd = -1;
272         u64 subvol_id;
273         char path[PATH_MAX];
274         DIR *dirstream = NULL;
275
276         if (check_argc_exact(argc, 3))
277                 usage(cmd_subvolid_resolve_usage);
278
279         fd = open_file_or_dir(argv[2], &dirstream);
280         if (fd < 0) {
281                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[2]);
282                 ret = -ENOENT;
283                 goto out;
284         }
285
286         subvol_id = arg_strtou64(argv[1]);
287         ret = btrfs_subvolid_resolve(fd, path, sizeof(path), subvol_id);
288
289         if (ret) {
290                 fprintf(stderr,
291                         "%s: btrfs_subvolid_resolve(subvol_id %llu) failed with ret=%d\n",
292                         argv[0], (unsigned long long)subvol_id, ret);
293                 goto out;
294         }
295
296         path[PATH_MAX - 1] = '\0';
297         printf("%s\n", path);
298
299 out:
300         close_file_or_dir(fd, dirstream);
301         return ret ? 1 : 0;
302 }
303
304 static const char* const cmd_rootid_usage[] = {
305         "btrfs inspect-internal rootid <path>",
306         "Get tree ID of the containing subvolume of path.",
307         NULL
308 };
309
310 static int cmd_rootid(int argc, char **argv)
311 {
312         int ret;
313         int fd = -1;
314         u64 rootid;
315         DIR *dirstream = NULL;
316
317         if (check_argc_exact(argc, 2))
318                 usage(cmd_rootid_usage);
319
320         fd = open_file_or_dir(argv[1], &dirstream);
321         if (fd < 0) {
322                 fprintf(stderr, "ERROR: can't access '%s'\n", argv[1]);
323                 ret = -ENOENT;
324                 goto out;
325         }
326
327         ret = lookup_ino_rootid(fd, &rootid);
328         if (ret) {
329                 fprintf(stderr, "%s: rootid failed with ret=%d\n",
330                         argv[0], ret);
331                 goto out;
332         }
333
334         printf("%llu\n", (unsigned long long)rootid);
335 out:
336         close_file_or_dir(fd, dirstream);
337
338         return !!ret;
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 get_min_size(int fd, DIR *dirstream, 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         close_file_or_dir(fd, dirstream);
576         free_dev_extent_list(&extents);
577         free_dev_extent_list(&holes);
578
579         return ret;
580 }
581
582 static const char inspect_cmd_group_info[] =
583 "query various internal information";
584
585 const struct cmd_group inspect_cmd_group = {
586         inspect_cmd_group_usage, inspect_cmd_group_info, {
587                 { "inode-resolve", cmd_inode_resolve, cmd_inode_resolve_usage,
588                         NULL, 0 },
589                 { "logical-resolve", cmd_logical_resolve,
590                         cmd_logical_resolve_usage, NULL, 0 },
591                 { "subvolid-resolve", cmd_subvolid_resolve,
592                         cmd_subvolid_resolve_usage, NULL, 0 },
593                 { "rootid", cmd_rootid, cmd_rootid_usage, NULL, 0 },
594                 NULL_CMD_STRUCT
595         }
596 };
597
598 int cmd_inspect(int argc, char **argv)
599 {
600         return handle_command_group(&inspect_cmd_group, argc, argv);
601 }